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 this._subscriptions
1611 .push(cx.subscribe_self(|editor, e: &EditorEvent, cx| {
1612 if let EditorEvent::SelectionsChanged { local } = e {
1613 if *local {
1614 let new_anchor = editor.scroll_manager.anchor();
1615 editor.update_restoration_data(cx, move |data| {
1616 data.scroll_anchor = new_anchor;
1617 });
1618 }
1619 }
1620 }));
1621
1622 this.end_selection(window, cx);
1623 this.scroll_manager.show_scrollbars(window, cx);
1624 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1625
1626 if mode == EditorMode::Full {
1627 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1628 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1629
1630 if this.git_blame_inline_enabled {
1631 this.git_blame_inline_enabled = true;
1632 this.start_git_blame_inline(false, window, cx);
1633 }
1634
1635 this.go_to_active_debug_line(window, cx);
1636
1637 if let Some(buffer) = buffer.read(cx).as_singleton() {
1638 if let Some(project) = this.project.as_ref() {
1639 let handle = project.update(cx, |project, cx| {
1640 project.register_buffer_with_language_servers(&buffer, cx)
1641 });
1642 this.registered_buffers
1643 .insert(buffer.read(cx).remote_id(), handle);
1644 }
1645 }
1646 }
1647
1648 this.report_editor_event("Editor Opened", None, cx);
1649 this
1650 }
1651
1652 pub fn deploy_mouse_context_menu(
1653 &mut self,
1654 position: gpui::Point<Pixels>,
1655 context_menu: Entity<ContextMenu>,
1656 window: &mut Window,
1657 cx: &mut Context<Self>,
1658 ) {
1659 self.mouse_context_menu = Some(MouseContextMenu::new(
1660 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1661 context_menu,
1662 window,
1663 cx,
1664 ));
1665 }
1666
1667 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1668 self.mouse_context_menu
1669 .as_ref()
1670 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1671 }
1672
1673 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1674 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1675 }
1676
1677 fn key_context_internal(
1678 &self,
1679 has_active_edit_prediction: bool,
1680 window: &Window,
1681 cx: &App,
1682 ) -> KeyContext {
1683 let mut key_context = KeyContext::new_with_defaults();
1684 key_context.add("Editor");
1685 let mode = match self.mode {
1686 EditorMode::SingleLine { .. } => "single_line",
1687 EditorMode::AutoHeight { .. } => "auto_height",
1688 EditorMode::Full => "full",
1689 };
1690
1691 if EditorSettings::jupyter_enabled(cx) {
1692 key_context.add("jupyter");
1693 }
1694
1695 key_context.set("mode", mode);
1696 if self.pending_rename.is_some() {
1697 key_context.add("renaming");
1698 }
1699
1700 match self.context_menu.borrow().as_ref() {
1701 Some(CodeContextMenu::Completions(_)) => {
1702 key_context.add("menu");
1703 key_context.add("showing_completions");
1704 }
1705 Some(CodeContextMenu::CodeActions(_)) => {
1706 key_context.add("menu");
1707 key_context.add("showing_code_actions")
1708 }
1709 None => {}
1710 }
1711
1712 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1713 if !self.focus_handle(cx).contains_focused(window, cx)
1714 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1715 {
1716 for addon in self.addons.values() {
1717 addon.extend_key_context(&mut key_context, cx)
1718 }
1719 }
1720
1721 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1722 if let Some(extension) = singleton_buffer
1723 .read(cx)
1724 .file()
1725 .and_then(|file| file.path().extension()?.to_str())
1726 {
1727 key_context.set("extension", extension.to_string());
1728 }
1729 } else {
1730 key_context.add("multibuffer");
1731 }
1732
1733 if has_active_edit_prediction {
1734 if self.edit_prediction_in_conflict() {
1735 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1736 } else {
1737 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1738 key_context.add("copilot_suggestion");
1739 }
1740 }
1741
1742 if self.selection_mark_mode {
1743 key_context.add("selection_mode");
1744 }
1745
1746 key_context
1747 }
1748
1749 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1750 self.mouse_cursor_hidden = match origin {
1751 HideMouseCursorOrigin::TypingAction => {
1752 matches!(
1753 self.hide_mouse_mode,
1754 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1755 )
1756 }
1757 HideMouseCursorOrigin::MovementAction => {
1758 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1759 }
1760 };
1761 }
1762
1763 pub fn edit_prediction_in_conflict(&self) -> bool {
1764 if !self.show_edit_predictions_in_menu() {
1765 return false;
1766 }
1767
1768 let showing_completions = self
1769 .context_menu
1770 .borrow()
1771 .as_ref()
1772 .map_or(false, |context| {
1773 matches!(context, CodeContextMenu::Completions(_))
1774 });
1775
1776 showing_completions
1777 || self.edit_prediction_requires_modifier()
1778 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1779 // bindings to insert tab characters.
1780 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1781 }
1782
1783 pub fn accept_edit_prediction_keybind(
1784 &self,
1785 window: &Window,
1786 cx: &App,
1787 ) -> AcceptEditPredictionBinding {
1788 let key_context = self.key_context_internal(true, window, cx);
1789 let in_conflict = self.edit_prediction_in_conflict();
1790
1791 AcceptEditPredictionBinding(
1792 window
1793 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1794 .into_iter()
1795 .filter(|binding| {
1796 !in_conflict
1797 || binding
1798 .keystrokes()
1799 .first()
1800 .map_or(false, |keystroke| keystroke.modifiers.modified())
1801 })
1802 .rev()
1803 .min_by_key(|binding| {
1804 binding
1805 .keystrokes()
1806 .first()
1807 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1808 }),
1809 )
1810 }
1811
1812 pub fn new_file(
1813 workspace: &mut Workspace,
1814 _: &workspace::NewFile,
1815 window: &mut Window,
1816 cx: &mut Context<Workspace>,
1817 ) {
1818 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1819 "Failed to create buffer",
1820 window,
1821 cx,
1822 |e, _, _| match e.error_code() {
1823 ErrorCode::RemoteUpgradeRequired => Some(format!(
1824 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1825 e.error_tag("required").unwrap_or("the latest version")
1826 )),
1827 _ => None,
1828 },
1829 );
1830 }
1831
1832 pub fn new_in_workspace(
1833 workspace: &mut Workspace,
1834 window: &mut Window,
1835 cx: &mut Context<Workspace>,
1836 ) -> Task<Result<Entity<Editor>>> {
1837 let project = workspace.project().clone();
1838 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1839
1840 cx.spawn_in(window, async move |workspace, cx| {
1841 let buffer = create.await?;
1842 workspace.update_in(cx, |workspace, window, cx| {
1843 let editor =
1844 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1845 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1846 editor
1847 })
1848 })
1849 }
1850
1851 fn new_file_vertical(
1852 workspace: &mut Workspace,
1853 _: &workspace::NewFileSplitVertical,
1854 window: &mut Window,
1855 cx: &mut Context<Workspace>,
1856 ) {
1857 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1858 }
1859
1860 fn new_file_horizontal(
1861 workspace: &mut Workspace,
1862 _: &workspace::NewFileSplitHorizontal,
1863 window: &mut Window,
1864 cx: &mut Context<Workspace>,
1865 ) {
1866 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1867 }
1868
1869 fn new_file_in_direction(
1870 workspace: &mut Workspace,
1871 direction: SplitDirection,
1872 window: &mut Window,
1873 cx: &mut Context<Workspace>,
1874 ) {
1875 let project = workspace.project().clone();
1876 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1877
1878 cx.spawn_in(window, async move |workspace, cx| {
1879 let buffer = create.await?;
1880 workspace.update_in(cx, move |workspace, window, cx| {
1881 workspace.split_item(
1882 direction,
1883 Box::new(
1884 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1885 ),
1886 window,
1887 cx,
1888 )
1889 })?;
1890 anyhow::Ok(())
1891 })
1892 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1893 match e.error_code() {
1894 ErrorCode::RemoteUpgradeRequired => Some(format!(
1895 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1896 e.error_tag("required").unwrap_or("the latest version")
1897 )),
1898 _ => None,
1899 }
1900 });
1901 }
1902
1903 pub fn leader_peer_id(&self) -> Option<PeerId> {
1904 self.leader_peer_id
1905 }
1906
1907 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1908 &self.buffer
1909 }
1910
1911 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1912 self.workspace.as_ref()?.0.upgrade()
1913 }
1914
1915 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1916 self.buffer().read(cx).title(cx)
1917 }
1918
1919 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1920 let git_blame_gutter_max_author_length = self
1921 .render_git_blame_gutter(cx)
1922 .then(|| {
1923 if let Some(blame) = self.blame.as_ref() {
1924 let max_author_length =
1925 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1926 Some(max_author_length)
1927 } else {
1928 None
1929 }
1930 })
1931 .flatten();
1932
1933 EditorSnapshot {
1934 mode: self.mode,
1935 show_gutter: self.show_gutter,
1936 show_line_numbers: self.show_line_numbers,
1937 show_git_diff_gutter: self.show_git_diff_gutter,
1938 show_code_actions: self.show_code_actions,
1939 show_runnables: self.show_runnables,
1940 show_breakpoints: self.show_breakpoints,
1941 git_blame_gutter_max_author_length,
1942 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1943 scroll_anchor: self.scroll_manager.anchor(),
1944 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1945 placeholder_text: self.placeholder_text.clone(),
1946 is_focused: self.focus_handle.is_focused(window),
1947 current_line_highlight: self
1948 .current_line_highlight
1949 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1950 gutter_hovered: self.gutter_hovered,
1951 }
1952 }
1953
1954 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1955 self.buffer.read(cx).language_at(point, cx)
1956 }
1957
1958 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1959 self.buffer.read(cx).read(cx).file_at(point).cloned()
1960 }
1961
1962 pub fn active_excerpt(
1963 &self,
1964 cx: &App,
1965 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1966 self.buffer
1967 .read(cx)
1968 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1969 }
1970
1971 pub fn mode(&self) -> EditorMode {
1972 self.mode
1973 }
1974
1975 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1976 self.collaboration_hub.as_deref()
1977 }
1978
1979 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1980 self.collaboration_hub = Some(hub);
1981 }
1982
1983 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1984 self.in_project_search = in_project_search;
1985 }
1986
1987 pub fn set_custom_context_menu(
1988 &mut self,
1989 f: impl 'static
1990 + Fn(
1991 &mut Self,
1992 DisplayPoint,
1993 &mut Window,
1994 &mut Context<Self>,
1995 ) -> Option<Entity<ui::ContextMenu>>,
1996 ) {
1997 self.custom_context_menu = Some(Box::new(f))
1998 }
1999
2000 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2001 self.completion_provider = provider;
2002 }
2003
2004 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2005 self.semantics_provider.clone()
2006 }
2007
2008 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2009 self.semantics_provider = provider;
2010 }
2011
2012 pub fn set_edit_prediction_provider<T>(
2013 &mut self,
2014 provider: Option<Entity<T>>,
2015 window: &mut Window,
2016 cx: &mut Context<Self>,
2017 ) where
2018 T: EditPredictionProvider,
2019 {
2020 self.edit_prediction_provider =
2021 provider.map(|provider| RegisteredInlineCompletionProvider {
2022 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2023 if this.focus_handle.is_focused(window) {
2024 this.update_visible_inline_completion(window, cx);
2025 }
2026 }),
2027 provider: Arc::new(provider),
2028 });
2029 self.update_edit_prediction_settings(cx);
2030 self.refresh_inline_completion(false, false, window, cx);
2031 }
2032
2033 pub fn placeholder_text(&self) -> Option<&str> {
2034 self.placeholder_text.as_deref()
2035 }
2036
2037 pub fn set_placeholder_text(
2038 &mut self,
2039 placeholder_text: impl Into<Arc<str>>,
2040 cx: &mut Context<Self>,
2041 ) {
2042 let placeholder_text = Some(placeholder_text.into());
2043 if self.placeholder_text != placeholder_text {
2044 self.placeholder_text = placeholder_text;
2045 cx.notify();
2046 }
2047 }
2048
2049 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2050 self.cursor_shape = cursor_shape;
2051
2052 // Disrupt blink for immediate user feedback that the cursor shape has changed
2053 self.blink_manager.update(cx, BlinkManager::show_cursor);
2054
2055 cx.notify();
2056 }
2057
2058 pub fn set_current_line_highlight(
2059 &mut self,
2060 current_line_highlight: Option<CurrentLineHighlight>,
2061 ) {
2062 self.current_line_highlight = current_line_highlight;
2063 }
2064
2065 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2066 self.collapse_matches = collapse_matches;
2067 }
2068
2069 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2070 let buffers = self.buffer.read(cx).all_buffers();
2071 let Some(project) = self.project.as_ref() else {
2072 return;
2073 };
2074 project.update(cx, |project, cx| {
2075 for buffer in buffers {
2076 self.registered_buffers
2077 .entry(buffer.read(cx).remote_id())
2078 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2079 }
2080 })
2081 }
2082
2083 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2084 if self.collapse_matches {
2085 return range.start..range.start;
2086 }
2087 range.clone()
2088 }
2089
2090 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2091 if self.display_map.read(cx).clip_at_line_ends != clip {
2092 self.display_map
2093 .update(cx, |map, _| map.clip_at_line_ends = clip);
2094 }
2095 }
2096
2097 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2098 self.input_enabled = input_enabled;
2099 }
2100
2101 pub fn set_inline_completions_hidden_for_vim_mode(
2102 &mut self,
2103 hidden: bool,
2104 window: &mut Window,
2105 cx: &mut Context<Self>,
2106 ) {
2107 if hidden != self.inline_completions_hidden_for_vim_mode {
2108 self.inline_completions_hidden_for_vim_mode = hidden;
2109 if hidden {
2110 self.update_visible_inline_completion(window, cx);
2111 } else {
2112 self.refresh_inline_completion(true, false, window, cx);
2113 }
2114 }
2115 }
2116
2117 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2118 self.menu_inline_completions_policy = value;
2119 }
2120
2121 pub fn set_autoindent(&mut self, autoindent: bool) {
2122 if autoindent {
2123 self.autoindent_mode = Some(AutoindentMode::EachLine);
2124 } else {
2125 self.autoindent_mode = None;
2126 }
2127 }
2128
2129 pub fn read_only(&self, cx: &App) -> bool {
2130 self.read_only || self.buffer.read(cx).read_only()
2131 }
2132
2133 pub fn set_read_only(&mut self, read_only: bool) {
2134 self.read_only = read_only;
2135 }
2136
2137 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2138 self.use_autoclose = autoclose;
2139 }
2140
2141 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2142 self.use_auto_surround = auto_surround;
2143 }
2144
2145 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2146 self.auto_replace_emoji_shortcode = auto_replace;
2147 }
2148
2149 pub fn toggle_edit_predictions(
2150 &mut self,
2151 _: &ToggleEditPrediction,
2152 window: &mut Window,
2153 cx: &mut Context<Self>,
2154 ) {
2155 if self.show_inline_completions_override.is_some() {
2156 self.set_show_edit_predictions(None, window, cx);
2157 } else {
2158 let show_edit_predictions = !self.edit_predictions_enabled();
2159 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2160 }
2161 }
2162
2163 pub fn set_show_edit_predictions(
2164 &mut self,
2165 show_edit_predictions: Option<bool>,
2166 window: &mut Window,
2167 cx: &mut Context<Self>,
2168 ) {
2169 self.show_inline_completions_override = show_edit_predictions;
2170 self.update_edit_prediction_settings(cx);
2171
2172 if let Some(false) = show_edit_predictions {
2173 self.discard_inline_completion(false, cx);
2174 } else {
2175 self.refresh_inline_completion(false, true, window, cx);
2176 }
2177 }
2178
2179 fn inline_completions_disabled_in_scope(
2180 &self,
2181 buffer: &Entity<Buffer>,
2182 buffer_position: language::Anchor,
2183 cx: &App,
2184 ) -> bool {
2185 let snapshot = buffer.read(cx).snapshot();
2186 let settings = snapshot.settings_at(buffer_position, cx);
2187
2188 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2189 return false;
2190 };
2191
2192 scope.override_name().map_or(false, |scope_name| {
2193 settings
2194 .edit_predictions_disabled_in
2195 .iter()
2196 .any(|s| s == scope_name)
2197 })
2198 }
2199
2200 pub fn set_use_modal_editing(&mut self, to: bool) {
2201 self.use_modal_editing = to;
2202 }
2203
2204 pub fn use_modal_editing(&self) -> bool {
2205 self.use_modal_editing
2206 }
2207
2208 fn selections_did_change(
2209 &mut self,
2210 local: bool,
2211 old_cursor_position: &Anchor,
2212 show_completions: bool,
2213 window: &mut Window,
2214 cx: &mut Context<Self>,
2215 ) {
2216 window.invalidate_character_coordinates();
2217
2218 // Copy selections to primary selection buffer
2219 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2220 if local {
2221 let selections = self.selections.all::<usize>(cx);
2222 let buffer_handle = self.buffer.read(cx).read(cx);
2223
2224 let mut text = String::new();
2225 for (index, selection) in selections.iter().enumerate() {
2226 let text_for_selection = buffer_handle
2227 .text_for_range(selection.start..selection.end)
2228 .collect::<String>();
2229
2230 text.push_str(&text_for_selection);
2231 if index != selections.len() - 1 {
2232 text.push('\n');
2233 }
2234 }
2235
2236 if !text.is_empty() {
2237 cx.write_to_primary(ClipboardItem::new_string(text));
2238 }
2239 }
2240
2241 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2242 self.buffer.update(cx, |buffer, cx| {
2243 buffer.set_active_selections(
2244 &self.selections.disjoint_anchors(),
2245 self.selections.line_mode,
2246 self.cursor_shape,
2247 cx,
2248 )
2249 });
2250 }
2251 let display_map = self
2252 .display_map
2253 .update(cx, |display_map, cx| display_map.snapshot(cx));
2254 let buffer = &display_map.buffer_snapshot;
2255 self.add_selections_state = None;
2256 self.select_next_state = None;
2257 self.select_prev_state = None;
2258 self.select_syntax_node_history.try_clear();
2259 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2260 self.snippet_stack
2261 .invalidate(&self.selections.disjoint_anchors(), buffer);
2262 self.take_rename(false, window, cx);
2263
2264 let new_cursor_position = self.selections.newest_anchor().head();
2265
2266 self.push_to_nav_history(
2267 *old_cursor_position,
2268 Some(new_cursor_position.to_point(buffer)),
2269 false,
2270 cx,
2271 );
2272
2273 if local {
2274 let new_cursor_position = self.selections.newest_anchor().head();
2275 let mut context_menu = self.context_menu.borrow_mut();
2276 let completion_menu = match context_menu.as_ref() {
2277 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2278 _ => {
2279 *context_menu = None;
2280 None
2281 }
2282 };
2283 if let Some(buffer_id) = new_cursor_position.buffer_id {
2284 if !self.registered_buffers.contains_key(&buffer_id) {
2285 if let Some(project) = self.project.as_ref() {
2286 project.update(cx, |project, cx| {
2287 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2288 return;
2289 };
2290 self.registered_buffers.insert(
2291 buffer_id,
2292 project.register_buffer_with_language_servers(&buffer, cx),
2293 );
2294 })
2295 }
2296 }
2297 }
2298
2299 if let Some(completion_menu) = completion_menu {
2300 let cursor_position = new_cursor_position.to_offset(buffer);
2301 let (word_range, kind) =
2302 buffer.surrounding_word(completion_menu.initial_position, true);
2303 if kind == Some(CharKind::Word)
2304 && word_range.to_inclusive().contains(&cursor_position)
2305 {
2306 let mut completion_menu = completion_menu.clone();
2307 drop(context_menu);
2308
2309 let query = Self::completion_query(buffer, cursor_position);
2310 cx.spawn(async move |this, cx| {
2311 completion_menu
2312 .filter(query.as_deref(), cx.background_executor().clone())
2313 .await;
2314
2315 this.update(cx, |this, cx| {
2316 let mut context_menu = this.context_menu.borrow_mut();
2317 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2318 else {
2319 return;
2320 };
2321
2322 if menu.id > completion_menu.id {
2323 return;
2324 }
2325
2326 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2327 drop(context_menu);
2328 cx.notify();
2329 })
2330 })
2331 .detach();
2332
2333 if show_completions {
2334 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2335 }
2336 } else {
2337 drop(context_menu);
2338 self.hide_context_menu(window, cx);
2339 }
2340 } else {
2341 drop(context_menu);
2342 }
2343
2344 hide_hover(self, cx);
2345
2346 if old_cursor_position.to_display_point(&display_map).row()
2347 != new_cursor_position.to_display_point(&display_map).row()
2348 {
2349 self.available_code_actions.take();
2350 }
2351 self.refresh_code_actions(window, cx);
2352 self.refresh_document_highlights(cx);
2353 self.refresh_selected_text_highlights(window, cx);
2354 refresh_matching_bracket_highlights(self, window, cx);
2355 self.update_visible_inline_completion(window, cx);
2356 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2357 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2358 if self.git_blame_inline_enabled {
2359 self.start_inline_blame_timer(window, cx);
2360 }
2361 }
2362
2363 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2364 cx.emit(EditorEvent::SelectionsChanged { local });
2365
2366 let selections = &self.selections.disjoint;
2367 if selections.len() == 1 {
2368 cx.emit(SearchEvent::ActiveMatchChanged)
2369 }
2370 if local && self.is_singleton(cx) {
2371 let inmemory_selections = selections.iter().map(|s| s.range()).collect();
2372 self.update_restoration_data(cx, |data| {
2373 data.selections = inmemory_selections;
2374 });
2375
2376 if WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2377 {
2378 if let Some(workspace_id) =
2379 self.workspace.as_ref().and_then(|workspace| workspace.1)
2380 {
2381 let snapshot = self.buffer().read(cx).snapshot(cx);
2382 let selections = selections.clone();
2383 let background_executor = cx.background_executor().clone();
2384 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2385 self.serialize_selections = cx.background_spawn(async move {
2386 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2387 let db_selections = selections
2388 .iter()
2389 .map(|selection| {
2390 (
2391 selection.start.to_offset(&snapshot),
2392 selection.end.to_offset(&snapshot),
2393 )
2394 })
2395 .collect();
2396
2397 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2398 .await
2399 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2400 .log_err();
2401 });
2402 }
2403 }
2404 }
2405
2406 cx.notify();
2407 }
2408
2409 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2410 if !self.is_singleton(cx)
2411 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
2412 {
2413 return;
2414 }
2415
2416 let snapshot = self.buffer().read(cx).snapshot(cx);
2417 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2418 display_map
2419 .snapshot(cx)
2420 .folds_in_range(0..snapshot.len())
2421 .map(|fold| fold.range.deref().clone())
2422 .collect()
2423 });
2424 self.update_restoration_data(cx, |data| {
2425 data.folds = inmemory_folds;
2426 });
2427
2428 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2429 return;
2430 };
2431 let background_executor = cx.background_executor().clone();
2432 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2433 let db_folds = self.display_map.update(cx, |display_map, cx| {
2434 display_map
2435 .snapshot(cx)
2436 .folds_in_range(0..snapshot.len())
2437 .map(|fold| {
2438 (
2439 fold.range.start.to_offset(&snapshot),
2440 fold.range.end.to_offset(&snapshot),
2441 )
2442 })
2443 .collect()
2444 });
2445 self.serialize_folds = cx.background_spawn(async move {
2446 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2447 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2448 .await
2449 .with_context(|| {
2450 format!(
2451 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2452 )
2453 })
2454 .log_err();
2455 });
2456 }
2457
2458 pub fn sync_selections(
2459 &mut self,
2460 other: Entity<Editor>,
2461 cx: &mut Context<Self>,
2462 ) -> gpui::Subscription {
2463 let other_selections = other.read(cx).selections.disjoint.to_vec();
2464 self.selections.change_with(cx, |selections| {
2465 selections.select_anchors(other_selections);
2466 });
2467
2468 let other_subscription =
2469 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2470 EditorEvent::SelectionsChanged { local: true } => {
2471 let other_selections = other.read(cx).selections.disjoint.to_vec();
2472 if other_selections.is_empty() {
2473 return;
2474 }
2475 this.selections.change_with(cx, |selections| {
2476 selections.select_anchors(other_selections);
2477 });
2478 }
2479 _ => {}
2480 });
2481
2482 let this_subscription =
2483 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2484 EditorEvent::SelectionsChanged { local: true } => {
2485 let these_selections = this.selections.disjoint.to_vec();
2486 if these_selections.is_empty() {
2487 return;
2488 }
2489 other.update(cx, |other_editor, cx| {
2490 other_editor.selections.change_with(cx, |selections| {
2491 selections.select_anchors(these_selections);
2492 })
2493 });
2494 }
2495 _ => {}
2496 });
2497
2498 Subscription::join(other_subscription, this_subscription)
2499 }
2500
2501 pub fn change_selections<R>(
2502 &mut self,
2503 autoscroll: Option<Autoscroll>,
2504 window: &mut Window,
2505 cx: &mut Context<Self>,
2506 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2507 ) -> R {
2508 self.change_selections_inner(autoscroll, true, window, cx, change)
2509 }
2510
2511 fn change_selections_inner<R>(
2512 &mut self,
2513 autoscroll: Option<Autoscroll>,
2514 request_completions: bool,
2515 window: &mut Window,
2516 cx: &mut Context<Self>,
2517 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2518 ) -> R {
2519 let old_cursor_position = self.selections.newest_anchor().head();
2520 self.push_to_selection_history();
2521
2522 let (changed, result) = self.selections.change_with(cx, change);
2523
2524 if changed {
2525 if let Some(autoscroll) = autoscroll {
2526 self.request_autoscroll(autoscroll, cx);
2527 }
2528 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2529
2530 if self.should_open_signature_help_automatically(
2531 &old_cursor_position,
2532 self.signature_help_state.backspace_pressed(),
2533 cx,
2534 ) {
2535 self.show_signature_help(&ShowSignatureHelp, window, cx);
2536 }
2537 self.signature_help_state.set_backspace_pressed(false);
2538 }
2539
2540 result
2541 }
2542
2543 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2544 where
2545 I: IntoIterator<Item = (Range<S>, T)>,
2546 S: ToOffset,
2547 T: Into<Arc<str>>,
2548 {
2549 if self.read_only(cx) {
2550 return;
2551 }
2552
2553 self.buffer
2554 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2555 }
2556
2557 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2558 where
2559 I: IntoIterator<Item = (Range<S>, T)>,
2560 S: ToOffset,
2561 T: Into<Arc<str>>,
2562 {
2563 if self.read_only(cx) {
2564 return;
2565 }
2566
2567 self.buffer.update(cx, |buffer, cx| {
2568 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2569 });
2570 }
2571
2572 pub fn edit_with_block_indent<I, S, T>(
2573 &mut self,
2574 edits: I,
2575 original_indent_columns: Vec<Option<u32>>,
2576 cx: &mut Context<Self>,
2577 ) where
2578 I: IntoIterator<Item = (Range<S>, T)>,
2579 S: ToOffset,
2580 T: Into<Arc<str>>,
2581 {
2582 if self.read_only(cx) {
2583 return;
2584 }
2585
2586 self.buffer.update(cx, |buffer, cx| {
2587 buffer.edit(
2588 edits,
2589 Some(AutoindentMode::Block {
2590 original_indent_columns,
2591 }),
2592 cx,
2593 )
2594 });
2595 }
2596
2597 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2598 self.hide_context_menu(window, cx);
2599
2600 match phase {
2601 SelectPhase::Begin {
2602 position,
2603 add,
2604 click_count,
2605 } => self.begin_selection(position, add, click_count, window, cx),
2606 SelectPhase::BeginColumnar {
2607 position,
2608 goal_column,
2609 reset,
2610 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2611 SelectPhase::Extend {
2612 position,
2613 click_count,
2614 } => self.extend_selection(position, click_count, window, cx),
2615 SelectPhase::Update {
2616 position,
2617 goal_column,
2618 scroll_delta,
2619 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2620 SelectPhase::End => self.end_selection(window, cx),
2621 }
2622 }
2623
2624 fn extend_selection(
2625 &mut self,
2626 position: DisplayPoint,
2627 click_count: usize,
2628 window: &mut Window,
2629 cx: &mut Context<Self>,
2630 ) {
2631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2632 let tail = self.selections.newest::<usize>(cx).tail();
2633 self.begin_selection(position, false, click_count, window, cx);
2634
2635 let position = position.to_offset(&display_map, Bias::Left);
2636 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2637
2638 let mut pending_selection = self
2639 .selections
2640 .pending_anchor()
2641 .expect("extend_selection not called with pending selection");
2642 if position >= tail {
2643 pending_selection.start = tail_anchor;
2644 } else {
2645 pending_selection.end = tail_anchor;
2646 pending_selection.reversed = true;
2647 }
2648
2649 let mut pending_mode = self.selections.pending_mode().unwrap();
2650 match &mut pending_mode {
2651 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2652 _ => {}
2653 }
2654
2655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2656 s.set_pending(pending_selection, pending_mode)
2657 });
2658 }
2659
2660 fn begin_selection(
2661 &mut self,
2662 position: DisplayPoint,
2663 add: bool,
2664 click_count: usize,
2665 window: &mut Window,
2666 cx: &mut Context<Self>,
2667 ) {
2668 if !self.focus_handle.is_focused(window) {
2669 self.last_focused_descendant = None;
2670 window.focus(&self.focus_handle);
2671 }
2672
2673 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2674 let buffer = &display_map.buffer_snapshot;
2675 let newest_selection = self.selections.newest_anchor().clone();
2676 let position = display_map.clip_point(position, Bias::Left);
2677
2678 let start;
2679 let end;
2680 let mode;
2681 let mut auto_scroll;
2682 match click_count {
2683 1 => {
2684 start = buffer.anchor_before(position.to_point(&display_map));
2685 end = start;
2686 mode = SelectMode::Character;
2687 auto_scroll = true;
2688 }
2689 2 => {
2690 let range = movement::surrounding_word(&display_map, position);
2691 start = buffer.anchor_before(range.start.to_point(&display_map));
2692 end = buffer.anchor_before(range.end.to_point(&display_map));
2693 mode = SelectMode::Word(start..end);
2694 auto_scroll = true;
2695 }
2696 3 => {
2697 let position = display_map
2698 .clip_point(position, Bias::Left)
2699 .to_point(&display_map);
2700 let line_start = display_map.prev_line_boundary(position).0;
2701 let next_line_start = buffer.clip_point(
2702 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2703 Bias::Left,
2704 );
2705 start = buffer.anchor_before(line_start);
2706 end = buffer.anchor_before(next_line_start);
2707 mode = SelectMode::Line(start..end);
2708 auto_scroll = true;
2709 }
2710 _ => {
2711 start = buffer.anchor_before(0);
2712 end = buffer.anchor_before(buffer.len());
2713 mode = SelectMode::All;
2714 auto_scroll = false;
2715 }
2716 }
2717 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2718
2719 let point_to_delete: Option<usize> = {
2720 let selected_points: Vec<Selection<Point>> =
2721 self.selections.disjoint_in_range(start..end, cx);
2722
2723 if !add || click_count > 1 {
2724 None
2725 } else if !selected_points.is_empty() {
2726 Some(selected_points[0].id)
2727 } else {
2728 let clicked_point_already_selected =
2729 self.selections.disjoint.iter().find(|selection| {
2730 selection.start.to_point(buffer) == start.to_point(buffer)
2731 || selection.end.to_point(buffer) == end.to_point(buffer)
2732 });
2733
2734 clicked_point_already_selected.map(|selection| selection.id)
2735 }
2736 };
2737
2738 let selections_count = self.selections.count();
2739
2740 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2741 if let Some(point_to_delete) = point_to_delete {
2742 s.delete(point_to_delete);
2743
2744 if selections_count == 1 {
2745 s.set_pending_anchor_range(start..end, mode);
2746 }
2747 } else {
2748 if !add {
2749 s.clear_disjoint();
2750 } else if click_count > 1 {
2751 s.delete(newest_selection.id)
2752 }
2753
2754 s.set_pending_anchor_range(start..end, mode);
2755 }
2756 });
2757 }
2758
2759 fn begin_columnar_selection(
2760 &mut self,
2761 position: DisplayPoint,
2762 goal_column: u32,
2763 reset: bool,
2764 window: &mut Window,
2765 cx: &mut Context<Self>,
2766 ) {
2767 if !self.focus_handle.is_focused(window) {
2768 self.last_focused_descendant = None;
2769 window.focus(&self.focus_handle);
2770 }
2771
2772 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2773
2774 if reset {
2775 let pointer_position = display_map
2776 .buffer_snapshot
2777 .anchor_before(position.to_point(&display_map));
2778
2779 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2780 s.clear_disjoint();
2781 s.set_pending_anchor_range(
2782 pointer_position..pointer_position,
2783 SelectMode::Character,
2784 );
2785 });
2786 }
2787
2788 let tail = self.selections.newest::<Point>(cx).tail();
2789 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2790
2791 if !reset {
2792 self.select_columns(
2793 tail.to_display_point(&display_map),
2794 position,
2795 goal_column,
2796 &display_map,
2797 window,
2798 cx,
2799 );
2800 }
2801 }
2802
2803 fn update_selection(
2804 &mut self,
2805 position: DisplayPoint,
2806 goal_column: u32,
2807 scroll_delta: gpui::Point<f32>,
2808 window: &mut Window,
2809 cx: &mut Context<Self>,
2810 ) {
2811 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2812
2813 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2814 let tail = tail.to_display_point(&display_map);
2815 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2816 } else if let Some(mut pending) = self.selections.pending_anchor() {
2817 let buffer = self.buffer.read(cx).snapshot(cx);
2818 let head;
2819 let tail;
2820 let mode = self.selections.pending_mode().unwrap();
2821 match &mode {
2822 SelectMode::Character => {
2823 head = position.to_point(&display_map);
2824 tail = pending.tail().to_point(&buffer);
2825 }
2826 SelectMode::Word(original_range) => {
2827 let original_display_range = original_range.start.to_display_point(&display_map)
2828 ..original_range.end.to_display_point(&display_map);
2829 let original_buffer_range = original_display_range.start.to_point(&display_map)
2830 ..original_display_range.end.to_point(&display_map);
2831 if movement::is_inside_word(&display_map, position)
2832 || original_display_range.contains(&position)
2833 {
2834 let word_range = movement::surrounding_word(&display_map, position);
2835 if word_range.start < original_display_range.start {
2836 head = word_range.start.to_point(&display_map);
2837 } else {
2838 head = word_range.end.to_point(&display_map);
2839 }
2840 } else {
2841 head = position.to_point(&display_map);
2842 }
2843
2844 if head <= original_buffer_range.start {
2845 tail = original_buffer_range.end;
2846 } else {
2847 tail = original_buffer_range.start;
2848 }
2849 }
2850 SelectMode::Line(original_range) => {
2851 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2852
2853 let position = display_map
2854 .clip_point(position, Bias::Left)
2855 .to_point(&display_map);
2856 let line_start = display_map.prev_line_boundary(position).0;
2857 let next_line_start = buffer.clip_point(
2858 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2859 Bias::Left,
2860 );
2861
2862 if line_start < original_range.start {
2863 head = line_start
2864 } else {
2865 head = next_line_start
2866 }
2867
2868 if head <= original_range.start {
2869 tail = original_range.end;
2870 } else {
2871 tail = original_range.start;
2872 }
2873 }
2874 SelectMode::All => {
2875 return;
2876 }
2877 };
2878
2879 if head < tail {
2880 pending.start = buffer.anchor_before(head);
2881 pending.end = buffer.anchor_before(tail);
2882 pending.reversed = true;
2883 } else {
2884 pending.start = buffer.anchor_before(tail);
2885 pending.end = buffer.anchor_before(head);
2886 pending.reversed = false;
2887 }
2888
2889 self.change_selections(None, window, cx, |s| {
2890 s.set_pending(pending, mode);
2891 });
2892 } else {
2893 log::error!("update_selection dispatched with no pending selection");
2894 return;
2895 }
2896
2897 self.apply_scroll_delta(scroll_delta, window, cx);
2898 cx.notify();
2899 }
2900
2901 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2902 self.columnar_selection_tail.take();
2903 if self.selections.pending_anchor().is_some() {
2904 let selections = self.selections.all::<usize>(cx);
2905 self.change_selections(None, window, cx, |s| {
2906 s.select(selections);
2907 s.clear_pending();
2908 });
2909 }
2910 }
2911
2912 fn select_columns(
2913 &mut self,
2914 tail: DisplayPoint,
2915 head: DisplayPoint,
2916 goal_column: u32,
2917 display_map: &DisplaySnapshot,
2918 window: &mut Window,
2919 cx: &mut Context<Self>,
2920 ) {
2921 let start_row = cmp::min(tail.row(), head.row());
2922 let end_row = cmp::max(tail.row(), head.row());
2923 let start_column = cmp::min(tail.column(), goal_column);
2924 let end_column = cmp::max(tail.column(), goal_column);
2925 let reversed = start_column < tail.column();
2926
2927 let selection_ranges = (start_row.0..=end_row.0)
2928 .map(DisplayRow)
2929 .filter_map(|row| {
2930 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2931 let start = display_map
2932 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2933 .to_point(display_map);
2934 let end = display_map
2935 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2936 .to_point(display_map);
2937 if reversed {
2938 Some(end..start)
2939 } else {
2940 Some(start..end)
2941 }
2942 } else {
2943 None
2944 }
2945 })
2946 .collect::<Vec<_>>();
2947
2948 self.change_selections(None, window, cx, |s| {
2949 s.select_ranges(selection_ranges);
2950 });
2951 cx.notify();
2952 }
2953
2954 pub fn has_pending_nonempty_selection(&self) -> bool {
2955 let pending_nonempty_selection = match self.selections.pending_anchor() {
2956 Some(Selection { start, end, .. }) => start != end,
2957 None => false,
2958 };
2959
2960 pending_nonempty_selection
2961 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2962 }
2963
2964 pub fn has_pending_selection(&self) -> bool {
2965 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2966 }
2967
2968 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2969 self.selection_mark_mode = false;
2970
2971 if self.clear_expanded_diff_hunks(cx) {
2972 cx.notify();
2973 return;
2974 }
2975 if self.dismiss_menus_and_popups(true, window, cx) {
2976 return;
2977 }
2978
2979 if self.mode == EditorMode::Full
2980 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2981 {
2982 return;
2983 }
2984
2985 cx.propagate();
2986 }
2987
2988 pub fn dismiss_menus_and_popups(
2989 &mut self,
2990 is_user_requested: bool,
2991 window: &mut Window,
2992 cx: &mut Context<Self>,
2993 ) -> bool {
2994 if self.take_rename(false, window, cx).is_some() {
2995 return true;
2996 }
2997
2998 if hide_hover(self, cx) {
2999 return true;
3000 }
3001
3002 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3003 return true;
3004 }
3005
3006 if self.hide_context_menu(window, cx).is_some() {
3007 return true;
3008 }
3009
3010 if self.mouse_context_menu.take().is_some() {
3011 return true;
3012 }
3013
3014 if is_user_requested && self.discard_inline_completion(true, cx) {
3015 return true;
3016 }
3017
3018 if self.snippet_stack.pop().is_some() {
3019 return true;
3020 }
3021
3022 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3023 self.dismiss_diagnostics(cx);
3024 return true;
3025 }
3026
3027 false
3028 }
3029
3030 fn linked_editing_ranges_for(
3031 &self,
3032 selection: Range<text::Anchor>,
3033 cx: &App,
3034 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3035 if self.linked_edit_ranges.is_empty() {
3036 return None;
3037 }
3038 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3039 selection.end.buffer_id.and_then(|end_buffer_id| {
3040 if selection.start.buffer_id != Some(end_buffer_id) {
3041 return None;
3042 }
3043 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3044 let snapshot = buffer.read(cx).snapshot();
3045 self.linked_edit_ranges
3046 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3047 .map(|ranges| (ranges, snapshot, buffer))
3048 })?;
3049 use text::ToOffset as TO;
3050 // find offset from the start of current range to current cursor position
3051 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3052
3053 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3054 let start_difference = start_offset - start_byte_offset;
3055 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3056 let end_difference = end_offset - start_byte_offset;
3057 // Current range has associated linked ranges.
3058 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3059 for range in linked_ranges.iter() {
3060 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3061 let end_offset = start_offset + end_difference;
3062 let start_offset = start_offset + start_difference;
3063 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3064 continue;
3065 }
3066 if self.selections.disjoint_anchor_ranges().any(|s| {
3067 if s.start.buffer_id != selection.start.buffer_id
3068 || s.end.buffer_id != selection.end.buffer_id
3069 {
3070 return false;
3071 }
3072 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3073 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3074 }) {
3075 continue;
3076 }
3077 let start = buffer_snapshot.anchor_after(start_offset);
3078 let end = buffer_snapshot.anchor_after(end_offset);
3079 linked_edits
3080 .entry(buffer.clone())
3081 .or_default()
3082 .push(start..end);
3083 }
3084 Some(linked_edits)
3085 }
3086
3087 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3088 let text: Arc<str> = text.into();
3089
3090 if self.read_only(cx) {
3091 return;
3092 }
3093
3094 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3095
3096 let selections = self.selections.all_adjusted(cx);
3097 let mut bracket_inserted = false;
3098 let mut edits = Vec::new();
3099 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3100 let mut new_selections = Vec::with_capacity(selections.len());
3101 let mut new_autoclose_regions = Vec::new();
3102 let snapshot = self.buffer.read(cx).read(cx);
3103
3104 for (selection, autoclose_region) in
3105 self.selections_with_autoclose_regions(selections, &snapshot)
3106 {
3107 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3108 // Determine if the inserted text matches the opening or closing
3109 // bracket of any of this language's bracket pairs.
3110 let mut bracket_pair = None;
3111 let mut is_bracket_pair_start = false;
3112 let mut is_bracket_pair_end = false;
3113 if !text.is_empty() {
3114 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3115 // and they are removing the character that triggered IME popup.
3116 for (pair, enabled) in scope.brackets() {
3117 if !pair.close && !pair.surround {
3118 continue;
3119 }
3120
3121 if enabled && pair.start.ends_with(text.as_ref()) {
3122 let prefix_len = pair.start.len() - text.len();
3123 let preceding_text_matches_prefix = prefix_len == 0
3124 || (selection.start.column >= (prefix_len as u32)
3125 && snapshot.contains_str_at(
3126 Point::new(
3127 selection.start.row,
3128 selection.start.column - (prefix_len as u32),
3129 ),
3130 &pair.start[..prefix_len],
3131 ));
3132 if preceding_text_matches_prefix {
3133 bracket_pair = Some(pair.clone());
3134 is_bracket_pair_start = true;
3135 break;
3136 }
3137 }
3138 if pair.end.as_str() == text.as_ref() {
3139 bracket_pair = Some(pair.clone());
3140 is_bracket_pair_end = true;
3141 break;
3142 }
3143 }
3144 }
3145
3146 if let Some(bracket_pair) = bracket_pair {
3147 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3148 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3149 let auto_surround =
3150 self.use_auto_surround && snapshot_settings.use_auto_surround;
3151 if selection.is_empty() {
3152 if is_bracket_pair_start {
3153 // If the inserted text is a suffix of an opening bracket and the
3154 // selection is preceded by the rest of the opening bracket, then
3155 // insert the closing bracket.
3156 let following_text_allows_autoclose = snapshot
3157 .chars_at(selection.start)
3158 .next()
3159 .map_or(true, |c| scope.should_autoclose_before(c));
3160
3161 let preceding_text_allows_autoclose = selection.start.column == 0
3162 || snapshot.reversed_chars_at(selection.start).next().map_or(
3163 true,
3164 |c| {
3165 bracket_pair.start != bracket_pair.end
3166 || !snapshot
3167 .char_classifier_at(selection.start)
3168 .is_word(c)
3169 },
3170 );
3171
3172 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3173 && bracket_pair.start.len() == 1
3174 {
3175 let target = bracket_pair.start.chars().next().unwrap();
3176 let current_line_count = snapshot
3177 .reversed_chars_at(selection.start)
3178 .take_while(|&c| c != '\n')
3179 .filter(|&c| c == target)
3180 .count();
3181 current_line_count % 2 == 1
3182 } else {
3183 false
3184 };
3185
3186 if autoclose
3187 && bracket_pair.close
3188 && following_text_allows_autoclose
3189 && preceding_text_allows_autoclose
3190 && !is_closing_quote
3191 {
3192 let anchor = snapshot.anchor_before(selection.end);
3193 new_selections.push((selection.map(|_| anchor), text.len()));
3194 new_autoclose_regions.push((
3195 anchor,
3196 text.len(),
3197 selection.id,
3198 bracket_pair.clone(),
3199 ));
3200 edits.push((
3201 selection.range(),
3202 format!("{}{}", text, bracket_pair.end).into(),
3203 ));
3204 bracket_inserted = true;
3205 continue;
3206 }
3207 }
3208
3209 if let Some(region) = autoclose_region {
3210 // If the selection is followed by an auto-inserted closing bracket,
3211 // then don't insert that closing bracket again; just move the selection
3212 // past the closing bracket.
3213 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3214 && text.as_ref() == region.pair.end.as_str();
3215 if should_skip {
3216 let anchor = snapshot.anchor_after(selection.end);
3217 new_selections
3218 .push((selection.map(|_| anchor), region.pair.end.len()));
3219 continue;
3220 }
3221 }
3222
3223 let always_treat_brackets_as_autoclosed = snapshot
3224 .language_settings_at(selection.start, cx)
3225 .always_treat_brackets_as_autoclosed;
3226 if always_treat_brackets_as_autoclosed
3227 && is_bracket_pair_end
3228 && snapshot.contains_str_at(selection.end, text.as_ref())
3229 {
3230 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3231 // and the inserted text is a closing bracket and the selection is followed
3232 // by the closing bracket then move the selection past the closing bracket.
3233 let anchor = snapshot.anchor_after(selection.end);
3234 new_selections.push((selection.map(|_| anchor), text.len()));
3235 continue;
3236 }
3237 }
3238 // If an opening bracket is 1 character long and is typed while
3239 // text is selected, then surround that text with the bracket pair.
3240 else if auto_surround
3241 && bracket_pair.surround
3242 && is_bracket_pair_start
3243 && bracket_pair.start.chars().count() == 1
3244 {
3245 edits.push((selection.start..selection.start, text.clone()));
3246 edits.push((
3247 selection.end..selection.end,
3248 bracket_pair.end.as_str().into(),
3249 ));
3250 bracket_inserted = true;
3251 new_selections.push((
3252 Selection {
3253 id: selection.id,
3254 start: snapshot.anchor_after(selection.start),
3255 end: snapshot.anchor_before(selection.end),
3256 reversed: selection.reversed,
3257 goal: selection.goal,
3258 },
3259 0,
3260 ));
3261 continue;
3262 }
3263 }
3264 }
3265
3266 if self.auto_replace_emoji_shortcode
3267 && selection.is_empty()
3268 && text.as_ref().ends_with(':')
3269 {
3270 if let Some(possible_emoji_short_code) =
3271 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3272 {
3273 if !possible_emoji_short_code.is_empty() {
3274 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3275 let emoji_shortcode_start = Point::new(
3276 selection.start.row,
3277 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3278 );
3279
3280 // Remove shortcode from buffer
3281 edits.push((
3282 emoji_shortcode_start..selection.start,
3283 "".to_string().into(),
3284 ));
3285 new_selections.push((
3286 Selection {
3287 id: selection.id,
3288 start: snapshot.anchor_after(emoji_shortcode_start),
3289 end: snapshot.anchor_before(selection.start),
3290 reversed: selection.reversed,
3291 goal: selection.goal,
3292 },
3293 0,
3294 ));
3295
3296 // Insert emoji
3297 let selection_start_anchor = snapshot.anchor_after(selection.start);
3298 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3299 edits.push((selection.start..selection.end, emoji.to_string().into()));
3300
3301 continue;
3302 }
3303 }
3304 }
3305 }
3306
3307 // If not handling any auto-close operation, then just replace the selected
3308 // text with the given input and move the selection to the end of the
3309 // newly inserted text.
3310 let anchor = snapshot.anchor_after(selection.end);
3311 if !self.linked_edit_ranges.is_empty() {
3312 let start_anchor = snapshot.anchor_before(selection.start);
3313
3314 let is_word_char = text.chars().next().map_or(true, |char| {
3315 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3316 classifier.is_word(char)
3317 });
3318
3319 if is_word_char {
3320 if let Some(ranges) = self
3321 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3322 {
3323 for (buffer, edits) in ranges {
3324 linked_edits
3325 .entry(buffer.clone())
3326 .or_default()
3327 .extend(edits.into_iter().map(|range| (range, text.clone())));
3328 }
3329 }
3330 }
3331 }
3332
3333 new_selections.push((selection.map(|_| anchor), 0));
3334 edits.push((selection.start..selection.end, text.clone()));
3335 }
3336
3337 drop(snapshot);
3338
3339 self.transact(window, cx, |this, window, cx| {
3340 let initial_buffer_versions =
3341 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3342
3343 this.buffer.update(cx, |buffer, cx| {
3344 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3345 });
3346 for (buffer, edits) in linked_edits {
3347 buffer.update(cx, |buffer, cx| {
3348 let snapshot = buffer.snapshot();
3349 let edits = edits
3350 .into_iter()
3351 .map(|(range, text)| {
3352 use text::ToPoint as TP;
3353 let end_point = TP::to_point(&range.end, &snapshot);
3354 let start_point = TP::to_point(&range.start, &snapshot);
3355 (start_point..end_point, text)
3356 })
3357 .sorted_by_key(|(range, _)| range.start);
3358 buffer.edit(edits, None, cx);
3359 })
3360 }
3361 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3362 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3363 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3364 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3365 .zip(new_selection_deltas)
3366 .map(|(selection, delta)| Selection {
3367 id: selection.id,
3368 start: selection.start + delta,
3369 end: selection.end + delta,
3370 reversed: selection.reversed,
3371 goal: SelectionGoal::None,
3372 })
3373 .collect::<Vec<_>>();
3374
3375 let mut i = 0;
3376 for (position, delta, selection_id, pair) in new_autoclose_regions {
3377 let position = position.to_offset(&map.buffer_snapshot) + delta;
3378 let start = map.buffer_snapshot.anchor_before(position);
3379 let end = map.buffer_snapshot.anchor_after(position);
3380 while let Some(existing_state) = this.autoclose_regions.get(i) {
3381 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3382 Ordering::Less => i += 1,
3383 Ordering::Greater => break,
3384 Ordering::Equal => {
3385 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3386 Ordering::Less => i += 1,
3387 Ordering::Equal => break,
3388 Ordering::Greater => break,
3389 }
3390 }
3391 }
3392 }
3393 this.autoclose_regions.insert(
3394 i,
3395 AutocloseRegion {
3396 selection_id,
3397 range: start..end,
3398 pair,
3399 },
3400 );
3401 }
3402
3403 let had_active_inline_completion = this.has_active_inline_completion();
3404 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3405 s.select(new_selections)
3406 });
3407
3408 if !bracket_inserted {
3409 if let Some(on_type_format_task) =
3410 this.trigger_on_type_formatting(text.to_string(), window, cx)
3411 {
3412 on_type_format_task.detach_and_log_err(cx);
3413 }
3414 }
3415
3416 let editor_settings = EditorSettings::get_global(cx);
3417 if bracket_inserted
3418 && (editor_settings.auto_signature_help
3419 || editor_settings.show_signature_help_after_edits)
3420 {
3421 this.show_signature_help(&ShowSignatureHelp, window, cx);
3422 }
3423
3424 let trigger_in_words =
3425 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3426 if this.hard_wrap.is_some() {
3427 let latest: Range<Point> = this.selections.newest(cx).range();
3428 if latest.is_empty()
3429 && this
3430 .buffer()
3431 .read(cx)
3432 .snapshot(cx)
3433 .line_len(MultiBufferRow(latest.start.row))
3434 == latest.start.column
3435 {
3436 this.rewrap_impl(
3437 RewrapOptions {
3438 override_language_settings: true,
3439 preserve_existing_whitespace: true,
3440 },
3441 cx,
3442 )
3443 }
3444 }
3445 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3446 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3447 this.refresh_inline_completion(true, false, window, cx);
3448 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3449 });
3450 }
3451
3452 fn find_possible_emoji_shortcode_at_position(
3453 snapshot: &MultiBufferSnapshot,
3454 position: Point,
3455 ) -> Option<String> {
3456 let mut chars = Vec::new();
3457 let mut found_colon = false;
3458 for char in snapshot.reversed_chars_at(position).take(100) {
3459 // Found a possible emoji shortcode in the middle of the buffer
3460 if found_colon {
3461 if char.is_whitespace() {
3462 chars.reverse();
3463 return Some(chars.iter().collect());
3464 }
3465 // If the previous character is not a whitespace, we are in the middle of a word
3466 // and we only want to complete the shortcode if the word is made up of other emojis
3467 let mut containing_word = String::new();
3468 for ch in snapshot
3469 .reversed_chars_at(position)
3470 .skip(chars.len() + 1)
3471 .take(100)
3472 {
3473 if ch.is_whitespace() {
3474 break;
3475 }
3476 containing_word.push(ch);
3477 }
3478 let containing_word = containing_word.chars().rev().collect::<String>();
3479 if util::word_consists_of_emojis(containing_word.as_str()) {
3480 chars.reverse();
3481 return Some(chars.iter().collect());
3482 }
3483 }
3484
3485 if char.is_whitespace() || !char.is_ascii() {
3486 return None;
3487 }
3488 if char == ':' {
3489 found_colon = true;
3490 } else {
3491 chars.push(char);
3492 }
3493 }
3494 // Found a possible emoji shortcode at the beginning of the buffer
3495 chars.reverse();
3496 Some(chars.iter().collect())
3497 }
3498
3499 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3500 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3501 self.transact(window, cx, |this, window, cx| {
3502 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3503 let selections = this.selections.all::<usize>(cx);
3504 let multi_buffer = this.buffer.read(cx);
3505 let buffer = multi_buffer.snapshot(cx);
3506 selections
3507 .iter()
3508 .map(|selection| {
3509 let start_point = selection.start.to_point(&buffer);
3510 let mut indent =
3511 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3512 indent.len = cmp::min(indent.len, start_point.column);
3513 let start = selection.start;
3514 let end = selection.end;
3515 let selection_is_empty = start == end;
3516 let language_scope = buffer.language_scope_at(start);
3517 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3518 &language_scope
3519 {
3520 let insert_extra_newline =
3521 insert_extra_newline_brackets(&buffer, start..end, language)
3522 || insert_extra_newline_tree_sitter(&buffer, start..end);
3523
3524 // Comment extension on newline is allowed only for cursor selections
3525 let comment_delimiter = maybe!({
3526 if !selection_is_empty {
3527 return None;
3528 }
3529
3530 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3531 return None;
3532 }
3533
3534 let delimiters = language.line_comment_prefixes();
3535 let max_len_of_delimiter =
3536 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3537 let (snapshot, range) =
3538 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3539
3540 let mut index_of_first_non_whitespace = 0;
3541 let comment_candidate = snapshot
3542 .chars_for_range(range)
3543 .skip_while(|c| {
3544 let should_skip = c.is_whitespace();
3545 if should_skip {
3546 index_of_first_non_whitespace += 1;
3547 }
3548 should_skip
3549 })
3550 .take(max_len_of_delimiter)
3551 .collect::<String>();
3552 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3553 comment_candidate.starts_with(comment_prefix.as_ref())
3554 })?;
3555 let cursor_is_placed_after_comment_marker =
3556 index_of_first_non_whitespace + comment_prefix.len()
3557 <= start_point.column as usize;
3558 if cursor_is_placed_after_comment_marker {
3559 Some(comment_prefix.clone())
3560 } else {
3561 None
3562 }
3563 });
3564 (comment_delimiter, insert_extra_newline)
3565 } else {
3566 (None, false)
3567 };
3568
3569 let capacity_for_delimiter = comment_delimiter
3570 .as_deref()
3571 .map(str::len)
3572 .unwrap_or_default();
3573 let mut new_text =
3574 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3575 new_text.push('\n');
3576 new_text.extend(indent.chars());
3577 if let Some(delimiter) = &comment_delimiter {
3578 new_text.push_str(delimiter);
3579 }
3580 if insert_extra_newline {
3581 new_text = new_text.repeat(2);
3582 }
3583
3584 let anchor = buffer.anchor_after(end);
3585 let new_selection = selection.map(|_| anchor);
3586 (
3587 (start..end, new_text),
3588 (insert_extra_newline, new_selection),
3589 )
3590 })
3591 .unzip()
3592 };
3593
3594 this.edit_with_autoindent(edits, cx);
3595 let buffer = this.buffer.read(cx).snapshot(cx);
3596 let new_selections = selection_fixup_info
3597 .into_iter()
3598 .map(|(extra_newline_inserted, new_selection)| {
3599 let mut cursor = new_selection.end.to_point(&buffer);
3600 if extra_newline_inserted {
3601 cursor.row -= 1;
3602 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3603 }
3604 new_selection.map(|_| cursor)
3605 })
3606 .collect();
3607
3608 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3609 s.select(new_selections)
3610 });
3611 this.refresh_inline_completion(true, false, window, cx);
3612 });
3613 }
3614
3615 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3616 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3617
3618 let buffer = self.buffer.read(cx);
3619 let snapshot = buffer.snapshot(cx);
3620
3621 let mut edits = Vec::new();
3622 let mut rows = Vec::new();
3623
3624 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3625 let cursor = selection.head();
3626 let row = cursor.row;
3627
3628 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3629
3630 let newline = "\n".to_string();
3631 edits.push((start_of_line..start_of_line, newline));
3632
3633 rows.push(row + rows_inserted as u32);
3634 }
3635
3636 self.transact(window, cx, |editor, window, cx| {
3637 editor.edit(edits, cx);
3638
3639 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3640 let mut index = 0;
3641 s.move_cursors_with(|map, _, _| {
3642 let row = rows[index];
3643 index += 1;
3644
3645 let point = Point::new(row, 0);
3646 let boundary = map.next_line_boundary(point).1;
3647 let clipped = map.clip_point(boundary, Bias::Left);
3648
3649 (clipped, SelectionGoal::None)
3650 });
3651 });
3652
3653 let mut indent_edits = Vec::new();
3654 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3655 for row in rows {
3656 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3657 for (row, indent) in indents {
3658 if indent.len == 0 {
3659 continue;
3660 }
3661
3662 let text = match indent.kind {
3663 IndentKind::Space => " ".repeat(indent.len as usize),
3664 IndentKind::Tab => "\t".repeat(indent.len as usize),
3665 };
3666 let point = Point::new(row.0, 0);
3667 indent_edits.push((point..point, text));
3668 }
3669 }
3670 editor.edit(indent_edits, cx);
3671 });
3672 }
3673
3674 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3675 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3676
3677 let buffer = self.buffer.read(cx);
3678 let snapshot = buffer.snapshot(cx);
3679
3680 let mut edits = Vec::new();
3681 let mut rows = Vec::new();
3682 let mut rows_inserted = 0;
3683
3684 for selection in self.selections.all_adjusted(cx) {
3685 let cursor = selection.head();
3686 let row = cursor.row;
3687
3688 let point = Point::new(row + 1, 0);
3689 let start_of_line = snapshot.clip_point(point, Bias::Left);
3690
3691 let newline = "\n".to_string();
3692 edits.push((start_of_line..start_of_line, newline));
3693
3694 rows_inserted += 1;
3695 rows.push(row + rows_inserted);
3696 }
3697
3698 self.transact(window, cx, |editor, window, cx| {
3699 editor.edit(edits, cx);
3700
3701 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3702 let mut index = 0;
3703 s.move_cursors_with(|map, _, _| {
3704 let row = rows[index];
3705 index += 1;
3706
3707 let point = Point::new(row, 0);
3708 let boundary = map.next_line_boundary(point).1;
3709 let clipped = map.clip_point(boundary, Bias::Left);
3710
3711 (clipped, SelectionGoal::None)
3712 });
3713 });
3714
3715 let mut indent_edits = Vec::new();
3716 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3717 for row in rows {
3718 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3719 for (row, indent) in indents {
3720 if indent.len == 0 {
3721 continue;
3722 }
3723
3724 let text = match indent.kind {
3725 IndentKind::Space => " ".repeat(indent.len as usize),
3726 IndentKind::Tab => "\t".repeat(indent.len as usize),
3727 };
3728 let point = Point::new(row.0, 0);
3729 indent_edits.push((point..point, text));
3730 }
3731 }
3732 editor.edit(indent_edits, cx);
3733 });
3734 }
3735
3736 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3737 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3738 original_indent_columns: Vec::new(),
3739 });
3740 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3741 }
3742
3743 fn insert_with_autoindent_mode(
3744 &mut self,
3745 text: &str,
3746 autoindent_mode: Option<AutoindentMode>,
3747 window: &mut Window,
3748 cx: &mut Context<Self>,
3749 ) {
3750 if self.read_only(cx) {
3751 return;
3752 }
3753
3754 let text: Arc<str> = text.into();
3755 self.transact(window, cx, |this, window, cx| {
3756 let old_selections = this.selections.all_adjusted(cx);
3757 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3758 let anchors = {
3759 let snapshot = buffer.read(cx);
3760 old_selections
3761 .iter()
3762 .map(|s| {
3763 let anchor = snapshot.anchor_after(s.head());
3764 s.map(|_| anchor)
3765 })
3766 .collect::<Vec<_>>()
3767 };
3768 buffer.edit(
3769 old_selections
3770 .iter()
3771 .map(|s| (s.start..s.end, text.clone())),
3772 autoindent_mode,
3773 cx,
3774 );
3775 anchors
3776 });
3777
3778 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3779 s.select_anchors(selection_anchors);
3780 });
3781
3782 cx.notify();
3783 });
3784 }
3785
3786 fn trigger_completion_on_input(
3787 &mut self,
3788 text: &str,
3789 trigger_in_words: bool,
3790 window: &mut Window,
3791 cx: &mut Context<Self>,
3792 ) {
3793 let ignore_completion_provider = self
3794 .context_menu
3795 .borrow()
3796 .as_ref()
3797 .map(|menu| match menu {
3798 CodeContextMenu::Completions(completions_menu) => {
3799 completions_menu.ignore_completion_provider
3800 }
3801 CodeContextMenu::CodeActions(_) => false,
3802 })
3803 .unwrap_or(false);
3804
3805 if ignore_completion_provider {
3806 self.show_word_completions(&ShowWordCompletions, window, cx);
3807 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3808 self.show_completions(
3809 &ShowCompletions {
3810 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3811 },
3812 window,
3813 cx,
3814 );
3815 } else {
3816 self.hide_context_menu(window, cx);
3817 }
3818 }
3819
3820 fn is_completion_trigger(
3821 &self,
3822 text: &str,
3823 trigger_in_words: bool,
3824 cx: &mut Context<Self>,
3825 ) -> bool {
3826 let position = self.selections.newest_anchor().head();
3827 let multibuffer = self.buffer.read(cx);
3828 let Some(buffer) = position
3829 .buffer_id
3830 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3831 else {
3832 return false;
3833 };
3834
3835 if let Some(completion_provider) = &self.completion_provider {
3836 completion_provider.is_completion_trigger(
3837 &buffer,
3838 position.text_anchor,
3839 text,
3840 trigger_in_words,
3841 cx,
3842 )
3843 } else {
3844 false
3845 }
3846 }
3847
3848 /// If any empty selections is touching the start of its innermost containing autoclose
3849 /// region, expand it to select the brackets.
3850 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3851 let selections = self.selections.all::<usize>(cx);
3852 let buffer = self.buffer.read(cx).read(cx);
3853 let new_selections = self
3854 .selections_with_autoclose_regions(selections, &buffer)
3855 .map(|(mut selection, region)| {
3856 if !selection.is_empty() {
3857 return selection;
3858 }
3859
3860 if let Some(region) = region {
3861 let mut range = region.range.to_offset(&buffer);
3862 if selection.start == range.start && range.start >= region.pair.start.len() {
3863 range.start -= region.pair.start.len();
3864 if buffer.contains_str_at(range.start, ®ion.pair.start)
3865 && buffer.contains_str_at(range.end, ®ion.pair.end)
3866 {
3867 range.end += region.pair.end.len();
3868 selection.start = range.start;
3869 selection.end = range.end;
3870
3871 return selection;
3872 }
3873 }
3874 }
3875
3876 let always_treat_brackets_as_autoclosed = buffer
3877 .language_settings_at(selection.start, cx)
3878 .always_treat_brackets_as_autoclosed;
3879
3880 if !always_treat_brackets_as_autoclosed {
3881 return selection;
3882 }
3883
3884 if let Some(scope) = buffer.language_scope_at(selection.start) {
3885 for (pair, enabled) in scope.brackets() {
3886 if !enabled || !pair.close {
3887 continue;
3888 }
3889
3890 if buffer.contains_str_at(selection.start, &pair.end) {
3891 let pair_start_len = pair.start.len();
3892 if buffer.contains_str_at(
3893 selection.start.saturating_sub(pair_start_len),
3894 &pair.start,
3895 ) {
3896 selection.start -= pair_start_len;
3897 selection.end += pair.end.len();
3898
3899 return selection;
3900 }
3901 }
3902 }
3903 }
3904
3905 selection
3906 })
3907 .collect();
3908
3909 drop(buffer);
3910 self.change_selections(None, window, cx, |selections| {
3911 selections.select(new_selections)
3912 });
3913 }
3914
3915 /// Iterate the given selections, and for each one, find the smallest surrounding
3916 /// autoclose region. This uses the ordering of the selections and the autoclose
3917 /// regions to avoid repeated comparisons.
3918 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3919 &'a self,
3920 selections: impl IntoIterator<Item = Selection<D>>,
3921 buffer: &'a MultiBufferSnapshot,
3922 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3923 let mut i = 0;
3924 let mut regions = self.autoclose_regions.as_slice();
3925 selections.into_iter().map(move |selection| {
3926 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3927
3928 let mut enclosing = None;
3929 while let Some(pair_state) = regions.get(i) {
3930 if pair_state.range.end.to_offset(buffer) < range.start {
3931 regions = ®ions[i + 1..];
3932 i = 0;
3933 } else if pair_state.range.start.to_offset(buffer) > range.end {
3934 break;
3935 } else {
3936 if pair_state.selection_id == selection.id {
3937 enclosing = Some(pair_state);
3938 }
3939 i += 1;
3940 }
3941 }
3942
3943 (selection, enclosing)
3944 })
3945 }
3946
3947 /// Remove any autoclose regions that no longer contain their selection.
3948 fn invalidate_autoclose_regions(
3949 &mut self,
3950 mut selections: &[Selection<Anchor>],
3951 buffer: &MultiBufferSnapshot,
3952 ) {
3953 self.autoclose_regions.retain(|state| {
3954 let mut i = 0;
3955 while let Some(selection) = selections.get(i) {
3956 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3957 selections = &selections[1..];
3958 continue;
3959 }
3960 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3961 break;
3962 }
3963 if selection.id == state.selection_id {
3964 return true;
3965 } else {
3966 i += 1;
3967 }
3968 }
3969 false
3970 });
3971 }
3972
3973 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3974 let offset = position.to_offset(buffer);
3975 let (word_range, kind) = buffer.surrounding_word(offset, true);
3976 if offset > word_range.start && kind == Some(CharKind::Word) {
3977 Some(
3978 buffer
3979 .text_for_range(word_range.start..offset)
3980 .collect::<String>(),
3981 )
3982 } else {
3983 None
3984 }
3985 }
3986
3987 pub fn toggle_inlay_hints(
3988 &mut self,
3989 _: &ToggleInlayHints,
3990 _: &mut Window,
3991 cx: &mut Context<Self>,
3992 ) {
3993 self.refresh_inlay_hints(
3994 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3995 cx,
3996 );
3997 }
3998
3999 pub fn inlay_hints_enabled(&self) -> bool {
4000 self.inlay_hint_cache.enabled
4001 }
4002
4003 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4004 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4005 return;
4006 }
4007
4008 let reason_description = reason.description();
4009 let ignore_debounce = matches!(
4010 reason,
4011 InlayHintRefreshReason::SettingsChange(_)
4012 | InlayHintRefreshReason::Toggle(_)
4013 | InlayHintRefreshReason::ExcerptsRemoved(_)
4014 | InlayHintRefreshReason::ModifiersChanged(_)
4015 );
4016 let (invalidate_cache, required_languages) = match reason {
4017 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4018 match self.inlay_hint_cache.modifiers_override(enabled) {
4019 Some(enabled) => {
4020 if enabled {
4021 (InvalidationStrategy::RefreshRequested, None)
4022 } else {
4023 self.splice_inlays(
4024 &self
4025 .visible_inlay_hints(cx)
4026 .iter()
4027 .map(|inlay| inlay.id)
4028 .collect::<Vec<InlayId>>(),
4029 Vec::new(),
4030 cx,
4031 );
4032 return;
4033 }
4034 }
4035 None => return,
4036 }
4037 }
4038 InlayHintRefreshReason::Toggle(enabled) => {
4039 if self.inlay_hint_cache.toggle(enabled) {
4040 if enabled {
4041 (InvalidationStrategy::RefreshRequested, None)
4042 } else {
4043 self.splice_inlays(
4044 &self
4045 .visible_inlay_hints(cx)
4046 .iter()
4047 .map(|inlay| inlay.id)
4048 .collect::<Vec<InlayId>>(),
4049 Vec::new(),
4050 cx,
4051 );
4052 return;
4053 }
4054 } else {
4055 return;
4056 }
4057 }
4058 InlayHintRefreshReason::SettingsChange(new_settings) => {
4059 match self.inlay_hint_cache.update_settings(
4060 &self.buffer,
4061 new_settings,
4062 self.visible_inlay_hints(cx),
4063 cx,
4064 ) {
4065 ControlFlow::Break(Some(InlaySplice {
4066 to_remove,
4067 to_insert,
4068 })) => {
4069 self.splice_inlays(&to_remove, to_insert, cx);
4070 return;
4071 }
4072 ControlFlow::Break(None) => return,
4073 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4074 }
4075 }
4076 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4077 if let Some(InlaySplice {
4078 to_remove,
4079 to_insert,
4080 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4081 {
4082 self.splice_inlays(&to_remove, to_insert, cx);
4083 }
4084 return;
4085 }
4086 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4087 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4088 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4089 }
4090 InlayHintRefreshReason::RefreshRequested => {
4091 (InvalidationStrategy::RefreshRequested, None)
4092 }
4093 };
4094
4095 if let Some(InlaySplice {
4096 to_remove,
4097 to_insert,
4098 }) = self.inlay_hint_cache.spawn_hint_refresh(
4099 reason_description,
4100 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4101 invalidate_cache,
4102 ignore_debounce,
4103 cx,
4104 ) {
4105 self.splice_inlays(&to_remove, to_insert, cx);
4106 }
4107 }
4108
4109 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4110 self.display_map
4111 .read(cx)
4112 .current_inlays()
4113 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4114 .cloned()
4115 .collect()
4116 }
4117
4118 pub fn excerpts_for_inlay_hints_query(
4119 &self,
4120 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4121 cx: &mut Context<Editor>,
4122 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4123 let Some(project) = self.project.as_ref() else {
4124 return HashMap::default();
4125 };
4126 let project = project.read(cx);
4127 let multi_buffer = self.buffer().read(cx);
4128 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4129 let multi_buffer_visible_start = self
4130 .scroll_manager
4131 .anchor()
4132 .anchor
4133 .to_point(&multi_buffer_snapshot);
4134 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4135 multi_buffer_visible_start
4136 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4137 Bias::Left,
4138 );
4139 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4140 multi_buffer_snapshot
4141 .range_to_buffer_ranges(multi_buffer_visible_range)
4142 .into_iter()
4143 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4144 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4145 let buffer_file = project::File::from_dyn(buffer.file())?;
4146 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4147 let worktree_entry = buffer_worktree
4148 .read(cx)
4149 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4150 if worktree_entry.is_ignored {
4151 return None;
4152 }
4153
4154 let language = buffer.language()?;
4155 if let Some(restrict_to_languages) = restrict_to_languages {
4156 if !restrict_to_languages.contains(language) {
4157 return None;
4158 }
4159 }
4160 Some((
4161 excerpt_id,
4162 (
4163 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4164 buffer.version().clone(),
4165 excerpt_visible_range,
4166 ),
4167 ))
4168 })
4169 .collect()
4170 }
4171
4172 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4173 TextLayoutDetails {
4174 text_system: window.text_system().clone(),
4175 editor_style: self.style.clone().unwrap(),
4176 rem_size: window.rem_size(),
4177 scroll_anchor: self.scroll_manager.anchor(),
4178 visible_rows: self.visible_line_count(),
4179 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4180 }
4181 }
4182
4183 pub fn splice_inlays(
4184 &self,
4185 to_remove: &[InlayId],
4186 to_insert: Vec<Inlay>,
4187 cx: &mut Context<Self>,
4188 ) {
4189 self.display_map.update(cx, |display_map, cx| {
4190 display_map.splice_inlays(to_remove, to_insert, cx)
4191 });
4192 cx.notify();
4193 }
4194
4195 fn trigger_on_type_formatting(
4196 &self,
4197 input: String,
4198 window: &mut Window,
4199 cx: &mut Context<Self>,
4200 ) -> Option<Task<Result<()>>> {
4201 if input.len() != 1 {
4202 return None;
4203 }
4204
4205 let project = self.project.as_ref()?;
4206 let position = self.selections.newest_anchor().head();
4207 let (buffer, buffer_position) = self
4208 .buffer
4209 .read(cx)
4210 .text_anchor_for_position(position, cx)?;
4211
4212 let settings = language_settings::language_settings(
4213 buffer
4214 .read(cx)
4215 .language_at(buffer_position)
4216 .map(|l| l.name()),
4217 buffer.read(cx).file(),
4218 cx,
4219 );
4220 if !settings.use_on_type_format {
4221 return None;
4222 }
4223
4224 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4225 // hence we do LSP request & edit on host side only — add formats to host's history.
4226 let push_to_lsp_host_history = true;
4227 // If this is not the host, append its history with new edits.
4228 let push_to_client_history = project.read(cx).is_via_collab();
4229
4230 let on_type_formatting = project.update(cx, |project, cx| {
4231 project.on_type_format(
4232 buffer.clone(),
4233 buffer_position,
4234 input,
4235 push_to_lsp_host_history,
4236 cx,
4237 )
4238 });
4239 Some(cx.spawn_in(window, async move |editor, cx| {
4240 if let Some(transaction) = on_type_formatting.await? {
4241 if push_to_client_history {
4242 buffer
4243 .update(cx, |buffer, _| {
4244 buffer.push_transaction(transaction, Instant::now());
4245 })
4246 .ok();
4247 }
4248 editor.update(cx, |editor, cx| {
4249 editor.refresh_document_highlights(cx);
4250 })?;
4251 }
4252 Ok(())
4253 }))
4254 }
4255
4256 pub fn show_word_completions(
4257 &mut self,
4258 _: &ShowWordCompletions,
4259 window: &mut Window,
4260 cx: &mut Context<Self>,
4261 ) {
4262 self.open_completions_menu(true, None, window, cx);
4263 }
4264
4265 pub fn show_completions(
4266 &mut self,
4267 options: &ShowCompletions,
4268 window: &mut Window,
4269 cx: &mut Context<Self>,
4270 ) {
4271 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4272 }
4273
4274 fn open_completions_menu(
4275 &mut self,
4276 ignore_completion_provider: bool,
4277 trigger: Option<&str>,
4278 window: &mut Window,
4279 cx: &mut Context<Self>,
4280 ) {
4281 if self.pending_rename.is_some() {
4282 return;
4283 }
4284 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4285 return;
4286 }
4287
4288 let position = self.selections.newest_anchor().head();
4289 if position.diff_base_anchor.is_some() {
4290 return;
4291 }
4292 let (buffer, buffer_position) =
4293 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4294 output
4295 } else {
4296 return;
4297 };
4298 let buffer_snapshot = buffer.read(cx).snapshot();
4299 let show_completion_documentation = buffer_snapshot
4300 .settings_at(buffer_position, cx)
4301 .show_completion_documentation;
4302
4303 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4304
4305 let trigger_kind = match trigger {
4306 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4307 CompletionTriggerKind::TRIGGER_CHARACTER
4308 }
4309 _ => CompletionTriggerKind::INVOKED,
4310 };
4311 let completion_context = CompletionContext {
4312 trigger_character: trigger.and_then(|trigger| {
4313 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4314 Some(String::from(trigger))
4315 } else {
4316 None
4317 }
4318 }),
4319 trigger_kind,
4320 };
4321
4322 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4323 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4324 let word_to_exclude = buffer_snapshot
4325 .text_for_range(old_range.clone())
4326 .collect::<String>();
4327 (
4328 buffer_snapshot.anchor_before(old_range.start)
4329 ..buffer_snapshot.anchor_after(old_range.end),
4330 Some(word_to_exclude),
4331 )
4332 } else {
4333 (buffer_position..buffer_position, None)
4334 };
4335
4336 let completion_settings = language_settings(
4337 buffer_snapshot
4338 .language_at(buffer_position)
4339 .map(|language| language.name()),
4340 buffer_snapshot.file(),
4341 cx,
4342 )
4343 .completions;
4344
4345 // The document can be large, so stay in reasonable bounds when searching for words,
4346 // otherwise completion pop-up might be slow to appear.
4347 const WORD_LOOKUP_ROWS: u32 = 5_000;
4348 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4349 let min_word_search = buffer_snapshot.clip_point(
4350 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4351 Bias::Left,
4352 );
4353 let max_word_search = buffer_snapshot.clip_point(
4354 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4355 Bias::Right,
4356 );
4357 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4358 ..buffer_snapshot.point_to_offset(max_word_search);
4359
4360 let provider = self
4361 .completion_provider
4362 .as_ref()
4363 .filter(|_| !ignore_completion_provider);
4364 let skip_digits = query
4365 .as_ref()
4366 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4367
4368 let (mut words, provided_completions) = match provider {
4369 Some(provider) => {
4370 let completions = provider.completions(
4371 position.excerpt_id,
4372 &buffer,
4373 buffer_position,
4374 completion_context,
4375 window,
4376 cx,
4377 );
4378
4379 let words = match completion_settings.words {
4380 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4381 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4382 .background_spawn(async move {
4383 buffer_snapshot.words_in_range(WordsQuery {
4384 fuzzy_contents: None,
4385 range: word_search_range,
4386 skip_digits,
4387 })
4388 }),
4389 };
4390
4391 (words, completions)
4392 }
4393 None => (
4394 cx.background_spawn(async move {
4395 buffer_snapshot.words_in_range(WordsQuery {
4396 fuzzy_contents: None,
4397 range: word_search_range,
4398 skip_digits,
4399 })
4400 }),
4401 Task::ready(Ok(None)),
4402 ),
4403 };
4404
4405 let sort_completions = provider
4406 .as_ref()
4407 .map_or(false, |provider| provider.sort_completions());
4408
4409 let filter_completions = provider
4410 .as_ref()
4411 .map_or(true, |provider| provider.filter_completions());
4412
4413 let id = post_inc(&mut self.next_completion_id);
4414 let task = cx.spawn_in(window, async move |editor, cx| {
4415 async move {
4416 editor.update(cx, |this, _| {
4417 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4418 })?;
4419
4420 let mut completions = Vec::new();
4421 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4422 completions.extend(provided_completions);
4423 if completion_settings.words == WordsCompletionMode::Fallback {
4424 words = Task::ready(BTreeMap::default());
4425 }
4426 }
4427
4428 let mut words = words.await;
4429 if let Some(word_to_exclude) = &word_to_exclude {
4430 words.remove(word_to_exclude);
4431 }
4432 for lsp_completion in &completions {
4433 words.remove(&lsp_completion.new_text);
4434 }
4435 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4436 old_range: old_range.clone(),
4437 new_text: word.clone(),
4438 label: CodeLabel::plain(word, None),
4439 icon_path: None,
4440 documentation: None,
4441 source: CompletionSource::BufferWord {
4442 word_range,
4443 resolved: false,
4444 },
4445 insert_text_mode: Some(InsertTextMode::AS_IS),
4446 confirm: None,
4447 }));
4448
4449 let menu = if completions.is_empty() {
4450 None
4451 } else {
4452 let mut menu = CompletionsMenu::new(
4453 id,
4454 sort_completions,
4455 show_completion_documentation,
4456 ignore_completion_provider,
4457 position,
4458 buffer.clone(),
4459 completions.into(),
4460 );
4461
4462 menu.filter(
4463 if filter_completions {
4464 query.as_deref()
4465 } else {
4466 None
4467 },
4468 cx.background_executor().clone(),
4469 )
4470 .await;
4471
4472 menu.visible().then_some(menu)
4473 };
4474
4475 editor.update_in(cx, |editor, window, cx| {
4476 match editor.context_menu.borrow().as_ref() {
4477 None => {}
4478 Some(CodeContextMenu::Completions(prev_menu)) => {
4479 if prev_menu.id > id {
4480 return;
4481 }
4482 }
4483 _ => return,
4484 }
4485
4486 if editor.focus_handle.is_focused(window) && menu.is_some() {
4487 let mut menu = menu.unwrap();
4488 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4489
4490 *editor.context_menu.borrow_mut() =
4491 Some(CodeContextMenu::Completions(menu));
4492
4493 if editor.show_edit_predictions_in_menu() {
4494 editor.update_visible_inline_completion(window, cx);
4495 } else {
4496 editor.discard_inline_completion(false, cx);
4497 }
4498
4499 cx.notify();
4500 } else if editor.completion_tasks.len() <= 1 {
4501 // If there are no more completion tasks and the last menu was
4502 // empty, we should hide it.
4503 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4504 // If it was already hidden and we don't show inline
4505 // completions in the menu, we should also show the
4506 // inline-completion when available.
4507 if was_hidden && editor.show_edit_predictions_in_menu() {
4508 editor.update_visible_inline_completion(window, cx);
4509 }
4510 }
4511 })?;
4512
4513 anyhow::Ok(())
4514 }
4515 .log_err()
4516 .await
4517 });
4518
4519 self.completion_tasks.push((id, task));
4520 }
4521
4522 #[cfg(feature = "test-support")]
4523 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4524 let menu = self.context_menu.borrow();
4525 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4526 let completions = menu.completions.borrow();
4527 Some(completions.to_vec())
4528 } else {
4529 None
4530 }
4531 }
4532
4533 pub fn confirm_completion(
4534 &mut self,
4535 action: &ConfirmCompletion,
4536 window: &mut Window,
4537 cx: &mut Context<Self>,
4538 ) -> Option<Task<Result<()>>> {
4539 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4540 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4541 }
4542
4543 pub fn compose_completion(
4544 &mut self,
4545 action: &ComposeCompletion,
4546 window: &mut Window,
4547 cx: &mut Context<Self>,
4548 ) -> Option<Task<Result<()>>> {
4549 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4550 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4551 }
4552
4553 fn do_completion(
4554 &mut self,
4555 item_ix: Option<usize>,
4556 intent: CompletionIntent,
4557 window: &mut Window,
4558 cx: &mut Context<Editor>,
4559 ) -> Option<Task<Result<()>>> {
4560 use language::ToOffset as _;
4561
4562 let completions_menu =
4563 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4564 menu
4565 } else {
4566 return None;
4567 };
4568
4569 let candidate_id = {
4570 let entries = completions_menu.entries.borrow();
4571 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4572 if self.show_edit_predictions_in_menu() {
4573 self.discard_inline_completion(true, cx);
4574 }
4575 mat.candidate_id
4576 };
4577
4578 let buffer_handle = completions_menu.buffer;
4579 let completion = completions_menu
4580 .completions
4581 .borrow()
4582 .get(candidate_id)?
4583 .clone();
4584 cx.stop_propagation();
4585
4586 let snippet;
4587 let new_text;
4588 if completion.is_snippet() {
4589 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4590 new_text = snippet.as_ref().unwrap().text.clone();
4591 } else {
4592 snippet = None;
4593 new_text = completion.new_text.clone();
4594 };
4595 let selections = self.selections.all::<usize>(cx);
4596 let buffer = buffer_handle.read(cx);
4597 let old_range = completion.old_range.to_offset(buffer);
4598 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4599
4600 let newest_selection = self.selections.newest_anchor();
4601 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4602 return None;
4603 }
4604
4605 let lookbehind = newest_selection
4606 .start
4607 .text_anchor
4608 .to_offset(buffer)
4609 .saturating_sub(old_range.start);
4610 let lookahead = old_range
4611 .end
4612 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4613 let mut common_prefix_len = old_text
4614 .bytes()
4615 .zip(new_text.bytes())
4616 .take_while(|(a, b)| a == b)
4617 .count();
4618
4619 let snapshot = self.buffer.read(cx).snapshot(cx);
4620 let mut range_to_replace: Option<Range<isize>> = None;
4621 let mut ranges = Vec::new();
4622 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4623 for selection in &selections {
4624 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4625 let start = selection.start.saturating_sub(lookbehind);
4626 let end = selection.end + lookahead;
4627 if selection.id == newest_selection.id {
4628 range_to_replace = Some(
4629 ((start + common_prefix_len) as isize - selection.start as isize)
4630 ..(end as isize - selection.start as isize),
4631 );
4632 }
4633 ranges.push(start + common_prefix_len..end);
4634 } else {
4635 common_prefix_len = 0;
4636 ranges.clear();
4637 ranges.extend(selections.iter().map(|s| {
4638 if s.id == newest_selection.id {
4639 range_to_replace = Some(
4640 old_range.start.to_offset_utf16(&snapshot).0 as isize
4641 - selection.start as isize
4642 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4643 - selection.start as isize,
4644 );
4645 old_range.clone()
4646 } else {
4647 s.start..s.end
4648 }
4649 }));
4650 break;
4651 }
4652 if !self.linked_edit_ranges.is_empty() {
4653 let start_anchor = snapshot.anchor_before(selection.head());
4654 let end_anchor = snapshot.anchor_after(selection.tail());
4655 if let Some(ranges) = self
4656 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4657 {
4658 for (buffer, edits) in ranges {
4659 linked_edits.entry(buffer.clone()).or_default().extend(
4660 edits
4661 .into_iter()
4662 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4663 );
4664 }
4665 }
4666 }
4667 }
4668 let text = &new_text[common_prefix_len..];
4669
4670 cx.emit(EditorEvent::InputHandled {
4671 utf16_range_to_replace: range_to_replace,
4672 text: text.into(),
4673 });
4674
4675 self.transact(window, cx, |this, window, cx| {
4676 if let Some(mut snippet) = snippet {
4677 snippet.text = text.to_string();
4678 for tabstop in snippet
4679 .tabstops
4680 .iter_mut()
4681 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4682 {
4683 tabstop.start -= common_prefix_len as isize;
4684 tabstop.end -= common_prefix_len as isize;
4685 }
4686
4687 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4688 } else {
4689 this.buffer.update(cx, |buffer, cx| {
4690 let edits = ranges.iter().map(|range| (range.clone(), text));
4691 let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
4692 {
4693 None
4694 } else {
4695 this.autoindent_mode.clone()
4696 };
4697 buffer.edit(edits, auto_indent, cx);
4698 });
4699 }
4700 for (buffer, edits) in linked_edits {
4701 buffer.update(cx, |buffer, cx| {
4702 let snapshot = buffer.snapshot();
4703 let edits = edits
4704 .into_iter()
4705 .map(|(range, text)| {
4706 use text::ToPoint as TP;
4707 let end_point = TP::to_point(&range.end, &snapshot);
4708 let start_point = TP::to_point(&range.start, &snapshot);
4709 (start_point..end_point, text)
4710 })
4711 .sorted_by_key(|(range, _)| range.start);
4712 buffer.edit(edits, None, cx);
4713 })
4714 }
4715
4716 this.refresh_inline_completion(true, false, window, cx);
4717 });
4718
4719 let show_new_completions_on_confirm = completion
4720 .confirm
4721 .as_ref()
4722 .map_or(false, |confirm| confirm(intent, window, cx));
4723 if show_new_completions_on_confirm {
4724 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4725 }
4726
4727 let provider = self.completion_provider.as_ref()?;
4728 drop(completion);
4729 let apply_edits = provider.apply_additional_edits_for_completion(
4730 buffer_handle,
4731 completions_menu.completions.clone(),
4732 candidate_id,
4733 true,
4734 cx,
4735 );
4736
4737 let editor_settings = EditorSettings::get_global(cx);
4738 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4739 // After the code completion is finished, users often want to know what signatures are needed.
4740 // so we should automatically call signature_help
4741 self.show_signature_help(&ShowSignatureHelp, window, cx);
4742 }
4743
4744 Some(cx.foreground_executor().spawn(async move {
4745 apply_edits.await?;
4746 Ok(())
4747 }))
4748 }
4749
4750 pub fn toggle_code_actions(
4751 &mut self,
4752 action: &ToggleCodeActions,
4753 window: &mut Window,
4754 cx: &mut Context<Self>,
4755 ) {
4756 let mut context_menu = self.context_menu.borrow_mut();
4757 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4758 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4759 // Toggle if we're selecting the same one
4760 *context_menu = None;
4761 cx.notify();
4762 return;
4763 } else {
4764 // Otherwise, clear it and start a new one
4765 *context_menu = None;
4766 cx.notify();
4767 }
4768 }
4769 drop(context_menu);
4770 let snapshot = self.snapshot(window, cx);
4771 let deployed_from_indicator = action.deployed_from_indicator;
4772 let mut task = self.code_actions_task.take();
4773 let action = action.clone();
4774 cx.spawn_in(window, async move |editor, cx| {
4775 while let Some(prev_task) = task {
4776 prev_task.await.log_err();
4777 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4778 }
4779
4780 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4781 if editor.focus_handle.is_focused(window) {
4782 let multibuffer_point = action
4783 .deployed_from_indicator
4784 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4785 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4786 let (buffer, buffer_row) = snapshot
4787 .buffer_snapshot
4788 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4789 .and_then(|(buffer_snapshot, range)| {
4790 editor
4791 .buffer
4792 .read(cx)
4793 .buffer(buffer_snapshot.remote_id())
4794 .map(|buffer| (buffer, range.start.row))
4795 })?;
4796 let (_, code_actions) = editor
4797 .available_code_actions
4798 .clone()
4799 .and_then(|(location, code_actions)| {
4800 let snapshot = location.buffer.read(cx).snapshot();
4801 let point_range = location.range.to_point(&snapshot);
4802 let point_range = point_range.start.row..=point_range.end.row;
4803 if point_range.contains(&buffer_row) {
4804 Some((location, code_actions))
4805 } else {
4806 None
4807 }
4808 })
4809 .unzip();
4810 let buffer_id = buffer.read(cx).remote_id();
4811 let tasks = editor
4812 .tasks
4813 .get(&(buffer_id, buffer_row))
4814 .map(|t| Arc::new(t.to_owned()));
4815 if tasks.is_none() && code_actions.is_none() {
4816 return None;
4817 }
4818
4819 editor.completion_tasks.clear();
4820 editor.discard_inline_completion(false, cx);
4821 let task_context =
4822 tasks
4823 .as_ref()
4824 .zip(editor.project.clone())
4825 .map(|(tasks, project)| {
4826 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4827 });
4828
4829 let debugger_flag = cx.has_flag::<Debugger>();
4830
4831 Some(cx.spawn_in(window, async move |editor, cx| {
4832 let task_context = match task_context {
4833 Some(task_context) => task_context.await,
4834 None => None,
4835 };
4836 let resolved_tasks =
4837 tasks.zip(task_context).map(|(tasks, task_context)| {
4838 Rc::new(ResolvedTasks {
4839 templates: tasks.resolve(&task_context).collect(),
4840 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4841 multibuffer_point.row,
4842 tasks.column,
4843 )),
4844 })
4845 });
4846 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
4847 tasks
4848 .templates
4849 .iter()
4850 .filter(|task| {
4851 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4852 debugger_flag
4853 } else {
4854 true
4855 }
4856 })
4857 .count()
4858 == 1
4859 }) && code_actions
4860 .as_ref()
4861 .map_or(true, |actions| actions.is_empty());
4862 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4863 *editor.context_menu.borrow_mut() =
4864 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4865 buffer,
4866 actions: CodeActionContents {
4867 tasks: resolved_tasks,
4868 actions: code_actions,
4869 },
4870 selected_item: Default::default(),
4871 scroll_handle: UniformListScrollHandle::default(),
4872 deployed_from_indicator,
4873 }));
4874 if spawn_straight_away {
4875 if let Some(task) = editor.confirm_code_action(
4876 &ConfirmCodeAction { item_ix: Some(0) },
4877 window,
4878 cx,
4879 ) {
4880 cx.notify();
4881 return task;
4882 }
4883 }
4884 cx.notify();
4885 Task::ready(Ok(()))
4886 }) {
4887 task.await
4888 } else {
4889 Ok(())
4890 }
4891 }))
4892 } else {
4893 Some(Task::ready(Ok(())))
4894 }
4895 })?;
4896 if let Some(task) = spawned_test_task {
4897 task.await?;
4898 }
4899
4900 Ok::<_, anyhow::Error>(())
4901 })
4902 .detach_and_log_err(cx);
4903 }
4904
4905 pub fn confirm_code_action(
4906 &mut self,
4907 action: &ConfirmCodeAction,
4908 window: &mut Window,
4909 cx: &mut Context<Self>,
4910 ) -> Option<Task<Result<()>>> {
4911 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4912
4913 let actions_menu =
4914 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4915 menu
4916 } else {
4917 return None;
4918 };
4919
4920 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4921 let action = actions_menu.actions.get(action_ix)?;
4922 let title = action.label();
4923 let buffer = actions_menu.buffer;
4924 let workspace = self.workspace()?;
4925
4926 match action {
4927 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4928 match resolved_task.task_type() {
4929 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
4930 workspace::tasks::schedule_resolved_task(
4931 workspace,
4932 task_source_kind,
4933 resolved_task,
4934 false,
4935 cx,
4936 );
4937
4938 Some(Task::ready(Ok(())))
4939 }),
4940 task::TaskType::Debug(debug_args) => {
4941 if debug_args.locator.is_some() {
4942 workspace.update(cx, |workspace, cx| {
4943 workspace::tasks::schedule_resolved_task(
4944 workspace,
4945 task_source_kind,
4946 resolved_task,
4947 false,
4948 cx,
4949 );
4950 });
4951
4952 return Some(Task::ready(Ok(())));
4953 }
4954
4955 if let Some(project) = self.project.as_ref() {
4956 project
4957 .update(cx, |project, cx| {
4958 project.start_debug_session(
4959 resolved_task.resolved_debug_adapter_config().unwrap(),
4960 cx,
4961 )
4962 })
4963 .detach_and_log_err(cx);
4964 Some(Task::ready(Ok(())))
4965 } else {
4966 Some(Task::ready(Ok(())))
4967 }
4968 }
4969 }
4970 }
4971 CodeActionsItem::CodeAction {
4972 excerpt_id,
4973 action,
4974 provider,
4975 } => {
4976 let apply_code_action =
4977 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4978 let workspace = workspace.downgrade();
4979 Some(cx.spawn_in(window, async move |editor, cx| {
4980 let project_transaction = apply_code_action.await?;
4981 Self::open_project_transaction(
4982 &editor,
4983 workspace,
4984 project_transaction,
4985 title,
4986 cx,
4987 )
4988 .await
4989 }))
4990 }
4991 }
4992 }
4993
4994 pub async fn open_project_transaction(
4995 this: &WeakEntity<Editor>,
4996 workspace: WeakEntity<Workspace>,
4997 transaction: ProjectTransaction,
4998 title: String,
4999 cx: &mut AsyncWindowContext,
5000 ) -> Result<()> {
5001 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5002 cx.update(|_, cx| {
5003 entries.sort_unstable_by_key(|(buffer, _)| {
5004 buffer.read(cx).file().map(|f| f.path().clone())
5005 });
5006 })?;
5007
5008 // If the project transaction's edits are all contained within this editor, then
5009 // avoid opening a new editor to display them.
5010
5011 if let Some((buffer, transaction)) = entries.first() {
5012 if entries.len() == 1 {
5013 let excerpt = this.update(cx, |editor, cx| {
5014 editor
5015 .buffer()
5016 .read(cx)
5017 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5018 })?;
5019 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5020 if excerpted_buffer == *buffer {
5021 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5022 let excerpt_range = excerpt_range.to_offset(buffer);
5023 buffer
5024 .edited_ranges_for_transaction::<usize>(transaction)
5025 .all(|range| {
5026 excerpt_range.start <= range.start
5027 && excerpt_range.end >= range.end
5028 })
5029 })?;
5030
5031 if all_edits_within_excerpt {
5032 return Ok(());
5033 }
5034 }
5035 }
5036 }
5037 } else {
5038 return Ok(());
5039 }
5040
5041 let mut ranges_to_highlight = Vec::new();
5042 let excerpt_buffer = cx.new(|cx| {
5043 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5044 for (buffer_handle, transaction) in &entries {
5045 let edited_ranges = buffer_handle
5046 .read(cx)
5047 .edited_ranges_for_transaction::<Point>(transaction)
5048 .collect::<Vec<_>>();
5049 let (ranges, _) = multibuffer.set_excerpts_for_path(
5050 PathKey::for_buffer(buffer_handle, cx),
5051 buffer_handle.clone(),
5052 edited_ranges,
5053 DEFAULT_MULTIBUFFER_CONTEXT,
5054 cx,
5055 );
5056
5057 ranges_to_highlight.extend(ranges);
5058 }
5059 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5060 multibuffer
5061 })?;
5062
5063 workspace.update_in(cx, |workspace, window, cx| {
5064 let project = workspace.project().clone();
5065 let editor =
5066 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5067 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5068 editor.update(cx, |editor, cx| {
5069 editor.highlight_background::<Self>(
5070 &ranges_to_highlight,
5071 |theme| theme.editor_highlighted_line_background,
5072 cx,
5073 );
5074 });
5075 })?;
5076
5077 Ok(())
5078 }
5079
5080 pub fn clear_code_action_providers(&mut self) {
5081 self.code_action_providers.clear();
5082 self.available_code_actions.take();
5083 }
5084
5085 pub fn add_code_action_provider(
5086 &mut self,
5087 provider: Rc<dyn CodeActionProvider>,
5088 window: &mut Window,
5089 cx: &mut Context<Self>,
5090 ) {
5091 if self
5092 .code_action_providers
5093 .iter()
5094 .any(|existing_provider| existing_provider.id() == provider.id())
5095 {
5096 return;
5097 }
5098
5099 self.code_action_providers.push(provider);
5100 self.refresh_code_actions(window, cx);
5101 }
5102
5103 pub fn remove_code_action_provider(
5104 &mut self,
5105 id: Arc<str>,
5106 window: &mut Window,
5107 cx: &mut Context<Self>,
5108 ) {
5109 self.code_action_providers
5110 .retain(|provider| provider.id() != id);
5111 self.refresh_code_actions(window, cx);
5112 }
5113
5114 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5115 let buffer = self.buffer.read(cx);
5116 let newest_selection = self.selections.newest_anchor().clone();
5117 if newest_selection.head().diff_base_anchor.is_some() {
5118 return None;
5119 }
5120 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5121 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5122 if start_buffer != end_buffer {
5123 return None;
5124 }
5125
5126 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5127 cx.background_executor()
5128 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5129 .await;
5130
5131 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5132 let providers = this.code_action_providers.clone();
5133 let tasks = this
5134 .code_action_providers
5135 .iter()
5136 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5137 .collect::<Vec<_>>();
5138 (providers, tasks)
5139 })?;
5140
5141 let mut actions = Vec::new();
5142 for (provider, provider_actions) in
5143 providers.into_iter().zip(future::join_all(tasks).await)
5144 {
5145 if let Some(provider_actions) = provider_actions.log_err() {
5146 actions.extend(provider_actions.into_iter().map(|action| {
5147 AvailableCodeAction {
5148 excerpt_id: newest_selection.start.excerpt_id,
5149 action,
5150 provider: provider.clone(),
5151 }
5152 }));
5153 }
5154 }
5155
5156 this.update(cx, |this, cx| {
5157 this.available_code_actions = if actions.is_empty() {
5158 None
5159 } else {
5160 Some((
5161 Location {
5162 buffer: start_buffer,
5163 range: start..end,
5164 },
5165 actions.into(),
5166 ))
5167 };
5168 cx.notify();
5169 })
5170 }));
5171 None
5172 }
5173
5174 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5175 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5176 self.show_git_blame_inline = false;
5177
5178 self.show_git_blame_inline_delay_task =
5179 Some(cx.spawn_in(window, async move |this, cx| {
5180 cx.background_executor().timer(delay).await;
5181
5182 this.update(cx, |this, cx| {
5183 this.show_git_blame_inline = true;
5184 cx.notify();
5185 })
5186 .log_err();
5187 }));
5188 }
5189 }
5190
5191 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5192 if self.pending_rename.is_some() {
5193 return None;
5194 }
5195
5196 let provider = self.semantics_provider.clone()?;
5197 let buffer = self.buffer.read(cx);
5198 let newest_selection = self.selections.newest_anchor().clone();
5199 let cursor_position = newest_selection.head();
5200 let (cursor_buffer, cursor_buffer_position) =
5201 buffer.text_anchor_for_position(cursor_position, cx)?;
5202 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5203 if cursor_buffer != tail_buffer {
5204 return None;
5205 }
5206 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5207 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5208 cx.background_executor()
5209 .timer(Duration::from_millis(debounce))
5210 .await;
5211
5212 let highlights = if let Some(highlights) = cx
5213 .update(|cx| {
5214 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5215 })
5216 .ok()
5217 .flatten()
5218 {
5219 highlights.await.log_err()
5220 } else {
5221 None
5222 };
5223
5224 if let Some(highlights) = highlights {
5225 this.update(cx, |this, cx| {
5226 if this.pending_rename.is_some() {
5227 return;
5228 }
5229
5230 let buffer_id = cursor_position.buffer_id;
5231 let buffer = this.buffer.read(cx);
5232 if !buffer
5233 .text_anchor_for_position(cursor_position, cx)
5234 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5235 {
5236 return;
5237 }
5238
5239 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5240 let mut write_ranges = Vec::new();
5241 let mut read_ranges = Vec::new();
5242 for highlight in highlights {
5243 for (excerpt_id, excerpt_range) in
5244 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5245 {
5246 let start = highlight
5247 .range
5248 .start
5249 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5250 let end = highlight
5251 .range
5252 .end
5253 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5254 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5255 continue;
5256 }
5257
5258 let range = Anchor {
5259 buffer_id,
5260 excerpt_id,
5261 text_anchor: start,
5262 diff_base_anchor: None,
5263 }..Anchor {
5264 buffer_id,
5265 excerpt_id,
5266 text_anchor: end,
5267 diff_base_anchor: None,
5268 };
5269 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5270 write_ranges.push(range);
5271 } else {
5272 read_ranges.push(range);
5273 }
5274 }
5275 }
5276
5277 this.highlight_background::<DocumentHighlightRead>(
5278 &read_ranges,
5279 |theme| theme.editor_document_highlight_read_background,
5280 cx,
5281 );
5282 this.highlight_background::<DocumentHighlightWrite>(
5283 &write_ranges,
5284 |theme| theme.editor_document_highlight_write_background,
5285 cx,
5286 );
5287 cx.notify();
5288 })
5289 .log_err();
5290 }
5291 }));
5292 None
5293 }
5294
5295 pub fn refresh_selected_text_highlights(
5296 &mut self,
5297 window: &mut Window,
5298 cx: &mut Context<Editor>,
5299 ) {
5300 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5301 return;
5302 }
5303 self.selection_highlight_task.take();
5304 if !EditorSettings::get_global(cx).selection_highlight {
5305 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5306 return;
5307 }
5308 if self.selections.count() != 1 || self.selections.line_mode {
5309 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5310 return;
5311 }
5312 let selection = self.selections.newest::<Point>(cx);
5313 if selection.is_empty() || selection.start.row != selection.end.row {
5314 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5315 return;
5316 }
5317 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5318 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5319 cx.background_executor()
5320 .timer(Duration::from_millis(debounce))
5321 .await;
5322 let Some(Some(matches_task)) = editor
5323 .update_in(cx, |editor, _, cx| {
5324 if editor.selections.count() != 1 || editor.selections.line_mode {
5325 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5326 return None;
5327 }
5328 let selection = editor.selections.newest::<Point>(cx);
5329 if selection.is_empty() || selection.start.row != selection.end.row {
5330 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5331 return None;
5332 }
5333 let buffer = editor.buffer().read(cx).snapshot(cx);
5334 let query = buffer.text_for_range(selection.range()).collect::<String>();
5335 if query.trim().is_empty() {
5336 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5337 return None;
5338 }
5339 Some(cx.background_spawn(async move {
5340 let mut ranges = Vec::new();
5341 let selection_anchors = selection.range().to_anchors(&buffer);
5342 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5343 for (search_buffer, search_range, excerpt_id) in
5344 buffer.range_to_buffer_ranges(range)
5345 {
5346 ranges.extend(
5347 project::search::SearchQuery::text(
5348 query.clone(),
5349 false,
5350 false,
5351 false,
5352 Default::default(),
5353 Default::default(),
5354 None,
5355 )
5356 .unwrap()
5357 .search(search_buffer, Some(search_range.clone()))
5358 .await
5359 .into_iter()
5360 .filter_map(
5361 |match_range| {
5362 let start = search_buffer.anchor_after(
5363 search_range.start + match_range.start,
5364 );
5365 let end = search_buffer.anchor_before(
5366 search_range.start + match_range.end,
5367 );
5368 let range = Anchor::range_in_buffer(
5369 excerpt_id,
5370 search_buffer.remote_id(),
5371 start..end,
5372 );
5373 (range != selection_anchors).then_some(range)
5374 },
5375 ),
5376 );
5377 }
5378 }
5379 ranges
5380 }))
5381 })
5382 .log_err()
5383 else {
5384 return;
5385 };
5386 let matches = matches_task.await;
5387 editor
5388 .update_in(cx, |editor, _, cx| {
5389 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5390 if !matches.is_empty() {
5391 editor.highlight_background::<SelectedTextHighlight>(
5392 &matches,
5393 |theme| theme.editor_document_highlight_bracket_background,
5394 cx,
5395 )
5396 }
5397 })
5398 .log_err();
5399 }));
5400 }
5401
5402 pub fn refresh_inline_completion(
5403 &mut self,
5404 debounce: bool,
5405 user_requested: bool,
5406 window: &mut Window,
5407 cx: &mut Context<Self>,
5408 ) -> Option<()> {
5409 let provider = self.edit_prediction_provider()?;
5410 let cursor = self.selections.newest_anchor().head();
5411 let (buffer, cursor_buffer_position) =
5412 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5413
5414 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5415 self.discard_inline_completion(false, cx);
5416 return None;
5417 }
5418
5419 if !user_requested
5420 && (!self.should_show_edit_predictions()
5421 || !self.is_focused(window)
5422 || buffer.read(cx).is_empty())
5423 {
5424 self.discard_inline_completion(false, cx);
5425 return None;
5426 }
5427
5428 self.update_visible_inline_completion(window, cx);
5429 provider.refresh(
5430 self.project.clone(),
5431 buffer,
5432 cursor_buffer_position,
5433 debounce,
5434 cx,
5435 );
5436 Some(())
5437 }
5438
5439 fn show_edit_predictions_in_menu(&self) -> bool {
5440 match self.edit_prediction_settings {
5441 EditPredictionSettings::Disabled => false,
5442 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5443 }
5444 }
5445
5446 pub fn edit_predictions_enabled(&self) -> bool {
5447 match self.edit_prediction_settings {
5448 EditPredictionSettings::Disabled => false,
5449 EditPredictionSettings::Enabled { .. } => true,
5450 }
5451 }
5452
5453 fn edit_prediction_requires_modifier(&self) -> bool {
5454 match self.edit_prediction_settings {
5455 EditPredictionSettings::Disabled => false,
5456 EditPredictionSettings::Enabled {
5457 preview_requires_modifier,
5458 ..
5459 } => preview_requires_modifier,
5460 }
5461 }
5462
5463 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5464 if self.edit_prediction_provider.is_none() {
5465 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5466 } else {
5467 let selection = self.selections.newest_anchor();
5468 let cursor = selection.head();
5469
5470 if let Some((buffer, cursor_buffer_position)) =
5471 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5472 {
5473 self.edit_prediction_settings =
5474 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5475 }
5476 }
5477 }
5478
5479 fn edit_prediction_settings_at_position(
5480 &self,
5481 buffer: &Entity<Buffer>,
5482 buffer_position: language::Anchor,
5483 cx: &App,
5484 ) -> EditPredictionSettings {
5485 if self.mode != EditorMode::Full
5486 || !self.show_inline_completions_override.unwrap_or(true)
5487 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5488 {
5489 return EditPredictionSettings::Disabled;
5490 }
5491
5492 let buffer = buffer.read(cx);
5493
5494 let file = buffer.file();
5495
5496 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5497 return EditPredictionSettings::Disabled;
5498 };
5499
5500 let by_provider = matches!(
5501 self.menu_inline_completions_policy,
5502 MenuInlineCompletionsPolicy::ByProvider
5503 );
5504
5505 let show_in_menu = by_provider
5506 && self
5507 .edit_prediction_provider
5508 .as_ref()
5509 .map_or(false, |provider| {
5510 provider.provider.show_completions_in_menu()
5511 });
5512
5513 let preview_requires_modifier =
5514 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5515
5516 EditPredictionSettings::Enabled {
5517 show_in_menu,
5518 preview_requires_modifier,
5519 }
5520 }
5521
5522 fn should_show_edit_predictions(&self) -> bool {
5523 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5524 }
5525
5526 pub fn edit_prediction_preview_is_active(&self) -> bool {
5527 matches!(
5528 self.edit_prediction_preview,
5529 EditPredictionPreview::Active { .. }
5530 )
5531 }
5532
5533 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5534 let cursor = self.selections.newest_anchor().head();
5535 if let Some((buffer, cursor_position)) =
5536 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5537 {
5538 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5539 } else {
5540 false
5541 }
5542 }
5543
5544 fn edit_predictions_enabled_in_buffer(
5545 &self,
5546 buffer: &Entity<Buffer>,
5547 buffer_position: language::Anchor,
5548 cx: &App,
5549 ) -> bool {
5550 maybe!({
5551 if self.read_only(cx) {
5552 return Some(false);
5553 }
5554 let provider = self.edit_prediction_provider()?;
5555 if !provider.is_enabled(&buffer, buffer_position, cx) {
5556 return Some(false);
5557 }
5558 let buffer = buffer.read(cx);
5559 let Some(file) = buffer.file() else {
5560 return Some(true);
5561 };
5562 let settings = all_language_settings(Some(file), cx);
5563 Some(settings.edit_predictions_enabled_for_file(file, cx))
5564 })
5565 .unwrap_or(false)
5566 }
5567
5568 fn cycle_inline_completion(
5569 &mut self,
5570 direction: Direction,
5571 window: &mut Window,
5572 cx: &mut Context<Self>,
5573 ) -> Option<()> {
5574 let provider = self.edit_prediction_provider()?;
5575 let cursor = self.selections.newest_anchor().head();
5576 let (buffer, cursor_buffer_position) =
5577 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5578 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5579 return None;
5580 }
5581
5582 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5583 self.update_visible_inline_completion(window, cx);
5584
5585 Some(())
5586 }
5587
5588 pub fn show_inline_completion(
5589 &mut self,
5590 _: &ShowEditPrediction,
5591 window: &mut Window,
5592 cx: &mut Context<Self>,
5593 ) {
5594 if !self.has_active_inline_completion() {
5595 self.refresh_inline_completion(false, true, window, cx);
5596 return;
5597 }
5598
5599 self.update_visible_inline_completion(window, cx);
5600 }
5601
5602 pub fn display_cursor_names(
5603 &mut self,
5604 _: &DisplayCursorNames,
5605 window: &mut Window,
5606 cx: &mut Context<Self>,
5607 ) {
5608 self.show_cursor_names(window, cx);
5609 }
5610
5611 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5612 self.show_cursor_names = true;
5613 cx.notify();
5614 cx.spawn_in(window, async move |this, cx| {
5615 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5616 this.update(cx, |this, cx| {
5617 this.show_cursor_names = false;
5618 cx.notify()
5619 })
5620 .ok()
5621 })
5622 .detach();
5623 }
5624
5625 pub fn next_edit_prediction(
5626 &mut self,
5627 _: &NextEditPrediction,
5628 window: &mut Window,
5629 cx: &mut Context<Self>,
5630 ) {
5631 if self.has_active_inline_completion() {
5632 self.cycle_inline_completion(Direction::Next, window, cx);
5633 } else {
5634 let is_copilot_disabled = self
5635 .refresh_inline_completion(false, true, window, cx)
5636 .is_none();
5637 if is_copilot_disabled {
5638 cx.propagate();
5639 }
5640 }
5641 }
5642
5643 pub fn previous_edit_prediction(
5644 &mut self,
5645 _: &PreviousEditPrediction,
5646 window: &mut Window,
5647 cx: &mut Context<Self>,
5648 ) {
5649 if self.has_active_inline_completion() {
5650 self.cycle_inline_completion(Direction::Prev, window, cx);
5651 } else {
5652 let is_copilot_disabled = self
5653 .refresh_inline_completion(false, true, window, cx)
5654 .is_none();
5655 if is_copilot_disabled {
5656 cx.propagate();
5657 }
5658 }
5659 }
5660
5661 pub fn accept_edit_prediction(
5662 &mut self,
5663 _: &AcceptEditPrediction,
5664 window: &mut Window,
5665 cx: &mut Context<Self>,
5666 ) {
5667 if self.show_edit_predictions_in_menu() {
5668 self.hide_context_menu(window, cx);
5669 }
5670
5671 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5672 return;
5673 };
5674
5675 self.report_inline_completion_event(
5676 active_inline_completion.completion_id.clone(),
5677 true,
5678 cx,
5679 );
5680
5681 match &active_inline_completion.completion {
5682 InlineCompletion::Move { target, .. } => {
5683 let target = *target;
5684
5685 if let Some(position_map) = &self.last_position_map {
5686 if position_map
5687 .visible_row_range
5688 .contains(&target.to_display_point(&position_map.snapshot).row())
5689 || !self.edit_prediction_requires_modifier()
5690 {
5691 self.unfold_ranges(&[target..target], true, false, cx);
5692 // Note that this is also done in vim's handler of the Tab action.
5693 self.change_selections(
5694 Some(Autoscroll::newest()),
5695 window,
5696 cx,
5697 |selections| {
5698 selections.select_anchor_ranges([target..target]);
5699 },
5700 );
5701 self.clear_row_highlights::<EditPredictionPreview>();
5702
5703 self.edit_prediction_preview
5704 .set_previous_scroll_position(None);
5705 } else {
5706 self.edit_prediction_preview
5707 .set_previous_scroll_position(Some(
5708 position_map.snapshot.scroll_anchor,
5709 ));
5710
5711 self.highlight_rows::<EditPredictionPreview>(
5712 target..target,
5713 cx.theme().colors().editor_highlighted_line_background,
5714 true,
5715 cx,
5716 );
5717 self.request_autoscroll(Autoscroll::fit(), cx);
5718 }
5719 }
5720 }
5721 InlineCompletion::Edit { edits, .. } => {
5722 if let Some(provider) = self.edit_prediction_provider() {
5723 provider.accept(cx);
5724 }
5725
5726 let snapshot = self.buffer.read(cx).snapshot(cx);
5727 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5728
5729 self.buffer.update(cx, |buffer, cx| {
5730 buffer.edit(edits.iter().cloned(), None, cx)
5731 });
5732
5733 self.change_selections(None, window, cx, |s| {
5734 s.select_anchor_ranges([last_edit_end..last_edit_end])
5735 });
5736
5737 self.update_visible_inline_completion(window, cx);
5738 if self.active_inline_completion.is_none() {
5739 self.refresh_inline_completion(true, true, window, cx);
5740 }
5741
5742 cx.notify();
5743 }
5744 }
5745
5746 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5747 }
5748
5749 pub fn accept_partial_inline_completion(
5750 &mut self,
5751 _: &AcceptPartialEditPrediction,
5752 window: &mut Window,
5753 cx: &mut Context<Self>,
5754 ) {
5755 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5756 return;
5757 };
5758 if self.selections.count() != 1 {
5759 return;
5760 }
5761
5762 self.report_inline_completion_event(
5763 active_inline_completion.completion_id.clone(),
5764 true,
5765 cx,
5766 );
5767
5768 match &active_inline_completion.completion {
5769 InlineCompletion::Move { target, .. } => {
5770 let target = *target;
5771 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5772 selections.select_anchor_ranges([target..target]);
5773 });
5774 }
5775 InlineCompletion::Edit { edits, .. } => {
5776 // Find an insertion that starts at the cursor position.
5777 let snapshot = self.buffer.read(cx).snapshot(cx);
5778 let cursor_offset = self.selections.newest::<usize>(cx).head();
5779 let insertion = edits.iter().find_map(|(range, text)| {
5780 let range = range.to_offset(&snapshot);
5781 if range.is_empty() && range.start == cursor_offset {
5782 Some(text)
5783 } else {
5784 None
5785 }
5786 });
5787
5788 if let Some(text) = insertion {
5789 let mut partial_completion = text
5790 .chars()
5791 .by_ref()
5792 .take_while(|c| c.is_alphabetic())
5793 .collect::<String>();
5794 if partial_completion.is_empty() {
5795 partial_completion = text
5796 .chars()
5797 .by_ref()
5798 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5799 .collect::<String>();
5800 }
5801
5802 cx.emit(EditorEvent::InputHandled {
5803 utf16_range_to_replace: None,
5804 text: partial_completion.clone().into(),
5805 });
5806
5807 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5808
5809 self.refresh_inline_completion(true, true, window, cx);
5810 cx.notify();
5811 } else {
5812 self.accept_edit_prediction(&Default::default(), window, cx);
5813 }
5814 }
5815 }
5816 }
5817
5818 fn discard_inline_completion(
5819 &mut self,
5820 should_report_inline_completion_event: bool,
5821 cx: &mut Context<Self>,
5822 ) -> bool {
5823 if should_report_inline_completion_event {
5824 let completion_id = self
5825 .active_inline_completion
5826 .as_ref()
5827 .and_then(|active_completion| active_completion.completion_id.clone());
5828
5829 self.report_inline_completion_event(completion_id, false, cx);
5830 }
5831
5832 if let Some(provider) = self.edit_prediction_provider() {
5833 provider.discard(cx);
5834 }
5835
5836 self.take_active_inline_completion(cx)
5837 }
5838
5839 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5840 let Some(provider) = self.edit_prediction_provider() else {
5841 return;
5842 };
5843
5844 let Some((_, buffer, _)) = self
5845 .buffer
5846 .read(cx)
5847 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5848 else {
5849 return;
5850 };
5851
5852 let extension = buffer
5853 .read(cx)
5854 .file()
5855 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5856
5857 let event_type = match accepted {
5858 true => "Edit Prediction Accepted",
5859 false => "Edit Prediction Discarded",
5860 };
5861 telemetry::event!(
5862 event_type,
5863 provider = provider.name(),
5864 prediction_id = id,
5865 suggestion_accepted = accepted,
5866 file_extension = extension,
5867 );
5868 }
5869
5870 pub fn has_active_inline_completion(&self) -> bool {
5871 self.active_inline_completion.is_some()
5872 }
5873
5874 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5875 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5876 return false;
5877 };
5878
5879 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5880 self.clear_highlights::<InlineCompletionHighlight>(cx);
5881 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5882 true
5883 }
5884
5885 /// Returns true when we're displaying the edit prediction popover below the cursor
5886 /// like we are not previewing and the LSP autocomplete menu is visible
5887 /// or we are in `when_holding_modifier` mode.
5888 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5889 if self.edit_prediction_preview_is_active()
5890 || !self.show_edit_predictions_in_menu()
5891 || !self.edit_predictions_enabled()
5892 {
5893 return false;
5894 }
5895
5896 if self.has_visible_completions_menu() {
5897 return true;
5898 }
5899
5900 has_completion && self.edit_prediction_requires_modifier()
5901 }
5902
5903 fn handle_modifiers_changed(
5904 &mut self,
5905 modifiers: Modifiers,
5906 position_map: &PositionMap,
5907 window: &mut Window,
5908 cx: &mut Context<Self>,
5909 ) {
5910 if self.show_edit_predictions_in_menu() {
5911 self.update_edit_prediction_preview(&modifiers, window, cx);
5912 }
5913
5914 self.update_selection_mode(&modifiers, position_map, window, cx);
5915
5916 let mouse_position = window.mouse_position();
5917 if !position_map.text_hitbox.is_hovered(window) {
5918 return;
5919 }
5920
5921 self.update_hovered_link(
5922 position_map.point_for_position(mouse_position),
5923 &position_map.snapshot,
5924 modifiers,
5925 window,
5926 cx,
5927 )
5928 }
5929
5930 fn update_selection_mode(
5931 &mut self,
5932 modifiers: &Modifiers,
5933 position_map: &PositionMap,
5934 window: &mut Window,
5935 cx: &mut Context<Self>,
5936 ) {
5937 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5938 return;
5939 }
5940
5941 let mouse_position = window.mouse_position();
5942 let point_for_position = position_map.point_for_position(mouse_position);
5943 let position = point_for_position.previous_valid;
5944
5945 self.select(
5946 SelectPhase::BeginColumnar {
5947 position,
5948 reset: false,
5949 goal_column: point_for_position.exact_unclipped.column(),
5950 },
5951 window,
5952 cx,
5953 );
5954 }
5955
5956 fn update_edit_prediction_preview(
5957 &mut self,
5958 modifiers: &Modifiers,
5959 window: &mut Window,
5960 cx: &mut Context<Self>,
5961 ) {
5962 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5963 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5964 return;
5965 };
5966
5967 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5968 if matches!(
5969 self.edit_prediction_preview,
5970 EditPredictionPreview::Inactive { .. }
5971 ) {
5972 self.edit_prediction_preview = EditPredictionPreview::Active {
5973 previous_scroll_position: None,
5974 since: Instant::now(),
5975 };
5976
5977 self.update_visible_inline_completion(window, cx);
5978 cx.notify();
5979 }
5980 } else if let EditPredictionPreview::Active {
5981 previous_scroll_position,
5982 since,
5983 } = self.edit_prediction_preview
5984 {
5985 if let (Some(previous_scroll_position), Some(position_map)) =
5986 (previous_scroll_position, self.last_position_map.as_ref())
5987 {
5988 self.set_scroll_position(
5989 previous_scroll_position
5990 .scroll_position(&position_map.snapshot.display_snapshot),
5991 window,
5992 cx,
5993 );
5994 }
5995
5996 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5997 released_too_fast: since.elapsed() < Duration::from_millis(200),
5998 };
5999 self.clear_row_highlights::<EditPredictionPreview>();
6000 self.update_visible_inline_completion(window, cx);
6001 cx.notify();
6002 }
6003 }
6004
6005 fn update_visible_inline_completion(
6006 &mut self,
6007 _window: &mut Window,
6008 cx: &mut Context<Self>,
6009 ) -> Option<()> {
6010 let selection = self.selections.newest_anchor();
6011 let cursor = selection.head();
6012 let multibuffer = self.buffer.read(cx).snapshot(cx);
6013 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6014 let excerpt_id = cursor.excerpt_id;
6015
6016 let show_in_menu = self.show_edit_predictions_in_menu();
6017 let completions_menu_has_precedence = !show_in_menu
6018 && (self.context_menu.borrow().is_some()
6019 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6020
6021 if completions_menu_has_precedence
6022 || !offset_selection.is_empty()
6023 || self
6024 .active_inline_completion
6025 .as_ref()
6026 .map_or(false, |completion| {
6027 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6028 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6029 !invalidation_range.contains(&offset_selection.head())
6030 })
6031 {
6032 self.discard_inline_completion(false, cx);
6033 return None;
6034 }
6035
6036 self.take_active_inline_completion(cx);
6037 let Some(provider) = self.edit_prediction_provider() else {
6038 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6039 return None;
6040 };
6041
6042 let (buffer, cursor_buffer_position) =
6043 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6044
6045 self.edit_prediction_settings =
6046 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6047
6048 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6049
6050 if self.edit_prediction_indent_conflict {
6051 let cursor_point = cursor.to_point(&multibuffer);
6052
6053 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6054
6055 if let Some((_, indent)) = indents.iter().next() {
6056 if indent.len == cursor_point.column {
6057 self.edit_prediction_indent_conflict = false;
6058 }
6059 }
6060 }
6061
6062 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6063 let edits = inline_completion
6064 .edits
6065 .into_iter()
6066 .flat_map(|(range, new_text)| {
6067 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6068 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6069 Some((start..end, new_text))
6070 })
6071 .collect::<Vec<_>>();
6072 if edits.is_empty() {
6073 return None;
6074 }
6075
6076 let first_edit_start = edits.first().unwrap().0.start;
6077 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6078 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6079
6080 let last_edit_end = edits.last().unwrap().0.end;
6081 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6082 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6083
6084 let cursor_row = cursor.to_point(&multibuffer).row;
6085
6086 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6087
6088 let mut inlay_ids = Vec::new();
6089 let invalidation_row_range;
6090 let move_invalidation_row_range = if cursor_row < edit_start_row {
6091 Some(cursor_row..edit_end_row)
6092 } else if cursor_row > edit_end_row {
6093 Some(edit_start_row..cursor_row)
6094 } else {
6095 None
6096 };
6097 let is_move =
6098 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6099 let completion = if is_move {
6100 invalidation_row_range =
6101 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6102 let target = first_edit_start;
6103 InlineCompletion::Move { target, snapshot }
6104 } else {
6105 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6106 && !self.inline_completions_hidden_for_vim_mode;
6107
6108 if show_completions_in_buffer {
6109 if edits
6110 .iter()
6111 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6112 {
6113 let mut inlays = Vec::new();
6114 for (range, new_text) in &edits {
6115 let inlay = Inlay::inline_completion(
6116 post_inc(&mut self.next_inlay_id),
6117 range.start,
6118 new_text.as_str(),
6119 );
6120 inlay_ids.push(inlay.id);
6121 inlays.push(inlay);
6122 }
6123
6124 self.splice_inlays(&[], inlays, cx);
6125 } else {
6126 let background_color = cx.theme().status().deleted_background;
6127 self.highlight_text::<InlineCompletionHighlight>(
6128 edits.iter().map(|(range, _)| range.clone()).collect(),
6129 HighlightStyle {
6130 background_color: Some(background_color),
6131 ..Default::default()
6132 },
6133 cx,
6134 );
6135 }
6136 }
6137
6138 invalidation_row_range = edit_start_row..edit_end_row;
6139
6140 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6141 if provider.show_tab_accept_marker() {
6142 EditDisplayMode::TabAccept
6143 } else {
6144 EditDisplayMode::Inline
6145 }
6146 } else {
6147 EditDisplayMode::DiffPopover
6148 };
6149
6150 InlineCompletion::Edit {
6151 edits,
6152 edit_preview: inline_completion.edit_preview,
6153 display_mode,
6154 snapshot,
6155 }
6156 };
6157
6158 let invalidation_range = multibuffer
6159 .anchor_before(Point::new(invalidation_row_range.start, 0))
6160 ..multibuffer.anchor_after(Point::new(
6161 invalidation_row_range.end,
6162 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6163 ));
6164
6165 self.stale_inline_completion_in_menu = None;
6166 self.active_inline_completion = Some(InlineCompletionState {
6167 inlay_ids,
6168 completion,
6169 completion_id: inline_completion.id,
6170 invalidation_range,
6171 });
6172
6173 cx.notify();
6174
6175 Some(())
6176 }
6177
6178 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6179 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6180 }
6181
6182 fn render_code_actions_indicator(
6183 &self,
6184 _style: &EditorStyle,
6185 row: DisplayRow,
6186 is_active: bool,
6187 breakpoint: Option<&(Anchor, Breakpoint)>,
6188 cx: &mut Context<Self>,
6189 ) -> Option<IconButton> {
6190 let color = Color::Muted;
6191 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6192 let show_tooltip = !self.context_menu_visible();
6193
6194 if self.available_code_actions.is_some() {
6195 Some(
6196 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6197 .shape(ui::IconButtonShape::Square)
6198 .icon_size(IconSize::XSmall)
6199 .icon_color(color)
6200 .toggle_state(is_active)
6201 .when(show_tooltip, |this| {
6202 this.tooltip({
6203 let focus_handle = self.focus_handle.clone();
6204 move |window, cx| {
6205 Tooltip::for_action_in(
6206 "Toggle Code Actions",
6207 &ToggleCodeActions {
6208 deployed_from_indicator: None,
6209 },
6210 &focus_handle,
6211 window,
6212 cx,
6213 )
6214 }
6215 })
6216 })
6217 .on_click(cx.listener(move |editor, _e, window, cx| {
6218 window.focus(&editor.focus_handle(cx));
6219 editor.toggle_code_actions(
6220 &ToggleCodeActions {
6221 deployed_from_indicator: Some(row),
6222 },
6223 window,
6224 cx,
6225 );
6226 }))
6227 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6228 editor.set_breakpoint_context_menu(
6229 row,
6230 position,
6231 event.down.position,
6232 window,
6233 cx,
6234 );
6235 })),
6236 )
6237 } else {
6238 None
6239 }
6240 }
6241
6242 fn clear_tasks(&mut self) {
6243 self.tasks.clear()
6244 }
6245
6246 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6247 if self.tasks.insert(key, value).is_some() {
6248 // This case should hopefully be rare, but just in case...
6249 log::error!(
6250 "multiple different run targets found on a single line, only the last target will be rendered"
6251 )
6252 }
6253 }
6254
6255 /// Get all display points of breakpoints that will be rendered within editor
6256 ///
6257 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6258 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6259 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6260 fn active_breakpoints(
6261 &self,
6262 range: Range<DisplayRow>,
6263 window: &mut Window,
6264 cx: &mut Context<Self>,
6265 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6266 let mut breakpoint_display_points = HashMap::default();
6267
6268 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6269 return breakpoint_display_points;
6270 };
6271
6272 let snapshot = self.snapshot(window, cx);
6273
6274 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6275 let Some(project) = self.project.as_ref() else {
6276 return breakpoint_display_points;
6277 };
6278
6279 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6280 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6281
6282 for (buffer_snapshot, range, excerpt_id) in
6283 multi_buffer_snapshot.range_to_buffer_ranges(range)
6284 {
6285 let Some(buffer) = project.read_with(cx, |this, cx| {
6286 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6287 }) else {
6288 continue;
6289 };
6290 let breakpoints = breakpoint_store.read(cx).breakpoints(
6291 &buffer,
6292 Some(
6293 buffer_snapshot.anchor_before(range.start)
6294 ..buffer_snapshot.anchor_after(range.end),
6295 ),
6296 buffer_snapshot,
6297 cx,
6298 );
6299 for (anchor, breakpoint) in breakpoints {
6300 let multi_buffer_anchor =
6301 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6302 let position = multi_buffer_anchor
6303 .to_point(&multi_buffer_snapshot)
6304 .to_display_point(&snapshot);
6305
6306 breakpoint_display_points
6307 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6308 }
6309 }
6310
6311 breakpoint_display_points
6312 }
6313
6314 fn breakpoint_context_menu(
6315 &self,
6316 anchor: Anchor,
6317 window: &mut Window,
6318 cx: &mut Context<Self>,
6319 ) -> Entity<ui::ContextMenu> {
6320 let weak_editor = cx.weak_entity();
6321 let focus_handle = self.focus_handle(cx);
6322
6323 let row = self
6324 .buffer
6325 .read(cx)
6326 .snapshot(cx)
6327 .summary_for_anchor::<Point>(&anchor)
6328 .row;
6329
6330 let breakpoint = self
6331 .breakpoint_at_row(row, window, cx)
6332 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6333
6334 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6335 "Edit Log Breakpoint"
6336 } else {
6337 "Set Log Breakpoint"
6338 };
6339
6340 let condition_breakpoint_msg = if breakpoint
6341 .as_ref()
6342 .is_some_and(|bp| bp.1.condition.is_some())
6343 {
6344 "Edit Condition Breakpoint"
6345 } else {
6346 "Set Condition Breakpoint"
6347 };
6348
6349 let hit_condition_breakpoint_msg = if breakpoint
6350 .as_ref()
6351 .is_some_and(|bp| bp.1.hit_condition.is_some())
6352 {
6353 "Edit Hit Condition Breakpoint"
6354 } else {
6355 "Set Hit Condition Breakpoint"
6356 };
6357
6358 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6359 "Unset Breakpoint"
6360 } else {
6361 "Set Breakpoint"
6362 };
6363
6364 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6365 BreakpointState::Enabled => Some("Disable"),
6366 BreakpointState::Disabled => Some("Enable"),
6367 });
6368
6369 let (anchor, breakpoint) =
6370 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6371
6372 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6373 menu.on_blur_subscription(Subscription::new(|| {}))
6374 .context(focus_handle)
6375 .when_some(toggle_state_msg, |this, msg| {
6376 this.entry(msg, None, {
6377 let weak_editor = weak_editor.clone();
6378 let breakpoint = breakpoint.clone();
6379 move |_window, cx| {
6380 weak_editor
6381 .update(cx, |this, cx| {
6382 this.edit_breakpoint_at_anchor(
6383 anchor,
6384 breakpoint.as_ref().clone(),
6385 BreakpointEditAction::InvertState,
6386 cx,
6387 );
6388 })
6389 .log_err();
6390 }
6391 })
6392 })
6393 .entry(set_breakpoint_msg, None, {
6394 let weak_editor = weak_editor.clone();
6395 let breakpoint = breakpoint.clone();
6396 move |_window, cx| {
6397 weak_editor
6398 .update(cx, |this, cx| {
6399 this.edit_breakpoint_at_anchor(
6400 anchor,
6401 breakpoint.as_ref().clone(),
6402 BreakpointEditAction::Toggle,
6403 cx,
6404 );
6405 })
6406 .log_err();
6407 }
6408 })
6409 .entry(log_breakpoint_msg, None, {
6410 let breakpoint = breakpoint.clone();
6411 let weak_editor = weak_editor.clone();
6412 move |window, cx| {
6413 weak_editor
6414 .update(cx, |this, cx| {
6415 this.add_edit_breakpoint_block(
6416 anchor,
6417 breakpoint.as_ref(),
6418 BreakpointPromptEditAction::Log,
6419 window,
6420 cx,
6421 );
6422 })
6423 .log_err();
6424 }
6425 })
6426 .entry(condition_breakpoint_msg, None, {
6427 let breakpoint = breakpoint.clone();
6428 let weak_editor = weak_editor.clone();
6429 move |window, cx| {
6430 weak_editor
6431 .update(cx, |this, cx| {
6432 this.add_edit_breakpoint_block(
6433 anchor,
6434 breakpoint.as_ref(),
6435 BreakpointPromptEditAction::Condition,
6436 window,
6437 cx,
6438 );
6439 })
6440 .log_err();
6441 }
6442 })
6443 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6444 weak_editor
6445 .update(cx, |this, cx| {
6446 this.add_edit_breakpoint_block(
6447 anchor,
6448 breakpoint.as_ref(),
6449 BreakpointPromptEditAction::HitCondition,
6450 window,
6451 cx,
6452 );
6453 })
6454 .log_err();
6455 })
6456 })
6457 }
6458
6459 fn render_breakpoint(
6460 &self,
6461 position: Anchor,
6462 row: DisplayRow,
6463 breakpoint: &Breakpoint,
6464 cx: &mut Context<Self>,
6465 ) -> IconButton {
6466 let (color, icon) = {
6467 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6468 (false, false) => ui::IconName::DebugBreakpoint,
6469 (true, false) => ui::IconName::DebugLogBreakpoint,
6470 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6471 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6472 };
6473
6474 let color = if self
6475 .gutter_breakpoint_indicator
6476 .0
6477 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6478 {
6479 Color::Hint
6480 } else {
6481 Color::Debugger
6482 };
6483
6484 (color, icon)
6485 };
6486
6487 let breakpoint = Arc::from(breakpoint.clone());
6488
6489 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6490 .icon_size(IconSize::XSmall)
6491 .size(ui::ButtonSize::None)
6492 .icon_color(color)
6493 .style(ButtonStyle::Transparent)
6494 .on_click(cx.listener({
6495 let breakpoint = breakpoint.clone();
6496
6497 move |editor, event: &ClickEvent, window, cx| {
6498 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6499 BreakpointEditAction::InvertState
6500 } else {
6501 BreakpointEditAction::Toggle
6502 };
6503
6504 window.focus(&editor.focus_handle(cx));
6505 editor.edit_breakpoint_at_anchor(
6506 position,
6507 breakpoint.as_ref().clone(),
6508 edit_action,
6509 cx,
6510 );
6511 }
6512 }))
6513 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6514 editor.set_breakpoint_context_menu(
6515 row,
6516 Some(position),
6517 event.down.position,
6518 window,
6519 cx,
6520 );
6521 }))
6522 }
6523
6524 fn build_tasks_context(
6525 project: &Entity<Project>,
6526 buffer: &Entity<Buffer>,
6527 buffer_row: u32,
6528 tasks: &Arc<RunnableTasks>,
6529 cx: &mut Context<Self>,
6530 ) -> Task<Option<task::TaskContext>> {
6531 let position = Point::new(buffer_row, tasks.column);
6532 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6533 let location = Location {
6534 buffer: buffer.clone(),
6535 range: range_start..range_start,
6536 };
6537 // Fill in the environmental variables from the tree-sitter captures
6538 let mut captured_task_variables = TaskVariables::default();
6539 for (capture_name, value) in tasks.extra_variables.clone() {
6540 captured_task_variables.insert(
6541 task::VariableName::Custom(capture_name.into()),
6542 value.clone(),
6543 );
6544 }
6545 project.update(cx, |project, cx| {
6546 project.task_store().update(cx, |task_store, cx| {
6547 task_store.task_context_for_location(captured_task_variables, location, cx)
6548 })
6549 })
6550 }
6551
6552 pub fn spawn_nearest_task(
6553 &mut self,
6554 action: &SpawnNearestTask,
6555 window: &mut Window,
6556 cx: &mut Context<Self>,
6557 ) {
6558 let Some((workspace, _)) = self.workspace.clone() else {
6559 return;
6560 };
6561 let Some(project) = self.project.clone() else {
6562 return;
6563 };
6564
6565 // Try to find a closest, enclosing node using tree-sitter that has a
6566 // task
6567 let Some((buffer, buffer_row, tasks)) = self
6568 .find_enclosing_node_task(cx)
6569 // Or find the task that's closest in row-distance.
6570 .or_else(|| self.find_closest_task(cx))
6571 else {
6572 return;
6573 };
6574
6575 let reveal_strategy = action.reveal;
6576 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6577 cx.spawn_in(window, async move |_, cx| {
6578 let context = task_context.await?;
6579 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6580
6581 let resolved = resolved_task.resolved.as_mut()?;
6582 resolved.reveal = reveal_strategy;
6583
6584 workspace
6585 .update(cx, |workspace, cx| {
6586 workspace::tasks::schedule_resolved_task(
6587 workspace,
6588 task_source_kind,
6589 resolved_task,
6590 false,
6591 cx,
6592 );
6593 })
6594 .ok()
6595 })
6596 .detach();
6597 }
6598
6599 fn find_closest_task(
6600 &mut self,
6601 cx: &mut Context<Self>,
6602 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6603 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6604
6605 let ((buffer_id, row), tasks) = self
6606 .tasks
6607 .iter()
6608 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6609
6610 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6611 let tasks = Arc::new(tasks.to_owned());
6612 Some((buffer, *row, tasks))
6613 }
6614
6615 fn find_enclosing_node_task(
6616 &mut self,
6617 cx: &mut Context<Self>,
6618 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6619 let snapshot = self.buffer.read(cx).snapshot(cx);
6620 let offset = self.selections.newest::<usize>(cx).head();
6621 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6622 let buffer_id = excerpt.buffer().remote_id();
6623
6624 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6625 let mut cursor = layer.node().walk();
6626
6627 while cursor.goto_first_child_for_byte(offset).is_some() {
6628 if cursor.node().end_byte() == offset {
6629 cursor.goto_next_sibling();
6630 }
6631 }
6632
6633 // Ascend to the smallest ancestor that contains the range and has a task.
6634 loop {
6635 let node = cursor.node();
6636 let node_range = node.byte_range();
6637 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6638
6639 // Check if this node contains our offset
6640 if node_range.start <= offset && node_range.end >= offset {
6641 // If it contains offset, check for task
6642 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6643 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6644 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6645 }
6646 }
6647
6648 if !cursor.goto_parent() {
6649 break;
6650 }
6651 }
6652 None
6653 }
6654
6655 fn render_run_indicator(
6656 &self,
6657 _style: &EditorStyle,
6658 is_active: bool,
6659 row: DisplayRow,
6660 breakpoint: Option<(Anchor, Breakpoint)>,
6661 cx: &mut Context<Self>,
6662 ) -> IconButton {
6663 let color = Color::Muted;
6664 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6665
6666 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6667 .shape(ui::IconButtonShape::Square)
6668 .icon_size(IconSize::XSmall)
6669 .icon_color(color)
6670 .toggle_state(is_active)
6671 .on_click(cx.listener(move |editor, _e, window, cx| {
6672 window.focus(&editor.focus_handle(cx));
6673 editor.toggle_code_actions(
6674 &ToggleCodeActions {
6675 deployed_from_indicator: Some(row),
6676 },
6677 window,
6678 cx,
6679 );
6680 }))
6681 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6682 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6683 }))
6684 }
6685
6686 pub fn context_menu_visible(&self) -> bool {
6687 !self.edit_prediction_preview_is_active()
6688 && self
6689 .context_menu
6690 .borrow()
6691 .as_ref()
6692 .map_or(false, |menu| menu.visible())
6693 }
6694
6695 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6696 self.context_menu
6697 .borrow()
6698 .as_ref()
6699 .map(|menu| menu.origin())
6700 }
6701
6702 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6703 self.context_menu_options = Some(options);
6704 }
6705
6706 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6707 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6708
6709 fn render_edit_prediction_popover(
6710 &mut self,
6711 text_bounds: &Bounds<Pixels>,
6712 content_origin: gpui::Point<Pixels>,
6713 editor_snapshot: &EditorSnapshot,
6714 visible_row_range: Range<DisplayRow>,
6715 scroll_top: f32,
6716 scroll_bottom: f32,
6717 line_layouts: &[LineWithInvisibles],
6718 line_height: Pixels,
6719 scroll_pixel_position: gpui::Point<Pixels>,
6720 newest_selection_head: Option<DisplayPoint>,
6721 editor_width: Pixels,
6722 style: &EditorStyle,
6723 window: &mut Window,
6724 cx: &mut App,
6725 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6726 let active_inline_completion = self.active_inline_completion.as_ref()?;
6727
6728 if self.edit_prediction_visible_in_cursor_popover(true) {
6729 return None;
6730 }
6731
6732 match &active_inline_completion.completion {
6733 InlineCompletion::Move { target, .. } => {
6734 let target_display_point = target.to_display_point(editor_snapshot);
6735
6736 if self.edit_prediction_requires_modifier() {
6737 if !self.edit_prediction_preview_is_active() {
6738 return None;
6739 }
6740
6741 self.render_edit_prediction_modifier_jump_popover(
6742 text_bounds,
6743 content_origin,
6744 visible_row_range,
6745 line_layouts,
6746 line_height,
6747 scroll_pixel_position,
6748 newest_selection_head,
6749 target_display_point,
6750 window,
6751 cx,
6752 )
6753 } else {
6754 self.render_edit_prediction_eager_jump_popover(
6755 text_bounds,
6756 content_origin,
6757 editor_snapshot,
6758 visible_row_range,
6759 scroll_top,
6760 scroll_bottom,
6761 line_height,
6762 scroll_pixel_position,
6763 target_display_point,
6764 editor_width,
6765 window,
6766 cx,
6767 )
6768 }
6769 }
6770 InlineCompletion::Edit {
6771 display_mode: EditDisplayMode::Inline,
6772 ..
6773 } => None,
6774 InlineCompletion::Edit {
6775 display_mode: EditDisplayMode::TabAccept,
6776 edits,
6777 ..
6778 } => {
6779 let range = &edits.first()?.0;
6780 let target_display_point = range.end.to_display_point(editor_snapshot);
6781
6782 self.render_edit_prediction_end_of_line_popover(
6783 "Accept",
6784 editor_snapshot,
6785 visible_row_range,
6786 target_display_point,
6787 line_height,
6788 scroll_pixel_position,
6789 content_origin,
6790 editor_width,
6791 window,
6792 cx,
6793 )
6794 }
6795 InlineCompletion::Edit {
6796 edits,
6797 edit_preview,
6798 display_mode: EditDisplayMode::DiffPopover,
6799 snapshot,
6800 } => self.render_edit_prediction_diff_popover(
6801 text_bounds,
6802 content_origin,
6803 editor_snapshot,
6804 visible_row_range,
6805 line_layouts,
6806 line_height,
6807 scroll_pixel_position,
6808 newest_selection_head,
6809 editor_width,
6810 style,
6811 edits,
6812 edit_preview,
6813 snapshot,
6814 window,
6815 cx,
6816 ),
6817 }
6818 }
6819
6820 fn render_edit_prediction_modifier_jump_popover(
6821 &mut self,
6822 text_bounds: &Bounds<Pixels>,
6823 content_origin: gpui::Point<Pixels>,
6824 visible_row_range: Range<DisplayRow>,
6825 line_layouts: &[LineWithInvisibles],
6826 line_height: Pixels,
6827 scroll_pixel_position: gpui::Point<Pixels>,
6828 newest_selection_head: Option<DisplayPoint>,
6829 target_display_point: DisplayPoint,
6830 window: &mut Window,
6831 cx: &mut App,
6832 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6833 let scrolled_content_origin =
6834 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6835
6836 const SCROLL_PADDING_Y: Pixels = px(12.);
6837
6838 if target_display_point.row() < visible_row_range.start {
6839 return self.render_edit_prediction_scroll_popover(
6840 |_| SCROLL_PADDING_Y,
6841 IconName::ArrowUp,
6842 visible_row_range,
6843 line_layouts,
6844 newest_selection_head,
6845 scrolled_content_origin,
6846 window,
6847 cx,
6848 );
6849 } else if target_display_point.row() >= visible_row_range.end {
6850 return self.render_edit_prediction_scroll_popover(
6851 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6852 IconName::ArrowDown,
6853 visible_row_range,
6854 line_layouts,
6855 newest_selection_head,
6856 scrolled_content_origin,
6857 window,
6858 cx,
6859 );
6860 }
6861
6862 const POLE_WIDTH: Pixels = px(2.);
6863
6864 let line_layout =
6865 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6866 let target_column = target_display_point.column() as usize;
6867
6868 let target_x = line_layout.x_for_index(target_column);
6869 let target_y =
6870 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6871
6872 let flag_on_right = target_x < text_bounds.size.width / 2.;
6873
6874 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6875 border_color.l += 0.001;
6876
6877 let mut element = v_flex()
6878 .items_end()
6879 .when(flag_on_right, |el| el.items_start())
6880 .child(if flag_on_right {
6881 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6882 .rounded_bl(px(0.))
6883 .rounded_tl(px(0.))
6884 .border_l_2()
6885 .border_color(border_color)
6886 } else {
6887 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6888 .rounded_br(px(0.))
6889 .rounded_tr(px(0.))
6890 .border_r_2()
6891 .border_color(border_color)
6892 })
6893 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6894 .into_any();
6895
6896 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6897
6898 let mut origin = scrolled_content_origin + point(target_x, target_y)
6899 - point(
6900 if flag_on_right {
6901 POLE_WIDTH
6902 } else {
6903 size.width - POLE_WIDTH
6904 },
6905 size.height - line_height,
6906 );
6907
6908 origin.x = origin.x.max(content_origin.x);
6909
6910 element.prepaint_at(origin, window, cx);
6911
6912 Some((element, origin))
6913 }
6914
6915 fn render_edit_prediction_scroll_popover(
6916 &mut self,
6917 to_y: impl Fn(Size<Pixels>) -> Pixels,
6918 scroll_icon: IconName,
6919 visible_row_range: Range<DisplayRow>,
6920 line_layouts: &[LineWithInvisibles],
6921 newest_selection_head: Option<DisplayPoint>,
6922 scrolled_content_origin: gpui::Point<Pixels>,
6923 window: &mut Window,
6924 cx: &mut App,
6925 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6926 let mut element = self
6927 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6928 .into_any();
6929
6930 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6931
6932 let cursor = newest_selection_head?;
6933 let cursor_row_layout =
6934 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6935 let cursor_column = cursor.column() as usize;
6936
6937 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6938
6939 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6940
6941 element.prepaint_at(origin, window, cx);
6942 Some((element, origin))
6943 }
6944
6945 fn render_edit_prediction_eager_jump_popover(
6946 &mut self,
6947 text_bounds: &Bounds<Pixels>,
6948 content_origin: gpui::Point<Pixels>,
6949 editor_snapshot: &EditorSnapshot,
6950 visible_row_range: Range<DisplayRow>,
6951 scroll_top: f32,
6952 scroll_bottom: f32,
6953 line_height: Pixels,
6954 scroll_pixel_position: gpui::Point<Pixels>,
6955 target_display_point: DisplayPoint,
6956 editor_width: Pixels,
6957 window: &mut Window,
6958 cx: &mut App,
6959 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6960 if target_display_point.row().as_f32() < scroll_top {
6961 let mut element = self
6962 .render_edit_prediction_line_popover(
6963 "Jump to Edit",
6964 Some(IconName::ArrowUp),
6965 window,
6966 cx,
6967 )?
6968 .into_any();
6969
6970 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6971 let offset = point(
6972 (text_bounds.size.width - size.width) / 2.,
6973 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6974 );
6975
6976 let origin = text_bounds.origin + offset;
6977 element.prepaint_at(origin, window, cx);
6978 Some((element, origin))
6979 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6980 let mut element = self
6981 .render_edit_prediction_line_popover(
6982 "Jump to Edit",
6983 Some(IconName::ArrowDown),
6984 window,
6985 cx,
6986 )?
6987 .into_any();
6988
6989 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6990 let offset = point(
6991 (text_bounds.size.width - size.width) / 2.,
6992 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6993 );
6994
6995 let origin = text_bounds.origin + offset;
6996 element.prepaint_at(origin, window, cx);
6997 Some((element, origin))
6998 } else {
6999 self.render_edit_prediction_end_of_line_popover(
7000 "Jump to Edit",
7001 editor_snapshot,
7002 visible_row_range,
7003 target_display_point,
7004 line_height,
7005 scroll_pixel_position,
7006 content_origin,
7007 editor_width,
7008 window,
7009 cx,
7010 )
7011 }
7012 }
7013
7014 fn render_edit_prediction_end_of_line_popover(
7015 self: &mut Editor,
7016 label: &'static str,
7017 editor_snapshot: &EditorSnapshot,
7018 visible_row_range: Range<DisplayRow>,
7019 target_display_point: DisplayPoint,
7020 line_height: Pixels,
7021 scroll_pixel_position: gpui::Point<Pixels>,
7022 content_origin: gpui::Point<Pixels>,
7023 editor_width: Pixels,
7024 window: &mut Window,
7025 cx: &mut App,
7026 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7027 let target_line_end = DisplayPoint::new(
7028 target_display_point.row(),
7029 editor_snapshot.line_len(target_display_point.row()),
7030 );
7031
7032 let mut element = self
7033 .render_edit_prediction_line_popover(label, None, window, cx)?
7034 .into_any();
7035
7036 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7037
7038 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7039
7040 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7041 let mut origin = start_point
7042 + line_origin
7043 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7044 origin.x = origin.x.max(content_origin.x);
7045
7046 let max_x = content_origin.x + editor_width - size.width;
7047
7048 if origin.x > max_x {
7049 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7050
7051 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7052 origin.y += offset;
7053 IconName::ArrowUp
7054 } else {
7055 origin.y -= offset;
7056 IconName::ArrowDown
7057 };
7058
7059 element = self
7060 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7061 .into_any();
7062
7063 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7064
7065 origin.x = content_origin.x + editor_width - size.width - px(2.);
7066 }
7067
7068 element.prepaint_at(origin, window, cx);
7069 Some((element, origin))
7070 }
7071
7072 fn render_edit_prediction_diff_popover(
7073 self: &Editor,
7074 text_bounds: &Bounds<Pixels>,
7075 content_origin: gpui::Point<Pixels>,
7076 editor_snapshot: &EditorSnapshot,
7077 visible_row_range: Range<DisplayRow>,
7078 line_layouts: &[LineWithInvisibles],
7079 line_height: Pixels,
7080 scroll_pixel_position: gpui::Point<Pixels>,
7081 newest_selection_head: Option<DisplayPoint>,
7082 editor_width: Pixels,
7083 style: &EditorStyle,
7084 edits: &Vec<(Range<Anchor>, String)>,
7085 edit_preview: &Option<language::EditPreview>,
7086 snapshot: &language::BufferSnapshot,
7087 window: &mut Window,
7088 cx: &mut App,
7089 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7090 let edit_start = edits
7091 .first()
7092 .unwrap()
7093 .0
7094 .start
7095 .to_display_point(editor_snapshot);
7096 let edit_end = edits
7097 .last()
7098 .unwrap()
7099 .0
7100 .end
7101 .to_display_point(editor_snapshot);
7102
7103 let is_visible = visible_row_range.contains(&edit_start.row())
7104 || visible_row_range.contains(&edit_end.row());
7105 if !is_visible {
7106 return None;
7107 }
7108
7109 let highlighted_edits =
7110 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7111
7112 let styled_text = highlighted_edits.to_styled_text(&style.text);
7113 let line_count = highlighted_edits.text.lines().count();
7114
7115 const BORDER_WIDTH: Pixels = px(1.);
7116
7117 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7118 let has_keybind = keybind.is_some();
7119
7120 let mut element = h_flex()
7121 .items_start()
7122 .child(
7123 h_flex()
7124 .bg(cx.theme().colors().editor_background)
7125 .border(BORDER_WIDTH)
7126 .shadow_sm()
7127 .border_color(cx.theme().colors().border)
7128 .rounded_l_lg()
7129 .when(line_count > 1, |el| el.rounded_br_lg())
7130 .pr_1()
7131 .child(styled_text),
7132 )
7133 .child(
7134 h_flex()
7135 .h(line_height + BORDER_WIDTH * 2.)
7136 .px_1p5()
7137 .gap_1()
7138 // Workaround: For some reason, there's a gap if we don't do this
7139 .ml(-BORDER_WIDTH)
7140 .shadow(smallvec![gpui::BoxShadow {
7141 color: gpui::black().opacity(0.05),
7142 offset: point(px(1.), px(1.)),
7143 blur_radius: px(2.),
7144 spread_radius: px(0.),
7145 }])
7146 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7147 .border(BORDER_WIDTH)
7148 .border_color(cx.theme().colors().border)
7149 .rounded_r_lg()
7150 .id("edit_prediction_diff_popover_keybind")
7151 .when(!has_keybind, |el| {
7152 let status_colors = cx.theme().status();
7153
7154 el.bg(status_colors.error_background)
7155 .border_color(status_colors.error.opacity(0.6))
7156 .child(Icon::new(IconName::Info).color(Color::Error))
7157 .cursor_default()
7158 .hoverable_tooltip(move |_window, cx| {
7159 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7160 })
7161 })
7162 .children(keybind),
7163 )
7164 .into_any();
7165
7166 let longest_row =
7167 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7168 let longest_line_width = if visible_row_range.contains(&longest_row) {
7169 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7170 } else {
7171 layout_line(
7172 longest_row,
7173 editor_snapshot,
7174 style,
7175 editor_width,
7176 |_| false,
7177 window,
7178 cx,
7179 )
7180 .width
7181 };
7182
7183 let viewport_bounds =
7184 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7185 right: -EditorElement::SCROLLBAR_WIDTH,
7186 ..Default::default()
7187 });
7188
7189 let x_after_longest =
7190 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7191 - scroll_pixel_position.x;
7192
7193 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7194
7195 // Fully visible if it can be displayed within the window (allow overlapping other
7196 // panes). However, this is only allowed if the popover starts within text_bounds.
7197 let can_position_to_the_right = x_after_longest < text_bounds.right()
7198 && x_after_longest + element_bounds.width < viewport_bounds.right();
7199
7200 let mut origin = if can_position_to_the_right {
7201 point(
7202 x_after_longest,
7203 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7204 - scroll_pixel_position.y,
7205 )
7206 } else {
7207 let cursor_row = newest_selection_head.map(|head| head.row());
7208 let above_edit = edit_start
7209 .row()
7210 .0
7211 .checked_sub(line_count as u32)
7212 .map(DisplayRow);
7213 let below_edit = Some(edit_end.row() + 1);
7214 let above_cursor =
7215 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7216 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7217
7218 // Place the edit popover adjacent to the edit if there is a location
7219 // available that is onscreen and does not obscure the cursor. Otherwise,
7220 // place it adjacent to the cursor.
7221 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7222 .into_iter()
7223 .flatten()
7224 .find(|&start_row| {
7225 let end_row = start_row + line_count as u32;
7226 visible_row_range.contains(&start_row)
7227 && visible_row_range.contains(&end_row)
7228 && cursor_row.map_or(true, |cursor_row| {
7229 !((start_row..end_row).contains(&cursor_row))
7230 })
7231 })?;
7232
7233 content_origin
7234 + point(
7235 -scroll_pixel_position.x,
7236 row_target.as_f32() * line_height - scroll_pixel_position.y,
7237 )
7238 };
7239
7240 origin.x -= BORDER_WIDTH;
7241
7242 window.defer_draw(element, origin, 1);
7243
7244 // Do not return an element, since it will already be drawn due to defer_draw.
7245 None
7246 }
7247
7248 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7249 px(30.)
7250 }
7251
7252 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7253 if self.read_only(cx) {
7254 cx.theme().players().read_only()
7255 } else {
7256 self.style.as_ref().unwrap().local_player
7257 }
7258 }
7259
7260 fn render_edit_prediction_accept_keybind(
7261 &self,
7262 window: &mut Window,
7263 cx: &App,
7264 ) -> Option<AnyElement> {
7265 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7266 let accept_keystroke = accept_binding.keystroke()?;
7267
7268 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7269
7270 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7271 Color::Accent
7272 } else {
7273 Color::Muted
7274 };
7275
7276 h_flex()
7277 .px_0p5()
7278 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7279 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7280 .text_size(TextSize::XSmall.rems(cx))
7281 .child(h_flex().children(ui::render_modifiers(
7282 &accept_keystroke.modifiers,
7283 PlatformStyle::platform(),
7284 Some(modifiers_color),
7285 Some(IconSize::XSmall.rems().into()),
7286 true,
7287 )))
7288 .when(is_platform_style_mac, |parent| {
7289 parent.child(accept_keystroke.key.clone())
7290 })
7291 .when(!is_platform_style_mac, |parent| {
7292 parent.child(
7293 Key::new(
7294 util::capitalize(&accept_keystroke.key),
7295 Some(Color::Default),
7296 )
7297 .size(Some(IconSize::XSmall.rems().into())),
7298 )
7299 })
7300 .into_any()
7301 .into()
7302 }
7303
7304 fn render_edit_prediction_line_popover(
7305 &self,
7306 label: impl Into<SharedString>,
7307 icon: Option<IconName>,
7308 window: &mut Window,
7309 cx: &App,
7310 ) -> Option<Stateful<Div>> {
7311 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7312
7313 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7314 let has_keybind = keybind.is_some();
7315
7316 let result = h_flex()
7317 .id("ep-line-popover")
7318 .py_0p5()
7319 .pl_1()
7320 .pr(padding_right)
7321 .gap_1()
7322 .rounded_md()
7323 .border_1()
7324 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7325 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7326 .shadow_sm()
7327 .when(!has_keybind, |el| {
7328 let status_colors = cx.theme().status();
7329
7330 el.bg(status_colors.error_background)
7331 .border_color(status_colors.error.opacity(0.6))
7332 .pl_2()
7333 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7334 .cursor_default()
7335 .hoverable_tooltip(move |_window, cx| {
7336 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7337 })
7338 })
7339 .children(keybind)
7340 .child(
7341 Label::new(label)
7342 .size(LabelSize::Small)
7343 .when(!has_keybind, |el| {
7344 el.color(cx.theme().status().error.into()).strikethrough()
7345 }),
7346 )
7347 .when(!has_keybind, |el| {
7348 el.child(
7349 h_flex().ml_1().child(
7350 Icon::new(IconName::Info)
7351 .size(IconSize::Small)
7352 .color(cx.theme().status().error.into()),
7353 ),
7354 )
7355 })
7356 .when_some(icon, |element, icon| {
7357 element.child(
7358 div()
7359 .mt(px(1.5))
7360 .child(Icon::new(icon).size(IconSize::Small)),
7361 )
7362 });
7363
7364 Some(result)
7365 }
7366
7367 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7368 let accent_color = cx.theme().colors().text_accent;
7369 let editor_bg_color = cx.theme().colors().editor_background;
7370 editor_bg_color.blend(accent_color.opacity(0.1))
7371 }
7372
7373 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7374 let accent_color = cx.theme().colors().text_accent;
7375 let editor_bg_color = cx.theme().colors().editor_background;
7376 editor_bg_color.blend(accent_color.opacity(0.6))
7377 }
7378
7379 fn render_edit_prediction_cursor_popover(
7380 &self,
7381 min_width: Pixels,
7382 max_width: Pixels,
7383 cursor_point: Point,
7384 style: &EditorStyle,
7385 accept_keystroke: Option<&gpui::Keystroke>,
7386 _window: &Window,
7387 cx: &mut Context<Editor>,
7388 ) -> Option<AnyElement> {
7389 let provider = self.edit_prediction_provider.as_ref()?;
7390
7391 if provider.provider.needs_terms_acceptance(cx) {
7392 return Some(
7393 h_flex()
7394 .min_w(min_width)
7395 .flex_1()
7396 .px_2()
7397 .py_1()
7398 .gap_3()
7399 .elevation_2(cx)
7400 .hover(|style| style.bg(cx.theme().colors().element_hover))
7401 .id("accept-terms")
7402 .cursor_pointer()
7403 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7404 .on_click(cx.listener(|this, _event, window, cx| {
7405 cx.stop_propagation();
7406 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7407 window.dispatch_action(
7408 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7409 cx,
7410 );
7411 }))
7412 .child(
7413 h_flex()
7414 .flex_1()
7415 .gap_2()
7416 .child(Icon::new(IconName::ZedPredict))
7417 .child(Label::new("Accept Terms of Service"))
7418 .child(div().w_full())
7419 .child(
7420 Icon::new(IconName::ArrowUpRight)
7421 .color(Color::Muted)
7422 .size(IconSize::Small),
7423 )
7424 .into_any_element(),
7425 )
7426 .into_any(),
7427 );
7428 }
7429
7430 let is_refreshing = provider.provider.is_refreshing(cx);
7431
7432 fn pending_completion_container() -> Div {
7433 h_flex()
7434 .h_full()
7435 .flex_1()
7436 .gap_2()
7437 .child(Icon::new(IconName::ZedPredict))
7438 }
7439
7440 let completion = match &self.active_inline_completion {
7441 Some(prediction) => {
7442 if !self.has_visible_completions_menu() {
7443 const RADIUS: Pixels = px(6.);
7444 const BORDER_WIDTH: Pixels = px(1.);
7445
7446 return Some(
7447 h_flex()
7448 .elevation_2(cx)
7449 .border(BORDER_WIDTH)
7450 .border_color(cx.theme().colors().border)
7451 .when(accept_keystroke.is_none(), |el| {
7452 el.border_color(cx.theme().status().error)
7453 })
7454 .rounded(RADIUS)
7455 .rounded_tl(px(0.))
7456 .overflow_hidden()
7457 .child(div().px_1p5().child(match &prediction.completion {
7458 InlineCompletion::Move { target, snapshot } => {
7459 use text::ToPoint as _;
7460 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7461 {
7462 Icon::new(IconName::ZedPredictDown)
7463 } else {
7464 Icon::new(IconName::ZedPredictUp)
7465 }
7466 }
7467 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7468 }))
7469 .child(
7470 h_flex()
7471 .gap_1()
7472 .py_1()
7473 .px_2()
7474 .rounded_r(RADIUS - BORDER_WIDTH)
7475 .border_l_1()
7476 .border_color(cx.theme().colors().border)
7477 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7478 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7479 el.child(
7480 Label::new("Hold")
7481 .size(LabelSize::Small)
7482 .when(accept_keystroke.is_none(), |el| {
7483 el.strikethrough()
7484 })
7485 .line_height_style(LineHeightStyle::UiLabel),
7486 )
7487 })
7488 .id("edit_prediction_cursor_popover_keybind")
7489 .when(accept_keystroke.is_none(), |el| {
7490 let status_colors = cx.theme().status();
7491
7492 el.bg(status_colors.error_background)
7493 .border_color(status_colors.error.opacity(0.6))
7494 .child(Icon::new(IconName::Info).color(Color::Error))
7495 .cursor_default()
7496 .hoverable_tooltip(move |_window, cx| {
7497 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7498 .into()
7499 })
7500 })
7501 .when_some(
7502 accept_keystroke.as_ref(),
7503 |el, accept_keystroke| {
7504 el.child(h_flex().children(ui::render_modifiers(
7505 &accept_keystroke.modifiers,
7506 PlatformStyle::platform(),
7507 Some(Color::Default),
7508 Some(IconSize::XSmall.rems().into()),
7509 false,
7510 )))
7511 },
7512 ),
7513 )
7514 .into_any(),
7515 );
7516 }
7517
7518 self.render_edit_prediction_cursor_popover_preview(
7519 prediction,
7520 cursor_point,
7521 style,
7522 cx,
7523 )?
7524 }
7525
7526 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7527 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7528 stale_completion,
7529 cursor_point,
7530 style,
7531 cx,
7532 )?,
7533
7534 None => {
7535 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7536 }
7537 },
7538
7539 None => pending_completion_container().child(Label::new("No Prediction")),
7540 };
7541
7542 let completion = if is_refreshing {
7543 completion
7544 .with_animation(
7545 "loading-completion",
7546 Animation::new(Duration::from_secs(2))
7547 .repeat()
7548 .with_easing(pulsating_between(0.4, 0.8)),
7549 |label, delta| label.opacity(delta),
7550 )
7551 .into_any_element()
7552 } else {
7553 completion.into_any_element()
7554 };
7555
7556 let has_completion = self.active_inline_completion.is_some();
7557
7558 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7559 Some(
7560 h_flex()
7561 .min_w(min_width)
7562 .max_w(max_width)
7563 .flex_1()
7564 .elevation_2(cx)
7565 .border_color(cx.theme().colors().border)
7566 .child(
7567 div()
7568 .flex_1()
7569 .py_1()
7570 .px_2()
7571 .overflow_hidden()
7572 .child(completion),
7573 )
7574 .when_some(accept_keystroke, |el, accept_keystroke| {
7575 if !accept_keystroke.modifiers.modified() {
7576 return el;
7577 }
7578
7579 el.child(
7580 h_flex()
7581 .h_full()
7582 .border_l_1()
7583 .rounded_r_lg()
7584 .border_color(cx.theme().colors().border)
7585 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7586 .gap_1()
7587 .py_1()
7588 .px_2()
7589 .child(
7590 h_flex()
7591 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7592 .when(is_platform_style_mac, |parent| parent.gap_1())
7593 .child(h_flex().children(ui::render_modifiers(
7594 &accept_keystroke.modifiers,
7595 PlatformStyle::platform(),
7596 Some(if !has_completion {
7597 Color::Muted
7598 } else {
7599 Color::Default
7600 }),
7601 None,
7602 false,
7603 ))),
7604 )
7605 .child(Label::new("Preview").into_any_element())
7606 .opacity(if has_completion { 1.0 } else { 0.4 }),
7607 )
7608 })
7609 .into_any(),
7610 )
7611 }
7612
7613 fn render_edit_prediction_cursor_popover_preview(
7614 &self,
7615 completion: &InlineCompletionState,
7616 cursor_point: Point,
7617 style: &EditorStyle,
7618 cx: &mut Context<Editor>,
7619 ) -> Option<Div> {
7620 use text::ToPoint as _;
7621
7622 fn render_relative_row_jump(
7623 prefix: impl Into<String>,
7624 current_row: u32,
7625 target_row: u32,
7626 ) -> Div {
7627 let (row_diff, arrow) = if target_row < current_row {
7628 (current_row - target_row, IconName::ArrowUp)
7629 } else {
7630 (target_row - current_row, IconName::ArrowDown)
7631 };
7632
7633 h_flex()
7634 .child(
7635 Label::new(format!("{}{}", prefix.into(), row_diff))
7636 .color(Color::Muted)
7637 .size(LabelSize::Small),
7638 )
7639 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7640 }
7641
7642 match &completion.completion {
7643 InlineCompletion::Move {
7644 target, snapshot, ..
7645 } => Some(
7646 h_flex()
7647 .px_2()
7648 .gap_2()
7649 .flex_1()
7650 .child(
7651 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7652 Icon::new(IconName::ZedPredictDown)
7653 } else {
7654 Icon::new(IconName::ZedPredictUp)
7655 },
7656 )
7657 .child(Label::new("Jump to Edit")),
7658 ),
7659
7660 InlineCompletion::Edit {
7661 edits,
7662 edit_preview,
7663 snapshot,
7664 display_mode: _,
7665 } => {
7666 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7667
7668 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7669 &snapshot,
7670 &edits,
7671 edit_preview.as_ref()?,
7672 true,
7673 cx,
7674 )
7675 .first_line_preview();
7676
7677 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7678 .with_default_highlights(&style.text, highlighted_edits.highlights);
7679
7680 let preview = h_flex()
7681 .gap_1()
7682 .min_w_16()
7683 .child(styled_text)
7684 .when(has_more_lines, |parent| parent.child("…"));
7685
7686 let left = if first_edit_row != cursor_point.row {
7687 render_relative_row_jump("", cursor_point.row, first_edit_row)
7688 .into_any_element()
7689 } else {
7690 Icon::new(IconName::ZedPredict).into_any_element()
7691 };
7692
7693 Some(
7694 h_flex()
7695 .h_full()
7696 .flex_1()
7697 .gap_2()
7698 .pr_1()
7699 .overflow_x_hidden()
7700 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7701 .child(left)
7702 .child(preview),
7703 )
7704 }
7705 }
7706 }
7707
7708 fn render_context_menu(
7709 &self,
7710 style: &EditorStyle,
7711 max_height_in_lines: u32,
7712 window: &mut Window,
7713 cx: &mut Context<Editor>,
7714 ) -> Option<AnyElement> {
7715 let menu = self.context_menu.borrow();
7716 let menu = menu.as_ref()?;
7717 if !menu.visible() {
7718 return None;
7719 };
7720 Some(menu.render(style, max_height_in_lines, window, cx))
7721 }
7722
7723 fn render_context_menu_aside(
7724 &mut self,
7725 max_size: Size<Pixels>,
7726 window: &mut Window,
7727 cx: &mut Context<Editor>,
7728 ) -> Option<AnyElement> {
7729 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7730 if menu.visible() {
7731 menu.render_aside(self, max_size, window, cx)
7732 } else {
7733 None
7734 }
7735 })
7736 }
7737
7738 fn hide_context_menu(
7739 &mut self,
7740 window: &mut Window,
7741 cx: &mut Context<Self>,
7742 ) -> Option<CodeContextMenu> {
7743 cx.notify();
7744 self.completion_tasks.clear();
7745 let context_menu = self.context_menu.borrow_mut().take();
7746 self.stale_inline_completion_in_menu.take();
7747 self.update_visible_inline_completion(window, cx);
7748 context_menu
7749 }
7750
7751 fn show_snippet_choices(
7752 &mut self,
7753 choices: &Vec<String>,
7754 selection: Range<Anchor>,
7755 cx: &mut Context<Self>,
7756 ) {
7757 if selection.start.buffer_id.is_none() {
7758 return;
7759 }
7760 let buffer_id = selection.start.buffer_id.unwrap();
7761 let buffer = self.buffer().read(cx).buffer(buffer_id);
7762 let id = post_inc(&mut self.next_completion_id);
7763
7764 if let Some(buffer) = buffer {
7765 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7766 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7767 ));
7768 }
7769 }
7770
7771 pub fn insert_snippet(
7772 &mut self,
7773 insertion_ranges: &[Range<usize>],
7774 snippet: Snippet,
7775 window: &mut Window,
7776 cx: &mut Context<Self>,
7777 ) -> Result<()> {
7778 struct Tabstop<T> {
7779 is_end_tabstop: bool,
7780 ranges: Vec<Range<T>>,
7781 choices: Option<Vec<String>>,
7782 }
7783
7784 let tabstops = self.buffer.update(cx, |buffer, cx| {
7785 let snippet_text: Arc<str> = snippet.text.clone().into();
7786 let edits = insertion_ranges
7787 .iter()
7788 .cloned()
7789 .map(|range| (range, snippet_text.clone()));
7790 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7791
7792 let snapshot = &*buffer.read(cx);
7793 let snippet = &snippet;
7794 snippet
7795 .tabstops
7796 .iter()
7797 .map(|tabstop| {
7798 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7799 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7800 });
7801 let mut tabstop_ranges = tabstop
7802 .ranges
7803 .iter()
7804 .flat_map(|tabstop_range| {
7805 let mut delta = 0_isize;
7806 insertion_ranges.iter().map(move |insertion_range| {
7807 let insertion_start = insertion_range.start as isize + delta;
7808 delta +=
7809 snippet.text.len() as isize - insertion_range.len() as isize;
7810
7811 let start = ((insertion_start + tabstop_range.start) as usize)
7812 .min(snapshot.len());
7813 let end = ((insertion_start + tabstop_range.end) as usize)
7814 .min(snapshot.len());
7815 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7816 })
7817 })
7818 .collect::<Vec<_>>();
7819 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7820
7821 Tabstop {
7822 is_end_tabstop,
7823 ranges: tabstop_ranges,
7824 choices: tabstop.choices.clone(),
7825 }
7826 })
7827 .collect::<Vec<_>>()
7828 });
7829 if let Some(tabstop) = tabstops.first() {
7830 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7831 s.select_ranges(tabstop.ranges.iter().cloned());
7832 });
7833
7834 if let Some(choices) = &tabstop.choices {
7835 if let Some(selection) = tabstop.ranges.first() {
7836 self.show_snippet_choices(choices, selection.clone(), cx)
7837 }
7838 }
7839
7840 // If we're already at the last tabstop and it's at the end of the snippet,
7841 // we're done, we don't need to keep the state around.
7842 if !tabstop.is_end_tabstop {
7843 let choices = tabstops
7844 .iter()
7845 .map(|tabstop| tabstop.choices.clone())
7846 .collect();
7847
7848 let ranges = tabstops
7849 .into_iter()
7850 .map(|tabstop| tabstop.ranges)
7851 .collect::<Vec<_>>();
7852
7853 self.snippet_stack.push(SnippetState {
7854 active_index: 0,
7855 ranges,
7856 choices,
7857 });
7858 }
7859
7860 // Check whether the just-entered snippet ends with an auto-closable bracket.
7861 if self.autoclose_regions.is_empty() {
7862 let snapshot = self.buffer.read(cx).snapshot(cx);
7863 for selection in &mut self.selections.all::<Point>(cx) {
7864 let selection_head = selection.head();
7865 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7866 continue;
7867 };
7868
7869 let mut bracket_pair = None;
7870 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7871 let prev_chars = snapshot
7872 .reversed_chars_at(selection_head)
7873 .collect::<String>();
7874 for (pair, enabled) in scope.brackets() {
7875 if enabled
7876 && pair.close
7877 && prev_chars.starts_with(pair.start.as_str())
7878 && next_chars.starts_with(pair.end.as_str())
7879 {
7880 bracket_pair = Some(pair.clone());
7881 break;
7882 }
7883 }
7884 if let Some(pair) = bracket_pair {
7885 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
7886 let autoclose_enabled =
7887 self.use_autoclose && snapshot_settings.use_autoclose;
7888 if autoclose_enabled {
7889 let start = snapshot.anchor_after(selection_head);
7890 let end = snapshot.anchor_after(selection_head);
7891 self.autoclose_regions.push(AutocloseRegion {
7892 selection_id: selection.id,
7893 range: start..end,
7894 pair,
7895 });
7896 }
7897 }
7898 }
7899 }
7900 }
7901 Ok(())
7902 }
7903
7904 pub fn move_to_next_snippet_tabstop(
7905 &mut self,
7906 window: &mut Window,
7907 cx: &mut Context<Self>,
7908 ) -> bool {
7909 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7910 }
7911
7912 pub fn move_to_prev_snippet_tabstop(
7913 &mut self,
7914 window: &mut Window,
7915 cx: &mut Context<Self>,
7916 ) -> bool {
7917 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7918 }
7919
7920 pub fn move_to_snippet_tabstop(
7921 &mut self,
7922 bias: Bias,
7923 window: &mut Window,
7924 cx: &mut Context<Self>,
7925 ) -> bool {
7926 if let Some(mut snippet) = self.snippet_stack.pop() {
7927 match bias {
7928 Bias::Left => {
7929 if snippet.active_index > 0 {
7930 snippet.active_index -= 1;
7931 } else {
7932 self.snippet_stack.push(snippet);
7933 return false;
7934 }
7935 }
7936 Bias::Right => {
7937 if snippet.active_index + 1 < snippet.ranges.len() {
7938 snippet.active_index += 1;
7939 } else {
7940 self.snippet_stack.push(snippet);
7941 return false;
7942 }
7943 }
7944 }
7945 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7946 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7947 s.select_anchor_ranges(current_ranges.iter().cloned())
7948 });
7949
7950 if let Some(choices) = &snippet.choices[snippet.active_index] {
7951 if let Some(selection) = current_ranges.first() {
7952 self.show_snippet_choices(&choices, selection.clone(), cx);
7953 }
7954 }
7955
7956 // If snippet state is not at the last tabstop, push it back on the stack
7957 if snippet.active_index + 1 < snippet.ranges.len() {
7958 self.snippet_stack.push(snippet);
7959 }
7960 return true;
7961 }
7962 }
7963
7964 false
7965 }
7966
7967 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7968 self.transact(window, cx, |this, window, cx| {
7969 this.select_all(&SelectAll, window, cx);
7970 this.insert("", window, cx);
7971 });
7972 }
7973
7974 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7975 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
7976 self.transact(window, cx, |this, window, cx| {
7977 this.select_autoclose_pair(window, cx);
7978 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7979 if !this.linked_edit_ranges.is_empty() {
7980 let selections = this.selections.all::<MultiBufferPoint>(cx);
7981 let snapshot = this.buffer.read(cx).snapshot(cx);
7982
7983 for selection in selections.iter() {
7984 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7985 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7986 if selection_start.buffer_id != selection_end.buffer_id {
7987 continue;
7988 }
7989 if let Some(ranges) =
7990 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7991 {
7992 for (buffer, entries) in ranges {
7993 linked_ranges.entry(buffer).or_default().extend(entries);
7994 }
7995 }
7996 }
7997 }
7998
7999 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8000 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8001 for selection in &mut selections {
8002 if selection.is_empty() {
8003 let old_head = selection.head();
8004 let mut new_head =
8005 movement::left(&display_map, old_head.to_display_point(&display_map))
8006 .to_point(&display_map);
8007 if let Some((buffer, line_buffer_range)) = display_map
8008 .buffer_snapshot
8009 .buffer_line_for_row(MultiBufferRow(old_head.row))
8010 {
8011 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8012 let indent_len = match indent_size.kind {
8013 IndentKind::Space => {
8014 buffer.settings_at(line_buffer_range.start, cx).tab_size
8015 }
8016 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8017 };
8018 if old_head.column <= indent_size.len && old_head.column > 0 {
8019 let indent_len = indent_len.get();
8020 new_head = cmp::min(
8021 new_head,
8022 MultiBufferPoint::new(
8023 old_head.row,
8024 ((old_head.column - 1) / indent_len) * indent_len,
8025 ),
8026 );
8027 }
8028 }
8029
8030 selection.set_head(new_head, SelectionGoal::None);
8031 }
8032 }
8033
8034 this.signature_help_state.set_backspace_pressed(true);
8035 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8036 s.select(selections)
8037 });
8038 this.insert("", window, cx);
8039 let empty_str: Arc<str> = Arc::from("");
8040 for (buffer, edits) in linked_ranges {
8041 let snapshot = buffer.read(cx).snapshot();
8042 use text::ToPoint as TP;
8043
8044 let edits = edits
8045 .into_iter()
8046 .map(|range| {
8047 let end_point = TP::to_point(&range.end, &snapshot);
8048 let mut start_point = TP::to_point(&range.start, &snapshot);
8049
8050 if end_point == start_point {
8051 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8052 .saturating_sub(1);
8053 start_point =
8054 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8055 };
8056
8057 (start_point..end_point, empty_str.clone())
8058 })
8059 .sorted_by_key(|(range, _)| range.start)
8060 .collect::<Vec<_>>();
8061 buffer.update(cx, |this, cx| {
8062 this.edit(edits, None, cx);
8063 })
8064 }
8065 this.refresh_inline_completion(true, false, window, cx);
8066 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8067 });
8068 }
8069
8070 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8071 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8072 self.transact(window, cx, |this, window, cx| {
8073 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8074 s.move_with(|map, selection| {
8075 if selection.is_empty() {
8076 let cursor = movement::right(map, selection.head());
8077 selection.end = cursor;
8078 selection.reversed = true;
8079 selection.goal = SelectionGoal::None;
8080 }
8081 })
8082 });
8083 this.insert("", window, cx);
8084 this.refresh_inline_completion(true, false, window, cx);
8085 });
8086 }
8087
8088 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8089 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8090 if self.move_to_prev_snippet_tabstop(window, cx) {
8091 return;
8092 }
8093 self.outdent(&Outdent, window, cx);
8094 }
8095
8096 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8097 if self.move_to_next_snippet_tabstop(window, cx) {
8098 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8099 return;
8100 }
8101 if self.read_only(cx) {
8102 return;
8103 }
8104 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8105 let mut selections = self.selections.all_adjusted(cx);
8106 let buffer = self.buffer.read(cx);
8107 let snapshot = buffer.snapshot(cx);
8108 let rows_iter = selections.iter().map(|s| s.head().row);
8109 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8110
8111 let mut edits = Vec::new();
8112 let mut prev_edited_row = 0;
8113 let mut row_delta = 0;
8114 for selection in &mut selections {
8115 if selection.start.row != prev_edited_row {
8116 row_delta = 0;
8117 }
8118 prev_edited_row = selection.end.row;
8119
8120 // If the selection is non-empty, then increase the indentation of the selected lines.
8121 if !selection.is_empty() {
8122 row_delta =
8123 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8124 continue;
8125 }
8126
8127 // If the selection is empty and the cursor is in the leading whitespace before the
8128 // suggested indentation, then auto-indent the line.
8129 let cursor = selection.head();
8130 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8131 if let Some(suggested_indent) =
8132 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8133 {
8134 if cursor.column < suggested_indent.len
8135 && cursor.column <= current_indent.len
8136 && current_indent.len <= suggested_indent.len
8137 {
8138 selection.start = Point::new(cursor.row, suggested_indent.len);
8139 selection.end = selection.start;
8140 if row_delta == 0 {
8141 edits.extend(Buffer::edit_for_indent_size_adjustment(
8142 cursor.row,
8143 current_indent,
8144 suggested_indent,
8145 ));
8146 row_delta = suggested_indent.len - current_indent.len;
8147 }
8148 continue;
8149 }
8150 }
8151
8152 // Otherwise, insert a hard or soft tab.
8153 let settings = buffer.language_settings_at(cursor, cx);
8154 let tab_size = if settings.hard_tabs {
8155 IndentSize::tab()
8156 } else {
8157 let tab_size = settings.tab_size.get();
8158 let char_column = snapshot
8159 .text_for_range(Point::new(cursor.row, 0)..cursor)
8160 .flat_map(str::chars)
8161 .count()
8162 + row_delta as usize;
8163 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
8164 IndentSize::spaces(chars_to_next_tab_stop)
8165 };
8166 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8167 selection.end = selection.start;
8168 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8169 row_delta += tab_size.len;
8170 }
8171
8172 self.transact(window, cx, |this, window, cx| {
8173 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8174 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8175 s.select(selections)
8176 });
8177 this.refresh_inline_completion(true, false, window, cx);
8178 });
8179 }
8180
8181 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8182 if self.read_only(cx) {
8183 return;
8184 }
8185 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8186 let mut selections = self.selections.all::<Point>(cx);
8187 let mut prev_edited_row = 0;
8188 let mut row_delta = 0;
8189 let mut edits = Vec::new();
8190 let buffer = self.buffer.read(cx);
8191 let snapshot = buffer.snapshot(cx);
8192 for selection in &mut selections {
8193 if selection.start.row != prev_edited_row {
8194 row_delta = 0;
8195 }
8196 prev_edited_row = selection.end.row;
8197
8198 row_delta =
8199 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8200 }
8201
8202 self.transact(window, cx, |this, window, cx| {
8203 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8204 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8205 s.select(selections)
8206 });
8207 });
8208 }
8209
8210 fn indent_selection(
8211 buffer: &MultiBuffer,
8212 snapshot: &MultiBufferSnapshot,
8213 selection: &mut Selection<Point>,
8214 edits: &mut Vec<(Range<Point>, String)>,
8215 delta_for_start_row: u32,
8216 cx: &App,
8217 ) -> u32 {
8218 let settings = buffer.language_settings_at(selection.start, cx);
8219 let tab_size = settings.tab_size.get();
8220 let indent_kind = if settings.hard_tabs {
8221 IndentKind::Tab
8222 } else {
8223 IndentKind::Space
8224 };
8225 let mut start_row = selection.start.row;
8226 let mut end_row = selection.end.row + 1;
8227
8228 // If a selection ends at the beginning of a line, don't indent
8229 // that last line.
8230 if selection.end.column == 0 && selection.end.row > selection.start.row {
8231 end_row -= 1;
8232 }
8233
8234 // Avoid re-indenting a row that has already been indented by a
8235 // previous selection, but still update this selection's column
8236 // to reflect that indentation.
8237 if delta_for_start_row > 0 {
8238 start_row += 1;
8239 selection.start.column += delta_for_start_row;
8240 if selection.end.row == selection.start.row {
8241 selection.end.column += delta_for_start_row;
8242 }
8243 }
8244
8245 let mut delta_for_end_row = 0;
8246 let has_multiple_rows = start_row + 1 != end_row;
8247 for row in start_row..end_row {
8248 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8249 let indent_delta = match (current_indent.kind, indent_kind) {
8250 (IndentKind::Space, IndentKind::Space) => {
8251 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8252 IndentSize::spaces(columns_to_next_tab_stop)
8253 }
8254 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8255 (_, IndentKind::Tab) => IndentSize::tab(),
8256 };
8257
8258 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8259 0
8260 } else {
8261 selection.start.column
8262 };
8263 let row_start = Point::new(row, start);
8264 edits.push((
8265 row_start..row_start,
8266 indent_delta.chars().collect::<String>(),
8267 ));
8268
8269 // Update this selection's endpoints to reflect the indentation.
8270 if row == selection.start.row {
8271 selection.start.column += indent_delta.len;
8272 }
8273 if row == selection.end.row {
8274 selection.end.column += indent_delta.len;
8275 delta_for_end_row = indent_delta.len;
8276 }
8277 }
8278
8279 if selection.start.row == selection.end.row {
8280 delta_for_start_row + delta_for_end_row
8281 } else {
8282 delta_for_end_row
8283 }
8284 }
8285
8286 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8287 if self.read_only(cx) {
8288 return;
8289 }
8290 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8291 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8292 let selections = self.selections.all::<Point>(cx);
8293 let mut deletion_ranges = Vec::new();
8294 let mut last_outdent = None;
8295 {
8296 let buffer = self.buffer.read(cx);
8297 let snapshot = buffer.snapshot(cx);
8298 for selection in &selections {
8299 let settings = buffer.language_settings_at(selection.start, cx);
8300 let tab_size = settings.tab_size.get();
8301 let mut rows = selection.spanned_rows(false, &display_map);
8302
8303 // Avoid re-outdenting a row that has already been outdented by a
8304 // previous selection.
8305 if let Some(last_row) = last_outdent {
8306 if last_row == rows.start {
8307 rows.start = rows.start.next_row();
8308 }
8309 }
8310 let has_multiple_rows = rows.len() > 1;
8311 for row in rows.iter_rows() {
8312 let indent_size = snapshot.indent_size_for_line(row);
8313 if indent_size.len > 0 {
8314 let deletion_len = match indent_size.kind {
8315 IndentKind::Space => {
8316 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8317 if columns_to_prev_tab_stop == 0 {
8318 tab_size
8319 } else {
8320 columns_to_prev_tab_stop
8321 }
8322 }
8323 IndentKind::Tab => 1,
8324 };
8325 let start = if has_multiple_rows
8326 || deletion_len > selection.start.column
8327 || indent_size.len < selection.start.column
8328 {
8329 0
8330 } else {
8331 selection.start.column - deletion_len
8332 };
8333 deletion_ranges.push(
8334 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8335 );
8336 last_outdent = Some(row);
8337 }
8338 }
8339 }
8340 }
8341
8342 self.transact(window, cx, |this, window, cx| {
8343 this.buffer.update(cx, |buffer, cx| {
8344 let empty_str: Arc<str> = Arc::default();
8345 buffer.edit(
8346 deletion_ranges
8347 .into_iter()
8348 .map(|range| (range, empty_str.clone())),
8349 None,
8350 cx,
8351 );
8352 });
8353 let selections = this.selections.all::<usize>(cx);
8354 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8355 s.select(selections)
8356 });
8357 });
8358 }
8359
8360 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8361 if self.read_only(cx) {
8362 return;
8363 }
8364 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8365 let selections = self
8366 .selections
8367 .all::<usize>(cx)
8368 .into_iter()
8369 .map(|s| s.range());
8370
8371 self.transact(window, cx, |this, window, cx| {
8372 this.buffer.update(cx, |buffer, cx| {
8373 buffer.autoindent_ranges(selections, cx);
8374 });
8375 let selections = this.selections.all::<usize>(cx);
8376 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8377 s.select(selections)
8378 });
8379 });
8380 }
8381
8382 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8383 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8384 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8385 let selections = self.selections.all::<Point>(cx);
8386
8387 let mut new_cursors = Vec::new();
8388 let mut edit_ranges = Vec::new();
8389 let mut selections = selections.iter().peekable();
8390 while let Some(selection) = selections.next() {
8391 let mut rows = selection.spanned_rows(false, &display_map);
8392 let goal_display_column = selection.head().to_display_point(&display_map).column();
8393
8394 // Accumulate contiguous regions of rows that we want to delete.
8395 while let Some(next_selection) = selections.peek() {
8396 let next_rows = next_selection.spanned_rows(false, &display_map);
8397 if next_rows.start <= rows.end {
8398 rows.end = next_rows.end;
8399 selections.next().unwrap();
8400 } else {
8401 break;
8402 }
8403 }
8404
8405 let buffer = &display_map.buffer_snapshot;
8406 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8407 let edit_end;
8408 let cursor_buffer_row;
8409 if buffer.max_point().row >= rows.end.0 {
8410 // If there's a line after the range, delete the \n from the end of the row range
8411 // and position the cursor on the next line.
8412 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8413 cursor_buffer_row = rows.end;
8414 } else {
8415 // If there isn't a line after the range, delete the \n from the line before the
8416 // start of the row range and position the cursor there.
8417 edit_start = edit_start.saturating_sub(1);
8418 edit_end = buffer.len();
8419 cursor_buffer_row = rows.start.previous_row();
8420 }
8421
8422 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8423 *cursor.column_mut() =
8424 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8425
8426 new_cursors.push((
8427 selection.id,
8428 buffer.anchor_after(cursor.to_point(&display_map)),
8429 ));
8430 edit_ranges.push(edit_start..edit_end);
8431 }
8432
8433 self.transact(window, cx, |this, window, cx| {
8434 let buffer = this.buffer.update(cx, |buffer, cx| {
8435 let empty_str: Arc<str> = Arc::default();
8436 buffer.edit(
8437 edit_ranges
8438 .into_iter()
8439 .map(|range| (range, empty_str.clone())),
8440 None,
8441 cx,
8442 );
8443 buffer.snapshot(cx)
8444 });
8445 let new_selections = new_cursors
8446 .into_iter()
8447 .map(|(id, cursor)| {
8448 let cursor = cursor.to_point(&buffer);
8449 Selection {
8450 id,
8451 start: cursor,
8452 end: cursor,
8453 reversed: false,
8454 goal: SelectionGoal::None,
8455 }
8456 })
8457 .collect();
8458
8459 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8460 s.select(new_selections);
8461 });
8462 });
8463 }
8464
8465 pub fn join_lines_impl(
8466 &mut self,
8467 insert_whitespace: bool,
8468 window: &mut Window,
8469 cx: &mut Context<Self>,
8470 ) {
8471 if self.read_only(cx) {
8472 return;
8473 }
8474 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8475 for selection in self.selections.all::<Point>(cx) {
8476 let start = MultiBufferRow(selection.start.row);
8477 // Treat single line selections as if they include the next line. Otherwise this action
8478 // would do nothing for single line selections individual cursors.
8479 let end = if selection.start.row == selection.end.row {
8480 MultiBufferRow(selection.start.row + 1)
8481 } else {
8482 MultiBufferRow(selection.end.row)
8483 };
8484
8485 if let Some(last_row_range) = row_ranges.last_mut() {
8486 if start <= last_row_range.end {
8487 last_row_range.end = end;
8488 continue;
8489 }
8490 }
8491 row_ranges.push(start..end);
8492 }
8493
8494 let snapshot = self.buffer.read(cx).snapshot(cx);
8495 let mut cursor_positions = Vec::new();
8496 for row_range in &row_ranges {
8497 let anchor = snapshot.anchor_before(Point::new(
8498 row_range.end.previous_row().0,
8499 snapshot.line_len(row_range.end.previous_row()),
8500 ));
8501 cursor_positions.push(anchor..anchor);
8502 }
8503
8504 self.transact(window, cx, |this, window, cx| {
8505 for row_range in row_ranges.into_iter().rev() {
8506 for row in row_range.iter_rows().rev() {
8507 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8508 let next_line_row = row.next_row();
8509 let indent = snapshot.indent_size_for_line(next_line_row);
8510 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8511
8512 let replace =
8513 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8514 " "
8515 } else {
8516 ""
8517 };
8518
8519 this.buffer.update(cx, |buffer, cx| {
8520 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8521 });
8522 }
8523 }
8524
8525 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8526 s.select_anchor_ranges(cursor_positions)
8527 });
8528 });
8529 }
8530
8531 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8532 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8533 self.join_lines_impl(true, window, cx);
8534 }
8535
8536 pub fn sort_lines_case_sensitive(
8537 &mut self,
8538 _: &SortLinesCaseSensitive,
8539 window: &mut Window,
8540 cx: &mut Context<Self>,
8541 ) {
8542 self.manipulate_lines(window, cx, |lines| lines.sort())
8543 }
8544
8545 pub fn sort_lines_case_insensitive(
8546 &mut self,
8547 _: &SortLinesCaseInsensitive,
8548 window: &mut Window,
8549 cx: &mut Context<Self>,
8550 ) {
8551 self.manipulate_lines(window, cx, |lines| {
8552 lines.sort_by_key(|line| line.to_lowercase())
8553 })
8554 }
8555
8556 pub fn unique_lines_case_insensitive(
8557 &mut self,
8558 _: &UniqueLinesCaseInsensitive,
8559 window: &mut Window,
8560 cx: &mut Context<Self>,
8561 ) {
8562 self.manipulate_lines(window, cx, |lines| {
8563 let mut seen = HashSet::default();
8564 lines.retain(|line| seen.insert(line.to_lowercase()));
8565 })
8566 }
8567
8568 pub fn unique_lines_case_sensitive(
8569 &mut self,
8570 _: &UniqueLinesCaseSensitive,
8571 window: &mut Window,
8572 cx: &mut Context<Self>,
8573 ) {
8574 self.manipulate_lines(window, cx, |lines| {
8575 let mut seen = HashSet::default();
8576 lines.retain(|line| seen.insert(*line));
8577 })
8578 }
8579
8580 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8581 let Some(project) = self.project.clone() else {
8582 return;
8583 };
8584 self.reload(project, window, cx)
8585 .detach_and_notify_err(window, cx);
8586 }
8587
8588 pub fn restore_file(
8589 &mut self,
8590 _: &::git::RestoreFile,
8591 window: &mut Window,
8592 cx: &mut Context<Self>,
8593 ) {
8594 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8595 let mut buffer_ids = HashSet::default();
8596 let snapshot = self.buffer().read(cx).snapshot(cx);
8597 for selection in self.selections.all::<usize>(cx) {
8598 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8599 }
8600
8601 let buffer = self.buffer().read(cx);
8602 let ranges = buffer_ids
8603 .into_iter()
8604 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8605 .collect::<Vec<_>>();
8606
8607 self.restore_hunks_in_ranges(ranges, window, cx);
8608 }
8609
8610 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8611 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8612 let selections = self
8613 .selections
8614 .all(cx)
8615 .into_iter()
8616 .map(|s| s.range())
8617 .collect();
8618 self.restore_hunks_in_ranges(selections, window, cx);
8619 }
8620
8621 pub fn restore_hunks_in_ranges(
8622 &mut self,
8623 ranges: Vec<Range<Point>>,
8624 window: &mut Window,
8625 cx: &mut Context<Editor>,
8626 ) {
8627 let mut revert_changes = HashMap::default();
8628 let chunk_by = self
8629 .snapshot(window, cx)
8630 .hunks_for_ranges(ranges)
8631 .into_iter()
8632 .chunk_by(|hunk| hunk.buffer_id);
8633 for (buffer_id, hunks) in &chunk_by {
8634 let hunks = hunks.collect::<Vec<_>>();
8635 for hunk in &hunks {
8636 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8637 }
8638 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8639 }
8640 drop(chunk_by);
8641 if !revert_changes.is_empty() {
8642 self.transact(window, cx, |editor, window, cx| {
8643 editor.restore(revert_changes, window, cx);
8644 });
8645 }
8646 }
8647
8648 pub fn open_active_item_in_terminal(
8649 &mut self,
8650 _: &OpenInTerminal,
8651 window: &mut Window,
8652 cx: &mut Context<Self>,
8653 ) {
8654 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8655 let project_path = buffer.read(cx).project_path(cx)?;
8656 let project = self.project.as_ref()?.read(cx);
8657 let entry = project.entry_for_path(&project_path, cx)?;
8658 let parent = match &entry.canonical_path {
8659 Some(canonical_path) => canonical_path.to_path_buf(),
8660 None => project.absolute_path(&project_path, cx)?,
8661 }
8662 .parent()?
8663 .to_path_buf();
8664 Some(parent)
8665 }) {
8666 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8667 }
8668 }
8669
8670 fn set_breakpoint_context_menu(
8671 &mut self,
8672 display_row: DisplayRow,
8673 position: Option<Anchor>,
8674 clicked_point: gpui::Point<Pixels>,
8675 window: &mut Window,
8676 cx: &mut Context<Self>,
8677 ) {
8678 if !cx.has_flag::<Debugger>() {
8679 return;
8680 }
8681 let source = self
8682 .buffer
8683 .read(cx)
8684 .snapshot(cx)
8685 .anchor_before(Point::new(display_row.0, 0u32));
8686
8687 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8688
8689 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8690 self,
8691 source,
8692 clicked_point,
8693 context_menu,
8694 window,
8695 cx,
8696 );
8697 }
8698
8699 fn add_edit_breakpoint_block(
8700 &mut self,
8701 anchor: Anchor,
8702 breakpoint: &Breakpoint,
8703 edit_action: BreakpointPromptEditAction,
8704 window: &mut Window,
8705 cx: &mut Context<Self>,
8706 ) {
8707 let weak_editor = cx.weak_entity();
8708 let bp_prompt = cx.new(|cx| {
8709 BreakpointPromptEditor::new(
8710 weak_editor,
8711 anchor,
8712 breakpoint.clone(),
8713 edit_action,
8714 window,
8715 cx,
8716 )
8717 });
8718
8719 let height = bp_prompt.update(cx, |this, cx| {
8720 this.prompt
8721 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8722 });
8723 let cloned_prompt = bp_prompt.clone();
8724 let blocks = vec![BlockProperties {
8725 style: BlockStyle::Sticky,
8726 placement: BlockPlacement::Above(anchor),
8727 height: Some(height),
8728 render: Arc::new(move |cx| {
8729 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8730 cloned_prompt.clone().into_any_element()
8731 }),
8732 priority: 0,
8733 }];
8734
8735 let focus_handle = bp_prompt.focus_handle(cx);
8736 window.focus(&focus_handle);
8737
8738 let block_ids = self.insert_blocks(blocks, None, cx);
8739 bp_prompt.update(cx, |prompt, _| {
8740 prompt.add_block_ids(block_ids);
8741 });
8742 }
8743
8744 fn breakpoint_at_cursor_head(
8745 &self,
8746 window: &mut Window,
8747 cx: &mut Context<Self>,
8748 ) -> Option<(Anchor, Breakpoint)> {
8749 let cursor_position: Point = self.selections.newest(cx).head();
8750 self.breakpoint_at_row(cursor_position.row, window, cx)
8751 }
8752
8753 pub(crate) fn breakpoint_at_row(
8754 &self,
8755 row: u32,
8756 window: &mut Window,
8757 cx: &mut Context<Self>,
8758 ) -> Option<(Anchor, Breakpoint)> {
8759 let snapshot = self.snapshot(window, cx);
8760 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8761
8762 let project = self.project.clone()?;
8763
8764 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8765 snapshot
8766 .buffer_snapshot
8767 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8768 })?;
8769
8770 let enclosing_excerpt = breakpoint_position.excerpt_id;
8771 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8772 let buffer_snapshot = buffer.read(cx).snapshot();
8773
8774 let row = buffer_snapshot
8775 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8776 .row;
8777
8778 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8779 let anchor_end = snapshot
8780 .buffer_snapshot
8781 .anchor_after(Point::new(row, line_len));
8782
8783 let bp = self
8784 .breakpoint_store
8785 .as_ref()?
8786 .read_with(cx, |breakpoint_store, cx| {
8787 breakpoint_store
8788 .breakpoints(
8789 &buffer,
8790 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8791 &buffer_snapshot,
8792 cx,
8793 )
8794 .next()
8795 .and_then(|(anchor, bp)| {
8796 let breakpoint_row = buffer_snapshot
8797 .summary_for_anchor::<text::PointUtf16>(anchor)
8798 .row;
8799
8800 if breakpoint_row == row {
8801 snapshot
8802 .buffer_snapshot
8803 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8804 .map(|anchor| (anchor, bp.clone()))
8805 } else {
8806 None
8807 }
8808 })
8809 });
8810 bp
8811 }
8812
8813 pub fn edit_log_breakpoint(
8814 &mut self,
8815 _: &EditLogBreakpoint,
8816 window: &mut Window,
8817 cx: &mut Context<Self>,
8818 ) {
8819 let (anchor, bp) = self
8820 .breakpoint_at_cursor_head(window, cx)
8821 .unwrap_or_else(|| {
8822 let cursor_position: Point = self.selections.newest(cx).head();
8823
8824 let breakpoint_position = self
8825 .snapshot(window, cx)
8826 .display_snapshot
8827 .buffer_snapshot
8828 .anchor_after(Point::new(cursor_position.row, 0));
8829
8830 (
8831 breakpoint_position,
8832 Breakpoint {
8833 message: None,
8834 state: BreakpointState::Enabled,
8835 condition: None,
8836 hit_condition: None,
8837 },
8838 )
8839 });
8840
8841 self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
8842 }
8843
8844 pub fn enable_breakpoint(
8845 &mut self,
8846 _: &crate::actions::EnableBreakpoint,
8847 window: &mut Window,
8848 cx: &mut Context<Self>,
8849 ) {
8850 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8851 if breakpoint.is_disabled() {
8852 self.edit_breakpoint_at_anchor(
8853 anchor,
8854 breakpoint,
8855 BreakpointEditAction::InvertState,
8856 cx,
8857 );
8858 }
8859 }
8860 }
8861
8862 pub fn disable_breakpoint(
8863 &mut self,
8864 _: &crate::actions::DisableBreakpoint,
8865 window: &mut Window,
8866 cx: &mut Context<Self>,
8867 ) {
8868 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8869 if breakpoint.is_enabled() {
8870 self.edit_breakpoint_at_anchor(
8871 anchor,
8872 breakpoint,
8873 BreakpointEditAction::InvertState,
8874 cx,
8875 );
8876 }
8877 }
8878 }
8879
8880 pub fn toggle_breakpoint(
8881 &mut self,
8882 _: &crate::actions::ToggleBreakpoint,
8883 window: &mut Window,
8884 cx: &mut Context<Self>,
8885 ) {
8886 let edit_action = BreakpointEditAction::Toggle;
8887
8888 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8889 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8890 } else {
8891 let cursor_position: Point = self.selections.newest(cx).head();
8892
8893 let breakpoint_position = self
8894 .snapshot(window, cx)
8895 .display_snapshot
8896 .buffer_snapshot
8897 .anchor_after(Point::new(cursor_position.row, 0));
8898
8899 self.edit_breakpoint_at_anchor(
8900 breakpoint_position,
8901 Breakpoint::new_standard(),
8902 edit_action,
8903 cx,
8904 );
8905 }
8906 }
8907
8908 pub fn edit_breakpoint_at_anchor(
8909 &mut self,
8910 breakpoint_position: Anchor,
8911 breakpoint: Breakpoint,
8912 edit_action: BreakpointEditAction,
8913 cx: &mut Context<Self>,
8914 ) {
8915 let Some(breakpoint_store) = &self.breakpoint_store else {
8916 return;
8917 };
8918
8919 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8920 if breakpoint_position == Anchor::min() {
8921 self.buffer()
8922 .read(cx)
8923 .excerpt_buffer_ids()
8924 .into_iter()
8925 .next()
8926 } else {
8927 None
8928 }
8929 }) else {
8930 return;
8931 };
8932
8933 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8934 return;
8935 };
8936
8937 breakpoint_store.update(cx, |breakpoint_store, cx| {
8938 breakpoint_store.toggle_breakpoint(
8939 buffer,
8940 (breakpoint_position.text_anchor, breakpoint),
8941 edit_action,
8942 cx,
8943 );
8944 });
8945
8946 cx.notify();
8947 }
8948
8949 #[cfg(any(test, feature = "test-support"))]
8950 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8951 self.breakpoint_store.clone()
8952 }
8953
8954 pub fn prepare_restore_change(
8955 &self,
8956 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8957 hunk: &MultiBufferDiffHunk,
8958 cx: &mut App,
8959 ) -> Option<()> {
8960 if hunk.is_created_file() {
8961 return None;
8962 }
8963 let buffer = self.buffer.read(cx);
8964 let diff = buffer.diff_for(hunk.buffer_id)?;
8965 let buffer = buffer.buffer(hunk.buffer_id)?;
8966 let buffer = buffer.read(cx);
8967 let original_text = diff
8968 .read(cx)
8969 .base_text()
8970 .as_rope()
8971 .slice(hunk.diff_base_byte_range.clone());
8972 let buffer_snapshot = buffer.snapshot();
8973 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8974 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8975 probe
8976 .0
8977 .start
8978 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8979 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8980 }) {
8981 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8982 Some(())
8983 } else {
8984 None
8985 }
8986 }
8987
8988 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8989 self.manipulate_lines(window, cx, |lines| lines.reverse())
8990 }
8991
8992 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8993 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8994 }
8995
8996 fn manipulate_lines<Fn>(
8997 &mut self,
8998 window: &mut Window,
8999 cx: &mut Context<Self>,
9000 mut callback: Fn,
9001 ) where
9002 Fn: FnMut(&mut Vec<&str>),
9003 {
9004 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9005
9006 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9007 let buffer = self.buffer.read(cx).snapshot(cx);
9008
9009 let mut edits = Vec::new();
9010
9011 let selections = self.selections.all::<Point>(cx);
9012 let mut selections = selections.iter().peekable();
9013 let mut contiguous_row_selections = Vec::new();
9014 let mut new_selections = Vec::new();
9015 let mut added_lines = 0;
9016 let mut removed_lines = 0;
9017
9018 while let Some(selection) = selections.next() {
9019 let (start_row, end_row) = consume_contiguous_rows(
9020 &mut contiguous_row_selections,
9021 selection,
9022 &display_map,
9023 &mut selections,
9024 );
9025
9026 let start_point = Point::new(start_row.0, 0);
9027 let end_point = Point::new(
9028 end_row.previous_row().0,
9029 buffer.line_len(end_row.previous_row()),
9030 );
9031 let text = buffer
9032 .text_for_range(start_point..end_point)
9033 .collect::<String>();
9034
9035 let mut lines = text.split('\n').collect_vec();
9036
9037 let lines_before = lines.len();
9038 callback(&mut lines);
9039 let lines_after = lines.len();
9040
9041 edits.push((start_point..end_point, lines.join("\n")));
9042
9043 // Selections must change based on added and removed line count
9044 let start_row =
9045 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9046 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9047 new_selections.push(Selection {
9048 id: selection.id,
9049 start: start_row,
9050 end: end_row,
9051 goal: SelectionGoal::None,
9052 reversed: selection.reversed,
9053 });
9054
9055 if lines_after > lines_before {
9056 added_lines += lines_after - lines_before;
9057 } else if lines_before > lines_after {
9058 removed_lines += lines_before - lines_after;
9059 }
9060 }
9061
9062 self.transact(window, cx, |this, window, cx| {
9063 let buffer = this.buffer.update(cx, |buffer, cx| {
9064 buffer.edit(edits, None, cx);
9065 buffer.snapshot(cx)
9066 });
9067
9068 // Recalculate offsets on newly edited buffer
9069 let new_selections = new_selections
9070 .iter()
9071 .map(|s| {
9072 let start_point = Point::new(s.start.0, 0);
9073 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9074 Selection {
9075 id: s.id,
9076 start: buffer.point_to_offset(start_point),
9077 end: buffer.point_to_offset(end_point),
9078 goal: s.goal,
9079 reversed: s.reversed,
9080 }
9081 })
9082 .collect();
9083
9084 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9085 s.select(new_selections);
9086 });
9087
9088 this.request_autoscroll(Autoscroll::fit(), cx);
9089 });
9090 }
9091
9092 pub fn convert_to_upper_case(
9093 &mut self,
9094 _: &ConvertToUpperCase,
9095 window: &mut Window,
9096 cx: &mut Context<Self>,
9097 ) {
9098 self.manipulate_text(window, cx, |text| text.to_uppercase())
9099 }
9100
9101 pub fn convert_to_lower_case(
9102 &mut self,
9103 _: &ConvertToLowerCase,
9104 window: &mut Window,
9105 cx: &mut Context<Self>,
9106 ) {
9107 self.manipulate_text(window, cx, |text| text.to_lowercase())
9108 }
9109
9110 pub fn convert_to_title_case(
9111 &mut self,
9112 _: &ConvertToTitleCase,
9113 window: &mut Window,
9114 cx: &mut Context<Self>,
9115 ) {
9116 self.manipulate_text(window, cx, |text| {
9117 text.split('\n')
9118 .map(|line| line.to_case(Case::Title))
9119 .join("\n")
9120 })
9121 }
9122
9123 pub fn convert_to_snake_case(
9124 &mut self,
9125 _: &ConvertToSnakeCase,
9126 window: &mut Window,
9127 cx: &mut Context<Self>,
9128 ) {
9129 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9130 }
9131
9132 pub fn convert_to_kebab_case(
9133 &mut self,
9134 _: &ConvertToKebabCase,
9135 window: &mut Window,
9136 cx: &mut Context<Self>,
9137 ) {
9138 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9139 }
9140
9141 pub fn convert_to_upper_camel_case(
9142 &mut self,
9143 _: &ConvertToUpperCamelCase,
9144 window: &mut Window,
9145 cx: &mut Context<Self>,
9146 ) {
9147 self.manipulate_text(window, cx, |text| {
9148 text.split('\n')
9149 .map(|line| line.to_case(Case::UpperCamel))
9150 .join("\n")
9151 })
9152 }
9153
9154 pub fn convert_to_lower_camel_case(
9155 &mut self,
9156 _: &ConvertToLowerCamelCase,
9157 window: &mut Window,
9158 cx: &mut Context<Self>,
9159 ) {
9160 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9161 }
9162
9163 pub fn convert_to_opposite_case(
9164 &mut self,
9165 _: &ConvertToOppositeCase,
9166 window: &mut Window,
9167 cx: &mut Context<Self>,
9168 ) {
9169 self.manipulate_text(window, cx, |text| {
9170 text.chars()
9171 .fold(String::with_capacity(text.len()), |mut t, c| {
9172 if c.is_uppercase() {
9173 t.extend(c.to_lowercase());
9174 } else {
9175 t.extend(c.to_uppercase());
9176 }
9177 t
9178 })
9179 })
9180 }
9181
9182 pub fn convert_to_rot13(
9183 &mut self,
9184 _: &ConvertToRot13,
9185 window: &mut Window,
9186 cx: &mut Context<Self>,
9187 ) {
9188 self.manipulate_text(window, cx, |text| {
9189 text.chars()
9190 .map(|c| match c {
9191 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9192 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9193 _ => c,
9194 })
9195 .collect()
9196 })
9197 }
9198
9199 pub fn convert_to_rot47(
9200 &mut self,
9201 _: &ConvertToRot47,
9202 window: &mut Window,
9203 cx: &mut Context<Self>,
9204 ) {
9205 self.manipulate_text(window, cx, |text| {
9206 text.chars()
9207 .map(|c| {
9208 let code_point = c as u32;
9209 if code_point >= 33 && code_point <= 126 {
9210 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9211 }
9212 c
9213 })
9214 .collect()
9215 })
9216 }
9217
9218 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9219 where
9220 Fn: FnMut(&str) -> String,
9221 {
9222 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9223 let buffer = self.buffer.read(cx).snapshot(cx);
9224
9225 let mut new_selections = Vec::new();
9226 let mut edits = Vec::new();
9227 let mut selection_adjustment = 0i32;
9228
9229 for selection in self.selections.all::<usize>(cx) {
9230 let selection_is_empty = selection.is_empty();
9231
9232 let (start, end) = if selection_is_empty {
9233 let word_range = movement::surrounding_word(
9234 &display_map,
9235 selection.start.to_display_point(&display_map),
9236 );
9237 let start = word_range.start.to_offset(&display_map, Bias::Left);
9238 let end = word_range.end.to_offset(&display_map, Bias::Left);
9239 (start, end)
9240 } else {
9241 (selection.start, selection.end)
9242 };
9243
9244 let text = buffer.text_for_range(start..end).collect::<String>();
9245 let old_length = text.len() as i32;
9246 let text = callback(&text);
9247
9248 new_selections.push(Selection {
9249 start: (start as i32 - selection_adjustment) as usize,
9250 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9251 goal: SelectionGoal::None,
9252 ..selection
9253 });
9254
9255 selection_adjustment += old_length - text.len() as i32;
9256
9257 edits.push((start..end, text));
9258 }
9259
9260 self.transact(window, cx, |this, window, cx| {
9261 this.buffer.update(cx, |buffer, cx| {
9262 buffer.edit(edits, None, cx);
9263 });
9264
9265 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9266 s.select(new_selections);
9267 });
9268
9269 this.request_autoscroll(Autoscroll::fit(), cx);
9270 });
9271 }
9272
9273 pub fn duplicate(
9274 &mut self,
9275 upwards: bool,
9276 whole_lines: bool,
9277 window: &mut Window,
9278 cx: &mut Context<Self>,
9279 ) {
9280 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9281
9282 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9283 let buffer = &display_map.buffer_snapshot;
9284 let selections = self.selections.all::<Point>(cx);
9285
9286 let mut edits = Vec::new();
9287 let mut selections_iter = selections.iter().peekable();
9288 while let Some(selection) = selections_iter.next() {
9289 let mut rows = selection.spanned_rows(false, &display_map);
9290 // duplicate line-wise
9291 if whole_lines || selection.start == selection.end {
9292 // Avoid duplicating the same lines twice.
9293 while let Some(next_selection) = selections_iter.peek() {
9294 let next_rows = next_selection.spanned_rows(false, &display_map);
9295 if next_rows.start < rows.end {
9296 rows.end = next_rows.end;
9297 selections_iter.next().unwrap();
9298 } else {
9299 break;
9300 }
9301 }
9302
9303 // Copy the text from the selected row region and splice it either at the start
9304 // or end of the region.
9305 let start = Point::new(rows.start.0, 0);
9306 let end = Point::new(
9307 rows.end.previous_row().0,
9308 buffer.line_len(rows.end.previous_row()),
9309 );
9310 let text = buffer
9311 .text_for_range(start..end)
9312 .chain(Some("\n"))
9313 .collect::<String>();
9314 let insert_location = if upwards {
9315 Point::new(rows.end.0, 0)
9316 } else {
9317 start
9318 };
9319 edits.push((insert_location..insert_location, text));
9320 } else {
9321 // duplicate character-wise
9322 let start = selection.start;
9323 let end = selection.end;
9324 let text = buffer.text_for_range(start..end).collect::<String>();
9325 edits.push((selection.end..selection.end, text));
9326 }
9327 }
9328
9329 self.transact(window, cx, |this, _, cx| {
9330 this.buffer.update(cx, |buffer, cx| {
9331 buffer.edit(edits, None, cx);
9332 });
9333
9334 this.request_autoscroll(Autoscroll::fit(), cx);
9335 });
9336 }
9337
9338 pub fn duplicate_line_up(
9339 &mut self,
9340 _: &DuplicateLineUp,
9341 window: &mut Window,
9342 cx: &mut Context<Self>,
9343 ) {
9344 self.duplicate(true, true, window, cx);
9345 }
9346
9347 pub fn duplicate_line_down(
9348 &mut self,
9349 _: &DuplicateLineDown,
9350 window: &mut Window,
9351 cx: &mut Context<Self>,
9352 ) {
9353 self.duplicate(false, true, window, cx);
9354 }
9355
9356 pub fn duplicate_selection(
9357 &mut self,
9358 _: &DuplicateSelection,
9359 window: &mut Window,
9360 cx: &mut Context<Self>,
9361 ) {
9362 self.duplicate(false, false, window, cx);
9363 }
9364
9365 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9366 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9367
9368 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9369 let buffer = self.buffer.read(cx).snapshot(cx);
9370
9371 let mut edits = Vec::new();
9372 let mut unfold_ranges = Vec::new();
9373 let mut refold_creases = Vec::new();
9374
9375 let selections = self.selections.all::<Point>(cx);
9376 let mut selections = selections.iter().peekable();
9377 let mut contiguous_row_selections = Vec::new();
9378 let mut new_selections = Vec::new();
9379
9380 while let Some(selection) = selections.next() {
9381 // Find all the selections that span a contiguous row range
9382 let (start_row, end_row) = consume_contiguous_rows(
9383 &mut contiguous_row_selections,
9384 selection,
9385 &display_map,
9386 &mut selections,
9387 );
9388
9389 // Move the text spanned by the row range to be before the line preceding the row range
9390 if start_row.0 > 0 {
9391 let range_to_move = Point::new(
9392 start_row.previous_row().0,
9393 buffer.line_len(start_row.previous_row()),
9394 )
9395 ..Point::new(
9396 end_row.previous_row().0,
9397 buffer.line_len(end_row.previous_row()),
9398 );
9399 let insertion_point = display_map
9400 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9401 .0;
9402
9403 // Don't move lines across excerpts
9404 if buffer
9405 .excerpt_containing(insertion_point..range_to_move.end)
9406 .is_some()
9407 {
9408 let text = buffer
9409 .text_for_range(range_to_move.clone())
9410 .flat_map(|s| s.chars())
9411 .skip(1)
9412 .chain(['\n'])
9413 .collect::<String>();
9414
9415 edits.push((
9416 buffer.anchor_after(range_to_move.start)
9417 ..buffer.anchor_before(range_to_move.end),
9418 String::new(),
9419 ));
9420 let insertion_anchor = buffer.anchor_after(insertion_point);
9421 edits.push((insertion_anchor..insertion_anchor, text));
9422
9423 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9424
9425 // Move selections up
9426 new_selections.extend(contiguous_row_selections.drain(..).map(
9427 |mut selection| {
9428 selection.start.row -= row_delta;
9429 selection.end.row -= row_delta;
9430 selection
9431 },
9432 ));
9433
9434 // Move folds up
9435 unfold_ranges.push(range_to_move.clone());
9436 for fold in display_map.folds_in_range(
9437 buffer.anchor_before(range_to_move.start)
9438 ..buffer.anchor_after(range_to_move.end),
9439 ) {
9440 let mut start = fold.range.start.to_point(&buffer);
9441 let mut end = fold.range.end.to_point(&buffer);
9442 start.row -= row_delta;
9443 end.row -= row_delta;
9444 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9445 }
9446 }
9447 }
9448
9449 // If we didn't move line(s), preserve the existing selections
9450 new_selections.append(&mut contiguous_row_selections);
9451 }
9452
9453 self.transact(window, cx, |this, window, cx| {
9454 this.unfold_ranges(&unfold_ranges, true, true, cx);
9455 this.buffer.update(cx, |buffer, cx| {
9456 for (range, text) in edits {
9457 buffer.edit([(range, text)], None, cx);
9458 }
9459 });
9460 this.fold_creases(refold_creases, true, window, cx);
9461 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9462 s.select(new_selections);
9463 })
9464 });
9465 }
9466
9467 pub fn move_line_down(
9468 &mut self,
9469 _: &MoveLineDown,
9470 window: &mut Window,
9471 cx: &mut Context<Self>,
9472 ) {
9473 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9474
9475 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9476 let buffer = self.buffer.read(cx).snapshot(cx);
9477
9478 let mut edits = Vec::new();
9479 let mut unfold_ranges = Vec::new();
9480 let mut refold_creases = Vec::new();
9481
9482 let selections = self.selections.all::<Point>(cx);
9483 let mut selections = selections.iter().peekable();
9484 let mut contiguous_row_selections = Vec::new();
9485 let mut new_selections = Vec::new();
9486
9487 while let Some(selection) = selections.next() {
9488 // Find all the selections that span a contiguous row range
9489 let (start_row, end_row) = consume_contiguous_rows(
9490 &mut contiguous_row_selections,
9491 selection,
9492 &display_map,
9493 &mut selections,
9494 );
9495
9496 // Move the text spanned by the row range to be after the last line of the row range
9497 if end_row.0 <= buffer.max_point().row {
9498 let range_to_move =
9499 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9500 let insertion_point = display_map
9501 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9502 .0;
9503
9504 // Don't move lines across excerpt boundaries
9505 if buffer
9506 .excerpt_containing(range_to_move.start..insertion_point)
9507 .is_some()
9508 {
9509 let mut text = String::from("\n");
9510 text.extend(buffer.text_for_range(range_to_move.clone()));
9511 text.pop(); // Drop trailing newline
9512 edits.push((
9513 buffer.anchor_after(range_to_move.start)
9514 ..buffer.anchor_before(range_to_move.end),
9515 String::new(),
9516 ));
9517 let insertion_anchor = buffer.anchor_after(insertion_point);
9518 edits.push((insertion_anchor..insertion_anchor, text));
9519
9520 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9521
9522 // Move selections down
9523 new_selections.extend(contiguous_row_selections.drain(..).map(
9524 |mut selection| {
9525 selection.start.row += row_delta;
9526 selection.end.row += row_delta;
9527 selection
9528 },
9529 ));
9530
9531 // Move folds down
9532 unfold_ranges.push(range_to_move.clone());
9533 for fold in display_map.folds_in_range(
9534 buffer.anchor_before(range_to_move.start)
9535 ..buffer.anchor_after(range_to_move.end),
9536 ) {
9537 let mut start = fold.range.start.to_point(&buffer);
9538 let mut end = fold.range.end.to_point(&buffer);
9539 start.row += row_delta;
9540 end.row += row_delta;
9541 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9542 }
9543 }
9544 }
9545
9546 // If we didn't move line(s), preserve the existing selections
9547 new_selections.append(&mut contiguous_row_selections);
9548 }
9549
9550 self.transact(window, cx, |this, window, cx| {
9551 this.unfold_ranges(&unfold_ranges, true, true, cx);
9552 this.buffer.update(cx, |buffer, cx| {
9553 for (range, text) in edits {
9554 buffer.edit([(range, text)], None, cx);
9555 }
9556 });
9557 this.fold_creases(refold_creases, true, window, cx);
9558 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9559 s.select(new_selections)
9560 });
9561 });
9562 }
9563
9564 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9565 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9566 let text_layout_details = &self.text_layout_details(window);
9567 self.transact(window, cx, |this, window, cx| {
9568 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9569 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9570 s.move_with(|display_map, selection| {
9571 if !selection.is_empty() {
9572 return;
9573 }
9574
9575 let mut head = selection.head();
9576 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9577 if head.column() == display_map.line_len(head.row()) {
9578 transpose_offset = display_map
9579 .buffer_snapshot
9580 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9581 }
9582
9583 if transpose_offset == 0 {
9584 return;
9585 }
9586
9587 *head.column_mut() += 1;
9588 head = display_map.clip_point(head, Bias::Right);
9589 let goal = SelectionGoal::HorizontalPosition(
9590 display_map
9591 .x_for_display_point(head, text_layout_details)
9592 .into(),
9593 );
9594 selection.collapse_to(head, goal);
9595
9596 let transpose_start = display_map
9597 .buffer_snapshot
9598 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9599 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9600 let transpose_end = display_map
9601 .buffer_snapshot
9602 .clip_offset(transpose_offset + 1, Bias::Right);
9603 if let Some(ch) =
9604 display_map.buffer_snapshot.chars_at(transpose_start).next()
9605 {
9606 edits.push((transpose_start..transpose_offset, String::new()));
9607 edits.push((transpose_end..transpose_end, ch.to_string()));
9608 }
9609 }
9610 });
9611 edits
9612 });
9613 this.buffer
9614 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9615 let selections = this.selections.all::<usize>(cx);
9616 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9617 s.select(selections);
9618 });
9619 });
9620 }
9621
9622 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9623 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9624 self.rewrap_impl(RewrapOptions::default(), cx)
9625 }
9626
9627 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9628 let buffer = self.buffer.read(cx).snapshot(cx);
9629 let selections = self.selections.all::<Point>(cx);
9630 let mut selections = selections.iter().peekable();
9631
9632 let mut edits = Vec::new();
9633 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9634
9635 while let Some(selection) = selections.next() {
9636 let mut start_row = selection.start.row;
9637 let mut end_row = selection.end.row;
9638
9639 // Skip selections that overlap with a range that has already been rewrapped.
9640 let selection_range = start_row..end_row;
9641 if rewrapped_row_ranges
9642 .iter()
9643 .any(|range| range.overlaps(&selection_range))
9644 {
9645 continue;
9646 }
9647
9648 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9649
9650 // Since not all lines in the selection may be at the same indent
9651 // level, choose the indent size that is the most common between all
9652 // of the lines.
9653 //
9654 // If there is a tie, we use the deepest indent.
9655 let (indent_size, indent_end) = {
9656 let mut indent_size_occurrences = HashMap::default();
9657 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9658
9659 for row in start_row..=end_row {
9660 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9661 rows_by_indent_size.entry(indent).or_default().push(row);
9662 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9663 }
9664
9665 let indent_size = indent_size_occurrences
9666 .into_iter()
9667 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9668 .map(|(indent, _)| indent)
9669 .unwrap_or_default();
9670 let row = rows_by_indent_size[&indent_size][0];
9671 let indent_end = Point::new(row, indent_size.len);
9672
9673 (indent_size, indent_end)
9674 };
9675
9676 let mut line_prefix = indent_size.chars().collect::<String>();
9677
9678 let mut inside_comment = false;
9679 if let Some(comment_prefix) =
9680 buffer
9681 .language_scope_at(selection.head())
9682 .and_then(|language| {
9683 language
9684 .line_comment_prefixes()
9685 .iter()
9686 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9687 .cloned()
9688 })
9689 {
9690 line_prefix.push_str(&comment_prefix);
9691 inside_comment = true;
9692 }
9693
9694 let language_settings = buffer.language_settings_at(selection.head(), cx);
9695 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9696 RewrapBehavior::InComments => inside_comment,
9697 RewrapBehavior::InSelections => !selection.is_empty(),
9698 RewrapBehavior::Anywhere => true,
9699 };
9700
9701 let should_rewrap = options.override_language_settings
9702 || allow_rewrap_based_on_language
9703 || self.hard_wrap.is_some();
9704 if !should_rewrap {
9705 continue;
9706 }
9707
9708 if selection.is_empty() {
9709 'expand_upwards: while start_row > 0 {
9710 let prev_row = start_row - 1;
9711 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9712 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9713 {
9714 start_row = prev_row;
9715 } else {
9716 break 'expand_upwards;
9717 }
9718 }
9719
9720 'expand_downwards: while end_row < buffer.max_point().row {
9721 let next_row = end_row + 1;
9722 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9723 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9724 {
9725 end_row = next_row;
9726 } else {
9727 break 'expand_downwards;
9728 }
9729 }
9730 }
9731
9732 let start = Point::new(start_row, 0);
9733 let start_offset = start.to_offset(&buffer);
9734 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9735 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9736 let Some(lines_without_prefixes) = selection_text
9737 .lines()
9738 .map(|line| {
9739 line.strip_prefix(&line_prefix)
9740 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9741 .ok_or_else(|| {
9742 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9743 })
9744 })
9745 .collect::<Result<Vec<_>, _>>()
9746 .log_err()
9747 else {
9748 continue;
9749 };
9750
9751 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9752 buffer
9753 .language_settings_at(Point::new(start_row, 0), cx)
9754 .preferred_line_length as usize
9755 });
9756 let wrapped_text = wrap_with_prefix(
9757 line_prefix,
9758 lines_without_prefixes.join("\n"),
9759 wrap_column,
9760 tab_size,
9761 options.preserve_existing_whitespace,
9762 );
9763
9764 // TODO: should always use char-based diff while still supporting cursor behavior that
9765 // matches vim.
9766 let mut diff_options = DiffOptions::default();
9767 if options.override_language_settings {
9768 diff_options.max_word_diff_len = 0;
9769 diff_options.max_word_diff_line_count = 0;
9770 } else {
9771 diff_options.max_word_diff_len = usize::MAX;
9772 diff_options.max_word_diff_line_count = usize::MAX;
9773 }
9774
9775 for (old_range, new_text) in
9776 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9777 {
9778 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9779 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9780 edits.push((edit_start..edit_end, new_text));
9781 }
9782
9783 rewrapped_row_ranges.push(start_row..=end_row);
9784 }
9785
9786 self.buffer
9787 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9788 }
9789
9790 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9791 let mut text = String::new();
9792 let buffer = self.buffer.read(cx).snapshot(cx);
9793 let mut selections = self.selections.all::<Point>(cx);
9794 let mut clipboard_selections = Vec::with_capacity(selections.len());
9795 {
9796 let max_point = buffer.max_point();
9797 let mut is_first = true;
9798 for selection in &mut selections {
9799 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9800 if is_entire_line {
9801 selection.start = Point::new(selection.start.row, 0);
9802 if !selection.is_empty() && selection.end.column == 0 {
9803 selection.end = cmp::min(max_point, selection.end);
9804 } else {
9805 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9806 }
9807 selection.goal = SelectionGoal::None;
9808 }
9809 if is_first {
9810 is_first = false;
9811 } else {
9812 text += "\n";
9813 }
9814 let mut len = 0;
9815 for chunk in buffer.text_for_range(selection.start..selection.end) {
9816 text.push_str(chunk);
9817 len += chunk.len();
9818 }
9819 clipboard_selections.push(ClipboardSelection {
9820 len,
9821 is_entire_line,
9822 first_line_indent: buffer
9823 .indent_size_for_line(MultiBufferRow(selection.start.row))
9824 .len,
9825 });
9826 }
9827 }
9828
9829 self.transact(window, cx, |this, window, cx| {
9830 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9831 s.select(selections);
9832 });
9833 this.insert("", window, cx);
9834 });
9835 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9836 }
9837
9838 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9839 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9840 let item = self.cut_common(window, cx);
9841 cx.write_to_clipboard(item);
9842 }
9843
9844 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9845 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9846 self.change_selections(None, window, cx, |s| {
9847 s.move_with(|snapshot, sel| {
9848 if sel.is_empty() {
9849 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9850 }
9851 });
9852 });
9853 let item = self.cut_common(window, cx);
9854 cx.set_global(KillRing(item))
9855 }
9856
9857 pub fn kill_ring_yank(
9858 &mut self,
9859 _: &KillRingYank,
9860 window: &mut Window,
9861 cx: &mut Context<Self>,
9862 ) {
9863 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9864 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9865 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9866 (kill_ring.text().to_string(), kill_ring.metadata_json())
9867 } else {
9868 return;
9869 }
9870 } else {
9871 return;
9872 };
9873 self.do_paste(&text, metadata, false, window, cx);
9874 }
9875
9876 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9877 self.do_copy(true, cx);
9878 }
9879
9880 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9881 self.do_copy(false, cx);
9882 }
9883
9884 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9885 let selections = self.selections.all::<Point>(cx);
9886 let buffer = self.buffer.read(cx).read(cx);
9887 let mut text = String::new();
9888
9889 let mut clipboard_selections = Vec::with_capacity(selections.len());
9890 {
9891 let max_point = buffer.max_point();
9892 let mut is_first = true;
9893 for selection in &selections {
9894 let mut start = selection.start;
9895 let mut end = selection.end;
9896 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9897 if is_entire_line {
9898 start = Point::new(start.row, 0);
9899 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9900 }
9901
9902 let mut trimmed_selections = Vec::new();
9903 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9904 let row = MultiBufferRow(start.row);
9905 let first_indent = buffer.indent_size_for_line(row);
9906 if first_indent.len == 0 || start.column > first_indent.len {
9907 trimmed_selections.push(start..end);
9908 } else {
9909 trimmed_selections.push(
9910 Point::new(row.0, first_indent.len)
9911 ..Point::new(row.0, buffer.line_len(row)),
9912 );
9913 for row in start.row + 1..=end.row {
9914 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
9915 if row_indent_size.len >= first_indent.len {
9916 trimmed_selections.push(
9917 Point::new(row, first_indent.len)
9918 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
9919 );
9920 } else {
9921 trimmed_selections.clear();
9922 trimmed_selections.push(start..end);
9923 break;
9924 }
9925 }
9926 }
9927 } else {
9928 trimmed_selections.push(start..end);
9929 }
9930
9931 for trimmed_range in trimmed_selections {
9932 if is_first {
9933 is_first = false;
9934 } else {
9935 text += "\n";
9936 }
9937 let mut len = 0;
9938 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
9939 text.push_str(chunk);
9940 len += chunk.len();
9941 }
9942 clipboard_selections.push(ClipboardSelection {
9943 len,
9944 is_entire_line,
9945 first_line_indent: buffer
9946 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
9947 .len,
9948 });
9949 }
9950 }
9951 }
9952
9953 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9954 text,
9955 clipboard_selections,
9956 ));
9957 }
9958
9959 pub fn do_paste(
9960 &mut self,
9961 text: &String,
9962 clipboard_selections: Option<Vec<ClipboardSelection>>,
9963 handle_entire_lines: bool,
9964 window: &mut Window,
9965 cx: &mut Context<Self>,
9966 ) {
9967 if self.read_only(cx) {
9968 return;
9969 }
9970
9971 let clipboard_text = Cow::Borrowed(text);
9972
9973 self.transact(window, cx, |this, window, cx| {
9974 if let Some(mut clipboard_selections) = clipboard_selections {
9975 let old_selections = this.selections.all::<usize>(cx);
9976 let all_selections_were_entire_line =
9977 clipboard_selections.iter().all(|s| s.is_entire_line);
9978 let first_selection_indent_column =
9979 clipboard_selections.first().map(|s| s.first_line_indent);
9980 if clipboard_selections.len() != old_selections.len() {
9981 clipboard_selections.drain(..);
9982 }
9983 let cursor_offset = this.selections.last::<usize>(cx).head();
9984 let mut auto_indent_on_paste = true;
9985
9986 this.buffer.update(cx, |buffer, cx| {
9987 let snapshot = buffer.read(cx);
9988 auto_indent_on_paste = snapshot
9989 .language_settings_at(cursor_offset, cx)
9990 .auto_indent_on_paste;
9991
9992 let mut start_offset = 0;
9993 let mut edits = Vec::new();
9994 let mut original_indent_columns = Vec::new();
9995 for (ix, selection) in old_selections.iter().enumerate() {
9996 let to_insert;
9997 let entire_line;
9998 let original_indent_column;
9999 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10000 let end_offset = start_offset + clipboard_selection.len;
10001 to_insert = &clipboard_text[start_offset..end_offset];
10002 entire_line = clipboard_selection.is_entire_line;
10003 start_offset = end_offset + 1;
10004 original_indent_column = Some(clipboard_selection.first_line_indent);
10005 } else {
10006 to_insert = clipboard_text.as_str();
10007 entire_line = all_selections_were_entire_line;
10008 original_indent_column = first_selection_indent_column
10009 }
10010
10011 // If the corresponding selection was empty when this slice of the
10012 // clipboard text was written, then the entire line containing the
10013 // selection was copied. If this selection is also currently empty,
10014 // then paste the line before the current line of the buffer.
10015 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10016 let column = selection.start.to_point(&snapshot).column as usize;
10017 let line_start = selection.start - column;
10018 line_start..line_start
10019 } else {
10020 selection.range()
10021 };
10022
10023 edits.push((range, to_insert));
10024 original_indent_columns.push(original_indent_column);
10025 }
10026 drop(snapshot);
10027
10028 buffer.edit(
10029 edits,
10030 if auto_indent_on_paste {
10031 Some(AutoindentMode::Block {
10032 original_indent_columns,
10033 })
10034 } else {
10035 None
10036 },
10037 cx,
10038 );
10039 });
10040
10041 let selections = this.selections.all::<usize>(cx);
10042 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10043 s.select(selections)
10044 });
10045 } else {
10046 this.insert(&clipboard_text, window, cx);
10047 }
10048 });
10049 }
10050
10051 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10052 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10053 if let Some(item) = cx.read_from_clipboard() {
10054 let entries = item.entries();
10055
10056 match entries.first() {
10057 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10058 // of all the pasted entries.
10059 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10060 .do_paste(
10061 clipboard_string.text(),
10062 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10063 true,
10064 window,
10065 cx,
10066 ),
10067 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10068 }
10069 }
10070 }
10071
10072 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10073 if self.read_only(cx) {
10074 return;
10075 }
10076
10077 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10078
10079 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10080 if let Some((selections, _)) =
10081 self.selection_history.transaction(transaction_id).cloned()
10082 {
10083 self.change_selections(None, window, cx, |s| {
10084 s.select_anchors(selections.to_vec());
10085 });
10086 } else {
10087 log::error!(
10088 "No entry in selection_history found for undo. \
10089 This may correspond to a bug where undo does not update the selection. \
10090 If this is occurring, please add details to \
10091 https://github.com/zed-industries/zed/issues/22692"
10092 );
10093 }
10094 self.request_autoscroll(Autoscroll::fit(), cx);
10095 self.unmark_text(window, cx);
10096 self.refresh_inline_completion(true, false, window, cx);
10097 cx.emit(EditorEvent::Edited { transaction_id });
10098 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10099 }
10100 }
10101
10102 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10103 if self.read_only(cx) {
10104 return;
10105 }
10106
10107 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10108
10109 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10110 if let Some((_, Some(selections))) =
10111 self.selection_history.transaction(transaction_id).cloned()
10112 {
10113 self.change_selections(None, window, cx, |s| {
10114 s.select_anchors(selections.to_vec());
10115 });
10116 } else {
10117 log::error!(
10118 "No entry in selection_history found for redo. \
10119 This may correspond to a bug where undo does not update the selection. \
10120 If this is occurring, please add details to \
10121 https://github.com/zed-industries/zed/issues/22692"
10122 );
10123 }
10124 self.request_autoscroll(Autoscroll::fit(), cx);
10125 self.unmark_text(window, cx);
10126 self.refresh_inline_completion(true, false, window, cx);
10127 cx.emit(EditorEvent::Edited { transaction_id });
10128 }
10129 }
10130
10131 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10132 self.buffer
10133 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10134 }
10135
10136 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10137 self.buffer
10138 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10139 }
10140
10141 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10142 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10143 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10144 s.move_with(|map, selection| {
10145 let cursor = if selection.is_empty() {
10146 movement::left(map, selection.start)
10147 } else {
10148 selection.start
10149 };
10150 selection.collapse_to(cursor, SelectionGoal::None);
10151 });
10152 })
10153 }
10154
10155 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10156 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10157 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10158 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10159 })
10160 }
10161
10162 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10163 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10165 s.move_with(|map, selection| {
10166 let cursor = if selection.is_empty() {
10167 movement::right(map, selection.end)
10168 } else {
10169 selection.end
10170 };
10171 selection.collapse_to(cursor, SelectionGoal::None)
10172 });
10173 })
10174 }
10175
10176 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10177 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10178 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10179 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10180 })
10181 }
10182
10183 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10184 if self.take_rename(true, window, cx).is_some() {
10185 return;
10186 }
10187
10188 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10189 cx.propagate();
10190 return;
10191 }
10192
10193 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10194
10195 let text_layout_details = &self.text_layout_details(window);
10196 let selection_count = self.selections.count();
10197 let first_selection = self.selections.first_anchor();
10198
10199 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10200 s.move_with(|map, selection| {
10201 if !selection.is_empty() {
10202 selection.goal = SelectionGoal::None;
10203 }
10204 let (cursor, goal) = movement::up(
10205 map,
10206 selection.start,
10207 selection.goal,
10208 false,
10209 text_layout_details,
10210 );
10211 selection.collapse_to(cursor, goal);
10212 });
10213 });
10214
10215 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10216 {
10217 cx.propagate();
10218 }
10219 }
10220
10221 pub fn move_up_by_lines(
10222 &mut self,
10223 action: &MoveUpByLines,
10224 window: &mut Window,
10225 cx: &mut Context<Self>,
10226 ) {
10227 if self.take_rename(true, window, cx).is_some() {
10228 return;
10229 }
10230
10231 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10232 cx.propagate();
10233 return;
10234 }
10235
10236 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10237
10238 let text_layout_details = &self.text_layout_details(window);
10239
10240 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10241 s.move_with(|map, selection| {
10242 if !selection.is_empty() {
10243 selection.goal = SelectionGoal::None;
10244 }
10245 let (cursor, goal) = movement::up_by_rows(
10246 map,
10247 selection.start,
10248 action.lines,
10249 selection.goal,
10250 false,
10251 text_layout_details,
10252 );
10253 selection.collapse_to(cursor, goal);
10254 });
10255 })
10256 }
10257
10258 pub fn move_down_by_lines(
10259 &mut self,
10260 action: &MoveDownByLines,
10261 window: &mut Window,
10262 cx: &mut Context<Self>,
10263 ) {
10264 if self.take_rename(true, window, cx).is_some() {
10265 return;
10266 }
10267
10268 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10269 cx.propagate();
10270 return;
10271 }
10272
10273 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10274
10275 let text_layout_details = &self.text_layout_details(window);
10276
10277 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10278 s.move_with(|map, selection| {
10279 if !selection.is_empty() {
10280 selection.goal = SelectionGoal::None;
10281 }
10282 let (cursor, goal) = movement::down_by_rows(
10283 map,
10284 selection.start,
10285 action.lines,
10286 selection.goal,
10287 false,
10288 text_layout_details,
10289 );
10290 selection.collapse_to(cursor, goal);
10291 });
10292 })
10293 }
10294
10295 pub fn select_down_by_lines(
10296 &mut self,
10297 action: &SelectDownByLines,
10298 window: &mut Window,
10299 cx: &mut Context<Self>,
10300 ) {
10301 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10302 let text_layout_details = &self.text_layout_details(window);
10303 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10304 s.move_heads_with(|map, head, goal| {
10305 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10306 })
10307 })
10308 }
10309
10310 pub fn select_up_by_lines(
10311 &mut self,
10312 action: &SelectUpByLines,
10313 window: &mut Window,
10314 cx: &mut Context<Self>,
10315 ) {
10316 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10317 let text_layout_details = &self.text_layout_details(window);
10318 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10319 s.move_heads_with(|map, head, goal| {
10320 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10321 })
10322 })
10323 }
10324
10325 pub fn select_page_up(
10326 &mut self,
10327 _: &SelectPageUp,
10328 window: &mut Window,
10329 cx: &mut Context<Self>,
10330 ) {
10331 let Some(row_count) = self.visible_row_count() else {
10332 return;
10333 };
10334
10335 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10336
10337 let text_layout_details = &self.text_layout_details(window);
10338
10339 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10340 s.move_heads_with(|map, head, goal| {
10341 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10342 })
10343 })
10344 }
10345
10346 pub fn move_page_up(
10347 &mut self,
10348 action: &MovePageUp,
10349 window: &mut Window,
10350 cx: &mut Context<Self>,
10351 ) {
10352 if self.take_rename(true, window, cx).is_some() {
10353 return;
10354 }
10355
10356 if self
10357 .context_menu
10358 .borrow_mut()
10359 .as_mut()
10360 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10361 .unwrap_or(false)
10362 {
10363 return;
10364 }
10365
10366 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10367 cx.propagate();
10368 return;
10369 }
10370
10371 let Some(row_count) = self.visible_row_count() else {
10372 return;
10373 };
10374
10375 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10376
10377 let autoscroll = if action.center_cursor {
10378 Autoscroll::center()
10379 } else {
10380 Autoscroll::fit()
10381 };
10382
10383 let text_layout_details = &self.text_layout_details(window);
10384
10385 self.change_selections(Some(autoscroll), window, cx, |s| {
10386 s.move_with(|map, selection| {
10387 if !selection.is_empty() {
10388 selection.goal = SelectionGoal::None;
10389 }
10390 let (cursor, goal) = movement::up_by_rows(
10391 map,
10392 selection.end,
10393 row_count,
10394 selection.goal,
10395 false,
10396 text_layout_details,
10397 );
10398 selection.collapse_to(cursor, goal);
10399 });
10400 });
10401 }
10402
10403 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10404 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10405 let text_layout_details = &self.text_layout_details(window);
10406 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10407 s.move_heads_with(|map, head, goal| {
10408 movement::up(map, head, goal, false, text_layout_details)
10409 })
10410 })
10411 }
10412
10413 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10414 self.take_rename(true, window, cx);
10415
10416 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10417 cx.propagate();
10418 return;
10419 }
10420
10421 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10422
10423 let text_layout_details = &self.text_layout_details(window);
10424 let selection_count = self.selections.count();
10425 let first_selection = self.selections.first_anchor();
10426
10427 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10428 s.move_with(|map, selection| {
10429 if !selection.is_empty() {
10430 selection.goal = SelectionGoal::None;
10431 }
10432 let (cursor, goal) = movement::down(
10433 map,
10434 selection.end,
10435 selection.goal,
10436 false,
10437 text_layout_details,
10438 );
10439 selection.collapse_to(cursor, goal);
10440 });
10441 });
10442
10443 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10444 {
10445 cx.propagate();
10446 }
10447 }
10448
10449 pub fn select_page_down(
10450 &mut self,
10451 _: &SelectPageDown,
10452 window: &mut Window,
10453 cx: &mut Context<Self>,
10454 ) {
10455 let Some(row_count) = self.visible_row_count() else {
10456 return;
10457 };
10458
10459 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10460
10461 let text_layout_details = &self.text_layout_details(window);
10462
10463 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10464 s.move_heads_with(|map, head, goal| {
10465 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10466 })
10467 })
10468 }
10469
10470 pub fn move_page_down(
10471 &mut self,
10472 action: &MovePageDown,
10473 window: &mut Window,
10474 cx: &mut Context<Self>,
10475 ) {
10476 if self.take_rename(true, window, cx).is_some() {
10477 return;
10478 }
10479
10480 if self
10481 .context_menu
10482 .borrow_mut()
10483 .as_mut()
10484 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10485 .unwrap_or(false)
10486 {
10487 return;
10488 }
10489
10490 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10491 cx.propagate();
10492 return;
10493 }
10494
10495 let Some(row_count) = self.visible_row_count() else {
10496 return;
10497 };
10498
10499 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10500
10501 let autoscroll = if action.center_cursor {
10502 Autoscroll::center()
10503 } else {
10504 Autoscroll::fit()
10505 };
10506
10507 let text_layout_details = &self.text_layout_details(window);
10508 self.change_selections(Some(autoscroll), window, cx, |s| {
10509 s.move_with(|map, selection| {
10510 if !selection.is_empty() {
10511 selection.goal = SelectionGoal::None;
10512 }
10513 let (cursor, goal) = movement::down_by_rows(
10514 map,
10515 selection.end,
10516 row_count,
10517 selection.goal,
10518 false,
10519 text_layout_details,
10520 );
10521 selection.collapse_to(cursor, goal);
10522 });
10523 });
10524 }
10525
10526 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10527 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10528 let text_layout_details = &self.text_layout_details(window);
10529 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10530 s.move_heads_with(|map, head, goal| {
10531 movement::down(map, head, goal, false, text_layout_details)
10532 })
10533 });
10534 }
10535
10536 pub fn context_menu_first(
10537 &mut self,
10538 _: &ContextMenuFirst,
10539 _window: &mut Window,
10540 cx: &mut Context<Self>,
10541 ) {
10542 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10543 context_menu.select_first(self.completion_provider.as_deref(), cx);
10544 }
10545 }
10546
10547 pub fn context_menu_prev(
10548 &mut self,
10549 _: &ContextMenuPrevious,
10550 _window: &mut Window,
10551 cx: &mut Context<Self>,
10552 ) {
10553 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10554 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10555 }
10556 }
10557
10558 pub fn context_menu_next(
10559 &mut self,
10560 _: &ContextMenuNext,
10561 _window: &mut Window,
10562 cx: &mut Context<Self>,
10563 ) {
10564 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10565 context_menu.select_next(self.completion_provider.as_deref(), cx);
10566 }
10567 }
10568
10569 pub fn context_menu_last(
10570 &mut self,
10571 _: &ContextMenuLast,
10572 _window: &mut Window,
10573 cx: &mut Context<Self>,
10574 ) {
10575 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10576 context_menu.select_last(self.completion_provider.as_deref(), cx);
10577 }
10578 }
10579
10580 pub fn move_to_previous_word_start(
10581 &mut self,
10582 _: &MoveToPreviousWordStart,
10583 window: &mut Window,
10584 cx: &mut Context<Self>,
10585 ) {
10586 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10587 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10588 s.move_cursors_with(|map, head, _| {
10589 (
10590 movement::previous_word_start(map, head),
10591 SelectionGoal::None,
10592 )
10593 });
10594 })
10595 }
10596
10597 pub fn move_to_previous_subword_start(
10598 &mut self,
10599 _: &MoveToPreviousSubwordStart,
10600 window: &mut Window,
10601 cx: &mut Context<Self>,
10602 ) {
10603 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10604 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10605 s.move_cursors_with(|map, head, _| {
10606 (
10607 movement::previous_subword_start(map, head),
10608 SelectionGoal::None,
10609 )
10610 });
10611 })
10612 }
10613
10614 pub fn select_to_previous_word_start(
10615 &mut self,
10616 _: &SelectToPreviousWordStart,
10617 window: &mut Window,
10618 cx: &mut Context<Self>,
10619 ) {
10620 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10621 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10622 s.move_heads_with(|map, head, _| {
10623 (
10624 movement::previous_word_start(map, head),
10625 SelectionGoal::None,
10626 )
10627 });
10628 })
10629 }
10630
10631 pub fn select_to_previous_subword_start(
10632 &mut self,
10633 _: &SelectToPreviousSubwordStart,
10634 window: &mut Window,
10635 cx: &mut Context<Self>,
10636 ) {
10637 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10638 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10639 s.move_heads_with(|map, head, _| {
10640 (
10641 movement::previous_subword_start(map, head),
10642 SelectionGoal::None,
10643 )
10644 });
10645 })
10646 }
10647
10648 pub fn delete_to_previous_word_start(
10649 &mut self,
10650 action: &DeleteToPreviousWordStart,
10651 window: &mut Window,
10652 cx: &mut Context<Self>,
10653 ) {
10654 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10655 self.transact(window, cx, |this, window, cx| {
10656 this.select_autoclose_pair(window, cx);
10657 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10658 s.move_with(|map, selection| {
10659 if selection.is_empty() {
10660 let cursor = if action.ignore_newlines {
10661 movement::previous_word_start(map, selection.head())
10662 } else {
10663 movement::previous_word_start_or_newline(map, selection.head())
10664 };
10665 selection.set_head(cursor, SelectionGoal::None);
10666 }
10667 });
10668 });
10669 this.insert("", window, cx);
10670 });
10671 }
10672
10673 pub fn delete_to_previous_subword_start(
10674 &mut self,
10675 _: &DeleteToPreviousSubwordStart,
10676 window: &mut Window,
10677 cx: &mut Context<Self>,
10678 ) {
10679 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10680 self.transact(window, cx, |this, window, cx| {
10681 this.select_autoclose_pair(window, cx);
10682 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10683 s.move_with(|map, selection| {
10684 if selection.is_empty() {
10685 let cursor = movement::previous_subword_start(map, selection.head());
10686 selection.set_head(cursor, SelectionGoal::None);
10687 }
10688 });
10689 });
10690 this.insert("", window, cx);
10691 });
10692 }
10693
10694 pub fn move_to_next_word_end(
10695 &mut self,
10696 _: &MoveToNextWordEnd,
10697 window: &mut Window,
10698 cx: &mut Context<Self>,
10699 ) {
10700 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10701 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10702 s.move_cursors_with(|map, head, _| {
10703 (movement::next_word_end(map, head), SelectionGoal::None)
10704 });
10705 })
10706 }
10707
10708 pub fn move_to_next_subword_end(
10709 &mut self,
10710 _: &MoveToNextSubwordEnd,
10711 window: &mut Window,
10712 cx: &mut Context<Self>,
10713 ) {
10714 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10715 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10716 s.move_cursors_with(|map, head, _| {
10717 (movement::next_subword_end(map, head), SelectionGoal::None)
10718 });
10719 })
10720 }
10721
10722 pub fn select_to_next_word_end(
10723 &mut self,
10724 _: &SelectToNextWordEnd,
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_heads_with(|map, head, _| {
10731 (movement::next_word_end(map, head), SelectionGoal::None)
10732 });
10733 })
10734 }
10735
10736 pub fn select_to_next_subword_end(
10737 &mut self,
10738 _: &SelectToNextSubwordEnd,
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_heads_with(|map, head, _| {
10745 (movement::next_subword_end(map, head), SelectionGoal::None)
10746 });
10747 })
10748 }
10749
10750 pub fn delete_to_next_word_end(
10751 &mut self,
10752 action: &DeleteToNextWordEnd,
10753 window: &mut Window,
10754 cx: &mut Context<Self>,
10755 ) {
10756 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10757 self.transact(window, cx, |this, window, cx| {
10758 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10759 s.move_with(|map, selection| {
10760 if selection.is_empty() {
10761 let cursor = if action.ignore_newlines {
10762 movement::next_word_end(map, selection.head())
10763 } else {
10764 movement::next_word_end_or_newline(map, selection.head())
10765 };
10766 selection.set_head(cursor, SelectionGoal::None);
10767 }
10768 });
10769 });
10770 this.insert("", window, cx);
10771 });
10772 }
10773
10774 pub fn delete_to_next_subword_end(
10775 &mut self,
10776 _: &DeleteToNextSubwordEnd,
10777 window: &mut Window,
10778 cx: &mut Context<Self>,
10779 ) {
10780 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10781 self.transact(window, cx, |this, window, cx| {
10782 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10783 s.move_with(|map, selection| {
10784 if selection.is_empty() {
10785 let cursor = movement::next_subword_end(map, selection.head());
10786 selection.set_head(cursor, SelectionGoal::None);
10787 }
10788 });
10789 });
10790 this.insert("", window, cx);
10791 });
10792 }
10793
10794 pub fn move_to_beginning_of_line(
10795 &mut self,
10796 action: &MoveToBeginningOfLine,
10797 window: &mut Window,
10798 cx: &mut Context<Self>,
10799 ) {
10800 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10801 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10802 s.move_cursors_with(|map, head, _| {
10803 (
10804 movement::indented_line_beginning(
10805 map,
10806 head,
10807 action.stop_at_soft_wraps,
10808 action.stop_at_indent,
10809 ),
10810 SelectionGoal::None,
10811 )
10812 });
10813 })
10814 }
10815
10816 pub fn select_to_beginning_of_line(
10817 &mut self,
10818 action: &SelectToBeginningOfLine,
10819 window: &mut Window,
10820 cx: &mut Context<Self>,
10821 ) {
10822 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10823 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10824 s.move_heads_with(|map, head, _| {
10825 (
10826 movement::indented_line_beginning(
10827 map,
10828 head,
10829 action.stop_at_soft_wraps,
10830 action.stop_at_indent,
10831 ),
10832 SelectionGoal::None,
10833 )
10834 });
10835 });
10836 }
10837
10838 pub fn delete_to_beginning_of_line(
10839 &mut self,
10840 action: &DeleteToBeginningOfLine,
10841 window: &mut Window,
10842 cx: &mut Context<Self>,
10843 ) {
10844 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10845 self.transact(window, cx, |this, window, cx| {
10846 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10847 s.move_with(|_, selection| {
10848 selection.reversed = true;
10849 });
10850 });
10851
10852 this.select_to_beginning_of_line(
10853 &SelectToBeginningOfLine {
10854 stop_at_soft_wraps: false,
10855 stop_at_indent: action.stop_at_indent,
10856 },
10857 window,
10858 cx,
10859 );
10860 this.backspace(&Backspace, window, cx);
10861 });
10862 }
10863
10864 pub fn move_to_end_of_line(
10865 &mut self,
10866 action: &MoveToEndOfLine,
10867 window: &mut Window,
10868 cx: &mut Context<Self>,
10869 ) {
10870 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10871 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10872 s.move_cursors_with(|map, head, _| {
10873 (
10874 movement::line_end(map, head, action.stop_at_soft_wraps),
10875 SelectionGoal::None,
10876 )
10877 });
10878 })
10879 }
10880
10881 pub fn select_to_end_of_line(
10882 &mut self,
10883 action: &SelectToEndOfLine,
10884 window: &mut Window,
10885 cx: &mut Context<Self>,
10886 ) {
10887 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10888 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10889 s.move_heads_with(|map, head, _| {
10890 (
10891 movement::line_end(map, head, action.stop_at_soft_wraps),
10892 SelectionGoal::None,
10893 )
10894 });
10895 })
10896 }
10897
10898 pub fn delete_to_end_of_line(
10899 &mut self,
10900 _: &DeleteToEndOfLine,
10901 window: &mut Window,
10902 cx: &mut Context<Self>,
10903 ) {
10904 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10905 self.transact(window, cx, |this, window, cx| {
10906 this.select_to_end_of_line(
10907 &SelectToEndOfLine {
10908 stop_at_soft_wraps: false,
10909 },
10910 window,
10911 cx,
10912 );
10913 this.delete(&Delete, window, cx);
10914 });
10915 }
10916
10917 pub fn cut_to_end_of_line(
10918 &mut self,
10919 _: &CutToEndOfLine,
10920 window: &mut Window,
10921 cx: &mut Context<Self>,
10922 ) {
10923 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10924 self.transact(window, cx, |this, window, cx| {
10925 this.select_to_end_of_line(
10926 &SelectToEndOfLine {
10927 stop_at_soft_wraps: false,
10928 },
10929 window,
10930 cx,
10931 );
10932 this.cut(&Cut, window, cx);
10933 });
10934 }
10935
10936 pub fn move_to_start_of_paragraph(
10937 &mut self,
10938 _: &MoveToStartOfParagraph,
10939 window: &mut Window,
10940 cx: &mut Context<Self>,
10941 ) {
10942 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10943 cx.propagate();
10944 return;
10945 }
10946 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10947 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10948 s.move_with(|map, selection| {
10949 selection.collapse_to(
10950 movement::start_of_paragraph(map, selection.head(), 1),
10951 SelectionGoal::None,
10952 )
10953 });
10954 })
10955 }
10956
10957 pub fn move_to_end_of_paragraph(
10958 &mut self,
10959 _: &MoveToEndOfParagraph,
10960 window: &mut Window,
10961 cx: &mut Context<Self>,
10962 ) {
10963 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10964 cx.propagate();
10965 return;
10966 }
10967 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10968 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10969 s.move_with(|map, selection| {
10970 selection.collapse_to(
10971 movement::end_of_paragraph(map, selection.head(), 1),
10972 SelectionGoal::None,
10973 )
10974 });
10975 })
10976 }
10977
10978 pub fn select_to_start_of_paragraph(
10979 &mut self,
10980 _: &SelectToStartOfParagraph,
10981 window: &mut Window,
10982 cx: &mut Context<Self>,
10983 ) {
10984 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10985 cx.propagate();
10986 return;
10987 }
10988 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10989 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10990 s.move_heads_with(|map, head, _| {
10991 (
10992 movement::start_of_paragraph(map, head, 1),
10993 SelectionGoal::None,
10994 )
10995 });
10996 })
10997 }
10998
10999 pub fn select_to_end_of_paragraph(
11000 &mut self,
11001 _: &SelectToEndOfParagraph,
11002 window: &mut Window,
11003 cx: &mut Context<Self>,
11004 ) {
11005 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11006 cx.propagate();
11007 return;
11008 }
11009 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11010 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11011 s.move_heads_with(|map, head, _| {
11012 (
11013 movement::end_of_paragraph(map, head, 1),
11014 SelectionGoal::None,
11015 )
11016 });
11017 })
11018 }
11019
11020 pub fn move_to_start_of_excerpt(
11021 &mut self,
11022 _: &MoveToStartOfExcerpt,
11023 window: &mut Window,
11024 cx: &mut Context<Self>,
11025 ) {
11026 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11027 cx.propagate();
11028 return;
11029 }
11030 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11031 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11032 s.move_with(|map, selection| {
11033 selection.collapse_to(
11034 movement::start_of_excerpt(
11035 map,
11036 selection.head(),
11037 workspace::searchable::Direction::Prev,
11038 ),
11039 SelectionGoal::None,
11040 )
11041 });
11042 })
11043 }
11044
11045 pub fn move_to_start_of_next_excerpt(
11046 &mut self,
11047 _: &MoveToStartOfNextExcerpt,
11048 window: &mut Window,
11049 cx: &mut Context<Self>,
11050 ) {
11051 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11052 cx.propagate();
11053 return;
11054 }
11055
11056 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11057 s.move_with(|map, selection| {
11058 selection.collapse_to(
11059 movement::start_of_excerpt(
11060 map,
11061 selection.head(),
11062 workspace::searchable::Direction::Next,
11063 ),
11064 SelectionGoal::None,
11065 )
11066 });
11067 })
11068 }
11069
11070 pub fn move_to_end_of_excerpt(
11071 &mut self,
11072 _: &MoveToEndOfExcerpt,
11073 window: &mut Window,
11074 cx: &mut Context<Self>,
11075 ) {
11076 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11077 cx.propagate();
11078 return;
11079 }
11080 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11081 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11082 s.move_with(|map, selection| {
11083 selection.collapse_to(
11084 movement::end_of_excerpt(
11085 map,
11086 selection.head(),
11087 workspace::searchable::Direction::Next,
11088 ),
11089 SelectionGoal::None,
11090 )
11091 });
11092 })
11093 }
11094
11095 pub fn move_to_end_of_previous_excerpt(
11096 &mut self,
11097 _: &MoveToEndOfPreviousExcerpt,
11098 window: &mut Window,
11099 cx: &mut Context<Self>,
11100 ) {
11101 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11102 cx.propagate();
11103 return;
11104 }
11105 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11106 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11107 s.move_with(|map, selection| {
11108 selection.collapse_to(
11109 movement::end_of_excerpt(
11110 map,
11111 selection.head(),
11112 workspace::searchable::Direction::Prev,
11113 ),
11114 SelectionGoal::None,
11115 )
11116 });
11117 })
11118 }
11119
11120 pub fn select_to_start_of_excerpt(
11121 &mut self,
11122 _: &SelectToStartOfExcerpt,
11123 window: &mut Window,
11124 cx: &mut Context<Self>,
11125 ) {
11126 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11127 cx.propagate();
11128 return;
11129 }
11130 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11131 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11132 s.move_heads_with(|map, head, _| {
11133 (
11134 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11135 SelectionGoal::None,
11136 )
11137 });
11138 })
11139 }
11140
11141 pub fn select_to_start_of_next_excerpt(
11142 &mut self,
11143 _: &SelectToStartOfNextExcerpt,
11144 window: &mut Window,
11145 cx: &mut Context<Self>,
11146 ) {
11147 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11148 cx.propagate();
11149 return;
11150 }
11151 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11152 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11153 s.move_heads_with(|map, head, _| {
11154 (
11155 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11156 SelectionGoal::None,
11157 )
11158 });
11159 })
11160 }
11161
11162 pub fn select_to_end_of_excerpt(
11163 &mut self,
11164 _: &SelectToEndOfExcerpt,
11165 window: &mut Window,
11166 cx: &mut Context<Self>,
11167 ) {
11168 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11169 cx.propagate();
11170 return;
11171 }
11172 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11173 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11174 s.move_heads_with(|map, head, _| {
11175 (
11176 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11177 SelectionGoal::None,
11178 )
11179 });
11180 })
11181 }
11182
11183 pub fn select_to_end_of_previous_excerpt(
11184 &mut self,
11185 _: &SelectToEndOfPreviousExcerpt,
11186 window: &mut Window,
11187 cx: &mut Context<Self>,
11188 ) {
11189 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11190 cx.propagate();
11191 return;
11192 }
11193 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11194 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11195 s.move_heads_with(|map, head, _| {
11196 (
11197 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11198 SelectionGoal::None,
11199 )
11200 });
11201 })
11202 }
11203
11204 pub fn move_to_beginning(
11205 &mut self,
11206 _: &MoveToBeginning,
11207 window: &mut Window,
11208 cx: &mut Context<Self>,
11209 ) {
11210 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11211 cx.propagate();
11212 return;
11213 }
11214 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11215 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11216 s.select_ranges(vec![0..0]);
11217 });
11218 }
11219
11220 pub fn select_to_beginning(
11221 &mut self,
11222 _: &SelectToBeginning,
11223 window: &mut Window,
11224 cx: &mut Context<Self>,
11225 ) {
11226 let mut selection = self.selections.last::<Point>(cx);
11227 selection.set_head(Point::zero(), SelectionGoal::None);
11228 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11229 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11230 s.select(vec![selection]);
11231 });
11232 }
11233
11234 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11235 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11236 cx.propagate();
11237 return;
11238 }
11239 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11240 let cursor = self.buffer.read(cx).read(cx).len();
11241 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11242 s.select_ranges(vec![cursor..cursor])
11243 });
11244 }
11245
11246 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11247 self.nav_history = nav_history;
11248 }
11249
11250 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11251 self.nav_history.as_ref()
11252 }
11253
11254 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11255 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11256 }
11257
11258 fn push_to_nav_history(
11259 &mut self,
11260 cursor_anchor: Anchor,
11261 new_position: Option<Point>,
11262 is_deactivate: bool,
11263 cx: &mut Context<Self>,
11264 ) {
11265 if let Some(nav_history) = self.nav_history.as_mut() {
11266 let buffer = self.buffer.read(cx).read(cx);
11267 let cursor_position = cursor_anchor.to_point(&buffer);
11268 let scroll_state = self.scroll_manager.anchor();
11269 let scroll_top_row = scroll_state.top_row(&buffer);
11270 drop(buffer);
11271
11272 if let Some(new_position) = new_position {
11273 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11274 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11275 return;
11276 }
11277 }
11278
11279 nav_history.push(
11280 Some(NavigationData {
11281 cursor_anchor,
11282 cursor_position,
11283 scroll_anchor: scroll_state,
11284 scroll_top_row,
11285 }),
11286 cx,
11287 );
11288 cx.emit(EditorEvent::PushedToNavHistory {
11289 anchor: cursor_anchor,
11290 is_deactivate,
11291 })
11292 }
11293 }
11294
11295 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11296 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11297 let buffer = self.buffer.read(cx).snapshot(cx);
11298 let mut selection = self.selections.first::<usize>(cx);
11299 selection.set_head(buffer.len(), SelectionGoal::None);
11300 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11301 s.select(vec![selection]);
11302 });
11303 }
11304
11305 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11306 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11307 let end = self.buffer.read(cx).read(cx).len();
11308 self.change_selections(None, window, cx, |s| {
11309 s.select_ranges(vec![0..end]);
11310 });
11311 }
11312
11313 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11314 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11315 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11316 let mut selections = self.selections.all::<Point>(cx);
11317 let max_point = display_map.buffer_snapshot.max_point();
11318 for selection in &mut selections {
11319 let rows = selection.spanned_rows(true, &display_map);
11320 selection.start = Point::new(rows.start.0, 0);
11321 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11322 selection.reversed = false;
11323 }
11324 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11325 s.select(selections);
11326 });
11327 }
11328
11329 pub fn split_selection_into_lines(
11330 &mut self,
11331 _: &SplitSelectionIntoLines,
11332 window: &mut Window,
11333 cx: &mut Context<Self>,
11334 ) {
11335 let selections = self
11336 .selections
11337 .all::<Point>(cx)
11338 .into_iter()
11339 .map(|selection| selection.start..selection.end)
11340 .collect::<Vec<_>>();
11341 self.unfold_ranges(&selections, true, true, cx);
11342
11343 let mut new_selection_ranges = Vec::new();
11344 {
11345 let buffer = self.buffer.read(cx).read(cx);
11346 for selection in selections {
11347 for row in selection.start.row..selection.end.row {
11348 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11349 new_selection_ranges.push(cursor..cursor);
11350 }
11351
11352 let is_multiline_selection = selection.start.row != selection.end.row;
11353 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11354 // so this action feels more ergonomic when paired with other selection operations
11355 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11356 if !should_skip_last {
11357 new_selection_ranges.push(selection.end..selection.end);
11358 }
11359 }
11360 }
11361 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11362 s.select_ranges(new_selection_ranges);
11363 });
11364 }
11365
11366 pub fn add_selection_above(
11367 &mut self,
11368 _: &AddSelectionAbove,
11369 window: &mut Window,
11370 cx: &mut Context<Self>,
11371 ) {
11372 self.add_selection(true, window, cx);
11373 }
11374
11375 pub fn add_selection_below(
11376 &mut self,
11377 _: &AddSelectionBelow,
11378 window: &mut Window,
11379 cx: &mut Context<Self>,
11380 ) {
11381 self.add_selection(false, window, cx);
11382 }
11383
11384 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11385 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11386
11387 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11388 let mut selections = self.selections.all::<Point>(cx);
11389 let text_layout_details = self.text_layout_details(window);
11390 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11391 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11392 let range = oldest_selection.display_range(&display_map).sorted();
11393
11394 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11395 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11396 let positions = start_x.min(end_x)..start_x.max(end_x);
11397
11398 selections.clear();
11399 let mut stack = Vec::new();
11400 for row in range.start.row().0..=range.end.row().0 {
11401 if let Some(selection) = self.selections.build_columnar_selection(
11402 &display_map,
11403 DisplayRow(row),
11404 &positions,
11405 oldest_selection.reversed,
11406 &text_layout_details,
11407 ) {
11408 stack.push(selection.id);
11409 selections.push(selection);
11410 }
11411 }
11412
11413 if above {
11414 stack.reverse();
11415 }
11416
11417 AddSelectionsState { above, stack }
11418 });
11419
11420 let last_added_selection = *state.stack.last().unwrap();
11421 let mut new_selections = Vec::new();
11422 if above == state.above {
11423 let end_row = if above {
11424 DisplayRow(0)
11425 } else {
11426 display_map.max_point().row()
11427 };
11428
11429 'outer: for selection in selections {
11430 if selection.id == last_added_selection {
11431 let range = selection.display_range(&display_map).sorted();
11432 debug_assert_eq!(range.start.row(), range.end.row());
11433 let mut row = range.start.row();
11434 let positions =
11435 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11436 px(start)..px(end)
11437 } else {
11438 let start_x =
11439 display_map.x_for_display_point(range.start, &text_layout_details);
11440 let end_x =
11441 display_map.x_for_display_point(range.end, &text_layout_details);
11442 start_x.min(end_x)..start_x.max(end_x)
11443 };
11444
11445 while row != end_row {
11446 if above {
11447 row.0 -= 1;
11448 } else {
11449 row.0 += 1;
11450 }
11451
11452 if let Some(new_selection) = self.selections.build_columnar_selection(
11453 &display_map,
11454 row,
11455 &positions,
11456 selection.reversed,
11457 &text_layout_details,
11458 ) {
11459 state.stack.push(new_selection.id);
11460 if above {
11461 new_selections.push(new_selection);
11462 new_selections.push(selection);
11463 } else {
11464 new_selections.push(selection);
11465 new_selections.push(new_selection);
11466 }
11467
11468 continue 'outer;
11469 }
11470 }
11471 }
11472
11473 new_selections.push(selection);
11474 }
11475 } else {
11476 new_selections = selections;
11477 new_selections.retain(|s| s.id != last_added_selection);
11478 state.stack.pop();
11479 }
11480
11481 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11482 s.select(new_selections);
11483 });
11484 if state.stack.len() > 1 {
11485 self.add_selections_state = Some(state);
11486 }
11487 }
11488
11489 pub fn select_next_match_internal(
11490 &mut self,
11491 display_map: &DisplaySnapshot,
11492 replace_newest: bool,
11493 autoscroll: Option<Autoscroll>,
11494 window: &mut Window,
11495 cx: &mut Context<Self>,
11496 ) -> Result<()> {
11497 fn select_next_match_ranges(
11498 this: &mut Editor,
11499 range: Range<usize>,
11500 replace_newest: bool,
11501 auto_scroll: Option<Autoscroll>,
11502 window: &mut Window,
11503 cx: &mut Context<Editor>,
11504 ) {
11505 this.unfold_ranges(&[range.clone()], false, true, cx);
11506 this.change_selections(auto_scroll, window, cx, |s| {
11507 if replace_newest {
11508 s.delete(s.newest_anchor().id);
11509 }
11510 s.insert_range(range.clone());
11511 });
11512 }
11513
11514 let buffer = &display_map.buffer_snapshot;
11515 let mut selections = self.selections.all::<usize>(cx);
11516 if let Some(mut select_next_state) = self.select_next_state.take() {
11517 let query = &select_next_state.query;
11518 if !select_next_state.done {
11519 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11520 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11521 let mut next_selected_range = None;
11522
11523 let bytes_after_last_selection =
11524 buffer.bytes_in_range(last_selection.end..buffer.len());
11525 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11526 let query_matches = query
11527 .stream_find_iter(bytes_after_last_selection)
11528 .map(|result| (last_selection.end, result))
11529 .chain(
11530 query
11531 .stream_find_iter(bytes_before_first_selection)
11532 .map(|result| (0, result)),
11533 );
11534
11535 for (start_offset, query_match) in query_matches {
11536 let query_match = query_match.unwrap(); // can only fail due to I/O
11537 let offset_range =
11538 start_offset + query_match.start()..start_offset + query_match.end();
11539 let display_range = offset_range.start.to_display_point(display_map)
11540 ..offset_range.end.to_display_point(display_map);
11541
11542 if !select_next_state.wordwise
11543 || (!movement::is_inside_word(display_map, display_range.start)
11544 && !movement::is_inside_word(display_map, display_range.end))
11545 {
11546 // TODO: This is n^2, because we might check all the selections
11547 if !selections
11548 .iter()
11549 .any(|selection| selection.range().overlaps(&offset_range))
11550 {
11551 next_selected_range = Some(offset_range);
11552 break;
11553 }
11554 }
11555 }
11556
11557 if let Some(next_selected_range) = next_selected_range {
11558 select_next_match_ranges(
11559 self,
11560 next_selected_range,
11561 replace_newest,
11562 autoscroll,
11563 window,
11564 cx,
11565 );
11566 } else {
11567 select_next_state.done = true;
11568 }
11569 }
11570
11571 self.select_next_state = Some(select_next_state);
11572 } else {
11573 let mut only_carets = true;
11574 let mut same_text_selected = true;
11575 let mut selected_text = None;
11576
11577 let mut selections_iter = selections.iter().peekable();
11578 while let Some(selection) = selections_iter.next() {
11579 if selection.start != selection.end {
11580 only_carets = false;
11581 }
11582
11583 if same_text_selected {
11584 if selected_text.is_none() {
11585 selected_text =
11586 Some(buffer.text_for_range(selection.range()).collect::<String>());
11587 }
11588
11589 if let Some(next_selection) = selections_iter.peek() {
11590 if next_selection.range().len() == selection.range().len() {
11591 let next_selected_text = buffer
11592 .text_for_range(next_selection.range())
11593 .collect::<String>();
11594 if Some(next_selected_text) != selected_text {
11595 same_text_selected = false;
11596 selected_text = None;
11597 }
11598 } else {
11599 same_text_selected = false;
11600 selected_text = None;
11601 }
11602 }
11603 }
11604 }
11605
11606 if only_carets {
11607 for selection in &mut selections {
11608 let word_range = movement::surrounding_word(
11609 display_map,
11610 selection.start.to_display_point(display_map),
11611 );
11612 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11613 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11614 selection.goal = SelectionGoal::None;
11615 selection.reversed = false;
11616 select_next_match_ranges(
11617 self,
11618 selection.start..selection.end,
11619 replace_newest,
11620 autoscroll,
11621 window,
11622 cx,
11623 );
11624 }
11625
11626 if selections.len() == 1 {
11627 let selection = selections
11628 .last()
11629 .expect("ensured that there's only one selection");
11630 let query = buffer
11631 .text_for_range(selection.start..selection.end)
11632 .collect::<String>();
11633 let is_empty = query.is_empty();
11634 let select_state = SelectNextState {
11635 query: AhoCorasick::new(&[query])?,
11636 wordwise: true,
11637 done: is_empty,
11638 };
11639 self.select_next_state = Some(select_state);
11640 } else {
11641 self.select_next_state = None;
11642 }
11643 } else if let Some(selected_text) = selected_text {
11644 self.select_next_state = Some(SelectNextState {
11645 query: AhoCorasick::new(&[selected_text])?,
11646 wordwise: false,
11647 done: false,
11648 });
11649 self.select_next_match_internal(
11650 display_map,
11651 replace_newest,
11652 autoscroll,
11653 window,
11654 cx,
11655 )?;
11656 }
11657 }
11658 Ok(())
11659 }
11660
11661 pub fn select_all_matches(
11662 &mut self,
11663 _action: &SelectAllMatches,
11664 window: &mut Window,
11665 cx: &mut Context<Self>,
11666 ) -> Result<()> {
11667 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11668
11669 self.push_to_selection_history();
11670 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11671
11672 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11673 let Some(select_next_state) = self.select_next_state.as_mut() else {
11674 return Ok(());
11675 };
11676 if select_next_state.done {
11677 return Ok(());
11678 }
11679
11680 let mut new_selections = self.selections.all::<usize>(cx);
11681
11682 let buffer = &display_map.buffer_snapshot;
11683 let query_matches = select_next_state
11684 .query
11685 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11686
11687 for query_match in query_matches {
11688 let query_match = query_match.unwrap(); // can only fail due to I/O
11689 let offset_range = query_match.start()..query_match.end();
11690 let display_range = offset_range.start.to_display_point(&display_map)
11691 ..offset_range.end.to_display_point(&display_map);
11692
11693 if !select_next_state.wordwise
11694 || (!movement::is_inside_word(&display_map, display_range.start)
11695 && !movement::is_inside_word(&display_map, display_range.end))
11696 {
11697 self.selections.change_with(cx, |selections| {
11698 new_selections.push(Selection {
11699 id: selections.new_selection_id(),
11700 start: offset_range.start,
11701 end: offset_range.end,
11702 reversed: false,
11703 goal: SelectionGoal::None,
11704 });
11705 });
11706 }
11707 }
11708
11709 new_selections.sort_by_key(|selection| selection.start);
11710 let mut ix = 0;
11711 while ix + 1 < new_selections.len() {
11712 let current_selection = &new_selections[ix];
11713 let next_selection = &new_selections[ix + 1];
11714 if current_selection.range().overlaps(&next_selection.range()) {
11715 if current_selection.id < next_selection.id {
11716 new_selections.remove(ix + 1);
11717 } else {
11718 new_selections.remove(ix);
11719 }
11720 } else {
11721 ix += 1;
11722 }
11723 }
11724
11725 let reversed = self.selections.oldest::<usize>(cx).reversed;
11726
11727 for selection in new_selections.iter_mut() {
11728 selection.reversed = reversed;
11729 }
11730
11731 select_next_state.done = true;
11732 self.unfold_ranges(
11733 &new_selections
11734 .iter()
11735 .map(|selection| selection.range())
11736 .collect::<Vec<_>>(),
11737 false,
11738 false,
11739 cx,
11740 );
11741 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11742 selections.select(new_selections)
11743 });
11744
11745 Ok(())
11746 }
11747
11748 pub fn select_next(
11749 &mut self,
11750 action: &SelectNext,
11751 window: &mut Window,
11752 cx: &mut Context<Self>,
11753 ) -> Result<()> {
11754 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11755 self.push_to_selection_history();
11756 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11757 self.select_next_match_internal(
11758 &display_map,
11759 action.replace_newest,
11760 Some(Autoscroll::newest()),
11761 window,
11762 cx,
11763 )?;
11764 Ok(())
11765 }
11766
11767 pub fn select_previous(
11768 &mut self,
11769 action: &SelectPrevious,
11770 window: &mut Window,
11771 cx: &mut Context<Self>,
11772 ) -> Result<()> {
11773 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11774 self.push_to_selection_history();
11775 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11776 let buffer = &display_map.buffer_snapshot;
11777 let mut selections = self.selections.all::<usize>(cx);
11778 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11779 let query = &select_prev_state.query;
11780 if !select_prev_state.done {
11781 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11782 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11783 let mut next_selected_range = None;
11784 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11785 let bytes_before_last_selection =
11786 buffer.reversed_bytes_in_range(0..last_selection.start);
11787 let bytes_after_first_selection =
11788 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11789 let query_matches = query
11790 .stream_find_iter(bytes_before_last_selection)
11791 .map(|result| (last_selection.start, result))
11792 .chain(
11793 query
11794 .stream_find_iter(bytes_after_first_selection)
11795 .map(|result| (buffer.len(), result)),
11796 );
11797 for (end_offset, query_match) in query_matches {
11798 let query_match = query_match.unwrap(); // can only fail due to I/O
11799 let offset_range =
11800 end_offset - query_match.end()..end_offset - query_match.start();
11801 let display_range = offset_range.start.to_display_point(&display_map)
11802 ..offset_range.end.to_display_point(&display_map);
11803
11804 if !select_prev_state.wordwise
11805 || (!movement::is_inside_word(&display_map, display_range.start)
11806 && !movement::is_inside_word(&display_map, display_range.end))
11807 {
11808 next_selected_range = Some(offset_range);
11809 break;
11810 }
11811 }
11812
11813 if let Some(next_selected_range) = next_selected_range {
11814 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11815 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11816 if action.replace_newest {
11817 s.delete(s.newest_anchor().id);
11818 }
11819 s.insert_range(next_selected_range);
11820 });
11821 } else {
11822 select_prev_state.done = true;
11823 }
11824 }
11825
11826 self.select_prev_state = Some(select_prev_state);
11827 } else {
11828 let mut only_carets = true;
11829 let mut same_text_selected = true;
11830 let mut selected_text = None;
11831
11832 let mut selections_iter = selections.iter().peekable();
11833 while let Some(selection) = selections_iter.next() {
11834 if selection.start != selection.end {
11835 only_carets = false;
11836 }
11837
11838 if same_text_selected {
11839 if selected_text.is_none() {
11840 selected_text =
11841 Some(buffer.text_for_range(selection.range()).collect::<String>());
11842 }
11843
11844 if let Some(next_selection) = selections_iter.peek() {
11845 if next_selection.range().len() == selection.range().len() {
11846 let next_selected_text = buffer
11847 .text_for_range(next_selection.range())
11848 .collect::<String>();
11849 if Some(next_selected_text) != selected_text {
11850 same_text_selected = false;
11851 selected_text = None;
11852 }
11853 } else {
11854 same_text_selected = false;
11855 selected_text = None;
11856 }
11857 }
11858 }
11859 }
11860
11861 if only_carets {
11862 for selection in &mut selections {
11863 let word_range = movement::surrounding_word(
11864 &display_map,
11865 selection.start.to_display_point(&display_map),
11866 );
11867 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11868 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11869 selection.goal = SelectionGoal::None;
11870 selection.reversed = false;
11871 }
11872 if selections.len() == 1 {
11873 let selection = selections
11874 .last()
11875 .expect("ensured that there's only one selection");
11876 let query = buffer
11877 .text_for_range(selection.start..selection.end)
11878 .collect::<String>();
11879 let is_empty = query.is_empty();
11880 let select_state = SelectNextState {
11881 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11882 wordwise: true,
11883 done: is_empty,
11884 };
11885 self.select_prev_state = Some(select_state);
11886 } else {
11887 self.select_prev_state = None;
11888 }
11889
11890 self.unfold_ranges(
11891 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11892 false,
11893 true,
11894 cx,
11895 );
11896 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11897 s.select(selections);
11898 });
11899 } else if let Some(selected_text) = selected_text {
11900 self.select_prev_state = Some(SelectNextState {
11901 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11902 wordwise: false,
11903 done: false,
11904 });
11905 self.select_previous(action, window, cx)?;
11906 }
11907 }
11908 Ok(())
11909 }
11910
11911 pub fn toggle_comments(
11912 &mut self,
11913 action: &ToggleComments,
11914 window: &mut Window,
11915 cx: &mut Context<Self>,
11916 ) {
11917 if self.read_only(cx) {
11918 return;
11919 }
11920 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11921 let text_layout_details = &self.text_layout_details(window);
11922 self.transact(window, cx, |this, window, cx| {
11923 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11924 let mut edits = Vec::new();
11925 let mut selection_edit_ranges = Vec::new();
11926 let mut last_toggled_row = None;
11927 let snapshot = this.buffer.read(cx).read(cx);
11928 let empty_str: Arc<str> = Arc::default();
11929 let mut suffixes_inserted = Vec::new();
11930 let ignore_indent = action.ignore_indent;
11931
11932 fn comment_prefix_range(
11933 snapshot: &MultiBufferSnapshot,
11934 row: MultiBufferRow,
11935 comment_prefix: &str,
11936 comment_prefix_whitespace: &str,
11937 ignore_indent: bool,
11938 ) -> Range<Point> {
11939 let indent_size = if ignore_indent {
11940 0
11941 } else {
11942 snapshot.indent_size_for_line(row).len
11943 };
11944
11945 let start = Point::new(row.0, indent_size);
11946
11947 let mut line_bytes = snapshot
11948 .bytes_in_range(start..snapshot.max_point())
11949 .flatten()
11950 .copied();
11951
11952 // If this line currently begins with the line comment prefix, then record
11953 // the range containing the prefix.
11954 if line_bytes
11955 .by_ref()
11956 .take(comment_prefix.len())
11957 .eq(comment_prefix.bytes())
11958 {
11959 // Include any whitespace that matches the comment prefix.
11960 let matching_whitespace_len = line_bytes
11961 .zip(comment_prefix_whitespace.bytes())
11962 .take_while(|(a, b)| a == b)
11963 .count() as u32;
11964 let end = Point::new(
11965 start.row,
11966 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11967 );
11968 start..end
11969 } else {
11970 start..start
11971 }
11972 }
11973
11974 fn comment_suffix_range(
11975 snapshot: &MultiBufferSnapshot,
11976 row: MultiBufferRow,
11977 comment_suffix: &str,
11978 comment_suffix_has_leading_space: bool,
11979 ) -> Range<Point> {
11980 let end = Point::new(row.0, snapshot.line_len(row));
11981 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11982
11983 let mut line_end_bytes = snapshot
11984 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11985 .flatten()
11986 .copied();
11987
11988 let leading_space_len = if suffix_start_column > 0
11989 && line_end_bytes.next() == Some(b' ')
11990 && comment_suffix_has_leading_space
11991 {
11992 1
11993 } else {
11994 0
11995 };
11996
11997 // If this line currently begins with the line comment prefix, then record
11998 // the range containing the prefix.
11999 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12000 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12001 start..end
12002 } else {
12003 end..end
12004 }
12005 }
12006
12007 // TODO: Handle selections that cross excerpts
12008 for selection in &mut selections {
12009 let start_column = snapshot
12010 .indent_size_for_line(MultiBufferRow(selection.start.row))
12011 .len;
12012 let language = if let Some(language) =
12013 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12014 {
12015 language
12016 } else {
12017 continue;
12018 };
12019
12020 selection_edit_ranges.clear();
12021
12022 // If multiple selections contain a given row, avoid processing that
12023 // row more than once.
12024 let mut start_row = MultiBufferRow(selection.start.row);
12025 if last_toggled_row == Some(start_row) {
12026 start_row = start_row.next_row();
12027 }
12028 let end_row =
12029 if selection.end.row > selection.start.row && selection.end.column == 0 {
12030 MultiBufferRow(selection.end.row - 1)
12031 } else {
12032 MultiBufferRow(selection.end.row)
12033 };
12034 last_toggled_row = Some(end_row);
12035
12036 if start_row > end_row {
12037 continue;
12038 }
12039
12040 // If the language has line comments, toggle those.
12041 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12042
12043 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12044 if ignore_indent {
12045 full_comment_prefixes = full_comment_prefixes
12046 .into_iter()
12047 .map(|s| Arc::from(s.trim_end()))
12048 .collect();
12049 }
12050
12051 if !full_comment_prefixes.is_empty() {
12052 let first_prefix = full_comment_prefixes
12053 .first()
12054 .expect("prefixes is non-empty");
12055 let prefix_trimmed_lengths = full_comment_prefixes
12056 .iter()
12057 .map(|p| p.trim_end_matches(' ').len())
12058 .collect::<SmallVec<[usize; 4]>>();
12059
12060 let mut all_selection_lines_are_comments = true;
12061
12062 for row in start_row.0..=end_row.0 {
12063 let row = MultiBufferRow(row);
12064 if start_row < end_row && snapshot.is_line_blank(row) {
12065 continue;
12066 }
12067
12068 let prefix_range = full_comment_prefixes
12069 .iter()
12070 .zip(prefix_trimmed_lengths.iter().copied())
12071 .map(|(prefix, trimmed_prefix_len)| {
12072 comment_prefix_range(
12073 snapshot.deref(),
12074 row,
12075 &prefix[..trimmed_prefix_len],
12076 &prefix[trimmed_prefix_len..],
12077 ignore_indent,
12078 )
12079 })
12080 .max_by_key(|range| range.end.column - range.start.column)
12081 .expect("prefixes is non-empty");
12082
12083 if prefix_range.is_empty() {
12084 all_selection_lines_are_comments = false;
12085 }
12086
12087 selection_edit_ranges.push(prefix_range);
12088 }
12089
12090 if all_selection_lines_are_comments {
12091 edits.extend(
12092 selection_edit_ranges
12093 .iter()
12094 .cloned()
12095 .map(|range| (range, empty_str.clone())),
12096 );
12097 } else {
12098 let min_column = selection_edit_ranges
12099 .iter()
12100 .map(|range| range.start.column)
12101 .min()
12102 .unwrap_or(0);
12103 edits.extend(selection_edit_ranges.iter().map(|range| {
12104 let position = Point::new(range.start.row, min_column);
12105 (position..position, first_prefix.clone())
12106 }));
12107 }
12108 } else if let Some((full_comment_prefix, comment_suffix)) =
12109 language.block_comment_delimiters()
12110 {
12111 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12112 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12113 let prefix_range = comment_prefix_range(
12114 snapshot.deref(),
12115 start_row,
12116 comment_prefix,
12117 comment_prefix_whitespace,
12118 ignore_indent,
12119 );
12120 let suffix_range = comment_suffix_range(
12121 snapshot.deref(),
12122 end_row,
12123 comment_suffix.trim_start_matches(' '),
12124 comment_suffix.starts_with(' '),
12125 );
12126
12127 if prefix_range.is_empty() || suffix_range.is_empty() {
12128 edits.push((
12129 prefix_range.start..prefix_range.start,
12130 full_comment_prefix.clone(),
12131 ));
12132 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12133 suffixes_inserted.push((end_row, comment_suffix.len()));
12134 } else {
12135 edits.push((prefix_range, empty_str.clone()));
12136 edits.push((suffix_range, empty_str.clone()));
12137 }
12138 } else {
12139 continue;
12140 }
12141 }
12142
12143 drop(snapshot);
12144 this.buffer.update(cx, |buffer, cx| {
12145 buffer.edit(edits, None, cx);
12146 });
12147
12148 // Adjust selections so that they end before any comment suffixes that
12149 // were inserted.
12150 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12151 let mut selections = this.selections.all::<Point>(cx);
12152 let snapshot = this.buffer.read(cx).read(cx);
12153 for selection in &mut selections {
12154 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12155 match row.cmp(&MultiBufferRow(selection.end.row)) {
12156 Ordering::Less => {
12157 suffixes_inserted.next();
12158 continue;
12159 }
12160 Ordering::Greater => break,
12161 Ordering::Equal => {
12162 if selection.end.column == snapshot.line_len(row) {
12163 if selection.is_empty() {
12164 selection.start.column -= suffix_len as u32;
12165 }
12166 selection.end.column -= suffix_len as u32;
12167 }
12168 break;
12169 }
12170 }
12171 }
12172 }
12173
12174 drop(snapshot);
12175 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12176 s.select(selections)
12177 });
12178
12179 let selections = this.selections.all::<Point>(cx);
12180 let selections_on_single_row = selections.windows(2).all(|selections| {
12181 selections[0].start.row == selections[1].start.row
12182 && selections[0].end.row == selections[1].end.row
12183 && selections[0].start.row == selections[0].end.row
12184 });
12185 let selections_selecting = selections
12186 .iter()
12187 .any(|selection| selection.start != selection.end);
12188 let advance_downwards = action.advance_downwards
12189 && selections_on_single_row
12190 && !selections_selecting
12191 && !matches!(this.mode, EditorMode::SingleLine { .. });
12192
12193 if advance_downwards {
12194 let snapshot = this.buffer.read(cx).snapshot(cx);
12195
12196 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12197 s.move_cursors_with(|display_snapshot, display_point, _| {
12198 let mut point = display_point.to_point(display_snapshot);
12199 point.row += 1;
12200 point = snapshot.clip_point(point, Bias::Left);
12201 let display_point = point.to_display_point(display_snapshot);
12202 let goal = SelectionGoal::HorizontalPosition(
12203 display_snapshot
12204 .x_for_display_point(display_point, text_layout_details)
12205 .into(),
12206 );
12207 (display_point, goal)
12208 })
12209 });
12210 }
12211 });
12212 }
12213
12214 pub fn select_enclosing_symbol(
12215 &mut self,
12216 _: &SelectEnclosingSymbol,
12217 window: &mut Window,
12218 cx: &mut Context<Self>,
12219 ) {
12220 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12221
12222 let buffer = self.buffer.read(cx).snapshot(cx);
12223 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12224
12225 fn update_selection(
12226 selection: &Selection<usize>,
12227 buffer_snap: &MultiBufferSnapshot,
12228 ) -> Option<Selection<usize>> {
12229 let cursor = selection.head();
12230 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12231 for symbol in symbols.iter().rev() {
12232 let start = symbol.range.start.to_offset(buffer_snap);
12233 let end = symbol.range.end.to_offset(buffer_snap);
12234 let new_range = start..end;
12235 if start < selection.start || end > selection.end {
12236 return Some(Selection {
12237 id: selection.id,
12238 start: new_range.start,
12239 end: new_range.end,
12240 goal: SelectionGoal::None,
12241 reversed: selection.reversed,
12242 });
12243 }
12244 }
12245 None
12246 }
12247
12248 let mut selected_larger_symbol = false;
12249 let new_selections = old_selections
12250 .iter()
12251 .map(|selection| match update_selection(selection, &buffer) {
12252 Some(new_selection) => {
12253 if new_selection.range() != selection.range() {
12254 selected_larger_symbol = true;
12255 }
12256 new_selection
12257 }
12258 None => selection.clone(),
12259 })
12260 .collect::<Vec<_>>();
12261
12262 if selected_larger_symbol {
12263 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12264 s.select(new_selections);
12265 });
12266 }
12267 }
12268
12269 pub fn select_larger_syntax_node(
12270 &mut self,
12271 _: &SelectLargerSyntaxNode,
12272 window: &mut Window,
12273 cx: &mut Context<Self>,
12274 ) {
12275 let Some(visible_row_count) = self.visible_row_count() else {
12276 return;
12277 };
12278 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12279 if old_selections.is_empty() {
12280 return;
12281 }
12282
12283 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12284
12285 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12286 let buffer = self.buffer.read(cx).snapshot(cx);
12287
12288 let mut selected_larger_node = false;
12289 let mut new_selections = old_selections
12290 .iter()
12291 .map(|selection| {
12292 let old_range = selection.start..selection.end;
12293 let mut new_range = old_range.clone();
12294 let mut new_node = None;
12295 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12296 {
12297 new_node = Some(node);
12298 new_range = match containing_range {
12299 MultiOrSingleBufferOffsetRange::Single(_) => break,
12300 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12301 };
12302 if !display_map.intersects_fold(new_range.start)
12303 && !display_map.intersects_fold(new_range.end)
12304 {
12305 break;
12306 }
12307 }
12308
12309 if let Some(node) = new_node {
12310 // Log the ancestor, to support using this action as a way to explore TreeSitter
12311 // nodes. Parent and grandparent are also logged because this operation will not
12312 // visit nodes that have the same range as their parent.
12313 log::info!("Node: {node:?}");
12314 let parent = node.parent();
12315 log::info!("Parent: {parent:?}");
12316 let grandparent = parent.and_then(|x| x.parent());
12317 log::info!("Grandparent: {grandparent:?}");
12318 }
12319
12320 selected_larger_node |= new_range != old_range;
12321 Selection {
12322 id: selection.id,
12323 start: new_range.start,
12324 end: new_range.end,
12325 goal: SelectionGoal::None,
12326 reversed: selection.reversed,
12327 }
12328 })
12329 .collect::<Vec<_>>();
12330
12331 if !selected_larger_node {
12332 return; // don't put this call in the history
12333 }
12334
12335 // scroll based on transformation done to the last selection created by the user
12336 let (last_old, last_new) = old_selections
12337 .last()
12338 .zip(new_selections.last().cloned())
12339 .expect("old_selections isn't empty");
12340
12341 // revert selection
12342 let is_selection_reversed = {
12343 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12344 new_selections.last_mut().expect("checked above").reversed =
12345 should_newest_selection_be_reversed;
12346 should_newest_selection_be_reversed
12347 };
12348
12349 if selected_larger_node {
12350 self.select_syntax_node_history.disable_clearing = true;
12351 self.change_selections(None, window, cx, |s| {
12352 s.select(new_selections.clone());
12353 });
12354 self.select_syntax_node_history.disable_clearing = false;
12355 }
12356
12357 let start_row = last_new.start.to_display_point(&display_map).row().0;
12358 let end_row = last_new.end.to_display_point(&display_map).row().0;
12359 let selection_height = end_row - start_row + 1;
12360 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12361
12362 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12363 let scroll_behavior = if fits_on_the_screen {
12364 self.request_autoscroll(Autoscroll::fit(), cx);
12365 SelectSyntaxNodeScrollBehavior::FitSelection
12366 } else if is_selection_reversed {
12367 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12368 SelectSyntaxNodeScrollBehavior::CursorTop
12369 } else {
12370 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12371 SelectSyntaxNodeScrollBehavior::CursorBottom
12372 };
12373
12374 self.select_syntax_node_history.push((
12375 old_selections,
12376 scroll_behavior,
12377 is_selection_reversed,
12378 ));
12379 }
12380
12381 pub fn select_smaller_syntax_node(
12382 &mut self,
12383 _: &SelectSmallerSyntaxNode,
12384 window: &mut Window,
12385 cx: &mut Context<Self>,
12386 ) {
12387 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12388
12389 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12390 self.select_syntax_node_history.pop()
12391 {
12392 if let Some(selection) = selections.last_mut() {
12393 selection.reversed = is_selection_reversed;
12394 }
12395
12396 self.select_syntax_node_history.disable_clearing = true;
12397 self.change_selections(None, window, cx, |s| {
12398 s.select(selections.to_vec());
12399 });
12400 self.select_syntax_node_history.disable_clearing = false;
12401
12402 match scroll_behavior {
12403 SelectSyntaxNodeScrollBehavior::CursorTop => {
12404 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12405 }
12406 SelectSyntaxNodeScrollBehavior::FitSelection => {
12407 self.request_autoscroll(Autoscroll::fit(), cx);
12408 }
12409 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12410 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12411 }
12412 }
12413 }
12414 }
12415
12416 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12417 if !EditorSettings::get_global(cx).gutter.runnables {
12418 self.clear_tasks();
12419 return Task::ready(());
12420 }
12421 let project = self.project.as_ref().map(Entity::downgrade);
12422 cx.spawn_in(window, async move |this, cx| {
12423 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12424 let Some(project) = project.and_then(|p| p.upgrade()) else {
12425 return;
12426 };
12427 let Ok(display_snapshot) = this.update(cx, |this, cx| {
12428 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12429 }) else {
12430 return;
12431 };
12432
12433 let hide_runnables = project
12434 .update(cx, |project, cx| {
12435 // Do not display any test indicators in non-dev server remote projects.
12436 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12437 })
12438 .unwrap_or(true);
12439 if hide_runnables {
12440 return;
12441 }
12442 let new_rows =
12443 cx.background_spawn({
12444 let snapshot = display_snapshot.clone();
12445 async move {
12446 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12447 }
12448 })
12449 .await;
12450
12451 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12452 this.update(cx, |this, _| {
12453 this.clear_tasks();
12454 for (key, value) in rows {
12455 this.insert_tasks(key, value);
12456 }
12457 })
12458 .ok();
12459 })
12460 }
12461 fn fetch_runnable_ranges(
12462 snapshot: &DisplaySnapshot,
12463 range: Range<Anchor>,
12464 ) -> Vec<language::RunnableRange> {
12465 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12466 }
12467
12468 fn runnable_rows(
12469 project: Entity<Project>,
12470 snapshot: DisplaySnapshot,
12471 runnable_ranges: Vec<RunnableRange>,
12472 mut cx: AsyncWindowContext,
12473 ) -> Vec<((BufferId, u32), RunnableTasks)> {
12474 runnable_ranges
12475 .into_iter()
12476 .filter_map(|mut runnable| {
12477 let tasks = cx
12478 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12479 .ok()?;
12480 if tasks.is_empty() {
12481 return None;
12482 }
12483
12484 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12485
12486 let row = snapshot
12487 .buffer_snapshot
12488 .buffer_line_for_row(MultiBufferRow(point.row))?
12489 .1
12490 .start
12491 .row;
12492
12493 let context_range =
12494 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12495 Some((
12496 (runnable.buffer_id, row),
12497 RunnableTasks {
12498 templates: tasks,
12499 offset: snapshot
12500 .buffer_snapshot
12501 .anchor_before(runnable.run_range.start),
12502 context_range,
12503 column: point.column,
12504 extra_variables: runnable.extra_captures,
12505 },
12506 ))
12507 })
12508 .collect()
12509 }
12510
12511 fn templates_with_tags(
12512 project: &Entity<Project>,
12513 runnable: &mut Runnable,
12514 cx: &mut App,
12515 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12516 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12517 let (worktree_id, file) = project
12518 .buffer_for_id(runnable.buffer, cx)
12519 .and_then(|buffer| buffer.read(cx).file())
12520 .map(|file| (file.worktree_id(cx), file.clone()))
12521 .unzip();
12522
12523 (
12524 project.task_store().read(cx).task_inventory().cloned(),
12525 worktree_id,
12526 file,
12527 )
12528 });
12529
12530 let tags = mem::take(&mut runnable.tags);
12531 let mut tags: Vec<_> = tags
12532 .into_iter()
12533 .flat_map(|tag| {
12534 let tag = tag.0.clone();
12535 inventory
12536 .as_ref()
12537 .into_iter()
12538 .flat_map(|inventory| {
12539 inventory.read(cx).list_tasks(
12540 file.clone(),
12541 Some(runnable.language.clone()),
12542 worktree_id,
12543 cx,
12544 )
12545 })
12546 .filter(move |(_, template)| {
12547 template.tags.iter().any(|source_tag| source_tag == &tag)
12548 })
12549 })
12550 .sorted_by_key(|(kind, _)| kind.to_owned())
12551 .collect();
12552 if let Some((leading_tag_source, _)) = tags.first() {
12553 // Strongest source wins; if we have worktree tag binding, prefer that to
12554 // global and language bindings;
12555 // if we have a global binding, prefer that to language binding.
12556 let first_mismatch = tags
12557 .iter()
12558 .position(|(tag_source, _)| tag_source != leading_tag_source);
12559 if let Some(index) = first_mismatch {
12560 tags.truncate(index);
12561 }
12562 }
12563
12564 tags
12565 }
12566
12567 pub fn move_to_enclosing_bracket(
12568 &mut self,
12569 _: &MoveToEnclosingBracket,
12570 window: &mut Window,
12571 cx: &mut Context<Self>,
12572 ) {
12573 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12574 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12575 s.move_offsets_with(|snapshot, selection| {
12576 let Some(enclosing_bracket_ranges) =
12577 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12578 else {
12579 return;
12580 };
12581
12582 let mut best_length = usize::MAX;
12583 let mut best_inside = false;
12584 let mut best_in_bracket_range = false;
12585 let mut best_destination = None;
12586 for (open, close) in enclosing_bracket_ranges {
12587 let close = close.to_inclusive();
12588 let length = close.end() - open.start;
12589 let inside = selection.start >= open.end && selection.end <= *close.start();
12590 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12591 || close.contains(&selection.head());
12592
12593 // If best is next to a bracket and current isn't, skip
12594 if !in_bracket_range && best_in_bracket_range {
12595 continue;
12596 }
12597
12598 // Prefer smaller lengths unless best is inside and current isn't
12599 if length > best_length && (best_inside || !inside) {
12600 continue;
12601 }
12602
12603 best_length = length;
12604 best_inside = inside;
12605 best_in_bracket_range = in_bracket_range;
12606 best_destination = Some(
12607 if close.contains(&selection.start) && close.contains(&selection.end) {
12608 if inside { open.end } else { open.start }
12609 } else if inside {
12610 *close.start()
12611 } else {
12612 *close.end()
12613 },
12614 );
12615 }
12616
12617 if let Some(destination) = best_destination {
12618 selection.collapse_to(destination, SelectionGoal::None);
12619 }
12620 })
12621 });
12622 }
12623
12624 pub fn undo_selection(
12625 &mut self,
12626 _: &UndoSelection,
12627 window: &mut Window,
12628 cx: &mut Context<Self>,
12629 ) {
12630 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12631 self.end_selection(window, cx);
12632 self.selection_history.mode = SelectionHistoryMode::Undoing;
12633 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12634 self.change_selections(None, window, cx, |s| {
12635 s.select_anchors(entry.selections.to_vec())
12636 });
12637 self.select_next_state = entry.select_next_state;
12638 self.select_prev_state = entry.select_prev_state;
12639 self.add_selections_state = entry.add_selections_state;
12640 self.request_autoscroll(Autoscroll::newest(), cx);
12641 }
12642 self.selection_history.mode = SelectionHistoryMode::Normal;
12643 }
12644
12645 pub fn redo_selection(
12646 &mut self,
12647 _: &RedoSelection,
12648 window: &mut Window,
12649 cx: &mut Context<Self>,
12650 ) {
12651 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12652 self.end_selection(window, cx);
12653 self.selection_history.mode = SelectionHistoryMode::Redoing;
12654 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12655 self.change_selections(None, window, cx, |s| {
12656 s.select_anchors(entry.selections.to_vec())
12657 });
12658 self.select_next_state = entry.select_next_state;
12659 self.select_prev_state = entry.select_prev_state;
12660 self.add_selections_state = entry.add_selections_state;
12661 self.request_autoscroll(Autoscroll::newest(), cx);
12662 }
12663 self.selection_history.mode = SelectionHistoryMode::Normal;
12664 }
12665
12666 pub fn expand_excerpts(
12667 &mut self,
12668 action: &ExpandExcerpts,
12669 _: &mut Window,
12670 cx: &mut Context<Self>,
12671 ) {
12672 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12673 }
12674
12675 pub fn expand_excerpts_down(
12676 &mut self,
12677 action: &ExpandExcerptsDown,
12678 _: &mut Window,
12679 cx: &mut Context<Self>,
12680 ) {
12681 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12682 }
12683
12684 pub fn expand_excerpts_up(
12685 &mut self,
12686 action: &ExpandExcerptsUp,
12687 _: &mut Window,
12688 cx: &mut Context<Self>,
12689 ) {
12690 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12691 }
12692
12693 pub fn expand_excerpts_for_direction(
12694 &mut self,
12695 lines: u32,
12696 direction: ExpandExcerptDirection,
12697
12698 cx: &mut Context<Self>,
12699 ) {
12700 let selections = self.selections.disjoint_anchors();
12701
12702 let lines = if lines == 0 {
12703 EditorSettings::get_global(cx).expand_excerpt_lines
12704 } else {
12705 lines
12706 };
12707
12708 self.buffer.update(cx, |buffer, cx| {
12709 let snapshot = buffer.snapshot(cx);
12710 let mut excerpt_ids = selections
12711 .iter()
12712 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12713 .collect::<Vec<_>>();
12714 excerpt_ids.sort();
12715 excerpt_ids.dedup();
12716 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12717 })
12718 }
12719
12720 pub fn expand_excerpt(
12721 &mut self,
12722 excerpt: ExcerptId,
12723 direction: ExpandExcerptDirection,
12724 window: &mut Window,
12725 cx: &mut Context<Self>,
12726 ) {
12727 let current_scroll_position = self.scroll_position(cx);
12728 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
12729 let mut should_scroll_up = false;
12730
12731 if direction == ExpandExcerptDirection::Down {
12732 let multi_buffer = self.buffer.read(cx);
12733 let snapshot = multi_buffer.snapshot(cx);
12734 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
12735 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12736 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
12737 let buffer_snapshot = buffer.read(cx).snapshot();
12738 let excerpt_end_row =
12739 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
12740 let last_row = buffer_snapshot.max_point().row;
12741 let lines_below = last_row.saturating_sub(excerpt_end_row);
12742 should_scroll_up = lines_below >= lines_to_expand;
12743 }
12744 }
12745 }
12746 }
12747
12748 self.buffer.update(cx, |buffer, cx| {
12749 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
12750 });
12751
12752 if should_scroll_up {
12753 let new_scroll_position =
12754 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
12755 self.set_scroll_position(new_scroll_position, window, cx);
12756 }
12757 }
12758
12759 pub fn go_to_singleton_buffer_point(
12760 &mut self,
12761 point: Point,
12762 window: &mut Window,
12763 cx: &mut Context<Self>,
12764 ) {
12765 self.go_to_singleton_buffer_range(point..point, window, cx);
12766 }
12767
12768 pub fn go_to_singleton_buffer_range(
12769 &mut self,
12770 range: Range<Point>,
12771 window: &mut Window,
12772 cx: &mut Context<Self>,
12773 ) {
12774 let multibuffer = self.buffer().read(cx);
12775 let Some(buffer) = multibuffer.as_singleton() else {
12776 return;
12777 };
12778 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12779 return;
12780 };
12781 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12782 return;
12783 };
12784 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12785 s.select_anchor_ranges([start..end])
12786 });
12787 }
12788
12789 fn go_to_diagnostic(
12790 &mut self,
12791 _: &GoToDiagnostic,
12792 window: &mut Window,
12793 cx: &mut Context<Self>,
12794 ) {
12795 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12796 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12797 }
12798
12799 fn go_to_prev_diagnostic(
12800 &mut self,
12801 _: &GoToPreviousDiagnostic,
12802 window: &mut Window,
12803 cx: &mut Context<Self>,
12804 ) {
12805 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12806 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12807 }
12808
12809 pub fn go_to_diagnostic_impl(
12810 &mut self,
12811 direction: Direction,
12812 window: &mut Window,
12813 cx: &mut Context<Self>,
12814 ) {
12815 let buffer = self.buffer.read(cx).snapshot(cx);
12816 let selection = self.selections.newest::<usize>(cx);
12817 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12818 if direction == Direction::Next {
12819 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12820 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12821 return;
12822 };
12823 self.activate_diagnostics(
12824 buffer_id,
12825 popover.local_diagnostic.diagnostic.group_id,
12826 window,
12827 cx,
12828 );
12829 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12830 let primary_range_start = active_diagnostics.primary_range.start;
12831 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12832 let mut new_selection = s.newest_anchor().clone();
12833 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12834 s.select_anchors(vec![new_selection.clone()]);
12835 });
12836 self.refresh_inline_completion(false, true, window, cx);
12837 }
12838 return;
12839 }
12840 }
12841
12842 let active_group_id = self
12843 .active_diagnostics
12844 .as_ref()
12845 .map(|active_group| active_group.group_id);
12846 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12847 active_diagnostics
12848 .primary_range
12849 .to_offset(&buffer)
12850 .to_inclusive()
12851 });
12852 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12853 if active_primary_range.contains(&selection.head()) {
12854 *active_primary_range.start()
12855 } else {
12856 selection.head()
12857 }
12858 } else {
12859 selection.head()
12860 };
12861
12862 let snapshot = self.snapshot(window, cx);
12863 let primary_diagnostics_before = buffer
12864 .diagnostics_in_range::<usize>(0..search_start)
12865 .filter(|entry| entry.diagnostic.is_primary)
12866 .filter(|entry| entry.range.start != entry.range.end)
12867 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12868 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12869 .collect::<Vec<_>>();
12870 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12871 primary_diagnostics_before
12872 .iter()
12873 .position(|entry| entry.diagnostic.group_id == active_group_id)
12874 });
12875
12876 let primary_diagnostics_after = buffer
12877 .diagnostics_in_range::<usize>(search_start..buffer.len())
12878 .filter(|entry| entry.diagnostic.is_primary)
12879 .filter(|entry| entry.range.start != entry.range.end)
12880 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12881 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12882 .collect::<Vec<_>>();
12883 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12884 primary_diagnostics_after
12885 .iter()
12886 .enumerate()
12887 .rev()
12888 .find_map(|(i, entry)| {
12889 if entry.diagnostic.group_id == active_group_id {
12890 Some(i)
12891 } else {
12892 None
12893 }
12894 })
12895 });
12896
12897 let next_primary_diagnostic = match direction {
12898 Direction::Prev => primary_diagnostics_before
12899 .iter()
12900 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12901 .rev()
12902 .next(),
12903 Direction::Next => primary_diagnostics_after
12904 .iter()
12905 .skip(
12906 last_same_group_diagnostic_after
12907 .map(|index| index + 1)
12908 .unwrap_or(0),
12909 )
12910 .next(),
12911 };
12912
12913 // Cycle around to the start of the buffer, potentially moving back to the start of
12914 // the currently active diagnostic.
12915 let cycle_around = || match direction {
12916 Direction::Prev => primary_diagnostics_after
12917 .iter()
12918 .rev()
12919 .chain(primary_diagnostics_before.iter().rev())
12920 .next(),
12921 Direction::Next => primary_diagnostics_before
12922 .iter()
12923 .chain(primary_diagnostics_after.iter())
12924 .next(),
12925 };
12926
12927 if let Some((primary_range, group_id)) = next_primary_diagnostic
12928 .or_else(cycle_around)
12929 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12930 {
12931 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12932 return;
12933 };
12934 self.activate_diagnostics(buffer_id, group_id, window, cx);
12935 if self.active_diagnostics.is_some() {
12936 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12937 s.select(vec![Selection {
12938 id: selection.id,
12939 start: primary_range.start,
12940 end: primary_range.start,
12941 reversed: false,
12942 goal: SelectionGoal::None,
12943 }]);
12944 });
12945 self.refresh_inline_completion(false, true, window, cx);
12946 }
12947 }
12948 }
12949
12950 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12951 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12952 let snapshot = self.snapshot(window, cx);
12953 let selection = self.selections.newest::<Point>(cx);
12954 self.go_to_hunk_before_or_after_position(
12955 &snapshot,
12956 selection.head(),
12957 Direction::Next,
12958 window,
12959 cx,
12960 );
12961 }
12962
12963 pub fn go_to_hunk_before_or_after_position(
12964 &mut self,
12965 snapshot: &EditorSnapshot,
12966 position: Point,
12967 direction: Direction,
12968 window: &mut Window,
12969 cx: &mut Context<Editor>,
12970 ) {
12971 let row = if direction == Direction::Next {
12972 self.hunk_after_position(snapshot, position)
12973 .map(|hunk| hunk.row_range.start)
12974 } else {
12975 self.hunk_before_position(snapshot, position)
12976 };
12977
12978 if let Some(row) = row {
12979 let destination = Point::new(row.0, 0);
12980 let autoscroll = Autoscroll::center();
12981
12982 self.unfold_ranges(&[destination..destination], false, false, cx);
12983 self.change_selections(Some(autoscroll), window, cx, |s| {
12984 s.select_ranges([destination..destination]);
12985 });
12986 }
12987 }
12988
12989 fn hunk_after_position(
12990 &mut self,
12991 snapshot: &EditorSnapshot,
12992 position: Point,
12993 ) -> Option<MultiBufferDiffHunk> {
12994 snapshot
12995 .buffer_snapshot
12996 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12997 .find(|hunk| hunk.row_range.start.0 > position.row)
12998 .or_else(|| {
12999 snapshot
13000 .buffer_snapshot
13001 .diff_hunks_in_range(Point::zero()..position)
13002 .find(|hunk| hunk.row_range.end.0 < position.row)
13003 })
13004 }
13005
13006 fn go_to_prev_hunk(
13007 &mut self,
13008 _: &GoToPreviousHunk,
13009 window: &mut Window,
13010 cx: &mut Context<Self>,
13011 ) {
13012 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13013 let snapshot = self.snapshot(window, cx);
13014 let selection = self.selections.newest::<Point>(cx);
13015 self.go_to_hunk_before_or_after_position(
13016 &snapshot,
13017 selection.head(),
13018 Direction::Prev,
13019 window,
13020 cx,
13021 );
13022 }
13023
13024 fn hunk_before_position(
13025 &mut self,
13026 snapshot: &EditorSnapshot,
13027 position: Point,
13028 ) -> Option<MultiBufferRow> {
13029 snapshot
13030 .buffer_snapshot
13031 .diff_hunk_before(position)
13032 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13033 }
13034
13035 fn go_to_line<T: 'static>(
13036 &mut self,
13037 position: Anchor,
13038 highlight_color: Option<Hsla>,
13039 window: &mut Window,
13040 cx: &mut Context<Self>,
13041 ) {
13042 let snapshot = self.snapshot(window, cx).display_snapshot;
13043 let position = position.to_point(&snapshot.buffer_snapshot);
13044 let start = snapshot
13045 .buffer_snapshot
13046 .clip_point(Point::new(position.row, 0), Bias::Left);
13047 let end = start + Point::new(1, 0);
13048 let start = snapshot.buffer_snapshot.anchor_before(start);
13049 let end = snapshot.buffer_snapshot.anchor_before(end);
13050
13051 self.highlight_rows::<T>(
13052 start..end,
13053 highlight_color
13054 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13055 false,
13056 cx,
13057 );
13058 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13059 }
13060
13061 pub fn go_to_definition(
13062 &mut self,
13063 _: &GoToDefinition,
13064 window: &mut Window,
13065 cx: &mut Context<Self>,
13066 ) -> Task<Result<Navigated>> {
13067 let definition =
13068 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13069 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13070 cx.spawn_in(window, async move |editor, cx| {
13071 if definition.await? == Navigated::Yes {
13072 return Ok(Navigated::Yes);
13073 }
13074 match fallback_strategy {
13075 GoToDefinitionFallback::None => Ok(Navigated::No),
13076 GoToDefinitionFallback::FindAllReferences => {
13077 match editor.update_in(cx, |editor, window, cx| {
13078 editor.find_all_references(&FindAllReferences, window, cx)
13079 })? {
13080 Some(references) => references.await,
13081 None => Ok(Navigated::No),
13082 }
13083 }
13084 }
13085 })
13086 }
13087
13088 pub fn go_to_declaration(
13089 &mut self,
13090 _: &GoToDeclaration,
13091 window: &mut Window,
13092 cx: &mut Context<Self>,
13093 ) -> Task<Result<Navigated>> {
13094 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13095 }
13096
13097 pub fn go_to_declaration_split(
13098 &mut self,
13099 _: &GoToDeclaration,
13100 window: &mut Window,
13101 cx: &mut Context<Self>,
13102 ) -> Task<Result<Navigated>> {
13103 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13104 }
13105
13106 pub fn go_to_implementation(
13107 &mut self,
13108 _: &GoToImplementation,
13109 window: &mut Window,
13110 cx: &mut Context<Self>,
13111 ) -> Task<Result<Navigated>> {
13112 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13113 }
13114
13115 pub fn go_to_implementation_split(
13116 &mut self,
13117 _: &GoToImplementationSplit,
13118 window: &mut Window,
13119 cx: &mut Context<Self>,
13120 ) -> Task<Result<Navigated>> {
13121 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13122 }
13123
13124 pub fn go_to_type_definition(
13125 &mut self,
13126 _: &GoToTypeDefinition,
13127 window: &mut Window,
13128 cx: &mut Context<Self>,
13129 ) -> Task<Result<Navigated>> {
13130 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13131 }
13132
13133 pub fn go_to_definition_split(
13134 &mut self,
13135 _: &GoToDefinitionSplit,
13136 window: &mut Window,
13137 cx: &mut Context<Self>,
13138 ) -> Task<Result<Navigated>> {
13139 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13140 }
13141
13142 pub fn go_to_type_definition_split(
13143 &mut self,
13144 _: &GoToTypeDefinitionSplit,
13145 window: &mut Window,
13146 cx: &mut Context<Self>,
13147 ) -> Task<Result<Navigated>> {
13148 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13149 }
13150
13151 fn go_to_definition_of_kind(
13152 &mut self,
13153 kind: GotoDefinitionKind,
13154 split: bool,
13155 window: &mut Window,
13156 cx: &mut Context<Self>,
13157 ) -> Task<Result<Navigated>> {
13158 let Some(provider) = self.semantics_provider.clone() else {
13159 return Task::ready(Ok(Navigated::No));
13160 };
13161 let head = self.selections.newest::<usize>(cx).head();
13162 let buffer = self.buffer.read(cx);
13163 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13164 text_anchor
13165 } else {
13166 return Task::ready(Ok(Navigated::No));
13167 };
13168
13169 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13170 return Task::ready(Ok(Navigated::No));
13171 };
13172
13173 cx.spawn_in(window, async move |editor, cx| {
13174 let definitions = definitions.await?;
13175 let navigated = editor
13176 .update_in(cx, |editor, window, cx| {
13177 editor.navigate_to_hover_links(
13178 Some(kind),
13179 definitions
13180 .into_iter()
13181 .filter(|location| {
13182 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13183 })
13184 .map(HoverLink::Text)
13185 .collect::<Vec<_>>(),
13186 split,
13187 window,
13188 cx,
13189 )
13190 })?
13191 .await?;
13192 anyhow::Ok(navigated)
13193 })
13194 }
13195
13196 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13197 let selection = self.selections.newest_anchor();
13198 let head = selection.head();
13199 let tail = selection.tail();
13200
13201 let Some((buffer, start_position)) =
13202 self.buffer.read(cx).text_anchor_for_position(head, cx)
13203 else {
13204 return;
13205 };
13206
13207 let end_position = if head != tail {
13208 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13209 return;
13210 };
13211 Some(pos)
13212 } else {
13213 None
13214 };
13215
13216 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13217 let url = if let Some(end_pos) = end_position {
13218 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13219 } else {
13220 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13221 };
13222
13223 if let Some(url) = url {
13224 editor.update(cx, |_, cx| {
13225 cx.open_url(&url);
13226 })
13227 } else {
13228 Ok(())
13229 }
13230 });
13231
13232 url_finder.detach();
13233 }
13234
13235 pub fn open_selected_filename(
13236 &mut self,
13237 _: &OpenSelectedFilename,
13238 window: &mut Window,
13239 cx: &mut Context<Self>,
13240 ) {
13241 let Some(workspace) = self.workspace() else {
13242 return;
13243 };
13244
13245 let position = self.selections.newest_anchor().head();
13246
13247 let Some((buffer, buffer_position)) =
13248 self.buffer.read(cx).text_anchor_for_position(position, cx)
13249 else {
13250 return;
13251 };
13252
13253 let project = self.project.clone();
13254
13255 cx.spawn_in(window, async move |_, cx| {
13256 let result = find_file(&buffer, project, buffer_position, cx).await;
13257
13258 if let Some((_, path)) = result {
13259 workspace
13260 .update_in(cx, |workspace, window, cx| {
13261 workspace.open_resolved_path(path, window, cx)
13262 })?
13263 .await?;
13264 }
13265 anyhow::Ok(())
13266 })
13267 .detach();
13268 }
13269
13270 pub(crate) fn navigate_to_hover_links(
13271 &mut self,
13272 kind: Option<GotoDefinitionKind>,
13273 mut definitions: Vec<HoverLink>,
13274 split: bool,
13275 window: &mut Window,
13276 cx: &mut Context<Editor>,
13277 ) -> Task<Result<Navigated>> {
13278 // If there is one definition, just open it directly
13279 if definitions.len() == 1 {
13280 let definition = definitions.pop().unwrap();
13281
13282 enum TargetTaskResult {
13283 Location(Option<Location>),
13284 AlreadyNavigated,
13285 }
13286
13287 let target_task = match definition {
13288 HoverLink::Text(link) => {
13289 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13290 }
13291 HoverLink::InlayHint(lsp_location, server_id) => {
13292 let computation =
13293 self.compute_target_location(lsp_location, server_id, window, cx);
13294 cx.background_spawn(async move {
13295 let location = computation.await?;
13296 Ok(TargetTaskResult::Location(location))
13297 })
13298 }
13299 HoverLink::Url(url) => {
13300 cx.open_url(&url);
13301 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13302 }
13303 HoverLink::File(path) => {
13304 if let Some(workspace) = self.workspace() {
13305 cx.spawn_in(window, async move |_, cx| {
13306 workspace
13307 .update_in(cx, |workspace, window, cx| {
13308 workspace.open_resolved_path(path, window, cx)
13309 })?
13310 .await
13311 .map(|_| TargetTaskResult::AlreadyNavigated)
13312 })
13313 } else {
13314 Task::ready(Ok(TargetTaskResult::Location(None)))
13315 }
13316 }
13317 };
13318 cx.spawn_in(window, async move |editor, cx| {
13319 let target = match target_task.await.context("target resolution task")? {
13320 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13321 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13322 TargetTaskResult::Location(Some(target)) => target,
13323 };
13324
13325 editor.update_in(cx, |editor, window, cx| {
13326 let Some(workspace) = editor.workspace() else {
13327 return Navigated::No;
13328 };
13329 let pane = workspace.read(cx).active_pane().clone();
13330
13331 let range = target.range.to_point(target.buffer.read(cx));
13332 let range = editor.range_for_match(&range);
13333 let range = collapse_multiline_range(range);
13334
13335 if !split
13336 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13337 {
13338 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13339 } else {
13340 window.defer(cx, move |window, cx| {
13341 let target_editor: Entity<Self> =
13342 workspace.update(cx, |workspace, cx| {
13343 let pane = if split {
13344 workspace.adjacent_pane(window, cx)
13345 } else {
13346 workspace.active_pane().clone()
13347 };
13348
13349 workspace.open_project_item(
13350 pane,
13351 target.buffer.clone(),
13352 true,
13353 true,
13354 window,
13355 cx,
13356 )
13357 });
13358 target_editor.update(cx, |target_editor, cx| {
13359 // When selecting a definition in a different buffer, disable the nav history
13360 // to avoid creating a history entry at the previous cursor location.
13361 pane.update(cx, |pane, _| pane.disable_history());
13362 target_editor.go_to_singleton_buffer_range(range, window, cx);
13363 pane.update(cx, |pane, _| pane.enable_history());
13364 });
13365 });
13366 }
13367 Navigated::Yes
13368 })
13369 })
13370 } else if !definitions.is_empty() {
13371 cx.spawn_in(window, async move |editor, cx| {
13372 let (title, location_tasks, workspace) = editor
13373 .update_in(cx, |editor, window, cx| {
13374 let tab_kind = match kind {
13375 Some(GotoDefinitionKind::Implementation) => "Implementations",
13376 _ => "Definitions",
13377 };
13378 let title = definitions
13379 .iter()
13380 .find_map(|definition| match definition {
13381 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13382 let buffer = origin.buffer.read(cx);
13383 format!(
13384 "{} for {}",
13385 tab_kind,
13386 buffer
13387 .text_for_range(origin.range.clone())
13388 .collect::<String>()
13389 )
13390 }),
13391 HoverLink::InlayHint(_, _) => None,
13392 HoverLink::Url(_) => None,
13393 HoverLink::File(_) => None,
13394 })
13395 .unwrap_or(tab_kind.to_string());
13396 let location_tasks = definitions
13397 .into_iter()
13398 .map(|definition| match definition {
13399 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13400 HoverLink::InlayHint(lsp_location, server_id) => editor
13401 .compute_target_location(lsp_location, server_id, window, cx),
13402 HoverLink::Url(_) => Task::ready(Ok(None)),
13403 HoverLink::File(_) => Task::ready(Ok(None)),
13404 })
13405 .collect::<Vec<_>>();
13406 (title, location_tasks, editor.workspace().clone())
13407 })
13408 .context("location tasks preparation")?;
13409
13410 let locations = future::join_all(location_tasks)
13411 .await
13412 .into_iter()
13413 .filter_map(|location| location.transpose())
13414 .collect::<Result<_>>()
13415 .context("location tasks")?;
13416
13417 let Some(workspace) = workspace else {
13418 return Ok(Navigated::No);
13419 };
13420 let opened = workspace
13421 .update_in(cx, |workspace, window, cx| {
13422 Self::open_locations_in_multibuffer(
13423 workspace,
13424 locations,
13425 title,
13426 split,
13427 MultibufferSelectionMode::First,
13428 window,
13429 cx,
13430 )
13431 })
13432 .ok();
13433
13434 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13435 })
13436 } else {
13437 Task::ready(Ok(Navigated::No))
13438 }
13439 }
13440
13441 fn compute_target_location(
13442 &self,
13443 lsp_location: lsp::Location,
13444 server_id: LanguageServerId,
13445 window: &mut Window,
13446 cx: &mut Context<Self>,
13447 ) -> Task<anyhow::Result<Option<Location>>> {
13448 let Some(project) = self.project.clone() else {
13449 return Task::ready(Ok(None));
13450 };
13451
13452 cx.spawn_in(window, async move |editor, cx| {
13453 let location_task = editor.update(cx, |_, cx| {
13454 project.update(cx, |project, cx| {
13455 let language_server_name = project
13456 .language_server_statuses(cx)
13457 .find(|(id, _)| server_id == *id)
13458 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13459 language_server_name.map(|language_server_name| {
13460 project.open_local_buffer_via_lsp(
13461 lsp_location.uri.clone(),
13462 server_id,
13463 language_server_name,
13464 cx,
13465 )
13466 })
13467 })
13468 })?;
13469 let location = match location_task {
13470 Some(task) => Some({
13471 let target_buffer_handle = task.await.context("open local buffer")?;
13472 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13473 let target_start = target_buffer
13474 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13475 let target_end = target_buffer
13476 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13477 target_buffer.anchor_after(target_start)
13478 ..target_buffer.anchor_before(target_end)
13479 })?;
13480 Location {
13481 buffer: target_buffer_handle,
13482 range,
13483 }
13484 }),
13485 None => None,
13486 };
13487 Ok(location)
13488 })
13489 }
13490
13491 pub fn find_all_references(
13492 &mut self,
13493 _: &FindAllReferences,
13494 window: &mut Window,
13495 cx: &mut Context<Self>,
13496 ) -> Option<Task<Result<Navigated>>> {
13497 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13498
13499 let selection = self.selections.newest::<usize>(cx);
13500 let multi_buffer = self.buffer.read(cx);
13501 let head = selection.head();
13502
13503 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13504 let head_anchor = multi_buffer_snapshot.anchor_at(
13505 head,
13506 if head < selection.tail() {
13507 Bias::Right
13508 } else {
13509 Bias::Left
13510 },
13511 );
13512
13513 match self
13514 .find_all_references_task_sources
13515 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13516 {
13517 Ok(_) => {
13518 log::info!(
13519 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13520 );
13521 return None;
13522 }
13523 Err(i) => {
13524 self.find_all_references_task_sources.insert(i, head_anchor);
13525 }
13526 }
13527
13528 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13529 let workspace = self.workspace()?;
13530 let project = workspace.read(cx).project().clone();
13531 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13532 Some(cx.spawn_in(window, async move |editor, cx| {
13533 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13534 if let Ok(i) = editor
13535 .find_all_references_task_sources
13536 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13537 {
13538 editor.find_all_references_task_sources.remove(i);
13539 }
13540 });
13541
13542 let locations = references.await?;
13543 if locations.is_empty() {
13544 return anyhow::Ok(Navigated::No);
13545 }
13546
13547 workspace.update_in(cx, |workspace, window, cx| {
13548 let title = locations
13549 .first()
13550 .as_ref()
13551 .map(|location| {
13552 let buffer = location.buffer.read(cx);
13553 format!(
13554 "References to `{}`",
13555 buffer
13556 .text_for_range(location.range.clone())
13557 .collect::<String>()
13558 )
13559 })
13560 .unwrap();
13561 Self::open_locations_in_multibuffer(
13562 workspace,
13563 locations,
13564 title,
13565 false,
13566 MultibufferSelectionMode::First,
13567 window,
13568 cx,
13569 );
13570 Navigated::Yes
13571 })
13572 }))
13573 }
13574
13575 /// Opens a multibuffer with the given project locations in it
13576 pub fn open_locations_in_multibuffer(
13577 workspace: &mut Workspace,
13578 mut locations: Vec<Location>,
13579 title: String,
13580 split: bool,
13581 multibuffer_selection_mode: MultibufferSelectionMode,
13582 window: &mut Window,
13583 cx: &mut Context<Workspace>,
13584 ) {
13585 // If there are multiple definitions, open them in a multibuffer
13586 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13587 let mut locations = locations.into_iter().peekable();
13588 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13589 let capability = workspace.project().read(cx).capability();
13590
13591 let excerpt_buffer = cx.new(|cx| {
13592 let mut multibuffer = MultiBuffer::new(capability);
13593 while let Some(location) = locations.next() {
13594 let buffer = location.buffer.read(cx);
13595 let mut ranges_for_buffer = Vec::new();
13596 let range = location.range.to_point(buffer);
13597 ranges_for_buffer.push(range.clone());
13598
13599 while let Some(next_location) = locations.peek() {
13600 if next_location.buffer == location.buffer {
13601 ranges_for_buffer.push(next_location.range.to_point(buffer));
13602 locations.next();
13603 } else {
13604 break;
13605 }
13606 }
13607
13608 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13609 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13610 PathKey::for_buffer(&location.buffer, cx),
13611 location.buffer.clone(),
13612 ranges_for_buffer,
13613 DEFAULT_MULTIBUFFER_CONTEXT,
13614 cx,
13615 );
13616 ranges.extend(new_ranges)
13617 }
13618
13619 multibuffer.with_title(title)
13620 });
13621
13622 let editor = cx.new(|cx| {
13623 Editor::for_multibuffer(
13624 excerpt_buffer,
13625 Some(workspace.project().clone()),
13626 window,
13627 cx,
13628 )
13629 });
13630 editor.update(cx, |editor, cx| {
13631 match multibuffer_selection_mode {
13632 MultibufferSelectionMode::First => {
13633 if let Some(first_range) = ranges.first() {
13634 editor.change_selections(None, window, cx, |selections| {
13635 selections.clear_disjoint();
13636 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13637 });
13638 }
13639 editor.highlight_background::<Self>(
13640 &ranges,
13641 |theme| theme.editor_highlighted_line_background,
13642 cx,
13643 );
13644 }
13645 MultibufferSelectionMode::All => {
13646 editor.change_selections(None, window, cx, |selections| {
13647 selections.clear_disjoint();
13648 selections.select_anchor_ranges(ranges);
13649 });
13650 }
13651 }
13652 editor.register_buffers_with_language_servers(cx);
13653 });
13654
13655 let item = Box::new(editor);
13656 let item_id = item.item_id();
13657
13658 if split {
13659 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13660 } else {
13661 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13662 let (preview_item_id, preview_item_idx) =
13663 workspace.active_pane().update(cx, |pane, _| {
13664 (pane.preview_item_id(), pane.preview_item_idx())
13665 });
13666
13667 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13668
13669 if let Some(preview_item_id) = preview_item_id {
13670 workspace.active_pane().update(cx, |pane, cx| {
13671 pane.remove_item(preview_item_id, false, false, window, cx);
13672 });
13673 }
13674 } else {
13675 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13676 }
13677 }
13678 workspace.active_pane().update(cx, |pane, cx| {
13679 pane.set_preview_item_id(Some(item_id), cx);
13680 });
13681 }
13682
13683 pub fn rename(
13684 &mut self,
13685 _: &Rename,
13686 window: &mut Window,
13687 cx: &mut Context<Self>,
13688 ) -> Option<Task<Result<()>>> {
13689 use language::ToOffset as _;
13690
13691 let provider = self.semantics_provider.clone()?;
13692 let selection = self.selections.newest_anchor().clone();
13693 let (cursor_buffer, cursor_buffer_position) = self
13694 .buffer
13695 .read(cx)
13696 .text_anchor_for_position(selection.head(), cx)?;
13697 let (tail_buffer, cursor_buffer_position_end) = self
13698 .buffer
13699 .read(cx)
13700 .text_anchor_for_position(selection.tail(), cx)?;
13701 if tail_buffer != cursor_buffer {
13702 return None;
13703 }
13704
13705 let snapshot = cursor_buffer.read(cx).snapshot();
13706 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13707 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13708 let prepare_rename = provider
13709 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13710 .unwrap_or_else(|| Task::ready(Ok(None)));
13711 drop(snapshot);
13712
13713 Some(cx.spawn_in(window, async move |this, cx| {
13714 let rename_range = if let Some(range) = prepare_rename.await? {
13715 Some(range)
13716 } else {
13717 this.update(cx, |this, cx| {
13718 let buffer = this.buffer.read(cx).snapshot(cx);
13719 let mut buffer_highlights = this
13720 .document_highlights_for_position(selection.head(), &buffer)
13721 .filter(|highlight| {
13722 highlight.start.excerpt_id == selection.head().excerpt_id
13723 && highlight.end.excerpt_id == selection.head().excerpt_id
13724 });
13725 buffer_highlights
13726 .next()
13727 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13728 })?
13729 };
13730 if let Some(rename_range) = rename_range {
13731 this.update_in(cx, |this, window, cx| {
13732 let snapshot = cursor_buffer.read(cx).snapshot();
13733 let rename_buffer_range = rename_range.to_offset(&snapshot);
13734 let cursor_offset_in_rename_range =
13735 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13736 let cursor_offset_in_rename_range_end =
13737 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13738
13739 this.take_rename(false, window, cx);
13740 let buffer = this.buffer.read(cx).read(cx);
13741 let cursor_offset = selection.head().to_offset(&buffer);
13742 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13743 let rename_end = rename_start + rename_buffer_range.len();
13744 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13745 let mut old_highlight_id = None;
13746 let old_name: Arc<str> = buffer
13747 .chunks(rename_start..rename_end, true)
13748 .map(|chunk| {
13749 if old_highlight_id.is_none() {
13750 old_highlight_id = chunk.syntax_highlight_id;
13751 }
13752 chunk.text
13753 })
13754 .collect::<String>()
13755 .into();
13756
13757 drop(buffer);
13758
13759 // Position the selection in the rename editor so that it matches the current selection.
13760 this.show_local_selections = false;
13761 let rename_editor = cx.new(|cx| {
13762 let mut editor = Editor::single_line(window, cx);
13763 editor.buffer.update(cx, |buffer, cx| {
13764 buffer.edit([(0..0, old_name.clone())], None, cx)
13765 });
13766 let rename_selection_range = match cursor_offset_in_rename_range
13767 .cmp(&cursor_offset_in_rename_range_end)
13768 {
13769 Ordering::Equal => {
13770 editor.select_all(&SelectAll, window, cx);
13771 return editor;
13772 }
13773 Ordering::Less => {
13774 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13775 }
13776 Ordering::Greater => {
13777 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13778 }
13779 };
13780 if rename_selection_range.end > old_name.len() {
13781 editor.select_all(&SelectAll, window, cx);
13782 } else {
13783 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13784 s.select_ranges([rename_selection_range]);
13785 });
13786 }
13787 editor
13788 });
13789 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13790 if e == &EditorEvent::Focused {
13791 cx.emit(EditorEvent::FocusedIn)
13792 }
13793 })
13794 .detach();
13795
13796 let write_highlights =
13797 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13798 let read_highlights =
13799 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13800 let ranges = write_highlights
13801 .iter()
13802 .flat_map(|(_, ranges)| ranges.iter())
13803 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13804 .cloned()
13805 .collect();
13806
13807 this.highlight_text::<Rename>(
13808 ranges,
13809 HighlightStyle {
13810 fade_out: Some(0.6),
13811 ..Default::default()
13812 },
13813 cx,
13814 );
13815 let rename_focus_handle = rename_editor.focus_handle(cx);
13816 window.focus(&rename_focus_handle);
13817 let block_id = this.insert_blocks(
13818 [BlockProperties {
13819 style: BlockStyle::Flex,
13820 placement: BlockPlacement::Below(range.start),
13821 height: Some(1),
13822 render: Arc::new({
13823 let rename_editor = rename_editor.clone();
13824 move |cx: &mut BlockContext| {
13825 let mut text_style = cx.editor_style.text.clone();
13826 if let Some(highlight_style) = old_highlight_id
13827 .and_then(|h| h.style(&cx.editor_style.syntax))
13828 {
13829 text_style = text_style.highlight(highlight_style);
13830 }
13831 div()
13832 .block_mouse_down()
13833 .pl(cx.anchor_x)
13834 .child(EditorElement::new(
13835 &rename_editor,
13836 EditorStyle {
13837 background: cx.theme().system().transparent,
13838 local_player: cx.editor_style.local_player,
13839 text: text_style,
13840 scrollbar_width: cx.editor_style.scrollbar_width,
13841 syntax: cx.editor_style.syntax.clone(),
13842 status: cx.editor_style.status.clone(),
13843 inlay_hints_style: HighlightStyle {
13844 font_weight: Some(FontWeight::BOLD),
13845 ..make_inlay_hints_style(cx.app)
13846 },
13847 inline_completion_styles: make_suggestion_styles(
13848 cx.app,
13849 ),
13850 ..EditorStyle::default()
13851 },
13852 ))
13853 .into_any_element()
13854 }
13855 }),
13856 priority: 0,
13857 }],
13858 Some(Autoscroll::fit()),
13859 cx,
13860 )[0];
13861 this.pending_rename = Some(RenameState {
13862 range,
13863 old_name,
13864 editor: rename_editor,
13865 block_id,
13866 });
13867 })?;
13868 }
13869
13870 Ok(())
13871 }))
13872 }
13873
13874 pub fn confirm_rename(
13875 &mut self,
13876 _: &ConfirmRename,
13877 window: &mut Window,
13878 cx: &mut Context<Self>,
13879 ) -> Option<Task<Result<()>>> {
13880 let rename = self.take_rename(false, window, cx)?;
13881 let workspace = self.workspace()?.downgrade();
13882 let (buffer, start) = self
13883 .buffer
13884 .read(cx)
13885 .text_anchor_for_position(rename.range.start, cx)?;
13886 let (end_buffer, _) = self
13887 .buffer
13888 .read(cx)
13889 .text_anchor_for_position(rename.range.end, cx)?;
13890 if buffer != end_buffer {
13891 return None;
13892 }
13893
13894 let old_name = rename.old_name;
13895 let new_name = rename.editor.read(cx).text(cx);
13896
13897 let rename = self.semantics_provider.as_ref()?.perform_rename(
13898 &buffer,
13899 start,
13900 new_name.clone(),
13901 cx,
13902 )?;
13903
13904 Some(cx.spawn_in(window, async move |editor, cx| {
13905 let project_transaction = rename.await?;
13906 Self::open_project_transaction(
13907 &editor,
13908 workspace,
13909 project_transaction,
13910 format!("Rename: {} → {}", old_name, new_name),
13911 cx,
13912 )
13913 .await?;
13914
13915 editor.update(cx, |editor, cx| {
13916 editor.refresh_document_highlights(cx);
13917 })?;
13918 Ok(())
13919 }))
13920 }
13921
13922 fn take_rename(
13923 &mut self,
13924 moving_cursor: bool,
13925 window: &mut Window,
13926 cx: &mut Context<Self>,
13927 ) -> Option<RenameState> {
13928 let rename = self.pending_rename.take()?;
13929 if rename.editor.focus_handle(cx).is_focused(window) {
13930 window.focus(&self.focus_handle);
13931 }
13932
13933 self.remove_blocks(
13934 [rename.block_id].into_iter().collect(),
13935 Some(Autoscroll::fit()),
13936 cx,
13937 );
13938 self.clear_highlights::<Rename>(cx);
13939 self.show_local_selections = true;
13940
13941 if moving_cursor {
13942 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13943 editor.selections.newest::<usize>(cx).head()
13944 });
13945
13946 // Update the selection to match the position of the selection inside
13947 // the rename editor.
13948 let snapshot = self.buffer.read(cx).read(cx);
13949 let rename_range = rename.range.to_offset(&snapshot);
13950 let cursor_in_editor = snapshot
13951 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13952 .min(rename_range.end);
13953 drop(snapshot);
13954
13955 self.change_selections(None, window, cx, |s| {
13956 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13957 });
13958 } else {
13959 self.refresh_document_highlights(cx);
13960 }
13961
13962 Some(rename)
13963 }
13964
13965 pub fn pending_rename(&self) -> Option<&RenameState> {
13966 self.pending_rename.as_ref()
13967 }
13968
13969 fn format(
13970 &mut self,
13971 _: &Format,
13972 window: &mut Window,
13973 cx: &mut Context<Self>,
13974 ) -> Option<Task<Result<()>>> {
13975 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13976
13977 let project = match &self.project {
13978 Some(project) => project.clone(),
13979 None => return None,
13980 };
13981
13982 Some(self.perform_format(
13983 project,
13984 FormatTrigger::Manual,
13985 FormatTarget::Buffers,
13986 window,
13987 cx,
13988 ))
13989 }
13990
13991 fn format_selections(
13992 &mut self,
13993 _: &FormatSelections,
13994 window: &mut Window,
13995 cx: &mut Context<Self>,
13996 ) -> Option<Task<Result<()>>> {
13997 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13998
13999 let project = match &self.project {
14000 Some(project) => project.clone(),
14001 None => return None,
14002 };
14003
14004 let ranges = self
14005 .selections
14006 .all_adjusted(cx)
14007 .into_iter()
14008 .map(|selection| selection.range())
14009 .collect_vec();
14010
14011 Some(self.perform_format(
14012 project,
14013 FormatTrigger::Manual,
14014 FormatTarget::Ranges(ranges),
14015 window,
14016 cx,
14017 ))
14018 }
14019
14020 fn perform_format(
14021 &mut self,
14022 project: Entity<Project>,
14023 trigger: FormatTrigger,
14024 target: FormatTarget,
14025 window: &mut Window,
14026 cx: &mut Context<Self>,
14027 ) -> Task<Result<()>> {
14028 let buffer = self.buffer.clone();
14029 let (buffers, target) = match target {
14030 FormatTarget::Buffers => {
14031 let mut buffers = buffer.read(cx).all_buffers();
14032 if trigger == FormatTrigger::Save {
14033 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14034 }
14035 (buffers, LspFormatTarget::Buffers)
14036 }
14037 FormatTarget::Ranges(selection_ranges) => {
14038 let multi_buffer = buffer.read(cx);
14039 let snapshot = multi_buffer.read(cx);
14040 let mut buffers = HashSet::default();
14041 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14042 BTreeMap::new();
14043 for selection_range in selection_ranges {
14044 for (buffer, buffer_range, _) in
14045 snapshot.range_to_buffer_ranges(selection_range)
14046 {
14047 let buffer_id = buffer.remote_id();
14048 let start = buffer.anchor_before(buffer_range.start);
14049 let end = buffer.anchor_after(buffer_range.end);
14050 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14051 buffer_id_to_ranges
14052 .entry(buffer_id)
14053 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14054 .or_insert_with(|| vec![start..end]);
14055 }
14056 }
14057 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14058 }
14059 };
14060
14061 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14062 let format = project.update(cx, |project, cx| {
14063 project.format(buffers, target, true, trigger, cx)
14064 });
14065
14066 cx.spawn_in(window, async move |_, cx| {
14067 let transaction = futures::select_biased! {
14068 transaction = format.log_err().fuse() => transaction,
14069 () = timeout => {
14070 log::warn!("timed out waiting for formatting");
14071 None
14072 }
14073 };
14074
14075 buffer
14076 .update(cx, |buffer, cx| {
14077 if let Some(transaction) = transaction {
14078 if !buffer.is_singleton() {
14079 buffer.push_transaction(&transaction.0, cx);
14080 }
14081 }
14082 cx.notify();
14083 })
14084 .ok();
14085
14086 Ok(())
14087 })
14088 }
14089
14090 fn organize_imports(
14091 &mut self,
14092 _: &OrganizeImports,
14093 window: &mut Window,
14094 cx: &mut Context<Self>,
14095 ) -> Option<Task<Result<()>>> {
14096 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14097 let project = match &self.project {
14098 Some(project) => project.clone(),
14099 None => return None,
14100 };
14101 Some(self.perform_code_action_kind(
14102 project,
14103 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14104 window,
14105 cx,
14106 ))
14107 }
14108
14109 fn perform_code_action_kind(
14110 &mut self,
14111 project: Entity<Project>,
14112 kind: CodeActionKind,
14113 window: &mut Window,
14114 cx: &mut Context<Self>,
14115 ) -> Task<Result<()>> {
14116 let buffer = self.buffer.clone();
14117 let buffers = buffer.read(cx).all_buffers();
14118 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14119 let apply_action = project.update(cx, |project, cx| {
14120 project.apply_code_action_kind(buffers, kind, true, cx)
14121 });
14122 cx.spawn_in(window, async move |_, cx| {
14123 let transaction = futures::select_biased! {
14124 () = timeout => {
14125 log::warn!("timed out waiting for executing code action");
14126 None
14127 }
14128 transaction = apply_action.log_err().fuse() => transaction,
14129 };
14130 buffer
14131 .update(cx, |buffer, cx| {
14132 // check if we need this
14133 if let Some(transaction) = transaction {
14134 if !buffer.is_singleton() {
14135 buffer.push_transaction(&transaction.0, cx);
14136 }
14137 }
14138 cx.notify();
14139 })
14140 .ok();
14141 Ok(())
14142 })
14143 }
14144
14145 fn restart_language_server(
14146 &mut self,
14147 _: &RestartLanguageServer,
14148 _: &mut Window,
14149 cx: &mut Context<Self>,
14150 ) {
14151 if let Some(project) = self.project.clone() {
14152 self.buffer.update(cx, |multi_buffer, cx| {
14153 project.update(cx, |project, cx| {
14154 project.restart_language_servers_for_buffers(
14155 multi_buffer.all_buffers().into_iter().collect(),
14156 cx,
14157 );
14158 });
14159 })
14160 }
14161 }
14162
14163 fn stop_language_server(
14164 &mut self,
14165 _: &StopLanguageServer,
14166 _: &mut Window,
14167 cx: &mut Context<Self>,
14168 ) {
14169 if let Some(project) = self.project.clone() {
14170 self.buffer.update(cx, |multi_buffer, cx| {
14171 project.update(cx, |project, cx| {
14172 project.stop_language_servers_for_buffers(
14173 multi_buffer.all_buffers().into_iter().collect(),
14174 cx,
14175 );
14176 cx.emit(project::Event::RefreshInlayHints);
14177 });
14178 });
14179 }
14180 }
14181
14182 fn cancel_language_server_work(
14183 workspace: &mut Workspace,
14184 _: &actions::CancelLanguageServerWork,
14185 _: &mut Window,
14186 cx: &mut Context<Workspace>,
14187 ) {
14188 let project = workspace.project();
14189 let buffers = workspace
14190 .active_item(cx)
14191 .and_then(|item| item.act_as::<Editor>(cx))
14192 .map_or(HashSet::default(), |editor| {
14193 editor.read(cx).buffer.read(cx).all_buffers()
14194 });
14195 project.update(cx, |project, cx| {
14196 project.cancel_language_server_work_for_buffers(buffers, cx);
14197 });
14198 }
14199
14200 fn show_character_palette(
14201 &mut self,
14202 _: &ShowCharacterPalette,
14203 window: &mut Window,
14204 _: &mut Context<Self>,
14205 ) {
14206 window.show_character_palette();
14207 }
14208
14209 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14210 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14211 let buffer = self.buffer.read(cx).snapshot(cx);
14212 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14213 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14214 let is_valid = buffer
14215 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14216 .any(|entry| {
14217 entry.diagnostic.is_primary
14218 && !entry.range.is_empty()
14219 && entry.range.start == primary_range_start
14220 && entry.diagnostic.message == active_diagnostics.primary_message
14221 });
14222
14223 if is_valid != active_diagnostics.is_valid {
14224 active_diagnostics.is_valid = is_valid;
14225 if is_valid {
14226 let mut new_styles = HashMap::default();
14227 for (block_id, diagnostic) in &active_diagnostics.blocks {
14228 new_styles.insert(
14229 *block_id,
14230 diagnostic_block_renderer(diagnostic.clone(), None, true),
14231 );
14232 }
14233 self.display_map.update(cx, |display_map, _cx| {
14234 display_map.replace_blocks(new_styles);
14235 });
14236 } else {
14237 self.dismiss_diagnostics(cx);
14238 }
14239 }
14240 }
14241 }
14242
14243 fn activate_diagnostics(
14244 &mut self,
14245 buffer_id: BufferId,
14246 group_id: usize,
14247 window: &mut Window,
14248 cx: &mut Context<Self>,
14249 ) {
14250 self.dismiss_diagnostics(cx);
14251 let snapshot = self.snapshot(window, cx);
14252 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14253 let buffer = self.buffer.read(cx).snapshot(cx);
14254
14255 let mut primary_range = None;
14256 let mut primary_message = None;
14257 let diagnostic_group = buffer
14258 .diagnostic_group(buffer_id, group_id)
14259 .filter_map(|entry| {
14260 let start = entry.range.start;
14261 let end = entry.range.end;
14262 if snapshot.is_line_folded(MultiBufferRow(start.row))
14263 && (start.row == end.row
14264 || snapshot.is_line_folded(MultiBufferRow(end.row)))
14265 {
14266 return None;
14267 }
14268 if entry.diagnostic.is_primary {
14269 primary_range = Some(entry.range.clone());
14270 primary_message = Some(entry.diagnostic.message.clone());
14271 }
14272 Some(entry)
14273 })
14274 .collect::<Vec<_>>();
14275 let primary_range = primary_range?;
14276 let primary_message = primary_message?;
14277
14278 let blocks = display_map
14279 .insert_blocks(
14280 diagnostic_group.iter().map(|entry| {
14281 let diagnostic = entry.diagnostic.clone();
14282 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14283 BlockProperties {
14284 style: BlockStyle::Fixed,
14285 placement: BlockPlacement::Below(
14286 buffer.anchor_after(entry.range.start),
14287 ),
14288 height: Some(message_height),
14289 render: diagnostic_block_renderer(diagnostic, None, true),
14290 priority: 0,
14291 }
14292 }),
14293 cx,
14294 )
14295 .into_iter()
14296 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14297 .collect();
14298
14299 Some(ActiveDiagnosticGroup {
14300 primary_range: buffer.anchor_before(primary_range.start)
14301 ..buffer.anchor_after(primary_range.end),
14302 primary_message,
14303 group_id,
14304 blocks,
14305 is_valid: true,
14306 })
14307 });
14308 }
14309
14310 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14311 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14312 self.display_map.update(cx, |display_map, cx| {
14313 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14314 });
14315 cx.notify();
14316 }
14317 }
14318
14319 /// Disable inline diagnostics rendering for this editor.
14320 pub fn disable_inline_diagnostics(&mut self) {
14321 self.inline_diagnostics_enabled = false;
14322 self.inline_diagnostics_update = Task::ready(());
14323 self.inline_diagnostics.clear();
14324 }
14325
14326 pub fn inline_diagnostics_enabled(&self) -> bool {
14327 self.inline_diagnostics_enabled
14328 }
14329
14330 pub fn show_inline_diagnostics(&self) -> bool {
14331 self.show_inline_diagnostics
14332 }
14333
14334 pub fn toggle_inline_diagnostics(
14335 &mut self,
14336 _: &ToggleInlineDiagnostics,
14337 window: &mut Window,
14338 cx: &mut Context<Editor>,
14339 ) {
14340 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14341 self.refresh_inline_diagnostics(false, window, cx);
14342 }
14343
14344 fn refresh_inline_diagnostics(
14345 &mut self,
14346 debounce: bool,
14347 window: &mut Window,
14348 cx: &mut Context<Self>,
14349 ) {
14350 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14351 self.inline_diagnostics_update = Task::ready(());
14352 self.inline_diagnostics.clear();
14353 return;
14354 }
14355
14356 let debounce_ms = ProjectSettings::get_global(cx)
14357 .diagnostics
14358 .inline
14359 .update_debounce_ms;
14360 let debounce = if debounce && debounce_ms > 0 {
14361 Some(Duration::from_millis(debounce_ms))
14362 } else {
14363 None
14364 };
14365 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14366 if let Some(debounce) = debounce {
14367 cx.background_executor().timer(debounce).await;
14368 }
14369 let Some(snapshot) = editor
14370 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14371 .ok()
14372 else {
14373 return;
14374 };
14375
14376 let new_inline_diagnostics = cx
14377 .background_spawn(async move {
14378 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14379 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14380 let message = diagnostic_entry
14381 .diagnostic
14382 .message
14383 .split_once('\n')
14384 .map(|(line, _)| line)
14385 .map(SharedString::new)
14386 .unwrap_or_else(|| {
14387 SharedString::from(diagnostic_entry.diagnostic.message)
14388 });
14389 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14390 let (Ok(i) | Err(i)) = inline_diagnostics
14391 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14392 inline_diagnostics.insert(
14393 i,
14394 (
14395 start_anchor,
14396 InlineDiagnostic {
14397 message,
14398 group_id: diagnostic_entry.diagnostic.group_id,
14399 start: diagnostic_entry.range.start.to_point(&snapshot),
14400 is_primary: diagnostic_entry.diagnostic.is_primary,
14401 severity: diagnostic_entry.diagnostic.severity,
14402 },
14403 ),
14404 );
14405 }
14406 inline_diagnostics
14407 })
14408 .await;
14409
14410 editor
14411 .update(cx, |editor, cx| {
14412 editor.inline_diagnostics = new_inline_diagnostics;
14413 cx.notify();
14414 })
14415 .ok();
14416 });
14417 }
14418
14419 pub fn set_selections_from_remote(
14420 &mut self,
14421 selections: Vec<Selection<Anchor>>,
14422 pending_selection: Option<Selection<Anchor>>,
14423 window: &mut Window,
14424 cx: &mut Context<Self>,
14425 ) {
14426 let old_cursor_position = self.selections.newest_anchor().head();
14427 self.selections.change_with(cx, |s| {
14428 s.select_anchors(selections);
14429 if let Some(pending_selection) = pending_selection {
14430 s.set_pending(pending_selection, SelectMode::Character);
14431 } else {
14432 s.clear_pending();
14433 }
14434 });
14435 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14436 }
14437
14438 fn push_to_selection_history(&mut self) {
14439 self.selection_history.push(SelectionHistoryEntry {
14440 selections: self.selections.disjoint_anchors(),
14441 select_next_state: self.select_next_state.clone(),
14442 select_prev_state: self.select_prev_state.clone(),
14443 add_selections_state: self.add_selections_state.clone(),
14444 });
14445 }
14446
14447 pub fn transact(
14448 &mut self,
14449 window: &mut Window,
14450 cx: &mut Context<Self>,
14451 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14452 ) -> Option<TransactionId> {
14453 self.start_transaction_at(Instant::now(), window, cx);
14454 update(self, window, cx);
14455 self.end_transaction_at(Instant::now(), cx)
14456 }
14457
14458 pub fn start_transaction_at(
14459 &mut self,
14460 now: Instant,
14461 window: &mut Window,
14462 cx: &mut Context<Self>,
14463 ) {
14464 self.end_selection(window, cx);
14465 if let Some(tx_id) = self
14466 .buffer
14467 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14468 {
14469 self.selection_history
14470 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14471 cx.emit(EditorEvent::TransactionBegun {
14472 transaction_id: tx_id,
14473 })
14474 }
14475 }
14476
14477 pub fn end_transaction_at(
14478 &mut self,
14479 now: Instant,
14480 cx: &mut Context<Self>,
14481 ) -> Option<TransactionId> {
14482 if let Some(transaction_id) = self
14483 .buffer
14484 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14485 {
14486 if let Some((_, end_selections)) =
14487 self.selection_history.transaction_mut(transaction_id)
14488 {
14489 *end_selections = Some(self.selections.disjoint_anchors());
14490 } else {
14491 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14492 }
14493
14494 cx.emit(EditorEvent::Edited { transaction_id });
14495 Some(transaction_id)
14496 } else {
14497 None
14498 }
14499 }
14500
14501 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14502 if self.selection_mark_mode {
14503 self.change_selections(None, window, cx, |s| {
14504 s.move_with(|_, sel| {
14505 sel.collapse_to(sel.head(), SelectionGoal::None);
14506 });
14507 })
14508 }
14509 self.selection_mark_mode = true;
14510 cx.notify();
14511 }
14512
14513 pub fn swap_selection_ends(
14514 &mut self,
14515 _: &actions::SwapSelectionEnds,
14516 window: &mut Window,
14517 cx: &mut Context<Self>,
14518 ) {
14519 self.change_selections(None, window, cx, |s| {
14520 s.move_with(|_, sel| {
14521 if sel.start != sel.end {
14522 sel.reversed = !sel.reversed
14523 }
14524 });
14525 });
14526 self.request_autoscroll(Autoscroll::newest(), cx);
14527 cx.notify();
14528 }
14529
14530 pub fn toggle_fold(
14531 &mut self,
14532 _: &actions::ToggleFold,
14533 window: &mut Window,
14534 cx: &mut Context<Self>,
14535 ) {
14536 if self.is_singleton(cx) {
14537 let selection = self.selections.newest::<Point>(cx);
14538
14539 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14540 let range = if selection.is_empty() {
14541 let point = selection.head().to_display_point(&display_map);
14542 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14543 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14544 .to_point(&display_map);
14545 start..end
14546 } else {
14547 selection.range()
14548 };
14549 if display_map.folds_in_range(range).next().is_some() {
14550 self.unfold_lines(&Default::default(), window, cx)
14551 } else {
14552 self.fold(&Default::default(), window, cx)
14553 }
14554 } else {
14555 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14556 let buffer_ids: HashSet<_> = self
14557 .selections
14558 .disjoint_anchor_ranges()
14559 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14560 .collect();
14561
14562 let should_unfold = buffer_ids
14563 .iter()
14564 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14565
14566 for buffer_id in buffer_ids {
14567 if should_unfold {
14568 self.unfold_buffer(buffer_id, cx);
14569 } else {
14570 self.fold_buffer(buffer_id, cx);
14571 }
14572 }
14573 }
14574 }
14575
14576 pub fn toggle_fold_recursive(
14577 &mut self,
14578 _: &actions::ToggleFoldRecursive,
14579 window: &mut Window,
14580 cx: &mut Context<Self>,
14581 ) {
14582 let selection = self.selections.newest::<Point>(cx);
14583
14584 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14585 let range = if selection.is_empty() {
14586 let point = selection.head().to_display_point(&display_map);
14587 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14588 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14589 .to_point(&display_map);
14590 start..end
14591 } else {
14592 selection.range()
14593 };
14594 if display_map.folds_in_range(range).next().is_some() {
14595 self.unfold_recursive(&Default::default(), window, cx)
14596 } else {
14597 self.fold_recursive(&Default::default(), window, cx)
14598 }
14599 }
14600
14601 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14602 if self.is_singleton(cx) {
14603 let mut to_fold = Vec::new();
14604 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14605 let selections = self.selections.all_adjusted(cx);
14606
14607 for selection in selections {
14608 let range = selection.range().sorted();
14609 let buffer_start_row = range.start.row;
14610
14611 if range.start.row != range.end.row {
14612 let mut found = false;
14613 let mut row = range.start.row;
14614 while row <= range.end.row {
14615 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14616 {
14617 found = true;
14618 row = crease.range().end.row + 1;
14619 to_fold.push(crease);
14620 } else {
14621 row += 1
14622 }
14623 }
14624 if found {
14625 continue;
14626 }
14627 }
14628
14629 for row in (0..=range.start.row).rev() {
14630 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14631 if crease.range().end.row >= buffer_start_row {
14632 to_fold.push(crease);
14633 if row <= range.start.row {
14634 break;
14635 }
14636 }
14637 }
14638 }
14639 }
14640
14641 self.fold_creases(to_fold, true, window, cx);
14642 } else {
14643 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14644 let buffer_ids = self
14645 .selections
14646 .disjoint_anchor_ranges()
14647 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14648 .collect::<HashSet<_>>();
14649 for buffer_id in buffer_ids {
14650 self.fold_buffer(buffer_id, cx);
14651 }
14652 }
14653 }
14654
14655 fn fold_at_level(
14656 &mut self,
14657 fold_at: &FoldAtLevel,
14658 window: &mut Window,
14659 cx: &mut Context<Self>,
14660 ) {
14661 if !self.buffer.read(cx).is_singleton() {
14662 return;
14663 }
14664
14665 let fold_at_level = fold_at.0;
14666 let snapshot = self.buffer.read(cx).snapshot(cx);
14667 let mut to_fold = Vec::new();
14668 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14669
14670 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14671 while start_row < end_row {
14672 match self
14673 .snapshot(window, cx)
14674 .crease_for_buffer_row(MultiBufferRow(start_row))
14675 {
14676 Some(crease) => {
14677 let nested_start_row = crease.range().start.row + 1;
14678 let nested_end_row = crease.range().end.row;
14679
14680 if current_level < fold_at_level {
14681 stack.push((nested_start_row, nested_end_row, current_level + 1));
14682 } else if current_level == fold_at_level {
14683 to_fold.push(crease);
14684 }
14685
14686 start_row = nested_end_row + 1;
14687 }
14688 None => start_row += 1,
14689 }
14690 }
14691 }
14692
14693 self.fold_creases(to_fold, true, window, cx);
14694 }
14695
14696 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14697 if self.buffer.read(cx).is_singleton() {
14698 let mut fold_ranges = Vec::new();
14699 let snapshot = self.buffer.read(cx).snapshot(cx);
14700
14701 for row in 0..snapshot.max_row().0 {
14702 if let Some(foldable_range) = self
14703 .snapshot(window, cx)
14704 .crease_for_buffer_row(MultiBufferRow(row))
14705 {
14706 fold_ranges.push(foldable_range);
14707 }
14708 }
14709
14710 self.fold_creases(fold_ranges, true, window, cx);
14711 } else {
14712 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14713 editor
14714 .update_in(cx, |editor, _, cx| {
14715 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14716 editor.fold_buffer(buffer_id, cx);
14717 }
14718 })
14719 .ok();
14720 });
14721 }
14722 }
14723
14724 pub fn fold_function_bodies(
14725 &mut self,
14726 _: &actions::FoldFunctionBodies,
14727 window: &mut Window,
14728 cx: &mut Context<Self>,
14729 ) {
14730 let snapshot = self.buffer.read(cx).snapshot(cx);
14731
14732 let ranges = snapshot
14733 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14734 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14735 .collect::<Vec<_>>();
14736
14737 let creases = ranges
14738 .into_iter()
14739 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14740 .collect();
14741
14742 self.fold_creases(creases, true, window, cx);
14743 }
14744
14745 pub fn fold_recursive(
14746 &mut self,
14747 _: &actions::FoldRecursive,
14748 window: &mut Window,
14749 cx: &mut Context<Self>,
14750 ) {
14751 let mut to_fold = Vec::new();
14752 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14753 let selections = self.selections.all_adjusted(cx);
14754
14755 for selection in selections {
14756 let range = selection.range().sorted();
14757 let buffer_start_row = range.start.row;
14758
14759 if range.start.row != range.end.row {
14760 let mut found = false;
14761 for row in range.start.row..=range.end.row {
14762 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14763 found = true;
14764 to_fold.push(crease);
14765 }
14766 }
14767 if found {
14768 continue;
14769 }
14770 }
14771
14772 for row in (0..=range.start.row).rev() {
14773 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14774 if crease.range().end.row >= buffer_start_row {
14775 to_fold.push(crease);
14776 } else {
14777 break;
14778 }
14779 }
14780 }
14781 }
14782
14783 self.fold_creases(to_fold, true, window, cx);
14784 }
14785
14786 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14787 let buffer_row = fold_at.buffer_row;
14788 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14789
14790 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14791 let autoscroll = self
14792 .selections
14793 .all::<Point>(cx)
14794 .iter()
14795 .any(|selection| crease.range().overlaps(&selection.range()));
14796
14797 self.fold_creases(vec![crease], autoscroll, window, cx);
14798 }
14799 }
14800
14801 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14802 if self.is_singleton(cx) {
14803 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14804 let buffer = &display_map.buffer_snapshot;
14805 let selections = self.selections.all::<Point>(cx);
14806 let ranges = selections
14807 .iter()
14808 .map(|s| {
14809 let range = s.display_range(&display_map).sorted();
14810 let mut start = range.start.to_point(&display_map);
14811 let mut end = range.end.to_point(&display_map);
14812 start.column = 0;
14813 end.column = buffer.line_len(MultiBufferRow(end.row));
14814 start..end
14815 })
14816 .collect::<Vec<_>>();
14817
14818 self.unfold_ranges(&ranges, true, true, cx);
14819 } else {
14820 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14821 let buffer_ids = self
14822 .selections
14823 .disjoint_anchor_ranges()
14824 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14825 .collect::<HashSet<_>>();
14826 for buffer_id in buffer_ids {
14827 self.unfold_buffer(buffer_id, cx);
14828 }
14829 }
14830 }
14831
14832 pub fn unfold_recursive(
14833 &mut self,
14834 _: &UnfoldRecursive,
14835 _window: &mut Window,
14836 cx: &mut Context<Self>,
14837 ) {
14838 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14839 let selections = self.selections.all::<Point>(cx);
14840 let ranges = selections
14841 .iter()
14842 .map(|s| {
14843 let mut range = s.display_range(&display_map).sorted();
14844 *range.start.column_mut() = 0;
14845 *range.end.column_mut() = display_map.line_len(range.end.row());
14846 let start = range.start.to_point(&display_map);
14847 let end = range.end.to_point(&display_map);
14848 start..end
14849 })
14850 .collect::<Vec<_>>();
14851
14852 self.unfold_ranges(&ranges, true, true, cx);
14853 }
14854
14855 pub fn unfold_at(
14856 &mut self,
14857 unfold_at: &UnfoldAt,
14858 _window: &mut Window,
14859 cx: &mut Context<Self>,
14860 ) {
14861 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14862
14863 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14864 ..Point::new(
14865 unfold_at.buffer_row.0,
14866 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14867 );
14868
14869 let autoscroll = self
14870 .selections
14871 .all::<Point>(cx)
14872 .iter()
14873 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14874
14875 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14876 }
14877
14878 pub fn unfold_all(
14879 &mut self,
14880 _: &actions::UnfoldAll,
14881 _window: &mut Window,
14882 cx: &mut Context<Self>,
14883 ) {
14884 if self.buffer.read(cx).is_singleton() {
14885 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14886 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14887 } else {
14888 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14889 editor
14890 .update(cx, |editor, cx| {
14891 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14892 editor.unfold_buffer(buffer_id, cx);
14893 }
14894 })
14895 .ok();
14896 });
14897 }
14898 }
14899
14900 pub fn fold_selected_ranges(
14901 &mut self,
14902 _: &FoldSelectedRanges,
14903 window: &mut Window,
14904 cx: &mut Context<Self>,
14905 ) {
14906 let selections = self.selections.all_adjusted(cx);
14907 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14908 let ranges = selections
14909 .into_iter()
14910 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
14911 .collect::<Vec<_>>();
14912 self.fold_creases(ranges, true, window, cx);
14913 }
14914
14915 pub fn fold_ranges<T: ToOffset + Clone>(
14916 &mut self,
14917 ranges: Vec<Range<T>>,
14918 auto_scroll: bool,
14919 window: &mut Window,
14920 cx: &mut Context<Self>,
14921 ) {
14922 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14923 let ranges = ranges
14924 .into_iter()
14925 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14926 .collect::<Vec<_>>();
14927 self.fold_creases(ranges, auto_scroll, window, cx);
14928 }
14929
14930 pub fn fold_creases<T: ToOffset + Clone>(
14931 &mut self,
14932 creases: Vec<Crease<T>>,
14933 auto_scroll: bool,
14934 window: &mut Window,
14935 cx: &mut Context<Self>,
14936 ) {
14937 if creases.is_empty() {
14938 return;
14939 }
14940
14941 let mut buffers_affected = HashSet::default();
14942 let multi_buffer = self.buffer().read(cx);
14943 for crease in &creases {
14944 if let Some((_, buffer, _)) =
14945 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14946 {
14947 buffers_affected.insert(buffer.read(cx).remote_id());
14948 };
14949 }
14950
14951 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14952
14953 if auto_scroll {
14954 self.request_autoscroll(Autoscroll::fit(), cx);
14955 }
14956
14957 cx.notify();
14958
14959 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14960 // Clear diagnostics block when folding a range that contains it.
14961 let snapshot = self.snapshot(window, cx);
14962 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14963 drop(snapshot);
14964 self.active_diagnostics = Some(active_diagnostics);
14965 self.dismiss_diagnostics(cx);
14966 } else {
14967 self.active_diagnostics = Some(active_diagnostics);
14968 }
14969 }
14970
14971 self.scrollbar_marker_state.dirty = true;
14972 self.folds_did_change(cx);
14973 }
14974
14975 /// Removes any folds whose ranges intersect any of the given ranges.
14976 pub fn unfold_ranges<T: ToOffset + Clone>(
14977 &mut self,
14978 ranges: &[Range<T>],
14979 inclusive: bool,
14980 auto_scroll: bool,
14981 cx: &mut Context<Self>,
14982 ) {
14983 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14984 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14985 });
14986 self.folds_did_change(cx);
14987 }
14988
14989 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14990 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14991 return;
14992 }
14993 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14994 self.display_map.update(cx, |display_map, cx| {
14995 display_map.fold_buffers([buffer_id], cx)
14996 });
14997 cx.emit(EditorEvent::BufferFoldToggled {
14998 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14999 folded: true,
15000 });
15001 cx.notify();
15002 }
15003
15004 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15005 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15006 return;
15007 }
15008 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15009 self.display_map.update(cx, |display_map, cx| {
15010 display_map.unfold_buffers([buffer_id], cx);
15011 });
15012 cx.emit(EditorEvent::BufferFoldToggled {
15013 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15014 folded: false,
15015 });
15016 cx.notify();
15017 }
15018
15019 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15020 self.display_map.read(cx).is_buffer_folded(buffer)
15021 }
15022
15023 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15024 self.display_map.read(cx).folded_buffers()
15025 }
15026
15027 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15028 self.display_map.update(cx, |display_map, cx| {
15029 display_map.disable_header_for_buffer(buffer_id, cx);
15030 });
15031 cx.notify();
15032 }
15033
15034 /// Removes any folds with the given ranges.
15035 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15036 &mut self,
15037 ranges: &[Range<T>],
15038 type_id: TypeId,
15039 auto_scroll: bool,
15040 cx: &mut Context<Self>,
15041 ) {
15042 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15043 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15044 });
15045 self.folds_did_change(cx);
15046 }
15047
15048 fn remove_folds_with<T: ToOffset + Clone>(
15049 &mut self,
15050 ranges: &[Range<T>],
15051 auto_scroll: bool,
15052 cx: &mut Context<Self>,
15053 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15054 ) {
15055 if ranges.is_empty() {
15056 return;
15057 }
15058
15059 let mut buffers_affected = HashSet::default();
15060 let multi_buffer = self.buffer().read(cx);
15061 for range in ranges {
15062 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15063 buffers_affected.insert(buffer.read(cx).remote_id());
15064 };
15065 }
15066
15067 self.display_map.update(cx, update);
15068
15069 if auto_scroll {
15070 self.request_autoscroll(Autoscroll::fit(), cx);
15071 }
15072
15073 cx.notify();
15074 self.scrollbar_marker_state.dirty = true;
15075 self.active_indent_guides_state.dirty = true;
15076 }
15077
15078 pub fn update_fold_widths(
15079 &mut self,
15080 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15081 cx: &mut Context<Self>,
15082 ) -> bool {
15083 self.display_map
15084 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15085 }
15086
15087 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15088 self.display_map.read(cx).fold_placeholder.clone()
15089 }
15090
15091 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15092 self.buffer.update(cx, |buffer, cx| {
15093 buffer.set_all_diff_hunks_expanded(cx);
15094 });
15095 }
15096
15097 pub fn expand_all_diff_hunks(
15098 &mut self,
15099 _: &ExpandAllDiffHunks,
15100 _window: &mut Window,
15101 cx: &mut Context<Self>,
15102 ) {
15103 self.buffer.update(cx, |buffer, cx| {
15104 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15105 });
15106 }
15107
15108 pub fn toggle_selected_diff_hunks(
15109 &mut self,
15110 _: &ToggleSelectedDiffHunks,
15111 _window: &mut Window,
15112 cx: &mut Context<Self>,
15113 ) {
15114 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15115 self.toggle_diff_hunks_in_ranges(ranges, cx);
15116 }
15117
15118 pub fn diff_hunks_in_ranges<'a>(
15119 &'a self,
15120 ranges: &'a [Range<Anchor>],
15121 buffer: &'a MultiBufferSnapshot,
15122 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15123 ranges.iter().flat_map(move |range| {
15124 let end_excerpt_id = range.end.excerpt_id;
15125 let range = range.to_point(buffer);
15126 let mut peek_end = range.end;
15127 if range.end.row < buffer.max_row().0 {
15128 peek_end = Point::new(range.end.row + 1, 0);
15129 }
15130 buffer
15131 .diff_hunks_in_range(range.start..peek_end)
15132 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15133 })
15134 }
15135
15136 pub fn has_stageable_diff_hunks_in_ranges(
15137 &self,
15138 ranges: &[Range<Anchor>],
15139 snapshot: &MultiBufferSnapshot,
15140 ) -> bool {
15141 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15142 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15143 }
15144
15145 pub fn toggle_staged_selected_diff_hunks(
15146 &mut self,
15147 _: &::git::ToggleStaged,
15148 _: &mut Window,
15149 cx: &mut Context<Self>,
15150 ) {
15151 let snapshot = self.buffer.read(cx).snapshot(cx);
15152 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15153 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15154 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15155 }
15156
15157 pub fn set_render_diff_hunk_controls(
15158 &mut self,
15159 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15160 cx: &mut Context<Self>,
15161 ) {
15162 self.render_diff_hunk_controls = render_diff_hunk_controls;
15163 cx.notify();
15164 }
15165
15166 pub fn stage_and_next(
15167 &mut self,
15168 _: &::git::StageAndNext,
15169 window: &mut Window,
15170 cx: &mut Context<Self>,
15171 ) {
15172 self.do_stage_or_unstage_and_next(true, window, cx);
15173 }
15174
15175 pub fn unstage_and_next(
15176 &mut self,
15177 _: &::git::UnstageAndNext,
15178 window: &mut Window,
15179 cx: &mut Context<Self>,
15180 ) {
15181 self.do_stage_or_unstage_and_next(false, window, cx);
15182 }
15183
15184 pub fn stage_or_unstage_diff_hunks(
15185 &mut self,
15186 stage: bool,
15187 ranges: Vec<Range<Anchor>>,
15188 cx: &mut Context<Self>,
15189 ) {
15190 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15191 cx.spawn(async move |this, cx| {
15192 task.await?;
15193 this.update(cx, |this, cx| {
15194 let snapshot = this.buffer.read(cx).snapshot(cx);
15195 let chunk_by = this
15196 .diff_hunks_in_ranges(&ranges, &snapshot)
15197 .chunk_by(|hunk| hunk.buffer_id);
15198 for (buffer_id, hunks) in &chunk_by {
15199 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15200 }
15201 })
15202 })
15203 .detach_and_log_err(cx);
15204 }
15205
15206 fn save_buffers_for_ranges_if_needed(
15207 &mut self,
15208 ranges: &[Range<Anchor>],
15209 cx: &mut Context<Editor>,
15210 ) -> Task<Result<()>> {
15211 let multibuffer = self.buffer.read(cx);
15212 let snapshot = multibuffer.read(cx);
15213 let buffer_ids: HashSet<_> = ranges
15214 .iter()
15215 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15216 .collect();
15217 drop(snapshot);
15218
15219 let mut buffers = HashSet::default();
15220 for buffer_id in buffer_ids {
15221 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15222 let buffer = buffer_entity.read(cx);
15223 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15224 {
15225 buffers.insert(buffer_entity);
15226 }
15227 }
15228 }
15229
15230 if let Some(project) = &self.project {
15231 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15232 } else {
15233 Task::ready(Ok(()))
15234 }
15235 }
15236
15237 fn do_stage_or_unstage_and_next(
15238 &mut self,
15239 stage: bool,
15240 window: &mut Window,
15241 cx: &mut Context<Self>,
15242 ) {
15243 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15244
15245 if ranges.iter().any(|range| range.start != range.end) {
15246 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15247 return;
15248 }
15249
15250 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15251 let snapshot = self.snapshot(window, cx);
15252 let position = self.selections.newest::<Point>(cx).head();
15253 let mut row = snapshot
15254 .buffer_snapshot
15255 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15256 .find(|hunk| hunk.row_range.start.0 > position.row)
15257 .map(|hunk| hunk.row_range.start);
15258
15259 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15260 // Outside of the project diff editor, wrap around to the beginning.
15261 if !all_diff_hunks_expanded {
15262 row = row.or_else(|| {
15263 snapshot
15264 .buffer_snapshot
15265 .diff_hunks_in_range(Point::zero()..position)
15266 .find(|hunk| hunk.row_range.end.0 < position.row)
15267 .map(|hunk| hunk.row_range.start)
15268 });
15269 }
15270
15271 if let Some(row) = row {
15272 let destination = Point::new(row.0, 0);
15273 let autoscroll = Autoscroll::center();
15274
15275 self.unfold_ranges(&[destination..destination], false, false, cx);
15276 self.change_selections(Some(autoscroll), window, cx, |s| {
15277 s.select_ranges([destination..destination]);
15278 });
15279 }
15280 }
15281
15282 fn do_stage_or_unstage(
15283 &self,
15284 stage: bool,
15285 buffer_id: BufferId,
15286 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15287 cx: &mut App,
15288 ) -> Option<()> {
15289 let project = self.project.as_ref()?;
15290 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15291 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15292 let buffer_snapshot = buffer.read(cx).snapshot();
15293 let file_exists = buffer_snapshot
15294 .file()
15295 .is_some_and(|file| file.disk_state().exists());
15296 diff.update(cx, |diff, cx| {
15297 diff.stage_or_unstage_hunks(
15298 stage,
15299 &hunks
15300 .map(|hunk| buffer_diff::DiffHunk {
15301 buffer_range: hunk.buffer_range,
15302 diff_base_byte_range: hunk.diff_base_byte_range,
15303 secondary_status: hunk.secondary_status,
15304 range: Point::zero()..Point::zero(), // unused
15305 })
15306 .collect::<Vec<_>>(),
15307 &buffer_snapshot,
15308 file_exists,
15309 cx,
15310 )
15311 });
15312 None
15313 }
15314
15315 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15316 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15317 self.buffer
15318 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15319 }
15320
15321 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15322 self.buffer.update(cx, |buffer, cx| {
15323 let ranges = vec![Anchor::min()..Anchor::max()];
15324 if !buffer.all_diff_hunks_expanded()
15325 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15326 {
15327 buffer.collapse_diff_hunks(ranges, cx);
15328 true
15329 } else {
15330 false
15331 }
15332 })
15333 }
15334
15335 fn toggle_diff_hunks_in_ranges(
15336 &mut self,
15337 ranges: Vec<Range<Anchor>>,
15338 cx: &mut Context<Editor>,
15339 ) {
15340 self.buffer.update(cx, |buffer, cx| {
15341 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15342 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15343 })
15344 }
15345
15346 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15347 self.buffer.update(cx, |buffer, cx| {
15348 let snapshot = buffer.snapshot(cx);
15349 let excerpt_id = range.end.excerpt_id;
15350 let point_range = range.to_point(&snapshot);
15351 let expand = !buffer.single_hunk_is_expanded(range, cx);
15352 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15353 })
15354 }
15355
15356 pub(crate) fn apply_all_diff_hunks(
15357 &mut self,
15358 _: &ApplyAllDiffHunks,
15359 window: &mut Window,
15360 cx: &mut Context<Self>,
15361 ) {
15362 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15363
15364 let buffers = self.buffer.read(cx).all_buffers();
15365 for branch_buffer in buffers {
15366 branch_buffer.update(cx, |branch_buffer, cx| {
15367 branch_buffer.merge_into_base(Vec::new(), cx);
15368 });
15369 }
15370
15371 if let Some(project) = self.project.clone() {
15372 self.save(true, project, window, cx).detach_and_log_err(cx);
15373 }
15374 }
15375
15376 pub(crate) fn apply_selected_diff_hunks(
15377 &mut self,
15378 _: &ApplyDiffHunk,
15379 window: &mut Window,
15380 cx: &mut Context<Self>,
15381 ) {
15382 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15383 let snapshot = self.snapshot(window, cx);
15384 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15385 let mut ranges_by_buffer = HashMap::default();
15386 self.transact(window, cx, |editor, _window, cx| {
15387 for hunk in hunks {
15388 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15389 ranges_by_buffer
15390 .entry(buffer.clone())
15391 .or_insert_with(Vec::new)
15392 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15393 }
15394 }
15395
15396 for (buffer, ranges) in ranges_by_buffer {
15397 buffer.update(cx, |buffer, cx| {
15398 buffer.merge_into_base(ranges, cx);
15399 });
15400 }
15401 });
15402
15403 if let Some(project) = self.project.clone() {
15404 self.save(true, project, window, cx).detach_and_log_err(cx);
15405 }
15406 }
15407
15408 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15409 if hovered != self.gutter_hovered {
15410 self.gutter_hovered = hovered;
15411 cx.notify();
15412 }
15413 }
15414
15415 pub fn insert_blocks(
15416 &mut self,
15417 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15418 autoscroll: Option<Autoscroll>,
15419 cx: &mut Context<Self>,
15420 ) -> Vec<CustomBlockId> {
15421 let blocks = self
15422 .display_map
15423 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15424 if let Some(autoscroll) = autoscroll {
15425 self.request_autoscroll(autoscroll, cx);
15426 }
15427 cx.notify();
15428 blocks
15429 }
15430
15431 pub fn resize_blocks(
15432 &mut self,
15433 heights: HashMap<CustomBlockId, u32>,
15434 autoscroll: Option<Autoscroll>,
15435 cx: &mut Context<Self>,
15436 ) {
15437 self.display_map
15438 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15439 if let Some(autoscroll) = autoscroll {
15440 self.request_autoscroll(autoscroll, cx);
15441 }
15442 cx.notify();
15443 }
15444
15445 pub fn replace_blocks(
15446 &mut self,
15447 renderers: HashMap<CustomBlockId, RenderBlock>,
15448 autoscroll: Option<Autoscroll>,
15449 cx: &mut Context<Self>,
15450 ) {
15451 self.display_map
15452 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15453 if let Some(autoscroll) = autoscroll {
15454 self.request_autoscroll(autoscroll, cx);
15455 }
15456 cx.notify();
15457 }
15458
15459 pub fn remove_blocks(
15460 &mut self,
15461 block_ids: HashSet<CustomBlockId>,
15462 autoscroll: Option<Autoscroll>,
15463 cx: &mut Context<Self>,
15464 ) {
15465 self.display_map.update(cx, |display_map, cx| {
15466 display_map.remove_blocks(block_ids, cx)
15467 });
15468 if let Some(autoscroll) = autoscroll {
15469 self.request_autoscroll(autoscroll, cx);
15470 }
15471 cx.notify();
15472 }
15473
15474 pub fn row_for_block(
15475 &self,
15476 block_id: CustomBlockId,
15477 cx: &mut Context<Self>,
15478 ) -> Option<DisplayRow> {
15479 self.display_map
15480 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15481 }
15482
15483 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15484 self.focused_block = Some(focused_block);
15485 }
15486
15487 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15488 self.focused_block.take()
15489 }
15490
15491 pub fn insert_creases(
15492 &mut self,
15493 creases: impl IntoIterator<Item = Crease<Anchor>>,
15494 cx: &mut Context<Self>,
15495 ) -> Vec<CreaseId> {
15496 self.display_map
15497 .update(cx, |map, cx| map.insert_creases(creases, cx))
15498 }
15499
15500 pub fn remove_creases(
15501 &mut self,
15502 ids: impl IntoIterator<Item = CreaseId>,
15503 cx: &mut Context<Self>,
15504 ) {
15505 self.display_map
15506 .update(cx, |map, cx| map.remove_creases(ids, cx));
15507 }
15508
15509 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15510 self.display_map
15511 .update(cx, |map, cx| map.snapshot(cx))
15512 .longest_row()
15513 }
15514
15515 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15516 self.display_map
15517 .update(cx, |map, cx| map.snapshot(cx))
15518 .max_point()
15519 }
15520
15521 pub fn text(&self, cx: &App) -> String {
15522 self.buffer.read(cx).read(cx).text()
15523 }
15524
15525 pub fn is_empty(&self, cx: &App) -> bool {
15526 self.buffer.read(cx).read(cx).is_empty()
15527 }
15528
15529 pub fn text_option(&self, cx: &App) -> Option<String> {
15530 let text = self.text(cx);
15531 let text = text.trim();
15532
15533 if text.is_empty() {
15534 return None;
15535 }
15536
15537 Some(text.to_string())
15538 }
15539
15540 pub fn set_text(
15541 &mut self,
15542 text: impl Into<Arc<str>>,
15543 window: &mut Window,
15544 cx: &mut Context<Self>,
15545 ) {
15546 self.transact(window, cx, |this, _, cx| {
15547 this.buffer
15548 .read(cx)
15549 .as_singleton()
15550 .expect("you can only call set_text on editors for singleton buffers")
15551 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15552 });
15553 }
15554
15555 pub fn display_text(&self, cx: &mut App) -> String {
15556 self.display_map
15557 .update(cx, |map, cx| map.snapshot(cx))
15558 .text()
15559 }
15560
15561 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15562 let mut wrap_guides = smallvec::smallvec![];
15563
15564 if self.show_wrap_guides == Some(false) {
15565 return wrap_guides;
15566 }
15567
15568 let settings = self.buffer.read(cx).language_settings(cx);
15569 if settings.show_wrap_guides {
15570 match self.soft_wrap_mode(cx) {
15571 SoftWrap::Column(soft_wrap) => {
15572 wrap_guides.push((soft_wrap as usize, true));
15573 }
15574 SoftWrap::Bounded(soft_wrap) => {
15575 wrap_guides.push((soft_wrap as usize, true));
15576 }
15577 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15578 }
15579 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15580 }
15581
15582 wrap_guides
15583 }
15584
15585 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15586 let settings = self.buffer.read(cx).language_settings(cx);
15587 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15588 match mode {
15589 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15590 SoftWrap::None
15591 }
15592 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15593 language_settings::SoftWrap::PreferredLineLength => {
15594 SoftWrap::Column(settings.preferred_line_length)
15595 }
15596 language_settings::SoftWrap::Bounded => {
15597 SoftWrap::Bounded(settings.preferred_line_length)
15598 }
15599 }
15600 }
15601
15602 pub fn set_soft_wrap_mode(
15603 &mut self,
15604 mode: language_settings::SoftWrap,
15605
15606 cx: &mut Context<Self>,
15607 ) {
15608 self.soft_wrap_mode_override = Some(mode);
15609 cx.notify();
15610 }
15611
15612 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15613 self.hard_wrap = hard_wrap;
15614 cx.notify();
15615 }
15616
15617 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15618 self.text_style_refinement = Some(style);
15619 }
15620
15621 /// called by the Element so we know what style we were most recently rendered with.
15622 pub(crate) fn set_style(
15623 &mut self,
15624 style: EditorStyle,
15625 window: &mut Window,
15626 cx: &mut Context<Self>,
15627 ) {
15628 let rem_size = window.rem_size();
15629 self.display_map.update(cx, |map, cx| {
15630 map.set_font(
15631 style.text.font(),
15632 style.text.font_size.to_pixels(rem_size),
15633 cx,
15634 )
15635 });
15636 self.style = Some(style);
15637 }
15638
15639 pub fn style(&self) -> Option<&EditorStyle> {
15640 self.style.as_ref()
15641 }
15642
15643 // Called by the element. This method is not designed to be called outside of the editor
15644 // element's layout code because it does not notify when rewrapping is computed synchronously.
15645 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15646 self.display_map
15647 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15648 }
15649
15650 pub fn set_soft_wrap(&mut self) {
15651 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15652 }
15653
15654 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15655 if self.soft_wrap_mode_override.is_some() {
15656 self.soft_wrap_mode_override.take();
15657 } else {
15658 let soft_wrap = match self.soft_wrap_mode(cx) {
15659 SoftWrap::GitDiff => return,
15660 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15661 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15662 language_settings::SoftWrap::None
15663 }
15664 };
15665 self.soft_wrap_mode_override = Some(soft_wrap);
15666 }
15667 cx.notify();
15668 }
15669
15670 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15671 let Some(workspace) = self.workspace() else {
15672 return;
15673 };
15674 let fs = workspace.read(cx).app_state().fs.clone();
15675 let current_show = TabBarSettings::get_global(cx).show;
15676 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15677 setting.show = Some(!current_show);
15678 });
15679 }
15680
15681 pub fn toggle_indent_guides(
15682 &mut self,
15683 _: &ToggleIndentGuides,
15684 _: &mut Window,
15685 cx: &mut Context<Self>,
15686 ) {
15687 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15688 self.buffer
15689 .read(cx)
15690 .language_settings(cx)
15691 .indent_guides
15692 .enabled
15693 });
15694 self.show_indent_guides = Some(!currently_enabled);
15695 cx.notify();
15696 }
15697
15698 fn should_show_indent_guides(&self) -> Option<bool> {
15699 self.show_indent_guides
15700 }
15701
15702 pub fn toggle_line_numbers(
15703 &mut self,
15704 _: &ToggleLineNumbers,
15705 _: &mut Window,
15706 cx: &mut Context<Self>,
15707 ) {
15708 let mut editor_settings = EditorSettings::get_global(cx).clone();
15709 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15710 EditorSettings::override_global(editor_settings, cx);
15711 }
15712
15713 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15714 if let Some(show_line_numbers) = self.show_line_numbers {
15715 return show_line_numbers;
15716 }
15717 EditorSettings::get_global(cx).gutter.line_numbers
15718 }
15719
15720 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15721 self.use_relative_line_numbers
15722 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15723 }
15724
15725 pub fn toggle_relative_line_numbers(
15726 &mut self,
15727 _: &ToggleRelativeLineNumbers,
15728 _: &mut Window,
15729 cx: &mut Context<Self>,
15730 ) {
15731 let is_relative = self.should_use_relative_line_numbers(cx);
15732 self.set_relative_line_number(Some(!is_relative), cx)
15733 }
15734
15735 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15736 self.use_relative_line_numbers = is_relative;
15737 cx.notify();
15738 }
15739
15740 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15741 self.show_gutter = show_gutter;
15742 cx.notify();
15743 }
15744
15745 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15746 self.show_scrollbars = show_scrollbars;
15747 cx.notify();
15748 }
15749
15750 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15751 self.show_line_numbers = Some(show_line_numbers);
15752 cx.notify();
15753 }
15754
15755 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15756 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15757 cx.notify();
15758 }
15759
15760 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15761 self.show_code_actions = Some(show_code_actions);
15762 cx.notify();
15763 }
15764
15765 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15766 self.show_runnables = Some(show_runnables);
15767 cx.notify();
15768 }
15769
15770 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15771 self.show_breakpoints = Some(show_breakpoints);
15772 cx.notify();
15773 }
15774
15775 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15776 if self.display_map.read(cx).masked != masked {
15777 self.display_map.update(cx, |map, _| map.masked = masked);
15778 }
15779 cx.notify()
15780 }
15781
15782 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15783 self.show_wrap_guides = Some(show_wrap_guides);
15784 cx.notify();
15785 }
15786
15787 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15788 self.show_indent_guides = Some(show_indent_guides);
15789 cx.notify();
15790 }
15791
15792 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15793 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15794 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15795 if let Some(dir) = file.abs_path(cx).parent() {
15796 return Some(dir.to_owned());
15797 }
15798 }
15799
15800 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15801 return Some(project_path.path.to_path_buf());
15802 }
15803 }
15804
15805 None
15806 }
15807
15808 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15809 self.active_excerpt(cx)?
15810 .1
15811 .read(cx)
15812 .file()
15813 .and_then(|f| f.as_local())
15814 }
15815
15816 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15817 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15818 let buffer = buffer.read(cx);
15819 if let Some(project_path) = buffer.project_path(cx) {
15820 let project = self.project.as_ref()?.read(cx);
15821 project.absolute_path(&project_path, cx)
15822 } else {
15823 buffer
15824 .file()
15825 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15826 }
15827 })
15828 }
15829
15830 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15831 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15832 let project_path = buffer.read(cx).project_path(cx)?;
15833 let project = self.project.as_ref()?.read(cx);
15834 let entry = project.entry_for_path(&project_path, cx)?;
15835 let path = entry.path.to_path_buf();
15836 Some(path)
15837 })
15838 }
15839
15840 pub fn reveal_in_finder(
15841 &mut self,
15842 _: &RevealInFileManager,
15843 _window: &mut Window,
15844 cx: &mut Context<Self>,
15845 ) {
15846 if let Some(target) = self.target_file(cx) {
15847 cx.reveal_path(&target.abs_path(cx));
15848 }
15849 }
15850
15851 pub fn copy_path(
15852 &mut self,
15853 _: &zed_actions::workspace::CopyPath,
15854 _window: &mut Window,
15855 cx: &mut Context<Self>,
15856 ) {
15857 if let Some(path) = self.target_file_abs_path(cx) {
15858 if let Some(path) = path.to_str() {
15859 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15860 }
15861 }
15862 }
15863
15864 pub fn copy_relative_path(
15865 &mut self,
15866 _: &zed_actions::workspace::CopyRelativePath,
15867 _window: &mut Window,
15868 cx: &mut Context<Self>,
15869 ) {
15870 if let Some(path) = self.target_file_path(cx) {
15871 if let Some(path) = path.to_str() {
15872 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15873 }
15874 }
15875 }
15876
15877 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15878 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15879 buffer.read(cx).project_path(cx)
15880 } else {
15881 None
15882 }
15883 }
15884
15885 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15886 let _ = maybe!({
15887 let breakpoint_store = self.breakpoint_store.as_ref()?;
15888
15889 let Some((_, _, active_position)) =
15890 breakpoint_store.read(cx).active_position().cloned()
15891 else {
15892 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15893 return None;
15894 };
15895
15896 let snapshot = self
15897 .project
15898 .as_ref()?
15899 .read(cx)
15900 .buffer_for_id(active_position.buffer_id?, cx)?
15901 .read(cx)
15902 .snapshot();
15903
15904 for (id, ExcerptRange { context, .. }) in self
15905 .buffer
15906 .read(cx)
15907 .excerpts_for_buffer(active_position.buffer_id?, cx)
15908 {
15909 if context.start.cmp(&active_position, &snapshot).is_ge()
15910 || context.end.cmp(&active_position, &snapshot).is_lt()
15911 {
15912 continue;
15913 }
15914 let snapshot = self.buffer.read(cx).snapshot(cx);
15915 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15916
15917 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15918 self.go_to_line::<DebugCurrentRowHighlight>(
15919 multibuffer_anchor,
15920 Some(cx.theme().colors().editor_debugger_active_line_background),
15921 window,
15922 cx,
15923 );
15924
15925 cx.notify();
15926 }
15927
15928 Some(())
15929 });
15930 }
15931
15932 pub fn copy_file_name_without_extension(
15933 &mut self,
15934 _: &CopyFileNameWithoutExtension,
15935 _: &mut Window,
15936 cx: &mut Context<Self>,
15937 ) {
15938 if let Some(file) = self.target_file(cx) {
15939 if let Some(file_stem) = file.path().file_stem() {
15940 if let Some(name) = file_stem.to_str() {
15941 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15942 }
15943 }
15944 }
15945 }
15946
15947 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15948 if let Some(file) = self.target_file(cx) {
15949 if let Some(file_name) = file.path().file_name() {
15950 if let Some(name) = file_name.to_str() {
15951 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15952 }
15953 }
15954 }
15955 }
15956
15957 pub fn toggle_git_blame(
15958 &mut self,
15959 _: &::git::Blame,
15960 window: &mut Window,
15961 cx: &mut Context<Self>,
15962 ) {
15963 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15964
15965 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15966 self.start_git_blame(true, window, cx);
15967 }
15968
15969 cx.notify();
15970 }
15971
15972 pub fn toggle_git_blame_inline(
15973 &mut self,
15974 _: &ToggleGitBlameInline,
15975 window: &mut Window,
15976 cx: &mut Context<Self>,
15977 ) {
15978 self.toggle_git_blame_inline_internal(true, window, cx);
15979 cx.notify();
15980 }
15981
15982 pub fn open_git_blame_commit(
15983 &mut self,
15984 _: &OpenGitBlameCommit,
15985 window: &mut Window,
15986 cx: &mut Context<Self>,
15987 ) {
15988 self.open_git_blame_commit_internal(window, cx);
15989 }
15990
15991 fn open_git_blame_commit_internal(
15992 &mut self,
15993 window: &mut Window,
15994 cx: &mut Context<Self>,
15995 ) -> Option<()> {
15996 let blame = self.blame.as_ref()?;
15997 let snapshot = self.snapshot(window, cx);
15998 let cursor = self.selections.newest::<Point>(cx).head();
15999 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16000 let blame_entry = blame
16001 .update(cx, |blame, cx| {
16002 blame
16003 .blame_for_rows(
16004 &[RowInfo {
16005 buffer_id: Some(buffer.remote_id()),
16006 buffer_row: Some(point.row),
16007 ..Default::default()
16008 }],
16009 cx,
16010 )
16011 .next()
16012 })
16013 .flatten()?;
16014 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16015 let repo = blame.read(cx).repository(cx)?;
16016 let workspace = self.workspace()?.downgrade();
16017 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16018 None
16019 }
16020
16021 pub fn git_blame_inline_enabled(&self) -> bool {
16022 self.git_blame_inline_enabled
16023 }
16024
16025 pub fn toggle_selection_menu(
16026 &mut self,
16027 _: &ToggleSelectionMenu,
16028 _: &mut Window,
16029 cx: &mut Context<Self>,
16030 ) {
16031 self.show_selection_menu = self
16032 .show_selection_menu
16033 .map(|show_selections_menu| !show_selections_menu)
16034 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16035
16036 cx.notify();
16037 }
16038
16039 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16040 self.show_selection_menu
16041 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16042 }
16043
16044 fn start_git_blame(
16045 &mut self,
16046 user_triggered: bool,
16047 window: &mut Window,
16048 cx: &mut Context<Self>,
16049 ) {
16050 if let Some(project) = self.project.as_ref() {
16051 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16052 return;
16053 };
16054
16055 if buffer.read(cx).file().is_none() {
16056 return;
16057 }
16058
16059 let focused = self.focus_handle(cx).contains_focused(window, cx);
16060
16061 let project = project.clone();
16062 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16063 self.blame_subscription =
16064 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16065 self.blame = Some(blame);
16066 }
16067 }
16068
16069 fn toggle_git_blame_inline_internal(
16070 &mut self,
16071 user_triggered: bool,
16072 window: &mut Window,
16073 cx: &mut Context<Self>,
16074 ) {
16075 if self.git_blame_inline_enabled {
16076 self.git_blame_inline_enabled = false;
16077 self.show_git_blame_inline = false;
16078 self.show_git_blame_inline_delay_task.take();
16079 } else {
16080 self.git_blame_inline_enabled = true;
16081 self.start_git_blame_inline(user_triggered, window, cx);
16082 }
16083
16084 cx.notify();
16085 }
16086
16087 fn start_git_blame_inline(
16088 &mut self,
16089 user_triggered: bool,
16090 window: &mut Window,
16091 cx: &mut Context<Self>,
16092 ) {
16093 self.start_git_blame(user_triggered, window, cx);
16094
16095 if ProjectSettings::get_global(cx)
16096 .git
16097 .inline_blame_delay()
16098 .is_some()
16099 {
16100 self.start_inline_blame_timer(window, cx);
16101 } else {
16102 self.show_git_blame_inline = true
16103 }
16104 }
16105
16106 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16107 self.blame.as_ref()
16108 }
16109
16110 pub fn show_git_blame_gutter(&self) -> bool {
16111 self.show_git_blame_gutter
16112 }
16113
16114 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16115 self.show_git_blame_gutter && self.has_blame_entries(cx)
16116 }
16117
16118 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16119 self.show_git_blame_inline
16120 && (self.focus_handle.is_focused(window)
16121 || self
16122 .git_blame_inline_tooltip
16123 .as_ref()
16124 .and_then(|t| t.upgrade())
16125 .is_some())
16126 && !self.newest_selection_head_on_empty_line(cx)
16127 && self.has_blame_entries(cx)
16128 }
16129
16130 fn has_blame_entries(&self, cx: &App) -> bool {
16131 self.blame()
16132 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16133 }
16134
16135 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16136 let cursor_anchor = self.selections.newest_anchor().head();
16137
16138 let snapshot = self.buffer.read(cx).snapshot(cx);
16139 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16140
16141 snapshot.line_len(buffer_row) == 0
16142 }
16143
16144 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16145 let buffer_and_selection = maybe!({
16146 let selection = self.selections.newest::<Point>(cx);
16147 let selection_range = selection.range();
16148
16149 let multi_buffer = self.buffer().read(cx);
16150 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16151 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16152
16153 let (buffer, range, _) = if selection.reversed {
16154 buffer_ranges.first()
16155 } else {
16156 buffer_ranges.last()
16157 }?;
16158
16159 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16160 ..text::ToPoint::to_point(&range.end, &buffer).row;
16161 Some((
16162 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16163 selection,
16164 ))
16165 });
16166
16167 let Some((buffer, selection)) = buffer_and_selection else {
16168 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16169 };
16170
16171 let Some(project) = self.project.as_ref() else {
16172 return Task::ready(Err(anyhow!("editor does not have project")));
16173 };
16174
16175 project.update(cx, |project, cx| {
16176 project.get_permalink_to_line(&buffer, selection, cx)
16177 })
16178 }
16179
16180 pub fn copy_permalink_to_line(
16181 &mut self,
16182 _: &CopyPermalinkToLine,
16183 window: &mut Window,
16184 cx: &mut Context<Self>,
16185 ) {
16186 let permalink_task = self.get_permalink_to_line(cx);
16187 let workspace = self.workspace();
16188
16189 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16190 Ok(permalink) => {
16191 cx.update(|_, cx| {
16192 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16193 })
16194 .ok();
16195 }
16196 Err(err) => {
16197 let message = format!("Failed to copy permalink: {err}");
16198
16199 Err::<(), anyhow::Error>(err).log_err();
16200
16201 if let Some(workspace) = workspace {
16202 workspace
16203 .update_in(cx, |workspace, _, cx| {
16204 struct CopyPermalinkToLine;
16205
16206 workspace.show_toast(
16207 Toast::new(
16208 NotificationId::unique::<CopyPermalinkToLine>(),
16209 message,
16210 ),
16211 cx,
16212 )
16213 })
16214 .ok();
16215 }
16216 }
16217 })
16218 .detach();
16219 }
16220
16221 pub fn copy_file_location(
16222 &mut self,
16223 _: &CopyFileLocation,
16224 _: &mut Window,
16225 cx: &mut Context<Self>,
16226 ) {
16227 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16228 if let Some(file) = self.target_file(cx) {
16229 if let Some(path) = file.path().to_str() {
16230 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16231 }
16232 }
16233 }
16234
16235 pub fn open_permalink_to_line(
16236 &mut self,
16237 _: &OpenPermalinkToLine,
16238 window: &mut Window,
16239 cx: &mut Context<Self>,
16240 ) {
16241 let permalink_task = self.get_permalink_to_line(cx);
16242 let workspace = self.workspace();
16243
16244 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16245 Ok(permalink) => {
16246 cx.update(|_, cx| {
16247 cx.open_url(permalink.as_ref());
16248 })
16249 .ok();
16250 }
16251 Err(err) => {
16252 let message = format!("Failed to open permalink: {err}");
16253
16254 Err::<(), anyhow::Error>(err).log_err();
16255
16256 if let Some(workspace) = workspace {
16257 workspace
16258 .update(cx, |workspace, cx| {
16259 struct OpenPermalinkToLine;
16260
16261 workspace.show_toast(
16262 Toast::new(
16263 NotificationId::unique::<OpenPermalinkToLine>(),
16264 message,
16265 ),
16266 cx,
16267 )
16268 })
16269 .ok();
16270 }
16271 }
16272 })
16273 .detach();
16274 }
16275
16276 pub fn insert_uuid_v4(
16277 &mut self,
16278 _: &InsertUuidV4,
16279 window: &mut Window,
16280 cx: &mut Context<Self>,
16281 ) {
16282 self.insert_uuid(UuidVersion::V4, window, cx);
16283 }
16284
16285 pub fn insert_uuid_v7(
16286 &mut self,
16287 _: &InsertUuidV7,
16288 window: &mut Window,
16289 cx: &mut Context<Self>,
16290 ) {
16291 self.insert_uuid(UuidVersion::V7, window, cx);
16292 }
16293
16294 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16295 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16296 self.transact(window, cx, |this, window, cx| {
16297 let edits = this
16298 .selections
16299 .all::<Point>(cx)
16300 .into_iter()
16301 .map(|selection| {
16302 let uuid = match version {
16303 UuidVersion::V4 => uuid::Uuid::new_v4(),
16304 UuidVersion::V7 => uuid::Uuid::now_v7(),
16305 };
16306
16307 (selection.range(), uuid.to_string())
16308 });
16309 this.edit(edits, cx);
16310 this.refresh_inline_completion(true, false, window, cx);
16311 });
16312 }
16313
16314 pub fn open_selections_in_multibuffer(
16315 &mut self,
16316 _: &OpenSelectionsInMultibuffer,
16317 window: &mut Window,
16318 cx: &mut Context<Self>,
16319 ) {
16320 let multibuffer = self.buffer.read(cx);
16321
16322 let Some(buffer) = multibuffer.as_singleton() else {
16323 return;
16324 };
16325
16326 let Some(workspace) = self.workspace() else {
16327 return;
16328 };
16329
16330 let locations = self
16331 .selections
16332 .disjoint_anchors()
16333 .iter()
16334 .map(|range| Location {
16335 buffer: buffer.clone(),
16336 range: range.start.text_anchor..range.end.text_anchor,
16337 })
16338 .collect::<Vec<_>>();
16339
16340 let title = multibuffer.title(cx).to_string();
16341
16342 cx.spawn_in(window, async move |_, cx| {
16343 workspace.update_in(cx, |workspace, window, cx| {
16344 Self::open_locations_in_multibuffer(
16345 workspace,
16346 locations,
16347 format!("Selections for '{title}'"),
16348 false,
16349 MultibufferSelectionMode::All,
16350 window,
16351 cx,
16352 );
16353 })
16354 })
16355 .detach();
16356 }
16357
16358 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16359 /// last highlight added will be used.
16360 ///
16361 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16362 pub fn highlight_rows<T: 'static>(
16363 &mut self,
16364 range: Range<Anchor>,
16365 color: Hsla,
16366 should_autoscroll: bool,
16367 cx: &mut Context<Self>,
16368 ) {
16369 let snapshot = self.buffer().read(cx).snapshot(cx);
16370 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16371 let ix = row_highlights.binary_search_by(|highlight| {
16372 Ordering::Equal
16373 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16374 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16375 });
16376
16377 if let Err(mut ix) = ix {
16378 let index = post_inc(&mut self.highlight_order);
16379
16380 // If this range intersects with the preceding highlight, then merge it with
16381 // the preceding highlight. Otherwise insert a new highlight.
16382 let mut merged = false;
16383 if ix > 0 {
16384 let prev_highlight = &mut row_highlights[ix - 1];
16385 if prev_highlight
16386 .range
16387 .end
16388 .cmp(&range.start, &snapshot)
16389 .is_ge()
16390 {
16391 ix -= 1;
16392 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16393 prev_highlight.range.end = range.end;
16394 }
16395 merged = true;
16396 prev_highlight.index = index;
16397 prev_highlight.color = color;
16398 prev_highlight.should_autoscroll = should_autoscroll;
16399 }
16400 }
16401
16402 if !merged {
16403 row_highlights.insert(
16404 ix,
16405 RowHighlight {
16406 range: range.clone(),
16407 index,
16408 color,
16409 should_autoscroll,
16410 },
16411 );
16412 }
16413
16414 // If any of the following highlights intersect with this one, merge them.
16415 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16416 let highlight = &row_highlights[ix];
16417 if next_highlight
16418 .range
16419 .start
16420 .cmp(&highlight.range.end, &snapshot)
16421 .is_le()
16422 {
16423 if next_highlight
16424 .range
16425 .end
16426 .cmp(&highlight.range.end, &snapshot)
16427 .is_gt()
16428 {
16429 row_highlights[ix].range.end = next_highlight.range.end;
16430 }
16431 row_highlights.remove(ix + 1);
16432 } else {
16433 break;
16434 }
16435 }
16436 }
16437 }
16438
16439 /// Remove any highlighted row ranges of the given type that intersect the
16440 /// given ranges.
16441 pub fn remove_highlighted_rows<T: 'static>(
16442 &mut self,
16443 ranges_to_remove: Vec<Range<Anchor>>,
16444 cx: &mut Context<Self>,
16445 ) {
16446 let snapshot = self.buffer().read(cx).snapshot(cx);
16447 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16448 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16449 row_highlights.retain(|highlight| {
16450 while let Some(range_to_remove) = ranges_to_remove.peek() {
16451 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16452 Ordering::Less | Ordering::Equal => {
16453 ranges_to_remove.next();
16454 }
16455 Ordering::Greater => {
16456 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16457 Ordering::Less | Ordering::Equal => {
16458 return false;
16459 }
16460 Ordering::Greater => break,
16461 }
16462 }
16463 }
16464 }
16465
16466 true
16467 })
16468 }
16469
16470 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16471 pub fn clear_row_highlights<T: 'static>(&mut self) {
16472 self.highlighted_rows.remove(&TypeId::of::<T>());
16473 }
16474
16475 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16476 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16477 self.highlighted_rows
16478 .get(&TypeId::of::<T>())
16479 .map_or(&[] as &[_], |vec| vec.as_slice())
16480 .iter()
16481 .map(|highlight| (highlight.range.clone(), highlight.color))
16482 }
16483
16484 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16485 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16486 /// Allows to ignore certain kinds of highlights.
16487 pub fn highlighted_display_rows(
16488 &self,
16489 window: &mut Window,
16490 cx: &mut App,
16491 ) -> BTreeMap<DisplayRow, LineHighlight> {
16492 let snapshot = self.snapshot(window, cx);
16493 let mut used_highlight_orders = HashMap::default();
16494 self.highlighted_rows
16495 .iter()
16496 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16497 .fold(
16498 BTreeMap::<DisplayRow, LineHighlight>::new(),
16499 |mut unique_rows, highlight| {
16500 let start = highlight.range.start.to_display_point(&snapshot);
16501 let end = highlight.range.end.to_display_point(&snapshot);
16502 let start_row = start.row().0;
16503 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16504 && end.column() == 0
16505 {
16506 end.row().0.saturating_sub(1)
16507 } else {
16508 end.row().0
16509 };
16510 for row in start_row..=end_row {
16511 let used_index =
16512 used_highlight_orders.entry(row).or_insert(highlight.index);
16513 if highlight.index >= *used_index {
16514 *used_index = highlight.index;
16515 unique_rows.insert(DisplayRow(row), highlight.color.into());
16516 }
16517 }
16518 unique_rows
16519 },
16520 )
16521 }
16522
16523 pub fn highlighted_display_row_for_autoscroll(
16524 &self,
16525 snapshot: &DisplaySnapshot,
16526 ) -> Option<DisplayRow> {
16527 self.highlighted_rows
16528 .values()
16529 .flat_map(|highlighted_rows| highlighted_rows.iter())
16530 .filter_map(|highlight| {
16531 if highlight.should_autoscroll {
16532 Some(highlight.range.start.to_display_point(snapshot).row())
16533 } else {
16534 None
16535 }
16536 })
16537 .min()
16538 }
16539
16540 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16541 self.highlight_background::<SearchWithinRange>(
16542 ranges,
16543 |colors| colors.editor_document_highlight_read_background,
16544 cx,
16545 )
16546 }
16547
16548 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16549 self.breadcrumb_header = Some(new_header);
16550 }
16551
16552 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16553 self.clear_background_highlights::<SearchWithinRange>(cx);
16554 }
16555
16556 pub fn highlight_background<T: 'static>(
16557 &mut self,
16558 ranges: &[Range<Anchor>],
16559 color_fetcher: fn(&ThemeColors) -> Hsla,
16560 cx: &mut Context<Self>,
16561 ) {
16562 self.background_highlights
16563 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16564 self.scrollbar_marker_state.dirty = true;
16565 cx.notify();
16566 }
16567
16568 pub fn clear_background_highlights<T: 'static>(
16569 &mut self,
16570 cx: &mut Context<Self>,
16571 ) -> Option<BackgroundHighlight> {
16572 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16573 if !text_highlights.1.is_empty() {
16574 self.scrollbar_marker_state.dirty = true;
16575 cx.notify();
16576 }
16577 Some(text_highlights)
16578 }
16579
16580 pub fn highlight_gutter<T: 'static>(
16581 &mut self,
16582 ranges: &[Range<Anchor>],
16583 color_fetcher: fn(&App) -> Hsla,
16584 cx: &mut Context<Self>,
16585 ) {
16586 self.gutter_highlights
16587 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16588 cx.notify();
16589 }
16590
16591 pub fn clear_gutter_highlights<T: 'static>(
16592 &mut self,
16593 cx: &mut Context<Self>,
16594 ) -> Option<GutterHighlight> {
16595 cx.notify();
16596 self.gutter_highlights.remove(&TypeId::of::<T>())
16597 }
16598
16599 #[cfg(feature = "test-support")]
16600 pub fn all_text_background_highlights(
16601 &self,
16602 window: &mut Window,
16603 cx: &mut Context<Self>,
16604 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16605 let snapshot = self.snapshot(window, cx);
16606 let buffer = &snapshot.buffer_snapshot;
16607 let start = buffer.anchor_before(0);
16608 let end = buffer.anchor_after(buffer.len());
16609 let theme = cx.theme().colors();
16610 self.background_highlights_in_range(start..end, &snapshot, theme)
16611 }
16612
16613 #[cfg(feature = "test-support")]
16614 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16615 let snapshot = self.buffer().read(cx).snapshot(cx);
16616
16617 let highlights = self
16618 .background_highlights
16619 .get(&TypeId::of::<items::BufferSearchHighlights>());
16620
16621 if let Some((_color, ranges)) = highlights {
16622 ranges
16623 .iter()
16624 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16625 .collect_vec()
16626 } else {
16627 vec![]
16628 }
16629 }
16630
16631 fn document_highlights_for_position<'a>(
16632 &'a self,
16633 position: Anchor,
16634 buffer: &'a MultiBufferSnapshot,
16635 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16636 let read_highlights = self
16637 .background_highlights
16638 .get(&TypeId::of::<DocumentHighlightRead>())
16639 .map(|h| &h.1);
16640 let write_highlights = self
16641 .background_highlights
16642 .get(&TypeId::of::<DocumentHighlightWrite>())
16643 .map(|h| &h.1);
16644 let left_position = position.bias_left(buffer);
16645 let right_position = position.bias_right(buffer);
16646 read_highlights
16647 .into_iter()
16648 .chain(write_highlights)
16649 .flat_map(move |ranges| {
16650 let start_ix = match ranges.binary_search_by(|probe| {
16651 let cmp = probe.end.cmp(&left_position, buffer);
16652 if cmp.is_ge() {
16653 Ordering::Greater
16654 } else {
16655 Ordering::Less
16656 }
16657 }) {
16658 Ok(i) | Err(i) => i,
16659 };
16660
16661 ranges[start_ix..]
16662 .iter()
16663 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16664 })
16665 }
16666
16667 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16668 self.background_highlights
16669 .get(&TypeId::of::<T>())
16670 .map_or(false, |(_, highlights)| !highlights.is_empty())
16671 }
16672
16673 pub fn background_highlights_in_range(
16674 &self,
16675 search_range: Range<Anchor>,
16676 display_snapshot: &DisplaySnapshot,
16677 theme: &ThemeColors,
16678 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16679 let mut results = Vec::new();
16680 for (color_fetcher, ranges) in self.background_highlights.values() {
16681 let color = color_fetcher(theme);
16682 let start_ix = match ranges.binary_search_by(|probe| {
16683 let cmp = probe
16684 .end
16685 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16686 if cmp.is_gt() {
16687 Ordering::Greater
16688 } else {
16689 Ordering::Less
16690 }
16691 }) {
16692 Ok(i) | Err(i) => i,
16693 };
16694 for range in &ranges[start_ix..] {
16695 if range
16696 .start
16697 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16698 .is_ge()
16699 {
16700 break;
16701 }
16702
16703 let start = range.start.to_display_point(display_snapshot);
16704 let end = range.end.to_display_point(display_snapshot);
16705 results.push((start..end, color))
16706 }
16707 }
16708 results
16709 }
16710
16711 pub fn background_highlight_row_ranges<T: 'static>(
16712 &self,
16713 search_range: Range<Anchor>,
16714 display_snapshot: &DisplaySnapshot,
16715 count: usize,
16716 ) -> Vec<RangeInclusive<DisplayPoint>> {
16717 let mut results = Vec::new();
16718 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16719 return vec![];
16720 };
16721
16722 let start_ix = match ranges.binary_search_by(|probe| {
16723 let cmp = probe
16724 .end
16725 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16726 if cmp.is_gt() {
16727 Ordering::Greater
16728 } else {
16729 Ordering::Less
16730 }
16731 }) {
16732 Ok(i) | Err(i) => i,
16733 };
16734 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16735 if let (Some(start_display), Some(end_display)) = (start, end) {
16736 results.push(
16737 start_display.to_display_point(display_snapshot)
16738 ..=end_display.to_display_point(display_snapshot),
16739 );
16740 }
16741 };
16742 let mut start_row: Option<Point> = None;
16743 let mut end_row: Option<Point> = None;
16744 if ranges.len() > count {
16745 return Vec::new();
16746 }
16747 for range in &ranges[start_ix..] {
16748 if range
16749 .start
16750 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16751 .is_ge()
16752 {
16753 break;
16754 }
16755 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16756 if let Some(current_row) = &end_row {
16757 if end.row == current_row.row {
16758 continue;
16759 }
16760 }
16761 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16762 if start_row.is_none() {
16763 assert_eq!(end_row, None);
16764 start_row = Some(start);
16765 end_row = Some(end);
16766 continue;
16767 }
16768 if let Some(current_end) = end_row.as_mut() {
16769 if start.row > current_end.row + 1 {
16770 push_region(start_row, end_row);
16771 start_row = Some(start);
16772 end_row = Some(end);
16773 } else {
16774 // Merge two hunks.
16775 *current_end = end;
16776 }
16777 } else {
16778 unreachable!();
16779 }
16780 }
16781 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16782 push_region(start_row, end_row);
16783 results
16784 }
16785
16786 pub fn gutter_highlights_in_range(
16787 &self,
16788 search_range: Range<Anchor>,
16789 display_snapshot: &DisplaySnapshot,
16790 cx: &App,
16791 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16792 let mut results = Vec::new();
16793 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16794 let color = color_fetcher(cx);
16795 let start_ix = match ranges.binary_search_by(|probe| {
16796 let cmp = probe
16797 .end
16798 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16799 if cmp.is_gt() {
16800 Ordering::Greater
16801 } else {
16802 Ordering::Less
16803 }
16804 }) {
16805 Ok(i) | Err(i) => i,
16806 };
16807 for range in &ranges[start_ix..] {
16808 if range
16809 .start
16810 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16811 .is_ge()
16812 {
16813 break;
16814 }
16815
16816 let start = range.start.to_display_point(display_snapshot);
16817 let end = range.end.to_display_point(display_snapshot);
16818 results.push((start..end, color))
16819 }
16820 }
16821 results
16822 }
16823
16824 /// Get the text ranges corresponding to the redaction query
16825 pub fn redacted_ranges(
16826 &self,
16827 search_range: Range<Anchor>,
16828 display_snapshot: &DisplaySnapshot,
16829 cx: &App,
16830 ) -> Vec<Range<DisplayPoint>> {
16831 display_snapshot
16832 .buffer_snapshot
16833 .redacted_ranges(search_range, |file| {
16834 if let Some(file) = file {
16835 file.is_private()
16836 && EditorSettings::get(
16837 Some(SettingsLocation {
16838 worktree_id: file.worktree_id(cx),
16839 path: file.path().as_ref(),
16840 }),
16841 cx,
16842 )
16843 .redact_private_values
16844 } else {
16845 false
16846 }
16847 })
16848 .map(|range| {
16849 range.start.to_display_point(display_snapshot)
16850 ..range.end.to_display_point(display_snapshot)
16851 })
16852 .collect()
16853 }
16854
16855 pub fn highlight_text<T: 'static>(
16856 &mut self,
16857 ranges: Vec<Range<Anchor>>,
16858 style: HighlightStyle,
16859 cx: &mut Context<Self>,
16860 ) {
16861 self.display_map.update(cx, |map, _| {
16862 map.highlight_text(TypeId::of::<T>(), ranges, style)
16863 });
16864 cx.notify();
16865 }
16866
16867 pub(crate) fn highlight_inlays<T: 'static>(
16868 &mut self,
16869 highlights: Vec<InlayHighlight>,
16870 style: HighlightStyle,
16871 cx: &mut Context<Self>,
16872 ) {
16873 self.display_map.update(cx, |map, _| {
16874 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16875 });
16876 cx.notify();
16877 }
16878
16879 pub fn text_highlights<'a, T: 'static>(
16880 &'a self,
16881 cx: &'a App,
16882 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16883 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16884 }
16885
16886 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16887 let cleared = self
16888 .display_map
16889 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16890 if cleared {
16891 cx.notify();
16892 }
16893 }
16894
16895 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16896 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16897 && self.focus_handle.is_focused(window)
16898 }
16899
16900 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16901 self.show_cursor_when_unfocused = is_enabled;
16902 cx.notify();
16903 }
16904
16905 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16906 cx.notify();
16907 }
16908
16909 fn on_buffer_event(
16910 &mut self,
16911 multibuffer: &Entity<MultiBuffer>,
16912 event: &multi_buffer::Event,
16913 window: &mut Window,
16914 cx: &mut Context<Self>,
16915 ) {
16916 match event {
16917 multi_buffer::Event::Edited {
16918 singleton_buffer_edited,
16919 edited_buffer: buffer_edited,
16920 } => {
16921 self.scrollbar_marker_state.dirty = true;
16922 self.active_indent_guides_state.dirty = true;
16923 self.refresh_active_diagnostics(cx);
16924 self.refresh_code_actions(window, cx);
16925 if self.has_active_inline_completion() {
16926 self.update_visible_inline_completion(window, cx);
16927 }
16928 if let Some(buffer) = buffer_edited {
16929 let buffer_id = buffer.read(cx).remote_id();
16930 if !self.registered_buffers.contains_key(&buffer_id) {
16931 if let Some(project) = self.project.as_ref() {
16932 project.update(cx, |project, cx| {
16933 self.registered_buffers.insert(
16934 buffer_id,
16935 project.register_buffer_with_language_servers(&buffer, cx),
16936 );
16937 })
16938 }
16939 }
16940 }
16941 cx.emit(EditorEvent::BufferEdited);
16942 cx.emit(SearchEvent::MatchesInvalidated);
16943 if *singleton_buffer_edited {
16944 if let Some(project) = &self.project {
16945 #[allow(clippy::mutable_key_type)]
16946 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16947 multibuffer
16948 .all_buffers()
16949 .into_iter()
16950 .filter_map(|buffer| {
16951 buffer.update(cx, |buffer, cx| {
16952 let language = buffer.language()?;
16953 let should_discard = project.update(cx, |project, cx| {
16954 project.is_local()
16955 && !project.has_language_servers_for(buffer, cx)
16956 });
16957 should_discard.not().then_some(language.clone())
16958 })
16959 })
16960 .collect::<HashSet<_>>()
16961 });
16962 if !languages_affected.is_empty() {
16963 self.refresh_inlay_hints(
16964 InlayHintRefreshReason::BufferEdited(languages_affected),
16965 cx,
16966 );
16967 }
16968 }
16969 }
16970
16971 let Some(project) = &self.project else { return };
16972 let (telemetry, is_via_ssh) = {
16973 let project = project.read(cx);
16974 let telemetry = project.client().telemetry().clone();
16975 let is_via_ssh = project.is_via_ssh();
16976 (telemetry, is_via_ssh)
16977 };
16978 refresh_linked_ranges(self, window, cx);
16979 telemetry.log_edit_event("editor", is_via_ssh);
16980 }
16981 multi_buffer::Event::ExcerptsAdded {
16982 buffer,
16983 predecessor,
16984 excerpts,
16985 } => {
16986 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16987 let buffer_id = buffer.read(cx).remote_id();
16988 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16989 if let Some(project) = &self.project {
16990 get_uncommitted_diff_for_buffer(
16991 project,
16992 [buffer.clone()],
16993 self.buffer.clone(),
16994 cx,
16995 )
16996 .detach();
16997 }
16998 }
16999 cx.emit(EditorEvent::ExcerptsAdded {
17000 buffer: buffer.clone(),
17001 predecessor: *predecessor,
17002 excerpts: excerpts.clone(),
17003 });
17004 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17005 }
17006 multi_buffer::Event::ExcerptsRemoved { ids } => {
17007 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17008 let buffer = self.buffer.read(cx);
17009 self.registered_buffers
17010 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17011 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17012 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17013 }
17014 multi_buffer::Event::ExcerptsEdited {
17015 excerpt_ids,
17016 buffer_ids,
17017 } => {
17018 self.display_map.update(cx, |map, cx| {
17019 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17020 });
17021 cx.emit(EditorEvent::ExcerptsEdited {
17022 ids: excerpt_ids.clone(),
17023 })
17024 }
17025 multi_buffer::Event::ExcerptsExpanded { ids } => {
17026 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17027 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17028 }
17029 multi_buffer::Event::Reparsed(buffer_id) => {
17030 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17031 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17032
17033 cx.emit(EditorEvent::Reparsed(*buffer_id));
17034 }
17035 multi_buffer::Event::DiffHunksToggled => {
17036 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17037 }
17038 multi_buffer::Event::LanguageChanged(buffer_id) => {
17039 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17040 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17041 cx.emit(EditorEvent::Reparsed(*buffer_id));
17042 cx.notify();
17043 }
17044 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17045 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17046 multi_buffer::Event::FileHandleChanged
17047 | multi_buffer::Event::Reloaded
17048 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17049 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17050 multi_buffer::Event::DiagnosticsUpdated => {
17051 self.refresh_active_diagnostics(cx);
17052 self.refresh_inline_diagnostics(true, window, cx);
17053 self.scrollbar_marker_state.dirty = true;
17054 cx.notify();
17055 }
17056 _ => {}
17057 };
17058 }
17059
17060 fn on_display_map_changed(
17061 &mut self,
17062 _: Entity<DisplayMap>,
17063 _: &mut Window,
17064 cx: &mut Context<Self>,
17065 ) {
17066 cx.notify();
17067 }
17068
17069 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17070 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17071 self.update_edit_prediction_settings(cx);
17072 self.refresh_inline_completion(true, false, window, cx);
17073 self.refresh_inlay_hints(
17074 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17075 self.selections.newest_anchor().head(),
17076 &self.buffer.read(cx).snapshot(cx),
17077 cx,
17078 )),
17079 cx,
17080 );
17081
17082 let old_cursor_shape = self.cursor_shape;
17083
17084 {
17085 let editor_settings = EditorSettings::get_global(cx);
17086 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17087 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17088 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17089 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17090 }
17091
17092 if old_cursor_shape != self.cursor_shape {
17093 cx.emit(EditorEvent::CursorShapeChanged);
17094 }
17095
17096 let project_settings = ProjectSettings::get_global(cx);
17097 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17098
17099 if self.mode == EditorMode::Full {
17100 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17101 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17102 if self.show_inline_diagnostics != show_inline_diagnostics {
17103 self.show_inline_diagnostics = show_inline_diagnostics;
17104 self.refresh_inline_diagnostics(false, window, cx);
17105 }
17106
17107 if self.git_blame_inline_enabled != inline_blame_enabled {
17108 self.toggle_git_blame_inline_internal(false, window, cx);
17109 }
17110 }
17111
17112 cx.notify();
17113 }
17114
17115 pub fn set_searchable(&mut self, searchable: bool) {
17116 self.searchable = searchable;
17117 }
17118
17119 pub fn searchable(&self) -> bool {
17120 self.searchable
17121 }
17122
17123 fn open_proposed_changes_editor(
17124 &mut self,
17125 _: &OpenProposedChangesEditor,
17126 window: &mut Window,
17127 cx: &mut Context<Self>,
17128 ) {
17129 let Some(workspace) = self.workspace() else {
17130 cx.propagate();
17131 return;
17132 };
17133
17134 let selections = self.selections.all::<usize>(cx);
17135 let multi_buffer = self.buffer.read(cx);
17136 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17137 let mut new_selections_by_buffer = HashMap::default();
17138 for selection in selections {
17139 for (buffer, range, _) in
17140 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17141 {
17142 let mut range = range.to_point(buffer);
17143 range.start.column = 0;
17144 range.end.column = buffer.line_len(range.end.row);
17145 new_selections_by_buffer
17146 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17147 .or_insert(Vec::new())
17148 .push(range)
17149 }
17150 }
17151
17152 let proposed_changes_buffers = new_selections_by_buffer
17153 .into_iter()
17154 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17155 .collect::<Vec<_>>();
17156 let proposed_changes_editor = cx.new(|cx| {
17157 ProposedChangesEditor::new(
17158 "Proposed changes",
17159 proposed_changes_buffers,
17160 self.project.clone(),
17161 window,
17162 cx,
17163 )
17164 });
17165
17166 window.defer(cx, move |window, cx| {
17167 workspace.update(cx, |workspace, cx| {
17168 workspace.active_pane().update(cx, |pane, cx| {
17169 pane.add_item(
17170 Box::new(proposed_changes_editor),
17171 true,
17172 true,
17173 None,
17174 window,
17175 cx,
17176 );
17177 });
17178 });
17179 });
17180 }
17181
17182 pub fn open_excerpts_in_split(
17183 &mut self,
17184 _: &OpenExcerptsSplit,
17185 window: &mut Window,
17186 cx: &mut Context<Self>,
17187 ) {
17188 self.open_excerpts_common(None, true, window, cx)
17189 }
17190
17191 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17192 self.open_excerpts_common(None, false, window, cx)
17193 }
17194
17195 fn open_excerpts_common(
17196 &mut self,
17197 jump_data: Option<JumpData>,
17198 split: bool,
17199 window: &mut Window,
17200 cx: &mut Context<Self>,
17201 ) {
17202 let Some(workspace) = self.workspace() else {
17203 cx.propagate();
17204 return;
17205 };
17206
17207 if self.buffer.read(cx).is_singleton() {
17208 cx.propagate();
17209 return;
17210 }
17211
17212 let mut new_selections_by_buffer = HashMap::default();
17213 match &jump_data {
17214 Some(JumpData::MultiBufferPoint {
17215 excerpt_id,
17216 position,
17217 anchor,
17218 line_offset_from_top,
17219 }) => {
17220 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17221 if let Some(buffer) = multi_buffer_snapshot
17222 .buffer_id_for_excerpt(*excerpt_id)
17223 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17224 {
17225 let buffer_snapshot = buffer.read(cx).snapshot();
17226 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17227 language::ToPoint::to_point(anchor, &buffer_snapshot)
17228 } else {
17229 buffer_snapshot.clip_point(*position, Bias::Left)
17230 };
17231 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17232 new_selections_by_buffer.insert(
17233 buffer,
17234 (
17235 vec![jump_to_offset..jump_to_offset],
17236 Some(*line_offset_from_top),
17237 ),
17238 );
17239 }
17240 }
17241 Some(JumpData::MultiBufferRow {
17242 row,
17243 line_offset_from_top,
17244 }) => {
17245 let point = MultiBufferPoint::new(row.0, 0);
17246 if let Some((buffer, buffer_point, _)) =
17247 self.buffer.read(cx).point_to_buffer_point(point, cx)
17248 {
17249 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17250 new_selections_by_buffer
17251 .entry(buffer)
17252 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17253 .0
17254 .push(buffer_offset..buffer_offset)
17255 }
17256 }
17257 None => {
17258 let selections = self.selections.all::<usize>(cx);
17259 let multi_buffer = self.buffer.read(cx);
17260 for selection in selections {
17261 for (snapshot, range, _, anchor) in multi_buffer
17262 .snapshot(cx)
17263 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17264 {
17265 if let Some(anchor) = anchor {
17266 // selection is in a deleted hunk
17267 let Some(buffer_id) = anchor.buffer_id else {
17268 continue;
17269 };
17270 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17271 continue;
17272 };
17273 let offset = text::ToOffset::to_offset(
17274 &anchor.text_anchor,
17275 &buffer_handle.read(cx).snapshot(),
17276 );
17277 let range = offset..offset;
17278 new_selections_by_buffer
17279 .entry(buffer_handle)
17280 .or_insert((Vec::new(), None))
17281 .0
17282 .push(range)
17283 } else {
17284 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17285 else {
17286 continue;
17287 };
17288 new_selections_by_buffer
17289 .entry(buffer_handle)
17290 .or_insert((Vec::new(), None))
17291 .0
17292 .push(range)
17293 }
17294 }
17295 }
17296 }
17297 }
17298
17299 new_selections_by_buffer
17300 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17301
17302 if new_selections_by_buffer.is_empty() {
17303 return;
17304 }
17305
17306 // We defer the pane interaction because we ourselves are a workspace item
17307 // and activating a new item causes the pane to call a method on us reentrantly,
17308 // which panics if we're on the stack.
17309 window.defer(cx, move |window, cx| {
17310 workspace.update(cx, |workspace, cx| {
17311 let pane = if split {
17312 workspace.adjacent_pane(window, cx)
17313 } else {
17314 workspace.active_pane().clone()
17315 };
17316
17317 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17318 let editor = buffer
17319 .read(cx)
17320 .file()
17321 .is_none()
17322 .then(|| {
17323 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17324 // so `workspace.open_project_item` will never find them, always opening a new editor.
17325 // Instead, we try to activate the existing editor in the pane first.
17326 let (editor, pane_item_index) =
17327 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17328 let editor = item.downcast::<Editor>()?;
17329 let singleton_buffer =
17330 editor.read(cx).buffer().read(cx).as_singleton()?;
17331 if singleton_buffer == buffer {
17332 Some((editor, i))
17333 } else {
17334 None
17335 }
17336 })?;
17337 pane.update(cx, |pane, cx| {
17338 pane.activate_item(pane_item_index, true, true, window, cx)
17339 });
17340 Some(editor)
17341 })
17342 .flatten()
17343 .unwrap_or_else(|| {
17344 workspace.open_project_item::<Self>(
17345 pane.clone(),
17346 buffer,
17347 true,
17348 true,
17349 window,
17350 cx,
17351 )
17352 });
17353
17354 editor.update(cx, |editor, cx| {
17355 let autoscroll = match scroll_offset {
17356 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17357 None => Autoscroll::newest(),
17358 };
17359 let nav_history = editor.nav_history.take();
17360 editor.change_selections(Some(autoscroll), window, cx, |s| {
17361 s.select_ranges(ranges);
17362 });
17363 editor.nav_history = nav_history;
17364 });
17365 }
17366 })
17367 });
17368 }
17369
17370 // For now, don't allow opening excerpts in buffers that aren't backed by
17371 // regular project files.
17372 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17373 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17374 }
17375
17376 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17377 let snapshot = self.buffer.read(cx).read(cx);
17378 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17379 Some(
17380 ranges
17381 .iter()
17382 .map(move |range| {
17383 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17384 })
17385 .collect(),
17386 )
17387 }
17388
17389 fn selection_replacement_ranges(
17390 &self,
17391 range: Range<OffsetUtf16>,
17392 cx: &mut App,
17393 ) -> Vec<Range<OffsetUtf16>> {
17394 let selections = self.selections.all::<OffsetUtf16>(cx);
17395 let newest_selection = selections
17396 .iter()
17397 .max_by_key(|selection| selection.id)
17398 .unwrap();
17399 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17400 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17401 let snapshot = self.buffer.read(cx).read(cx);
17402 selections
17403 .into_iter()
17404 .map(|mut selection| {
17405 selection.start.0 =
17406 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17407 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17408 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17409 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17410 })
17411 .collect()
17412 }
17413
17414 fn report_editor_event(
17415 &self,
17416 event_type: &'static str,
17417 file_extension: Option<String>,
17418 cx: &App,
17419 ) {
17420 if cfg!(any(test, feature = "test-support")) {
17421 return;
17422 }
17423
17424 let Some(project) = &self.project else { return };
17425
17426 // If None, we are in a file without an extension
17427 let file = self
17428 .buffer
17429 .read(cx)
17430 .as_singleton()
17431 .and_then(|b| b.read(cx).file());
17432 let file_extension = file_extension.or(file
17433 .as_ref()
17434 .and_then(|file| Path::new(file.file_name(cx)).extension())
17435 .and_then(|e| e.to_str())
17436 .map(|a| a.to_string()));
17437
17438 let vim_mode = cx
17439 .global::<SettingsStore>()
17440 .raw_user_settings()
17441 .get("vim_mode")
17442 == Some(&serde_json::Value::Bool(true));
17443
17444 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17445 let copilot_enabled = edit_predictions_provider
17446 == language::language_settings::EditPredictionProvider::Copilot;
17447 let copilot_enabled_for_language = self
17448 .buffer
17449 .read(cx)
17450 .language_settings(cx)
17451 .show_edit_predictions;
17452
17453 let project = project.read(cx);
17454 telemetry::event!(
17455 event_type,
17456 file_extension,
17457 vim_mode,
17458 copilot_enabled,
17459 copilot_enabled_for_language,
17460 edit_predictions_provider,
17461 is_via_ssh = project.is_via_ssh(),
17462 );
17463 }
17464
17465 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17466 /// with each line being an array of {text, highlight} objects.
17467 fn copy_highlight_json(
17468 &mut self,
17469 _: &CopyHighlightJson,
17470 window: &mut Window,
17471 cx: &mut Context<Self>,
17472 ) {
17473 #[derive(Serialize)]
17474 struct Chunk<'a> {
17475 text: String,
17476 highlight: Option<&'a str>,
17477 }
17478
17479 let snapshot = self.buffer.read(cx).snapshot(cx);
17480 let range = self
17481 .selected_text_range(false, window, cx)
17482 .and_then(|selection| {
17483 if selection.range.is_empty() {
17484 None
17485 } else {
17486 Some(selection.range)
17487 }
17488 })
17489 .unwrap_or_else(|| 0..snapshot.len());
17490
17491 let chunks = snapshot.chunks(range, true);
17492 let mut lines = Vec::new();
17493 let mut line: VecDeque<Chunk> = VecDeque::new();
17494
17495 let Some(style) = self.style.as_ref() else {
17496 return;
17497 };
17498
17499 for chunk in chunks {
17500 let highlight = chunk
17501 .syntax_highlight_id
17502 .and_then(|id| id.name(&style.syntax));
17503 let mut chunk_lines = chunk.text.split('\n').peekable();
17504 while let Some(text) = chunk_lines.next() {
17505 let mut merged_with_last_token = false;
17506 if let Some(last_token) = line.back_mut() {
17507 if last_token.highlight == highlight {
17508 last_token.text.push_str(text);
17509 merged_with_last_token = true;
17510 }
17511 }
17512
17513 if !merged_with_last_token {
17514 line.push_back(Chunk {
17515 text: text.into(),
17516 highlight,
17517 });
17518 }
17519
17520 if chunk_lines.peek().is_some() {
17521 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17522 line.pop_front();
17523 }
17524 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17525 line.pop_back();
17526 }
17527
17528 lines.push(mem::take(&mut line));
17529 }
17530 }
17531 }
17532
17533 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17534 return;
17535 };
17536 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17537 }
17538
17539 pub fn open_context_menu(
17540 &mut self,
17541 _: &OpenContextMenu,
17542 window: &mut Window,
17543 cx: &mut Context<Self>,
17544 ) {
17545 self.request_autoscroll(Autoscroll::newest(), cx);
17546 let position = self.selections.newest_display(cx).start;
17547 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17548 }
17549
17550 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17551 &self.inlay_hint_cache
17552 }
17553
17554 pub fn replay_insert_event(
17555 &mut self,
17556 text: &str,
17557 relative_utf16_range: Option<Range<isize>>,
17558 window: &mut Window,
17559 cx: &mut Context<Self>,
17560 ) {
17561 if !self.input_enabled {
17562 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17563 return;
17564 }
17565 if let Some(relative_utf16_range) = relative_utf16_range {
17566 let selections = self.selections.all::<OffsetUtf16>(cx);
17567 self.change_selections(None, window, cx, |s| {
17568 let new_ranges = selections.into_iter().map(|range| {
17569 let start = OffsetUtf16(
17570 range
17571 .head()
17572 .0
17573 .saturating_add_signed(relative_utf16_range.start),
17574 );
17575 let end = OffsetUtf16(
17576 range
17577 .head()
17578 .0
17579 .saturating_add_signed(relative_utf16_range.end),
17580 );
17581 start..end
17582 });
17583 s.select_ranges(new_ranges);
17584 });
17585 }
17586
17587 self.handle_input(text, window, cx);
17588 }
17589
17590 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17591 let Some(provider) = self.semantics_provider.as_ref() else {
17592 return false;
17593 };
17594
17595 let mut supports = false;
17596 self.buffer().update(cx, |this, cx| {
17597 this.for_each_buffer(|buffer| {
17598 supports |= provider.supports_inlay_hints(buffer, cx);
17599 });
17600 });
17601
17602 supports
17603 }
17604
17605 pub fn is_focused(&self, window: &Window) -> bool {
17606 self.focus_handle.is_focused(window)
17607 }
17608
17609 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17610 cx.emit(EditorEvent::Focused);
17611
17612 if let Some(descendant) = self
17613 .last_focused_descendant
17614 .take()
17615 .and_then(|descendant| descendant.upgrade())
17616 {
17617 window.focus(&descendant);
17618 } else {
17619 if let Some(blame) = self.blame.as_ref() {
17620 blame.update(cx, GitBlame::focus)
17621 }
17622
17623 self.blink_manager.update(cx, BlinkManager::enable);
17624 self.show_cursor_names(window, cx);
17625 self.buffer.update(cx, |buffer, cx| {
17626 buffer.finalize_last_transaction(cx);
17627 if self.leader_peer_id.is_none() {
17628 buffer.set_active_selections(
17629 &self.selections.disjoint_anchors(),
17630 self.selections.line_mode,
17631 self.cursor_shape,
17632 cx,
17633 );
17634 }
17635 });
17636 }
17637 }
17638
17639 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17640 cx.emit(EditorEvent::FocusedIn)
17641 }
17642
17643 fn handle_focus_out(
17644 &mut self,
17645 event: FocusOutEvent,
17646 _window: &mut Window,
17647 cx: &mut Context<Self>,
17648 ) {
17649 if event.blurred != self.focus_handle {
17650 self.last_focused_descendant = Some(event.blurred);
17651 }
17652 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17653 }
17654
17655 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17656 self.blink_manager.update(cx, BlinkManager::disable);
17657 self.buffer
17658 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17659
17660 if let Some(blame) = self.blame.as_ref() {
17661 blame.update(cx, GitBlame::blur)
17662 }
17663 if !self.hover_state.focused(window, cx) {
17664 hide_hover(self, cx);
17665 }
17666 if !self
17667 .context_menu
17668 .borrow()
17669 .as_ref()
17670 .is_some_and(|context_menu| context_menu.focused(window, cx))
17671 {
17672 self.hide_context_menu(window, cx);
17673 }
17674 self.discard_inline_completion(false, cx);
17675 cx.emit(EditorEvent::Blurred);
17676 cx.notify();
17677 }
17678
17679 pub fn register_action<A: Action>(
17680 &mut self,
17681 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17682 ) -> Subscription {
17683 let id = self.next_editor_action_id.post_inc();
17684 let listener = Arc::new(listener);
17685 self.editor_actions.borrow_mut().insert(
17686 id,
17687 Box::new(move |window, _| {
17688 let listener = listener.clone();
17689 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17690 let action = action.downcast_ref().unwrap();
17691 if phase == DispatchPhase::Bubble {
17692 listener(action, window, cx)
17693 }
17694 })
17695 }),
17696 );
17697
17698 let editor_actions = self.editor_actions.clone();
17699 Subscription::new(move || {
17700 editor_actions.borrow_mut().remove(&id);
17701 })
17702 }
17703
17704 pub fn file_header_size(&self) -> u32 {
17705 FILE_HEADER_HEIGHT
17706 }
17707
17708 pub fn restore(
17709 &mut self,
17710 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17711 window: &mut Window,
17712 cx: &mut Context<Self>,
17713 ) {
17714 let workspace = self.workspace();
17715 let project = self.project.as_ref();
17716 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17717 let mut tasks = Vec::new();
17718 for (buffer_id, changes) in revert_changes {
17719 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17720 buffer.update(cx, |buffer, cx| {
17721 buffer.edit(
17722 changes
17723 .into_iter()
17724 .map(|(range, text)| (range, text.to_string())),
17725 None,
17726 cx,
17727 );
17728 });
17729
17730 if let Some(project) =
17731 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17732 {
17733 project.update(cx, |project, cx| {
17734 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17735 })
17736 }
17737 }
17738 }
17739 tasks
17740 });
17741 cx.spawn_in(window, async move |_, cx| {
17742 for (buffer, task) in save_tasks {
17743 let result = task.await;
17744 if result.is_err() {
17745 let Some(path) = buffer
17746 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17747 .ok()
17748 else {
17749 continue;
17750 };
17751 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17752 let Some(task) = cx
17753 .update_window_entity(&workspace, |workspace, window, cx| {
17754 workspace
17755 .open_path_preview(path, None, false, false, false, window, cx)
17756 })
17757 .ok()
17758 else {
17759 continue;
17760 };
17761 task.await.log_err();
17762 }
17763 }
17764 }
17765 })
17766 .detach();
17767 self.change_selections(None, window, cx, |selections| selections.refresh());
17768 }
17769
17770 pub fn to_pixel_point(
17771 &self,
17772 source: multi_buffer::Anchor,
17773 editor_snapshot: &EditorSnapshot,
17774 window: &mut Window,
17775 ) -> Option<gpui::Point<Pixels>> {
17776 let source_point = source.to_display_point(editor_snapshot);
17777 self.display_to_pixel_point(source_point, editor_snapshot, window)
17778 }
17779
17780 pub fn display_to_pixel_point(
17781 &self,
17782 source: DisplayPoint,
17783 editor_snapshot: &EditorSnapshot,
17784 window: &mut Window,
17785 ) -> Option<gpui::Point<Pixels>> {
17786 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17787 let text_layout_details = self.text_layout_details(window);
17788 let scroll_top = text_layout_details
17789 .scroll_anchor
17790 .scroll_position(editor_snapshot)
17791 .y;
17792
17793 if source.row().as_f32() < scroll_top.floor() {
17794 return None;
17795 }
17796 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17797 let source_y = line_height * (source.row().as_f32() - scroll_top);
17798 Some(gpui::Point::new(source_x, source_y))
17799 }
17800
17801 pub fn has_visible_completions_menu(&self) -> bool {
17802 !self.edit_prediction_preview_is_active()
17803 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17804 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17805 })
17806 }
17807
17808 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17809 self.addons
17810 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17811 }
17812
17813 pub fn unregister_addon<T: Addon>(&mut self) {
17814 self.addons.remove(&std::any::TypeId::of::<T>());
17815 }
17816
17817 pub fn addon<T: Addon>(&self) -> Option<&T> {
17818 let type_id = std::any::TypeId::of::<T>();
17819 self.addons
17820 .get(&type_id)
17821 .and_then(|item| item.to_any().downcast_ref::<T>())
17822 }
17823
17824 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17825 let text_layout_details = self.text_layout_details(window);
17826 let style = &text_layout_details.editor_style;
17827 let font_id = window.text_system().resolve_font(&style.text.font());
17828 let font_size = style.text.font_size.to_pixels(window.rem_size());
17829 let line_height = style.text.line_height_in_pixels(window.rem_size());
17830 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17831
17832 gpui::Size::new(em_width, line_height)
17833 }
17834
17835 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17836 self.load_diff_task.clone()
17837 }
17838
17839 fn read_metadata_from_db(
17840 &mut self,
17841 item_id: u64,
17842 workspace_id: WorkspaceId,
17843 window: &mut Window,
17844 cx: &mut Context<Editor>,
17845 ) {
17846 if self.is_singleton(cx)
17847 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17848 {
17849 let buffer_snapshot = OnceCell::new();
17850
17851 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17852 if !folds.is_empty() {
17853 let snapshot =
17854 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17855 self.fold_ranges(
17856 folds
17857 .into_iter()
17858 .map(|(start, end)| {
17859 snapshot.clip_offset(start, Bias::Left)
17860 ..snapshot.clip_offset(end, Bias::Right)
17861 })
17862 .collect(),
17863 false,
17864 window,
17865 cx,
17866 );
17867 }
17868 }
17869
17870 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17871 if !selections.is_empty() {
17872 let snapshot =
17873 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17874 self.change_selections(None, window, cx, |s| {
17875 s.select_ranges(selections.into_iter().map(|(start, end)| {
17876 snapshot.clip_offset(start, Bias::Left)
17877 ..snapshot.clip_offset(end, Bias::Right)
17878 }));
17879 });
17880 }
17881 };
17882 }
17883
17884 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17885 }
17886}
17887
17888fn insert_extra_newline_brackets(
17889 buffer: &MultiBufferSnapshot,
17890 range: Range<usize>,
17891 language: &language::LanguageScope,
17892) -> bool {
17893 let leading_whitespace_len = buffer
17894 .reversed_chars_at(range.start)
17895 .take_while(|c| c.is_whitespace() && *c != '\n')
17896 .map(|c| c.len_utf8())
17897 .sum::<usize>();
17898 let trailing_whitespace_len = buffer
17899 .chars_at(range.end)
17900 .take_while(|c| c.is_whitespace() && *c != '\n')
17901 .map(|c| c.len_utf8())
17902 .sum::<usize>();
17903 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17904
17905 language.brackets().any(|(pair, enabled)| {
17906 let pair_start = pair.start.trim_end();
17907 let pair_end = pair.end.trim_start();
17908
17909 enabled
17910 && pair.newline
17911 && buffer.contains_str_at(range.end, pair_end)
17912 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17913 })
17914}
17915
17916fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17917 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17918 [(buffer, range, _)] => (*buffer, range.clone()),
17919 _ => return false,
17920 };
17921 let pair = {
17922 let mut result: Option<BracketMatch> = None;
17923
17924 for pair in buffer
17925 .all_bracket_ranges(range.clone())
17926 .filter(move |pair| {
17927 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17928 })
17929 {
17930 let len = pair.close_range.end - pair.open_range.start;
17931
17932 if let Some(existing) = &result {
17933 let existing_len = existing.close_range.end - existing.open_range.start;
17934 if len > existing_len {
17935 continue;
17936 }
17937 }
17938
17939 result = Some(pair);
17940 }
17941
17942 result
17943 };
17944 let Some(pair) = pair else {
17945 return false;
17946 };
17947 pair.newline_only
17948 && buffer
17949 .chars_for_range(pair.open_range.end..range.start)
17950 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17951 .all(|c| c.is_whitespace() && c != '\n')
17952}
17953
17954fn get_uncommitted_diff_for_buffer(
17955 project: &Entity<Project>,
17956 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17957 buffer: Entity<MultiBuffer>,
17958 cx: &mut App,
17959) -> Task<()> {
17960 let mut tasks = Vec::new();
17961 project.update(cx, |project, cx| {
17962 for buffer in buffers {
17963 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
17964 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17965 }
17966 }
17967 });
17968 cx.spawn(async move |cx| {
17969 let diffs = future::join_all(tasks).await;
17970 buffer
17971 .update(cx, |buffer, cx| {
17972 for diff in diffs.into_iter().flatten() {
17973 buffer.add_diff(diff, cx);
17974 }
17975 })
17976 .ok();
17977 })
17978}
17979
17980fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17981 let tab_size = tab_size.get() as usize;
17982 let mut width = offset;
17983
17984 for ch in text.chars() {
17985 width += if ch == '\t' {
17986 tab_size - (width % tab_size)
17987 } else {
17988 1
17989 };
17990 }
17991
17992 width - offset
17993}
17994
17995#[cfg(test)]
17996mod tests {
17997 use super::*;
17998
17999 #[test]
18000 fn test_string_size_with_expanded_tabs() {
18001 let nz = |val| NonZeroU32::new(val).unwrap();
18002 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18003 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18004 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18005 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18006 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18007 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18008 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18009 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18010 }
18011}
18012
18013/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18014struct WordBreakingTokenizer<'a> {
18015 input: &'a str,
18016}
18017
18018impl<'a> WordBreakingTokenizer<'a> {
18019 fn new(input: &'a str) -> Self {
18020 Self { input }
18021 }
18022}
18023
18024fn is_char_ideographic(ch: char) -> bool {
18025 use unicode_script::Script::*;
18026 use unicode_script::UnicodeScript;
18027 matches!(ch.script(), Han | Tangut | Yi)
18028}
18029
18030fn is_grapheme_ideographic(text: &str) -> bool {
18031 text.chars().any(is_char_ideographic)
18032}
18033
18034fn is_grapheme_whitespace(text: &str) -> bool {
18035 text.chars().any(|x| x.is_whitespace())
18036}
18037
18038fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18039 text.chars().next().map_or(false, |ch| {
18040 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18041 })
18042}
18043
18044#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18045enum WordBreakToken<'a> {
18046 Word { token: &'a str, grapheme_len: usize },
18047 InlineWhitespace { token: &'a str, grapheme_len: usize },
18048 Newline,
18049}
18050
18051impl<'a> Iterator for WordBreakingTokenizer<'a> {
18052 /// Yields a span, the count of graphemes in the token, and whether it was
18053 /// whitespace. Note that it also breaks at word boundaries.
18054 type Item = WordBreakToken<'a>;
18055
18056 fn next(&mut self) -> Option<Self::Item> {
18057 use unicode_segmentation::UnicodeSegmentation;
18058 if self.input.is_empty() {
18059 return None;
18060 }
18061
18062 let mut iter = self.input.graphemes(true).peekable();
18063 let mut offset = 0;
18064 let mut grapheme_len = 0;
18065 if let Some(first_grapheme) = iter.next() {
18066 let is_newline = first_grapheme == "\n";
18067 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18068 offset += first_grapheme.len();
18069 grapheme_len += 1;
18070 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18071 if let Some(grapheme) = iter.peek().copied() {
18072 if should_stay_with_preceding_ideograph(grapheme) {
18073 offset += grapheme.len();
18074 grapheme_len += 1;
18075 }
18076 }
18077 } else {
18078 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18079 let mut next_word_bound = words.peek().copied();
18080 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18081 next_word_bound = words.next();
18082 }
18083 while let Some(grapheme) = iter.peek().copied() {
18084 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18085 break;
18086 };
18087 if is_grapheme_whitespace(grapheme) != is_whitespace
18088 || (grapheme == "\n") != is_newline
18089 {
18090 break;
18091 };
18092 offset += grapheme.len();
18093 grapheme_len += 1;
18094 iter.next();
18095 }
18096 }
18097 let token = &self.input[..offset];
18098 self.input = &self.input[offset..];
18099 if token == "\n" {
18100 Some(WordBreakToken::Newline)
18101 } else if is_whitespace {
18102 Some(WordBreakToken::InlineWhitespace {
18103 token,
18104 grapheme_len,
18105 })
18106 } else {
18107 Some(WordBreakToken::Word {
18108 token,
18109 grapheme_len,
18110 })
18111 }
18112 } else {
18113 None
18114 }
18115 }
18116}
18117
18118#[test]
18119fn test_word_breaking_tokenizer() {
18120 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18121 ("", &[]),
18122 (" ", &[whitespace(" ", 2)]),
18123 ("Ʒ", &[word("Ʒ", 1)]),
18124 ("Ǽ", &[word("Ǽ", 1)]),
18125 ("⋑", &[word("⋑", 1)]),
18126 ("⋑⋑", &[word("⋑⋑", 2)]),
18127 (
18128 "原理,进而",
18129 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18130 ),
18131 (
18132 "hello world",
18133 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18134 ),
18135 (
18136 "hello, world",
18137 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18138 ),
18139 (
18140 " hello world",
18141 &[
18142 whitespace(" ", 2),
18143 word("hello", 5),
18144 whitespace(" ", 1),
18145 word("world", 5),
18146 ],
18147 ),
18148 (
18149 "这是什么 \n 钢笔",
18150 &[
18151 word("这", 1),
18152 word("是", 1),
18153 word("什", 1),
18154 word("么", 1),
18155 whitespace(" ", 1),
18156 newline(),
18157 whitespace(" ", 1),
18158 word("钢", 1),
18159 word("笔", 1),
18160 ],
18161 ),
18162 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18163 ];
18164
18165 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18166 WordBreakToken::Word {
18167 token,
18168 grapheme_len,
18169 }
18170 }
18171
18172 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18173 WordBreakToken::InlineWhitespace {
18174 token,
18175 grapheme_len,
18176 }
18177 }
18178
18179 fn newline() -> WordBreakToken<'static> {
18180 WordBreakToken::Newline
18181 }
18182
18183 for (input, result) in tests {
18184 assert_eq!(
18185 WordBreakingTokenizer::new(input)
18186 .collect::<Vec<_>>()
18187 .as_slice(),
18188 *result,
18189 );
18190 }
18191}
18192
18193fn wrap_with_prefix(
18194 line_prefix: String,
18195 unwrapped_text: String,
18196 wrap_column: usize,
18197 tab_size: NonZeroU32,
18198 preserve_existing_whitespace: bool,
18199) -> String {
18200 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18201 let mut wrapped_text = String::new();
18202 let mut current_line = line_prefix.clone();
18203
18204 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18205 let mut current_line_len = line_prefix_len;
18206 let mut in_whitespace = false;
18207 for token in tokenizer {
18208 let have_preceding_whitespace = in_whitespace;
18209 match token {
18210 WordBreakToken::Word {
18211 token,
18212 grapheme_len,
18213 } => {
18214 in_whitespace = false;
18215 if current_line_len + grapheme_len > wrap_column
18216 && current_line_len != line_prefix_len
18217 {
18218 wrapped_text.push_str(current_line.trim_end());
18219 wrapped_text.push('\n');
18220 current_line.truncate(line_prefix.len());
18221 current_line_len = line_prefix_len;
18222 }
18223 current_line.push_str(token);
18224 current_line_len += grapheme_len;
18225 }
18226 WordBreakToken::InlineWhitespace {
18227 mut token,
18228 mut grapheme_len,
18229 } => {
18230 in_whitespace = true;
18231 if have_preceding_whitespace && !preserve_existing_whitespace {
18232 continue;
18233 }
18234 if !preserve_existing_whitespace {
18235 token = " ";
18236 grapheme_len = 1;
18237 }
18238 if current_line_len + grapheme_len > wrap_column {
18239 wrapped_text.push_str(current_line.trim_end());
18240 wrapped_text.push('\n');
18241 current_line.truncate(line_prefix.len());
18242 current_line_len = line_prefix_len;
18243 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18244 current_line.push_str(token);
18245 current_line_len += grapheme_len;
18246 }
18247 }
18248 WordBreakToken::Newline => {
18249 in_whitespace = true;
18250 if preserve_existing_whitespace {
18251 wrapped_text.push_str(current_line.trim_end());
18252 wrapped_text.push('\n');
18253 current_line.truncate(line_prefix.len());
18254 current_line_len = line_prefix_len;
18255 } else if have_preceding_whitespace {
18256 continue;
18257 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18258 {
18259 wrapped_text.push_str(current_line.trim_end());
18260 wrapped_text.push('\n');
18261 current_line.truncate(line_prefix.len());
18262 current_line_len = line_prefix_len;
18263 } else if current_line_len != line_prefix_len {
18264 current_line.push(' ');
18265 current_line_len += 1;
18266 }
18267 }
18268 }
18269 }
18270
18271 if !current_line.is_empty() {
18272 wrapped_text.push_str(¤t_line);
18273 }
18274 wrapped_text
18275}
18276
18277#[test]
18278fn test_wrap_with_prefix() {
18279 assert_eq!(
18280 wrap_with_prefix(
18281 "# ".to_string(),
18282 "abcdefg".to_string(),
18283 4,
18284 NonZeroU32::new(4).unwrap(),
18285 false,
18286 ),
18287 "# abcdefg"
18288 );
18289 assert_eq!(
18290 wrap_with_prefix(
18291 "".to_string(),
18292 "\thello world".to_string(),
18293 8,
18294 NonZeroU32::new(4).unwrap(),
18295 false,
18296 ),
18297 "hello\nworld"
18298 );
18299 assert_eq!(
18300 wrap_with_prefix(
18301 "// ".to_string(),
18302 "xx \nyy zz aa bb cc".to_string(),
18303 12,
18304 NonZeroU32::new(4).unwrap(),
18305 false,
18306 ),
18307 "// xx yy zz\n// aa bb cc"
18308 );
18309 assert_eq!(
18310 wrap_with_prefix(
18311 String::new(),
18312 "这是什么 \n 钢笔".to_string(),
18313 3,
18314 NonZeroU32::new(4).unwrap(),
18315 false,
18316 ),
18317 "这是什\n么 钢\n笔"
18318 );
18319}
18320
18321pub trait CollaborationHub {
18322 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18323 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18324 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18325}
18326
18327impl CollaborationHub for Entity<Project> {
18328 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18329 self.read(cx).collaborators()
18330 }
18331
18332 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18333 self.read(cx).user_store().read(cx).participant_indices()
18334 }
18335
18336 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18337 let this = self.read(cx);
18338 let user_ids = this.collaborators().values().map(|c| c.user_id);
18339 this.user_store().read_with(cx, |user_store, cx| {
18340 user_store.participant_names(user_ids, cx)
18341 })
18342 }
18343}
18344
18345pub trait SemanticsProvider {
18346 fn hover(
18347 &self,
18348 buffer: &Entity<Buffer>,
18349 position: text::Anchor,
18350 cx: &mut App,
18351 ) -> Option<Task<Vec<project::Hover>>>;
18352
18353 fn inlay_hints(
18354 &self,
18355 buffer_handle: Entity<Buffer>,
18356 range: Range<text::Anchor>,
18357 cx: &mut App,
18358 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18359
18360 fn resolve_inlay_hint(
18361 &self,
18362 hint: InlayHint,
18363 buffer_handle: Entity<Buffer>,
18364 server_id: LanguageServerId,
18365 cx: &mut App,
18366 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18367
18368 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18369
18370 fn document_highlights(
18371 &self,
18372 buffer: &Entity<Buffer>,
18373 position: text::Anchor,
18374 cx: &mut App,
18375 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18376
18377 fn definitions(
18378 &self,
18379 buffer: &Entity<Buffer>,
18380 position: text::Anchor,
18381 kind: GotoDefinitionKind,
18382 cx: &mut App,
18383 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18384
18385 fn range_for_rename(
18386 &self,
18387 buffer: &Entity<Buffer>,
18388 position: text::Anchor,
18389 cx: &mut App,
18390 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18391
18392 fn perform_rename(
18393 &self,
18394 buffer: &Entity<Buffer>,
18395 position: text::Anchor,
18396 new_name: String,
18397 cx: &mut App,
18398 ) -> Option<Task<Result<ProjectTransaction>>>;
18399}
18400
18401pub trait CompletionProvider {
18402 fn completions(
18403 &self,
18404 excerpt_id: ExcerptId,
18405 buffer: &Entity<Buffer>,
18406 buffer_position: text::Anchor,
18407 trigger: CompletionContext,
18408 window: &mut Window,
18409 cx: &mut Context<Editor>,
18410 ) -> Task<Result<Option<Vec<Completion>>>>;
18411
18412 fn resolve_completions(
18413 &self,
18414 buffer: Entity<Buffer>,
18415 completion_indices: Vec<usize>,
18416 completions: Rc<RefCell<Box<[Completion]>>>,
18417 cx: &mut Context<Editor>,
18418 ) -> Task<Result<bool>>;
18419
18420 fn apply_additional_edits_for_completion(
18421 &self,
18422 _buffer: Entity<Buffer>,
18423 _completions: Rc<RefCell<Box<[Completion]>>>,
18424 _completion_index: usize,
18425 _push_to_history: bool,
18426 _cx: &mut Context<Editor>,
18427 ) -> Task<Result<Option<language::Transaction>>> {
18428 Task::ready(Ok(None))
18429 }
18430
18431 fn is_completion_trigger(
18432 &self,
18433 buffer: &Entity<Buffer>,
18434 position: language::Anchor,
18435 text: &str,
18436 trigger_in_words: bool,
18437 cx: &mut Context<Editor>,
18438 ) -> bool;
18439
18440 fn sort_completions(&self) -> bool {
18441 true
18442 }
18443
18444 fn filter_completions(&self) -> bool {
18445 true
18446 }
18447}
18448
18449pub trait CodeActionProvider {
18450 fn id(&self) -> Arc<str>;
18451
18452 fn code_actions(
18453 &self,
18454 buffer: &Entity<Buffer>,
18455 range: Range<text::Anchor>,
18456 window: &mut Window,
18457 cx: &mut App,
18458 ) -> Task<Result<Vec<CodeAction>>>;
18459
18460 fn apply_code_action(
18461 &self,
18462 buffer_handle: Entity<Buffer>,
18463 action: CodeAction,
18464 excerpt_id: ExcerptId,
18465 push_to_history: bool,
18466 window: &mut Window,
18467 cx: &mut App,
18468 ) -> Task<Result<ProjectTransaction>>;
18469}
18470
18471impl CodeActionProvider for Entity<Project> {
18472 fn id(&self) -> Arc<str> {
18473 "project".into()
18474 }
18475
18476 fn code_actions(
18477 &self,
18478 buffer: &Entity<Buffer>,
18479 range: Range<text::Anchor>,
18480 _window: &mut Window,
18481 cx: &mut App,
18482 ) -> Task<Result<Vec<CodeAction>>> {
18483 self.update(cx, |project, cx| {
18484 let code_lens = project.code_lens(buffer, range.clone(), cx);
18485 let code_actions = project.code_actions(buffer, range, None, cx);
18486 cx.background_spawn(async move {
18487 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18488 Ok(code_lens
18489 .context("code lens fetch")?
18490 .into_iter()
18491 .chain(code_actions.context("code action fetch")?)
18492 .collect())
18493 })
18494 })
18495 }
18496
18497 fn apply_code_action(
18498 &self,
18499 buffer_handle: Entity<Buffer>,
18500 action: CodeAction,
18501 _excerpt_id: ExcerptId,
18502 push_to_history: bool,
18503 _window: &mut Window,
18504 cx: &mut App,
18505 ) -> Task<Result<ProjectTransaction>> {
18506 self.update(cx, |project, cx| {
18507 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18508 })
18509 }
18510}
18511
18512fn snippet_completions(
18513 project: &Project,
18514 buffer: &Entity<Buffer>,
18515 buffer_position: text::Anchor,
18516 cx: &mut App,
18517) -> Task<Result<Vec<Completion>>> {
18518 let language = buffer.read(cx).language_at(buffer_position);
18519 let language_name = language.as_ref().map(|language| language.lsp_id());
18520 let snippet_store = project.snippets().read(cx);
18521 let snippets = snippet_store.snippets_for(language_name, cx);
18522
18523 if snippets.is_empty() {
18524 return Task::ready(Ok(vec![]));
18525 }
18526 let snapshot = buffer.read(cx).text_snapshot();
18527 let chars: String = snapshot
18528 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18529 .collect();
18530
18531 let scope = language.map(|language| language.default_scope());
18532 let executor = cx.background_executor().clone();
18533
18534 cx.background_spawn(async move {
18535 let classifier = CharClassifier::new(scope).for_completion(true);
18536 let mut last_word = chars
18537 .chars()
18538 .take_while(|c| classifier.is_word(*c))
18539 .collect::<String>();
18540 last_word = last_word.chars().rev().collect();
18541
18542 if last_word.is_empty() {
18543 return Ok(vec![]);
18544 }
18545
18546 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18547 let to_lsp = |point: &text::Anchor| {
18548 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18549 point_to_lsp(end)
18550 };
18551 let lsp_end = to_lsp(&buffer_position);
18552
18553 let candidates = snippets
18554 .iter()
18555 .enumerate()
18556 .flat_map(|(ix, snippet)| {
18557 snippet
18558 .prefix
18559 .iter()
18560 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18561 })
18562 .collect::<Vec<StringMatchCandidate>>();
18563
18564 let mut matches = fuzzy::match_strings(
18565 &candidates,
18566 &last_word,
18567 last_word.chars().any(|c| c.is_uppercase()),
18568 100,
18569 &Default::default(),
18570 executor,
18571 )
18572 .await;
18573
18574 // Remove all candidates where the query's start does not match the start of any word in the candidate
18575 if let Some(query_start) = last_word.chars().next() {
18576 matches.retain(|string_match| {
18577 split_words(&string_match.string).any(|word| {
18578 // Check that the first codepoint of the word as lowercase matches the first
18579 // codepoint of the query as lowercase
18580 word.chars()
18581 .flat_map(|codepoint| codepoint.to_lowercase())
18582 .zip(query_start.to_lowercase())
18583 .all(|(word_cp, query_cp)| word_cp == query_cp)
18584 })
18585 });
18586 }
18587
18588 let matched_strings = matches
18589 .into_iter()
18590 .map(|m| m.string)
18591 .collect::<HashSet<_>>();
18592
18593 let result: Vec<Completion> = snippets
18594 .into_iter()
18595 .filter_map(|snippet| {
18596 let matching_prefix = snippet
18597 .prefix
18598 .iter()
18599 .find(|prefix| matched_strings.contains(*prefix))?;
18600 let start = as_offset - last_word.len();
18601 let start = snapshot.anchor_before(start);
18602 let range = start..buffer_position;
18603 let lsp_start = to_lsp(&start);
18604 let lsp_range = lsp::Range {
18605 start: lsp_start,
18606 end: lsp_end,
18607 };
18608 Some(Completion {
18609 old_range: range,
18610 new_text: snippet.body.clone(),
18611 source: CompletionSource::Lsp {
18612 server_id: LanguageServerId(usize::MAX),
18613 resolved: true,
18614 lsp_completion: Box::new(lsp::CompletionItem {
18615 label: snippet.prefix.first().unwrap().clone(),
18616 kind: Some(CompletionItemKind::SNIPPET),
18617 label_details: snippet.description.as_ref().map(|description| {
18618 lsp::CompletionItemLabelDetails {
18619 detail: Some(description.clone()),
18620 description: None,
18621 }
18622 }),
18623 insert_text_format: Some(InsertTextFormat::SNIPPET),
18624 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18625 lsp::InsertReplaceEdit {
18626 new_text: snippet.body.clone(),
18627 insert: lsp_range,
18628 replace: lsp_range,
18629 },
18630 )),
18631 filter_text: Some(snippet.body.clone()),
18632 sort_text: Some(char::MAX.to_string()),
18633 ..lsp::CompletionItem::default()
18634 }),
18635 lsp_defaults: None,
18636 },
18637 label: CodeLabel {
18638 text: matching_prefix.clone(),
18639 runs: Vec::new(),
18640 filter_range: 0..matching_prefix.len(),
18641 },
18642 icon_path: None,
18643 documentation: snippet
18644 .description
18645 .clone()
18646 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18647 insert_text_mode: None,
18648 confirm: None,
18649 })
18650 })
18651 .collect();
18652
18653 Ok(result)
18654 })
18655}
18656
18657impl CompletionProvider for Entity<Project> {
18658 fn completions(
18659 &self,
18660 _excerpt_id: ExcerptId,
18661 buffer: &Entity<Buffer>,
18662 buffer_position: text::Anchor,
18663 options: CompletionContext,
18664 _window: &mut Window,
18665 cx: &mut Context<Editor>,
18666 ) -> Task<Result<Option<Vec<Completion>>>> {
18667 self.update(cx, |project, cx| {
18668 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18669 let project_completions = project.completions(buffer, buffer_position, options, cx);
18670 cx.background_spawn(async move {
18671 let snippets_completions = snippets.await?;
18672 match project_completions.await? {
18673 Some(mut completions) => {
18674 completions.extend(snippets_completions);
18675 Ok(Some(completions))
18676 }
18677 None => {
18678 if snippets_completions.is_empty() {
18679 Ok(None)
18680 } else {
18681 Ok(Some(snippets_completions))
18682 }
18683 }
18684 }
18685 })
18686 })
18687 }
18688
18689 fn resolve_completions(
18690 &self,
18691 buffer: Entity<Buffer>,
18692 completion_indices: Vec<usize>,
18693 completions: Rc<RefCell<Box<[Completion]>>>,
18694 cx: &mut Context<Editor>,
18695 ) -> Task<Result<bool>> {
18696 self.update(cx, |project, cx| {
18697 project.lsp_store().update(cx, |lsp_store, cx| {
18698 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18699 })
18700 })
18701 }
18702
18703 fn apply_additional_edits_for_completion(
18704 &self,
18705 buffer: Entity<Buffer>,
18706 completions: Rc<RefCell<Box<[Completion]>>>,
18707 completion_index: usize,
18708 push_to_history: bool,
18709 cx: &mut Context<Editor>,
18710 ) -> Task<Result<Option<language::Transaction>>> {
18711 self.update(cx, |project, cx| {
18712 project.lsp_store().update(cx, |lsp_store, cx| {
18713 lsp_store.apply_additional_edits_for_completion(
18714 buffer,
18715 completions,
18716 completion_index,
18717 push_to_history,
18718 cx,
18719 )
18720 })
18721 })
18722 }
18723
18724 fn is_completion_trigger(
18725 &self,
18726 buffer: &Entity<Buffer>,
18727 position: language::Anchor,
18728 text: &str,
18729 trigger_in_words: bool,
18730 cx: &mut Context<Editor>,
18731 ) -> bool {
18732 let mut chars = text.chars();
18733 let char = if let Some(char) = chars.next() {
18734 char
18735 } else {
18736 return false;
18737 };
18738 if chars.next().is_some() {
18739 return false;
18740 }
18741
18742 let buffer = buffer.read(cx);
18743 let snapshot = buffer.snapshot();
18744 if !snapshot.settings_at(position, cx).show_completions_on_input {
18745 return false;
18746 }
18747 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18748 if trigger_in_words && classifier.is_word(char) {
18749 return true;
18750 }
18751
18752 buffer.completion_triggers().contains(text)
18753 }
18754}
18755
18756impl SemanticsProvider for Entity<Project> {
18757 fn hover(
18758 &self,
18759 buffer: &Entity<Buffer>,
18760 position: text::Anchor,
18761 cx: &mut App,
18762 ) -> Option<Task<Vec<project::Hover>>> {
18763 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18764 }
18765
18766 fn document_highlights(
18767 &self,
18768 buffer: &Entity<Buffer>,
18769 position: text::Anchor,
18770 cx: &mut App,
18771 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18772 Some(self.update(cx, |project, cx| {
18773 project.document_highlights(buffer, position, cx)
18774 }))
18775 }
18776
18777 fn definitions(
18778 &self,
18779 buffer: &Entity<Buffer>,
18780 position: text::Anchor,
18781 kind: GotoDefinitionKind,
18782 cx: &mut App,
18783 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18784 Some(self.update(cx, |project, cx| match kind {
18785 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18786 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18787 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18788 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18789 }))
18790 }
18791
18792 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18793 // TODO: make this work for remote projects
18794 self.update(cx, |this, cx| {
18795 buffer.update(cx, |buffer, cx| {
18796 this.any_language_server_supports_inlay_hints(buffer, cx)
18797 })
18798 })
18799 }
18800
18801 fn inlay_hints(
18802 &self,
18803 buffer_handle: Entity<Buffer>,
18804 range: Range<text::Anchor>,
18805 cx: &mut App,
18806 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18807 Some(self.update(cx, |project, cx| {
18808 project.inlay_hints(buffer_handle, range, cx)
18809 }))
18810 }
18811
18812 fn resolve_inlay_hint(
18813 &self,
18814 hint: InlayHint,
18815 buffer_handle: Entity<Buffer>,
18816 server_id: LanguageServerId,
18817 cx: &mut App,
18818 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18819 Some(self.update(cx, |project, cx| {
18820 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18821 }))
18822 }
18823
18824 fn range_for_rename(
18825 &self,
18826 buffer: &Entity<Buffer>,
18827 position: text::Anchor,
18828 cx: &mut App,
18829 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18830 Some(self.update(cx, |project, cx| {
18831 let buffer = buffer.clone();
18832 let task = project.prepare_rename(buffer.clone(), position, cx);
18833 cx.spawn(async move |_, cx| {
18834 Ok(match task.await? {
18835 PrepareRenameResponse::Success(range) => Some(range),
18836 PrepareRenameResponse::InvalidPosition => None,
18837 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18838 // Fallback on using TreeSitter info to determine identifier range
18839 buffer.update(cx, |buffer, _| {
18840 let snapshot = buffer.snapshot();
18841 let (range, kind) = snapshot.surrounding_word(position);
18842 if kind != Some(CharKind::Word) {
18843 return None;
18844 }
18845 Some(
18846 snapshot.anchor_before(range.start)
18847 ..snapshot.anchor_after(range.end),
18848 )
18849 })?
18850 }
18851 })
18852 })
18853 }))
18854 }
18855
18856 fn perform_rename(
18857 &self,
18858 buffer: &Entity<Buffer>,
18859 position: text::Anchor,
18860 new_name: String,
18861 cx: &mut App,
18862 ) -> Option<Task<Result<ProjectTransaction>>> {
18863 Some(self.update(cx, |project, cx| {
18864 project.perform_rename(buffer.clone(), position, new_name, cx)
18865 }))
18866 }
18867}
18868
18869fn inlay_hint_settings(
18870 location: Anchor,
18871 snapshot: &MultiBufferSnapshot,
18872 cx: &mut Context<Editor>,
18873) -> InlayHintSettings {
18874 let file = snapshot.file_at(location);
18875 let language = snapshot.language_at(location).map(|l| l.name());
18876 language_settings(language, file, cx).inlay_hints
18877}
18878
18879fn consume_contiguous_rows(
18880 contiguous_row_selections: &mut Vec<Selection<Point>>,
18881 selection: &Selection<Point>,
18882 display_map: &DisplaySnapshot,
18883 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18884) -> (MultiBufferRow, MultiBufferRow) {
18885 contiguous_row_selections.push(selection.clone());
18886 let start_row = MultiBufferRow(selection.start.row);
18887 let mut end_row = ending_row(selection, display_map);
18888
18889 while let Some(next_selection) = selections.peek() {
18890 if next_selection.start.row <= end_row.0 {
18891 end_row = ending_row(next_selection, display_map);
18892 contiguous_row_selections.push(selections.next().unwrap().clone());
18893 } else {
18894 break;
18895 }
18896 }
18897 (start_row, end_row)
18898}
18899
18900fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18901 if next_selection.end.column > 0 || next_selection.is_empty() {
18902 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18903 } else {
18904 MultiBufferRow(next_selection.end.row)
18905 }
18906}
18907
18908impl EditorSnapshot {
18909 pub fn remote_selections_in_range<'a>(
18910 &'a self,
18911 range: &'a Range<Anchor>,
18912 collaboration_hub: &dyn CollaborationHub,
18913 cx: &'a App,
18914 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18915 let participant_names = collaboration_hub.user_names(cx);
18916 let participant_indices = collaboration_hub.user_participant_indices(cx);
18917 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18918 let collaborators_by_replica_id = collaborators_by_peer_id
18919 .iter()
18920 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18921 .collect::<HashMap<_, _>>();
18922 self.buffer_snapshot
18923 .selections_in_range(range, false)
18924 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18925 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18926 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18927 let user_name = participant_names.get(&collaborator.user_id).cloned();
18928 Some(RemoteSelection {
18929 replica_id,
18930 selection,
18931 cursor_shape,
18932 line_mode,
18933 participant_index,
18934 peer_id: collaborator.peer_id,
18935 user_name,
18936 })
18937 })
18938 }
18939
18940 pub fn hunks_for_ranges(
18941 &self,
18942 ranges: impl IntoIterator<Item = Range<Point>>,
18943 ) -> Vec<MultiBufferDiffHunk> {
18944 let mut hunks = Vec::new();
18945 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18946 HashMap::default();
18947 for query_range in ranges {
18948 let query_rows =
18949 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18950 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18951 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18952 ) {
18953 // Include deleted hunks that are adjacent to the query range, because
18954 // otherwise they would be missed.
18955 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18956 if hunk.status().is_deleted() {
18957 intersects_range |= hunk.row_range.start == query_rows.end;
18958 intersects_range |= hunk.row_range.end == query_rows.start;
18959 }
18960 if intersects_range {
18961 if !processed_buffer_rows
18962 .entry(hunk.buffer_id)
18963 .or_default()
18964 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18965 {
18966 continue;
18967 }
18968 hunks.push(hunk);
18969 }
18970 }
18971 }
18972
18973 hunks
18974 }
18975
18976 fn display_diff_hunks_for_rows<'a>(
18977 &'a self,
18978 display_rows: Range<DisplayRow>,
18979 folded_buffers: &'a HashSet<BufferId>,
18980 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18981 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18982 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18983
18984 self.buffer_snapshot
18985 .diff_hunks_in_range(buffer_start..buffer_end)
18986 .filter_map(|hunk| {
18987 if folded_buffers.contains(&hunk.buffer_id) {
18988 return None;
18989 }
18990
18991 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18992 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18993
18994 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18995 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18996
18997 let display_hunk = if hunk_display_start.column() != 0 {
18998 DisplayDiffHunk::Folded {
18999 display_row: hunk_display_start.row(),
19000 }
19001 } else {
19002 let mut end_row = hunk_display_end.row();
19003 if hunk_display_end.column() > 0 {
19004 end_row.0 += 1;
19005 }
19006 let is_created_file = hunk.is_created_file();
19007 DisplayDiffHunk::Unfolded {
19008 status: hunk.status(),
19009 diff_base_byte_range: hunk.diff_base_byte_range,
19010 display_row_range: hunk_display_start.row()..end_row,
19011 multi_buffer_range: Anchor::range_in_buffer(
19012 hunk.excerpt_id,
19013 hunk.buffer_id,
19014 hunk.buffer_range,
19015 ),
19016 is_created_file,
19017 }
19018 };
19019
19020 Some(display_hunk)
19021 })
19022 }
19023
19024 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19025 self.display_snapshot.buffer_snapshot.language_at(position)
19026 }
19027
19028 pub fn is_focused(&self) -> bool {
19029 self.is_focused
19030 }
19031
19032 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19033 self.placeholder_text.as_ref()
19034 }
19035
19036 pub fn scroll_position(&self) -> gpui::Point<f32> {
19037 self.scroll_anchor.scroll_position(&self.display_snapshot)
19038 }
19039
19040 fn gutter_dimensions(
19041 &self,
19042 font_id: FontId,
19043 font_size: Pixels,
19044 max_line_number_width: Pixels,
19045 cx: &App,
19046 ) -> Option<GutterDimensions> {
19047 if !self.show_gutter {
19048 return None;
19049 }
19050
19051 let descent = cx.text_system().descent(font_id, font_size);
19052 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19053 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19054
19055 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19056 matches!(
19057 ProjectSettings::get_global(cx).git.git_gutter,
19058 Some(GitGutterSetting::TrackedFiles)
19059 )
19060 });
19061 let gutter_settings = EditorSettings::get_global(cx).gutter;
19062 let show_line_numbers = self
19063 .show_line_numbers
19064 .unwrap_or(gutter_settings.line_numbers);
19065 let line_gutter_width = if show_line_numbers {
19066 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19067 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19068 max_line_number_width.max(min_width_for_number_on_gutter)
19069 } else {
19070 0.0.into()
19071 };
19072
19073 let show_code_actions = self
19074 .show_code_actions
19075 .unwrap_or(gutter_settings.code_actions);
19076
19077 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19078 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19079
19080 let git_blame_entries_width =
19081 self.git_blame_gutter_max_author_length
19082 .map(|max_author_length| {
19083 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19084 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19085
19086 /// The number of characters to dedicate to gaps and margins.
19087 const SPACING_WIDTH: usize = 4;
19088
19089 let max_char_count = max_author_length.min(renderer.max_author_length())
19090 + ::git::SHORT_SHA_LENGTH
19091 + MAX_RELATIVE_TIMESTAMP.len()
19092 + SPACING_WIDTH;
19093
19094 em_advance * max_char_count
19095 });
19096
19097 let is_singleton = self.buffer_snapshot.is_singleton();
19098
19099 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19100 left_padding += if !is_singleton {
19101 em_width * 4.0
19102 } else if show_code_actions || show_runnables || show_breakpoints {
19103 em_width * 3.0
19104 } else if show_git_gutter && show_line_numbers {
19105 em_width * 2.0
19106 } else if show_git_gutter || show_line_numbers {
19107 em_width
19108 } else {
19109 px(0.)
19110 };
19111
19112 let shows_folds = is_singleton && gutter_settings.folds;
19113
19114 let right_padding = if shows_folds && show_line_numbers {
19115 em_width * 4.0
19116 } else if shows_folds || (!is_singleton && show_line_numbers) {
19117 em_width * 3.0
19118 } else if show_line_numbers {
19119 em_width
19120 } else {
19121 px(0.)
19122 };
19123
19124 Some(GutterDimensions {
19125 left_padding,
19126 right_padding,
19127 width: line_gutter_width + left_padding + right_padding,
19128 margin: -descent,
19129 git_blame_entries_width,
19130 })
19131 }
19132
19133 pub fn render_crease_toggle(
19134 &self,
19135 buffer_row: MultiBufferRow,
19136 row_contains_cursor: bool,
19137 editor: Entity<Editor>,
19138 window: &mut Window,
19139 cx: &mut App,
19140 ) -> Option<AnyElement> {
19141 let folded = self.is_line_folded(buffer_row);
19142 let mut is_foldable = false;
19143
19144 if let Some(crease) = self
19145 .crease_snapshot
19146 .query_row(buffer_row, &self.buffer_snapshot)
19147 {
19148 is_foldable = true;
19149 match crease {
19150 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19151 if let Some(render_toggle) = render_toggle {
19152 let toggle_callback =
19153 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19154 if folded {
19155 editor.update(cx, |editor, cx| {
19156 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19157 });
19158 } else {
19159 editor.update(cx, |editor, cx| {
19160 editor.unfold_at(
19161 &crate::UnfoldAt { buffer_row },
19162 window,
19163 cx,
19164 )
19165 });
19166 }
19167 });
19168 return Some((render_toggle)(
19169 buffer_row,
19170 folded,
19171 toggle_callback,
19172 window,
19173 cx,
19174 ));
19175 }
19176 }
19177 }
19178 }
19179
19180 is_foldable |= self.starts_indent(buffer_row);
19181
19182 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19183 Some(
19184 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19185 .toggle_state(folded)
19186 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19187 if folded {
19188 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19189 } else {
19190 this.fold_at(&FoldAt { buffer_row }, window, cx);
19191 }
19192 }))
19193 .into_any_element(),
19194 )
19195 } else {
19196 None
19197 }
19198 }
19199
19200 pub fn render_crease_trailer(
19201 &self,
19202 buffer_row: MultiBufferRow,
19203 window: &mut Window,
19204 cx: &mut App,
19205 ) -> Option<AnyElement> {
19206 let folded = self.is_line_folded(buffer_row);
19207 if let Crease::Inline { render_trailer, .. } = self
19208 .crease_snapshot
19209 .query_row(buffer_row, &self.buffer_snapshot)?
19210 {
19211 let render_trailer = render_trailer.as_ref()?;
19212 Some(render_trailer(buffer_row, folded, window, cx))
19213 } else {
19214 None
19215 }
19216 }
19217}
19218
19219impl Deref for EditorSnapshot {
19220 type Target = DisplaySnapshot;
19221
19222 fn deref(&self) -> &Self::Target {
19223 &self.display_snapshot
19224 }
19225}
19226
19227#[derive(Clone, Debug, PartialEq, Eq)]
19228pub enum EditorEvent {
19229 InputIgnored {
19230 text: Arc<str>,
19231 },
19232 InputHandled {
19233 utf16_range_to_replace: Option<Range<isize>>,
19234 text: Arc<str>,
19235 },
19236 ExcerptsAdded {
19237 buffer: Entity<Buffer>,
19238 predecessor: ExcerptId,
19239 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19240 },
19241 ExcerptsRemoved {
19242 ids: Vec<ExcerptId>,
19243 },
19244 BufferFoldToggled {
19245 ids: Vec<ExcerptId>,
19246 folded: bool,
19247 },
19248 ExcerptsEdited {
19249 ids: Vec<ExcerptId>,
19250 },
19251 ExcerptsExpanded {
19252 ids: Vec<ExcerptId>,
19253 },
19254 BufferEdited,
19255 Edited {
19256 transaction_id: clock::Lamport,
19257 },
19258 Reparsed(BufferId),
19259 Focused,
19260 FocusedIn,
19261 Blurred,
19262 DirtyChanged,
19263 Saved,
19264 TitleChanged,
19265 DiffBaseChanged,
19266 SelectionsChanged {
19267 local: bool,
19268 },
19269 ScrollPositionChanged {
19270 local: bool,
19271 autoscroll: bool,
19272 },
19273 Closed,
19274 TransactionUndone {
19275 transaction_id: clock::Lamport,
19276 },
19277 TransactionBegun {
19278 transaction_id: clock::Lamport,
19279 },
19280 Reloaded,
19281 CursorShapeChanged,
19282 PushedToNavHistory {
19283 anchor: Anchor,
19284 is_deactivate: bool,
19285 },
19286}
19287
19288impl EventEmitter<EditorEvent> for Editor {}
19289
19290impl Focusable for Editor {
19291 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19292 self.focus_handle.clone()
19293 }
19294}
19295
19296impl Render for Editor {
19297 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19298 let settings = ThemeSettings::get_global(cx);
19299
19300 let mut text_style = match self.mode {
19301 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19302 color: cx.theme().colors().editor_foreground,
19303 font_family: settings.ui_font.family.clone(),
19304 font_features: settings.ui_font.features.clone(),
19305 font_fallbacks: settings.ui_font.fallbacks.clone(),
19306 font_size: rems(0.875).into(),
19307 font_weight: settings.ui_font.weight,
19308 line_height: relative(settings.buffer_line_height.value()),
19309 ..Default::default()
19310 },
19311 EditorMode::Full => TextStyle {
19312 color: cx.theme().colors().editor_foreground,
19313 font_family: settings.buffer_font.family.clone(),
19314 font_features: settings.buffer_font.features.clone(),
19315 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19316 font_size: settings.buffer_font_size(cx).into(),
19317 font_weight: settings.buffer_font.weight,
19318 line_height: relative(settings.buffer_line_height.value()),
19319 ..Default::default()
19320 },
19321 };
19322 if let Some(text_style_refinement) = &self.text_style_refinement {
19323 text_style.refine(text_style_refinement)
19324 }
19325
19326 let background = match self.mode {
19327 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19328 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19329 EditorMode::Full => cx.theme().colors().editor_background,
19330 };
19331
19332 EditorElement::new(
19333 &cx.entity(),
19334 EditorStyle {
19335 background,
19336 local_player: cx.theme().players().local(),
19337 text: text_style,
19338 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19339 syntax: cx.theme().syntax().clone(),
19340 status: cx.theme().status().clone(),
19341 inlay_hints_style: make_inlay_hints_style(cx),
19342 inline_completion_styles: make_suggestion_styles(cx),
19343 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19344 },
19345 )
19346 }
19347}
19348
19349impl EntityInputHandler for Editor {
19350 fn text_for_range(
19351 &mut self,
19352 range_utf16: Range<usize>,
19353 adjusted_range: &mut Option<Range<usize>>,
19354 _: &mut Window,
19355 cx: &mut Context<Self>,
19356 ) -> Option<String> {
19357 let snapshot = self.buffer.read(cx).read(cx);
19358 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19359 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19360 if (start.0..end.0) != range_utf16 {
19361 adjusted_range.replace(start.0..end.0);
19362 }
19363 Some(snapshot.text_for_range(start..end).collect())
19364 }
19365
19366 fn selected_text_range(
19367 &mut self,
19368 ignore_disabled_input: bool,
19369 _: &mut Window,
19370 cx: &mut Context<Self>,
19371 ) -> Option<UTF16Selection> {
19372 // Prevent the IME menu from appearing when holding down an alphabetic key
19373 // while input is disabled.
19374 if !ignore_disabled_input && !self.input_enabled {
19375 return None;
19376 }
19377
19378 let selection = self.selections.newest::<OffsetUtf16>(cx);
19379 let range = selection.range();
19380
19381 Some(UTF16Selection {
19382 range: range.start.0..range.end.0,
19383 reversed: selection.reversed,
19384 })
19385 }
19386
19387 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19388 let snapshot = self.buffer.read(cx).read(cx);
19389 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19390 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19391 }
19392
19393 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19394 self.clear_highlights::<InputComposition>(cx);
19395 self.ime_transaction.take();
19396 }
19397
19398 fn replace_text_in_range(
19399 &mut self,
19400 range_utf16: Option<Range<usize>>,
19401 text: &str,
19402 window: &mut Window,
19403 cx: &mut Context<Self>,
19404 ) {
19405 if !self.input_enabled {
19406 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19407 return;
19408 }
19409
19410 self.transact(window, cx, |this, window, cx| {
19411 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19412 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19413 Some(this.selection_replacement_ranges(range_utf16, cx))
19414 } else {
19415 this.marked_text_ranges(cx)
19416 };
19417
19418 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19419 let newest_selection_id = this.selections.newest_anchor().id;
19420 this.selections
19421 .all::<OffsetUtf16>(cx)
19422 .iter()
19423 .zip(ranges_to_replace.iter())
19424 .find_map(|(selection, range)| {
19425 if selection.id == newest_selection_id {
19426 Some(
19427 (range.start.0 as isize - selection.head().0 as isize)
19428 ..(range.end.0 as isize - selection.head().0 as isize),
19429 )
19430 } else {
19431 None
19432 }
19433 })
19434 });
19435
19436 cx.emit(EditorEvent::InputHandled {
19437 utf16_range_to_replace: range_to_replace,
19438 text: text.into(),
19439 });
19440
19441 if let Some(new_selected_ranges) = new_selected_ranges {
19442 this.change_selections(None, window, cx, |selections| {
19443 selections.select_ranges(new_selected_ranges)
19444 });
19445 this.backspace(&Default::default(), window, cx);
19446 }
19447
19448 this.handle_input(text, window, cx);
19449 });
19450
19451 if let Some(transaction) = self.ime_transaction {
19452 self.buffer.update(cx, |buffer, cx| {
19453 buffer.group_until_transaction(transaction, cx);
19454 });
19455 }
19456
19457 self.unmark_text(window, cx);
19458 }
19459
19460 fn replace_and_mark_text_in_range(
19461 &mut self,
19462 range_utf16: Option<Range<usize>>,
19463 text: &str,
19464 new_selected_range_utf16: Option<Range<usize>>,
19465 window: &mut Window,
19466 cx: &mut Context<Self>,
19467 ) {
19468 if !self.input_enabled {
19469 return;
19470 }
19471
19472 let transaction = self.transact(window, cx, |this, window, cx| {
19473 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19474 let snapshot = this.buffer.read(cx).read(cx);
19475 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19476 for marked_range in &mut marked_ranges {
19477 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19478 marked_range.start.0 += relative_range_utf16.start;
19479 marked_range.start =
19480 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19481 marked_range.end =
19482 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19483 }
19484 }
19485 Some(marked_ranges)
19486 } else if let Some(range_utf16) = range_utf16 {
19487 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19488 Some(this.selection_replacement_ranges(range_utf16, cx))
19489 } else {
19490 None
19491 };
19492
19493 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19494 let newest_selection_id = this.selections.newest_anchor().id;
19495 this.selections
19496 .all::<OffsetUtf16>(cx)
19497 .iter()
19498 .zip(ranges_to_replace.iter())
19499 .find_map(|(selection, range)| {
19500 if selection.id == newest_selection_id {
19501 Some(
19502 (range.start.0 as isize - selection.head().0 as isize)
19503 ..(range.end.0 as isize - selection.head().0 as isize),
19504 )
19505 } else {
19506 None
19507 }
19508 })
19509 });
19510
19511 cx.emit(EditorEvent::InputHandled {
19512 utf16_range_to_replace: range_to_replace,
19513 text: text.into(),
19514 });
19515
19516 if let Some(ranges) = ranges_to_replace {
19517 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19518 }
19519
19520 let marked_ranges = {
19521 let snapshot = this.buffer.read(cx).read(cx);
19522 this.selections
19523 .disjoint_anchors()
19524 .iter()
19525 .map(|selection| {
19526 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19527 })
19528 .collect::<Vec<_>>()
19529 };
19530
19531 if text.is_empty() {
19532 this.unmark_text(window, cx);
19533 } else {
19534 this.highlight_text::<InputComposition>(
19535 marked_ranges.clone(),
19536 HighlightStyle {
19537 underline: Some(UnderlineStyle {
19538 thickness: px(1.),
19539 color: None,
19540 wavy: false,
19541 }),
19542 ..Default::default()
19543 },
19544 cx,
19545 );
19546 }
19547
19548 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19549 let use_autoclose = this.use_autoclose;
19550 let use_auto_surround = this.use_auto_surround;
19551 this.set_use_autoclose(false);
19552 this.set_use_auto_surround(false);
19553 this.handle_input(text, window, cx);
19554 this.set_use_autoclose(use_autoclose);
19555 this.set_use_auto_surround(use_auto_surround);
19556
19557 if let Some(new_selected_range) = new_selected_range_utf16 {
19558 let snapshot = this.buffer.read(cx).read(cx);
19559 let new_selected_ranges = marked_ranges
19560 .into_iter()
19561 .map(|marked_range| {
19562 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19563 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19564 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19565 snapshot.clip_offset_utf16(new_start, Bias::Left)
19566 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19567 })
19568 .collect::<Vec<_>>();
19569
19570 drop(snapshot);
19571 this.change_selections(None, window, cx, |selections| {
19572 selections.select_ranges(new_selected_ranges)
19573 });
19574 }
19575 });
19576
19577 self.ime_transaction = self.ime_transaction.or(transaction);
19578 if let Some(transaction) = self.ime_transaction {
19579 self.buffer.update(cx, |buffer, cx| {
19580 buffer.group_until_transaction(transaction, cx);
19581 });
19582 }
19583
19584 if self.text_highlights::<InputComposition>(cx).is_none() {
19585 self.ime_transaction.take();
19586 }
19587 }
19588
19589 fn bounds_for_range(
19590 &mut self,
19591 range_utf16: Range<usize>,
19592 element_bounds: gpui::Bounds<Pixels>,
19593 window: &mut Window,
19594 cx: &mut Context<Self>,
19595 ) -> Option<gpui::Bounds<Pixels>> {
19596 let text_layout_details = self.text_layout_details(window);
19597 let gpui::Size {
19598 width: em_width,
19599 height: line_height,
19600 } = self.character_size(window);
19601
19602 let snapshot = self.snapshot(window, cx);
19603 let scroll_position = snapshot.scroll_position();
19604 let scroll_left = scroll_position.x * em_width;
19605
19606 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19607 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19608 + self.gutter_dimensions.width
19609 + self.gutter_dimensions.margin;
19610 let y = line_height * (start.row().as_f32() - scroll_position.y);
19611
19612 Some(Bounds {
19613 origin: element_bounds.origin + point(x, y),
19614 size: size(em_width, line_height),
19615 })
19616 }
19617
19618 fn character_index_for_point(
19619 &mut self,
19620 point: gpui::Point<Pixels>,
19621 _window: &mut Window,
19622 _cx: &mut Context<Self>,
19623 ) -> Option<usize> {
19624 let position_map = self.last_position_map.as_ref()?;
19625 if !position_map.text_hitbox.contains(&point) {
19626 return None;
19627 }
19628 let display_point = position_map.point_for_position(point).previous_valid;
19629 let anchor = position_map
19630 .snapshot
19631 .display_point_to_anchor(display_point, Bias::Left);
19632 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19633 Some(utf16_offset.0)
19634 }
19635}
19636
19637trait SelectionExt {
19638 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19639 fn spanned_rows(
19640 &self,
19641 include_end_if_at_line_start: bool,
19642 map: &DisplaySnapshot,
19643 ) -> Range<MultiBufferRow>;
19644}
19645
19646impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19647 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19648 let start = self
19649 .start
19650 .to_point(&map.buffer_snapshot)
19651 .to_display_point(map);
19652 let end = self
19653 .end
19654 .to_point(&map.buffer_snapshot)
19655 .to_display_point(map);
19656 if self.reversed {
19657 end..start
19658 } else {
19659 start..end
19660 }
19661 }
19662
19663 fn spanned_rows(
19664 &self,
19665 include_end_if_at_line_start: bool,
19666 map: &DisplaySnapshot,
19667 ) -> Range<MultiBufferRow> {
19668 let start = self.start.to_point(&map.buffer_snapshot);
19669 let mut end = self.end.to_point(&map.buffer_snapshot);
19670 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19671 end.row -= 1;
19672 }
19673
19674 let buffer_start = map.prev_line_boundary(start).0;
19675 let buffer_end = map.next_line_boundary(end).0;
19676 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19677 }
19678}
19679
19680impl<T: InvalidationRegion> InvalidationStack<T> {
19681 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19682 where
19683 S: Clone + ToOffset,
19684 {
19685 while let Some(region) = self.last() {
19686 let all_selections_inside_invalidation_ranges =
19687 if selections.len() == region.ranges().len() {
19688 selections
19689 .iter()
19690 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19691 .all(|(selection, invalidation_range)| {
19692 let head = selection.head().to_offset(buffer);
19693 invalidation_range.start <= head && invalidation_range.end >= head
19694 })
19695 } else {
19696 false
19697 };
19698
19699 if all_selections_inside_invalidation_ranges {
19700 break;
19701 } else {
19702 self.pop();
19703 }
19704 }
19705 }
19706}
19707
19708impl<T> Default for InvalidationStack<T> {
19709 fn default() -> Self {
19710 Self(Default::default())
19711 }
19712}
19713
19714impl<T> Deref for InvalidationStack<T> {
19715 type Target = Vec<T>;
19716
19717 fn deref(&self) -> &Self::Target {
19718 &self.0
19719 }
19720}
19721
19722impl<T> DerefMut for InvalidationStack<T> {
19723 fn deref_mut(&mut self) -> &mut Self::Target {
19724 &mut self.0
19725 }
19726}
19727
19728impl InvalidationRegion for SnippetState {
19729 fn ranges(&self) -> &[Range<Anchor>] {
19730 &self.ranges[self.active_index]
19731 }
19732}
19733
19734pub fn diagnostic_block_renderer(
19735 diagnostic: Diagnostic,
19736 max_message_rows: Option<u8>,
19737 allow_closing: bool,
19738) -> RenderBlock {
19739 let (text_without_backticks, code_ranges) =
19740 highlight_diagnostic_message(&diagnostic, max_message_rows);
19741
19742 Arc::new(move |cx: &mut BlockContext| {
19743 let group_id: SharedString = cx.block_id.to_string().into();
19744
19745 let mut text_style = cx.window.text_style().clone();
19746 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19747 let theme_settings = ThemeSettings::get_global(cx);
19748 text_style.font_family = theme_settings.buffer_font.family.clone();
19749 text_style.font_style = theme_settings.buffer_font.style;
19750 text_style.font_features = theme_settings.buffer_font.features.clone();
19751 text_style.font_weight = theme_settings.buffer_font.weight;
19752
19753 let multi_line_diagnostic = diagnostic.message.contains('\n');
19754
19755 let buttons = |diagnostic: &Diagnostic| {
19756 if multi_line_diagnostic {
19757 v_flex()
19758 } else {
19759 h_flex()
19760 }
19761 .when(allow_closing, |div| {
19762 div.children(diagnostic.is_primary.then(|| {
19763 IconButton::new("close-block", IconName::XCircle)
19764 .icon_color(Color::Muted)
19765 .size(ButtonSize::Compact)
19766 .style(ButtonStyle::Transparent)
19767 .visible_on_hover(group_id.clone())
19768 .on_click(move |_click, window, cx| {
19769 window.dispatch_action(Box::new(Cancel), cx)
19770 })
19771 .tooltip(|window, cx| {
19772 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19773 })
19774 }))
19775 })
19776 .child(
19777 IconButton::new("copy-block", IconName::Copy)
19778 .icon_color(Color::Muted)
19779 .size(ButtonSize::Compact)
19780 .style(ButtonStyle::Transparent)
19781 .visible_on_hover(group_id.clone())
19782 .on_click({
19783 let message = diagnostic.message.clone();
19784 move |_click, _, cx| {
19785 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19786 }
19787 })
19788 .tooltip(Tooltip::text("Copy diagnostic message")),
19789 )
19790 };
19791
19792 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19793 AvailableSpace::min_size(),
19794 cx.window,
19795 cx.app,
19796 );
19797
19798 h_flex()
19799 .id(cx.block_id)
19800 .group(group_id.clone())
19801 .relative()
19802 .size_full()
19803 .block_mouse_down()
19804 .pl(cx.gutter_dimensions.width)
19805 .w(cx.max_width - cx.gutter_dimensions.full_width())
19806 .child(
19807 div()
19808 .flex()
19809 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19810 .flex_shrink(),
19811 )
19812 .child(buttons(&diagnostic))
19813 .child(div().flex().flex_shrink_0().child(
19814 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19815 &text_style,
19816 code_ranges.iter().map(|range| {
19817 (
19818 range.clone(),
19819 HighlightStyle {
19820 font_weight: Some(FontWeight::BOLD),
19821 ..Default::default()
19822 },
19823 )
19824 }),
19825 ),
19826 ))
19827 .into_any_element()
19828 })
19829}
19830
19831fn inline_completion_edit_text(
19832 current_snapshot: &BufferSnapshot,
19833 edits: &[(Range<Anchor>, String)],
19834 edit_preview: &EditPreview,
19835 include_deletions: bool,
19836 cx: &App,
19837) -> HighlightedText {
19838 let edits = edits
19839 .iter()
19840 .map(|(anchor, text)| {
19841 (
19842 anchor.start.text_anchor..anchor.end.text_anchor,
19843 text.clone(),
19844 )
19845 })
19846 .collect::<Vec<_>>();
19847
19848 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19849}
19850
19851pub fn highlight_diagnostic_message(
19852 diagnostic: &Diagnostic,
19853 mut max_message_rows: Option<u8>,
19854) -> (SharedString, Vec<Range<usize>>) {
19855 let mut text_without_backticks = String::new();
19856 let mut code_ranges = Vec::new();
19857
19858 if let Some(source) = &diagnostic.source {
19859 text_without_backticks.push_str(source);
19860 code_ranges.push(0..source.len());
19861 text_without_backticks.push_str(": ");
19862 }
19863
19864 let mut prev_offset = 0;
19865 let mut in_code_block = false;
19866 let has_row_limit = max_message_rows.is_some();
19867 let mut newline_indices = diagnostic
19868 .message
19869 .match_indices('\n')
19870 .filter(|_| has_row_limit)
19871 .map(|(ix, _)| ix)
19872 .fuse()
19873 .peekable();
19874
19875 for (quote_ix, _) in diagnostic
19876 .message
19877 .match_indices('`')
19878 .chain([(diagnostic.message.len(), "")])
19879 {
19880 let mut first_newline_ix = None;
19881 let mut last_newline_ix = None;
19882 while let Some(newline_ix) = newline_indices.peek() {
19883 if *newline_ix < quote_ix {
19884 if first_newline_ix.is_none() {
19885 first_newline_ix = Some(*newline_ix);
19886 }
19887 last_newline_ix = Some(*newline_ix);
19888
19889 if let Some(rows_left) = &mut max_message_rows {
19890 if *rows_left == 0 {
19891 break;
19892 } else {
19893 *rows_left -= 1;
19894 }
19895 }
19896 let _ = newline_indices.next();
19897 } else {
19898 break;
19899 }
19900 }
19901 let prev_len = text_without_backticks.len();
19902 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19903 text_without_backticks.push_str(new_text);
19904 if in_code_block {
19905 code_ranges.push(prev_len..text_without_backticks.len());
19906 }
19907 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19908 in_code_block = !in_code_block;
19909 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19910 text_without_backticks.push_str("...");
19911 break;
19912 }
19913 }
19914
19915 (text_without_backticks.into(), code_ranges)
19916}
19917
19918fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19919 match severity {
19920 DiagnosticSeverity::ERROR => colors.error,
19921 DiagnosticSeverity::WARNING => colors.warning,
19922 DiagnosticSeverity::INFORMATION => colors.info,
19923 DiagnosticSeverity::HINT => colors.info,
19924 _ => colors.ignored,
19925 }
19926}
19927
19928pub fn styled_runs_for_code_label<'a>(
19929 label: &'a CodeLabel,
19930 syntax_theme: &'a theme::SyntaxTheme,
19931) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19932 let fade_out = HighlightStyle {
19933 fade_out: Some(0.35),
19934 ..Default::default()
19935 };
19936
19937 let mut prev_end = label.filter_range.end;
19938 label
19939 .runs
19940 .iter()
19941 .enumerate()
19942 .flat_map(move |(ix, (range, highlight_id))| {
19943 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19944 style
19945 } else {
19946 return Default::default();
19947 };
19948 let mut muted_style = style;
19949 muted_style.highlight(fade_out);
19950
19951 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19952 if range.start >= label.filter_range.end {
19953 if range.start > prev_end {
19954 runs.push((prev_end..range.start, fade_out));
19955 }
19956 runs.push((range.clone(), muted_style));
19957 } else if range.end <= label.filter_range.end {
19958 runs.push((range.clone(), style));
19959 } else {
19960 runs.push((range.start..label.filter_range.end, style));
19961 runs.push((label.filter_range.end..range.end, muted_style));
19962 }
19963 prev_end = cmp::max(prev_end, range.end);
19964
19965 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19966 runs.push((prev_end..label.text.len(), fade_out));
19967 }
19968
19969 runs
19970 })
19971}
19972
19973pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19974 let mut prev_index = 0;
19975 let mut prev_codepoint: Option<char> = None;
19976 text.char_indices()
19977 .chain([(text.len(), '\0')])
19978 .filter_map(move |(index, codepoint)| {
19979 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19980 let is_boundary = index == text.len()
19981 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19982 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19983 if is_boundary {
19984 let chunk = &text[prev_index..index];
19985 prev_index = index;
19986 Some(chunk)
19987 } else {
19988 None
19989 }
19990 })
19991}
19992
19993pub trait RangeToAnchorExt: Sized {
19994 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19995
19996 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19997 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19998 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19999 }
20000}
20001
20002impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20003 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20004 let start_offset = self.start.to_offset(snapshot);
20005 let end_offset = self.end.to_offset(snapshot);
20006 if start_offset == end_offset {
20007 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20008 } else {
20009 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20010 }
20011 }
20012}
20013
20014pub trait RowExt {
20015 fn as_f32(&self) -> f32;
20016
20017 fn next_row(&self) -> Self;
20018
20019 fn previous_row(&self) -> Self;
20020
20021 fn minus(&self, other: Self) -> u32;
20022}
20023
20024impl RowExt for DisplayRow {
20025 fn as_f32(&self) -> f32 {
20026 self.0 as f32
20027 }
20028
20029 fn next_row(&self) -> Self {
20030 Self(self.0 + 1)
20031 }
20032
20033 fn previous_row(&self) -> Self {
20034 Self(self.0.saturating_sub(1))
20035 }
20036
20037 fn minus(&self, other: Self) -> u32 {
20038 self.0 - other.0
20039 }
20040}
20041
20042impl RowExt for MultiBufferRow {
20043 fn as_f32(&self) -> f32 {
20044 self.0 as f32
20045 }
20046
20047 fn next_row(&self) -> Self {
20048 Self(self.0 + 1)
20049 }
20050
20051 fn previous_row(&self) -> Self {
20052 Self(self.0.saturating_sub(1))
20053 }
20054
20055 fn minus(&self, other: Self) -> u32 {
20056 self.0 - other.0
20057 }
20058}
20059
20060trait RowRangeExt {
20061 type Row;
20062
20063 fn len(&self) -> usize;
20064
20065 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20066}
20067
20068impl RowRangeExt for Range<MultiBufferRow> {
20069 type Row = MultiBufferRow;
20070
20071 fn len(&self) -> usize {
20072 (self.end.0 - self.start.0) as usize
20073 }
20074
20075 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20076 (self.start.0..self.end.0).map(MultiBufferRow)
20077 }
20078}
20079
20080impl RowRangeExt for Range<DisplayRow> {
20081 type Row = DisplayRow;
20082
20083 fn len(&self) -> usize {
20084 (self.end.0 - self.start.0) as usize
20085 }
20086
20087 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20088 (self.start.0..self.end.0).map(DisplayRow)
20089 }
20090}
20091
20092/// If select range has more than one line, we
20093/// just point the cursor to range.start.
20094fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20095 if range.start.row == range.end.row {
20096 range
20097 } else {
20098 range.start..range.start
20099 }
20100}
20101pub struct KillRing(ClipboardItem);
20102impl Global for KillRing {}
20103
20104const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20105
20106enum BreakpointPromptEditAction {
20107 Log,
20108 Condition,
20109 HitCondition,
20110}
20111
20112struct BreakpointPromptEditor {
20113 pub(crate) prompt: Entity<Editor>,
20114 editor: WeakEntity<Editor>,
20115 breakpoint_anchor: Anchor,
20116 breakpoint: Breakpoint,
20117 edit_action: BreakpointPromptEditAction,
20118 block_ids: HashSet<CustomBlockId>,
20119 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20120 _subscriptions: Vec<Subscription>,
20121}
20122
20123impl BreakpointPromptEditor {
20124 const MAX_LINES: u8 = 4;
20125
20126 fn new(
20127 editor: WeakEntity<Editor>,
20128 breakpoint_anchor: Anchor,
20129 breakpoint: Breakpoint,
20130 edit_action: BreakpointPromptEditAction,
20131 window: &mut Window,
20132 cx: &mut Context<Self>,
20133 ) -> Self {
20134 let base_text = match edit_action {
20135 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20136 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20137 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20138 }
20139 .map(|msg| msg.to_string())
20140 .unwrap_or_default();
20141
20142 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20143 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20144
20145 let prompt = cx.new(|cx| {
20146 let mut prompt = Editor::new(
20147 EditorMode::AutoHeight {
20148 max_lines: Self::MAX_LINES as usize,
20149 },
20150 buffer,
20151 None,
20152 window,
20153 cx,
20154 );
20155 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20156 prompt.set_show_cursor_when_unfocused(false, cx);
20157 prompt.set_placeholder_text(
20158 match edit_action {
20159 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20160 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20161 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20162 },
20163 cx,
20164 );
20165
20166 prompt
20167 });
20168
20169 Self {
20170 prompt,
20171 editor,
20172 breakpoint_anchor,
20173 breakpoint,
20174 edit_action,
20175 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20176 block_ids: Default::default(),
20177 _subscriptions: vec![],
20178 }
20179 }
20180
20181 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20182 self.block_ids.extend(block_ids)
20183 }
20184
20185 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20186 if let Some(editor) = self.editor.upgrade() {
20187 let message = self
20188 .prompt
20189 .read(cx)
20190 .buffer
20191 .read(cx)
20192 .as_singleton()
20193 .expect("A multi buffer in breakpoint prompt isn't possible")
20194 .read(cx)
20195 .as_rope()
20196 .to_string();
20197
20198 editor.update(cx, |editor, cx| {
20199 editor.edit_breakpoint_at_anchor(
20200 self.breakpoint_anchor,
20201 self.breakpoint.clone(),
20202 match self.edit_action {
20203 BreakpointPromptEditAction::Log => {
20204 BreakpointEditAction::EditLogMessage(message.into())
20205 }
20206 BreakpointPromptEditAction::Condition => {
20207 BreakpointEditAction::EditCondition(message.into())
20208 }
20209 BreakpointPromptEditAction::HitCondition => {
20210 BreakpointEditAction::EditHitCondition(message.into())
20211 }
20212 },
20213 cx,
20214 );
20215
20216 editor.remove_blocks(self.block_ids.clone(), None, cx);
20217 cx.focus_self(window);
20218 });
20219 }
20220 }
20221
20222 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20223 self.editor
20224 .update(cx, |editor, cx| {
20225 editor.remove_blocks(self.block_ids.clone(), None, cx);
20226 window.focus(&editor.focus_handle);
20227 })
20228 .log_err();
20229 }
20230
20231 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20232 let settings = ThemeSettings::get_global(cx);
20233 let text_style = TextStyle {
20234 color: if self.prompt.read(cx).read_only(cx) {
20235 cx.theme().colors().text_disabled
20236 } else {
20237 cx.theme().colors().text
20238 },
20239 font_family: settings.buffer_font.family.clone(),
20240 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20241 font_size: settings.buffer_font_size(cx).into(),
20242 font_weight: settings.buffer_font.weight,
20243 line_height: relative(settings.buffer_line_height.value()),
20244 ..Default::default()
20245 };
20246 EditorElement::new(
20247 &self.prompt,
20248 EditorStyle {
20249 background: cx.theme().colors().editor_background,
20250 local_player: cx.theme().players().local(),
20251 text: text_style,
20252 ..Default::default()
20253 },
20254 )
20255 }
20256}
20257
20258impl Render for BreakpointPromptEditor {
20259 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20260 let gutter_dimensions = *self.gutter_dimensions.lock();
20261 h_flex()
20262 .key_context("Editor")
20263 .bg(cx.theme().colors().editor_background)
20264 .border_y_1()
20265 .border_color(cx.theme().status().info_border)
20266 .size_full()
20267 .py(window.line_height() / 2.5)
20268 .on_action(cx.listener(Self::confirm))
20269 .on_action(cx.listener(Self::cancel))
20270 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20271 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20272 }
20273}
20274
20275impl Focusable for BreakpointPromptEditor {
20276 fn focus_handle(&self, cx: &App) -> FocusHandle {
20277 self.prompt.focus_handle(cx)
20278 }
20279}
20280
20281fn all_edits_insertions_or_deletions(
20282 edits: &Vec<(Range<Anchor>, String)>,
20283 snapshot: &MultiBufferSnapshot,
20284) -> bool {
20285 let mut all_insertions = true;
20286 let mut all_deletions = true;
20287
20288 for (range, new_text) in edits.iter() {
20289 let range_is_empty = range.to_offset(&snapshot).is_empty();
20290 let text_is_empty = new_text.is_empty();
20291
20292 if range_is_empty != text_is_empty {
20293 if range_is_empty {
20294 all_deletions = false;
20295 } else {
20296 all_insertions = false;
20297 }
20298 } else {
20299 return false;
20300 }
20301
20302 if !all_insertions && !all_deletions {
20303 return false;
20304 }
20305 }
20306 all_insertions || all_deletions
20307}
20308
20309struct MissingEditPredictionKeybindingTooltip;
20310
20311impl Render for MissingEditPredictionKeybindingTooltip {
20312 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20313 ui::tooltip_container(window, cx, |container, _, cx| {
20314 container
20315 .flex_shrink_0()
20316 .max_w_80()
20317 .min_h(rems_from_px(124.))
20318 .justify_between()
20319 .child(
20320 v_flex()
20321 .flex_1()
20322 .text_ui_sm(cx)
20323 .child(Label::new("Conflict with Accept Keybinding"))
20324 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20325 )
20326 .child(
20327 h_flex()
20328 .pb_1()
20329 .gap_1()
20330 .items_end()
20331 .w_full()
20332 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20333 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20334 }))
20335 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20336 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20337 })),
20338 )
20339 })
20340 }
20341}
20342
20343#[derive(Debug, Clone, Copy, PartialEq)]
20344pub struct LineHighlight {
20345 pub background: Background,
20346 pub border: Option<gpui::Hsla>,
20347}
20348
20349impl From<Hsla> for LineHighlight {
20350 fn from(hsla: Hsla) -> Self {
20351 Self {
20352 background: hsla.into(),
20353 border: None,
20354 }
20355 }
20356}
20357
20358impl From<Background> for LineHighlight {
20359 fn from(background: Background) -> Self {
20360 Self {
20361 background,
20362 border: None,
20363 }
20364 }
20365}
20366
20367fn render_diff_hunk_controls(
20368 row: u32,
20369 status: &DiffHunkStatus,
20370 hunk_range: Range<Anchor>,
20371 is_created_file: bool,
20372 line_height: Pixels,
20373 editor: &Entity<Editor>,
20374 _window: &mut Window,
20375 cx: &mut App,
20376) -> AnyElement {
20377 h_flex()
20378 .h(line_height)
20379 .mr_1()
20380 .gap_1()
20381 .px_0p5()
20382 .pb_1()
20383 .border_x_1()
20384 .border_b_1()
20385 .border_color(cx.theme().colors().border_variant)
20386 .rounded_b_lg()
20387 .bg(cx.theme().colors().editor_background)
20388 .gap_1()
20389 .occlude()
20390 .shadow_md()
20391 .child(if status.has_secondary_hunk() {
20392 Button::new(("stage", row as u64), "Stage")
20393 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20394 .tooltip({
20395 let focus_handle = editor.focus_handle(cx);
20396 move |window, cx| {
20397 Tooltip::for_action_in(
20398 "Stage Hunk",
20399 &::git::ToggleStaged,
20400 &focus_handle,
20401 window,
20402 cx,
20403 )
20404 }
20405 })
20406 .on_click({
20407 let editor = editor.clone();
20408 move |_event, _window, cx| {
20409 editor.update(cx, |editor, cx| {
20410 editor.stage_or_unstage_diff_hunks(
20411 true,
20412 vec![hunk_range.start..hunk_range.start],
20413 cx,
20414 );
20415 });
20416 }
20417 })
20418 } else {
20419 Button::new(("unstage", row as u64), "Unstage")
20420 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20421 .tooltip({
20422 let focus_handle = editor.focus_handle(cx);
20423 move |window, cx| {
20424 Tooltip::for_action_in(
20425 "Unstage Hunk",
20426 &::git::ToggleStaged,
20427 &focus_handle,
20428 window,
20429 cx,
20430 )
20431 }
20432 })
20433 .on_click({
20434 let editor = editor.clone();
20435 move |_event, _window, cx| {
20436 editor.update(cx, |editor, cx| {
20437 editor.stage_or_unstage_diff_hunks(
20438 false,
20439 vec![hunk_range.start..hunk_range.start],
20440 cx,
20441 );
20442 });
20443 }
20444 })
20445 })
20446 .child(
20447 Button::new(("restore", row as u64), "Restore")
20448 .tooltip({
20449 let focus_handle = editor.focus_handle(cx);
20450 move |window, cx| {
20451 Tooltip::for_action_in(
20452 "Restore Hunk",
20453 &::git::Restore,
20454 &focus_handle,
20455 window,
20456 cx,
20457 )
20458 }
20459 })
20460 .on_click({
20461 let editor = editor.clone();
20462 move |_event, window, cx| {
20463 editor.update(cx, |editor, cx| {
20464 let snapshot = editor.snapshot(window, cx);
20465 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20466 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20467 });
20468 }
20469 })
20470 .disabled(is_created_file),
20471 )
20472 .when(
20473 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20474 |el| {
20475 el.child(
20476 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20477 .shape(IconButtonShape::Square)
20478 .icon_size(IconSize::Small)
20479 // .disabled(!has_multiple_hunks)
20480 .tooltip({
20481 let focus_handle = editor.focus_handle(cx);
20482 move |window, cx| {
20483 Tooltip::for_action_in(
20484 "Next Hunk",
20485 &GoToHunk,
20486 &focus_handle,
20487 window,
20488 cx,
20489 )
20490 }
20491 })
20492 .on_click({
20493 let editor = editor.clone();
20494 move |_event, window, cx| {
20495 editor.update(cx, |editor, cx| {
20496 let snapshot = editor.snapshot(window, cx);
20497 let position =
20498 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20499 editor.go_to_hunk_before_or_after_position(
20500 &snapshot,
20501 position,
20502 Direction::Next,
20503 window,
20504 cx,
20505 );
20506 editor.expand_selected_diff_hunks(cx);
20507 });
20508 }
20509 }),
20510 )
20511 .child(
20512 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20513 .shape(IconButtonShape::Square)
20514 .icon_size(IconSize::Small)
20515 // .disabled(!has_multiple_hunks)
20516 .tooltip({
20517 let focus_handle = editor.focus_handle(cx);
20518 move |window, cx| {
20519 Tooltip::for_action_in(
20520 "Previous Hunk",
20521 &GoToPreviousHunk,
20522 &focus_handle,
20523 window,
20524 cx,
20525 )
20526 }
20527 })
20528 .on_click({
20529 let editor = editor.clone();
20530 move |_event, window, cx| {
20531 editor.update(cx, |editor, cx| {
20532 let snapshot = editor.snapshot(window, cx);
20533 let point =
20534 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20535 editor.go_to_hunk_before_or_after_position(
20536 &snapshot,
20537 point,
20538 Direction::Prev,
20539 window,
20540 cx,
20541 );
20542 editor.expand_selected_diff_hunks(cx);
20543 });
20544 }
20545 }),
20546 )
20547 },
20548 )
20549 .into_any_element()
20550}