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, LspInsertMode, RewrapBehavior, WordsCompletionMode,
113 all_language_settings, 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, RunnableTag, TaskTemplate, TaskVariables};
135
136pub use lsp::CompletionContext;
137use lsp::{
138 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
139 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
140};
141
142use language::BufferSnapshot;
143pub use lsp_ext::lsp_tasks;
144use movement::TextLayoutDetails;
145pub use multi_buffer::{
146 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
147 ToOffset, ToPoint,
148};
149use multi_buffer::{
150 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
151 MultiOrSingleBufferOffsetRange, PathKey, ToOffsetUtf16,
152};
153use parking_lot::Mutex;
154use project::{
155 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
156 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
157 TaskSourceKind,
158 debugger::breakpoint_store::Breakpoint,
159 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
160 project_settings::{GitGutterSetting, ProjectSettings},
161};
162use rand::prelude::*;
163use rpc::{ErrorExt, proto::*};
164use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
165use selections_collection::{
166 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
167};
168use serde::{Deserialize, Serialize};
169use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
170use smallvec::SmallVec;
171use snippet::Snippet;
172use std::sync::Arc;
173use std::{
174 any::TypeId,
175 borrow::Cow,
176 cell::RefCell,
177 cmp::{self, Ordering, Reverse},
178 mem,
179 num::NonZeroU32,
180 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
181 path::{Path, PathBuf},
182 rc::Rc,
183 time::{Duration, Instant},
184};
185pub use sum_tree::Bias;
186use sum_tree::TreeMap;
187use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
188use theme::{
189 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
190 observe_buffer_font_size_adjustment,
191};
192use ui::{
193 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
194 IconSize, Key, Tooltip, h_flex, prelude::*,
195};
196use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
197use workspace::{
198 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
199 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
200 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
201 item::{ItemHandle, PreviewTabsSettings},
202 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
203 searchable::SearchEvent,
204};
205
206use crate::hover_links::{find_url, find_url_from_range};
207use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
208
209pub const FILE_HEADER_HEIGHT: u32 = 2;
210pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
211pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
212const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
213const MAX_LINE_LEN: usize = 1024;
214const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
215const MAX_SELECTION_HISTORY_LEN: usize = 1024;
216pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
217#[doc(hidden)]
218pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
219
220pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
221pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
222pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
223
224pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
225pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
226pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
227
228pub type RenderDiffHunkControlsFn = Arc<
229 dyn Fn(
230 u32,
231 &DiffHunkStatus,
232 Range<Anchor>,
233 bool,
234 Pixels,
235 &Entity<Editor>,
236 &mut Window,
237 &mut App,
238 ) -> AnyElement,
239>;
240
241const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
242 alt: true,
243 shift: true,
244 control: false,
245 platform: false,
246 function: false,
247};
248
249#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
250pub enum InlayId {
251 InlineCompletion(usize),
252 Hint(usize),
253}
254
255impl InlayId {
256 fn id(&self) -> usize {
257 match self {
258 Self::InlineCompletion(id) => *id,
259 Self::Hint(id) => *id,
260 }
261 }
262}
263
264pub enum DebugCurrentRowHighlight {}
265enum DocumentHighlightRead {}
266enum DocumentHighlightWrite {}
267enum InputComposition {}
268enum SelectedTextHighlight {}
269
270#[derive(Debug, Copy, Clone, PartialEq, Eq)]
271pub enum Navigated {
272 Yes,
273 No,
274}
275
276impl Navigated {
277 pub fn from_bool(yes: bool) -> Navigated {
278 if yes { Navigated::Yes } else { Navigated::No }
279 }
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
283enum DisplayDiffHunk {
284 Folded {
285 display_row: DisplayRow,
286 },
287 Unfolded {
288 is_created_file: bool,
289 diff_base_byte_range: Range<usize>,
290 display_row_range: Range<DisplayRow>,
291 multi_buffer_range: Range<Anchor>,
292 status: DiffHunkStatus,
293 },
294}
295
296pub enum HideMouseCursorOrigin {
297 TypingAction,
298 MovementAction,
299}
300
301pub fn init_settings(cx: &mut App) {
302 EditorSettings::register(cx);
303}
304
305pub fn init(cx: &mut App) {
306 init_settings(cx);
307
308 cx.set_global(GlobalBlameRenderer(Arc::new(())));
309
310 workspace::register_project_item::<Editor>(cx);
311 workspace::FollowableViewRegistry::register::<Editor>(cx);
312 workspace::register_serializable_item::<Editor>(cx);
313
314 cx.observe_new(
315 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
316 workspace.register_action(Editor::new_file);
317 workspace.register_action(Editor::new_file_vertical);
318 workspace.register_action(Editor::new_file_horizontal);
319 workspace.register_action(Editor::cancel_language_server_work);
320 },
321 )
322 .detach();
323
324 cx.on_action(move |_: &workspace::NewFile, cx| {
325 let app_state = workspace::AppState::global(cx);
326 if let Some(app_state) = app_state.upgrade() {
327 workspace::open_new(
328 Default::default(),
329 app_state,
330 cx,
331 |workspace, window, cx| {
332 Editor::new_file(workspace, &Default::default(), window, cx)
333 },
334 )
335 .detach();
336 }
337 });
338 cx.on_action(move |_: &workspace::NewWindow, cx| {
339 let app_state = workspace::AppState::global(cx);
340 if let Some(app_state) = app_state.upgrade() {
341 workspace::open_new(
342 Default::default(),
343 app_state,
344 cx,
345 |workspace, window, cx| {
346 cx.activate(true);
347 Editor::new_file(workspace, &Default::default(), window, cx)
348 },
349 )
350 .detach();
351 }
352 });
353}
354
355pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
356 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
357}
358
359pub struct SearchWithinRange;
360
361trait InvalidationRegion {
362 fn ranges(&self) -> &[Range<Anchor>];
363}
364
365#[derive(Clone, Debug, PartialEq)]
366pub enum SelectPhase {
367 Begin {
368 position: DisplayPoint,
369 add: bool,
370 click_count: usize,
371 },
372 BeginColumnar {
373 position: DisplayPoint,
374 reset: bool,
375 goal_column: u32,
376 },
377 Extend {
378 position: DisplayPoint,
379 click_count: usize,
380 },
381 Update {
382 position: DisplayPoint,
383 goal_column: u32,
384 scroll_delta: gpui::Point<f32>,
385 },
386 End,
387}
388
389#[derive(Clone, Debug)]
390pub enum SelectMode {
391 Character,
392 Word(Range<Anchor>),
393 Line(Range<Anchor>),
394 All,
395}
396
397#[derive(Copy, Clone, PartialEq, Eq, Debug)]
398pub enum EditorMode {
399 SingleLine { auto_width: bool },
400 AutoHeight { max_lines: usize },
401 Full,
402}
403
404impl EditorMode {
405 pub fn full() -> Self {
406 Self::Full
407 }
408
409 pub fn is_full(&self) -> bool {
410 matches!(self, Self::Full { .. })
411 }
412}
413
414#[derive(Copy, Clone, Debug)]
415pub enum SoftWrap {
416 /// Prefer not to wrap at all.
417 ///
418 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
419 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
420 GitDiff,
421 /// Prefer a single line generally, unless an overly long line is encountered.
422 None,
423 /// Soft wrap lines that exceed the editor width.
424 EditorWidth,
425 /// Soft wrap lines at the preferred line length.
426 Column(u32),
427 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
428 Bounded(u32),
429}
430
431#[derive(Clone)]
432pub struct EditorStyle {
433 pub background: Hsla,
434 pub local_player: PlayerColor,
435 pub text: TextStyle,
436 pub scrollbar_width: Pixels,
437 pub syntax: Arc<SyntaxTheme>,
438 pub status: StatusColors,
439 pub inlay_hints_style: HighlightStyle,
440 pub inline_completion_styles: InlineCompletionStyles,
441 pub unnecessary_code_fade: f32,
442}
443
444impl Default for EditorStyle {
445 fn default() -> Self {
446 Self {
447 background: Hsla::default(),
448 local_player: PlayerColor::default(),
449 text: TextStyle::default(),
450 scrollbar_width: Pixels::default(),
451 syntax: Default::default(),
452 // HACK: Status colors don't have a real default.
453 // We should look into removing the status colors from the editor
454 // style and retrieve them directly from the theme.
455 status: StatusColors::dark(),
456 inlay_hints_style: HighlightStyle::default(),
457 inline_completion_styles: InlineCompletionStyles {
458 insertion: HighlightStyle::default(),
459 whitespace: HighlightStyle::default(),
460 },
461 unnecessary_code_fade: Default::default(),
462 }
463 }
464}
465
466pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
467 let show_background = language_settings::language_settings(None, None, cx)
468 .inlay_hints
469 .show_background;
470
471 HighlightStyle {
472 color: Some(cx.theme().status().hint),
473 background_color: show_background.then(|| cx.theme().status().hint_background),
474 ..HighlightStyle::default()
475 }
476}
477
478pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
479 InlineCompletionStyles {
480 insertion: HighlightStyle {
481 color: Some(cx.theme().status().predictive),
482 ..HighlightStyle::default()
483 },
484 whitespace: HighlightStyle {
485 background_color: Some(cx.theme().status().created_background),
486 ..HighlightStyle::default()
487 },
488 }
489}
490
491type CompletionId = usize;
492
493pub(crate) enum EditDisplayMode {
494 TabAccept,
495 DiffPopover,
496 Inline,
497}
498
499enum InlineCompletion {
500 Edit {
501 edits: Vec<(Range<Anchor>, String)>,
502 edit_preview: Option<EditPreview>,
503 display_mode: EditDisplayMode,
504 snapshot: BufferSnapshot,
505 },
506 Move {
507 target: Anchor,
508 snapshot: BufferSnapshot,
509 },
510}
511
512struct InlineCompletionState {
513 inlay_ids: Vec<InlayId>,
514 completion: InlineCompletion,
515 completion_id: Option<SharedString>,
516 invalidation_range: Range<Anchor>,
517}
518
519enum EditPredictionSettings {
520 Disabled,
521 Enabled {
522 show_in_menu: bool,
523 preview_requires_modifier: bool,
524 },
525}
526
527enum InlineCompletionHighlight {}
528
529#[derive(Debug, Clone)]
530struct InlineDiagnostic {
531 message: SharedString,
532 group_id: usize,
533 is_primary: bool,
534 start: Point,
535 severity: DiagnosticSeverity,
536}
537
538pub enum MenuInlineCompletionsPolicy {
539 Never,
540 ByProvider,
541}
542
543pub enum EditPredictionPreview {
544 /// Modifier is not pressed
545 Inactive { released_too_fast: bool },
546 /// Modifier pressed
547 Active {
548 since: Instant,
549 previous_scroll_position: Option<ScrollAnchor>,
550 },
551}
552
553impl EditPredictionPreview {
554 pub fn released_too_fast(&self) -> bool {
555 match self {
556 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
557 EditPredictionPreview::Active { .. } => false,
558 }
559 }
560
561 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
562 if let EditPredictionPreview::Active {
563 previous_scroll_position,
564 ..
565 } = self
566 {
567 *previous_scroll_position = scroll_position;
568 }
569 }
570}
571
572pub struct ContextMenuOptions {
573 pub min_entries_visible: usize,
574 pub max_entries_visible: usize,
575 pub placement: Option<ContextMenuPlacement>,
576}
577
578#[derive(Debug, Clone, PartialEq, Eq)]
579pub enum ContextMenuPlacement {
580 Above,
581 Below,
582}
583
584#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
585struct EditorActionId(usize);
586
587impl EditorActionId {
588 pub fn post_inc(&mut self) -> Self {
589 let answer = self.0;
590
591 *self = Self(answer + 1);
592
593 Self(answer)
594 }
595}
596
597// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
598// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
599
600type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
601type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
602
603#[derive(Default)]
604struct ScrollbarMarkerState {
605 scrollbar_size: Size<Pixels>,
606 dirty: bool,
607 markers: Arc<[PaintQuad]>,
608 pending_refresh: Option<Task<Result<()>>>,
609}
610
611impl ScrollbarMarkerState {
612 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
613 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
614 }
615}
616
617#[derive(Clone, Debug)]
618struct RunnableTasks {
619 templates: Vec<(TaskSourceKind, TaskTemplate)>,
620 offset: multi_buffer::Anchor,
621 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
622 column: u32,
623 // Values of all named captures, including those starting with '_'
624 extra_variables: HashMap<String, String>,
625 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
626 context_range: Range<BufferOffset>,
627}
628
629impl RunnableTasks {
630 fn resolve<'a>(
631 &'a self,
632 cx: &'a task::TaskContext,
633 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
634 self.templates.iter().filter_map(|(kind, template)| {
635 template
636 .resolve_task(&kind.to_id_base(), cx)
637 .map(|task| (kind.clone(), task))
638 })
639 }
640}
641
642#[derive(Clone)]
643struct ResolvedTasks {
644 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
645 position: Anchor,
646}
647
648#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
649struct BufferOffset(usize);
650
651// Addons allow storing per-editor state in other crates (e.g. Vim)
652pub trait Addon: 'static {
653 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
654
655 fn render_buffer_header_controls(
656 &self,
657 _: &ExcerptInfo,
658 _: &Window,
659 _: &App,
660 ) -> Option<AnyElement> {
661 None
662 }
663
664 fn to_any(&self) -> &dyn std::any::Any;
665}
666
667/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
668///
669/// See the [module level documentation](self) for more information.
670pub struct Editor {
671 focus_handle: FocusHandle,
672 last_focused_descendant: Option<WeakFocusHandle>,
673 /// The text buffer being edited
674 buffer: Entity<MultiBuffer>,
675 /// Map of how text in the buffer should be displayed.
676 /// Handles soft wraps, folds, fake inlay text insertions, etc.
677 pub display_map: Entity<DisplayMap>,
678 pub selections: SelectionsCollection,
679 pub scroll_manager: ScrollManager,
680 /// When inline assist editors are linked, they all render cursors because
681 /// typing enters text into each of them, even the ones that aren't focused.
682 pub(crate) show_cursor_when_unfocused: bool,
683 columnar_selection_tail: Option<Anchor>,
684 add_selections_state: Option<AddSelectionsState>,
685 select_next_state: Option<SelectNextState>,
686 select_prev_state: Option<SelectNextState>,
687 selection_history: SelectionHistory,
688 autoclose_regions: Vec<AutocloseRegion>,
689 snippet_stack: InvalidationStack<SnippetState>,
690 select_syntax_node_history: SelectSyntaxNodeHistory,
691 ime_transaction: Option<TransactionId>,
692 active_diagnostics: Option<ActiveDiagnosticGroup>,
693 show_inline_diagnostics: bool,
694 inline_diagnostics_update: Task<()>,
695 inline_diagnostics_enabled: bool,
696 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
697 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
698 hard_wrap: Option<usize>,
699
700 // TODO: make this a access method
701 pub project: Option<Entity<Project>>,
702 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
703 completion_provider: Option<Box<dyn CompletionProvider>>,
704 collaboration_hub: Option<Box<dyn CollaborationHub>>,
705 blink_manager: Entity<BlinkManager>,
706 show_cursor_names: bool,
707 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
708 pub show_local_selections: bool,
709 mode: EditorMode,
710 show_breadcrumbs: bool,
711 show_gutter: bool,
712 show_scrollbars: bool,
713 show_line_numbers: Option<bool>,
714 use_relative_line_numbers: Option<bool>,
715 show_git_diff_gutter: Option<bool>,
716 show_code_actions: Option<bool>,
717 show_runnables: Option<bool>,
718 show_breakpoints: Option<bool>,
719 show_wrap_guides: Option<bool>,
720 show_indent_guides: Option<bool>,
721 placeholder_text: Option<Arc<str>>,
722 highlight_order: usize,
723 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
724 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
725 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
726 scrollbar_marker_state: ScrollbarMarkerState,
727 active_indent_guides_state: ActiveIndentGuidesState,
728 nav_history: Option<ItemNavHistory>,
729 context_menu: RefCell<Option<CodeContextMenu>>,
730 context_menu_options: Option<ContextMenuOptions>,
731 mouse_context_menu: Option<MouseContextMenu>,
732 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
733 signature_help_state: SignatureHelpState,
734 auto_signature_help: Option<bool>,
735 find_all_references_task_sources: Vec<Anchor>,
736 next_completion_id: CompletionId,
737 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
738 code_actions_task: Option<Task<Result<()>>>,
739 selection_highlight_task: Option<Task<()>>,
740 document_highlights_task: Option<Task<()>>,
741 linked_editing_range_task: Option<Task<Option<()>>>,
742 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
743 pending_rename: Option<RenameState>,
744 searchable: bool,
745 cursor_shape: CursorShape,
746 current_line_highlight: Option<CurrentLineHighlight>,
747 collapse_matches: bool,
748 autoindent_mode: Option<AutoindentMode>,
749 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
750 input_enabled: bool,
751 use_modal_editing: bool,
752 read_only: bool,
753 leader_peer_id: Option<PeerId>,
754 remote_id: Option<ViewId>,
755 hover_state: HoverState,
756 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
757 gutter_hovered: bool,
758 hovered_link_state: Option<HoveredLinkState>,
759 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
760 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
761 active_inline_completion: Option<InlineCompletionState>,
762 /// Used to prevent flickering as the user types while the menu is open
763 stale_inline_completion_in_menu: Option<InlineCompletionState>,
764 edit_prediction_settings: EditPredictionSettings,
765 inline_completions_hidden_for_vim_mode: bool,
766 show_inline_completions_override: Option<bool>,
767 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
768 edit_prediction_preview: EditPredictionPreview,
769 edit_prediction_indent_conflict: bool,
770 edit_prediction_requires_modifier_in_indent_conflict: bool,
771 inlay_hint_cache: InlayHintCache,
772 next_inlay_id: usize,
773 _subscriptions: Vec<Subscription>,
774 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
775 gutter_dimensions: GutterDimensions,
776 style: Option<EditorStyle>,
777 text_style_refinement: Option<TextStyleRefinement>,
778 next_editor_action_id: EditorActionId,
779 editor_actions:
780 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
781 use_autoclose: bool,
782 use_auto_surround: bool,
783 auto_replace_emoji_shortcode: bool,
784 jsx_tag_auto_close_enabled_in_any_buffer: bool,
785 show_git_blame_gutter: bool,
786 show_git_blame_inline: bool,
787 show_git_blame_inline_delay_task: Option<Task<()>>,
788 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
789 git_blame_inline_enabled: bool,
790 render_diff_hunk_controls: RenderDiffHunkControlsFn,
791 serialize_dirty_buffers: bool,
792 show_selection_menu: Option<bool>,
793 blame: Option<Entity<GitBlame>>,
794 blame_subscription: Option<Subscription>,
795 custom_context_menu: Option<
796 Box<
797 dyn 'static
798 + Fn(
799 &mut Self,
800 DisplayPoint,
801 &mut Window,
802 &mut Context<Self>,
803 ) -> Option<Entity<ui::ContextMenu>>,
804 >,
805 >,
806 last_bounds: Option<Bounds<Pixels>>,
807 last_position_map: Option<Rc<PositionMap>>,
808 expect_bounds_change: Option<Bounds<Pixels>>,
809 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
810 tasks_update_task: Option<Task<()>>,
811 breakpoint_store: Option<Entity<BreakpointStore>>,
812 /// Allow's a user to create a breakpoint by selecting this indicator
813 /// It should be None while a user is not hovering over the gutter
814 /// Otherwise it represents the point that the breakpoint will be shown
815 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
816 in_project_search: bool,
817 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
818 breadcrumb_header: Option<String>,
819 focused_block: Option<FocusedBlock>,
820 next_scroll_position: NextScrollCursorCenterTopBottom,
821 addons: HashMap<TypeId, Box<dyn Addon>>,
822 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
823 load_diff_task: Option<Shared<Task<()>>>,
824 selection_mark_mode: bool,
825 toggle_fold_multiple_buffers: Task<()>,
826 _scroll_cursor_center_top_bottom_task: Task<()>,
827 serialize_selections: Task<()>,
828 serialize_folds: Task<()>,
829 mouse_cursor_hidden: bool,
830 hide_mouse_mode: HideMouseMode,
831}
832
833#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
834enum NextScrollCursorCenterTopBottom {
835 #[default]
836 Center,
837 Top,
838 Bottom,
839}
840
841impl NextScrollCursorCenterTopBottom {
842 fn next(&self) -> Self {
843 match self {
844 Self::Center => Self::Top,
845 Self::Top => Self::Bottom,
846 Self::Bottom => Self::Center,
847 }
848 }
849}
850
851#[derive(Clone)]
852pub struct EditorSnapshot {
853 pub mode: EditorMode,
854 show_gutter: bool,
855 show_line_numbers: Option<bool>,
856 show_git_diff_gutter: Option<bool>,
857 show_code_actions: Option<bool>,
858 show_runnables: Option<bool>,
859 show_breakpoints: Option<bool>,
860 git_blame_gutter_max_author_length: Option<usize>,
861 pub display_snapshot: DisplaySnapshot,
862 pub placeholder_text: Option<Arc<str>>,
863 is_focused: bool,
864 scroll_anchor: ScrollAnchor,
865 ongoing_scroll: OngoingScroll,
866 current_line_highlight: CurrentLineHighlight,
867 gutter_hovered: bool,
868}
869
870#[derive(Default, Debug, Clone, Copy)]
871pub struct GutterDimensions {
872 pub left_padding: Pixels,
873 pub right_padding: Pixels,
874 pub width: Pixels,
875 pub margin: Pixels,
876 pub git_blame_entries_width: Option<Pixels>,
877}
878
879impl GutterDimensions {
880 /// The full width of the space taken up by the gutter.
881 pub fn full_width(&self) -> Pixels {
882 self.margin + self.width
883 }
884
885 /// The width of the space reserved for the fold indicators,
886 /// use alongside 'justify_end' and `gutter_width` to
887 /// right align content with the line numbers
888 pub fn fold_area_width(&self) -> Pixels {
889 self.margin + self.right_padding
890 }
891}
892
893#[derive(Debug)]
894pub struct RemoteSelection {
895 pub replica_id: ReplicaId,
896 pub selection: Selection<Anchor>,
897 pub cursor_shape: CursorShape,
898 pub peer_id: PeerId,
899 pub line_mode: bool,
900 pub participant_index: Option<ParticipantIndex>,
901 pub user_name: Option<SharedString>,
902}
903
904#[derive(Clone, Debug)]
905struct SelectionHistoryEntry {
906 selections: Arc<[Selection<Anchor>]>,
907 select_next_state: Option<SelectNextState>,
908 select_prev_state: Option<SelectNextState>,
909 add_selections_state: Option<AddSelectionsState>,
910}
911
912enum SelectionHistoryMode {
913 Normal,
914 Undoing,
915 Redoing,
916}
917
918#[derive(Clone, PartialEq, Eq, Hash)]
919struct HoveredCursor {
920 replica_id: u16,
921 selection_id: usize,
922}
923
924impl Default for SelectionHistoryMode {
925 fn default() -> Self {
926 Self::Normal
927 }
928}
929
930#[derive(Default)]
931struct SelectionHistory {
932 #[allow(clippy::type_complexity)]
933 selections_by_transaction:
934 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
935 mode: SelectionHistoryMode,
936 undo_stack: VecDeque<SelectionHistoryEntry>,
937 redo_stack: VecDeque<SelectionHistoryEntry>,
938}
939
940impl SelectionHistory {
941 fn insert_transaction(
942 &mut self,
943 transaction_id: TransactionId,
944 selections: Arc<[Selection<Anchor>]>,
945 ) {
946 self.selections_by_transaction
947 .insert(transaction_id, (selections, None));
948 }
949
950 #[allow(clippy::type_complexity)]
951 fn transaction(
952 &self,
953 transaction_id: TransactionId,
954 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
955 self.selections_by_transaction.get(&transaction_id)
956 }
957
958 #[allow(clippy::type_complexity)]
959 fn transaction_mut(
960 &mut self,
961 transaction_id: TransactionId,
962 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
963 self.selections_by_transaction.get_mut(&transaction_id)
964 }
965
966 fn push(&mut self, entry: SelectionHistoryEntry) {
967 if !entry.selections.is_empty() {
968 match self.mode {
969 SelectionHistoryMode::Normal => {
970 self.push_undo(entry);
971 self.redo_stack.clear();
972 }
973 SelectionHistoryMode::Undoing => self.push_redo(entry),
974 SelectionHistoryMode::Redoing => self.push_undo(entry),
975 }
976 }
977 }
978
979 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
980 if self
981 .undo_stack
982 .back()
983 .map_or(true, |e| e.selections != entry.selections)
984 {
985 self.undo_stack.push_back(entry);
986 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
987 self.undo_stack.pop_front();
988 }
989 }
990 }
991
992 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
993 if self
994 .redo_stack
995 .back()
996 .map_or(true, |e| e.selections != entry.selections)
997 {
998 self.redo_stack.push_back(entry);
999 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1000 self.redo_stack.pop_front();
1001 }
1002 }
1003 }
1004}
1005
1006struct RowHighlight {
1007 index: usize,
1008 range: Range<Anchor>,
1009 color: Hsla,
1010 should_autoscroll: bool,
1011}
1012
1013#[derive(Clone, Debug)]
1014struct AddSelectionsState {
1015 above: bool,
1016 stack: Vec<usize>,
1017}
1018
1019#[derive(Clone)]
1020struct SelectNextState {
1021 query: AhoCorasick,
1022 wordwise: bool,
1023 done: bool,
1024}
1025
1026impl std::fmt::Debug for SelectNextState {
1027 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1028 f.debug_struct(std::any::type_name::<Self>())
1029 .field("wordwise", &self.wordwise)
1030 .field("done", &self.done)
1031 .finish()
1032 }
1033}
1034
1035#[derive(Debug)]
1036struct AutocloseRegion {
1037 selection_id: usize,
1038 range: Range<Anchor>,
1039 pair: BracketPair,
1040}
1041
1042#[derive(Debug)]
1043struct SnippetState {
1044 ranges: Vec<Vec<Range<Anchor>>>,
1045 active_index: usize,
1046 choices: Vec<Option<Vec<String>>>,
1047}
1048
1049#[doc(hidden)]
1050pub struct RenameState {
1051 pub range: Range<Anchor>,
1052 pub old_name: Arc<str>,
1053 pub editor: Entity<Editor>,
1054 block_id: CustomBlockId,
1055}
1056
1057struct InvalidationStack<T>(Vec<T>);
1058
1059struct RegisteredInlineCompletionProvider {
1060 provider: Arc<dyn InlineCompletionProviderHandle>,
1061 _subscription: Subscription,
1062}
1063
1064#[derive(Debug, PartialEq, Eq)]
1065struct ActiveDiagnosticGroup {
1066 primary_range: Range<Anchor>,
1067 primary_message: String,
1068 group_id: usize,
1069 blocks: HashMap<CustomBlockId, Diagnostic>,
1070 is_valid: bool,
1071}
1072
1073#[derive(Serialize, Deserialize, Clone, Debug)]
1074pub struct ClipboardSelection {
1075 /// The number of bytes in this selection.
1076 pub len: usize,
1077 /// Whether this was a full-line selection.
1078 pub is_entire_line: bool,
1079 /// The indentation of the first line when this content was originally copied.
1080 pub first_line_indent: u32,
1081}
1082
1083// selections, scroll behavior, was newest selection reversed
1084type SelectSyntaxNodeHistoryState = (
1085 Box<[Selection<usize>]>,
1086 SelectSyntaxNodeScrollBehavior,
1087 bool,
1088);
1089
1090#[derive(Default)]
1091struct SelectSyntaxNodeHistory {
1092 stack: Vec<SelectSyntaxNodeHistoryState>,
1093 // disable temporarily to allow changing selections without losing the stack
1094 pub disable_clearing: bool,
1095}
1096
1097impl SelectSyntaxNodeHistory {
1098 pub fn try_clear(&mut self) {
1099 if !self.disable_clearing {
1100 self.stack.clear();
1101 }
1102 }
1103
1104 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1105 self.stack.push(selection);
1106 }
1107
1108 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1109 self.stack.pop()
1110 }
1111}
1112
1113enum SelectSyntaxNodeScrollBehavior {
1114 CursorTop,
1115 FitSelection,
1116 CursorBottom,
1117}
1118
1119#[derive(Debug)]
1120pub(crate) struct NavigationData {
1121 cursor_anchor: Anchor,
1122 cursor_position: Point,
1123 scroll_anchor: ScrollAnchor,
1124 scroll_top_row: u32,
1125}
1126
1127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1128pub enum GotoDefinitionKind {
1129 Symbol,
1130 Declaration,
1131 Type,
1132 Implementation,
1133}
1134
1135#[derive(Debug, Clone)]
1136enum InlayHintRefreshReason {
1137 ModifiersChanged(bool),
1138 Toggle(bool),
1139 SettingsChange(InlayHintSettings),
1140 NewLinesShown,
1141 BufferEdited(HashSet<Arc<Language>>),
1142 RefreshRequested,
1143 ExcerptsRemoved(Vec<ExcerptId>),
1144}
1145
1146impl InlayHintRefreshReason {
1147 fn description(&self) -> &'static str {
1148 match self {
1149 Self::ModifiersChanged(_) => "modifiers changed",
1150 Self::Toggle(_) => "toggle",
1151 Self::SettingsChange(_) => "settings change",
1152 Self::NewLinesShown => "new lines shown",
1153 Self::BufferEdited(_) => "buffer edited",
1154 Self::RefreshRequested => "refresh requested",
1155 Self::ExcerptsRemoved(_) => "excerpts removed",
1156 }
1157 }
1158}
1159
1160pub enum FormatTarget {
1161 Buffers,
1162 Ranges(Vec<Range<MultiBufferPoint>>),
1163}
1164
1165pub(crate) struct FocusedBlock {
1166 id: BlockId,
1167 focus_handle: WeakFocusHandle,
1168}
1169
1170#[derive(Clone)]
1171enum JumpData {
1172 MultiBufferRow {
1173 row: MultiBufferRow,
1174 line_offset_from_top: u32,
1175 },
1176 MultiBufferPoint {
1177 excerpt_id: ExcerptId,
1178 position: Point,
1179 anchor: text::Anchor,
1180 line_offset_from_top: u32,
1181 },
1182}
1183
1184pub enum MultibufferSelectionMode {
1185 First,
1186 All,
1187}
1188
1189#[derive(Clone, Copy, Debug, Default)]
1190pub struct RewrapOptions {
1191 pub override_language_settings: bool,
1192 pub preserve_existing_whitespace: bool,
1193}
1194
1195impl Editor {
1196 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1197 let buffer = cx.new(|cx| Buffer::local("", cx));
1198 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1199 Self::new(
1200 EditorMode::SingleLine { auto_width: false },
1201 buffer,
1202 None,
1203 window,
1204 cx,
1205 )
1206 }
1207
1208 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1209 let buffer = cx.new(|cx| Buffer::local("", cx));
1210 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1211 Self::new(EditorMode::full(), buffer, None, window, cx)
1212 }
1213
1214 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1215 let buffer = cx.new(|cx| Buffer::local("", cx));
1216 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1217 Self::new(
1218 EditorMode::SingleLine { auto_width: true },
1219 buffer,
1220 None,
1221 window,
1222 cx,
1223 )
1224 }
1225
1226 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1227 let buffer = cx.new(|cx| Buffer::local("", cx));
1228 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1229 Self::new(
1230 EditorMode::AutoHeight { max_lines },
1231 buffer,
1232 None,
1233 window,
1234 cx,
1235 )
1236 }
1237
1238 pub fn for_buffer(
1239 buffer: Entity<Buffer>,
1240 project: Option<Entity<Project>>,
1241 window: &mut Window,
1242 cx: &mut Context<Self>,
1243 ) -> Self {
1244 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1245 Self::new(EditorMode::full(), buffer, project, window, cx)
1246 }
1247
1248 pub fn for_multibuffer(
1249 buffer: Entity<MultiBuffer>,
1250 project: Option<Entity<Project>>,
1251 window: &mut Window,
1252 cx: &mut Context<Self>,
1253 ) -> Self {
1254 Self::new(EditorMode::full(), buffer, project, window, cx)
1255 }
1256
1257 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1258 let mut clone = Self::new(
1259 self.mode,
1260 self.buffer.clone(),
1261 self.project.clone(),
1262 window,
1263 cx,
1264 );
1265 self.display_map.update(cx, |display_map, cx| {
1266 let snapshot = display_map.snapshot(cx);
1267 clone.display_map.update(cx, |display_map, cx| {
1268 display_map.set_state(&snapshot, cx);
1269 });
1270 });
1271 clone.folds_did_change(cx);
1272 clone.selections.clone_state(&self.selections);
1273 clone.scroll_manager.clone_state(&self.scroll_manager);
1274 clone.searchable = self.searchable;
1275 clone.read_only = self.read_only;
1276 clone
1277 }
1278
1279 pub fn new(
1280 mode: EditorMode,
1281 buffer: Entity<MultiBuffer>,
1282 project: Option<Entity<Project>>,
1283 window: &mut Window,
1284 cx: &mut Context<Self>,
1285 ) -> Self {
1286 let style = window.text_style();
1287 let font_size = style.font_size.to_pixels(window.rem_size());
1288 let editor = cx.entity().downgrade();
1289 let fold_placeholder = FoldPlaceholder {
1290 constrain_width: true,
1291 render: Arc::new(move |fold_id, fold_range, cx| {
1292 let editor = editor.clone();
1293 div()
1294 .id(fold_id)
1295 .bg(cx.theme().colors().ghost_element_background)
1296 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1297 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1298 .rounded_xs()
1299 .size_full()
1300 .cursor_pointer()
1301 .child("⋯")
1302 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1303 .on_click(move |_, _window, cx| {
1304 editor
1305 .update(cx, |editor, cx| {
1306 editor.unfold_ranges(
1307 &[fold_range.start..fold_range.end],
1308 true,
1309 false,
1310 cx,
1311 );
1312 cx.stop_propagation();
1313 })
1314 .ok();
1315 })
1316 .into_any()
1317 }),
1318 merge_adjacent: true,
1319 ..Default::default()
1320 };
1321 let display_map = cx.new(|cx| {
1322 DisplayMap::new(
1323 buffer.clone(),
1324 style.font(),
1325 font_size,
1326 None,
1327 FILE_HEADER_HEIGHT,
1328 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1329 fold_placeholder,
1330 cx,
1331 )
1332 });
1333
1334 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1335
1336 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1337
1338 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1339 .then(|| language_settings::SoftWrap::None);
1340
1341 let mut project_subscriptions = Vec::new();
1342 if mode.is_full() {
1343 if let Some(project) = project.as_ref() {
1344 project_subscriptions.push(cx.subscribe_in(
1345 project,
1346 window,
1347 |editor, _, event, window, cx| match event {
1348 project::Event::RefreshCodeLens => {
1349 // we always query lens with actions, without storing them, always refreshing them
1350 }
1351 project::Event::RefreshInlayHints => {
1352 editor
1353 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1354 }
1355 project::Event::SnippetEdit(id, snippet_edits) => {
1356 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1357 let focus_handle = editor.focus_handle(cx);
1358 if focus_handle.is_focused(window) {
1359 let snapshot = buffer.read(cx).snapshot();
1360 for (range, snippet) in snippet_edits {
1361 let editor_range =
1362 language::range_from_lsp(*range).to_offset(&snapshot);
1363 editor
1364 .insert_snippet(
1365 &[editor_range],
1366 snippet.clone(),
1367 window,
1368 cx,
1369 )
1370 .ok();
1371 }
1372 }
1373 }
1374 }
1375 _ => {}
1376 },
1377 ));
1378 if let Some(task_inventory) = project
1379 .read(cx)
1380 .task_store()
1381 .read(cx)
1382 .task_inventory()
1383 .cloned()
1384 {
1385 project_subscriptions.push(cx.observe_in(
1386 &task_inventory,
1387 window,
1388 |editor, _, window, cx| {
1389 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1390 },
1391 ));
1392 };
1393
1394 project_subscriptions.push(cx.subscribe_in(
1395 &project.read(cx).breakpoint_store(),
1396 window,
1397 |editor, _, event, window, cx| match event {
1398 BreakpointStoreEvent::ActiveDebugLineChanged => {
1399 if editor.go_to_active_debug_line(window, cx) {
1400 cx.stop_propagation();
1401 }
1402 }
1403 _ => {}
1404 },
1405 ));
1406 }
1407 }
1408
1409 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1410
1411 let inlay_hint_settings =
1412 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1413 let focus_handle = cx.focus_handle();
1414 cx.on_focus(&focus_handle, window, Self::handle_focus)
1415 .detach();
1416 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1417 .detach();
1418 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1419 .detach();
1420 cx.on_blur(&focus_handle, window, Self::handle_blur)
1421 .detach();
1422
1423 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1424 Some(false)
1425 } else {
1426 None
1427 };
1428
1429 let breakpoint_store = match (mode, project.as_ref()) {
1430 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1431 _ => None,
1432 };
1433
1434 let mut code_action_providers = Vec::new();
1435 let mut load_uncommitted_diff = None;
1436 if let Some(project) = project.clone() {
1437 load_uncommitted_diff = Some(
1438 get_uncommitted_diff_for_buffer(
1439 &project,
1440 buffer.read(cx).all_buffers(),
1441 buffer.clone(),
1442 cx,
1443 )
1444 .shared(),
1445 );
1446 code_action_providers.push(Rc::new(project) as Rc<_>);
1447 }
1448
1449 let mut this = Self {
1450 focus_handle,
1451 show_cursor_when_unfocused: false,
1452 last_focused_descendant: None,
1453 buffer: buffer.clone(),
1454 display_map: display_map.clone(),
1455 selections,
1456 scroll_manager: ScrollManager::new(cx),
1457 columnar_selection_tail: None,
1458 add_selections_state: None,
1459 select_next_state: None,
1460 select_prev_state: None,
1461 selection_history: Default::default(),
1462 autoclose_regions: Default::default(),
1463 snippet_stack: Default::default(),
1464 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1465 ime_transaction: Default::default(),
1466 active_diagnostics: None,
1467 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1468 inline_diagnostics_update: Task::ready(()),
1469 inline_diagnostics: Vec::new(),
1470 soft_wrap_mode_override,
1471 hard_wrap: None,
1472 completion_provider: project.clone().map(|project| Box::new(project) as _),
1473 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1474 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1475 project,
1476 blink_manager: blink_manager.clone(),
1477 show_local_selections: true,
1478 show_scrollbars: true,
1479 mode,
1480 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1481 show_gutter: mode.is_full(),
1482 show_line_numbers: None,
1483 use_relative_line_numbers: None,
1484 show_git_diff_gutter: None,
1485 show_code_actions: None,
1486 show_runnables: None,
1487 show_breakpoints: None,
1488 show_wrap_guides: None,
1489 show_indent_guides,
1490 placeholder_text: None,
1491 highlight_order: 0,
1492 highlighted_rows: HashMap::default(),
1493 background_highlights: Default::default(),
1494 gutter_highlights: TreeMap::default(),
1495 scrollbar_marker_state: ScrollbarMarkerState::default(),
1496 active_indent_guides_state: ActiveIndentGuidesState::default(),
1497 nav_history: None,
1498 context_menu: RefCell::new(None),
1499 context_menu_options: None,
1500 mouse_context_menu: None,
1501 completion_tasks: Default::default(),
1502 signature_help_state: SignatureHelpState::default(),
1503 auto_signature_help: None,
1504 find_all_references_task_sources: Vec::new(),
1505 next_completion_id: 0,
1506 next_inlay_id: 0,
1507 code_action_providers,
1508 available_code_actions: Default::default(),
1509 code_actions_task: Default::default(),
1510 selection_highlight_task: Default::default(),
1511 document_highlights_task: Default::default(),
1512 linked_editing_range_task: Default::default(),
1513 pending_rename: Default::default(),
1514 searchable: true,
1515 cursor_shape: EditorSettings::get_global(cx)
1516 .cursor_shape
1517 .unwrap_or_default(),
1518 current_line_highlight: None,
1519 autoindent_mode: Some(AutoindentMode::EachLine),
1520 collapse_matches: false,
1521 workspace: None,
1522 input_enabled: true,
1523 use_modal_editing: mode.is_full(),
1524 read_only: false,
1525 use_autoclose: true,
1526 use_auto_surround: true,
1527 auto_replace_emoji_shortcode: false,
1528 jsx_tag_auto_close_enabled_in_any_buffer: false,
1529 leader_peer_id: None,
1530 remote_id: None,
1531 hover_state: Default::default(),
1532 pending_mouse_down: None,
1533 hovered_link_state: Default::default(),
1534 edit_prediction_provider: None,
1535 active_inline_completion: None,
1536 stale_inline_completion_in_menu: None,
1537 edit_prediction_preview: EditPredictionPreview::Inactive {
1538 released_too_fast: false,
1539 },
1540 inline_diagnostics_enabled: mode.is_full(),
1541 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1542
1543 gutter_hovered: false,
1544 pixel_position_of_newest_cursor: None,
1545 last_bounds: None,
1546 last_position_map: None,
1547 expect_bounds_change: None,
1548 gutter_dimensions: GutterDimensions::default(),
1549 style: None,
1550 show_cursor_names: false,
1551 hovered_cursors: Default::default(),
1552 next_editor_action_id: EditorActionId::default(),
1553 editor_actions: Rc::default(),
1554 inline_completions_hidden_for_vim_mode: false,
1555 show_inline_completions_override: None,
1556 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1557 edit_prediction_settings: EditPredictionSettings::Disabled,
1558 edit_prediction_indent_conflict: false,
1559 edit_prediction_requires_modifier_in_indent_conflict: true,
1560 custom_context_menu: None,
1561 show_git_blame_gutter: false,
1562 show_git_blame_inline: false,
1563 show_selection_menu: None,
1564 show_git_blame_inline_delay_task: None,
1565 git_blame_inline_tooltip: None,
1566 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1567 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1568 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1569 .session
1570 .restore_unsaved_buffers,
1571 blame: None,
1572 blame_subscription: None,
1573 tasks: Default::default(),
1574
1575 breakpoint_store,
1576 gutter_breakpoint_indicator: (None, None),
1577 _subscriptions: vec![
1578 cx.observe(&buffer, Self::on_buffer_changed),
1579 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1580 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1581 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1582 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1583 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1584 cx.observe_window_activation(window, |editor, window, cx| {
1585 let active = window.is_window_active();
1586 editor.blink_manager.update(cx, |blink_manager, cx| {
1587 if active {
1588 blink_manager.enable(cx);
1589 } else {
1590 blink_manager.disable(cx);
1591 }
1592 });
1593 }),
1594 ],
1595 tasks_update_task: None,
1596 linked_edit_ranges: Default::default(),
1597 in_project_search: false,
1598 previous_search_ranges: None,
1599 breadcrumb_header: None,
1600 focused_block: None,
1601 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1602 addons: HashMap::default(),
1603 registered_buffers: HashMap::default(),
1604 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1605 selection_mark_mode: false,
1606 toggle_fold_multiple_buffers: Task::ready(()),
1607 serialize_selections: Task::ready(()),
1608 serialize_folds: Task::ready(()),
1609 text_style_refinement: None,
1610 load_diff_task: load_uncommitted_diff,
1611 mouse_cursor_hidden: false,
1612 hide_mouse_mode: EditorSettings::get_global(cx)
1613 .hide_mouse
1614 .unwrap_or_default(),
1615 };
1616 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1617 this._subscriptions
1618 .push(cx.observe(breakpoints, |_, _, cx| {
1619 cx.notify();
1620 }));
1621 }
1622 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1623 this._subscriptions.extend(project_subscriptions);
1624
1625 this._subscriptions.push(cx.subscribe_in(
1626 &cx.entity(),
1627 window,
1628 |editor, _, e: &EditorEvent, window, cx| {
1629 if let EditorEvent::SelectionsChanged { local } = e {
1630 if *local {
1631 let new_anchor = editor.scroll_manager.anchor();
1632 let snapshot = editor.snapshot(window, cx);
1633 editor.update_restoration_data(cx, move |data| {
1634 data.scroll_position = (
1635 new_anchor.top_row(&snapshot.buffer_snapshot),
1636 new_anchor.offset,
1637 );
1638 });
1639 }
1640 }
1641 },
1642 ));
1643
1644 this.end_selection(window, cx);
1645 this.scroll_manager.show_scrollbars(window, cx);
1646 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1647
1648 if mode.is_full() {
1649 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1650 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1651
1652 if this.git_blame_inline_enabled {
1653 this.git_blame_inline_enabled = true;
1654 this.start_git_blame_inline(false, window, cx);
1655 }
1656
1657 this.go_to_active_debug_line(window, cx);
1658
1659 if let Some(buffer) = buffer.read(cx).as_singleton() {
1660 if let Some(project) = this.project.as_ref() {
1661 let handle = project.update(cx, |project, cx| {
1662 project.register_buffer_with_language_servers(&buffer, cx)
1663 });
1664 this.registered_buffers
1665 .insert(buffer.read(cx).remote_id(), handle);
1666 }
1667 }
1668 }
1669
1670 this.report_editor_event("Editor Opened", None, cx);
1671 this
1672 }
1673
1674 pub fn deploy_mouse_context_menu(
1675 &mut self,
1676 position: gpui::Point<Pixels>,
1677 context_menu: Entity<ContextMenu>,
1678 window: &mut Window,
1679 cx: &mut Context<Self>,
1680 ) {
1681 self.mouse_context_menu = Some(MouseContextMenu::new(
1682 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1683 context_menu,
1684 window,
1685 cx,
1686 ));
1687 }
1688
1689 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1690 self.mouse_context_menu
1691 .as_ref()
1692 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1693 }
1694
1695 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1696 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1697 }
1698
1699 fn key_context_internal(
1700 &self,
1701 has_active_edit_prediction: bool,
1702 window: &Window,
1703 cx: &App,
1704 ) -> KeyContext {
1705 let mut key_context = KeyContext::new_with_defaults();
1706 key_context.add("Editor");
1707 let mode = match self.mode {
1708 EditorMode::SingleLine { .. } => "single_line",
1709 EditorMode::AutoHeight { .. } => "auto_height",
1710 EditorMode::Full { .. } => "full",
1711 };
1712
1713 if EditorSettings::jupyter_enabled(cx) {
1714 key_context.add("jupyter");
1715 }
1716
1717 key_context.set("mode", mode);
1718 if self.pending_rename.is_some() {
1719 key_context.add("renaming");
1720 }
1721
1722 match self.context_menu.borrow().as_ref() {
1723 Some(CodeContextMenu::Completions(_)) => {
1724 key_context.add("menu");
1725 key_context.add("showing_completions");
1726 }
1727 Some(CodeContextMenu::CodeActions(_)) => {
1728 key_context.add("menu");
1729 key_context.add("showing_code_actions")
1730 }
1731 None => {}
1732 }
1733
1734 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1735 if !self.focus_handle(cx).contains_focused(window, cx)
1736 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1737 {
1738 for addon in self.addons.values() {
1739 addon.extend_key_context(&mut key_context, cx)
1740 }
1741 }
1742
1743 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1744 if let Some(extension) = singleton_buffer
1745 .read(cx)
1746 .file()
1747 .and_then(|file| file.path().extension()?.to_str())
1748 {
1749 key_context.set("extension", extension.to_string());
1750 }
1751 } else {
1752 key_context.add("multibuffer");
1753 }
1754
1755 if has_active_edit_prediction {
1756 if self.edit_prediction_in_conflict() {
1757 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1758 } else {
1759 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1760 key_context.add("copilot_suggestion");
1761 }
1762 }
1763
1764 if self.selection_mark_mode {
1765 key_context.add("selection_mode");
1766 }
1767
1768 key_context
1769 }
1770
1771 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1772 self.mouse_cursor_hidden = match origin {
1773 HideMouseCursorOrigin::TypingAction => {
1774 matches!(
1775 self.hide_mouse_mode,
1776 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1777 )
1778 }
1779 HideMouseCursorOrigin::MovementAction => {
1780 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1781 }
1782 };
1783 }
1784
1785 pub fn edit_prediction_in_conflict(&self) -> bool {
1786 if !self.show_edit_predictions_in_menu() {
1787 return false;
1788 }
1789
1790 let showing_completions = self
1791 .context_menu
1792 .borrow()
1793 .as_ref()
1794 .map_or(false, |context| {
1795 matches!(context, CodeContextMenu::Completions(_))
1796 });
1797
1798 showing_completions
1799 || self.edit_prediction_requires_modifier()
1800 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1801 // bindings to insert tab characters.
1802 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1803 }
1804
1805 pub fn accept_edit_prediction_keybind(
1806 &self,
1807 window: &Window,
1808 cx: &App,
1809 ) -> AcceptEditPredictionBinding {
1810 let key_context = self.key_context_internal(true, window, cx);
1811 let in_conflict = self.edit_prediction_in_conflict();
1812
1813 AcceptEditPredictionBinding(
1814 window
1815 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1816 .into_iter()
1817 .filter(|binding| {
1818 !in_conflict
1819 || binding
1820 .keystrokes()
1821 .first()
1822 .map_or(false, |keystroke| keystroke.modifiers.modified())
1823 })
1824 .rev()
1825 .min_by_key(|binding| {
1826 binding
1827 .keystrokes()
1828 .first()
1829 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1830 }),
1831 )
1832 }
1833
1834 pub fn new_file(
1835 workspace: &mut Workspace,
1836 _: &workspace::NewFile,
1837 window: &mut Window,
1838 cx: &mut Context<Workspace>,
1839 ) {
1840 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1841 "Failed to create buffer",
1842 window,
1843 cx,
1844 |e, _, _| match e.error_code() {
1845 ErrorCode::RemoteUpgradeRequired => Some(format!(
1846 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1847 e.error_tag("required").unwrap_or("the latest version")
1848 )),
1849 _ => None,
1850 },
1851 );
1852 }
1853
1854 pub fn new_in_workspace(
1855 workspace: &mut Workspace,
1856 window: &mut Window,
1857 cx: &mut Context<Workspace>,
1858 ) -> Task<Result<Entity<Editor>>> {
1859 let project = workspace.project().clone();
1860 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1861
1862 cx.spawn_in(window, async move |workspace, cx| {
1863 let buffer = create.await?;
1864 workspace.update_in(cx, |workspace, window, cx| {
1865 let editor =
1866 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1867 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1868 editor
1869 })
1870 })
1871 }
1872
1873 fn new_file_vertical(
1874 workspace: &mut Workspace,
1875 _: &workspace::NewFileSplitVertical,
1876 window: &mut Window,
1877 cx: &mut Context<Workspace>,
1878 ) {
1879 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1880 }
1881
1882 fn new_file_horizontal(
1883 workspace: &mut Workspace,
1884 _: &workspace::NewFileSplitHorizontal,
1885 window: &mut Window,
1886 cx: &mut Context<Workspace>,
1887 ) {
1888 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1889 }
1890
1891 fn new_file_in_direction(
1892 workspace: &mut Workspace,
1893 direction: SplitDirection,
1894 window: &mut Window,
1895 cx: &mut Context<Workspace>,
1896 ) {
1897 let project = workspace.project().clone();
1898 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1899
1900 cx.spawn_in(window, async move |workspace, cx| {
1901 let buffer = create.await?;
1902 workspace.update_in(cx, move |workspace, window, cx| {
1903 workspace.split_item(
1904 direction,
1905 Box::new(
1906 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1907 ),
1908 window,
1909 cx,
1910 )
1911 })?;
1912 anyhow::Ok(())
1913 })
1914 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1915 match e.error_code() {
1916 ErrorCode::RemoteUpgradeRequired => Some(format!(
1917 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1918 e.error_tag("required").unwrap_or("the latest version")
1919 )),
1920 _ => None,
1921 }
1922 });
1923 }
1924
1925 pub fn leader_peer_id(&self) -> Option<PeerId> {
1926 self.leader_peer_id
1927 }
1928
1929 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1930 &self.buffer
1931 }
1932
1933 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1934 self.workspace.as_ref()?.0.upgrade()
1935 }
1936
1937 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1938 self.buffer().read(cx).title(cx)
1939 }
1940
1941 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1942 let git_blame_gutter_max_author_length = self
1943 .render_git_blame_gutter(cx)
1944 .then(|| {
1945 if let Some(blame) = self.blame.as_ref() {
1946 let max_author_length =
1947 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1948 Some(max_author_length)
1949 } else {
1950 None
1951 }
1952 })
1953 .flatten();
1954
1955 EditorSnapshot {
1956 mode: self.mode,
1957 show_gutter: self.show_gutter,
1958 show_line_numbers: self.show_line_numbers,
1959 show_git_diff_gutter: self.show_git_diff_gutter,
1960 show_code_actions: self.show_code_actions,
1961 show_runnables: self.show_runnables,
1962 show_breakpoints: self.show_breakpoints,
1963 git_blame_gutter_max_author_length,
1964 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1965 scroll_anchor: self.scroll_manager.anchor(),
1966 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1967 placeholder_text: self.placeholder_text.clone(),
1968 is_focused: self.focus_handle.is_focused(window),
1969 current_line_highlight: self
1970 .current_line_highlight
1971 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1972 gutter_hovered: self.gutter_hovered,
1973 }
1974 }
1975
1976 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1977 self.buffer.read(cx).language_at(point, cx)
1978 }
1979
1980 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1981 self.buffer.read(cx).read(cx).file_at(point).cloned()
1982 }
1983
1984 pub fn active_excerpt(
1985 &self,
1986 cx: &App,
1987 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1988 self.buffer
1989 .read(cx)
1990 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1991 }
1992
1993 pub fn mode(&self) -> EditorMode {
1994 self.mode
1995 }
1996
1997 pub fn set_mode(&mut self, mode: EditorMode) {
1998 self.mode = mode;
1999 }
2000
2001 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2002 self.collaboration_hub.as_deref()
2003 }
2004
2005 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2006 self.collaboration_hub = Some(hub);
2007 }
2008
2009 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2010 self.in_project_search = in_project_search;
2011 }
2012
2013 pub fn set_custom_context_menu(
2014 &mut self,
2015 f: impl 'static
2016 + Fn(
2017 &mut Self,
2018 DisplayPoint,
2019 &mut Window,
2020 &mut Context<Self>,
2021 ) -> Option<Entity<ui::ContextMenu>>,
2022 ) {
2023 self.custom_context_menu = Some(Box::new(f))
2024 }
2025
2026 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2027 self.completion_provider = provider;
2028 }
2029
2030 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2031 self.semantics_provider.clone()
2032 }
2033
2034 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2035 self.semantics_provider = provider;
2036 }
2037
2038 pub fn set_edit_prediction_provider<T>(
2039 &mut self,
2040 provider: Option<Entity<T>>,
2041 window: &mut Window,
2042 cx: &mut Context<Self>,
2043 ) where
2044 T: EditPredictionProvider,
2045 {
2046 self.edit_prediction_provider =
2047 provider.map(|provider| RegisteredInlineCompletionProvider {
2048 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2049 if this.focus_handle.is_focused(window) {
2050 this.update_visible_inline_completion(window, cx);
2051 }
2052 }),
2053 provider: Arc::new(provider),
2054 });
2055 self.update_edit_prediction_settings(cx);
2056 self.refresh_inline_completion(false, false, window, cx);
2057 }
2058
2059 pub fn placeholder_text(&self) -> Option<&str> {
2060 self.placeholder_text.as_deref()
2061 }
2062
2063 pub fn set_placeholder_text(
2064 &mut self,
2065 placeholder_text: impl Into<Arc<str>>,
2066 cx: &mut Context<Self>,
2067 ) {
2068 let placeholder_text = Some(placeholder_text.into());
2069 if self.placeholder_text != placeholder_text {
2070 self.placeholder_text = placeholder_text;
2071 cx.notify();
2072 }
2073 }
2074
2075 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2076 self.cursor_shape = cursor_shape;
2077
2078 // Disrupt blink for immediate user feedback that the cursor shape has changed
2079 self.blink_manager.update(cx, BlinkManager::show_cursor);
2080
2081 cx.notify();
2082 }
2083
2084 pub fn set_current_line_highlight(
2085 &mut self,
2086 current_line_highlight: Option<CurrentLineHighlight>,
2087 ) {
2088 self.current_line_highlight = current_line_highlight;
2089 }
2090
2091 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2092 self.collapse_matches = collapse_matches;
2093 }
2094
2095 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2096 let buffers = self.buffer.read(cx).all_buffers();
2097 let Some(project) = self.project.as_ref() else {
2098 return;
2099 };
2100 project.update(cx, |project, cx| {
2101 for buffer in buffers {
2102 self.registered_buffers
2103 .entry(buffer.read(cx).remote_id())
2104 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2105 }
2106 })
2107 }
2108
2109 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2110 if self.collapse_matches {
2111 return range.start..range.start;
2112 }
2113 range.clone()
2114 }
2115
2116 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2117 if self.display_map.read(cx).clip_at_line_ends != clip {
2118 self.display_map
2119 .update(cx, |map, _| map.clip_at_line_ends = clip);
2120 }
2121 }
2122
2123 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2124 self.input_enabled = input_enabled;
2125 }
2126
2127 pub fn set_inline_completions_hidden_for_vim_mode(
2128 &mut self,
2129 hidden: bool,
2130 window: &mut Window,
2131 cx: &mut Context<Self>,
2132 ) {
2133 if hidden != self.inline_completions_hidden_for_vim_mode {
2134 self.inline_completions_hidden_for_vim_mode = hidden;
2135 if hidden {
2136 self.update_visible_inline_completion(window, cx);
2137 } else {
2138 self.refresh_inline_completion(true, false, window, cx);
2139 }
2140 }
2141 }
2142
2143 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2144 self.menu_inline_completions_policy = value;
2145 }
2146
2147 pub fn set_autoindent(&mut self, autoindent: bool) {
2148 if autoindent {
2149 self.autoindent_mode = Some(AutoindentMode::EachLine);
2150 } else {
2151 self.autoindent_mode = None;
2152 }
2153 }
2154
2155 pub fn read_only(&self, cx: &App) -> bool {
2156 self.read_only || self.buffer.read(cx).read_only()
2157 }
2158
2159 pub fn set_read_only(&mut self, read_only: bool) {
2160 self.read_only = read_only;
2161 }
2162
2163 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2164 self.use_autoclose = autoclose;
2165 }
2166
2167 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2168 self.use_auto_surround = auto_surround;
2169 }
2170
2171 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2172 self.auto_replace_emoji_shortcode = auto_replace;
2173 }
2174
2175 pub fn toggle_edit_predictions(
2176 &mut self,
2177 _: &ToggleEditPrediction,
2178 window: &mut Window,
2179 cx: &mut Context<Self>,
2180 ) {
2181 if self.show_inline_completions_override.is_some() {
2182 self.set_show_edit_predictions(None, window, cx);
2183 } else {
2184 let show_edit_predictions = !self.edit_predictions_enabled();
2185 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2186 }
2187 }
2188
2189 pub fn set_show_edit_predictions(
2190 &mut self,
2191 show_edit_predictions: Option<bool>,
2192 window: &mut Window,
2193 cx: &mut Context<Self>,
2194 ) {
2195 self.show_inline_completions_override = show_edit_predictions;
2196 self.update_edit_prediction_settings(cx);
2197
2198 if let Some(false) = show_edit_predictions {
2199 self.discard_inline_completion(false, cx);
2200 } else {
2201 self.refresh_inline_completion(false, true, window, cx);
2202 }
2203 }
2204
2205 fn inline_completions_disabled_in_scope(
2206 &self,
2207 buffer: &Entity<Buffer>,
2208 buffer_position: language::Anchor,
2209 cx: &App,
2210 ) -> bool {
2211 let snapshot = buffer.read(cx).snapshot();
2212 let settings = snapshot.settings_at(buffer_position, cx);
2213
2214 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2215 return false;
2216 };
2217
2218 scope.override_name().map_or(false, |scope_name| {
2219 settings
2220 .edit_predictions_disabled_in
2221 .iter()
2222 .any(|s| s == scope_name)
2223 })
2224 }
2225
2226 pub fn set_use_modal_editing(&mut self, to: bool) {
2227 self.use_modal_editing = to;
2228 }
2229
2230 pub fn use_modal_editing(&self) -> bool {
2231 self.use_modal_editing
2232 }
2233
2234 fn selections_did_change(
2235 &mut self,
2236 local: bool,
2237 old_cursor_position: &Anchor,
2238 show_completions: bool,
2239 window: &mut Window,
2240 cx: &mut Context<Self>,
2241 ) {
2242 window.invalidate_character_coordinates();
2243
2244 // Copy selections to primary selection buffer
2245 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2246 if local {
2247 let selections = self.selections.all::<usize>(cx);
2248 let buffer_handle = self.buffer.read(cx).read(cx);
2249
2250 let mut text = String::new();
2251 for (index, selection) in selections.iter().enumerate() {
2252 let text_for_selection = buffer_handle
2253 .text_for_range(selection.start..selection.end)
2254 .collect::<String>();
2255
2256 text.push_str(&text_for_selection);
2257 if index != selections.len() - 1 {
2258 text.push('\n');
2259 }
2260 }
2261
2262 if !text.is_empty() {
2263 cx.write_to_primary(ClipboardItem::new_string(text));
2264 }
2265 }
2266
2267 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2268 self.buffer.update(cx, |buffer, cx| {
2269 buffer.set_active_selections(
2270 &self.selections.disjoint_anchors(),
2271 self.selections.line_mode,
2272 self.cursor_shape,
2273 cx,
2274 )
2275 });
2276 }
2277 let display_map = self
2278 .display_map
2279 .update(cx, |display_map, cx| display_map.snapshot(cx));
2280 let buffer = &display_map.buffer_snapshot;
2281 self.add_selections_state = None;
2282 self.select_next_state = None;
2283 self.select_prev_state = None;
2284 self.select_syntax_node_history.try_clear();
2285 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2286 self.snippet_stack
2287 .invalidate(&self.selections.disjoint_anchors(), buffer);
2288 self.take_rename(false, window, cx);
2289
2290 let new_cursor_position = self.selections.newest_anchor().head();
2291
2292 self.push_to_nav_history(
2293 *old_cursor_position,
2294 Some(new_cursor_position.to_point(buffer)),
2295 false,
2296 cx,
2297 );
2298
2299 if local {
2300 let new_cursor_position = self.selections.newest_anchor().head();
2301 let mut context_menu = self.context_menu.borrow_mut();
2302 let completion_menu = match context_menu.as_ref() {
2303 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2304 _ => {
2305 *context_menu = None;
2306 None
2307 }
2308 };
2309 if let Some(buffer_id) = new_cursor_position.buffer_id {
2310 if !self.registered_buffers.contains_key(&buffer_id) {
2311 if let Some(project) = self.project.as_ref() {
2312 project.update(cx, |project, cx| {
2313 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2314 return;
2315 };
2316 self.registered_buffers.insert(
2317 buffer_id,
2318 project.register_buffer_with_language_servers(&buffer, cx),
2319 );
2320 })
2321 }
2322 }
2323 }
2324
2325 if let Some(completion_menu) = completion_menu {
2326 let cursor_position = new_cursor_position.to_offset(buffer);
2327 let (word_range, kind) =
2328 buffer.surrounding_word(completion_menu.initial_position, true);
2329 if kind == Some(CharKind::Word)
2330 && word_range.to_inclusive().contains(&cursor_position)
2331 {
2332 let mut completion_menu = completion_menu.clone();
2333 drop(context_menu);
2334
2335 let query = Self::completion_query(buffer, cursor_position);
2336 cx.spawn(async move |this, cx| {
2337 completion_menu
2338 .filter(query.as_deref(), cx.background_executor().clone())
2339 .await;
2340
2341 this.update(cx, |this, cx| {
2342 let mut context_menu = this.context_menu.borrow_mut();
2343 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2344 else {
2345 return;
2346 };
2347
2348 if menu.id > completion_menu.id {
2349 return;
2350 }
2351
2352 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2353 drop(context_menu);
2354 cx.notify();
2355 })
2356 })
2357 .detach();
2358
2359 if show_completions {
2360 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2361 }
2362 } else {
2363 drop(context_menu);
2364 self.hide_context_menu(window, cx);
2365 }
2366 } else {
2367 drop(context_menu);
2368 }
2369
2370 hide_hover(self, cx);
2371
2372 if old_cursor_position.to_display_point(&display_map).row()
2373 != new_cursor_position.to_display_point(&display_map).row()
2374 {
2375 self.available_code_actions.take();
2376 }
2377 self.refresh_code_actions(window, cx);
2378 self.refresh_document_highlights(cx);
2379 self.refresh_selected_text_highlights(window, cx);
2380 refresh_matching_bracket_highlights(self, window, cx);
2381 self.update_visible_inline_completion(window, cx);
2382 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2383 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2384 if self.git_blame_inline_enabled {
2385 self.start_inline_blame_timer(window, cx);
2386 }
2387 }
2388
2389 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2390 cx.emit(EditorEvent::SelectionsChanged { local });
2391
2392 let selections = &self.selections.disjoint;
2393 if selections.len() == 1 {
2394 cx.emit(SearchEvent::ActiveMatchChanged)
2395 }
2396 if local {
2397 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2398 let inmemory_selections = selections
2399 .iter()
2400 .map(|s| {
2401 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2402 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2403 })
2404 .collect();
2405 self.update_restoration_data(cx, |data| {
2406 data.selections = inmemory_selections;
2407 });
2408
2409 if WorkspaceSettings::get(None, cx).restore_on_startup
2410 != RestoreOnStartupBehavior::None
2411 {
2412 if let Some(workspace_id) =
2413 self.workspace.as_ref().and_then(|workspace| workspace.1)
2414 {
2415 let snapshot = self.buffer().read(cx).snapshot(cx);
2416 let selections = selections.clone();
2417 let background_executor = cx.background_executor().clone();
2418 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2419 self.serialize_selections = cx.background_spawn(async move {
2420 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2421 let db_selections = selections
2422 .iter()
2423 .map(|selection| {
2424 (
2425 selection.start.to_offset(&snapshot),
2426 selection.end.to_offset(&snapshot),
2427 )
2428 })
2429 .collect();
2430
2431 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2432 .await
2433 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2434 .log_err();
2435 });
2436 }
2437 }
2438 }
2439 }
2440
2441 cx.notify();
2442 }
2443
2444 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2445 use text::ToOffset as _;
2446 use text::ToPoint as _;
2447
2448 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2449 return;
2450 }
2451
2452 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2453 return;
2454 };
2455
2456 let snapshot = singleton.read(cx).snapshot();
2457 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2458 let display_snapshot = display_map.snapshot(cx);
2459
2460 display_snapshot
2461 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2462 .map(|fold| {
2463 fold.range.start.text_anchor.to_point(&snapshot)
2464 ..fold.range.end.text_anchor.to_point(&snapshot)
2465 })
2466 .collect()
2467 });
2468 self.update_restoration_data(cx, |data| {
2469 data.folds = inmemory_folds;
2470 });
2471
2472 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2473 return;
2474 };
2475 let background_executor = cx.background_executor().clone();
2476 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2477 let db_folds = self.display_map.update(cx, |display_map, cx| {
2478 display_map
2479 .snapshot(cx)
2480 .folds_in_range(0..snapshot.len())
2481 .map(|fold| {
2482 (
2483 fold.range.start.text_anchor.to_offset(&snapshot),
2484 fold.range.end.text_anchor.to_offset(&snapshot),
2485 )
2486 })
2487 .collect()
2488 });
2489 self.serialize_folds = cx.background_spawn(async move {
2490 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2491 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2492 .await
2493 .with_context(|| {
2494 format!(
2495 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2496 )
2497 })
2498 .log_err();
2499 });
2500 }
2501
2502 pub fn sync_selections(
2503 &mut self,
2504 other: Entity<Editor>,
2505 cx: &mut Context<Self>,
2506 ) -> gpui::Subscription {
2507 let other_selections = other.read(cx).selections.disjoint.to_vec();
2508 self.selections.change_with(cx, |selections| {
2509 selections.select_anchors(other_selections);
2510 });
2511
2512 let other_subscription =
2513 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2514 EditorEvent::SelectionsChanged { local: true } => {
2515 let other_selections = other.read(cx).selections.disjoint.to_vec();
2516 if other_selections.is_empty() {
2517 return;
2518 }
2519 this.selections.change_with(cx, |selections| {
2520 selections.select_anchors(other_selections);
2521 });
2522 }
2523 _ => {}
2524 });
2525
2526 let this_subscription =
2527 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2528 EditorEvent::SelectionsChanged { local: true } => {
2529 let these_selections = this.selections.disjoint.to_vec();
2530 if these_selections.is_empty() {
2531 return;
2532 }
2533 other.update(cx, |other_editor, cx| {
2534 other_editor.selections.change_with(cx, |selections| {
2535 selections.select_anchors(these_selections);
2536 })
2537 });
2538 }
2539 _ => {}
2540 });
2541
2542 Subscription::join(other_subscription, this_subscription)
2543 }
2544
2545 pub fn change_selections<R>(
2546 &mut self,
2547 autoscroll: Option<Autoscroll>,
2548 window: &mut Window,
2549 cx: &mut Context<Self>,
2550 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2551 ) -> R {
2552 self.change_selections_inner(autoscroll, true, window, cx, change)
2553 }
2554
2555 fn change_selections_inner<R>(
2556 &mut self,
2557 autoscroll: Option<Autoscroll>,
2558 request_completions: bool,
2559 window: &mut Window,
2560 cx: &mut Context<Self>,
2561 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2562 ) -> R {
2563 let old_cursor_position = self.selections.newest_anchor().head();
2564 self.push_to_selection_history();
2565
2566 let (changed, result) = self.selections.change_with(cx, change);
2567
2568 if changed {
2569 if let Some(autoscroll) = autoscroll {
2570 self.request_autoscroll(autoscroll, cx);
2571 }
2572 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2573
2574 if self.should_open_signature_help_automatically(
2575 &old_cursor_position,
2576 self.signature_help_state.backspace_pressed(),
2577 cx,
2578 ) {
2579 self.show_signature_help(&ShowSignatureHelp, window, cx);
2580 }
2581 self.signature_help_state.set_backspace_pressed(false);
2582 }
2583
2584 result
2585 }
2586
2587 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2588 where
2589 I: IntoIterator<Item = (Range<S>, T)>,
2590 S: ToOffset,
2591 T: Into<Arc<str>>,
2592 {
2593 if self.read_only(cx) {
2594 return;
2595 }
2596
2597 self.buffer
2598 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2599 }
2600
2601 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2602 where
2603 I: IntoIterator<Item = (Range<S>, T)>,
2604 S: ToOffset,
2605 T: Into<Arc<str>>,
2606 {
2607 if self.read_only(cx) {
2608 return;
2609 }
2610
2611 self.buffer.update(cx, |buffer, cx| {
2612 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2613 });
2614 }
2615
2616 pub fn edit_with_block_indent<I, S, T>(
2617 &mut self,
2618 edits: I,
2619 original_indent_columns: Vec<Option<u32>>,
2620 cx: &mut Context<Self>,
2621 ) where
2622 I: IntoIterator<Item = (Range<S>, T)>,
2623 S: ToOffset,
2624 T: Into<Arc<str>>,
2625 {
2626 if self.read_only(cx) {
2627 return;
2628 }
2629
2630 self.buffer.update(cx, |buffer, cx| {
2631 buffer.edit(
2632 edits,
2633 Some(AutoindentMode::Block {
2634 original_indent_columns,
2635 }),
2636 cx,
2637 )
2638 });
2639 }
2640
2641 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2642 self.hide_context_menu(window, cx);
2643
2644 match phase {
2645 SelectPhase::Begin {
2646 position,
2647 add,
2648 click_count,
2649 } => self.begin_selection(position, add, click_count, window, cx),
2650 SelectPhase::BeginColumnar {
2651 position,
2652 goal_column,
2653 reset,
2654 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2655 SelectPhase::Extend {
2656 position,
2657 click_count,
2658 } => self.extend_selection(position, click_count, window, cx),
2659 SelectPhase::Update {
2660 position,
2661 goal_column,
2662 scroll_delta,
2663 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2664 SelectPhase::End => self.end_selection(window, cx),
2665 }
2666 }
2667
2668 fn extend_selection(
2669 &mut self,
2670 position: DisplayPoint,
2671 click_count: usize,
2672 window: &mut Window,
2673 cx: &mut Context<Self>,
2674 ) {
2675 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2676 let tail = self.selections.newest::<usize>(cx).tail();
2677 self.begin_selection(position, false, click_count, window, cx);
2678
2679 let position = position.to_offset(&display_map, Bias::Left);
2680 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2681
2682 let mut pending_selection = self
2683 .selections
2684 .pending_anchor()
2685 .expect("extend_selection not called with pending selection");
2686 if position >= tail {
2687 pending_selection.start = tail_anchor;
2688 } else {
2689 pending_selection.end = tail_anchor;
2690 pending_selection.reversed = true;
2691 }
2692
2693 let mut pending_mode = self.selections.pending_mode().unwrap();
2694 match &mut pending_mode {
2695 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2696 _ => {}
2697 }
2698
2699 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2700 s.set_pending(pending_selection, pending_mode)
2701 });
2702 }
2703
2704 fn begin_selection(
2705 &mut self,
2706 position: DisplayPoint,
2707 add: bool,
2708 click_count: usize,
2709 window: &mut Window,
2710 cx: &mut Context<Self>,
2711 ) {
2712 if !self.focus_handle.is_focused(window) {
2713 self.last_focused_descendant = None;
2714 window.focus(&self.focus_handle);
2715 }
2716
2717 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2718 let buffer = &display_map.buffer_snapshot;
2719 let newest_selection = self.selections.newest_anchor().clone();
2720 let position = display_map.clip_point(position, Bias::Left);
2721
2722 let start;
2723 let end;
2724 let mode;
2725 let mut auto_scroll;
2726 match click_count {
2727 1 => {
2728 start = buffer.anchor_before(position.to_point(&display_map));
2729 end = start;
2730 mode = SelectMode::Character;
2731 auto_scroll = true;
2732 }
2733 2 => {
2734 let range = movement::surrounding_word(&display_map, position);
2735 start = buffer.anchor_before(range.start.to_point(&display_map));
2736 end = buffer.anchor_before(range.end.to_point(&display_map));
2737 mode = SelectMode::Word(start..end);
2738 auto_scroll = true;
2739 }
2740 3 => {
2741 let position = display_map
2742 .clip_point(position, Bias::Left)
2743 .to_point(&display_map);
2744 let line_start = display_map.prev_line_boundary(position).0;
2745 let next_line_start = buffer.clip_point(
2746 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2747 Bias::Left,
2748 );
2749 start = buffer.anchor_before(line_start);
2750 end = buffer.anchor_before(next_line_start);
2751 mode = SelectMode::Line(start..end);
2752 auto_scroll = true;
2753 }
2754 _ => {
2755 start = buffer.anchor_before(0);
2756 end = buffer.anchor_before(buffer.len());
2757 mode = SelectMode::All;
2758 auto_scroll = false;
2759 }
2760 }
2761 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2762
2763 let point_to_delete: Option<usize> = {
2764 let selected_points: Vec<Selection<Point>> =
2765 self.selections.disjoint_in_range(start..end, cx);
2766
2767 if !add || click_count > 1 {
2768 None
2769 } else if !selected_points.is_empty() {
2770 Some(selected_points[0].id)
2771 } else {
2772 let clicked_point_already_selected =
2773 self.selections.disjoint.iter().find(|selection| {
2774 selection.start.to_point(buffer) == start.to_point(buffer)
2775 || selection.end.to_point(buffer) == end.to_point(buffer)
2776 });
2777
2778 clicked_point_already_selected.map(|selection| selection.id)
2779 }
2780 };
2781
2782 let selections_count = self.selections.count();
2783
2784 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2785 if let Some(point_to_delete) = point_to_delete {
2786 s.delete(point_to_delete);
2787
2788 if selections_count == 1 {
2789 s.set_pending_anchor_range(start..end, mode);
2790 }
2791 } else {
2792 if !add {
2793 s.clear_disjoint();
2794 } else if click_count > 1 {
2795 s.delete(newest_selection.id)
2796 }
2797
2798 s.set_pending_anchor_range(start..end, mode);
2799 }
2800 });
2801 }
2802
2803 fn begin_columnar_selection(
2804 &mut self,
2805 position: DisplayPoint,
2806 goal_column: u32,
2807 reset: bool,
2808 window: &mut Window,
2809 cx: &mut Context<Self>,
2810 ) {
2811 if !self.focus_handle.is_focused(window) {
2812 self.last_focused_descendant = None;
2813 window.focus(&self.focus_handle);
2814 }
2815
2816 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2817
2818 if reset {
2819 let pointer_position = display_map
2820 .buffer_snapshot
2821 .anchor_before(position.to_point(&display_map));
2822
2823 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2824 s.clear_disjoint();
2825 s.set_pending_anchor_range(
2826 pointer_position..pointer_position,
2827 SelectMode::Character,
2828 );
2829 });
2830 }
2831
2832 let tail = self.selections.newest::<Point>(cx).tail();
2833 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2834
2835 if !reset {
2836 self.select_columns(
2837 tail.to_display_point(&display_map),
2838 position,
2839 goal_column,
2840 &display_map,
2841 window,
2842 cx,
2843 );
2844 }
2845 }
2846
2847 fn update_selection(
2848 &mut self,
2849 position: DisplayPoint,
2850 goal_column: u32,
2851 scroll_delta: gpui::Point<f32>,
2852 window: &mut Window,
2853 cx: &mut Context<Self>,
2854 ) {
2855 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2856
2857 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2858 let tail = tail.to_display_point(&display_map);
2859 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2860 } else if let Some(mut pending) = self.selections.pending_anchor() {
2861 let buffer = self.buffer.read(cx).snapshot(cx);
2862 let head;
2863 let tail;
2864 let mode = self.selections.pending_mode().unwrap();
2865 match &mode {
2866 SelectMode::Character => {
2867 head = position.to_point(&display_map);
2868 tail = pending.tail().to_point(&buffer);
2869 }
2870 SelectMode::Word(original_range) => {
2871 let original_display_range = original_range.start.to_display_point(&display_map)
2872 ..original_range.end.to_display_point(&display_map);
2873 let original_buffer_range = original_display_range.start.to_point(&display_map)
2874 ..original_display_range.end.to_point(&display_map);
2875 if movement::is_inside_word(&display_map, position)
2876 || original_display_range.contains(&position)
2877 {
2878 let word_range = movement::surrounding_word(&display_map, position);
2879 if word_range.start < original_display_range.start {
2880 head = word_range.start.to_point(&display_map);
2881 } else {
2882 head = word_range.end.to_point(&display_map);
2883 }
2884 } else {
2885 head = position.to_point(&display_map);
2886 }
2887
2888 if head <= original_buffer_range.start {
2889 tail = original_buffer_range.end;
2890 } else {
2891 tail = original_buffer_range.start;
2892 }
2893 }
2894 SelectMode::Line(original_range) => {
2895 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2896
2897 let position = display_map
2898 .clip_point(position, Bias::Left)
2899 .to_point(&display_map);
2900 let line_start = display_map.prev_line_boundary(position).0;
2901 let next_line_start = buffer.clip_point(
2902 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2903 Bias::Left,
2904 );
2905
2906 if line_start < original_range.start {
2907 head = line_start
2908 } else {
2909 head = next_line_start
2910 }
2911
2912 if head <= original_range.start {
2913 tail = original_range.end;
2914 } else {
2915 tail = original_range.start;
2916 }
2917 }
2918 SelectMode::All => {
2919 return;
2920 }
2921 };
2922
2923 if head < tail {
2924 pending.start = buffer.anchor_before(head);
2925 pending.end = buffer.anchor_before(tail);
2926 pending.reversed = true;
2927 } else {
2928 pending.start = buffer.anchor_before(tail);
2929 pending.end = buffer.anchor_before(head);
2930 pending.reversed = false;
2931 }
2932
2933 self.change_selections(None, window, cx, |s| {
2934 s.set_pending(pending, mode);
2935 });
2936 } else {
2937 log::error!("update_selection dispatched with no pending selection");
2938 return;
2939 }
2940
2941 self.apply_scroll_delta(scroll_delta, window, cx);
2942 cx.notify();
2943 }
2944
2945 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2946 self.columnar_selection_tail.take();
2947 if self.selections.pending_anchor().is_some() {
2948 let selections = self.selections.all::<usize>(cx);
2949 self.change_selections(None, window, cx, |s| {
2950 s.select(selections);
2951 s.clear_pending();
2952 });
2953 }
2954 }
2955
2956 fn select_columns(
2957 &mut self,
2958 tail: DisplayPoint,
2959 head: DisplayPoint,
2960 goal_column: u32,
2961 display_map: &DisplaySnapshot,
2962 window: &mut Window,
2963 cx: &mut Context<Self>,
2964 ) {
2965 let start_row = cmp::min(tail.row(), head.row());
2966 let end_row = cmp::max(tail.row(), head.row());
2967 let start_column = cmp::min(tail.column(), goal_column);
2968 let end_column = cmp::max(tail.column(), goal_column);
2969 let reversed = start_column < tail.column();
2970
2971 let selection_ranges = (start_row.0..=end_row.0)
2972 .map(DisplayRow)
2973 .filter_map(|row| {
2974 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2975 let start = display_map
2976 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2977 .to_point(display_map);
2978 let end = display_map
2979 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2980 .to_point(display_map);
2981 if reversed {
2982 Some(end..start)
2983 } else {
2984 Some(start..end)
2985 }
2986 } else {
2987 None
2988 }
2989 })
2990 .collect::<Vec<_>>();
2991
2992 self.change_selections(None, window, cx, |s| {
2993 s.select_ranges(selection_ranges);
2994 });
2995 cx.notify();
2996 }
2997
2998 pub fn has_pending_nonempty_selection(&self) -> bool {
2999 let pending_nonempty_selection = match self.selections.pending_anchor() {
3000 Some(Selection { start, end, .. }) => start != end,
3001 None => false,
3002 };
3003
3004 pending_nonempty_selection
3005 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3006 }
3007
3008 pub fn has_pending_selection(&self) -> bool {
3009 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3010 }
3011
3012 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3013 self.selection_mark_mode = false;
3014
3015 if self.clear_expanded_diff_hunks(cx) {
3016 cx.notify();
3017 return;
3018 }
3019 if self.dismiss_menus_and_popups(true, window, cx) {
3020 return;
3021 }
3022
3023 if self.mode.is_full()
3024 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3025 {
3026 return;
3027 }
3028
3029 cx.propagate();
3030 }
3031
3032 pub fn dismiss_menus_and_popups(
3033 &mut self,
3034 is_user_requested: bool,
3035 window: &mut Window,
3036 cx: &mut Context<Self>,
3037 ) -> bool {
3038 if self.take_rename(false, window, cx).is_some() {
3039 return true;
3040 }
3041
3042 if hide_hover(self, cx) {
3043 return true;
3044 }
3045
3046 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3047 return true;
3048 }
3049
3050 if self.hide_context_menu(window, cx).is_some() {
3051 return true;
3052 }
3053
3054 if self.mouse_context_menu.take().is_some() {
3055 return true;
3056 }
3057
3058 if is_user_requested && self.discard_inline_completion(true, cx) {
3059 return true;
3060 }
3061
3062 if self.snippet_stack.pop().is_some() {
3063 return true;
3064 }
3065
3066 if self.mode.is_full() && self.active_diagnostics.is_some() {
3067 self.dismiss_diagnostics(cx);
3068 return true;
3069 }
3070
3071 false
3072 }
3073
3074 fn linked_editing_ranges_for(
3075 &self,
3076 selection: Range<text::Anchor>,
3077 cx: &App,
3078 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3079 if self.linked_edit_ranges.is_empty() {
3080 return None;
3081 }
3082 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3083 selection.end.buffer_id.and_then(|end_buffer_id| {
3084 if selection.start.buffer_id != Some(end_buffer_id) {
3085 return None;
3086 }
3087 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3088 let snapshot = buffer.read(cx).snapshot();
3089 self.linked_edit_ranges
3090 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3091 .map(|ranges| (ranges, snapshot, buffer))
3092 })?;
3093 use text::ToOffset as TO;
3094 // find offset from the start of current range to current cursor position
3095 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3096
3097 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3098 let start_difference = start_offset - start_byte_offset;
3099 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3100 let end_difference = end_offset - start_byte_offset;
3101 // Current range has associated linked ranges.
3102 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3103 for range in linked_ranges.iter() {
3104 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3105 let end_offset = start_offset + end_difference;
3106 let start_offset = start_offset + start_difference;
3107 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3108 continue;
3109 }
3110 if self.selections.disjoint_anchor_ranges().any(|s| {
3111 if s.start.buffer_id != selection.start.buffer_id
3112 || s.end.buffer_id != selection.end.buffer_id
3113 {
3114 return false;
3115 }
3116 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3117 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3118 }) {
3119 continue;
3120 }
3121 let start = buffer_snapshot.anchor_after(start_offset);
3122 let end = buffer_snapshot.anchor_after(end_offset);
3123 linked_edits
3124 .entry(buffer.clone())
3125 .or_default()
3126 .push(start..end);
3127 }
3128 Some(linked_edits)
3129 }
3130
3131 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3132 let text: Arc<str> = text.into();
3133
3134 if self.read_only(cx) {
3135 return;
3136 }
3137
3138 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3139
3140 let selections = self.selections.all_adjusted(cx);
3141 let mut bracket_inserted = false;
3142 let mut edits = Vec::new();
3143 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3144 let mut new_selections = Vec::with_capacity(selections.len());
3145 let mut new_autoclose_regions = Vec::new();
3146 let snapshot = self.buffer.read(cx).read(cx);
3147 let mut clear_linked_edit_ranges = false;
3148
3149 for (selection, autoclose_region) in
3150 self.selections_with_autoclose_regions(selections, &snapshot)
3151 {
3152 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3153 // Determine if the inserted text matches the opening or closing
3154 // bracket of any of this language's bracket pairs.
3155 let mut bracket_pair = None;
3156 let mut is_bracket_pair_start = false;
3157 let mut is_bracket_pair_end = false;
3158 if !text.is_empty() {
3159 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3160 // and they are removing the character that triggered IME popup.
3161 for (pair, enabled) in scope.brackets() {
3162 if !pair.close && !pair.surround {
3163 continue;
3164 }
3165
3166 if enabled && pair.start.ends_with(text.as_ref()) {
3167 let prefix_len = pair.start.len() - text.len();
3168 let preceding_text_matches_prefix = prefix_len == 0
3169 || (selection.start.column >= (prefix_len as u32)
3170 && snapshot.contains_str_at(
3171 Point::new(
3172 selection.start.row,
3173 selection.start.column - (prefix_len as u32),
3174 ),
3175 &pair.start[..prefix_len],
3176 ));
3177 if preceding_text_matches_prefix {
3178 bracket_pair = Some(pair.clone());
3179 is_bracket_pair_start = true;
3180 break;
3181 }
3182 }
3183 if pair.end.as_str() == text.as_ref() {
3184 bracket_pair = Some(pair.clone());
3185 is_bracket_pair_end = true;
3186 break;
3187 }
3188 }
3189 }
3190
3191 if let Some(bracket_pair) = bracket_pair {
3192 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3193 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3194 let auto_surround =
3195 self.use_auto_surround && snapshot_settings.use_auto_surround;
3196 if selection.is_empty() {
3197 if is_bracket_pair_start {
3198 // If the inserted text is a suffix of an opening bracket and the
3199 // selection is preceded by the rest of the opening bracket, then
3200 // insert the closing bracket.
3201 let following_text_allows_autoclose = snapshot
3202 .chars_at(selection.start)
3203 .next()
3204 .map_or(true, |c| scope.should_autoclose_before(c));
3205
3206 let preceding_text_allows_autoclose = selection.start.column == 0
3207 || snapshot.reversed_chars_at(selection.start).next().map_or(
3208 true,
3209 |c| {
3210 bracket_pair.start != bracket_pair.end
3211 || !snapshot
3212 .char_classifier_at(selection.start)
3213 .is_word(c)
3214 },
3215 );
3216
3217 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3218 && bracket_pair.start.len() == 1
3219 {
3220 let target = bracket_pair.start.chars().next().unwrap();
3221 let current_line_count = snapshot
3222 .reversed_chars_at(selection.start)
3223 .take_while(|&c| c != '\n')
3224 .filter(|&c| c == target)
3225 .count();
3226 current_line_count % 2 == 1
3227 } else {
3228 false
3229 };
3230
3231 if autoclose
3232 && bracket_pair.close
3233 && following_text_allows_autoclose
3234 && preceding_text_allows_autoclose
3235 && !is_closing_quote
3236 {
3237 let anchor = snapshot.anchor_before(selection.end);
3238 new_selections.push((selection.map(|_| anchor), text.len()));
3239 new_autoclose_regions.push((
3240 anchor,
3241 text.len(),
3242 selection.id,
3243 bracket_pair.clone(),
3244 ));
3245 edits.push((
3246 selection.range(),
3247 format!("{}{}", text, bracket_pair.end).into(),
3248 ));
3249 bracket_inserted = true;
3250 continue;
3251 }
3252 }
3253
3254 if let Some(region) = autoclose_region {
3255 // If the selection is followed by an auto-inserted closing bracket,
3256 // then don't insert that closing bracket again; just move the selection
3257 // past the closing bracket.
3258 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3259 && text.as_ref() == region.pair.end.as_str();
3260 if should_skip {
3261 let anchor = snapshot.anchor_after(selection.end);
3262 new_selections
3263 .push((selection.map(|_| anchor), region.pair.end.len()));
3264 continue;
3265 }
3266 }
3267
3268 let always_treat_brackets_as_autoclosed = snapshot
3269 .language_settings_at(selection.start, cx)
3270 .always_treat_brackets_as_autoclosed;
3271 if always_treat_brackets_as_autoclosed
3272 && is_bracket_pair_end
3273 && snapshot.contains_str_at(selection.end, text.as_ref())
3274 {
3275 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3276 // and the inserted text is a closing bracket and the selection is followed
3277 // by the closing bracket then move the selection past the closing bracket.
3278 let anchor = snapshot.anchor_after(selection.end);
3279 new_selections.push((selection.map(|_| anchor), text.len()));
3280 continue;
3281 }
3282 }
3283 // If an opening bracket is 1 character long and is typed while
3284 // text is selected, then surround that text with the bracket pair.
3285 else if auto_surround
3286 && bracket_pair.surround
3287 && is_bracket_pair_start
3288 && bracket_pair.start.chars().count() == 1
3289 {
3290 edits.push((selection.start..selection.start, text.clone()));
3291 edits.push((
3292 selection.end..selection.end,
3293 bracket_pair.end.as_str().into(),
3294 ));
3295 bracket_inserted = true;
3296 new_selections.push((
3297 Selection {
3298 id: selection.id,
3299 start: snapshot.anchor_after(selection.start),
3300 end: snapshot.anchor_before(selection.end),
3301 reversed: selection.reversed,
3302 goal: selection.goal,
3303 },
3304 0,
3305 ));
3306 continue;
3307 }
3308 }
3309 }
3310
3311 if self.auto_replace_emoji_shortcode
3312 && selection.is_empty()
3313 && text.as_ref().ends_with(':')
3314 {
3315 if let Some(possible_emoji_short_code) =
3316 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3317 {
3318 if !possible_emoji_short_code.is_empty() {
3319 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3320 let emoji_shortcode_start = Point::new(
3321 selection.start.row,
3322 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3323 );
3324
3325 // Remove shortcode from buffer
3326 edits.push((
3327 emoji_shortcode_start..selection.start,
3328 "".to_string().into(),
3329 ));
3330 new_selections.push((
3331 Selection {
3332 id: selection.id,
3333 start: snapshot.anchor_after(emoji_shortcode_start),
3334 end: snapshot.anchor_before(selection.start),
3335 reversed: selection.reversed,
3336 goal: selection.goal,
3337 },
3338 0,
3339 ));
3340
3341 // Insert emoji
3342 let selection_start_anchor = snapshot.anchor_after(selection.start);
3343 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3344 edits.push((selection.start..selection.end, emoji.to_string().into()));
3345
3346 continue;
3347 }
3348 }
3349 }
3350 }
3351
3352 // If not handling any auto-close operation, then just replace the selected
3353 // text with the given input and move the selection to the end of the
3354 // newly inserted text.
3355 let anchor = snapshot.anchor_after(selection.end);
3356 if !self.linked_edit_ranges.is_empty() {
3357 let start_anchor = snapshot.anchor_before(selection.start);
3358
3359 let is_word_char = text.chars().next().map_or(true, |char| {
3360 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3361 classifier.is_word(char)
3362 });
3363
3364 if is_word_char {
3365 if let Some(ranges) = self
3366 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3367 {
3368 for (buffer, edits) in ranges {
3369 linked_edits
3370 .entry(buffer.clone())
3371 .or_default()
3372 .extend(edits.into_iter().map(|range| (range, text.clone())));
3373 }
3374 }
3375 } else {
3376 clear_linked_edit_ranges = true;
3377 }
3378 }
3379
3380 new_selections.push((selection.map(|_| anchor), 0));
3381 edits.push((selection.start..selection.end, text.clone()));
3382 }
3383
3384 drop(snapshot);
3385
3386 self.transact(window, cx, |this, window, cx| {
3387 if clear_linked_edit_ranges {
3388 this.linked_edit_ranges.clear();
3389 }
3390 let initial_buffer_versions =
3391 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3392
3393 this.buffer.update(cx, |buffer, cx| {
3394 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3395 });
3396 for (buffer, edits) in linked_edits {
3397 buffer.update(cx, |buffer, cx| {
3398 let snapshot = buffer.snapshot();
3399 let edits = edits
3400 .into_iter()
3401 .map(|(range, text)| {
3402 use text::ToPoint as TP;
3403 let end_point = TP::to_point(&range.end, &snapshot);
3404 let start_point = TP::to_point(&range.start, &snapshot);
3405 (start_point..end_point, text)
3406 })
3407 .sorted_by_key(|(range, _)| range.start);
3408 buffer.edit(edits, None, cx);
3409 })
3410 }
3411 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3412 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3413 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3414 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3415 .zip(new_selection_deltas)
3416 .map(|(selection, delta)| Selection {
3417 id: selection.id,
3418 start: selection.start + delta,
3419 end: selection.end + delta,
3420 reversed: selection.reversed,
3421 goal: SelectionGoal::None,
3422 })
3423 .collect::<Vec<_>>();
3424
3425 let mut i = 0;
3426 for (position, delta, selection_id, pair) in new_autoclose_regions {
3427 let position = position.to_offset(&map.buffer_snapshot) + delta;
3428 let start = map.buffer_snapshot.anchor_before(position);
3429 let end = map.buffer_snapshot.anchor_after(position);
3430 while let Some(existing_state) = this.autoclose_regions.get(i) {
3431 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3432 Ordering::Less => i += 1,
3433 Ordering::Greater => break,
3434 Ordering::Equal => {
3435 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3436 Ordering::Less => i += 1,
3437 Ordering::Equal => break,
3438 Ordering::Greater => break,
3439 }
3440 }
3441 }
3442 }
3443 this.autoclose_regions.insert(
3444 i,
3445 AutocloseRegion {
3446 selection_id,
3447 range: start..end,
3448 pair,
3449 },
3450 );
3451 }
3452
3453 let had_active_inline_completion = this.has_active_inline_completion();
3454 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3455 s.select(new_selections)
3456 });
3457
3458 if !bracket_inserted {
3459 if let Some(on_type_format_task) =
3460 this.trigger_on_type_formatting(text.to_string(), window, cx)
3461 {
3462 on_type_format_task.detach_and_log_err(cx);
3463 }
3464 }
3465
3466 let editor_settings = EditorSettings::get_global(cx);
3467 if bracket_inserted
3468 && (editor_settings.auto_signature_help
3469 || editor_settings.show_signature_help_after_edits)
3470 {
3471 this.show_signature_help(&ShowSignatureHelp, window, cx);
3472 }
3473
3474 let trigger_in_words =
3475 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3476 if this.hard_wrap.is_some() {
3477 let latest: Range<Point> = this.selections.newest(cx).range();
3478 if latest.is_empty()
3479 && this
3480 .buffer()
3481 .read(cx)
3482 .snapshot(cx)
3483 .line_len(MultiBufferRow(latest.start.row))
3484 == latest.start.column
3485 {
3486 this.rewrap_impl(
3487 RewrapOptions {
3488 override_language_settings: true,
3489 preserve_existing_whitespace: true,
3490 },
3491 cx,
3492 )
3493 }
3494 }
3495 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3496 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3497 this.refresh_inline_completion(true, false, window, cx);
3498 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3499 });
3500 }
3501
3502 fn find_possible_emoji_shortcode_at_position(
3503 snapshot: &MultiBufferSnapshot,
3504 position: Point,
3505 ) -> Option<String> {
3506 let mut chars = Vec::new();
3507 let mut found_colon = false;
3508 for char in snapshot.reversed_chars_at(position).take(100) {
3509 // Found a possible emoji shortcode in the middle of the buffer
3510 if found_colon {
3511 if char.is_whitespace() {
3512 chars.reverse();
3513 return Some(chars.iter().collect());
3514 }
3515 // If the previous character is not a whitespace, we are in the middle of a word
3516 // and we only want to complete the shortcode if the word is made up of other emojis
3517 let mut containing_word = String::new();
3518 for ch in snapshot
3519 .reversed_chars_at(position)
3520 .skip(chars.len() + 1)
3521 .take(100)
3522 {
3523 if ch.is_whitespace() {
3524 break;
3525 }
3526 containing_word.push(ch);
3527 }
3528 let containing_word = containing_word.chars().rev().collect::<String>();
3529 if util::word_consists_of_emojis(containing_word.as_str()) {
3530 chars.reverse();
3531 return Some(chars.iter().collect());
3532 }
3533 }
3534
3535 if char.is_whitespace() || !char.is_ascii() {
3536 return None;
3537 }
3538 if char == ':' {
3539 found_colon = true;
3540 } else {
3541 chars.push(char);
3542 }
3543 }
3544 // Found a possible emoji shortcode at the beginning of the buffer
3545 chars.reverse();
3546 Some(chars.iter().collect())
3547 }
3548
3549 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3550 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3551 self.transact(window, cx, |this, window, cx| {
3552 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3553 let selections = this.selections.all::<usize>(cx);
3554 let multi_buffer = this.buffer.read(cx);
3555 let buffer = multi_buffer.snapshot(cx);
3556 selections
3557 .iter()
3558 .map(|selection| {
3559 let start_point = selection.start.to_point(&buffer);
3560 let mut indent =
3561 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3562 indent.len = cmp::min(indent.len, start_point.column);
3563 let start = selection.start;
3564 let end = selection.end;
3565 let selection_is_empty = start == end;
3566 let language_scope = buffer.language_scope_at(start);
3567 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3568 &language_scope
3569 {
3570 let insert_extra_newline =
3571 insert_extra_newline_brackets(&buffer, start..end, language)
3572 || insert_extra_newline_tree_sitter(&buffer, start..end);
3573
3574 // Comment extension on newline is allowed only for cursor selections
3575 let comment_delimiter = maybe!({
3576 if !selection_is_empty {
3577 return None;
3578 }
3579
3580 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3581 return None;
3582 }
3583
3584 let delimiters = language.line_comment_prefixes();
3585 let max_len_of_delimiter =
3586 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3587 let (snapshot, range) =
3588 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3589
3590 let mut index_of_first_non_whitespace = 0;
3591 let comment_candidate = snapshot
3592 .chars_for_range(range)
3593 .skip_while(|c| {
3594 let should_skip = c.is_whitespace();
3595 if should_skip {
3596 index_of_first_non_whitespace += 1;
3597 }
3598 should_skip
3599 })
3600 .take(max_len_of_delimiter)
3601 .collect::<String>();
3602 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3603 comment_candidate.starts_with(comment_prefix.as_ref())
3604 })?;
3605 let cursor_is_placed_after_comment_marker =
3606 index_of_first_non_whitespace + comment_prefix.len()
3607 <= start_point.column as usize;
3608 if cursor_is_placed_after_comment_marker {
3609 Some(comment_prefix.clone())
3610 } else {
3611 None
3612 }
3613 });
3614 (comment_delimiter, insert_extra_newline)
3615 } else {
3616 (None, false)
3617 };
3618
3619 let capacity_for_delimiter = comment_delimiter
3620 .as_deref()
3621 .map(str::len)
3622 .unwrap_or_default();
3623 let mut new_text =
3624 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3625 new_text.push('\n');
3626 new_text.extend(indent.chars());
3627 if let Some(delimiter) = &comment_delimiter {
3628 new_text.push_str(delimiter);
3629 }
3630 if insert_extra_newline {
3631 new_text = new_text.repeat(2);
3632 }
3633
3634 let anchor = buffer.anchor_after(end);
3635 let new_selection = selection.map(|_| anchor);
3636 (
3637 (start..end, new_text),
3638 (insert_extra_newline, new_selection),
3639 )
3640 })
3641 .unzip()
3642 };
3643
3644 this.edit_with_autoindent(edits, cx);
3645 let buffer = this.buffer.read(cx).snapshot(cx);
3646 let new_selections = selection_fixup_info
3647 .into_iter()
3648 .map(|(extra_newline_inserted, new_selection)| {
3649 let mut cursor = new_selection.end.to_point(&buffer);
3650 if extra_newline_inserted {
3651 cursor.row -= 1;
3652 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3653 }
3654 new_selection.map(|_| cursor)
3655 })
3656 .collect();
3657
3658 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3659 s.select(new_selections)
3660 });
3661 this.refresh_inline_completion(true, false, window, cx);
3662 });
3663 }
3664
3665 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3666 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3667
3668 let buffer = self.buffer.read(cx);
3669 let snapshot = buffer.snapshot(cx);
3670
3671 let mut edits = Vec::new();
3672 let mut rows = Vec::new();
3673
3674 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3675 let cursor = selection.head();
3676 let row = cursor.row;
3677
3678 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3679
3680 let newline = "\n".to_string();
3681 edits.push((start_of_line..start_of_line, newline));
3682
3683 rows.push(row + rows_inserted as u32);
3684 }
3685
3686 self.transact(window, cx, |editor, window, cx| {
3687 editor.edit(edits, cx);
3688
3689 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3690 let mut index = 0;
3691 s.move_cursors_with(|map, _, _| {
3692 let row = rows[index];
3693 index += 1;
3694
3695 let point = Point::new(row, 0);
3696 let boundary = map.next_line_boundary(point).1;
3697 let clipped = map.clip_point(boundary, Bias::Left);
3698
3699 (clipped, SelectionGoal::None)
3700 });
3701 });
3702
3703 let mut indent_edits = Vec::new();
3704 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3705 for row in rows {
3706 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3707 for (row, indent) in indents {
3708 if indent.len == 0 {
3709 continue;
3710 }
3711
3712 let text = match indent.kind {
3713 IndentKind::Space => " ".repeat(indent.len as usize),
3714 IndentKind::Tab => "\t".repeat(indent.len as usize),
3715 };
3716 let point = Point::new(row.0, 0);
3717 indent_edits.push((point..point, text));
3718 }
3719 }
3720 editor.edit(indent_edits, cx);
3721 });
3722 }
3723
3724 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3725 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3726
3727 let buffer = self.buffer.read(cx);
3728 let snapshot = buffer.snapshot(cx);
3729
3730 let mut edits = Vec::new();
3731 let mut rows = Vec::new();
3732 let mut rows_inserted = 0;
3733
3734 for selection in self.selections.all_adjusted(cx) {
3735 let cursor = selection.head();
3736 let row = cursor.row;
3737
3738 let point = Point::new(row + 1, 0);
3739 let start_of_line = snapshot.clip_point(point, Bias::Left);
3740
3741 let newline = "\n".to_string();
3742 edits.push((start_of_line..start_of_line, newline));
3743
3744 rows_inserted += 1;
3745 rows.push(row + rows_inserted);
3746 }
3747
3748 self.transact(window, cx, |editor, window, cx| {
3749 editor.edit(edits, cx);
3750
3751 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3752 let mut index = 0;
3753 s.move_cursors_with(|map, _, _| {
3754 let row = rows[index];
3755 index += 1;
3756
3757 let point = Point::new(row, 0);
3758 let boundary = map.next_line_boundary(point).1;
3759 let clipped = map.clip_point(boundary, Bias::Left);
3760
3761 (clipped, SelectionGoal::None)
3762 });
3763 });
3764
3765 let mut indent_edits = Vec::new();
3766 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3767 for row in rows {
3768 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3769 for (row, indent) in indents {
3770 if indent.len == 0 {
3771 continue;
3772 }
3773
3774 let text = match indent.kind {
3775 IndentKind::Space => " ".repeat(indent.len as usize),
3776 IndentKind::Tab => "\t".repeat(indent.len as usize),
3777 };
3778 let point = Point::new(row.0, 0);
3779 indent_edits.push((point..point, text));
3780 }
3781 }
3782 editor.edit(indent_edits, cx);
3783 });
3784 }
3785
3786 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3787 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3788 original_indent_columns: Vec::new(),
3789 });
3790 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3791 }
3792
3793 fn insert_with_autoindent_mode(
3794 &mut self,
3795 text: &str,
3796 autoindent_mode: Option<AutoindentMode>,
3797 window: &mut Window,
3798 cx: &mut Context<Self>,
3799 ) {
3800 if self.read_only(cx) {
3801 return;
3802 }
3803
3804 let text: Arc<str> = text.into();
3805 self.transact(window, cx, |this, window, cx| {
3806 let old_selections = this.selections.all_adjusted(cx);
3807 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3808 let anchors = {
3809 let snapshot = buffer.read(cx);
3810 old_selections
3811 .iter()
3812 .map(|s| {
3813 let anchor = snapshot.anchor_after(s.head());
3814 s.map(|_| anchor)
3815 })
3816 .collect::<Vec<_>>()
3817 };
3818 buffer.edit(
3819 old_selections
3820 .iter()
3821 .map(|s| (s.start..s.end, text.clone())),
3822 autoindent_mode,
3823 cx,
3824 );
3825 anchors
3826 });
3827
3828 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3829 s.select_anchors(selection_anchors);
3830 });
3831
3832 cx.notify();
3833 });
3834 }
3835
3836 fn trigger_completion_on_input(
3837 &mut self,
3838 text: &str,
3839 trigger_in_words: bool,
3840 window: &mut Window,
3841 cx: &mut Context<Self>,
3842 ) {
3843 let ignore_completion_provider = self
3844 .context_menu
3845 .borrow()
3846 .as_ref()
3847 .map(|menu| match menu {
3848 CodeContextMenu::Completions(completions_menu) => {
3849 completions_menu.ignore_completion_provider
3850 }
3851 CodeContextMenu::CodeActions(_) => false,
3852 })
3853 .unwrap_or(false);
3854
3855 if ignore_completion_provider {
3856 self.show_word_completions(&ShowWordCompletions, window, cx);
3857 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3858 self.show_completions(
3859 &ShowCompletions {
3860 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3861 },
3862 window,
3863 cx,
3864 );
3865 } else {
3866 self.hide_context_menu(window, cx);
3867 }
3868 }
3869
3870 fn is_completion_trigger(
3871 &self,
3872 text: &str,
3873 trigger_in_words: bool,
3874 cx: &mut Context<Self>,
3875 ) -> bool {
3876 let position = self.selections.newest_anchor().head();
3877 let multibuffer = self.buffer.read(cx);
3878 let Some(buffer) = position
3879 .buffer_id
3880 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3881 else {
3882 return false;
3883 };
3884
3885 if let Some(completion_provider) = &self.completion_provider {
3886 completion_provider.is_completion_trigger(
3887 &buffer,
3888 position.text_anchor,
3889 text,
3890 trigger_in_words,
3891 cx,
3892 )
3893 } else {
3894 false
3895 }
3896 }
3897
3898 /// If any empty selections is touching the start of its innermost containing autoclose
3899 /// region, expand it to select the brackets.
3900 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3901 let selections = self.selections.all::<usize>(cx);
3902 let buffer = self.buffer.read(cx).read(cx);
3903 let new_selections = self
3904 .selections_with_autoclose_regions(selections, &buffer)
3905 .map(|(mut selection, region)| {
3906 if !selection.is_empty() {
3907 return selection;
3908 }
3909
3910 if let Some(region) = region {
3911 let mut range = region.range.to_offset(&buffer);
3912 if selection.start == range.start && range.start >= region.pair.start.len() {
3913 range.start -= region.pair.start.len();
3914 if buffer.contains_str_at(range.start, ®ion.pair.start)
3915 && buffer.contains_str_at(range.end, ®ion.pair.end)
3916 {
3917 range.end += region.pair.end.len();
3918 selection.start = range.start;
3919 selection.end = range.end;
3920
3921 return selection;
3922 }
3923 }
3924 }
3925
3926 let always_treat_brackets_as_autoclosed = buffer
3927 .language_settings_at(selection.start, cx)
3928 .always_treat_brackets_as_autoclosed;
3929
3930 if !always_treat_brackets_as_autoclosed {
3931 return selection;
3932 }
3933
3934 if let Some(scope) = buffer.language_scope_at(selection.start) {
3935 for (pair, enabled) in scope.brackets() {
3936 if !enabled || !pair.close {
3937 continue;
3938 }
3939
3940 if buffer.contains_str_at(selection.start, &pair.end) {
3941 let pair_start_len = pair.start.len();
3942 if buffer.contains_str_at(
3943 selection.start.saturating_sub(pair_start_len),
3944 &pair.start,
3945 ) {
3946 selection.start -= pair_start_len;
3947 selection.end += pair.end.len();
3948
3949 return selection;
3950 }
3951 }
3952 }
3953 }
3954
3955 selection
3956 })
3957 .collect();
3958
3959 drop(buffer);
3960 self.change_selections(None, window, cx, |selections| {
3961 selections.select(new_selections)
3962 });
3963 }
3964
3965 /// Iterate the given selections, and for each one, find the smallest surrounding
3966 /// autoclose region. This uses the ordering of the selections and the autoclose
3967 /// regions to avoid repeated comparisons.
3968 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3969 &'a self,
3970 selections: impl IntoIterator<Item = Selection<D>>,
3971 buffer: &'a MultiBufferSnapshot,
3972 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3973 let mut i = 0;
3974 let mut regions = self.autoclose_regions.as_slice();
3975 selections.into_iter().map(move |selection| {
3976 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3977
3978 let mut enclosing = None;
3979 while let Some(pair_state) = regions.get(i) {
3980 if pair_state.range.end.to_offset(buffer) < range.start {
3981 regions = ®ions[i + 1..];
3982 i = 0;
3983 } else if pair_state.range.start.to_offset(buffer) > range.end {
3984 break;
3985 } else {
3986 if pair_state.selection_id == selection.id {
3987 enclosing = Some(pair_state);
3988 }
3989 i += 1;
3990 }
3991 }
3992
3993 (selection, enclosing)
3994 })
3995 }
3996
3997 /// Remove any autoclose regions that no longer contain their selection.
3998 fn invalidate_autoclose_regions(
3999 &mut self,
4000 mut selections: &[Selection<Anchor>],
4001 buffer: &MultiBufferSnapshot,
4002 ) {
4003 self.autoclose_regions.retain(|state| {
4004 let mut i = 0;
4005 while let Some(selection) = selections.get(i) {
4006 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4007 selections = &selections[1..];
4008 continue;
4009 }
4010 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4011 break;
4012 }
4013 if selection.id == state.selection_id {
4014 return true;
4015 } else {
4016 i += 1;
4017 }
4018 }
4019 false
4020 });
4021 }
4022
4023 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4024 let offset = position.to_offset(buffer);
4025 let (word_range, kind) = buffer.surrounding_word(offset, true);
4026 if offset > word_range.start && kind == Some(CharKind::Word) {
4027 Some(
4028 buffer
4029 .text_for_range(word_range.start..offset)
4030 .collect::<String>(),
4031 )
4032 } else {
4033 None
4034 }
4035 }
4036
4037 pub fn toggle_inlay_hints(
4038 &mut self,
4039 _: &ToggleInlayHints,
4040 _: &mut Window,
4041 cx: &mut Context<Self>,
4042 ) {
4043 self.refresh_inlay_hints(
4044 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4045 cx,
4046 );
4047 }
4048
4049 pub fn inlay_hints_enabled(&self) -> bool {
4050 self.inlay_hint_cache.enabled
4051 }
4052
4053 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4054 if self.semantics_provider.is_none() || !self.mode.is_full() {
4055 return;
4056 }
4057
4058 let reason_description = reason.description();
4059 let ignore_debounce = matches!(
4060 reason,
4061 InlayHintRefreshReason::SettingsChange(_)
4062 | InlayHintRefreshReason::Toggle(_)
4063 | InlayHintRefreshReason::ExcerptsRemoved(_)
4064 | InlayHintRefreshReason::ModifiersChanged(_)
4065 );
4066 let (invalidate_cache, required_languages) = match reason {
4067 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4068 match self.inlay_hint_cache.modifiers_override(enabled) {
4069 Some(enabled) => {
4070 if enabled {
4071 (InvalidationStrategy::RefreshRequested, None)
4072 } else {
4073 self.splice_inlays(
4074 &self
4075 .visible_inlay_hints(cx)
4076 .iter()
4077 .map(|inlay| inlay.id)
4078 .collect::<Vec<InlayId>>(),
4079 Vec::new(),
4080 cx,
4081 );
4082 return;
4083 }
4084 }
4085 None => return,
4086 }
4087 }
4088 InlayHintRefreshReason::Toggle(enabled) => {
4089 if self.inlay_hint_cache.toggle(enabled) {
4090 if enabled {
4091 (InvalidationStrategy::RefreshRequested, None)
4092 } else {
4093 self.splice_inlays(
4094 &self
4095 .visible_inlay_hints(cx)
4096 .iter()
4097 .map(|inlay| inlay.id)
4098 .collect::<Vec<InlayId>>(),
4099 Vec::new(),
4100 cx,
4101 );
4102 return;
4103 }
4104 } else {
4105 return;
4106 }
4107 }
4108 InlayHintRefreshReason::SettingsChange(new_settings) => {
4109 match self.inlay_hint_cache.update_settings(
4110 &self.buffer,
4111 new_settings,
4112 self.visible_inlay_hints(cx),
4113 cx,
4114 ) {
4115 ControlFlow::Break(Some(InlaySplice {
4116 to_remove,
4117 to_insert,
4118 })) => {
4119 self.splice_inlays(&to_remove, to_insert, cx);
4120 return;
4121 }
4122 ControlFlow::Break(None) => return,
4123 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4124 }
4125 }
4126 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4127 if let Some(InlaySplice {
4128 to_remove,
4129 to_insert,
4130 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4131 {
4132 self.splice_inlays(&to_remove, to_insert, cx);
4133 }
4134 return;
4135 }
4136 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4137 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4138 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4139 }
4140 InlayHintRefreshReason::RefreshRequested => {
4141 (InvalidationStrategy::RefreshRequested, None)
4142 }
4143 };
4144
4145 if let Some(InlaySplice {
4146 to_remove,
4147 to_insert,
4148 }) = self.inlay_hint_cache.spawn_hint_refresh(
4149 reason_description,
4150 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4151 invalidate_cache,
4152 ignore_debounce,
4153 cx,
4154 ) {
4155 self.splice_inlays(&to_remove, to_insert, cx);
4156 }
4157 }
4158
4159 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4160 self.display_map
4161 .read(cx)
4162 .current_inlays()
4163 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4164 .cloned()
4165 .collect()
4166 }
4167
4168 pub fn excerpts_for_inlay_hints_query(
4169 &self,
4170 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4171 cx: &mut Context<Editor>,
4172 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4173 let Some(project) = self.project.as_ref() else {
4174 return HashMap::default();
4175 };
4176 let project = project.read(cx);
4177 let multi_buffer = self.buffer().read(cx);
4178 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4179 let multi_buffer_visible_start = self
4180 .scroll_manager
4181 .anchor()
4182 .anchor
4183 .to_point(&multi_buffer_snapshot);
4184 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4185 multi_buffer_visible_start
4186 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4187 Bias::Left,
4188 );
4189 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4190 multi_buffer_snapshot
4191 .range_to_buffer_ranges(multi_buffer_visible_range)
4192 .into_iter()
4193 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4194 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4195 let buffer_file = project::File::from_dyn(buffer.file())?;
4196 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4197 let worktree_entry = buffer_worktree
4198 .read(cx)
4199 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4200 if worktree_entry.is_ignored {
4201 return None;
4202 }
4203
4204 let language = buffer.language()?;
4205 if let Some(restrict_to_languages) = restrict_to_languages {
4206 if !restrict_to_languages.contains(language) {
4207 return None;
4208 }
4209 }
4210 Some((
4211 excerpt_id,
4212 (
4213 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4214 buffer.version().clone(),
4215 excerpt_visible_range,
4216 ),
4217 ))
4218 })
4219 .collect()
4220 }
4221
4222 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4223 TextLayoutDetails {
4224 text_system: window.text_system().clone(),
4225 editor_style: self.style.clone().unwrap(),
4226 rem_size: window.rem_size(),
4227 scroll_anchor: self.scroll_manager.anchor(),
4228 visible_rows: self.visible_line_count(),
4229 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4230 }
4231 }
4232
4233 pub fn splice_inlays(
4234 &self,
4235 to_remove: &[InlayId],
4236 to_insert: Vec<Inlay>,
4237 cx: &mut Context<Self>,
4238 ) {
4239 self.display_map.update(cx, |display_map, cx| {
4240 display_map.splice_inlays(to_remove, to_insert, cx)
4241 });
4242 cx.notify();
4243 }
4244
4245 fn trigger_on_type_formatting(
4246 &self,
4247 input: String,
4248 window: &mut Window,
4249 cx: &mut Context<Self>,
4250 ) -> Option<Task<Result<()>>> {
4251 if input.len() != 1 {
4252 return None;
4253 }
4254
4255 let project = self.project.as_ref()?;
4256 let position = self.selections.newest_anchor().head();
4257 let (buffer, buffer_position) = self
4258 .buffer
4259 .read(cx)
4260 .text_anchor_for_position(position, cx)?;
4261
4262 let settings = language_settings::language_settings(
4263 buffer
4264 .read(cx)
4265 .language_at(buffer_position)
4266 .map(|l| l.name()),
4267 buffer.read(cx).file(),
4268 cx,
4269 );
4270 if !settings.use_on_type_format {
4271 return None;
4272 }
4273
4274 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4275 // hence we do LSP request & edit on host side only — add formats to host's history.
4276 let push_to_lsp_host_history = true;
4277 // If this is not the host, append its history with new edits.
4278 let push_to_client_history = project.read(cx).is_via_collab();
4279
4280 let on_type_formatting = project.update(cx, |project, cx| {
4281 project.on_type_format(
4282 buffer.clone(),
4283 buffer_position,
4284 input,
4285 push_to_lsp_host_history,
4286 cx,
4287 )
4288 });
4289 Some(cx.spawn_in(window, async move |editor, cx| {
4290 if let Some(transaction) = on_type_formatting.await? {
4291 if push_to_client_history {
4292 buffer
4293 .update(cx, |buffer, _| {
4294 buffer.push_transaction(transaction, Instant::now());
4295 buffer.finalize_last_transaction();
4296 })
4297 .ok();
4298 }
4299 editor.update(cx, |editor, cx| {
4300 editor.refresh_document_highlights(cx);
4301 })?;
4302 }
4303 Ok(())
4304 }))
4305 }
4306
4307 pub fn show_word_completions(
4308 &mut self,
4309 _: &ShowWordCompletions,
4310 window: &mut Window,
4311 cx: &mut Context<Self>,
4312 ) {
4313 self.open_completions_menu(true, None, window, cx);
4314 }
4315
4316 pub fn show_completions(
4317 &mut self,
4318 options: &ShowCompletions,
4319 window: &mut Window,
4320 cx: &mut Context<Self>,
4321 ) {
4322 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4323 }
4324
4325 fn open_completions_menu(
4326 &mut self,
4327 ignore_completion_provider: bool,
4328 trigger: Option<&str>,
4329 window: &mut Window,
4330 cx: &mut Context<Self>,
4331 ) {
4332 if self.pending_rename.is_some() {
4333 return;
4334 }
4335 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4336 return;
4337 }
4338
4339 let position = self.selections.newest_anchor().head();
4340 if position.diff_base_anchor.is_some() {
4341 return;
4342 }
4343 let (buffer, buffer_position) =
4344 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4345 output
4346 } else {
4347 return;
4348 };
4349 let buffer_snapshot = buffer.read(cx).snapshot();
4350 let show_completion_documentation = buffer_snapshot
4351 .settings_at(buffer_position, cx)
4352 .show_completion_documentation;
4353
4354 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4355
4356 let trigger_kind = match trigger {
4357 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4358 CompletionTriggerKind::TRIGGER_CHARACTER
4359 }
4360 _ => CompletionTriggerKind::INVOKED,
4361 };
4362 let completion_context = CompletionContext {
4363 trigger_character: trigger.and_then(|trigger| {
4364 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4365 Some(String::from(trigger))
4366 } else {
4367 None
4368 }
4369 }),
4370 trigger_kind,
4371 };
4372
4373 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4374 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4375 let word_to_exclude = buffer_snapshot
4376 .text_for_range(old_range.clone())
4377 .collect::<String>();
4378 (
4379 buffer_snapshot.anchor_before(old_range.start)
4380 ..buffer_snapshot.anchor_after(old_range.end),
4381 Some(word_to_exclude),
4382 )
4383 } else {
4384 (buffer_position..buffer_position, None)
4385 };
4386
4387 let completion_settings = language_settings(
4388 buffer_snapshot
4389 .language_at(buffer_position)
4390 .map(|language| language.name()),
4391 buffer_snapshot.file(),
4392 cx,
4393 )
4394 .completions;
4395
4396 // The document can be large, so stay in reasonable bounds when searching for words,
4397 // otherwise completion pop-up might be slow to appear.
4398 const WORD_LOOKUP_ROWS: u32 = 5_000;
4399 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4400 let min_word_search = buffer_snapshot.clip_point(
4401 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4402 Bias::Left,
4403 );
4404 let max_word_search = buffer_snapshot.clip_point(
4405 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4406 Bias::Right,
4407 );
4408 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4409 ..buffer_snapshot.point_to_offset(max_word_search);
4410
4411 let provider = self
4412 .completion_provider
4413 .as_ref()
4414 .filter(|_| !ignore_completion_provider);
4415 let skip_digits = query
4416 .as_ref()
4417 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4418
4419 let (mut words, provided_completions) = match provider {
4420 Some(provider) => {
4421 let completions = provider.completions(
4422 position.excerpt_id,
4423 &buffer,
4424 buffer_position,
4425 completion_context,
4426 window,
4427 cx,
4428 );
4429
4430 let words = match completion_settings.words {
4431 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4432 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4433 .background_spawn(async move {
4434 buffer_snapshot.words_in_range(WordsQuery {
4435 fuzzy_contents: None,
4436 range: word_search_range,
4437 skip_digits,
4438 })
4439 }),
4440 };
4441
4442 (words, completions)
4443 }
4444 None => (
4445 cx.background_spawn(async move {
4446 buffer_snapshot.words_in_range(WordsQuery {
4447 fuzzy_contents: None,
4448 range: word_search_range,
4449 skip_digits,
4450 })
4451 }),
4452 Task::ready(Ok(None)),
4453 ),
4454 };
4455
4456 let sort_completions = provider
4457 .as_ref()
4458 .map_or(false, |provider| provider.sort_completions());
4459
4460 let filter_completions = provider
4461 .as_ref()
4462 .map_or(true, |provider| provider.filter_completions());
4463
4464 let id = post_inc(&mut self.next_completion_id);
4465 let task = cx.spawn_in(window, async move |editor, cx| {
4466 async move {
4467 editor.update(cx, |this, _| {
4468 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4469 })?;
4470
4471 let mut completions = Vec::new();
4472 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4473 completions.extend(provided_completions);
4474 if completion_settings.words == WordsCompletionMode::Fallback {
4475 words = Task::ready(BTreeMap::default());
4476 }
4477 }
4478
4479 let mut words = words.await;
4480 if let Some(word_to_exclude) = &word_to_exclude {
4481 words.remove(word_to_exclude);
4482 }
4483 for lsp_completion in &completions {
4484 words.remove(&lsp_completion.new_text);
4485 }
4486 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4487 replace_range: old_range.clone(),
4488 new_text: word.clone(),
4489 label: CodeLabel::plain(word, None),
4490 icon_path: None,
4491 documentation: None,
4492 source: CompletionSource::BufferWord {
4493 word_range,
4494 resolved: false,
4495 },
4496 insert_text_mode: Some(InsertTextMode::AS_IS),
4497 confirm: None,
4498 }));
4499
4500 let menu = if completions.is_empty() {
4501 None
4502 } else {
4503 let mut menu = CompletionsMenu::new(
4504 id,
4505 sort_completions,
4506 show_completion_documentation,
4507 ignore_completion_provider,
4508 position,
4509 buffer.clone(),
4510 completions.into(),
4511 );
4512
4513 menu.filter(
4514 if filter_completions {
4515 query.as_deref()
4516 } else {
4517 None
4518 },
4519 cx.background_executor().clone(),
4520 )
4521 .await;
4522
4523 menu.visible().then_some(menu)
4524 };
4525
4526 editor.update_in(cx, |editor, window, cx| {
4527 match editor.context_menu.borrow().as_ref() {
4528 None => {}
4529 Some(CodeContextMenu::Completions(prev_menu)) => {
4530 if prev_menu.id > id {
4531 return;
4532 }
4533 }
4534 _ => return,
4535 }
4536
4537 if editor.focus_handle.is_focused(window) && menu.is_some() {
4538 let mut menu = menu.unwrap();
4539 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4540
4541 *editor.context_menu.borrow_mut() =
4542 Some(CodeContextMenu::Completions(menu));
4543
4544 if editor.show_edit_predictions_in_menu() {
4545 editor.update_visible_inline_completion(window, cx);
4546 } else {
4547 editor.discard_inline_completion(false, cx);
4548 }
4549
4550 cx.notify();
4551 } else if editor.completion_tasks.len() <= 1 {
4552 // If there are no more completion tasks and the last menu was
4553 // empty, we should hide it.
4554 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4555 // If it was already hidden and we don't show inline
4556 // completions in the menu, we should also show the
4557 // inline-completion when available.
4558 if was_hidden && editor.show_edit_predictions_in_menu() {
4559 editor.update_visible_inline_completion(window, cx);
4560 }
4561 }
4562 })?;
4563
4564 anyhow::Ok(())
4565 }
4566 .log_err()
4567 .await
4568 });
4569
4570 self.completion_tasks.push((id, task));
4571 }
4572
4573 #[cfg(feature = "test-support")]
4574 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4575 let menu = self.context_menu.borrow();
4576 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4577 let completions = menu.completions.borrow();
4578 Some(completions.to_vec())
4579 } else {
4580 None
4581 }
4582 }
4583
4584 pub fn confirm_completion(
4585 &mut self,
4586 action: &ConfirmCompletion,
4587 window: &mut Window,
4588 cx: &mut Context<Self>,
4589 ) -> Option<Task<Result<()>>> {
4590 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4591 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4592 }
4593
4594 pub fn confirm_completion_insert(
4595 &mut self,
4596 _: &ConfirmCompletionInsert,
4597 window: &mut Window,
4598 cx: &mut Context<Self>,
4599 ) -> Option<Task<Result<()>>> {
4600 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4601 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4602 }
4603
4604 pub fn confirm_completion_replace(
4605 &mut self,
4606 _: &ConfirmCompletionReplace,
4607 window: &mut Window,
4608 cx: &mut Context<Self>,
4609 ) -> Option<Task<Result<()>>> {
4610 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4611 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4612 }
4613
4614 pub fn compose_completion(
4615 &mut self,
4616 action: &ComposeCompletion,
4617 window: &mut Window,
4618 cx: &mut Context<Self>,
4619 ) -> Option<Task<Result<()>>> {
4620 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4621 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4622 }
4623
4624 fn do_completion(
4625 &mut self,
4626 item_ix: Option<usize>,
4627 intent: CompletionIntent,
4628 window: &mut Window,
4629 cx: &mut Context<Editor>,
4630 ) -> Option<Task<Result<()>>> {
4631 use language::ToOffset as _;
4632
4633 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4634 else {
4635 return None;
4636 };
4637
4638 let candidate_id = {
4639 let entries = completions_menu.entries.borrow();
4640 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4641 if self.show_edit_predictions_in_menu() {
4642 self.discard_inline_completion(true, cx);
4643 }
4644 mat.candidate_id
4645 };
4646
4647 let buffer_handle = completions_menu.buffer;
4648 let completion = completions_menu
4649 .completions
4650 .borrow()
4651 .get(candidate_id)?
4652 .clone();
4653 cx.stop_propagation();
4654
4655 let snippet;
4656 let new_text;
4657 if completion.is_snippet() {
4658 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4659 new_text = snippet.as_ref().unwrap().text.clone();
4660 } else {
4661 snippet = None;
4662 new_text = completion.new_text.clone();
4663 };
4664 let selections = self.selections.all::<usize>(cx);
4665
4666 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4667 let buffer = buffer_handle.read(cx);
4668 let old_text = buffer
4669 .text_for_range(replace_range.clone())
4670 .collect::<String>();
4671
4672 let newest_selection = self.selections.newest_anchor();
4673 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4674 return None;
4675 }
4676
4677 let lookbehind = newest_selection
4678 .start
4679 .text_anchor
4680 .to_offset(buffer)
4681 .saturating_sub(replace_range.start);
4682 let lookahead = replace_range
4683 .end
4684 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4685 let mut common_prefix_len = 0;
4686 for (a, b) in old_text.chars().zip(new_text.chars()) {
4687 if a == b {
4688 common_prefix_len += a.len_utf8();
4689 } else {
4690 break;
4691 }
4692 }
4693
4694 let snapshot = self.buffer.read(cx).snapshot(cx);
4695 let mut range_to_replace: Option<Range<usize>> = None;
4696 let mut ranges = Vec::new();
4697 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4698 for selection in &selections {
4699 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4700 let start = selection.start.saturating_sub(lookbehind);
4701 let end = selection.end + lookahead;
4702 if selection.id == newest_selection.id {
4703 range_to_replace = Some(start + common_prefix_len..end);
4704 }
4705 ranges.push(start + common_prefix_len..end);
4706 } else {
4707 common_prefix_len = 0;
4708 ranges.clear();
4709 ranges.extend(selections.iter().map(|s| {
4710 if s.id == newest_selection.id {
4711 range_to_replace = Some(replace_range.clone());
4712 replace_range.clone()
4713 } else {
4714 s.start..s.end
4715 }
4716 }));
4717 break;
4718 }
4719 if !self.linked_edit_ranges.is_empty() {
4720 let start_anchor = snapshot.anchor_before(selection.head());
4721 let end_anchor = snapshot.anchor_after(selection.tail());
4722 if let Some(ranges) = self
4723 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4724 {
4725 for (buffer, edits) in ranges {
4726 linked_edits.entry(buffer.clone()).or_default().extend(
4727 edits
4728 .into_iter()
4729 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4730 );
4731 }
4732 }
4733 }
4734 }
4735 let text = &new_text[common_prefix_len..];
4736
4737 let utf16_range_to_replace = range_to_replace.map(|range| {
4738 let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
4739 let selection_start_utf16 = newest_selection.start.0 as isize;
4740
4741 range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4742 ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4743 });
4744 cx.emit(EditorEvent::InputHandled {
4745 utf16_range_to_replace,
4746 text: text.into(),
4747 });
4748
4749 self.transact(window, cx, |this, window, cx| {
4750 if let Some(mut snippet) = snippet {
4751 snippet.text = text.to_string();
4752 for tabstop in snippet
4753 .tabstops
4754 .iter_mut()
4755 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4756 {
4757 tabstop.start -= common_prefix_len as isize;
4758 tabstop.end -= common_prefix_len as isize;
4759 }
4760
4761 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4762 } else {
4763 this.buffer.update(cx, |buffer, cx| {
4764 let edits = ranges.iter().map(|range| (range.clone(), text));
4765 let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
4766 {
4767 None
4768 } else {
4769 this.autoindent_mode.clone()
4770 };
4771 buffer.edit(edits, auto_indent, cx);
4772 });
4773 }
4774 for (buffer, edits) in linked_edits {
4775 buffer.update(cx, |buffer, cx| {
4776 let snapshot = buffer.snapshot();
4777 let edits = edits
4778 .into_iter()
4779 .map(|(range, text)| {
4780 use text::ToPoint as TP;
4781 let end_point = TP::to_point(&range.end, &snapshot);
4782 let start_point = TP::to_point(&range.start, &snapshot);
4783 (start_point..end_point, text)
4784 })
4785 .sorted_by_key(|(range, _)| range.start);
4786 buffer.edit(edits, None, cx);
4787 })
4788 }
4789
4790 this.refresh_inline_completion(true, false, window, cx);
4791 });
4792
4793 let show_new_completions_on_confirm = completion
4794 .confirm
4795 .as_ref()
4796 .map_or(false, |confirm| confirm(intent, window, cx));
4797 if show_new_completions_on_confirm {
4798 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4799 }
4800
4801 let provider = self.completion_provider.as_ref()?;
4802 drop(completion);
4803 let apply_edits = provider.apply_additional_edits_for_completion(
4804 buffer_handle,
4805 completions_menu.completions.clone(),
4806 candidate_id,
4807 true,
4808 cx,
4809 );
4810
4811 let editor_settings = EditorSettings::get_global(cx);
4812 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4813 // After the code completion is finished, users often want to know what signatures are needed.
4814 // so we should automatically call signature_help
4815 self.show_signature_help(&ShowSignatureHelp, window, cx);
4816 }
4817
4818 Some(cx.foreground_executor().spawn(async move {
4819 apply_edits.await?;
4820 Ok(())
4821 }))
4822 }
4823
4824 pub fn toggle_code_actions(
4825 &mut self,
4826 action: &ToggleCodeActions,
4827 window: &mut Window,
4828 cx: &mut Context<Self>,
4829 ) {
4830 let mut context_menu = self.context_menu.borrow_mut();
4831 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4832 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4833 // Toggle if we're selecting the same one
4834 *context_menu = None;
4835 cx.notify();
4836 return;
4837 } else {
4838 // Otherwise, clear it and start a new one
4839 *context_menu = None;
4840 cx.notify();
4841 }
4842 }
4843 drop(context_menu);
4844 let snapshot = self.snapshot(window, cx);
4845 let deployed_from_indicator = action.deployed_from_indicator;
4846 let mut task = self.code_actions_task.take();
4847 let action = action.clone();
4848 cx.spawn_in(window, async move |editor, cx| {
4849 while let Some(prev_task) = task {
4850 prev_task.await.log_err();
4851 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4852 }
4853
4854 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4855 if editor.focus_handle.is_focused(window) {
4856 let multibuffer_point = action
4857 .deployed_from_indicator
4858 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4859 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4860 let (buffer, buffer_row) = snapshot
4861 .buffer_snapshot
4862 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4863 .and_then(|(buffer_snapshot, range)| {
4864 editor
4865 .buffer
4866 .read(cx)
4867 .buffer(buffer_snapshot.remote_id())
4868 .map(|buffer| (buffer, range.start.row))
4869 })?;
4870 let (_, code_actions) = editor
4871 .available_code_actions
4872 .clone()
4873 .and_then(|(location, code_actions)| {
4874 let snapshot = location.buffer.read(cx).snapshot();
4875 let point_range = location.range.to_point(&snapshot);
4876 let point_range = point_range.start.row..=point_range.end.row;
4877 if point_range.contains(&buffer_row) {
4878 Some((location, code_actions))
4879 } else {
4880 None
4881 }
4882 })
4883 .unzip();
4884 let buffer_id = buffer.read(cx).remote_id();
4885 let tasks = editor
4886 .tasks
4887 .get(&(buffer_id, buffer_row))
4888 .map(|t| Arc::new(t.to_owned()));
4889 if tasks.is_none() && code_actions.is_none() {
4890 return None;
4891 }
4892
4893 editor.completion_tasks.clear();
4894 editor.discard_inline_completion(false, cx);
4895 let task_context =
4896 tasks
4897 .as_ref()
4898 .zip(editor.project.clone())
4899 .map(|(tasks, project)| {
4900 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4901 });
4902
4903 let debugger_flag = cx.has_flag::<Debugger>();
4904
4905 Some(cx.spawn_in(window, async move |editor, cx| {
4906 let task_context = match task_context {
4907 Some(task_context) => task_context.await,
4908 None => None,
4909 };
4910 let resolved_tasks =
4911 tasks.zip(task_context).map(|(tasks, task_context)| {
4912 Rc::new(ResolvedTasks {
4913 templates: tasks.resolve(&task_context).collect(),
4914 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4915 multibuffer_point.row,
4916 tasks.column,
4917 )),
4918 })
4919 });
4920 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
4921 tasks
4922 .templates
4923 .iter()
4924 .filter(|task| {
4925 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4926 debugger_flag
4927 } else {
4928 true
4929 }
4930 })
4931 .count()
4932 == 1
4933 }) && code_actions
4934 .as_ref()
4935 .map_or(true, |actions| actions.is_empty());
4936 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4937 *editor.context_menu.borrow_mut() =
4938 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4939 buffer,
4940 actions: CodeActionContents {
4941 tasks: resolved_tasks,
4942 actions: code_actions,
4943 },
4944 selected_item: Default::default(),
4945 scroll_handle: UniformListScrollHandle::default(),
4946 deployed_from_indicator,
4947 }));
4948 if spawn_straight_away {
4949 if let Some(task) = editor.confirm_code_action(
4950 &ConfirmCodeAction { item_ix: Some(0) },
4951 window,
4952 cx,
4953 ) {
4954 cx.notify();
4955 return task;
4956 }
4957 }
4958 cx.notify();
4959 Task::ready(Ok(()))
4960 }) {
4961 task.await
4962 } else {
4963 Ok(())
4964 }
4965 }))
4966 } else {
4967 Some(Task::ready(Ok(())))
4968 }
4969 })?;
4970 if let Some(task) = spawned_test_task {
4971 task.await?;
4972 }
4973
4974 Ok::<_, anyhow::Error>(())
4975 })
4976 .detach_and_log_err(cx);
4977 }
4978
4979 pub fn confirm_code_action(
4980 &mut self,
4981 action: &ConfirmCodeAction,
4982 window: &mut Window,
4983 cx: &mut Context<Self>,
4984 ) -> Option<Task<Result<()>>> {
4985 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4986
4987 let actions_menu =
4988 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4989 menu
4990 } else {
4991 return None;
4992 };
4993
4994 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4995 let action = actions_menu.actions.get(action_ix)?;
4996 let title = action.label();
4997 let buffer = actions_menu.buffer;
4998 let workspace = self.workspace()?;
4999
5000 match action {
5001 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5002 match resolved_task.task_type() {
5003 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5004 workspace::tasks::schedule_resolved_task(
5005 workspace,
5006 task_source_kind,
5007 resolved_task,
5008 false,
5009 cx,
5010 );
5011
5012 Some(Task::ready(Ok(())))
5013 }),
5014 task::TaskType::Debug(debug_args) => {
5015 if debug_args.locator.is_some() {
5016 workspace.update(cx, |workspace, cx| {
5017 workspace::tasks::schedule_resolved_task(
5018 workspace,
5019 task_source_kind,
5020 resolved_task,
5021 false,
5022 cx,
5023 );
5024 });
5025
5026 return Some(Task::ready(Ok(())));
5027 }
5028
5029 if let Some(project) = self.project.as_ref() {
5030 project
5031 .update(cx, |project, cx| {
5032 project.start_debug_session(
5033 resolved_task.resolved_debug_adapter_config().unwrap(),
5034 cx,
5035 )
5036 })
5037 .detach_and_log_err(cx);
5038 Some(Task::ready(Ok(())))
5039 } else {
5040 Some(Task::ready(Ok(())))
5041 }
5042 }
5043 }
5044 }
5045 CodeActionsItem::CodeAction {
5046 excerpt_id,
5047 action,
5048 provider,
5049 } => {
5050 let apply_code_action =
5051 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5052 let workspace = workspace.downgrade();
5053 Some(cx.spawn_in(window, async move |editor, cx| {
5054 let project_transaction = apply_code_action.await?;
5055 Self::open_project_transaction(
5056 &editor,
5057 workspace,
5058 project_transaction,
5059 title,
5060 cx,
5061 )
5062 .await
5063 }))
5064 }
5065 }
5066 }
5067
5068 pub async fn open_project_transaction(
5069 this: &WeakEntity<Editor>,
5070 workspace: WeakEntity<Workspace>,
5071 transaction: ProjectTransaction,
5072 title: String,
5073 cx: &mut AsyncWindowContext,
5074 ) -> Result<()> {
5075 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5076 cx.update(|_, cx| {
5077 entries.sort_unstable_by_key(|(buffer, _)| {
5078 buffer.read(cx).file().map(|f| f.path().clone())
5079 });
5080 })?;
5081
5082 // If the project transaction's edits are all contained within this editor, then
5083 // avoid opening a new editor to display them.
5084
5085 if let Some((buffer, transaction)) = entries.first() {
5086 if entries.len() == 1 {
5087 let excerpt = this.update(cx, |editor, cx| {
5088 editor
5089 .buffer()
5090 .read(cx)
5091 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5092 })?;
5093 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5094 if excerpted_buffer == *buffer {
5095 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5096 let excerpt_range = excerpt_range.to_offset(buffer);
5097 buffer
5098 .edited_ranges_for_transaction::<usize>(transaction)
5099 .all(|range| {
5100 excerpt_range.start <= range.start
5101 && excerpt_range.end >= range.end
5102 })
5103 })?;
5104
5105 if all_edits_within_excerpt {
5106 return Ok(());
5107 }
5108 }
5109 }
5110 }
5111 } else {
5112 return Ok(());
5113 }
5114
5115 let mut ranges_to_highlight = Vec::new();
5116 let excerpt_buffer = cx.new(|cx| {
5117 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5118 for (buffer_handle, transaction) in &entries {
5119 let edited_ranges = buffer_handle
5120 .read(cx)
5121 .edited_ranges_for_transaction::<Point>(transaction)
5122 .collect::<Vec<_>>();
5123 let (ranges, _) = multibuffer.set_excerpts_for_path(
5124 PathKey::for_buffer(buffer_handle, cx),
5125 buffer_handle.clone(),
5126 edited_ranges,
5127 DEFAULT_MULTIBUFFER_CONTEXT,
5128 cx,
5129 );
5130
5131 ranges_to_highlight.extend(ranges);
5132 }
5133 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5134 multibuffer
5135 })?;
5136
5137 workspace.update_in(cx, |workspace, window, cx| {
5138 let project = workspace.project().clone();
5139 let editor =
5140 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5141 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5142 editor.update(cx, |editor, cx| {
5143 editor.highlight_background::<Self>(
5144 &ranges_to_highlight,
5145 |theme| theme.editor_highlighted_line_background,
5146 cx,
5147 );
5148 });
5149 })?;
5150
5151 Ok(())
5152 }
5153
5154 pub fn clear_code_action_providers(&mut self) {
5155 self.code_action_providers.clear();
5156 self.available_code_actions.take();
5157 }
5158
5159 pub fn add_code_action_provider(
5160 &mut self,
5161 provider: Rc<dyn CodeActionProvider>,
5162 window: &mut Window,
5163 cx: &mut Context<Self>,
5164 ) {
5165 if self
5166 .code_action_providers
5167 .iter()
5168 .any(|existing_provider| existing_provider.id() == provider.id())
5169 {
5170 return;
5171 }
5172
5173 self.code_action_providers.push(provider);
5174 self.refresh_code_actions(window, cx);
5175 }
5176
5177 pub fn remove_code_action_provider(
5178 &mut self,
5179 id: Arc<str>,
5180 window: &mut Window,
5181 cx: &mut Context<Self>,
5182 ) {
5183 self.code_action_providers
5184 .retain(|provider| provider.id() != id);
5185 self.refresh_code_actions(window, cx);
5186 }
5187
5188 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5189 let newest_selection = self.selections.newest_anchor().clone();
5190 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5191 let buffer = self.buffer.read(cx);
5192 if newest_selection.head().diff_base_anchor.is_some() {
5193 return None;
5194 }
5195 let (start_buffer, start) =
5196 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5197 let (end_buffer, end) =
5198 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5199 if start_buffer != end_buffer {
5200 return None;
5201 }
5202
5203 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5204 cx.background_executor()
5205 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5206 .await;
5207
5208 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5209 let providers = this.code_action_providers.clone();
5210 let tasks = this
5211 .code_action_providers
5212 .iter()
5213 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5214 .collect::<Vec<_>>();
5215 (providers, tasks)
5216 })?;
5217
5218 let mut actions = Vec::new();
5219 for (provider, provider_actions) in
5220 providers.into_iter().zip(future::join_all(tasks).await)
5221 {
5222 if let Some(provider_actions) = provider_actions.log_err() {
5223 actions.extend(provider_actions.into_iter().map(|action| {
5224 AvailableCodeAction {
5225 excerpt_id: newest_selection.start.excerpt_id,
5226 action,
5227 provider: provider.clone(),
5228 }
5229 }));
5230 }
5231 }
5232
5233 this.update(cx, |this, cx| {
5234 this.available_code_actions = if actions.is_empty() {
5235 None
5236 } else {
5237 Some((
5238 Location {
5239 buffer: start_buffer,
5240 range: start..end,
5241 },
5242 actions.into(),
5243 ))
5244 };
5245 cx.notify();
5246 })
5247 }));
5248 None
5249 }
5250
5251 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5252 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5253 self.show_git_blame_inline = false;
5254
5255 self.show_git_blame_inline_delay_task =
5256 Some(cx.spawn_in(window, async move |this, cx| {
5257 cx.background_executor().timer(delay).await;
5258
5259 this.update(cx, |this, cx| {
5260 this.show_git_blame_inline = true;
5261 cx.notify();
5262 })
5263 .log_err();
5264 }));
5265 }
5266 }
5267
5268 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5269 if self.pending_rename.is_some() {
5270 return None;
5271 }
5272
5273 let provider = self.semantics_provider.clone()?;
5274 let buffer = self.buffer.read(cx);
5275 let newest_selection = self.selections.newest_anchor().clone();
5276 let cursor_position = newest_selection.head();
5277 let (cursor_buffer, cursor_buffer_position) =
5278 buffer.text_anchor_for_position(cursor_position, cx)?;
5279 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5280 if cursor_buffer != tail_buffer {
5281 return None;
5282 }
5283 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5284 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5285 cx.background_executor()
5286 .timer(Duration::from_millis(debounce))
5287 .await;
5288
5289 let highlights = if let Some(highlights) = cx
5290 .update(|cx| {
5291 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5292 })
5293 .ok()
5294 .flatten()
5295 {
5296 highlights.await.log_err()
5297 } else {
5298 None
5299 };
5300
5301 if let Some(highlights) = highlights {
5302 this.update(cx, |this, cx| {
5303 if this.pending_rename.is_some() {
5304 return;
5305 }
5306
5307 let buffer_id = cursor_position.buffer_id;
5308 let buffer = this.buffer.read(cx);
5309 if !buffer
5310 .text_anchor_for_position(cursor_position, cx)
5311 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5312 {
5313 return;
5314 }
5315
5316 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5317 let mut write_ranges = Vec::new();
5318 let mut read_ranges = Vec::new();
5319 for highlight in highlights {
5320 for (excerpt_id, excerpt_range) in
5321 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5322 {
5323 let start = highlight
5324 .range
5325 .start
5326 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5327 let end = highlight
5328 .range
5329 .end
5330 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5331 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5332 continue;
5333 }
5334
5335 let range = Anchor {
5336 buffer_id,
5337 excerpt_id,
5338 text_anchor: start,
5339 diff_base_anchor: None,
5340 }..Anchor {
5341 buffer_id,
5342 excerpt_id,
5343 text_anchor: end,
5344 diff_base_anchor: None,
5345 };
5346 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5347 write_ranges.push(range);
5348 } else {
5349 read_ranges.push(range);
5350 }
5351 }
5352 }
5353
5354 this.highlight_background::<DocumentHighlightRead>(
5355 &read_ranges,
5356 |theme| theme.editor_document_highlight_read_background,
5357 cx,
5358 );
5359 this.highlight_background::<DocumentHighlightWrite>(
5360 &write_ranges,
5361 |theme| theme.editor_document_highlight_write_background,
5362 cx,
5363 );
5364 cx.notify();
5365 })
5366 .log_err();
5367 }
5368 }));
5369 None
5370 }
5371
5372 pub fn refresh_selected_text_highlights(
5373 &mut self,
5374 window: &mut Window,
5375 cx: &mut Context<Editor>,
5376 ) {
5377 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5378 return;
5379 }
5380 self.selection_highlight_task.take();
5381 if !EditorSettings::get_global(cx).selection_highlight {
5382 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5383 return;
5384 }
5385 if self.selections.count() != 1 || self.selections.line_mode {
5386 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5387 return;
5388 }
5389 let selection = self.selections.newest::<Point>(cx);
5390 if selection.is_empty() || selection.start.row != selection.end.row {
5391 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5392 return;
5393 }
5394 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5395 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5396 cx.background_executor()
5397 .timer(Duration::from_millis(debounce))
5398 .await;
5399 let Some(Some(matches_task)) = editor
5400 .update_in(cx, |editor, _, cx| {
5401 if editor.selections.count() != 1 || editor.selections.line_mode {
5402 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5403 return None;
5404 }
5405 let selection = editor.selections.newest::<Point>(cx);
5406 if selection.is_empty() || selection.start.row != selection.end.row {
5407 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5408 return None;
5409 }
5410 let buffer = editor.buffer().read(cx).snapshot(cx);
5411 let query = buffer.text_for_range(selection.range()).collect::<String>();
5412 if query.trim().is_empty() {
5413 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5414 return None;
5415 }
5416 Some(cx.background_spawn(async move {
5417 let mut ranges = Vec::new();
5418 let selection_anchors = selection.range().to_anchors(&buffer);
5419 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5420 for (search_buffer, search_range, excerpt_id) in
5421 buffer.range_to_buffer_ranges(range)
5422 {
5423 ranges.extend(
5424 project::search::SearchQuery::text(
5425 query.clone(),
5426 false,
5427 false,
5428 false,
5429 Default::default(),
5430 Default::default(),
5431 None,
5432 )
5433 .unwrap()
5434 .search(search_buffer, Some(search_range.clone()))
5435 .await
5436 .into_iter()
5437 .filter_map(
5438 |match_range| {
5439 let start = search_buffer.anchor_after(
5440 search_range.start + match_range.start,
5441 );
5442 let end = search_buffer.anchor_before(
5443 search_range.start + match_range.end,
5444 );
5445 let range = Anchor::range_in_buffer(
5446 excerpt_id,
5447 search_buffer.remote_id(),
5448 start..end,
5449 );
5450 (range != selection_anchors).then_some(range)
5451 },
5452 ),
5453 );
5454 }
5455 }
5456 ranges
5457 }))
5458 })
5459 .log_err()
5460 else {
5461 return;
5462 };
5463 let matches = matches_task.await;
5464 editor
5465 .update_in(cx, |editor, _, cx| {
5466 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5467 if !matches.is_empty() {
5468 editor.highlight_background::<SelectedTextHighlight>(
5469 &matches,
5470 |theme| theme.editor_document_highlight_bracket_background,
5471 cx,
5472 )
5473 }
5474 })
5475 .log_err();
5476 }));
5477 }
5478
5479 pub fn refresh_inline_completion(
5480 &mut self,
5481 debounce: bool,
5482 user_requested: bool,
5483 window: &mut Window,
5484 cx: &mut Context<Self>,
5485 ) -> Option<()> {
5486 let provider = self.edit_prediction_provider()?;
5487 let cursor = self.selections.newest_anchor().head();
5488 let (buffer, cursor_buffer_position) =
5489 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5490
5491 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5492 self.discard_inline_completion(false, cx);
5493 return None;
5494 }
5495
5496 if !user_requested
5497 && (!self.should_show_edit_predictions()
5498 || !self.is_focused(window)
5499 || buffer.read(cx).is_empty())
5500 {
5501 self.discard_inline_completion(false, cx);
5502 return None;
5503 }
5504
5505 self.update_visible_inline_completion(window, cx);
5506 provider.refresh(
5507 self.project.clone(),
5508 buffer,
5509 cursor_buffer_position,
5510 debounce,
5511 cx,
5512 );
5513 Some(())
5514 }
5515
5516 fn show_edit_predictions_in_menu(&self) -> bool {
5517 match self.edit_prediction_settings {
5518 EditPredictionSettings::Disabled => false,
5519 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5520 }
5521 }
5522
5523 pub fn edit_predictions_enabled(&self) -> bool {
5524 match self.edit_prediction_settings {
5525 EditPredictionSettings::Disabled => false,
5526 EditPredictionSettings::Enabled { .. } => true,
5527 }
5528 }
5529
5530 fn edit_prediction_requires_modifier(&self) -> bool {
5531 match self.edit_prediction_settings {
5532 EditPredictionSettings::Disabled => false,
5533 EditPredictionSettings::Enabled {
5534 preview_requires_modifier,
5535 ..
5536 } => preview_requires_modifier,
5537 }
5538 }
5539
5540 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5541 if self.edit_prediction_provider.is_none() {
5542 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5543 } else {
5544 let selection = self.selections.newest_anchor();
5545 let cursor = selection.head();
5546
5547 if let Some((buffer, cursor_buffer_position)) =
5548 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5549 {
5550 self.edit_prediction_settings =
5551 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5552 }
5553 }
5554 }
5555
5556 fn edit_prediction_settings_at_position(
5557 &self,
5558 buffer: &Entity<Buffer>,
5559 buffer_position: language::Anchor,
5560 cx: &App,
5561 ) -> EditPredictionSettings {
5562 if !self.mode.is_full()
5563 || !self.show_inline_completions_override.unwrap_or(true)
5564 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5565 {
5566 return EditPredictionSettings::Disabled;
5567 }
5568
5569 let buffer = buffer.read(cx);
5570
5571 let file = buffer.file();
5572
5573 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5574 return EditPredictionSettings::Disabled;
5575 };
5576
5577 let by_provider = matches!(
5578 self.menu_inline_completions_policy,
5579 MenuInlineCompletionsPolicy::ByProvider
5580 );
5581
5582 let show_in_menu = by_provider
5583 && self
5584 .edit_prediction_provider
5585 .as_ref()
5586 .map_or(false, |provider| {
5587 provider.provider.show_completions_in_menu()
5588 });
5589
5590 let preview_requires_modifier =
5591 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5592
5593 EditPredictionSettings::Enabled {
5594 show_in_menu,
5595 preview_requires_modifier,
5596 }
5597 }
5598
5599 fn should_show_edit_predictions(&self) -> bool {
5600 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5601 }
5602
5603 pub fn edit_prediction_preview_is_active(&self) -> bool {
5604 matches!(
5605 self.edit_prediction_preview,
5606 EditPredictionPreview::Active { .. }
5607 )
5608 }
5609
5610 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5611 let cursor = self.selections.newest_anchor().head();
5612 if let Some((buffer, cursor_position)) =
5613 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5614 {
5615 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5616 } else {
5617 false
5618 }
5619 }
5620
5621 fn edit_predictions_enabled_in_buffer(
5622 &self,
5623 buffer: &Entity<Buffer>,
5624 buffer_position: language::Anchor,
5625 cx: &App,
5626 ) -> bool {
5627 maybe!({
5628 if self.read_only(cx) {
5629 return Some(false);
5630 }
5631 let provider = self.edit_prediction_provider()?;
5632 if !provider.is_enabled(&buffer, buffer_position, cx) {
5633 return Some(false);
5634 }
5635 let buffer = buffer.read(cx);
5636 let Some(file) = buffer.file() else {
5637 return Some(true);
5638 };
5639 let settings = all_language_settings(Some(file), cx);
5640 Some(settings.edit_predictions_enabled_for_file(file, cx))
5641 })
5642 .unwrap_or(false)
5643 }
5644
5645 fn cycle_inline_completion(
5646 &mut self,
5647 direction: Direction,
5648 window: &mut Window,
5649 cx: &mut Context<Self>,
5650 ) -> Option<()> {
5651 let provider = self.edit_prediction_provider()?;
5652 let cursor = self.selections.newest_anchor().head();
5653 let (buffer, cursor_buffer_position) =
5654 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5655 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5656 return None;
5657 }
5658
5659 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5660 self.update_visible_inline_completion(window, cx);
5661
5662 Some(())
5663 }
5664
5665 pub fn show_inline_completion(
5666 &mut self,
5667 _: &ShowEditPrediction,
5668 window: &mut Window,
5669 cx: &mut Context<Self>,
5670 ) {
5671 if !self.has_active_inline_completion() {
5672 self.refresh_inline_completion(false, true, window, cx);
5673 return;
5674 }
5675
5676 self.update_visible_inline_completion(window, cx);
5677 }
5678
5679 pub fn display_cursor_names(
5680 &mut self,
5681 _: &DisplayCursorNames,
5682 window: &mut Window,
5683 cx: &mut Context<Self>,
5684 ) {
5685 self.show_cursor_names(window, cx);
5686 }
5687
5688 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5689 self.show_cursor_names = true;
5690 cx.notify();
5691 cx.spawn_in(window, async move |this, cx| {
5692 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5693 this.update(cx, |this, cx| {
5694 this.show_cursor_names = false;
5695 cx.notify()
5696 })
5697 .ok()
5698 })
5699 .detach();
5700 }
5701
5702 pub fn next_edit_prediction(
5703 &mut self,
5704 _: &NextEditPrediction,
5705 window: &mut Window,
5706 cx: &mut Context<Self>,
5707 ) {
5708 if self.has_active_inline_completion() {
5709 self.cycle_inline_completion(Direction::Next, window, cx);
5710 } else {
5711 let is_copilot_disabled = self
5712 .refresh_inline_completion(false, true, window, cx)
5713 .is_none();
5714 if is_copilot_disabled {
5715 cx.propagate();
5716 }
5717 }
5718 }
5719
5720 pub fn previous_edit_prediction(
5721 &mut self,
5722 _: &PreviousEditPrediction,
5723 window: &mut Window,
5724 cx: &mut Context<Self>,
5725 ) {
5726 if self.has_active_inline_completion() {
5727 self.cycle_inline_completion(Direction::Prev, window, cx);
5728 } else {
5729 let is_copilot_disabled = self
5730 .refresh_inline_completion(false, true, window, cx)
5731 .is_none();
5732 if is_copilot_disabled {
5733 cx.propagate();
5734 }
5735 }
5736 }
5737
5738 pub fn accept_edit_prediction(
5739 &mut self,
5740 _: &AcceptEditPrediction,
5741 window: &mut Window,
5742 cx: &mut Context<Self>,
5743 ) {
5744 if self.show_edit_predictions_in_menu() {
5745 self.hide_context_menu(window, cx);
5746 }
5747
5748 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5749 return;
5750 };
5751
5752 self.report_inline_completion_event(
5753 active_inline_completion.completion_id.clone(),
5754 true,
5755 cx,
5756 );
5757
5758 match &active_inline_completion.completion {
5759 InlineCompletion::Move { target, .. } => {
5760 let target = *target;
5761
5762 if let Some(position_map) = &self.last_position_map {
5763 if position_map
5764 .visible_row_range
5765 .contains(&target.to_display_point(&position_map.snapshot).row())
5766 || !self.edit_prediction_requires_modifier()
5767 {
5768 self.unfold_ranges(&[target..target], true, false, cx);
5769 // Note that this is also done in vim's handler of the Tab action.
5770 self.change_selections(
5771 Some(Autoscroll::newest()),
5772 window,
5773 cx,
5774 |selections| {
5775 selections.select_anchor_ranges([target..target]);
5776 },
5777 );
5778 self.clear_row_highlights::<EditPredictionPreview>();
5779
5780 self.edit_prediction_preview
5781 .set_previous_scroll_position(None);
5782 } else {
5783 self.edit_prediction_preview
5784 .set_previous_scroll_position(Some(
5785 position_map.snapshot.scroll_anchor,
5786 ));
5787
5788 self.highlight_rows::<EditPredictionPreview>(
5789 target..target,
5790 cx.theme().colors().editor_highlighted_line_background,
5791 true,
5792 cx,
5793 );
5794 self.request_autoscroll(Autoscroll::fit(), cx);
5795 }
5796 }
5797 }
5798 InlineCompletion::Edit { edits, .. } => {
5799 if let Some(provider) = self.edit_prediction_provider() {
5800 provider.accept(cx);
5801 }
5802
5803 let snapshot = self.buffer.read(cx).snapshot(cx);
5804 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5805
5806 self.buffer.update(cx, |buffer, cx| {
5807 buffer.edit(edits.iter().cloned(), None, cx)
5808 });
5809
5810 self.change_selections(None, window, cx, |s| {
5811 s.select_anchor_ranges([last_edit_end..last_edit_end])
5812 });
5813
5814 self.update_visible_inline_completion(window, cx);
5815 if self.active_inline_completion.is_none() {
5816 self.refresh_inline_completion(true, true, window, cx);
5817 }
5818
5819 cx.notify();
5820 }
5821 }
5822
5823 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5824 }
5825
5826 pub fn accept_partial_inline_completion(
5827 &mut self,
5828 _: &AcceptPartialEditPrediction,
5829 window: &mut Window,
5830 cx: &mut Context<Self>,
5831 ) {
5832 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5833 return;
5834 };
5835 if self.selections.count() != 1 {
5836 return;
5837 }
5838
5839 self.report_inline_completion_event(
5840 active_inline_completion.completion_id.clone(),
5841 true,
5842 cx,
5843 );
5844
5845 match &active_inline_completion.completion {
5846 InlineCompletion::Move { target, .. } => {
5847 let target = *target;
5848 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5849 selections.select_anchor_ranges([target..target]);
5850 });
5851 }
5852 InlineCompletion::Edit { edits, .. } => {
5853 // Find an insertion that starts at the cursor position.
5854 let snapshot = self.buffer.read(cx).snapshot(cx);
5855 let cursor_offset = self.selections.newest::<usize>(cx).head();
5856 let insertion = edits.iter().find_map(|(range, text)| {
5857 let range = range.to_offset(&snapshot);
5858 if range.is_empty() && range.start == cursor_offset {
5859 Some(text)
5860 } else {
5861 None
5862 }
5863 });
5864
5865 if let Some(text) = insertion {
5866 let mut partial_completion = text
5867 .chars()
5868 .by_ref()
5869 .take_while(|c| c.is_alphabetic())
5870 .collect::<String>();
5871 if partial_completion.is_empty() {
5872 partial_completion = text
5873 .chars()
5874 .by_ref()
5875 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5876 .collect::<String>();
5877 }
5878
5879 cx.emit(EditorEvent::InputHandled {
5880 utf16_range_to_replace: None,
5881 text: partial_completion.clone().into(),
5882 });
5883
5884 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5885
5886 self.refresh_inline_completion(true, true, window, cx);
5887 cx.notify();
5888 } else {
5889 self.accept_edit_prediction(&Default::default(), window, cx);
5890 }
5891 }
5892 }
5893 }
5894
5895 fn discard_inline_completion(
5896 &mut self,
5897 should_report_inline_completion_event: bool,
5898 cx: &mut Context<Self>,
5899 ) -> bool {
5900 if should_report_inline_completion_event {
5901 let completion_id = self
5902 .active_inline_completion
5903 .as_ref()
5904 .and_then(|active_completion| active_completion.completion_id.clone());
5905
5906 self.report_inline_completion_event(completion_id, false, cx);
5907 }
5908
5909 if let Some(provider) = self.edit_prediction_provider() {
5910 provider.discard(cx);
5911 }
5912
5913 self.take_active_inline_completion(cx)
5914 }
5915
5916 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5917 let Some(provider) = self.edit_prediction_provider() else {
5918 return;
5919 };
5920
5921 let Some((_, buffer, _)) = self
5922 .buffer
5923 .read(cx)
5924 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5925 else {
5926 return;
5927 };
5928
5929 let extension = buffer
5930 .read(cx)
5931 .file()
5932 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5933
5934 let event_type = match accepted {
5935 true => "Edit Prediction Accepted",
5936 false => "Edit Prediction Discarded",
5937 };
5938 telemetry::event!(
5939 event_type,
5940 provider = provider.name(),
5941 prediction_id = id,
5942 suggestion_accepted = accepted,
5943 file_extension = extension,
5944 );
5945 }
5946
5947 pub fn has_active_inline_completion(&self) -> bool {
5948 self.active_inline_completion.is_some()
5949 }
5950
5951 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5952 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5953 return false;
5954 };
5955
5956 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5957 self.clear_highlights::<InlineCompletionHighlight>(cx);
5958 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5959 true
5960 }
5961
5962 /// Returns true when we're displaying the edit prediction popover below the cursor
5963 /// like we are not previewing and the LSP autocomplete menu is visible
5964 /// or we are in `when_holding_modifier` mode.
5965 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5966 if self.edit_prediction_preview_is_active()
5967 || !self.show_edit_predictions_in_menu()
5968 || !self.edit_predictions_enabled()
5969 {
5970 return false;
5971 }
5972
5973 if self.has_visible_completions_menu() {
5974 return true;
5975 }
5976
5977 has_completion && self.edit_prediction_requires_modifier()
5978 }
5979
5980 fn handle_modifiers_changed(
5981 &mut self,
5982 modifiers: Modifiers,
5983 position_map: &PositionMap,
5984 window: &mut Window,
5985 cx: &mut Context<Self>,
5986 ) {
5987 if self.show_edit_predictions_in_menu() {
5988 self.update_edit_prediction_preview(&modifiers, window, cx);
5989 }
5990
5991 self.update_selection_mode(&modifiers, position_map, window, cx);
5992
5993 let mouse_position = window.mouse_position();
5994 if !position_map.text_hitbox.is_hovered(window) {
5995 return;
5996 }
5997
5998 self.update_hovered_link(
5999 position_map.point_for_position(mouse_position),
6000 &position_map.snapshot,
6001 modifiers,
6002 window,
6003 cx,
6004 )
6005 }
6006
6007 fn update_selection_mode(
6008 &mut self,
6009 modifiers: &Modifiers,
6010 position_map: &PositionMap,
6011 window: &mut Window,
6012 cx: &mut Context<Self>,
6013 ) {
6014 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6015 return;
6016 }
6017
6018 let mouse_position = window.mouse_position();
6019 let point_for_position = position_map.point_for_position(mouse_position);
6020 let position = point_for_position.previous_valid;
6021
6022 self.select(
6023 SelectPhase::BeginColumnar {
6024 position,
6025 reset: false,
6026 goal_column: point_for_position.exact_unclipped.column(),
6027 },
6028 window,
6029 cx,
6030 );
6031 }
6032
6033 fn update_edit_prediction_preview(
6034 &mut self,
6035 modifiers: &Modifiers,
6036 window: &mut Window,
6037 cx: &mut Context<Self>,
6038 ) {
6039 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6040 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6041 return;
6042 };
6043
6044 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6045 if matches!(
6046 self.edit_prediction_preview,
6047 EditPredictionPreview::Inactive { .. }
6048 ) {
6049 self.edit_prediction_preview = EditPredictionPreview::Active {
6050 previous_scroll_position: None,
6051 since: Instant::now(),
6052 };
6053
6054 self.update_visible_inline_completion(window, cx);
6055 cx.notify();
6056 }
6057 } else if let EditPredictionPreview::Active {
6058 previous_scroll_position,
6059 since,
6060 } = self.edit_prediction_preview
6061 {
6062 if let (Some(previous_scroll_position), Some(position_map)) =
6063 (previous_scroll_position, self.last_position_map.as_ref())
6064 {
6065 self.set_scroll_position(
6066 previous_scroll_position
6067 .scroll_position(&position_map.snapshot.display_snapshot),
6068 window,
6069 cx,
6070 );
6071 }
6072
6073 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6074 released_too_fast: since.elapsed() < Duration::from_millis(200),
6075 };
6076 self.clear_row_highlights::<EditPredictionPreview>();
6077 self.update_visible_inline_completion(window, cx);
6078 cx.notify();
6079 }
6080 }
6081
6082 fn update_visible_inline_completion(
6083 &mut self,
6084 _window: &mut Window,
6085 cx: &mut Context<Self>,
6086 ) -> Option<()> {
6087 let selection = self.selections.newest_anchor();
6088 let cursor = selection.head();
6089 let multibuffer = self.buffer.read(cx).snapshot(cx);
6090 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6091 let excerpt_id = cursor.excerpt_id;
6092
6093 let show_in_menu = self.show_edit_predictions_in_menu();
6094 let completions_menu_has_precedence = !show_in_menu
6095 && (self.context_menu.borrow().is_some()
6096 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6097
6098 if completions_menu_has_precedence
6099 || !offset_selection.is_empty()
6100 || self
6101 .active_inline_completion
6102 .as_ref()
6103 .map_or(false, |completion| {
6104 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6105 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6106 !invalidation_range.contains(&offset_selection.head())
6107 })
6108 {
6109 self.discard_inline_completion(false, cx);
6110 return None;
6111 }
6112
6113 self.take_active_inline_completion(cx);
6114 let Some(provider) = self.edit_prediction_provider() else {
6115 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6116 return None;
6117 };
6118
6119 let (buffer, cursor_buffer_position) =
6120 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6121
6122 self.edit_prediction_settings =
6123 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6124
6125 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6126
6127 if self.edit_prediction_indent_conflict {
6128 let cursor_point = cursor.to_point(&multibuffer);
6129
6130 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6131
6132 if let Some((_, indent)) = indents.iter().next() {
6133 if indent.len == cursor_point.column {
6134 self.edit_prediction_indent_conflict = false;
6135 }
6136 }
6137 }
6138
6139 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6140 let edits = inline_completion
6141 .edits
6142 .into_iter()
6143 .flat_map(|(range, new_text)| {
6144 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6145 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6146 Some((start..end, new_text))
6147 })
6148 .collect::<Vec<_>>();
6149 if edits.is_empty() {
6150 return None;
6151 }
6152
6153 let first_edit_start = edits.first().unwrap().0.start;
6154 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6155 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6156
6157 let last_edit_end = edits.last().unwrap().0.end;
6158 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6159 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6160
6161 let cursor_row = cursor.to_point(&multibuffer).row;
6162
6163 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6164
6165 let mut inlay_ids = Vec::new();
6166 let invalidation_row_range;
6167 let move_invalidation_row_range = if cursor_row < edit_start_row {
6168 Some(cursor_row..edit_end_row)
6169 } else if cursor_row > edit_end_row {
6170 Some(edit_start_row..cursor_row)
6171 } else {
6172 None
6173 };
6174 let is_move =
6175 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6176 let completion = if is_move {
6177 invalidation_row_range =
6178 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6179 let target = first_edit_start;
6180 InlineCompletion::Move { target, snapshot }
6181 } else {
6182 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6183 && !self.inline_completions_hidden_for_vim_mode;
6184
6185 if show_completions_in_buffer {
6186 if edits
6187 .iter()
6188 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6189 {
6190 let mut inlays = Vec::new();
6191 for (range, new_text) in &edits {
6192 let inlay = Inlay::inline_completion(
6193 post_inc(&mut self.next_inlay_id),
6194 range.start,
6195 new_text.as_str(),
6196 );
6197 inlay_ids.push(inlay.id);
6198 inlays.push(inlay);
6199 }
6200
6201 self.splice_inlays(&[], inlays, cx);
6202 } else {
6203 let background_color = cx.theme().status().deleted_background;
6204 self.highlight_text::<InlineCompletionHighlight>(
6205 edits.iter().map(|(range, _)| range.clone()).collect(),
6206 HighlightStyle {
6207 background_color: Some(background_color),
6208 ..Default::default()
6209 },
6210 cx,
6211 );
6212 }
6213 }
6214
6215 invalidation_row_range = edit_start_row..edit_end_row;
6216
6217 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6218 if provider.show_tab_accept_marker() {
6219 EditDisplayMode::TabAccept
6220 } else {
6221 EditDisplayMode::Inline
6222 }
6223 } else {
6224 EditDisplayMode::DiffPopover
6225 };
6226
6227 InlineCompletion::Edit {
6228 edits,
6229 edit_preview: inline_completion.edit_preview,
6230 display_mode,
6231 snapshot,
6232 }
6233 };
6234
6235 let invalidation_range = multibuffer
6236 .anchor_before(Point::new(invalidation_row_range.start, 0))
6237 ..multibuffer.anchor_after(Point::new(
6238 invalidation_row_range.end,
6239 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6240 ));
6241
6242 self.stale_inline_completion_in_menu = None;
6243 self.active_inline_completion = Some(InlineCompletionState {
6244 inlay_ids,
6245 completion,
6246 completion_id: inline_completion.id,
6247 invalidation_range,
6248 });
6249
6250 cx.notify();
6251
6252 Some(())
6253 }
6254
6255 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6256 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6257 }
6258
6259 fn render_code_actions_indicator(
6260 &self,
6261 _style: &EditorStyle,
6262 row: DisplayRow,
6263 is_active: bool,
6264 breakpoint: Option<&(Anchor, Breakpoint)>,
6265 cx: &mut Context<Self>,
6266 ) -> Option<IconButton> {
6267 let color = Color::Muted;
6268 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6269 let show_tooltip = !self.context_menu_visible();
6270
6271 if self.available_code_actions.is_some() {
6272 Some(
6273 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6274 .shape(ui::IconButtonShape::Square)
6275 .icon_size(IconSize::XSmall)
6276 .icon_color(color)
6277 .toggle_state(is_active)
6278 .when(show_tooltip, |this| {
6279 this.tooltip({
6280 let focus_handle = self.focus_handle.clone();
6281 move |window, cx| {
6282 Tooltip::for_action_in(
6283 "Toggle Code Actions",
6284 &ToggleCodeActions {
6285 deployed_from_indicator: None,
6286 },
6287 &focus_handle,
6288 window,
6289 cx,
6290 )
6291 }
6292 })
6293 })
6294 .on_click(cx.listener(move |editor, _e, window, cx| {
6295 window.focus(&editor.focus_handle(cx));
6296 editor.toggle_code_actions(
6297 &ToggleCodeActions {
6298 deployed_from_indicator: Some(row),
6299 },
6300 window,
6301 cx,
6302 );
6303 }))
6304 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6305 editor.set_breakpoint_context_menu(
6306 row,
6307 position,
6308 event.down.position,
6309 window,
6310 cx,
6311 );
6312 })),
6313 )
6314 } else {
6315 None
6316 }
6317 }
6318
6319 fn clear_tasks(&mut self) {
6320 self.tasks.clear()
6321 }
6322
6323 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6324 if self.tasks.insert(key, value).is_some() {
6325 // This case should hopefully be rare, but just in case...
6326 log::error!(
6327 "multiple different run targets found on a single line, only the last target will be rendered"
6328 )
6329 }
6330 }
6331
6332 /// Get all display points of breakpoints that will be rendered within editor
6333 ///
6334 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6335 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6336 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6337 fn active_breakpoints(
6338 &self,
6339 range: Range<DisplayRow>,
6340 window: &mut Window,
6341 cx: &mut Context<Self>,
6342 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6343 let mut breakpoint_display_points = HashMap::default();
6344
6345 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6346 return breakpoint_display_points;
6347 };
6348
6349 let snapshot = self.snapshot(window, cx);
6350
6351 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6352 let Some(project) = self.project.as_ref() else {
6353 return breakpoint_display_points;
6354 };
6355
6356 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6357 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6358
6359 for (buffer_snapshot, range, excerpt_id) in
6360 multi_buffer_snapshot.range_to_buffer_ranges(range)
6361 {
6362 let Some(buffer) = project.read_with(cx, |this, cx| {
6363 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6364 }) else {
6365 continue;
6366 };
6367 let breakpoints = breakpoint_store.read(cx).breakpoints(
6368 &buffer,
6369 Some(
6370 buffer_snapshot.anchor_before(range.start)
6371 ..buffer_snapshot.anchor_after(range.end),
6372 ),
6373 buffer_snapshot,
6374 cx,
6375 );
6376 for (anchor, breakpoint) in breakpoints {
6377 let multi_buffer_anchor =
6378 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6379 let position = multi_buffer_anchor
6380 .to_point(&multi_buffer_snapshot)
6381 .to_display_point(&snapshot);
6382
6383 breakpoint_display_points
6384 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6385 }
6386 }
6387
6388 breakpoint_display_points
6389 }
6390
6391 fn breakpoint_context_menu(
6392 &self,
6393 anchor: Anchor,
6394 window: &mut Window,
6395 cx: &mut Context<Self>,
6396 ) -> Entity<ui::ContextMenu> {
6397 let weak_editor = cx.weak_entity();
6398 let focus_handle = self.focus_handle(cx);
6399
6400 let row = self
6401 .buffer
6402 .read(cx)
6403 .snapshot(cx)
6404 .summary_for_anchor::<Point>(&anchor)
6405 .row;
6406
6407 let breakpoint = self
6408 .breakpoint_at_row(row, window, cx)
6409 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6410
6411 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6412 "Edit Log Breakpoint"
6413 } else {
6414 "Set Log Breakpoint"
6415 };
6416
6417 let condition_breakpoint_msg = if breakpoint
6418 .as_ref()
6419 .is_some_and(|bp| bp.1.condition.is_some())
6420 {
6421 "Edit Condition Breakpoint"
6422 } else {
6423 "Set Condition Breakpoint"
6424 };
6425
6426 let hit_condition_breakpoint_msg = if breakpoint
6427 .as_ref()
6428 .is_some_and(|bp| bp.1.hit_condition.is_some())
6429 {
6430 "Edit Hit Condition Breakpoint"
6431 } else {
6432 "Set Hit Condition Breakpoint"
6433 };
6434
6435 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6436 "Unset Breakpoint"
6437 } else {
6438 "Set Breakpoint"
6439 };
6440
6441 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6442 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6443
6444 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6445 BreakpointState::Enabled => Some("Disable"),
6446 BreakpointState::Disabled => Some("Enable"),
6447 });
6448
6449 let (anchor, breakpoint) =
6450 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6451
6452 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6453 menu.on_blur_subscription(Subscription::new(|| {}))
6454 .context(focus_handle)
6455 .when(run_to_cursor, |this| {
6456 let weak_editor = weak_editor.clone();
6457 this.entry("Run to cursor", None, move |window, cx| {
6458 weak_editor
6459 .update(cx, |editor, cx| {
6460 editor.change_selections(None, window, cx, |s| {
6461 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6462 });
6463 })
6464 .ok();
6465
6466 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6467 })
6468 .separator()
6469 })
6470 .when_some(toggle_state_msg, |this, msg| {
6471 this.entry(msg, None, {
6472 let weak_editor = weak_editor.clone();
6473 let breakpoint = breakpoint.clone();
6474 move |_window, cx| {
6475 weak_editor
6476 .update(cx, |this, cx| {
6477 this.edit_breakpoint_at_anchor(
6478 anchor,
6479 breakpoint.as_ref().clone(),
6480 BreakpointEditAction::InvertState,
6481 cx,
6482 );
6483 })
6484 .log_err();
6485 }
6486 })
6487 })
6488 .entry(set_breakpoint_msg, None, {
6489 let weak_editor = weak_editor.clone();
6490 let breakpoint = breakpoint.clone();
6491 move |_window, cx| {
6492 weak_editor
6493 .update(cx, |this, cx| {
6494 this.edit_breakpoint_at_anchor(
6495 anchor,
6496 breakpoint.as_ref().clone(),
6497 BreakpointEditAction::Toggle,
6498 cx,
6499 );
6500 })
6501 .log_err();
6502 }
6503 })
6504 .entry(log_breakpoint_msg, None, {
6505 let breakpoint = breakpoint.clone();
6506 let weak_editor = weak_editor.clone();
6507 move |window, cx| {
6508 weak_editor
6509 .update(cx, |this, cx| {
6510 this.add_edit_breakpoint_block(
6511 anchor,
6512 breakpoint.as_ref(),
6513 BreakpointPromptEditAction::Log,
6514 window,
6515 cx,
6516 );
6517 })
6518 .log_err();
6519 }
6520 })
6521 .entry(condition_breakpoint_msg, None, {
6522 let breakpoint = breakpoint.clone();
6523 let weak_editor = weak_editor.clone();
6524 move |window, cx| {
6525 weak_editor
6526 .update(cx, |this, cx| {
6527 this.add_edit_breakpoint_block(
6528 anchor,
6529 breakpoint.as_ref(),
6530 BreakpointPromptEditAction::Condition,
6531 window,
6532 cx,
6533 );
6534 })
6535 .log_err();
6536 }
6537 })
6538 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6539 weak_editor
6540 .update(cx, |this, cx| {
6541 this.add_edit_breakpoint_block(
6542 anchor,
6543 breakpoint.as_ref(),
6544 BreakpointPromptEditAction::HitCondition,
6545 window,
6546 cx,
6547 );
6548 })
6549 .log_err();
6550 })
6551 })
6552 }
6553
6554 fn render_breakpoint(
6555 &self,
6556 position: Anchor,
6557 row: DisplayRow,
6558 breakpoint: &Breakpoint,
6559 cx: &mut Context<Self>,
6560 ) -> IconButton {
6561 let (color, icon) = {
6562 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6563 (false, false) => ui::IconName::DebugBreakpoint,
6564 (true, false) => ui::IconName::DebugLogBreakpoint,
6565 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6566 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6567 };
6568
6569 let color = if self
6570 .gutter_breakpoint_indicator
6571 .0
6572 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6573 {
6574 Color::Hint
6575 } else {
6576 Color::Debugger
6577 };
6578
6579 (color, icon)
6580 };
6581
6582 let breakpoint = Arc::from(breakpoint.clone());
6583
6584 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6585 .icon_size(IconSize::XSmall)
6586 .size(ui::ButtonSize::None)
6587 .icon_color(color)
6588 .style(ButtonStyle::Transparent)
6589 .on_click(cx.listener({
6590 let breakpoint = breakpoint.clone();
6591
6592 move |editor, event: &ClickEvent, window, cx| {
6593 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6594 BreakpointEditAction::InvertState
6595 } else {
6596 BreakpointEditAction::Toggle
6597 };
6598
6599 window.focus(&editor.focus_handle(cx));
6600 editor.edit_breakpoint_at_anchor(
6601 position,
6602 breakpoint.as_ref().clone(),
6603 edit_action,
6604 cx,
6605 );
6606 }
6607 }))
6608 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6609 editor.set_breakpoint_context_menu(
6610 row,
6611 Some(position),
6612 event.down.position,
6613 window,
6614 cx,
6615 );
6616 }))
6617 }
6618
6619 fn build_tasks_context(
6620 project: &Entity<Project>,
6621 buffer: &Entity<Buffer>,
6622 buffer_row: u32,
6623 tasks: &Arc<RunnableTasks>,
6624 cx: &mut Context<Self>,
6625 ) -> Task<Option<task::TaskContext>> {
6626 let position = Point::new(buffer_row, tasks.column);
6627 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6628 let location = Location {
6629 buffer: buffer.clone(),
6630 range: range_start..range_start,
6631 };
6632 // Fill in the environmental variables from the tree-sitter captures
6633 let mut captured_task_variables = TaskVariables::default();
6634 for (capture_name, value) in tasks.extra_variables.clone() {
6635 captured_task_variables.insert(
6636 task::VariableName::Custom(capture_name.into()),
6637 value.clone(),
6638 );
6639 }
6640 project.update(cx, |project, cx| {
6641 project.task_store().update(cx, |task_store, cx| {
6642 task_store.task_context_for_location(captured_task_variables, location, cx)
6643 })
6644 })
6645 }
6646
6647 pub fn spawn_nearest_task(
6648 &mut self,
6649 action: &SpawnNearestTask,
6650 window: &mut Window,
6651 cx: &mut Context<Self>,
6652 ) {
6653 let Some((workspace, _)) = self.workspace.clone() else {
6654 return;
6655 };
6656 let Some(project) = self.project.clone() else {
6657 return;
6658 };
6659
6660 // Try to find a closest, enclosing node using tree-sitter that has a
6661 // task
6662 let Some((buffer, buffer_row, tasks)) = self
6663 .find_enclosing_node_task(cx)
6664 // Or find the task that's closest in row-distance.
6665 .or_else(|| self.find_closest_task(cx))
6666 else {
6667 return;
6668 };
6669
6670 let reveal_strategy = action.reveal;
6671 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6672 cx.spawn_in(window, async move |_, cx| {
6673 let context = task_context.await?;
6674 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6675
6676 let resolved = resolved_task.resolved.as_mut()?;
6677 resolved.reveal = reveal_strategy;
6678
6679 workspace
6680 .update(cx, |workspace, cx| {
6681 workspace::tasks::schedule_resolved_task(
6682 workspace,
6683 task_source_kind,
6684 resolved_task,
6685 false,
6686 cx,
6687 );
6688 })
6689 .ok()
6690 })
6691 .detach();
6692 }
6693
6694 fn find_closest_task(
6695 &mut self,
6696 cx: &mut Context<Self>,
6697 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6698 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6699
6700 let ((buffer_id, row), tasks) = self
6701 .tasks
6702 .iter()
6703 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6704
6705 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6706 let tasks = Arc::new(tasks.to_owned());
6707 Some((buffer, *row, tasks))
6708 }
6709
6710 fn find_enclosing_node_task(
6711 &mut self,
6712 cx: &mut Context<Self>,
6713 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6714 let snapshot = self.buffer.read(cx).snapshot(cx);
6715 let offset = self.selections.newest::<usize>(cx).head();
6716 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6717 let buffer_id = excerpt.buffer().remote_id();
6718
6719 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6720 let mut cursor = layer.node().walk();
6721
6722 while cursor.goto_first_child_for_byte(offset).is_some() {
6723 if cursor.node().end_byte() == offset {
6724 cursor.goto_next_sibling();
6725 }
6726 }
6727
6728 // Ascend to the smallest ancestor that contains the range and has a task.
6729 loop {
6730 let node = cursor.node();
6731 let node_range = node.byte_range();
6732 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6733
6734 // Check if this node contains our offset
6735 if node_range.start <= offset && node_range.end >= offset {
6736 // If it contains offset, check for task
6737 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6738 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6739 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6740 }
6741 }
6742
6743 if !cursor.goto_parent() {
6744 break;
6745 }
6746 }
6747 None
6748 }
6749
6750 fn render_run_indicator(
6751 &self,
6752 _style: &EditorStyle,
6753 is_active: bool,
6754 row: DisplayRow,
6755 breakpoint: Option<(Anchor, Breakpoint)>,
6756 cx: &mut Context<Self>,
6757 ) -> IconButton {
6758 let color = Color::Muted;
6759 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6760
6761 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6762 .shape(ui::IconButtonShape::Square)
6763 .icon_size(IconSize::XSmall)
6764 .icon_color(color)
6765 .toggle_state(is_active)
6766 .on_click(cx.listener(move |editor, _e, window, cx| {
6767 window.focus(&editor.focus_handle(cx));
6768 editor.toggle_code_actions(
6769 &ToggleCodeActions {
6770 deployed_from_indicator: Some(row),
6771 },
6772 window,
6773 cx,
6774 );
6775 }))
6776 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6777 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6778 }))
6779 }
6780
6781 pub fn context_menu_visible(&self) -> bool {
6782 !self.edit_prediction_preview_is_active()
6783 && self
6784 .context_menu
6785 .borrow()
6786 .as_ref()
6787 .map_or(false, |menu| menu.visible())
6788 }
6789
6790 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6791 self.context_menu
6792 .borrow()
6793 .as_ref()
6794 .map(|menu| menu.origin())
6795 }
6796
6797 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6798 self.context_menu_options = Some(options);
6799 }
6800
6801 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6802 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6803
6804 fn render_edit_prediction_popover(
6805 &mut self,
6806 text_bounds: &Bounds<Pixels>,
6807 content_origin: gpui::Point<Pixels>,
6808 editor_snapshot: &EditorSnapshot,
6809 visible_row_range: Range<DisplayRow>,
6810 scroll_top: f32,
6811 scroll_bottom: f32,
6812 line_layouts: &[LineWithInvisibles],
6813 line_height: Pixels,
6814 scroll_pixel_position: gpui::Point<Pixels>,
6815 newest_selection_head: Option<DisplayPoint>,
6816 editor_width: Pixels,
6817 style: &EditorStyle,
6818 window: &mut Window,
6819 cx: &mut App,
6820 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6821 let active_inline_completion = self.active_inline_completion.as_ref()?;
6822
6823 if self.edit_prediction_visible_in_cursor_popover(true) {
6824 return None;
6825 }
6826
6827 match &active_inline_completion.completion {
6828 InlineCompletion::Move { target, .. } => {
6829 let target_display_point = target.to_display_point(editor_snapshot);
6830
6831 if self.edit_prediction_requires_modifier() {
6832 if !self.edit_prediction_preview_is_active() {
6833 return None;
6834 }
6835
6836 self.render_edit_prediction_modifier_jump_popover(
6837 text_bounds,
6838 content_origin,
6839 visible_row_range,
6840 line_layouts,
6841 line_height,
6842 scroll_pixel_position,
6843 newest_selection_head,
6844 target_display_point,
6845 window,
6846 cx,
6847 )
6848 } else {
6849 self.render_edit_prediction_eager_jump_popover(
6850 text_bounds,
6851 content_origin,
6852 editor_snapshot,
6853 visible_row_range,
6854 scroll_top,
6855 scroll_bottom,
6856 line_height,
6857 scroll_pixel_position,
6858 target_display_point,
6859 editor_width,
6860 window,
6861 cx,
6862 )
6863 }
6864 }
6865 InlineCompletion::Edit {
6866 display_mode: EditDisplayMode::Inline,
6867 ..
6868 } => None,
6869 InlineCompletion::Edit {
6870 display_mode: EditDisplayMode::TabAccept,
6871 edits,
6872 ..
6873 } => {
6874 let range = &edits.first()?.0;
6875 let target_display_point = range.end.to_display_point(editor_snapshot);
6876
6877 self.render_edit_prediction_end_of_line_popover(
6878 "Accept",
6879 editor_snapshot,
6880 visible_row_range,
6881 target_display_point,
6882 line_height,
6883 scroll_pixel_position,
6884 content_origin,
6885 editor_width,
6886 window,
6887 cx,
6888 )
6889 }
6890 InlineCompletion::Edit {
6891 edits,
6892 edit_preview,
6893 display_mode: EditDisplayMode::DiffPopover,
6894 snapshot,
6895 } => self.render_edit_prediction_diff_popover(
6896 text_bounds,
6897 content_origin,
6898 editor_snapshot,
6899 visible_row_range,
6900 line_layouts,
6901 line_height,
6902 scroll_pixel_position,
6903 newest_selection_head,
6904 editor_width,
6905 style,
6906 edits,
6907 edit_preview,
6908 snapshot,
6909 window,
6910 cx,
6911 ),
6912 }
6913 }
6914
6915 fn render_edit_prediction_modifier_jump_popover(
6916 &mut self,
6917 text_bounds: &Bounds<Pixels>,
6918 content_origin: gpui::Point<Pixels>,
6919 visible_row_range: Range<DisplayRow>,
6920 line_layouts: &[LineWithInvisibles],
6921 line_height: Pixels,
6922 scroll_pixel_position: gpui::Point<Pixels>,
6923 newest_selection_head: Option<DisplayPoint>,
6924 target_display_point: DisplayPoint,
6925 window: &mut Window,
6926 cx: &mut App,
6927 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6928 let scrolled_content_origin =
6929 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6930
6931 const SCROLL_PADDING_Y: Pixels = px(12.);
6932
6933 if target_display_point.row() < visible_row_range.start {
6934 return self.render_edit_prediction_scroll_popover(
6935 |_| SCROLL_PADDING_Y,
6936 IconName::ArrowUp,
6937 visible_row_range,
6938 line_layouts,
6939 newest_selection_head,
6940 scrolled_content_origin,
6941 window,
6942 cx,
6943 );
6944 } else if target_display_point.row() >= visible_row_range.end {
6945 return self.render_edit_prediction_scroll_popover(
6946 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6947 IconName::ArrowDown,
6948 visible_row_range,
6949 line_layouts,
6950 newest_selection_head,
6951 scrolled_content_origin,
6952 window,
6953 cx,
6954 );
6955 }
6956
6957 const POLE_WIDTH: Pixels = px(2.);
6958
6959 let line_layout =
6960 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6961 let target_column = target_display_point.column() as usize;
6962
6963 let target_x = line_layout.x_for_index(target_column);
6964 let target_y =
6965 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6966
6967 let flag_on_right = target_x < text_bounds.size.width / 2.;
6968
6969 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6970 border_color.l += 0.001;
6971
6972 let mut element = v_flex()
6973 .items_end()
6974 .when(flag_on_right, |el| el.items_start())
6975 .child(if flag_on_right {
6976 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6977 .rounded_bl(px(0.))
6978 .rounded_tl(px(0.))
6979 .border_l_2()
6980 .border_color(border_color)
6981 } else {
6982 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6983 .rounded_br(px(0.))
6984 .rounded_tr(px(0.))
6985 .border_r_2()
6986 .border_color(border_color)
6987 })
6988 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6989 .into_any();
6990
6991 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6992
6993 let mut origin = scrolled_content_origin + point(target_x, target_y)
6994 - point(
6995 if flag_on_right {
6996 POLE_WIDTH
6997 } else {
6998 size.width - POLE_WIDTH
6999 },
7000 size.height - line_height,
7001 );
7002
7003 origin.x = origin.x.max(content_origin.x);
7004
7005 element.prepaint_at(origin, window, cx);
7006
7007 Some((element, origin))
7008 }
7009
7010 fn render_edit_prediction_scroll_popover(
7011 &mut self,
7012 to_y: impl Fn(Size<Pixels>) -> Pixels,
7013 scroll_icon: IconName,
7014 visible_row_range: Range<DisplayRow>,
7015 line_layouts: &[LineWithInvisibles],
7016 newest_selection_head: Option<DisplayPoint>,
7017 scrolled_content_origin: gpui::Point<Pixels>,
7018 window: &mut Window,
7019 cx: &mut App,
7020 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7021 let mut element = self
7022 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7023 .into_any();
7024
7025 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7026
7027 let cursor = newest_selection_head?;
7028 let cursor_row_layout =
7029 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7030 let cursor_column = cursor.column() as usize;
7031
7032 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7033
7034 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7035
7036 element.prepaint_at(origin, window, cx);
7037 Some((element, origin))
7038 }
7039
7040 fn render_edit_prediction_eager_jump_popover(
7041 &mut self,
7042 text_bounds: &Bounds<Pixels>,
7043 content_origin: gpui::Point<Pixels>,
7044 editor_snapshot: &EditorSnapshot,
7045 visible_row_range: Range<DisplayRow>,
7046 scroll_top: f32,
7047 scroll_bottom: f32,
7048 line_height: Pixels,
7049 scroll_pixel_position: gpui::Point<Pixels>,
7050 target_display_point: DisplayPoint,
7051 editor_width: Pixels,
7052 window: &mut Window,
7053 cx: &mut App,
7054 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7055 if target_display_point.row().as_f32() < scroll_top {
7056 let mut element = self
7057 .render_edit_prediction_line_popover(
7058 "Jump to Edit",
7059 Some(IconName::ArrowUp),
7060 window,
7061 cx,
7062 )?
7063 .into_any();
7064
7065 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7066 let offset = point(
7067 (text_bounds.size.width - size.width) / 2.,
7068 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7069 );
7070
7071 let origin = text_bounds.origin + offset;
7072 element.prepaint_at(origin, window, cx);
7073 Some((element, origin))
7074 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7075 let mut element = self
7076 .render_edit_prediction_line_popover(
7077 "Jump to Edit",
7078 Some(IconName::ArrowDown),
7079 window,
7080 cx,
7081 )?
7082 .into_any();
7083
7084 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7085 let offset = point(
7086 (text_bounds.size.width - size.width) / 2.,
7087 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7088 );
7089
7090 let origin = text_bounds.origin + offset;
7091 element.prepaint_at(origin, window, cx);
7092 Some((element, origin))
7093 } else {
7094 self.render_edit_prediction_end_of_line_popover(
7095 "Jump to Edit",
7096 editor_snapshot,
7097 visible_row_range,
7098 target_display_point,
7099 line_height,
7100 scroll_pixel_position,
7101 content_origin,
7102 editor_width,
7103 window,
7104 cx,
7105 )
7106 }
7107 }
7108
7109 fn render_edit_prediction_end_of_line_popover(
7110 self: &mut Editor,
7111 label: &'static str,
7112 editor_snapshot: &EditorSnapshot,
7113 visible_row_range: Range<DisplayRow>,
7114 target_display_point: DisplayPoint,
7115 line_height: Pixels,
7116 scroll_pixel_position: gpui::Point<Pixels>,
7117 content_origin: gpui::Point<Pixels>,
7118 editor_width: Pixels,
7119 window: &mut Window,
7120 cx: &mut App,
7121 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7122 let target_line_end = DisplayPoint::new(
7123 target_display_point.row(),
7124 editor_snapshot.line_len(target_display_point.row()),
7125 );
7126
7127 let mut element = self
7128 .render_edit_prediction_line_popover(label, None, window, cx)?
7129 .into_any();
7130
7131 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7132
7133 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7134
7135 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7136 let mut origin = start_point
7137 + line_origin
7138 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7139 origin.x = origin.x.max(content_origin.x);
7140
7141 let max_x = content_origin.x + editor_width - size.width;
7142
7143 if origin.x > max_x {
7144 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7145
7146 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7147 origin.y += offset;
7148 IconName::ArrowUp
7149 } else {
7150 origin.y -= offset;
7151 IconName::ArrowDown
7152 };
7153
7154 element = self
7155 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7156 .into_any();
7157
7158 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7159
7160 origin.x = content_origin.x + editor_width - size.width - px(2.);
7161 }
7162
7163 element.prepaint_at(origin, window, cx);
7164 Some((element, origin))
7165 }
7166
7167 fn render_edit_prediction_diff_popover(
7168 self: &Editor,
7169 text_bounds: &Bounds<Pixels>,
7170 content_origin: gpui::Point<Pixels>,
7171 editor_snapshot: &EditorSnapshot,
7172 visible_row_range: Range<DisplayRow>,
7173 line_layouts: &[LineWithInvisibles],
7174 line_height: Pixels,
7175 scroll_pixel_position: gpui::Point<Pixels>,
7176 newest_selection_head: Option<DisplayPoint>,
7177 editor_width: Pixels,
7178 style: &EditorStyle,
7179 edits: &Vec<(Range<Anchor>, String)>,
7180 edit_preview: &Option<language::EditPreview>,
7181 snapshot: &language::BufferSnapshot,
7182 window: &mut Window,
7183 cx: &mut App,
7184 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7185 let edit_start = edits
7186 .first()
7187 .unwrap()
7188 .0
7189 .start
7190 .to_display_point(editor_snapshot);
7191 let edit_end = edits
7192 .last()
7193 .unwrap()
7194 .0
7195 .end
7196 .to_display_point(editor_snapshot);
7197
7198 let is_visible = visible_row_range.contains(&edit_start.row())
7199 || visible_row_range.contains(&edit_end.row());
7200 if !is_visible {
7201 return None;
7202 }
7203
7204 let highlighted_edits =
7205 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7206
7207 let styled_text = highlighted_edits.to_styled_text(&style.text);
7208 let line_count = highlighted_edits.text.lines().count();
7209
7210 const BORDER_WIDTH: Pixels = px(1.);
7211
7212 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7213 let has_keybind = keybind.is_some();
7214
7215 let mut element = h_flex()
7216 .items_start()
7217 .child(
7218 h_flex()
7219 .bg(cx.theme().colors().editor_background)
7220 .border(BORDER_WIDTH)
7221 .shadow_sm()
7222 .border_color(cx.theme().colors().border)
7223 .rounded_l_lg()
7224 .when(line_count > 1, |el| el.rounded_br_lg())
7225 .pr_1()
7226 .child(styled_text),
7227 )
7228 .child(
7229 h_flex()
7230 .h(line_height + BORDER_WIDTH * 2.)
7231 .px_1p5()
7232 .gap_1()
7233 // Workaround: For some reason, there's a gap if we don't do this
7234 .ml(-BORDER_WIDTH)
7235 .shadow(smallvec![gpui::BoxShadow {
7236 color: gpui::black().opacity(0.05),
7237 offset: point(px(1.), px(1.)),
7238 blur_radius: px(2.),
7239 spread_radius: px(0.),
7240 }])
7241 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7242 .border(BORDER_WIDTH)
7243 .border_color(cx.theme().colors().border)
7244 .rounded_r_lg()
7245 .id("edit_prediction_diff_popover_keybind")
7246 .when(!has_keybind, |el| {
7247 let status_colors = cx.theme().status();
7248
7249 el.bg(status_colors.error_background)
7250 .border_color(status_colors.error.opacity(0.6))
7251 .child(Icon::new(IconName::Info).color(Color::Error))
7252 .cursor_default()
7253 .hoverable_tooltip(move |_window, cx| {
7254 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7255 })
7256 })
7257 .children(keybind),
7258 )
7259 .into_any();
7260
7261 let longest_row =
7262 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7263 let longest_line_width = if visible_row_range.contains(&longest_row) {
7264 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7265 } else {
7266 layout_line(
7267 longest_row,
7268 editor_snapshot,
7269 style,
7270 editor_width,
7271 |_| false,
7272 window,
7273 cx,
7274 )
7275 .width
7276 };
7277
7278 let viewport_bounds =
7279 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7280 right: -EditorElement::SCROLLBAR_WIDTH,
7281 ..Default::default()
7282 });
7283
7284 let x_after_longest =
7285 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7286 - scroll_pixel_position.x;
7287
7288 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7289
7290 // Fully visible if it can be displayed within the window (allow overlapping other
7291 // panes). However, this is only allowed if the popover starts within text_bounds.
7292 let can_position_to_the_right = x_after_longest < text_bounds.right()
7293 && x_after_longest + element_bounds.width < viewport_bounds.right();
7294
7295 let mut origin = if can_position_to_the_right {
7296 point(
7297 x_after_longest,
7298 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7299 - scroll_pixel_position.y,
7300 )
7301 } else {
7302 let cursor_row = newest_selection_head.map(|head| head.row());
7303 let above_edit = edit_start
7304 .row()
7305 .0
7306 .checked_sub(line_count as u32)
7307 .map(DisplayRow);
7308 let below_edit = Some(edit_end.row() + 1);
7309 let above_cursor =
7310 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7311 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7312
7313 // Place the edit popover adjacent to the edit if there is a location
7314 // available that is onscreen and does not obscure the cursor. Otherwise,
7315 // place it adjacent to the cursor.
7316 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7317 .into_iter()
7318 .flatten()
7319 .find(|&start_row| {
7320 let end_row = start_row + line_count as u32;
7321 visible_row_range.contains(&start_row)
7322 && visible_row_range.contains(&end_row)
7323 && cursor_row.map_or(true, |cursor_row| {
7324 !((start_row..end_row).contains(&cursor_row))
7325 })
7326 })?;
7327
7328 content_origin
7329 + point(
7330 -scroll_pixel_position.x,
7331 row_target.as_f32() * line_height - scroll_pixel_position.y,
7332 )
7333 };
7334
7335 origin.x -= BORDER_WIDTH;
7336
7337 window.defer_draw(element, origin, 1);
7338
7339 // Do not return an element, since it will already be drawn due to defer_draw.
7340 None
7341 }
7342
7343 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7344 px(30.)
7345 }
7346
7347 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7348 if self.read_only(cx) {
7349 cx.theme().players().read_only()
7350 } else {
7351 self.style.as_ref().unwrap().local_player
7352 }
7353 }
7354
7355 fn render_edit_prediction_accept_keybind(
7356 &self,
7357 window: &mut Window,
7358 cx: &App,
7359 ) -> Option<AnyElement> {
7360 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7361 let accept_keystroke = accept_binding.keystroke()?;
7362
7363 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7364
7365 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7366 Color::Accent
7367 } else {
7368 Color::Muted
7369 };
7370
7371 h_flex()
7372 .px_0p5()
7373 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7374 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7375 .text_size(TextSize::XSmall.rems(cx))
7376 .child(h_flex().children(ui::render_modifiers(
7377 &accept_keystroke.modifiers,
7378 PlatformStyle::platform(),
7379 Some(modifiers_color),
7380 Some(IconSize::XSmall.rems().into()),
7381 true,
7382 )))
7383 .when(is_platform_style_mac, |parent| {
7384 parent.child(accept_keystroke.key.clone())
7385 })
7386 .when(!is_platform_style_mac, |parent| {
7387 parent.child(
7388 Key::new(
7389 util::capitalize(&accept_keystroke.key),
7390 Some(Color::Default),
7391 )
7392 .size(Some(IconSize::XSmall.rems().into())),
7393 )
7394 })
7395 .into_any()
7396 .into()
7397 }
7398
7399 fn render_edit_prediction_line_popover(
7400 &self,
7401 label: impl Into<SharedString>,
7402 icon: Option<IconName>,
7403 window: &mut Window,
7404 cx: &App,
7405 ) -> Option<Stateful<Div>> {
7406 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7407
7408 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7409 let has_keybind = keybind.is_some();
7410
7411 let result = h_flex()
7412 .id("ep-line-popover")
7413 .py_0p5()
7414 .pl_1()
7415 .pr(padding_right)
7416 .gap_1()
7417 .rounded_md()
7418 .border_1()
7419 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7420 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7421 .shadow_sm()
7422 .when(!has_keybind, |el| {
7423 let status_colors = cx.theme().status();
7424
7425 el.bg(status_colors.error_background)
7426 .border_color(status_colors.error.opacity(0.6))
7427 .pl_2()
7428 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7429 .cursor_default()
7430 .hoverable_tooltip(move |_window, cx| {
7431 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7432 })
7433 })
7434 .children(keybind)
7435 .child(
7436 Label::new(label)
7437 .size(LabelSize::Small)
7438 .when(!has_keybind, |el| {
7439 el.color(cx.theme().status().error.into()).strikethrough()
7440 }),
7441 )
7442 .when(!has_keybind, |el| {
7443 el.child(
7444 h_flex().ml_1().child(
7445 Icon::new(IconName::Info)
7446 .size(IconSize::Small)
7447 .color(cx.theme().status().error.into()),
7448 ),
7449 )
7450 })
7451 .when_some(icon, |element, icon| {
7452 element.child(
7453 div()
7454 .mt(px(1.5))
7455 .child(Icon::new(icon).size(IconSize::Small)),
7456 )
7457 });
7458
7459 Some(result)
7460 }
7461
7462 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7463 let accent_color = cx.theme().colors().text_accent;
7464 let editor_bg_color = cx.theme().colors().editor_background;
7465 editor_bg_color.blend(accent_color.opacity(0.1))
7466 }
7467
7468 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7469 let accent_color = cx.theme().colors().text_accent;
7470 let editor_bg_color = cx.theme().colors().editor_background;
7471 editor_bg_color.blend(accent_color.opacity(0.6))
7472 }
7473
7474 fn render_edit_prediction_cursor_popover(
7475 &self,
7476 min_width: Pixels,
7477 max_width: Pixels,
7478 cursor_point: Point,
7479 style: &EditorStyle,
7480 accept_keystroke: Option<&gpui::Keystroke>,
7481 _window: &Window,
7482 cx: &mut Context<Editor>,
7483 ) -> Option<AnyElement> {
7484 let provider = self.edit_prediction_provider.as_ref()?;
7485
7486 if provider.provider.needs_terms_acceptance(cx) {
7487 return Some(
7488 h_flex()
7489 .min_w(min_width)
7490 .flex_1()
7491 .px_2()
7492 .py_1()
7493 .gap_3()
7494 .elevation_2(cx)
7495 .hover(|style| style.bg(cx.theme().colors().element_hover))
7496 .id("accept-terms")
7497 .cursor_pointer()
7498 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7499 .on_click(cx.listener(|this, _event, window, cx| {
7500 cx.stop_propagation();
7501 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7502 window.dispatch_action(
7503 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7504 cx,
7505 );
7506 }))
7507 .child(
7508 h_flex()
7509 .flex_1()
7510 .gap_2()
7511 .child(Icon::new(IconName::ZedPredict))
7512 .child(Label::new("Accept Terms of Service"))
7513 .child(div().w_full())
7514 .child(
7515 Icon::new(IconName::ArrowUpRight)
7516 .color(Color::Muted)
7517 .size(IconSize::Small),
7518 )
7519 .into_any_element(),
7520 )
7521 .into_any(),
7522 );
7523 }
7524
7525 let is_refreshing = provider.provider.is_refreshing(cx);
7526
7527 fn pending_completion_container() -> Div {
7528 h_flex()
7529 .h_full()
7530 .flex_1()
7531 .gap_2()
7532 .child(Icon::new(IconName::ZedPredict))
7533 }
7534
7535 let completion = match &self.active_inline_completion {
7536 Some(prediction) => {
7537 if !self.has_visible_completions_menu() {
7538 const RADIUS: Pixels = px(6.);
7539 const BORDER_WIDTH: Pixels = px(1.);
7540
7541 return Some(
7542 h_flex()
7543 .elevation_2(cx)
7544 .border(BORDER_WIDTH)
7545 .border_color(cx.theme().colors().border)
7546 .when(accept_keystroke.is_none(), |el| {
7547 el.border_color(cx.theme().status().error)
7548 })
7549 .rounded(RADIUS)
7550 .rounded_tl(px(0.))
7551 .overflow_hidden()
7552 .child(div().px_1p5().child(match &prediction.completion {
7553 InlineCompletion::Move { target, snapshot } => {
7554 use text::ToPoint as _;
7555 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7556 {
7557 Icon::new(IconName::ZedPredictDown)
7558 } else {
7559 Icon::new(IconName::ZedPredictUp)
7560 }
7561 }
7562 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7563 }))
7564 .child(
7565 h_flex()
7566 .gap_1()
7567 .py_1()
7568 .px_2()
7569 .rounded_r(RADIUS - BORDER_WIDTH)
7570 .border_l_1()
7571 .border_color(cx.theme().colors().border)
7572 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7573 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7574 el.child(
7575 Label::new("Hold")
7576 .size(LabelSize::Small)
7577 .when(accept_keystroke.is_none(), |el| {
7578 el.strikethrough()
7579 })
7580 .line_height_style(LineHeightStyle::UiLabel),
7581 )
7582 })
7583 .id("edit_prediction_cursor_popover_keybind")
7584 .when(accept_keystroke.is_none(), |el| {
7585 let status_colors = cx.theme().status();
7586
7587 el.bg(status_colors.error_background)
7588 .border_color(status_colors.error.opacity(0.6))
7589 .child(Icon::new(IconName::Info).color(Color::Error))
7590 .cursor_default()
7591 .hoverable_tooltip(move |_window, cx| {
7592 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7593 .into()
7594 })
7595 })
7596 .when_some(
7597 accept_keystroke.as_ref(),
7598 |el, accept_keystroke| {
7599 el.child(h_flex().children(ui::render_modifiers(
7600 &accept_keystroke.modifiers,
7601 PlatformStyle::platform(),
7602 Some(Color::Default),
7603 Some(IconSize::XSmall.rems().into()),
7604 false,
7605 )))
7606 },
7607 ),
7608 )
7609 .into_any(),
7610 );
7611 }
7612
7613 self.render_edit_prediction_cursor_popover_preview(
7614 prediction,
7615 cursor_point,
7616 style,
7617 cx,
7618 )?
7619 }
7620
7621 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7622 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7623 stale_completion,
7624 cursor_point,
7625 style,
7626 cx,
7627 )?,
7628
7629 None => {
7630 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7631 }
7632 },
7633
7634 None => pending_completion_container().child(Label::new("No Prediction")),
7635 };
7636
7637 let completion = if is_refreshing {
7638 completion
7639 .with_animation(
7640 "loading-completion",
7641 Animation::new(Duration::from_secs(2))
7642 .repeat()
7643 .with_easing(pulsating_between(0.4, 0.8)),
7644 |label, delta| label.opacity(delta),
7645 )
7646 .into_any_element()
7647 } else {
7648 completion.into_any_element()
7649 };
7650
7651 let has_completion = self.active_inline_completion.is_some();
7652
7653 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7654 Some(
7655 h_flex()
7656 .min_w(min_width)
7657 .max_w(max_width)
7658 .flex_1()
7659 .elevation_2(cx)
7660 .border_color(cx.theme().colors().border)
7661 .child(
7662 div()
7663 .flex_1()
7664 .py_1()
7665 .px_2()
7666 .overflow_hidden()
7667 .child(completion),
7668 )
7669 .when_some(accept_keystroke, |el, accept_keystroke| {
7670 if !accept_keystroke.modifiers.modified() {
7671 return el;
7672 }
7673
7674 el.child(
7675 h_flex()
7676 .h_full()
7677 .border_l_1()
7678 .rounded_r_lg()
7679 .border_color(cx.theme().colors().border)
7680 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7681 .gap_1()
7682 .py_1()
7683 .px_2()
7684 .child(
7685 h_flex()
7686 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7687 .when(is_platform_style_mac, |parent| parent.gap_1())
7688 .child(h_flex().children(ui::render_modifiers(
7689 &accept_keystroke.modifiers,
7690 PlatformStyle::platform(),
7691 Some(if !has_completion {
7692 Color::Muted
7693 } else {
7694 Color::Default
7695 }),
7696 None,
7697 false,
7698 ))),
7699 )
7700 .child(Label::new("Preview").into_any_element())
7701 .opacity(if has_completion { 1.0 } else { 0.4 }),
7702 )
7703 })
7704 .into_any(),
7705 )
7706 }
7707
7708 fn render_edit_prediction_cursor_popover_preview(
7709 &self,
7710 completion: &InlineCompletionState,
7711 cursor_point: Point,
7712 style: &EditorStyle,
7713 cx: &mut Context<Editor>,
7714 ) -> Option<Div> {
7715 use text::ToPoint as _;
7716
7717 fn render_relative_row_jump(
7718 prefix: impl Into<String>,
7719 current_row: u32,
7720 target_row: u32,
7721 ) -> Div {
7722 let (row_diff, arrow) = if target_row < current_row {
7723 (current_row - target_row, IconName::ArrowUp)
7724 } else {
7725 (target_row - current_row, IconName::ArrowDown)
7726 };
7727
7728 h_flex()
7729 .child(
7730 Label::new(format!("{}{}", prefix.into(), row_diff))
7731 .color(Color::Muted)
7732 .size(LabelSize::Small),
7733 )
7734 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7735 }
7736
7737 match &completion.completion {
7738 InlineCompletion::Move {
7739 target, snapshot, ..
7740 } => Some(
7741 h_flex()
7742 .px_2()
7743 .gap_2()
7744 .flex_1()
7745 .child(
7746 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7747 Icon::new(IconName::ZedPredictDown)
7748 } else {
7749 Icon::new(IconName::ZedPredictUp)
7750 },
7751 )
7752 .child(Label::new("Jump to Edit")),
7753 ),
7754
7755 InlineCompletion::Edit {
7756 edits,
7757 edit_preview,
7758 snapshot,
7759 display_mode: _,
7760 } => {
7761 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7762
7763 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7764 &snapshot,
7765 &edits,
7766 edit_preview.as_ref()?,
7767 true,
7768 cx,
7769 )
7770 .first_line_preview();
7771
7772 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7773 .with_default_highlights(&style.text, highlighted_edits.highlights);
7774
7775 let preview = h_flex()
7776 .gap_1()
7777 .min_w_16()
7778 .child(styled_text)
7779 .when(has_more_lines, |parent| parent.child("…"));
7780
7781 let left = if first_edit_row != cursor_point.row {
7782 render_relative_row_jump("", cursor_point.row, first_edit_row)
7783 .into_any_element()
7784 } else {
7785 Icon::new(IconName::ZedPredict).into_any_element()
7786 };
7787
7788 Some(
7789 h_flex()
7790 .h_full()
7791 .flex_1()
7792 .gap_2()
7793 .pr_1()
7794 .overflow_x_hidden()
7795 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7796 .child(left)
7797 .child(preview),
7798 )
7799 }
7800 }
7801 }
7802
7803 fn render_context_menu(
7804 &self,
7805 style: &EditorStyle,
7806 max_height_in_lines: u32,
7807 window: &mut Window,
7808 cx: &mut Context<Editor>,
7809 ) -> Option<AnyElement> {
7810 let menu = self.context_menu.borrow();
7811 let menu = menu.as_ref()?;
7812 if !menu.visible() {
7813 return None;
7814 };
7815 Some(menu.render(style, max_height_in_lines, window, cx))
7816 }
7817
7818 fn render_context_menu_aside(
7819 &mut self,
7820 max_size: Size<Pixels>,
7821 window: &mut Window,
7822 cx: &mut Context<Editor>,
7823 ) -> Option<AnyElement> {
7824 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7825 if menu.visible() {
7826 menu.render_aside(self, max_size, window, cx)
7827 } else {
7828 None
7829 }
7830 })
7831 }
7832
7833 fn hide_context_menu(
7834 &mut self,
7835 window: &mut Window,
7836 cx: &mut Context<Self>,
7837 ) -> Option<CodeContextMenu> {
7838 cx.notify();
7839 self.completion_tasks.clear();
7840 let context_menu = self.context_menu.borrow_mut().take();
7841 self.stale_inline_completion_in_menu.take();
7842 self.update_visible_inline_completion(window, cx);
7843 context_menu
7844 }
7845
7846 fn show_snippet_choices(
7847 &mut self,
7848 choices: &Vec<String>,
7849 selection: Range<Anchor>,
7850 cx: &mut Context<Self>,
7851 ) {
7852 if selection.start.buffer_id.is_none() {
7853 return;
7854 }
7855 let buffer_id = selection.start.buffer_id.unwrap();
7856 let buffer = self.buffer().read(cx).buffer(buffer_id);
7857 let id = post_inc(&mut self.next_completion_id);
7858
7859 if let Some(buffer) = buffer {
7860 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7861 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7862 ));
7863 }
7864 }
7865
7866 pub fn insert_snippet(
7867 &mut self,
7868 insertion_ranges: &[Range<usize>],
7869 snippet: Snippet,
7870 window: &mut Window,
7871 cx: &mut Context<Self>,
7872 ) -> Result<()> {
7873 struct Tabstop<T> {
7874 is_end_tabstop: bool,
7875 ranges: Vec<Range<T>>,
7876 choices: Option<Vec<String>>,
7877 }
7878
7879 let tabstops = self.buffer.update(cx, |buffer, cx| {
7880 let snippet_text: Arc<str> = snippet.text.clone().into();
7881 let edits = insertion_ranges
7882 .iter()
7883 .cloned()
7884 .map(|range| (range, snippet_text.clone()));
7885 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7886
7887 let snapshot = &*buffer.read(cx);
7888 let snippet = &snippet;
7889 snippet
7890 .tabstops
7891 .iter()
7892 .map(|tabstop| {
7893 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7894 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7895 });
7896 let mut tabstop_ranges = tabstop
7897 .ranges
7898 .iter()
7899 .flat_map(|tabstop_range| {
7900 let mut delta = 0_isize;
7901 insertion_ranges.iter().map(move |insertion_range| {
7902 let insertion_start = insertion_range.start as isize + delta;
7903 delta +=
7904 snippet.text.len() as isize - insertion_range.len() as isize;
7905
7906 let start = ((insertion_start + tabstop_range.start) as usize)
7907 .min(snapshot.len());
7908 let end = ((insertion_start + tabstop_range.end) as usize)
7909 .min(snapshot.len());
7910 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7911 })
7912 })
7913 .collect::<Vec<_>>();
7914 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7915
7916 Tabstop {
7917 is_end_tabstop,
7918 ranges: tabstop_ranges,
7919 choices: tabstop.choices.clone(),
7920 }
7921 })
7922 .collect::<Vec<_>>()
7923 });
7924 if let Some(tabstop) = tabstops.first() {
7925 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7926 s.select_ranges(tabstop.ranges.iter().cloned());
7927 });
7928
7929 if let Some(choices) = &tabstop.choices {
7930 if let Some(selection) = tabstop.ranges.first() {
7931 self.show_snippet_choices(choices, selection.clone(), cx)
7932 }
7933 }
7934
7935 // If we're already at the last tabstop and it's at the end of the snippet,
7936 // we're done, we don't need to keep the state around.
7937 if !tabstop.is_end_tabstop {
7938 let choices = tabstops
7939 .iter()
7940 .map(|tabstop| tabstop.choices.clone())
7941 .collect();
7942
7943 let ranges = tabstops
7944 .into_iter()
7945 .map(|tabstop| tabstop.ranges)
7946 .collect::<Vec<_>>();
7947
7948 self.snippet_stack.push(SnippetState {
7949 active_index: 0,
7950 ranges,
7951 choices,
7952 });
7953 }
7954
7955 // Check whether the just-entered snippet ends with an auto-closable bracket.
7956 if self.autoclose_regions.is_empty() {
7957 let snapshot = self.buffer.read(cx).snapshot(cx);
7958 for selection in &mut self.selections.all::<Point>(cx) {
7959 let selection_head = selection.head();
7960 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7961 continue;
7962 };
7963
7964 let mut bracket_pair = None;
7965 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7966 let prev_chars = snapshot
7967 .reversed_chars_at(selection_head)
7968 .collect::<String>();
7969 for (pair, enabled) in scope.brackets() {
7970 if enabled
7971 && pair.close
7972 && prev_chars.starts_with(pair.start.as_str())
7973 && next_chars.starts_with(pair.end.as_str())
7974 {
7975 bracket_pair = Some(pair.clone());
7976 break;
7977 }
7978 }
7979 if let Some(pair) = bracket_pair {
7980 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
7981 let autoclose_enabled =
7982 self.use_autoclose && snapshot_settings.use_autoclose;
7983 if autoclose_enabled {
7984 let start = snapshot.anchor_after(selection_head);
7985 let end = snapshot.anchor_after(selection_head);
7986 self.autoclose_regions.push(AutocloseRegion {
7987 selection_id: selection.id,
7988 range: start..end,
7989 pair,
7990 });
7991 }
7992 }
7993 }
7994 }
7995 }
7996 Ok(())
7997 }
7998
7999 pub fn move_to_next_snippet_tabstop(
8000 &mut self,
8001 window: &mut Window,
8002 cx: &mut Context<Self>,
8003 ) -> bool {
8004 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8005 }
8006
8007 pub fn move_to_prev_snippet_tabstop(
8008 &mut self,
8009 window: &mut Window,
8010 cx: &mut Context<Self>,
8011 ) -> bool {
8012 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8013 }
8014
8015 pub fn move_to_snippet_tabstop(
8016 &mut self,
8017 bias: Bias,
8018 window: &mut Window,
8019 cx: &mut Context<Self>,
8020 ) -> bool {
8021 if let Some(mut snippet) = self.snippet_stack.pop() {
8022 match bias {
8023 Bias::Left => {
8024 if snippet.active_index > 0 {
8025 snippet.active_index -= 1;
8026 } else {
8027 self.snippet_stack.push(snippet);
8028 return false;
8029 }
8030 }
8031 Bias::Right => {
8032 if snippet.active_index + 1 < snippet.ranges.len() {
8033 snippet.active_index += 1;
8034 } else {
8035 self.snippet_stack.push(snippet);
8036 return false;
8037 }
8038 }
8039 }
8040 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8041 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8042 s.select_anchor_ranges(current_ranges.iter().cloned())
8043 });
8044
8045 if let Some(choices) = &snippet.choices[snippet.active_index] {
8046 if let Some(selection) = current_ranges.first() {
8047 self.show_snippet_choices(&choices, selection.clone(), cx);
8048 }
8049 }
8050
8051 // If snippet state is not at the last tabstop, push it back on the stack
8052 if snippet.active_index + 1 < snippet.ranges.len() {
8053 self.snippet_stack.push(snippet);
8054 }
8055 return true;
8056 }
8057 }
8058
8059 false
8060 }
8061
8062 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8063 self.transact(window, cx, |this, window, cx| {
8064 this.select_all(&SelectAll, window, cx);
8065 this.insert("", window, cx);
8066 });
8067 }
8068
8069 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8070 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8071 self.transact(window, cx, |this, window, cx| {
8072 this.select_autoclose_pair(window, cx);
8073 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8074 if !this.linked_edit_ranges.is_empty() {
8075 let selections = this.selections.all::<MultiBufferPoint>(cx);
8076 let snapshot = this.buffer.read(cx).snapshot(cx);
8077
8078 for selection in selections.iter() {
8079 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8080 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8081 if selection_start.buffer_id != selection_end.buffer_id {
8082 continue;
8083 }
8084 if let Some(ranges) =
8085 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8086 {
8087 for (buffer, entries) in ranges {
8088 linked_ranges.entry(buffer).or_default().extend(entries);
8089 }
8090 }
8091 }
8092 }
8093
8094 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8095 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8096 for selection in &mut selections {
8097 if selection.is_empty() {
8098 let old_head = selection.head();
8099 let mut new_head =
8100 movement::left(&display_map, old_head.to_display_point(&display_map))
8101 .to_point(&display_map);
8102 if let Some((buffer, line_buffer_range)) = display_map
8103 .buffer_snapshot
8104 .buffer_line_for_row(MultiBufferRow(old_head.row))
8105 {
8106 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8107 let indent_len = match indent_size.kind {
8108 IndentKind::Space => {
8109 buffer.settings_at(line_buffer_range.start, cx).tab_size
8110 }
8111 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8112 };
8113 if old_head.column <= indent_size.len && old_head.column > 0 {
8114 let indent_len = indent_len.get();
8115 new_head = cmp::min(
8116 new_head,
8117 MultiBufferPoint::new(
8118 old_head.row,
8119 ((old_head.column - 1) / indent_len) * indent_len,
8120 ),
8121 );
8122 }
8123 }
8124
8125 selection.set_head(new_head, SelectionGoal::None);
8126 }
8127 }
8128
8129 this.signature_help_state.set_backspace_pressed(true);
8130 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8131 s.select(selections)
8132 });
8133 this.insert("", window, cx);
8134 let empty_str: Arc<str> = Arc::from("");
8135 for (buffer, edits) in linked_ranges {
8136 let snapshot = buffer.read(cx).snapshot();
8137 use text::ToPoint as TP;
8138
8139 let edits = edits
8140 .into_iter()
8141 .map(|range| {
8142 let end_point = TP::to_point(&range.end, &snapshot);
8143 let mut start_point = TP::to_point(&range.start, &snapshot);
8144
8145 if end_point == start_point {
8146 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8147 .saturating_sub(1);
8148 start_point =
8149 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8150 };
8151
8152 (start_point..end_point, empty_str.clone())
8153 })
8154 .sorted_by_key(|(range, _)| range.start)
8155 .collect::<Vec<_>>();
8156 buffer.update(cx, |this, cx| {
8157 this.edit(edits, None, cx);
8158 })
8159 }
8160 this.refresh_inline_completion(true, false, window, cx);
8161 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8162 });
8163 }
8164
8165 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8166 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8167 self.transact(window, cx, |this, window, cx| {
8168 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8169 s.move_with(|map, selection| {
8170 if selection.is_empty() {
8171 let cursor = movement::right(map, selection.head());
8172 selection.end = cursor;
8173 selection.reversed = true;
8174 selection.goal = SelectionGoal::None;
8175 }
8176 })
8177 });
8178 this.insert("", window, cx);
8179 this.refresh_inline_completion(true, false, window, cx);
8180 });
8181 }
8182
8183 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8184 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8185 if self.move_to_prev_snippet_tabstop(window, cx) {
8186 return;
8187 }
8188 self.outdent(&Outdent, window, cx);
8189 }
8190
8191 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8192 if self.move_to_next_snippet_tabstop(window, cx) {
8193 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8194 return;
8195 }
8196 if self.read_only(cx) {
8197 return;
8198 }
8199 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8200 let mut selections = self.selections.all_adjusted(cx);
8201 let buffer = self.buffer.read(cx);
8202 let snapshot = buffer.snapshot(cx);
8203 let rows_iter = selections.iter().map(|s| s.head().row);
8204 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8205
8206 let mut edits = Vec::new();
8207 let mut prev_edited_row = 0;
8208 let mut row_delta = 0;
8209 for selection in &mut selections {
8210 if selection.start.row != prev_edited_row {
8211 row_delta = 0;
8212 }
8213 prev_edited_row = selection.end.row;
8214
8215 // If the selection is non-empty, then increase the indentation of the selected lines.
8216 if !selection.is_empty() {
8217 row_delta =
8218 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8219 continue;
8220 }
8221
8222 // If the selection is empty and the cursor is in the leading whitespace before the
8223 // suggested indentation, then auto-indent the line.
8224 let cursor = selection.head();
8225 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8226 if let Some(suggested_indent) =
8227 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8228 {
8229 if cursor.column < suggested_indent.len
8230 && cursor.column <= current_indent.len
8231 && current_indent.len <= suggested_indent.len
8232 {
8233 selection.start = Point::new(cursor.row, suggested_indent.len);
8234 selection.end = selection.start;
8235 if row_delta == 0 {
8236 edits.extend(Buffer::edit_for_indent_size_adjustment(
8237 cursor.row,
8238 current_indent,
8239 suggested_indent,
8240 ));
8241 row_delta = suggested_indent.len - current_indent.len;
8242 }
8243 continue;
8244 }
8245 }
8246
8247 // Otherwise, insert a hard or soft tab.
8248 let settings = buffer.language_settings_at(cursor, cx);
8249 let tab_size = if settings.hard_tabs {
8250 IndentSize::tab()
8251 } else {
8252 let tab_size = settings.tab_size.get();
8253 let indent_remainder = snapshot
8254 .text_for_range(Point::new(cursor.row, 0)..cursor)
8255 .flat_map(str::chars)
8256 .fold(row_delta % tab_size, |counter: u32, c| {
8257 if c == '\t' {
8258 0
8259 } else {
8260 (counter + 1) % tab_size
8261 }
8262 });
8263
8264 let chars_to_next_tab_stop = tab_size - indent_remainder;
8265 IndentSize::spaces(chars_to_next_tab_stop)
8266 };
8267 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8268 selection.end = selection.start;
8269 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8270 row_delta += tab_size.len;
8271 }
8272
8273 self.transact(window, cx, |this, window, cx| {
8274 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8275 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8276 s.select(selections)
8277 });
8278 this.refresh_inline_completion(true, false, window, cx);
8279 });
8280 }
8281
8282 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8283 if self.read_only(cx) {
8284 return;
8285 }
8286 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8287 let mut selections = self.selections.all::<Point>(cx);
8288 let mut prev_edited_row = 0;
8289 let mut row_delta = 0;
8290 let mut edits = Vec::new();
8291 let buffer = self.buffer.read(cx);
8292 let snapshot = buffer.snapshot(cx);
8293 for selection in &mut selections {
8294 if selection.start.row != prev_edited_row {
8295 row_delta = 0;
8296 }
8297 prev_edited_row = selection.end.row;
8298
8299 row_delta =
8300 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8301 }
8302
8303 self.transact(window, cx, |this, window, cx| {
8304 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8305 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8306 s.select(selections)
8307 });
8308 });
8309 }
8310
8311 fn indent_selection(
8312 buffer: &MultiBuffer,
8313 snapshot: &MultiBufferSnapshot,
8314 selection: &mut Selection<Point>,
8315 edits: &mut Vec<(Range<Point>, String)>,
8316 delta_for_start_row: u32,
8317 cx: &App,
8318 ) -> u32 {
8319 let settings = buffer.language_settings_at(selection.start, cx);
8320 let tab_size = settings.tab_size.get();
8321 let indent_kind = if settings.hard_tabs {
8322 IndentKind::Tab
8323 } else {
8324 IndentKind::Space
8325 };
8326 let mut start_row = selection.start.row;
8327 let mut end_row = selection.end.row + 1;
8328
8329 // If a selection ends at the beginning of a line, don't indent
8330 // that last line.
8331 if selection.end.column == 0 && selection.end.row > selection.start.row {
8332 end_row -= 1;
8333 }
8334
8335 // Avoid re-indenting a row that has already been indented by a
8336 // previous selection, but still update this selection's column
8337 // to reflect that indentation.
8338 if delta_for_start_row > 0 {
8339 start_row += 1;
8340 selection.start.column += delta_for_start_row;
8341 if selection.end.row == selection.start.row {
8342 selection.end.column += delta_for_start_row;
8343 }
8344 }
8345
8346 let mut delta_for_end_row = 0;
8347 let has_multiple_rows = start_row + 1 != end_row;
8348 for row in start_row..end_row {
8349 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8350 let indent_delta = match (current_indent.kind, indent_kind) {
8351 (IndentKind::Space, IndentKind::Space) => {
8352 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8353 IndentSize::spaces(columns_to_next_tab_stop)
8354 }
8355 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8356 (_, IndentKind::Tab) => IndentSize::tab(),
8357 };
8358
8359 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8360 0
8361 } else {
8362 selection.start.column
8363 };
8364 let row_start = Point::new(row, start);
8365 edits.push((
8366 row_start..row_start,
8367 indent_delta.chars().collect::<String>(),
8368 ));
8369
8370 // Update this selection's endpoints to reflect the indentation.
8371 if row == selection.start.row {
8372 selection.start.column += indent_delta.len;
8373 }
8374 if row == selection.end.row {
8375 selection.end.column += indent_delta.len;
8376 delta_for_end_row = indent_delta.len;
8377 }
8378 }
8379
8380 if selection.start.row == selection.end.row {
8381 delta_for_start_row + delta_for_end_row
8382 } else {
8383 delta_for_end_row
8384 }
8385 }
8386
8387 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8388 if self.read_only(cx) {
8389 return;
8390 }
8391 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8392 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8393 let selections = self.selections.all::<Point>(cx);
8394 let mut deletion_ranges = Vec::new();
8395 let mut last_outdent = None;
8396 {
8397 let buffer = self.buffer.read(cx);
8398 let snapshot = buffer.snapshot(cx);
8399 for selection in &selections {
8400 let settings = buffer.language_settings_at(selection.start, cx);
8401 let tab_size = settings.tab_size.get();
8402 let mut rows = selection.spanned_rows(false, &display_map);
8403
8404 // Avoid re-outdenting a row that has already been outdented by a
8405 // previous selection.
8406 if let Some(last_row) = last_outdent {
8407 if last_row == rows.start {
8408 rows.start = rows.start.next_row();
8409 }
8410 }
8411 let has_multiple_rows = rows.len() > 1;
8412 for row in rows.iter_rows() {
8413 let indent_size = snapshot.indent_size_for_line(row);
8414 if indent_size.len > 0 {
8415 let deletion_len = match indent_size.kind {
8416 IndentKind::Space => {
8417 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8418 if columns_to_prev_tab_stop == 0 {
8419 tab_size
8420 } else {
8421 columns_to_prev_tab_stop
8422 }
8423 }
8424 IndentKind::Tab => 1,
8425 };
8426 let start = if has_multiple_rows
8427 || deletion_len > selection.start.column
8428 || indent_size.len < selection.start.column
8429 {
8430 0
8431 } else {
8432 selection.start.column - deletion_len
8433 };
8434 deletion_ranges.push(
8435 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8436 );
8437 last_outdent = Some(row);
8438 }
8439 }
8440 }
8441 }
8442
8443 self.transact(window, cx, |this, window, cx| {
8444 this.buffer.update(cx, |buffer, cx| {
8445 let empty_str: Arc<str> = Arc::default();
8446 buffer.edit(
8447 deletion_ranges
8448 .into_iter()
8449 .map(|range| (range, empty_str.clone())),
8450 None,
8451 cx,
8452 );
8453 });
8454 let selections = this.selections.all::<usize>(cx);
8455 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8456 s.select(selections)
8457 });
8458 });
8459 }
8460
8461 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8462 if self.read_only(cx) {
8463 return;
8464 }
8465 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8466 let selections = self
8467 .selections
8468 .all::<usize>(cx)
8469 .into_iter()
8470 .map(|s| s.range());
8471
8472 self.transact(window, cx, |this, window, cx| {
8473 this.buffer.update(cx, |buffer, cx| {
8474 buffer.autoindent_ranges(selections, cx);
8475 });
8476 let selections = this.selections.all::<usize>(cx);
8477 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8478 s.select(selections)
8479 });
8480 });
8481 }
8482
8483 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8484 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8485 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8486 let selections = self.selections.all::<Point>(cx);
8487
8488 let mut new_cursors = Vec::new();
8489 let mut edit_ranges = Vec::new();
8490 let mut selections = selections.iter().peekable();
8491 while let Some(selection) = selections.next() {
8492 let mut rows = selection.spanned_rows(false, &display_map);
8493 let goal_display_column = selection.head().to_display_point(&display_map).column();
8494
8495 // Accumulate contiguous regions of rows that we want to delete.
8496 while let Some(next_selection) = selections.peek() {
8497 let next_rows = next_selection.spanned_rows(false, &display_map);
8498 if next_rows.start <= rows.end {
8499 rows.end = next_rows.end;
8500 selections.next().unwrap();
8501 } else {
8502 break;
8503 }
8504 }
8505
8506 let buffer = &display_map.buffer_snapshot;
8507 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8508 let edit_end;
8509 let cursor_buffer_row;
8510 if buffer.max_point().row >= rows.end.0 {
8511 // If there's a line after the range, delete the \n from the end of the row range
8512 // and position the cursor on the next line.
8513 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8514 cursor_buffer_row = rows.end;
8515 } else {
8516 // If there isn't a line after the range, delete the \n from the line before the
8517 // start of the row range and position the cursor there.
8518 edit_start = edit_start.saturating_sub(1);
8519 edit_end = buffer.len();
8520 cursor_buffer_row = rows.start.previous_row();
8521 }
8522
8523 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8524 *cursor.column_mut() =
8525 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8526
8527 new_cursors.push((
8528 selection.id,
8529 buffer.anchor_after(cursor.to_point(&display_map)),
8530 ));
8531 edit_ranges.push(edit_start..edit_end);
8532 }
8533
8534 self.transact(window, cx, |this, window, cx| {
8535 let buffer = this.buffer.update(cx, |buffer, cx| {
8536 let empty_str: Arc<str> = Arc::default();
8537 buffer.edit(
8538 edit_ranges
8539 .into_iter()
8540 .map(|range| (range, empty_str.clone())),
8541 None,
8542 cx,
8543 );
8544 buffer.snapshot(cx)
8545 });
8546 let new_selections = new_cursors
8547 .into_iter()
8548 .map(|(id, cursor)| {
8549 let cursor = cursor.to_point(&buffer);
8550 Selection {
8551 id,
8552 start: cursor,
8553 end: cursor,
8554 reversed: false,
8555 goal: SelectionGoal::None,
8556 }
8557 })
8558 .collect();
8559
8560 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8561 s.select(new_selections);
8562 });
8563 });
8564 }
8565
8566 pub fn join_lines_impl(
8567 &mut self,
8568 insert_whitespace: bool,
8569 window: &mut Window,
8570 cx: &mut Context<Self>,
8571 ) {
8572 if self.read_only(cx) {
8573 return;
8574 }
8575 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8576 for selection in self.selections.all::<Point>(cx) {
8577 let start = MultiBufferRow(selection.start.row);
8578 // Treat single line selections as if they include the next line. Otherwise this action
8579 // would do nothing for single line selections individual cursors.
8580 let end = if selection.start.row == selection.end.row {
8581 MultiBufferRow(selection.start.row + 1)
8582 } else {
8583 MultiBufferRow(selection.end.row)
8584 };
8585
8586 if let Some(last_row_range) = row_ranges.last_mut() {
8587 if start <= last_row_range.end {
8588 last_row_range.end = end;
8589 continue;
8590 }
8591 }
8592 row_ranges.push(start..end);
8593 }
8594
8595 let snapshot = self.buffer.read(cx).snapshot(cx);
8596 let mut cursor_positions = Vec::new();
8597 for row_range in &row_ranges {
8598 let anchor = snapshot.anchor_before(Point::new(
8599 row_range.end.previous_row().0,
8600 snapshot.line_len(row_range.end.previous_row()),
8601 ));
8602 cursor_positions.push(anchor..anchor);
8603 }
8604
8605 self.transact(window, cx, |this, window, cx| {
8606 for row_range in row_ranges.into_iter().rev() {
8607 for row in row_range.iter_rows().rev() {
8608 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8609 let next_line_row = row.next_row();
8610 let indent = snapshot.indent_size_for_line(next_line_row);
8611 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8612
8613 let replace =
8614 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8615 " "
8616 } else {
8617 ""
8618 };
8619
8620 this.buffer.update(cx, |buffer, cx| {
8621 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8622 });
8623 }
8624 }
8625
8626 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8627 s.select_anchor_ranges(cursor_positions)
8628 });
8629 });
8630 }
8631
8632 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8633 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8634 self.join_lines_impl(true, window, cx);
8635 }
8636
8637 pub fn sort_lines_case_sensitive(
8638 &mut self,
8639 _: &SortLinesCaseSensitive,
8640 window: &mut Window,
8641 cx: &mut Context<Self>,
8642 ) {
8643 self.manipulate_lines(window, cx, |lines| lines.sort())
8644 }
8645
8646 pub fn sort_lines_case_insensitive(
8647 &mut self,
8648 _: &SortLinesCaseInsensitive,
8649 window: &mut Window,
8650 cx: &mut Context<Self>,
8651 ) {
8652 self.manipulate_lines(window, cx, |lines| {
8653 lines.sort_by_key(|line| line.to_lowercase())
8654 })
8655 }
8656
8657 pub fn unique_lines_case_insensitive(
8658 &mut self,
8659 _: &UniqueLinesCaseInsensitive,
8660 window: &mut Window,
8661 cx: &mut Context<Self>,
8662 ) {
8663 self.manipulate_lines(window, cx, |lines| {
8664 let mut seen = HashSet::default();
8665 lines.retain(|line| seen.insert(line.to_lowercase()));
8666 })
8667 }
8668
8669 pub fn unique_lines_case_sensitive(
8670 &mut self,
8671 _: &UniqueLinesCaseSensitive,
8672 window: &mut Window,
8673 cx: &mut Context<Self>,
8674 ) {
8675 self.manipulate_lines(window, cx, |lines| {
8676 let mut seen = HashSet::default();
8677 lines.retain(|line| seen.insert(*line));
8678 })
8679 }
8680
8681 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8682 let Some(project) = self.project.clone() else {
8683 return;
8684 };
8685 self.reload(project, window, cx)
8686 .detach_and_notify_err(window, cx);
8687 }
8688
8689 pub fn restore_file(
8690 &mut self,
8691 _: &::git::RestoreFile,
8692 window: &mut Window,
8693 cx: &mut Context<Self>,
8694 ) {
8695 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8696 let mut buffer_ids = HashSet::default();
8697 let snapshot = self.buffer().read(cx).snapshot(cx);
8698 for selection in self.selections.all::<usize>(cx) {
8699 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8700 }
8701
8702 let buffer = self.buffer().read(cx);
8703 let ranges = buffer_ids
8704 .into_iter()
8705 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8706 .collect::<Vec<_>>();
8707
8708 self.restore_hunks_in_ranges(ranges, window, cx);
8709 }
8710
8711 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8712 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8713 let selections = self
8714 .selections
8715 .all(cx)
8716 .into_iter()
8717 .map(|s| s.range())
8718 .collect();
8719 self.restore_hunks_in_ranges(selections, window, cx);
8720 }
8721
8722 pub fn restore_hunks_in_ranges(
8723 &mut self,
8724 ranges: Vec<Range<Point>>,
8725 window: &mut Window,
8726 cx: &mut Context<Editor>,
8727 ) {
8728 let mut revert_changes = HashMap::default();
8729 let chunk_by = self
8730 .snapshot(window, cx)
8731 .hunks_for_ranges(ranges)
8732 .into_iter()
8733 .chunk_by(|hunk| hunk.buffer_id);
8734 for (buffer_id, hunks) in &chunk_by {
8735 let hunks = hunks.collect::<Vec<_>>();
8736 for hunk in &hunks {
8737 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8738 }
8739 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8740 }
8741 drop(chunk_by);
8742 if !revert_changes.is_empty() {
8743 self.transact(window, cx, |editor, window, cx| {
8744 editor.restore(revert_changes, window, cx);
8745 });
8746 }
8747 }
8748
8749 pub fn open_active_item_in_terminal(
8750 &mut self,
8751 _: &OpenInTerminal,
8752 window: &mut Window,
8753 cx: &mut Context<Self>,
8754 ) {
8755 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8756 let project_path = buffer.read(cx).project_path(cx)?;
8757 let project = self.project.as_ref()?.read(cx);
8758 let entry = project.entry_for_path(&project_path, cx)?;
8759 let parent = match &entry.canonical_path {
8760 Some(canonical_path) => canonical_path.to_path_buf(),
8761 None => project.absolute_path(&project_path, cx)?,
8762 }
8763 .parent()?
8764 .to_path_buf();
8765 Some(parent)
8766 }) {
8767 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8768 }
8769 }
8770
8771 fn set_breakpoint_context_menu(
8772 &mut self,
8773 display_row: DisplayRow,
8774 position: Option<Anchor>,
8775 clicked_point: gpui::Point<Pixels>,
8776 window: &mut Window,
8777 cx: &mut Context<Self>,
8778 ) {
8779 if !cx.has_flag::<Debugger>() {
8780 return;
8781 }
8782 let source = self
8783 .buffer
8784 .read(cx)
8785 .snapshot(cx)
8786 .anchor_before(Point::new(display_row.0, 0u32));
8787
8788 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8789
8790 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8791 self,
8792 source,
8793 clicked_point,
8794 context_menu,
8795 window,
8796 cx,
8797 );
8798 }
8799
8800 fn add_edit_breakpoint_block(
8801 &mut self,
8802 anchor: Anchor,
8803 breakpoint: &Breakpoint,
8804 edit_action: BreakpointPromptEditAction,
8805 window: &mut Window,
8806 cx: &mut Context<Self>,
8807 ) {
8808 let weak_editor = cx.weak_entity();
8809 let bp_prompt = cx.new(|cx| {
8810 BreakpointPromptEditor::new(
8811 weak_editor,
8812 anchor,
8813 breakpoint.clone(),
8814 edit_action,
8815 window,
8816 cx,
8817 )
8818 });
8819
8820 let height = bp_prompt.update(cx, |this, cx| {
8821 this.prompt
8822 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8823 });
8824 let cloned_prompt = bp_prompt.clone();
8825 let blocks = vec![BlockProperties {
8826 style: BlockStyle::Sticky,
8827 placement: BlockPlacement::Above(anchor),
8828 height: Some(height),
8829 render: Arc::new(move |cx| {
8830 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8831 cloned_prompt.clone().into_any_element()
8832 }),
8833 priority: 0,
8834 }];
8835
8836 let focus_handle = bp_prompt.focus_handle(cx);
8837 window.focus(&focus_handle);
8838
8839 let block_ids = self.insert_blocks(blocks, None, cx);
8840 bp_prompt.update(cx, |prompt, _| {
8841 prompt.add_block_ids(block_ids);
8842 });
8843 }
8844
8845 fn breakpoint_at_cursor_head(
8846 &self,
8847 window: &mut Window,
8848 cx: &mut Context<Self>,
8849 ) -> Option<(Anchor, Breakpoint)> {
8850 let cursor_position: Point = self.selections.newest(cx).head();
8851 self.breakpoint_at_row(cursor_position.row, window, cx)
8852 }
8853
8854 pub(crate) fn breakpoint_at_row(
8855 &self,
8856 row: u32,
8857 window: &mut Window,
8858 cx: &mut Context<Self>,
8859 ) -> Option<(Anchor, Breakpoint)> {
8860 let snapshot = self.snapshot(window, cx);
8861 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8862
8863 let project = self.project.clone()?;
8864
8865 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8866 snapshot
8867 .buffer_snapshot
8868 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8869 })?;
8870
8871 let enclosing_excerpt = breakpoint_position.excerpt_id;
8872 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8873 let buffer_snapshot = buffer.read(cx).snapshot();
8874
8875 let row = buffer_snapshot
8876 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8877 .row;
8878
8879 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8880 let anchor_end = snapshot
8881 .buffer_snapshot
8882 .anchor_after(Point::new(row, line_len));
8883
8884 let bp = self
8885 .breakpoint_store
8886 .as_ref()?
8887 .read_with(cx, |breakpoint_store, cx| {
8888 breakpoint_store
8889 .breakpoints(
8890 &buffer,
8891 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8892 &buffer_snapshot,
8893 cx,
8894 )
8895 .next()
8896 .and_then(|(anchor, bp)| {
8897 let breakpoint_row = buffer_snapshot
8898 .summary_for_anchor::<text::PointUtf16>(anchor)
8899 .row;
8900
8901 if breakpoint_row == row {
8902 snapshot
8903 .buffer_snapshot
8904 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8905 .map(|anchor| (anchor, bp.clone()))
8906 } else {
8907 None
8908 }
8909 })
8910 });
8911 bp
8912 }
8913
8914 pub fn edit_log_breakpoint(
8915 &mut self,
8916 _: &EditLogBreakpoint,
8917 window: &mut Window,
8918 cx: &mut Context<Self>,
8919 ) {
8920 let (anchor, bp) = self
8921 .breakpoint_at_cursor_head(window, cx)
8922 .unwrap_or_else(|| {
8923 let cursor_position: Point = self.selections.newest(cx).head();
8924
8925 let breakpoint_position = self
8926 .snapshot(window, cx)
8927 .display_snapshot
8928 .buffer_snapshot
8929 .anchor_after(Point::new(cursor_position.row, 0));
8930
8931 (
8932 breakpoint_position,
8933 Breakpoint {
8934 message: None,
8935 state: BreakpointState::Enabled,
8936 condition: None,
8937 hit_condition: None,
8938 },
8939 )
8940 });
8941
8942 self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
8943 }
8944
8945 pub fn enable_breakpoint(
8946 &mut self,
8947 _: &crate::actions::EnableBreakpoint,
8948 window: &mut Window,
8949 cx: &mut Context<Self>,
8950 ) {
8951 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8952 if breakpoint.is_disabled() {
8953 self.edit_breakpoint_at_anchor(
8954 anchor,
8955 breakpoint,
8956 BreakpointEditAction::InvertState,
8957 cx,
8958 );
8959 }
8960 }
8961 }
8962
8963 pub fn disable_breakpoint(
8964 &mut self,
8965 _: &crate::actions::DisableBreakpoint,
8966 window: &mut Window,
8967 cx: &mut Context<Self>,
8968 ) {
8969 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8970 if breakpoint.is_enabled() {
8971 self.edit_breakpoint_at_anchor(
8972 anchor,
8973 breakpoint,
8974 BreakpointEditAction::InvertState,
8975 cx,
8976 );
8977 }
8978 }
8979 }
8980
8981 pub fn toggle_breakpoint(
8982 &mut self,
8983 _: &crate::actions::ToggleBreakpoint,
8984 window: &mut Window,
8985 cx: &mut Context<Self>,
8986 ) {
8987 let edit_action = BreakpointEditAction::Toggle;
8988
8989 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8990 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8991 } else {
8992 let cursor_position: Point = self.selections.newest(cx).head();
8993
8994 let breakpoint_position = self
8995 .snapshot(window, cx)
8996 .display_snapshot
8997 .buffer_snapshot
8998 .anchor_after(Point::new(cursor_position.row, 0));
8999
9000 self.edit_breakpoint_at_anchor(
9001 breakpoint_position,
9002 Breakpoint::new_standard(),
9003 edit_action,
9004 cx,
9005 );
9006 }
9007 }
9008
9009 pub fn edit_breakpoint_at_anchor(
9010 &mut self,
9011 breakpoint_position: Anchor,
9012 breakpoint: Breakpoint,
9013 edit_action: BreakpointEditAction,
9014 cx: &mut Context<Self>,
9015 ) {
9016 let Some(breakpoint_store) = &self.breakpoint_store else {
9017 return;
9018 };
9019
9020 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9021 if breakpoint_position == Anchor::min() {
9022 self.buffer()
9023 .read(cx)
9024 .excerpt_buffer_ids()
9025 .into_iter()
9026 .next()
9027 } else {
9028 None
9029 }
9030 }) else {
9031 return;
9032 };
9033
9034 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9035 return;
9036 };
9037
9038 breakpoint_store.update(cx, |breakpoint_store, cx| {
9039 breakpoint_store.toggle_breakpoint(
9040 buffer,
9041 (breakpoint_position.text_anchor, breakpoint),
9042 edit_action,
9043 cx,
9044 );
9045 });
9046
9047 cx.notify();
9048 }
9049
9050 #[cfg(any(test, feature = "test-support"))]
9051 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9052 self.breakpoint_store.clone()
9053 }
9054
9055 pub fn prepare_restore_change(
9056 &self,
9057 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9058 hunk: &MultiBufferDiffHunk,
9059 cx: &mut App,
9060 ) -> Option<()> {
9061 if hunk.is_created_file() {
9062 return None;
9063 }
9064 let buffer = self.buffer.read(cx);
9065 let diff = buffer.diff_for(hunk.buffer_id)?;
9066 let buffer = buffer.buffer(hunk.buffer_id)?;
9067 let buffer = buffer.read(cx);
9068 let original_text = diff
9069 .read(cx)
9070 .base_text()
9071 .as_rope()
9072 .slice(hunk.diff_base_byte_range.clone());
9073 let buffer_snapshot = buffer.snapshot();
9074 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9075 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9076 probe
9077 .0
9078 .start
9079 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9080 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9081 }) {
9082 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9083 Some(())
9084 } else {
9085 None
9086 }
9087 }
9088
9089 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9090 self.manipulate_lines(window, cx, |lines| lines.reverse())
9091 }
9092
9093 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9094 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9095 }
9096
9097 fn manipulate_lines<Fn>(
9098 &mut self,
9099 window: &mut Window,
9100 cx: &mut Context<Self>,
9101 mut callback: Fn,
9102 ) where
9103 Fn: FnMut(&mut Vec<&str>),
9104 {
9105 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9106
9107 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9108 let buffer = self.buffer.read(cx).snapshot(cx);
9109
9110 let mut edits = Vec::new();
9111
9112 let selections = self.selections.all::<Point>(cx);
9113 let mut selections = selections.iter().peekable();
9114 let mut contiguous_row_selections = Vec::new();
9115 let mut new_selections = Vec::new();
9116 let mut added_lines = 0;
9117 let mut removed_lines = 0;
9118
9119 while let Some(selection) = selections.next() {
9120 let (start_row, end_row) = consume_contiguous_rows(
9121 &mut contiguous_row_selections,
9122 selection,
9123 &display_map,
9124 &mut selections,
9125 );
9126
9127 let start_point = Point::new(start_row.0, 0);
9128 let end_point = Point::new(
9129 end_row.previous_row().0,
9130 buffer.line_len(end_row.previous_row()),
9131 );
9132 let text = buffer
9133 .text_for_range(start_point..end_point)
9134 .collect::<String>();
9135
9136 let mut lines = text.split('\n').collect_vec();
9137
9138 let lines_before = lines.len();
9139 callback(&mut lines);
9140 let lines_after = lines.len();
9141
9142 edits.push((start_point..end_point, lines.join("\n")));
9143
9144 // Selections must change based on added and removed line count
9145 let start_row =
9146 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9147 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9148 new_selections.push(Selection {
9149 id: selection.id,
9150 start: start_row,
9151 end: end_row,
9152 goal: SelectionGoal::None,
9153 reversed: selection.reversed,
9154 });
9155
9156 if lines_after > lines_before {
9157 added_lines += lines_after - lines_before;
9158 } else if lines_before > lines_after {
9159 removed_lines += lines_before - lines_after;
9160 }
9161 }
9162
9163 self.transact(window, cx, |this, window, cx| {
9164 let buffer = this.buffer.update(cx, |buffer, cx| {
9165 buffer.edit(edits, None, cx);
9166 buffer.snapshot(cx)
9167 });
9168
9169 // Recalculate offsets on newly edited buffer
9170 let new_selections = new_selections
9171 .iter()
9172 .map(|s| {
9173 let start_point = Point::new(s.start.0, 0);
9174 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9175 Selection {
9176 id: s.id,
9177 start: buffer.point_to_offset(start_point),
9178 end: buffer.point_to_offset(end_point),
9179 goal: s.goal,
9180 reversed: s.reversed,
9181 }
9182 })
9183 .collect();
9184
9185 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9186 s.select(new_selections);
9187 });
9188
9189 this.request_autoscroll(Autoscroll::fit(), cx);
9190 });
9191 }
9192
9193 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9194 self.manipulate_text(window, cx, |text| {
9195 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9196 if has_upper_case_characters {
9197 text.to_lowercase()
9198 } else {
9199 text.to_uppercase()
9200 }
9201 })
9202 }
9203
9204 pub fn convert_to_upper_case(
9205 &mut self,
9206 _: &ConvertToUpperCase,
9207 window: &mut Window,
9208 cx: &mut Context<Self>,
9209 ) {
9210 self.manipulate_text(window, cx, |text| text.to_uppercase())
9211 }
9212
9213 pub fn convert_to_lower_case(
9214 &mut self,
9215 _: &ConvertToLowerCase,
9216 window: &mut Window,
9217 cx: &mut Context<Self>,
9218 ) {
9219 self.manipulate_text(window, cx, |text| text.to_lowercase())
9220 }
9221
9222 pub fn convert_to_title_case(
9223 &mut self,
9224 _: &ConvertToTitleCase,
9225 window: &mut Window,
9226 cx: &mut Context<Self>,
9227 ) {
9228 self.manipulate_text(window, cx, |text| {
9229 text.split('\n')
9230 .map(|line| line.to_case(Case::Title))
9231 .join("\n")
9232 })
9233 }
9234
9235 pub fn convert_to_snake_case(
9236 &mut self,
9237 _: &ConvertToSnakeCase,
9238 window: &mut Window,
9239 cx: &mut Context<Self>,
9240 ) {
9241 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9242 }
9243
9244 pub fn convert_to_kebab_case(
9245 &mut self,
9246 _: &ConvertToKebabCase,
9247 window: &mut Window,
9248 cx: &mut Context<Self>,
9249 ) {
9250 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9251 }
9252
9253 pub fn convert_to_upper_camel_case(
9254 &mut self,
9255 _: &ConvertToUpperCamelCase,
9256 window: &mut Window,
9257 cx: &mut Context<Self>,
9258 ) {
9259 self.manipulate_text(window, cx, |text| {
9260 text.split('\n')
9261 .map(|line| line.to_case(Case::UpperCamel))
9262 .join("\n")
9263 })
9264 }
9265
9266 pub fn convert_to_lower_camel_case(
9267 &mut self,
9268 _: &ConvertToLowerCamelCase,
9269 window: &mut Window,
9270 cx: &mut Context<Self>,
9271 ) {
9272 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9273 }
9274
9275 pub fn convert_to_opposite_case(
9276 &mut self,
9277 _: &ConvertToOppositeCase,
9278 window: &mut Window,
9279 cx: &mut Context<Self>,
9280 ) {
9281 self.manipulate_text(window, cx, |text| {
9282 text.chars()
9283 .fold(String::with_capacity(text.len()), |mut t, c| {
9284 if c.is_uppercase() {
9285 t.extend(c.to_lowercase());
9286 } else {
9287 t.extend(c.to_uppercase());
9288 }
9289 t
9290 })
9291 })
9292 }
9293
9294 pub fn convert_to_rot13(
9295 &mut self,
9296 _: &ConvertToRot13,
9297 window: &mut Window,
9298 cx: &mut Context<Self>,
9299 ) {
9300 self.manipulate_text(window, cx, |text| {
9301 text.chars()
9302 .map(|c| match c {
9303 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9304 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9305 _ => c,
9306 })
9307 .collect()
9308 })
9309 }
9310
9311 pub fn convert_to_rot47(
9312 &mut self,
9313 _: &ConvertToRot47,
9314 window: &mut Window,
9315 cx: &mut Context<Self>,
9316 ) {
9317 self.manipulate_text(window, cx, |text| {
9318 text.chars()
9319 .map(|c| {
9320 let code_point = c as u32;
9321 if code_point >= 33 && code_point <= 126 {
9322 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9323 }
9324 c
9325 })
9326 .collect()
9327 })
9328 }
9329
9330 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9331 where
9332 Fn: FnMut(&str) -> String,
9333 {
9334 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9335 let buffer = self.buffer.read(cx).snapshot(cx);
9336
9337 let mut new_selections = Vec::new();
9338 let mut edits = Vec::new();
9339 let mut selection_adjustment = 0i32;
9340
9341 for selection in self.selections.all::<usize>(cx) {
9342 let selection_is_empty = selection.is_empty();
9343
9344 let (start, end) = if selection_is_empty {
9345 let word_range = movement::surrounding_word(
9346 &display_map,
9347 selection.start.to_display_point(&display_map),
9348 );
9349 let start = word_range.start.to_offset(&display_map, Bias::Left);
9350 let end = word_range.end.to_offset(&display_map, Bias::Left);
9351 (start, end)
9352 } else {
9353 (selection.start, selection.end)
9354 };
9355
9356 let text = buffer.text_for_range(start..end).collect::<String>();
9357 let old_length = text.len() as i32;
9358 let text = callback(&text);
9359
9360 new_selections.push(Selection {
9361 start: (start as i32 - selection_adjustment) as usize,
9362 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9363 goal: SelectionGoal::None,
9364 ..selection
9365 });
9366
9367 selection_adjustment += old_length - text.len() as i32;
9368
9369 edits.push((start..end, text));
9370 }
9371
9372 self.transact(window, cx, |this, window, cx| {
9373 this.buffer.update(cx, |buffer, cx| {
9374 buffer.edit(edits, None, cx);
9375 });
9376
9377 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9378 s.select(new_selections);
9379 });
9380
9381 this.request_autoscroll(Autoscroll::fit(), cx);
9382 });
9383 }
9384
9385 pub fn duplicate(
9386 &mut self,
9387 upwards: bool,
9388 whole_lines: bool,
9389 window: &mut Window,
9390 cx: &mut Context<Self>,
9391 ) {
9392 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9393
9394 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9395 let buffer = &display_map.buffer_snapshot;
9396 let selections = self.selections.all::<Point>(cx);
9397
9398 let mut edits = Vec::new();
9399 let mut selections_iter = selections.iter().peekable();
9400 while let Some(selection) = selections_iter.next() {
9401 let mut rows = selection.spanned_rows(false, &display_map);
9402 // duplicate line-wise
9403 if whole_lines || selection.start == selection.end {
9404 // Avoid duplicating the same lines twice.
9405 while let Some(next_selection) = selections_iter.peek() {
9406 let next_rows = next_selection.spanned_rows(false, &display_map);
9407 if next_rows.start < rows.end {
9408 rows.end = next_rows.end;
9409 selections_iter.next().unwrap();
9410 } else {
9411 break;
9412 }
9413 }
9414
9415 // Copy the text from the selected row region and splice it either at the start
9416 // or end of the region.
9417 let start = Point::new(rows.start.0, 0);
9418 let end = Point::new(
9419 rows.end.previous_row().0,
9420 buffer.line_len(rows.end.previous_row()),
9421 );
9422 let text = buffer
9423 .text_for_range(start..end)
9424 .chain(Some("\n"))
9425 .collect::<String>();
9426 let insert_location = if upwards {
9427 Point::new(rows.end.0, 0)
9428 } else {
9429 start
9430 };
9431 edits.push((insert_location..insert_location, text));
9432 } else {
9433 // duplicate character-wise
9434 let start = selection.start;
9435 let end = selection.end;
9436 let text = buffer.text_for_range(start..end).collect::<String>();
9437 edits.push((selection.end..selection.end, text));
9438 }
9439 }
9440
9441 self.transact(window, cx, |this, _, cx| {
9442 this.buffer.update(cx, |buffer, cx| {
9443 buffer.edit(edits, None, cx);
9444 });
9445
9446 this.request_autoscroll(Autoscroll::fit(), cx);
9447 });
9448 }
9449
9450 pub fn duplicate_line_up(
9451 &mut self,
9452 _: &DuplicateLineUp,
9453 window: &mut Window,
9454 cx: &mut Context<Self>,
9455 ) {
9456 self.duplicate(true, true, window, cx);
9457 }
9458
9459 pub fn duplicate_line_down(
9460 &mut self,
9461 _: &DuplicateLineDown,
9462 window: &mut Window,
9463 cx: &mut Context<Self>,
9464 ) {
9465 self.duplicate(false, true, window, cx);
9466 }
9467
9468 pub fn duplicate_selection(
9469 &mut self,
9470 _: &DuplicateSelection,
9471 window: &mut Window,
9472 cx: &mut Context<Self>,
9473 ) {
9474 self.duplicate(false, false, window, cx);
9475 }
9476
9477 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9478 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9479
9480 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9481 let buffer = self.buffer.read(cx).snapshot(cx);
9482
9483 let mut edits = Vec::new();
9484 let mut unfold_ranges = Vec::new();
9485 let mut refold_creases = Vec::new();
9486
9487 let selections = self.selections.all::<Point>(cx);
9488 let mut selections = selections.iter().peekable();
9489 let mut contiguous_row_selections = Vec::new();
9490 let mut new_selections = Vec::new();
9491
9492 while let Some(selection) = selections.next() {
9493 // Find all the selections that span a contiguous row range
9494 let (start_row, end_row) = consume_contiguous_rows(
9495 &mut contiguous_row_selections,
9496 selection,
9497 &display_map,
9498 &mut selections,
9499 );
9500
9501 // Move the text spanned by the row range to be before the line preceding the row range
9502 if start_row.0 > 0 {
9503 let range_to_move = Point::new(
9504 start_row.previous_row().0,
9505 buffer.line_len(start_row.previous_row()),
9506 )
9507 ..Point::new(
9508 end_row.previous_row().0,
9509 buffer.line_len(end_row.previous_row()),
9510 );
9511 let insertion_point = display_map
9512 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9513 .0;
9514
9515 // Don't move lines across excerpts
9516 if buffer
9517 .excerpt_containing(insertion_point..range_to_move.end)
9518 .is_some()
9519 {
9520 let text = buffer
9521 .text_for_range(range_to_move.clone())
9522 .flat_map(|s| s.chars())
9523 .skip(1)
9524 .chain(['\n'])
9525 .collect::<String>();
9526
9527 edits.push((
9528 buffer.anchor_after(range_to_move.start)
9529 ..buffer.anchor_before(range_to_move.end),
9530 String::new(),
9531 ));
9532 let insertion_anchor = buffer.anchor_after(insertion_point);
9533 edits.push((insertion_anchor..insertion_anchor, text));
9534
9535 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9536
9537 // Move selections up
9538 new_selections.extend(contiguous_row_selections.drain(..).map(
9539 |mut selection| {
9540 selection.start.row -= row_delta;
9541 selection.end.row -= row_delta;
9542 selection
9543 },
9544 ));
9545
9546 // Move folds up
9547 unfold_ranges.push(range_to_move.clone());
9548 for fold in display_map.folds_in_range(
9549 buffer.anchor_before(range_to_move.start)
9550 ..buffer.anchor_after(range_to_move.end),
9551 ) {
9552 let mut start = fold.range.start.to_point(&buffer);
9553 let mut end = fold.range.end.to_point(&buffer);
9554 start.row -= row_delta;
9555 end.row -= row_delta;
9556 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9557 }
9558 }
9559 }
9560
9561 // If we didn't move line(s), preserve the existing selections
9562 new_selections.append(&mut contiguous_row_selections);
9563 }
9564
9565 self.transact(window, cx, |this, window, cx| {
9566 this.unfold_ranges(&unfold_ranges, true, true, cx);
9567 this.buffer.update(cx, |buffer, cx| {
9568 for (range, text) in edits {
9569 buffer.edit([(range, text)], None, cx);
9570 }
9571 });
9572 this.fold_creases(refold_creases, true, window, cx);
9573 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9574 s.select(new_selections);
9575 })
9576 });
9577 }
9578
9579 pub fn move_line_down(
9580 &mut self,
9581 _: &MoveLineDown,
9582 window: &mut Window,
9583 cx: &mut Context<Self>,
9584 ) {
9585 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9586
9587 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9588 let buffer = self.buffer.read(cx).snapshot(cx);
9589
9590 let mut edits = Vec::new();
9591 let mut unfold_ranges = Vec::new();
9592 let mut refold_creases = Vec::new();
9593
9594 let selections = self.selections.all::<Point>(cx);
9595 let mut selections = selections.iter().peekable();
9596 let mut contiguous_row_selections = Vec::new();
9597 let mut new_selections = Vec::new();
9598
9599 while let Some(selection) = selections.next() {
9600 // Find all the selections that span a contiguous row range
9601 let (start_row, end_row) = consume_contiguous_rows(
9602 &mut contiguous_row_selections,
9603 selection,
9604 &display_map,
9605 &mut selections,
9606 );
9607
9608 // Move the text spanned by the row range to be after the last line of the row range
9609 if end_row.0 <= buffer.max_point().row {
9610 let range_to_move =
9611 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9612 let insertion_point = display_map
9613 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9614 .0;
9615
9616 // Don't move lines across excerpt boundaries
9617 if buffer
9618 .excerpt_containing(range_to_move.start..insertion_point)
9619 .is_some()
9620 {
9621 let mut text = String::from("\n");
9622 text.extend(buffer.text_for_range(range_to_move.clone()));
9623 text.pop(); // Drop trailing newline
9624 edits.push((
9625 buffer.anchor_after(range_to_move.start)
9626 ..buffer.anchor_before(range_to_move.end),
9627 String::new(),
9628 ));
9629 let insertion_anchor = buffer.anchor_after(insertion_point);
9630 edits.push((insertion_anchor..insertion_anchor, text));
9631
9632 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9633
9634 // Move selections down
9635 new_selections.extend(contiguous_row_selections.drain(..).map(
9636 |mut selection| {
9637 selection.start.row += row_delta;
9638 selection.end.row += row_delta;
9639 selection
9640 },
9641 ));
9642
9643 // Move folds down
9644 unfold_ranges.push(range_to_move.clone());
9645 for fold in display_map.folds_in_range(
9646 buffer.anchor_before(range_to_move.start)
9647 ..buffer.anchor_after(range_to_move.end),
9648 ) {
9649 let mut start = fold.range.start.to_point(&buffer);
9650 let mut end = fold.range.end.to_point(&buffer);
9651 start.row += row_delta;
9652 end.row += row_delta;
9653 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9654 }
9655 }
9656 }
9657
9658 // If we didn't move line(s), preserve the existing selections
9659 new_selections.append(&mut contiguous_row_selections);
9660 }
9661
9662 self.transact(window, cx, |this, window, cx| {
9663 this.unfold_ranges(&unfold_ranges, true, true, cx);
9664 this.buffer.update(cx, |buffer, cx| {
9665 for (range, text) in edits {
9666 buffer.edit([(range, text)], None, cx);
9667 }
9668 });
9669 this.fold_creases(refold_creases, true, window, cx);
9670 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9671 s.select(new_selections)
9672 });
9673 });
9674 }
9675
9676 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9677 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9678 let text_layout_details = &self.text_layout_details(window);
9679 self.transact(window, cx, |this, window, cx| {
9680 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9681 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9682 s.move_with(|display_map, selection| {
9683 if !selection.is_empty() {
9684 return;
9685 }
9686
9687 let mut head = selection.head();
9688 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9689 if head.column() == display_map.line_len(head.row()) {
9690 transpose_offset = display_map
9691 .buffer_snapshot
9692 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9693 }
9694
9695 if transpose_offset == 0 {
9696 return;
9697 }
9698
9699 *head.column_mut() += 1;
9700 head = display_map.clip_point(head, Bias::Right);
9701 let goal = SelectionGoal::HorizontalPosition(
9702 display_map
9703 .x_for_display_point(head, text_layout_details)
9704 .into(),
9705 );
9706 selection.collapse_to(head, goal);
9707
9708 let transpose_start = display_map
9709 .buffer_snapshot
9710 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9711 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9712 let transpose_end = display_map
9713 .buffer_snapshot
9714 .clip_offset(transpose_offset + 1, Bias::Right);
9715 if let Some(ch) =
9716 display_map.buffer_snapshot.chars_at(transpose_start).next()
9717 {
9718 edits.push((transpose_start..transpose_offset, String::new()));
9719 edits.push((transpose_end..transpose_end, ch.to_string()));
9720 }
9721 }
9722 });
9723 edits
9724 });
9725 this.buffer
9726 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9727 let selections = this.selections.all::<usize>(cx);
9728 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9729 s.select(selections);
9730 });
9731 });
9732 }
9733
9734 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9735 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9736 self.rewrap_impl(RewrapOptions::default(), cx)
9737 }
9738
9739 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9740 let buffer = self.buffer.read(cx).snapshot(cx);
9741 let selections = self.selections.all::<Point>(cx);
9742 let mut selections = selections.iter().peekable();
9743
9744 let mut edits = Vec::new();
9745 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9746
9747 while let Some(selection) = selections.next() {
9748 let mut start_row = selection.start.row;
9749 let mut end_row = selection.end.row;
9750
9751 // Skip selections that overlap with a range that has already been rewrapped.
9752 let selection_range = start_row..end_row;
9753 if rewrapped_row_ranges
9754 .iter()
9755 .any(|range| range.overlaps(&selection_range))
9756 {
9757 continue;
9758 }
9759
9760 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9761
9762 // Since not all lines in the selection may be at the same indent
9763 // level, choose the indent size that is the most common between all
9764 // of the lines.
9765 //
9766 // If there is a tie, we use the deepest indent.
9767 let (indent_size, indent_end) = {
9768 let mut indent_size_occurrences = HashMap::default();
9769 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9770
9771 for row in start_row..=end_row {
9772 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9773 rows_by_indent_size.entry(indent).or_default().push(row);
9774 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9775 }
9776
9777 let indent_size = indent_size_occurrences
9778 .into_iter()
9779 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9780 .map(|(indent, _)| indent)
9781 .unwrap_or_default();
9782 let row = rows_by_indent_size[&indent_size][0];
9783 let indent_end = Point::new(row, indent_size.len);
9784
9785 (indent_size, indent_end)
9786 };
9787
9788 let mut line_prefix = indent_size.chars().collect::<String>();
9789
9790 let mut inside_comment = false;
9791 if let Some(comment_prefix) =
9792 buffer
9793 .language_scope_at(selection.head())
9794 .and_then(|language| {
9795 language
9796 .line_comment_prefixes()
9797 .iter()
9798 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9799 .cloned()
9800 })
9801 {
9802 line_prefix.push_str(&comment_prefix);
9803 inside_comment = true;
9804 }
9805
9806 let language_settings = buffer.language_settings_at(selection.head(), cx);
9807 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9808 RewrapBehavior::InComments => inside_comment,
9809 RewrapBehavior::InSelections => !selection.is_empty(),
9810 RewrapBehavior::Anywhere => true,
9811 };
9812
9813 let should_rewrap = options.override_language_settings
9814 || allow_rewrap_based_on_language
9815 || self.hard_wrap.is_some();
9816 if !should_rewrap {
9817 continue;
9818 }
9819
9820 if selection.is_empty() {
9821 'expand_upwards: while start_row > 0 {
9822 let prev_row = start_row - 1;
9823 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9824 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9825 {
9826 start_row = prev_row;
9827 } else {
9828 break 'expand_upwards;
9829 }
9830 }
9831
9832 'expand_downwards: while end_row < buffer.max_point().row {
9833 let next_row = end_row + 1;
9834 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9835 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9836 {
9837 end_row = next_row;
9838 } else {
9839 break 'expand_downwards;
9840 }
9841 }
9842 }
9843
9844 let start = Point::new(start_row, 0);
9845 let start_offset = start.to_offset(&buffer);
9846 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9847 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9848 let Some(lines_without_prefixes) = selection_text
9849 .lines()
9850 .map(|line| {
9851 line.strip_prefix(&line_prefix)
9852 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9853 .ok_or_else(|| {
9854 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9855 })
9856 })
9857 .collect::<Result<Vec<_>, _>>()
9858 .log_err()
9859 else {
9860 continue;
9861 };
9862
9863 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9864 buffer
9865 .language_settings_at(Point::new(start_row, 0), cx)
9866 .preferred_line_length as usize
9867 });
9868 let wrapped_text = wrap_with_prefix(
9869 line_prefix,
9870 lines_without_prefixes.join("\n"),
9871 wrap_column,
9872 tab_size,
9873 options.preserve_existing_whitespace,
9874 );
9875
9876 // TODO: should always use char-based diff while still supporting cursor behavior that
9877 // matches vim.
9878 let mut diff_options = DiffOptions::default();
9879 if options.override_language_settings {
9880 diff_options.max_word_diff_len = 0;
9881 diff_options.max_word_diff_line_count = 0;
9882 } else {
9883 diff_options.max_word_diff_len = usize::MAX;
9884 diff_options.max_word_diff_line_count = usize::MAX;
9885 }
9886
9887 for (old_range, new_text) in
9888 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9889 {
9890 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9891 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9892 edits.push((edit_start..edit_end, new_text));
9893 }
9894
9895 rewrapped_row_ranges.push(start_row..=end_row);
9896 }
9897
9898 self.buffer
9899 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9900 }
9901
9902 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9903 let mut text = String::new();
9904 let buffer = self.buffer.read(cx).snapshot(cx);
9905 let mut selections = self.selections.all::<Point>(cx);
9906 let mut clipboard_selections = Vec::with_capacity(selections.len());
9907 {
9908 let max_point = buffer.max_point();
9909 let mut is_first = true;
9910 for selection in &mut selections {
9911 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9912 if is_entire_line {
9913 selection.start = Point::new(selection.start.row, 0);
9914 if !selection.is_empty() && selection.end.column == 0 {
9915 selection.end = cmp::min(max_point, selection.end);
9916 } else {
9917 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9918 }
9919 selection.goal = SelectionGoal::None;
9920 }
9921 if is_first {
9922 is_first = false;
9923 } else {
9924 text += "\n";
9925 }
9926 let mut len = 0;
9927 for chunk in buffer.text_for_range(selection.start..selection.end) {
9928 text.push_str(chunk);
9929 len += chunk.len();
9930 }
9931 clipboard_selections.push(ClipboardSelection {
9932 len,
9933 is_entire_line,
9934 first_line_indent: buffer
9935 .indent_size_for_line(MultiBufferRow(selection.start.row))
9936 .len,
9937 });
9938 }
9939 }
9940
9941 self.transact(window, cx, |this, window, cx| {
9942 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9943 s.select(selections);
9944 });
9945 this.insert("", window, cx);
9946 });
9947 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9948 }
9949
9950 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9951 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9952 let item = self.cut_common(window, cx);
9953 cx.write_to_clipboard(item);
9954 }
9955
9956 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9957 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9958 self.change_selections(None, window, cx, |s| {
9959 s.move_with(|snapshot, sel| {
9960 if sel.is_empty() {
9961 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9962 }
9963 });
9964 });
9965 let item = self.cut_common(window, cx);
9966 cx.set_global(KillRing(item))
9967 }
9968
9969 pub fn kill_ring_yank(
9970 &mut self,
9971 _: &KillRingYank,
9972 window: &mut Window,
9973 cx: &mut Context<Self>,
9974 ) {
9975 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9976 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9977 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9978 (kill_ring.text().to_string(), kill_ring.metadata_json())
9979 } else {
9980 return;
9981 }
9982 } else {
9983 return;
9984 };
9985 self.do_paste(&text, metadata, false, window, cx);
9986 }
9987
9988 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9989 self.do_copy(true, cx);
9990 }
9991
9992 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9993 self.do_copy(false, cx);
9994 }
9995
9996 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9997 let selections = self.selections.all::<Point>(cx);
9998 let buffer = self.buffer.read(cx).read(cx);
9999 let mut text = String::new();
10000
10001 let mut clipboard_selections = Vec::with_capacity(selections.len());
10002 {
10003 let max_point = buffer.max_point();
10004 let mut is_first = true;
10005 for selection in &selections {
10006 let mut start = selection.start;
10007 let mut end = selection.end;
10008 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10009 if is_entire_line {
10010 start = Point::new(start.row, 0);
10011 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10012 }
10013
10014 let mut trimmed_selections = Vec::new();
10015 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10016 let row = MultiBufferRow(start.row);
10017 let first_indent = buffer.indent_size_for_line(row);
10018 if first_indent.len == 0 || start.column > first_indent.len {
10019 trimmed_selections.push(start..end);
10020 } else {
10021 trimmed_selections.push(
10022 Point::new(row.0, first_indent.len)
10023 ..Point::new(row.0, buffer.line_len(row)),
10024 );
10025 for row in start.row + 1..=end.row {
10026 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10027 if row_indent_size.len >= first_indent.len {
10028 trimmed_selections.push(
10029 Point::new(row, first_indent.len)
10030 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10031 );
10032 } else {
10033 trimmed_selections.clear();
10034 trimmed_selections.push(start..end);
10035 break;
10036 }
10037 }
10038 }
10039 } else {
10040 trimmed_selections.push(start..end);
10041 }
10042
10043 for trimmed_range in trimmed_selections {
10044 if is_first {
10045 is_first = false;
10046 } else {
10047 text += "\n";
10048 }
10049 let mut len = 0;
10050 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10051 text.push_str(chunk);
10052 len += chunk.len();
10053 }
10054 clipboard_selections.push(ClipboardSelection {
10055 len,
10056 is_entire_line,
10057 first_line_indent: buffer
10058 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10059 .len,
10060 });
10061 }
10062 }
10063 }
10064
10065 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10066 text,
10067 clipboard_selections,
10068 ));
10069 }
10070
10071 pub fn do_paste(
10072 &mut self,
10073 text: &String,
10074 clipboard_selections: Option<Vec<ClipboardSelection>>,
10075 handle_entire_lines: bool,
10076 window: &mut Window,
10077 cx: &mut Context<Self>,
10078 ) {
10079 if self.read_only(cx) {
10080 return;
10081 }
10082
10083 let clipboard_text = Cow::Borrowed(text);
10084
10085 self.transact(window, cx, |this, window, cx| {
10086 if let Some(mut clipboard_selections) = clipboard_selections {
10087 let old_selections = this.selections.all::<usize>(cx);
10088 let all_selections_were_entire_line =
10089 clipboard_selections.iter().all(|s| s.is_entire_line);
10090 let first_selection_indent_column =
10091 clipboard_selections.first().map(|s| s.first_line_indent);
10092 if clipboard_selections.len() != old_selections.len() {
10093 clipboard_selections.drain(..);
10094 }
10095 let cursor_offset = this.selections.last::<usize>(cx).head();
10096 let mut auto_indent_on_paste = true;
10097
10098 this.buffer.update(cx, |buffer, cx| {
10099 let snapshot = buffer.read(cx);
10100 auto_indent_on_paste = snapshot
10101 .language_settings_at(cursor_offset, cx)
10102 .auto_indent_on_paste;
10103
10104 let mut start_offset = 0;
10105 let mut edits = Vec::new();
10106 let mut original_indent_columns = Vec::new();
10107 for (ix, selection) in old_selections.iter().enumerate() {
10108 let to_insert;
10109 let entire_line;
10110 let original_indent_column;
10111 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10112 let end_offset = start_offset + clipboard_selection.len;
10113 to_insert = &clipboard_text[start_offset..end_offset];
10114 entire_line = clipboard_selection.is_entire_line;
10115 start_offset = end_offset + 1;
10116 original_indent_column = Some(clipboard_selection.first_line_indent);
10117 } else {
10118 to_insert = clipboard_text.as_str();
10119 entire_line = all_selections_were_entire_line;
10120 original_indent_column = first_selection_indent_column
10121 }
10122
10123 // If the corresponding selection was empty when this slice of the
10124 // clipboard text was written, then the entire line containing the
10125 // selection was copied. If this selection is also currently empty,
10126 // then paste the line before the current line of the buffer.
10127 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10128 let column = selection.start.to_point(&snapshot).column as usize;
10129 let line_start = selection.start - column;
10130 line_start..line_start
10131 } else {
10132 selection.range()
10133 };
10134
10135 edits.push((range, to_insert));
10136 original_indent_columns.push(original_indent_column);
10137 }
10138 drop(snapshot);
10139
10140 buffer.edit(
10141 edits,
10142 if auto_indent_on_paste {
10143 Some(AutoindentMode::Block {
10144 original_indent_columns,
10145 })
10146 } else {
10147 None
10148 },
10149 cx,
10150 );
10151 });
10152
10153 let selections = this.selections.all::<usize>(cx);
10154 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10155 s.select(selections)
10156 });
10157 } else {
10158 this.insert(&clipboard_text, window, cx);
10159 }
10160 });
10161 }
10162
10163 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10164 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10165 if let Some(item) = cx.read_from_clipboard() {
10166 let entries = item.entries();
10167
10168 match entries.first() {
10169 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10170 // of all the pasted entries.
10171 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10172 .do_paste(
10173 clipboard_string.text(),
10174 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10175 true,
10176 window,
10177 cx,
10178 ),
10179 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10180 }
10181 }
10182 }
10183
10184 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10185 if self.read_only(cx) {
10186 return;
10187 }
10188
10189 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10190
10191 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10192 if let Some((selections, _)) =
10193 self.selection_history.transaction(transaction_id).cloned()
10194 {
10195 self.change_selections(None, window, cx, |s| {
10196 s.select_anchors(selections.to_vec());
10197 });
10198 } else {
10199 log::error!(
10200 "No entry in selection_history found for undo. \
10201 This may correspond to a bug where undo does not update the selection. \
10202 If this is occurring, please add details to \
10203 https://github.com/zed-industries/zed/issues/22692"
10204 );
10205 }
10206 self.request_autoscroll(Autoscroll::fit(), cx);
10207 self.unmark_text(window, cx);
10208 self.refresh_inline_completion(true, false, window, cx);
10209 cx.emit(EditorEvent::Edited { transaction_id });
10210 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10211 }
10212 }
10213
10214 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10215 if self.read_only(cx) {
10216 return;
10217 }
10218
10219 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10220
10221 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10222 if let Some((_, Some(selections))) =
10223 self.selection_history.transaction(transaction_id).cloned()
10224 {
10225 self.change_selections(None, window, cx, |s| {
10226 s.select_anchors(selections.to_vec());
10227 });
10228 } else {
10229 log::error!(
10230 "No entry in selection_history found for redo. \
10231 This may correspond to a bug where undo does not update the selection. \
10232 If this is occurring, please add details to \
10233 https://github.com/zed-industries/zed/issues/22692"
10234 );
10235 }
10236 self.request_autoscroll(Autoscroll::fit(), cx);
10237 self.unmark_text(window, cx);
10238 self.refresh_inline_completion(true, false, window, cx);
10239 cx.emit(EditorEvent::Edited { transaction_id });
10240 }
10241 }
10242
10243 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10244 self.buffer
10245 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10246 }
10247
10248 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10249 self.buffer
10250 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10251 }
10252
10253 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10254 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10255 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10256 s.move_with(|map, selection| {
10257 let cursor = if selection.is_empty() {
10258 movement::left(map, selection.start)
10259 } else {
10260 selection.start
10261 };
10262 selection.collapse_to(cursor, SelectionGoal::None);
10263 });
10264 })
10265 }
10266
10267 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10268 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10269 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10270 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10271 })
10272 }
10273
10274 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10275 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10276 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10277 s.move_with(|map, selection| {
10278 let cursor = if selection.is_empty() {
10279 movement::right(map, selection.end)
10280 } else {
10281 selection.end
10282 };
10283 selection.collapse_to(cursor, SelectionGoal::None)
10284 });
10285 })
10286 }
10287
10288 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10289 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10290 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10291 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10292 })
10293 }
10294
10295 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10296 if self.take_rename(true, window, cx).is_some() {
10297 return;
10298 }
10299
10300 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10301 cx.propagate();
10302 return;
10303 }
10304
10305 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10306
10307 let text_layout_details = &self.text_layout_details(window);
10308 let selection_count = self.selections.count();
10309 let first_selection = self.selections.first_anchor();
10310
10311 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10312 s.move_with(|map, selection| {
10313 if !selection.is_empty() {
10314 selection.goal = SelectionGoal::None;
10315 }
10316 let (cursor, goal) = movement::up(
10317 map,
10318 selection.start,
10319 selection.goal,
10320 false,
10321 text_layout_details,
10322 );
10323 selection.collapse_to(cursor, goal);
10324 });
10325 });
10326
10327 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10328 {
10329 cx.propagate();
10330 }
10331 }
10332
10333 pub fn move_up_by_lines(
10334 &mut self,
10335 action: &MoveUpByLines,
10336 window: &mut Window,
10337 cx: &mut Context<Self>,
10338 ) {
10339 if self.take_rename(true, window, cx).is_some() {
10340 return;
10341 }
10342
10343 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10344 cx.propagate();
10345 return;
10346 }
10347
10348 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10349
10350 let text_layout_details = &self.text_layout_details(window);
10351
10352 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10353 s.move_with(|map, selection| {
10354 if !selection.is_empty() {
10355 selection.goal = SelectionGoal::None;
10356 }
10357 let (cursor, goal) = movement::up_by_rows(
10358 map,
10359 selection.start,
10360 action.lines,
10361 selection.goal,
10362 false,
10363 text_layout_details,
10364 );
10365 selection.collapse_to(cursor, goal);
10366 });
10367 })
10368 }
10369
10370 pub fn move_down_by_lines(
10371 &mut self,
10372 action: &MoveDownByLines,
10373 window: &mut Window,
10374 cx: &mut Context<Self>,
10375 ) {
10376 if self.take_rename(true, window, cx).is_some() {
10377 return;
10378 }
10379
10380 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10381 cx.propagate();
10382 return;
10383 }
10384
10385 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10386
10387 let text_layout_details = &self.text_layout_details(window);
10388
10389 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10390 s.move_with(|map, selection| {
10391 if !selection.is_empty() {
10392 selection.goal = SelectionGoal::None;
10393 }
10394 let (cursor, goal) = movement::down_by_rows(
10395 map,
10396 selection.start,
10397 action.lines,
10398 selection.goal,
10399 false,
10400 text_layout_details,
10401 );
10402 selection.collapse_to(cursor, goal);
10403 });
10404 })
10405 }
10406
10407 pub fn select_down_by_lines(
10408 &mut self,
10409 action: &SelectDownByLines,
10410 window: &mut Window,
10411 cx: &mut Context<Self>,
10412 ) {
10413 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10414 let text_layout_details = &self.text_layout_details(window);
10415 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10416 s.move_heads_with(|map, head, goal| {
10417 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10418 })
10419 })
10420 }
10421
10422 pub fn select_up_by_lines(
10423 &mut self,
10424 action: &SelectUpByLines,
10425 window: &mut Window,
10426 cx: &mut Context<Self>,
10427 ) {
10428 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10429 let text_layout_details = &self.text_layout_details(window);
10430 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10431 s.move_heads_with(|map, head, goal| {
10432 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10433 })
10434 })
10435 }
10436
10437 pub fn select_page_up(
10438 &mut self,
10439 _: &SelectPageUp,
10440 window: &mut Window,
10441 cx: &mut Context<Self>,
10442 ) {
10443 let Some(row_count) = self.visible_row_count() else {
10444 return;
10445 };
10446
10447 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10448
10449 let text_layout_details = &self.text_layout_details(window);
10450
10451 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10452 s.move_heads_with(|map, head, goal| {
10453 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10454 })
10455 })
10456 }
10457
10458 pub fn move_page_up(
10459 &mut self,
10460 action: &MovePageUp,
10461 window: &mut Window,
10462 cx: &mut Context<Self>,
10463 ) {
10464 if self.take_rename(true, window, cx).is_some() {
10465 return;
10466 }
10467
10468 if self
10469 .context_menu
10470 .borrow_mut()
10471 .as_mut()
10472 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10473 .unwrap_or(false)
10474 {
10475 return;
10476 }
10477
10478 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10479 cx.propagate();
10480 return;
10481 }
10482
10483 let Some(row_count) = self.visible_row_count() else {
10484 return;
10485 };
10486
10487 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10488
10489 let autoscroll = if action.center_cursor {
10490 Autoscroll::center()
10491 } else {
10492 Autoscroll::fit()
10493 };
10494
10495 let text_layout_details = &self.text_layout_details(window);
10496
10497 self.change_selections(Some(autoscroll), window, cx, |s| {
10498 s.move_with(|map, selection| {
10499 if !selection.is_empty() {
10500 selection.goal = SelectionGoal::None;
10501 }
10502 let (cursor, goal) = movement::up_by_rows(
10503 map,
10504 selection.end,
10505 row_count,
10506 selection.goal,
10507 false,
10508 text_layout_details,
10509 );
10510 selection.collapse_to(cursor, goal);
10511 });
10512 });
10513 }
10514
10515 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10516 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10517 let text_layout_details = &self.text_layout_details(window);
10518 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10519 s.move_heads_with(|map, head, goal| {
10520 movement::up(map, head, goal, false, text_layout_details)
10521 })
10522 })
10523 }
10524
10525 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10526 self.take_rename(true, window, cx);
10527
10528 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10529 cx.propagate();
10530 return;
10531 }
10532
10533 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10534
10535 let text_layout_details = &self.text_layout_details(window);
10536 let selection_count = self.selections.count();
10537 let first_selection = self.selections.first_anchor();
10538
10539 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10540 s.move_with(|map, selection| {
10541 if !selection.is_empty() {
10542 selection.goal = SelectionGoal::None;
10543 }
10544 let (cursor, goal) = movement::down(
10545 map,
10546 selection.end,
10547 selection.goal,
10548 false,
10549 text_layout_details,
10550 );
10551 selection.collapse_to(cursor, goal);
10552 });
10553 });
10554
10555 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10556 {
10557 cx.propagate();
10558 }
10559 }
10560
10561 pub fn select_page_down(
10562 &mut self,
10563 _: &SelectPageDown,
10564 window: &mut Window,
10565 cx: &mut Context<Self>,
10566 ) {
10567 let Some(row_count) = self.visible_row_count() else {
10568 return;
10569 };
10570
10571 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10572
10573 let text_layout_details = &self.text_layout_details(window);
10574
10575 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10576 s.move_heads_with(|map, head, goal| {
10577 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10578 })
10579 })
10580 }
10581
10582 pub fn move_page_down(
10583 &mut self,
10584 action: &MovePageDown,
10585 window: &mut Window,
10586 cx: &mut Context<Self>,
10587 ) {
10588 if self.take_rename(true, window, cx).is_some() {
10589 return;
10590 }
10591
10592 if self
10593 .context_menu
10594 .borrow_mut()
10595 .as_mut()
10596 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10597 .unwrap_or(false)
10598 {
10599 return;
10600 }
10601
10602 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10603 cx.propagate();
10604 return;
10605 }
10606
10607 let Some(row_count) = self.visible_row_count() else {
10608 return;
10609 };
10610
10611 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10612
10613 let autoscroll = if action.center_cursor {
10614 Autoscroll::center()
10615 } else {
10616 Autoscroll::fit()
10617 };
10618
10619 let text_layout_details = &self.text_layout_details(window);
10620 self.change_selections(Some(autoscroll), window, cx, |s| {
10621 s.move_with(|map, selection| {
10622 if !selection.is_empty() {
10623 selection.goal = SelectionGoal::None;
10624 }
10625 let (cursor, goal) = movement::down_by_rows(
10626 map,
10627 selection.end,
10628 row_count,
10629 selection.goal,
10630 false,
10631 text_layout_details,
10632 );
10633 selection.collapse_to(cursor, goal);
10634 });
10635 });
10636 }
10637
10638 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10639 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10640 let text_layout_details = &self.text_layout_details(window);
10641 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10642 s.move_heads_with(|map, head, goal| {
10643 movement::down(map, head, goal, false, text_layout_details)
10644 })
10645 });
10646 }
10647
10648 pub fn context_menu_first(
10649 &mut self,
10650 _: &ContextMenuFirst,
10651 _window: &mut Window,
10652 cx: &mut Context<Self>,
10653 ) {
10654 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10655 context_menu.select_first(self.completion_provider.as_deref(), cx);
10656 }
10657 }
10658
10659 pub fn context_menu_prev(
10660 &mut self,
10661 _: &ContextMenuPrevious,
10662 _window: &mut Window,
10663 cx: &mut Context<Self>,
10664 ) {
10665 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10666 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10667 }
10668 }
10669
10670 pub fn context_menu_next(
10671 &mut self,
10672 _: &ContextMenuNext,
10673 _window: &mut Window,
10674 cx: &mut Context<Self>,
10675 ) {
10676 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10677 context_menu.select_next(self.completion_provider.as_deref(), cx);
10678 }
10679 }
10680
10681 pub fn context_menu_last(
10682 &mut self,
10683 _: &ContextMenuLast,
10684 _window: &mut Window,
10685 cx: &mut Context<Self>,
10686 ) {
10687 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10688 context_menu.select_last(self.completion_provider.as_deref(), cx);
10689 }
10690 }
10691
10692 pub fn move_to_previous_word_start(
10693 &mut self,
10694 _: &MoveToPreviousWordStart,
10695 window: &mut Window,
10696 cx: &mut Context<Self>,
10697 ) {
10698 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10699 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10700 s.move_cursors_with(|map, head, _| {
10701 (
10702 movement::previous_word_start(map, head),
10703 SelectionGoal::None,
10704 )
10705 });
10706 })
10707 }
10708
10709 pub fn move_to_previous_subword_start(
10710 &mut self,
10711 _: &MoveToPreviousSubwordStart,
10712 window: &mut Window,
10713 cx: &mut Context<Self>,
10714 ) {
10715 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10716 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10717 s.move_cursors_with(|map, head, _| {
10718 (
10719 movement::previous_subword_start(map, head),
10720 SelectionGoal::None,
10721 )
10722 });
10723 })
10724 }
10725
10726 pub fn select_to_previous_word_start(
10727 &mut self,
10728 _: &SelectToPreviousWordStart,
10729 window: &mut Window,
10730 cx: &mut Context<Self>,
10731 ) {
10732 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10733 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10734 s.move_heads_with(|map, head, _| {
10735 (
10736 movement::previous_word_start(map, head),
10737 SelectionGoal::None,
10738 )
10739 });
10740 })
10741 }
10742
10743 pub fn select_to_previous_subword_start(
10744 &mut self,
10745 _: &SelectToPreviousSubwordStart,
10746 window: &mut Window,
10747 cx: &mut Context<Self>,
10748 ) {
10749 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10750 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10751 s.move_heads_with(|map, head, _| {
10752 (
10753 movement::previous_subword_start(map, head),
10754 SelectionGoal::None,
10755 )
10756 });
10757 })
10758 }
10759
10760 pub fn delete_to_previous_word_start(
10761 &mut self,
10762 action: &DeleteToPreviousWordStart,
10763 window: &mut Window,
10764 cx: &mut Context<Self>,
10765 ) {
10766 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10767 self.transact(window, cx, |this, window, cx| {
10768 this.select_autoclose_pair(window, cx);
10769 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10770 s.move_with(|map, selection| {
10771 if selection.is_empty() {
10772 let cursor = if action.ignore_newlines {
10773 movement::previous_word_start(map, selection.head())
10774 } else {
10775 movement::previous_word_start_or_newline(map, selection.head())
10776 };
10777 selection.set_head(cursor, SelectionGoal::None);
10778 }
10779 });
10780 });
10781 this.insert("", window, cx);
10782 });
10783 }
10784
10785 pub fn delete_to_previous_subword_start(
10786 &mut self,
10787 _: &DeleteToPreviousSubwordStart,
10788 window: &mut Window,
10789 cx: &mut Context<Self>,
10790 ) {
10791 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10792 self.transact(window, cx, |this, window, cx| {
10793 this.select_autoclose_pair(window, cx);
10794 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10795 s.move_with(|map, selection| {
10796 if selection.is_empty() {
10797 let cursor = movement::previous_subword_start(map, selection.head());
10798 selection.set_head(cursor, SelectionGoal::None);
10799 }
10800 });
10801 });
10802 this.insert("", window, cx);
10803 });
10804 }
10805
10806 pub fn move_to_next_word_end(
10807 &mut self,
10808 _: &MoveToNextWordEnd,
10809 window: &mut Window,
10810 cx: &mut Context<Self>,
10811 ) {
10812 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10813 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10814 s.move_cursors_with(|map, head, _| {
10815 (movement::next_word_end(map, head), SelectionGoal::None)
10816 });
10817 })
10818 }
10819
10820 pub fn move_to_next_subword_end(
10821 &mut self,
10822 _: &MoveToNextSubwordEnd,
10823 window: &mut Window,
10824 cx: &mut Context<Self>,
10825 ) {
10826 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10827 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10828 s.move_cursors_with(|map, head, _| {
10829 (movement::next_subword_end(map, head), SelectionGoal::None)
10830 });
10831 })
10832 }
10833
10834 pub fn select_to_next_word_end(
10835 &mut self,
10836 _: &SelectToNextWordEnd,
10837 window: &mut Window,
10838 cx: &mut Context<Self>,
10839 ) {
10840 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10841 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10842 s.move_heads_with(|map, head, _| {
10843 (movement::next_word_end(map, head), SelectionGoal::None)
10844 });
10845 })
10846 }
10847
10848 pub fn select_to_next_subword_end(
10849 &mut self,
10850 _: &SelectToNextSubwordEnd,
10851 window: &mut Window,
10852 cx: &mut Context<Self>,
10853 ) {
10854 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10855 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10856 s.move_heads_with(|map, head, _| {
10857 (movement::next_subword_end(map, head), SelectionGoal::None)
10858 });
10859 })
10860 }
10861
10862 pub fn delete_to_next_word_end(
10863 &mut self,
10864 action: &DeleteToNextWordEnd,
10865 window: &mut Window,
10866 cx: &mut Context<Self>,
10867 ) {
10868 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10869 self.transact(window, cx, |this, window, cx| {
10870 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10871 s.move_with(|map, selection| {
10872 if selection.is_empty() {
10873 let cursor = if action.ignore_newlines {
10874 movement::next_word_end(map, selection.head())
10875 } else {
10876 movement::next_word_end_or_newline(map, selection.head())
10877 };
10878 selection.set_head(cursor, SelectionGoal::None);
10879 }
10880 });
10881 });
10882 this.insert("", window, cx);
10883 });
10884 }
10885
10886 pub fn delete_to_next_subword_end(
10887 &mut self,
10888 _: &DeleteToNextSubwordEnd,
10889 window: &mut Window,
10890 cx: &mut Context<Self>,
10891 ) {
10892 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10893 self.transact(window, cx, |this, window, cx| {
10894 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10895 s.move_with(|map, selection| {
10896 if selection.is_empty() {
10897 let cursor = movement::next_subword_end(map, selection.head());
10898 selection.set_head(cursor, SelectionGoal::None);
10899 }
10900 });
10901 });
10902 this.insert("", window, cx);
10903 });
10904 }
10905
10906 pub fn move_to_beginning_of_line(
10907 &mut self,
10908 action: &MoveToBeginningOfLine,
10909 window: &mut Window,
10910 cx: &mut Context<Self>,
10911 ) {
10912 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10913 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10914 s.move_cursors_with(|map, head, _| {
10915 (
10916 movement::indented_line_beginning(
10917 map,
10918 head,
10919 action.stop_at_soft_wraps,
10920 action.stop_at_indent,
10921 ),
10922 SelectionGoal::None,
10923 )
10924 });
10925 })
10926 }
10927
10928 pub fn select_to_beginning_of_line(
10929 &mut self,
10930 action: &SelectToBeginningOfLine,
10931 window: &mut Window,
10932 cx: &mut Context<Self>,
10933 ) {
10934 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10935 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10936 s.move_heads_with(|map, head, _| {
10937 (
10938 movement::indented_line_beginning(
10939 map,
10940 head,
10941 action.stop_at_soft_wraps,
10942 action.stop_at_indent,
10943 ),
10944 SelectionGoal::None,
10945 )
10946 });
10947 });
10948 }
10949
10950 pub fn delete_to_beginning_of_line(
10951 &mut self,
10952 action: &DeleteToBeginningOfLine,
10953 window: &mut Window,
10954 cx: &mut Context<Self>,
10955 ) {
10956 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10957 self.transact(window, cx, |this, window, cx| {
10958 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10959 s.move_with(|_, selection| {
10960 selection.reversed = true;
10961 });
10962 });
10963
10964 this.select_to_beginning_of_line(
10965 &SelectToBeginningOfLine {
10966 stop_at_soft_wraps: false,
10967 stop_at_indent: action.stop_at_indent,
10968 },
10969 window,
10970 cx,
10971 );
10972 this.backspace(&Backspace, window, cx);
10973 });
10974 }
10975
10976 pub fn move_to_end_of_line(
10977 &mut self,
10978 action: &MoveToEndOfLine,
10979 window: &mut Window,
10980 cx: &mut Context<Self>,
10981 ) {
10982 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10983 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10984 s.move_cursors_with(|map, head, _| {
10985 (
10986 movement::line_end(map, head, action.stop_at_soft_wraps),
10987 SelectionGoal::None,
10988 )
10989 });
10990 })
10991 }
10992
10993 pub fn select_to_end_of_line(
10994 &mut self,
10995 action: &SelectToEndOfLine,
10996 window: &mut Window,
10997 cx: &mut Context<Self>,
10998 ) {
10999 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11000 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11001 s.move_heads_with(|map, head, _| {
11002 (
11003 movement::line_end(map, head, action.stop_at_soft_wraps),
11004 SelectionGoal::None,
11005 )
11006 });
11007 })
11008 }
11009
11010 pub fn delete_to_end_of_line(
11011 &mut self,
11012 _: &DeleteToEndOfLine,
11013 window: &mut Window,
11014 cx: &mut Context<Self>,
11015 ) {
11016 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11017 self.transact(window, cx, |this, window, cx| {
11018 this.select_to_end_of_line(
11019 &SelectToEndOfLine {
11020 stop_at_soft_wraps: false,
11021 },
11022 window,
11023 cx,
11024 );
11025 this.delete(&Delete, window, cx);
11026 });
11027 }
11028
11029 pub fn cut_to_end_of_line(
11030 &mut self,
11031 _: &CutToEndOfLine,
11032 window: &mut Window,
11033 cx: &mut Context<Self>,
11034 ) {
11035 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11036 self.transact(window, cx, |this, window, cx| {
11037 this.select_to_end_of_line(
11038 &SelectToEndOfLine {
11039 stop_at_soft_wraps: false,
11040 },
11041 window,
11042 cx,
11043 );
11044 this.cut(&Cut, window, cx);
11045 });
11046 }
11047
11048 pub fn move_to_start_of_paragraph(
11049 &mut self,
11050 _: &MoveToStartOfParagraph,
11051 window: &mut Window,
11052 cx: &mut Context<Self>,
11053 ) {
11054 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11055 cx.propagate();
11056 return;
11057 }
11058 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11059 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11060 s.move_with(|map, selection| {
11061 selection.collapse_to(
11062 movement::start_of_paragraph(map, selection.head(), 1),
11063 SelectionGoal::None,
11064 )
11065 });
11066 })
11067 }
11068
11069 pub fn move_to_end_of_paragraph(
11070 &mut self,
11071 _: &MoveToEndOfParagraph,
11072 window: &mut Window,
11073 cx: &mut Context<Self>,
11074 ) {
11075 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11076 cx.propagate();
11077 return;
11078 }
11079 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11080 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11081 s.move_with(|map, selection| {
11082 selection.collapse_to(
11083 movement::end_of_paragraph(map, selection.head(), 1),
11084 SelectionGoal::None,
11085 )
11086 });
11087 })
11088 }
11089
11090 pub fn select_to_start_of_paragraph(
11091 &mut self,
11092 _: &SelectToStartOfParagraph,
11093 window: &mut Window,
11094 cx: &mut Context<Self>,
11095 ) {
11096 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11097 cx.propagate();
11098 return;
11099 }
11100 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11101 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11102 s.move_heads_with(|map, head, _| {
11103 (
11104 movement::start_of_paragraph(map, head, 1),
11105 SelectionGoal::None,
11106 )
11107 });
11108 })
11109 }
11110
11111 pub fn select_to_end_of_paragraph(
11112 &mut self,
11113 _: &SelectToEndOfParagraph,
11114 window: &mut Window,
11115 cx: &mut Context<Self>,
11116 ) {
11117 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11118 cx.propagate();
11119 return;
11120 }
11121 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11122 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11123 s.move_heads_with(|map, head, _| {
11124 (
11125 movement::end_of_paragraph(map, head, 1),
11126 SelectionGoal::None,
11127 )
11128 });
11129 })
11130 }
11131
11132 pub fn move_to_start_of_excerpt(
11133 &mut self,
11134 _: &MoveToStartOfExcerpt,
11135 window: &mut Window,
11136 cx: &mut Context<Self>,
11137 ) {
11138 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11139 cx.propagate();
11140 return;
11141 }
11142 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11143 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11144 s.move_with(|map, selection| {
11145 selection.collapse_to(
11146 movement::start_of_excerpt(
11147 map,
11148 selection.head(),
11149 workspace::searchable::Direction::Prev,
11150 ),
11151 SelectionGoal::None,
11152 )
11153 });
11154 })
11155 }
11156
11157 pub fn move_to_start_of_next_excerpt(
11158 &mut self,
11159 _: &MoveToStartOfNextExcerpt,
11160 window: &mut Window,
11161 cx: &mut Context<Self>,
11162 ) {
11163 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11164 cx.propagate();
11165 return;
11166 }
11167
11168 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11169 s.move_with(|map, selection| {
11170 selection.collapse_to(
11171 movement::start_of_excerpt(
11172 map,
11173 selection.head(),
11174 workspace::searchable::Direction::Next,
11175 ),
11176 SelectionGoal::None,
11177 )
11178 });
11179 })
11180 }
11181
11182 pub fn move_to_end_of_excerpt(
11183 &mut self,
11184 _: &MoveToEndOfExcerpt,
11185 window: &mut Window,
11186 cx: &mut Context<Self>,
11187 ) {
11188 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11189 cx.propagate();
11190 return;
11191 }
11192 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11193 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11194 s.move_with(|map, selection| {
11195 selection.collapse_to(
11196 movement::end_of_excerpt(
11197 map,
11198 selection.head(),
11199 workspace::searchable::Direction::Next,
11200 ),
11201 SelectionGoal::None,
11202 )
11203 });
11204 })
11205 }
11206
11207 pub fn move_to_end_of_previous_excerpt(
11208 &mut self,
11209 _: &MoveToEndOfPreviousExcerpt,
11210 window: &mut Window,
11211 cx: &mut Context<Self>,
11212 ) {
11213 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11214 cx.propagate();
11215 return;
11216 }
11217 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11218 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11219 s.move_with(|map, selection| {
11220 selection.collapse_to(
11221 movement::end_of_excerpt(
11222 map,
11223 selection.head(),
11224 workspace::searchable::Direction::Prev,
11225 ),
11226 SelectionGoal::None,
11227 )
11228 });
11229 })
11230 }
11231
11232 pub fn select_to_start_of_excerpt(
11233 &mut self,
11234 _: &SelectToStartOfExcerpt,
11235 window: &mut Window,
11236 cx: &mut Context<Self>,
11237 ) {
11238 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11239 cx.propagate();
11240 return;
11241 }
11242 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11243 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11244 s.move_heads_with(|map, head, _| {
11245 (
11246 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11247 SelectionGoal::None,
11248 )
11249 });
11250 })
11251 }
11252
11253 pub fn select_to_start_of_next_excerpt(
11254 &mut self,
11255 _: &SelectToStartOfNextExcerpt,
11256 window: &mut Window,
11257 cx: &mut Context<Self>,
11258 ) {
11259 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11260 cx.propagate();
11261 return;
11262 }
11263 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11264 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11265 s.move_heads_with(|map, head, _| {
11266 (
11267 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11268 SelectionGoal::None,
11269 )
11270 });
11271 })
11272 }
11273
11274 pub fn select_to_end_of_excerpt(
11275 &mut self,
11276 _: &SelectToEndOfExcerpt,
11277 window: &mut Window,
11278 cx: &mut Context<Self>,
11279 ) {
11280 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11281 cx.propagate();
11282 return;
11283 }
11284 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11285 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11286 s.move_heads_with(|map, head, _| {
11287 (
11288 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11289 SelectionGoal::None,
11290 )
11291 });
11292 })
11293 }
11294
11295 pub fn select_to_end_of_previous_excerpt(
11296 &mut self,
11297 _: &SelectToEndOfPreviousExcerpt,
11298 window: &mut Window,
11299 cx: &mut Context<Self>,
11300 ) {
11301 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11302 cx.propagate();
11303 return;
11304 }
11305 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11306 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11307 s.move_heads_with(|map, head, _| {
11308 (
11309 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11310 SelectionGoal::None,
11311 )
11312 });
11313 })
11314 }
11315
11316 pub fn move_to_beginning(
11317 &mut self,
11318 _: &MoveToBeginning,
11319 window: &mut Window,
11320 cx: &mut Context<Self>,
11321 ) {
11322 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11323 cx.propagate();
11324 return;
11325 }
11326 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11327 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11328 s.select_ranges(vec![0..0]);
11329 });
11330 }
11331
11332 pub fn select_to_beginning(
11333 &mut self,
11334 _: &SelectToBeginning,
11335 window: &mut Window,
11336 cx: &mut Context<Self>,
11337 ) {
11338 let mut selection = self.selections.last::<Point>(cx);
11339 selection.set_head(Point::zero(), SelectionGoal::None);
11340 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11341 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11342 s.select(vec![selection]);
11343 });
11344 }
11345
11346 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11347 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11348 cx.propagate();
11349 return;
11350 }
11351 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11352 let cursor = self.buffer.read(cx).read(cx).len();
11353 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11354 s.select_ranges(vec![cursor..cursor])
11355 });
11356 }
11357
11358 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11359 self.nav_history = nav_history;
11360 }
11361
11362 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11363 self.nav_history.as_ref()
11364 }
11365
11366 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11367 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11368 }
11369
11370 fn push_to_nav_history(
11371 &mut self,
11372 cursor_anchor: Anchor,
11373 new_position: Option<Point>,
11374 is_deactivate: bool,
11375 cx: &mut Context<Self>,
11376 ) {
11377 if let Some(nav_history) = self.nav_history.as_mut() {
11378 let buffer = self.buffer.read(cx).read(cx);
11379 let cursor_position = cursor_anchor.to_point(&buffer);
11380 let scroll_state = self.scroll_manager.anchor();
11381 let scroll_top_row = scroll_state.top_row(&buffer);
11382 drop(buffer);
11383
11384 if let Some(new_position) = new_position {
11385 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11386 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11387 return;
11388 }
11389 }
11390
11391 nav_history.push(
11392 Some(NavigationData {
11393 cursor_anchor,
11394 cursor_position,
11395 scroll_anchor: scroll_state,
11396 scroll_top_row,
11397 }),
11398 cx,
11399 );
11400 cx.emit(EditorEvent::PushedToNavHistory {
11401 anchor: cursor_anchor,
11402 is_deactivate,
11403 })
11404 }
11405 }
11406
11407 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11408 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11409 let buffer = self.buffer.read(cx).snapshot(cx);
11410 let mut selection = self.selections.first::<usize>(cx);
11411 selection.set_head(buffer.len(), SelectionGoal::None);
11412 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11413 s.select(vec![selection]);
11414 });
11415 }
11416
11417 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11418 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11419 let end = self.buffer.read(cx).read(cx).len();
11420 self.change_selections(None, window, cx, |s| {
11421 s.select_ranges(vec![0..end]);
11422 });
11423 }
11424
11425 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11426 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11427 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11428 let mut selections = self.selections.all::<Point>(cx);
11429 let max_point = display_map.buffer_snapshot.max_point();
11430 for selection in &mut selections {
11431 let rows = selection.spanned_rows(true, &display_map);
11432 selection.start = Point::new(rows.start.0, 0);
11433 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11434 selection.reversed = false;
11435 }
11436 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11437 s.select(selections);
11438 });
11439 }
11440
11441 pub fn split_selection_into_lines(
11442 &mut self,
11443 _: &SplitSelectionIntoLines,
11444 window: &mut Window,
11445 cx: &mut Context<Self>,
11446 ) {
11447 let selections = self
11448 .selections
11449 .all::<Point>(cx)
11450 .into_iter()
11451 .map(|selection| selection.start..selection.end)
11452 .collect::<Vec<_>>();
11453 self.unfold_ranges(&selections, true, true, cx);
11454
11455 let mut new_selection_ranges = Vec::new();
11456 {
11457 let buffer = self.buffer.read(cx).read(cx);
11458 for selection in selections {
11459 for row in selection.start.row..selection.end.row {
11460 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11461 new_selection_ranges.push(cursor..cursor);
11462 }
11463
11464 let is_multiline_selection = selection.start.row != selection.end.row;
11465 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11466 // so this action feels more ergonomic when paired with other selection operations
11467 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11468 if !should_skip_last {
11469 new_selection_ranges.push(selection.end..selection.end);
11470 }
11471 }
11472 }
11473 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11474 s.select_ranges(new_selection_ranges);
11475 });
11476 }
11477
11478 pub fn add_selection_above(
11479 &mut self,
11480 _: &AddSelectionAbove,
11481 window: &mut Window,
11482 cx: &mut Context<Self>,
11483 ) {
11484 self.add_selection(true, window, cx);
11485 }
11486
11487 pub fn add_selection_below(
11488 &mut self,
11489 _: &AddSelectionBelow,
11490 window: &mut Window,
11491 cx: &mut Context<Self>,
11492 ) {
11493 self.add_selection(false, window, cx);
11494 }
11495
11496 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11497 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11498
11499 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11500 let mut selections = self.selections.all::<Point>(cx);
11501 let text_layout_details = self.text_layout_details(window);
11502 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11503 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11504 let range = oldest_selection.display_range(&display_map).sorted();
11505
11506 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11507 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11508 let positions = start_x.min(end_x)..start_x.max(end_x);
11509
11510 selections.clear();
11511 let mut stack = Vec::new();
11512 for row in range.start.row().0..=range.end.row().0 {
11513 if let Some(selection) = self.selections.build_columnar_selection(
11514 &display_map,
11515 DisplayRow(row),
11516 &positions,
11517 oldest_selection.reversed,
11518 &text_layout_details,
11519 ) {
11520 stack.push(selection.id);
11521 selections.push(selection);
11522 }
11523 }
11524
11525 if above {
11526 stack.reverse();
11527 }
11528
11529 AddSelectionsState { above, stack }
11530 });
11531
11532 let last_added_selection = *state.stack.last().unwrap();
11533 let mut new_selections = Vec::new();
11534 if above == state.above {
11535 let end_row = if above {
11536 DisplayRow(0)
11537 } else {
11538 display_map.max_point().row()
11539 };
11540
11541 'outer: for selection in selections {
11542 if selection.id == last_added_selection {
11543 let range = selection.display_range(&display_map).sorted();
11544 debug_assert_eq!(range.start.row(), range.end.row());
11545 let mut row = range.start.row();
11546 let positions =
11547 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11548 px(start)..px(end)
11549 } else {
11550 let start_x =
11551 display_map.x_for_display_point(range.start, &text_layout_details);
11552 let end_x =
11553 display_map.x_for_display_point(range.end, &text_layout_details);
11554 start_x.min(end_x)..start_x.max(end_x)
11555 };
11556
11557 while row != end_row {
11558 if above {
11559 row.0 -= 1;
11560 } else {
11561 row.0 += 1;
11562 }
11563
11564 if let Some(new_selection) = self.selections.build_columnar_selection(
11565 &display_map,
11566 row,
11567 &positions,
11568 selection.reversed,
11569 &text_layout_details,
11570 ) {
11571 state.stack.push(new_selection.id);
11572 if above {
11573 new_selections.push(new_selection);
11574 new_selections.push(selection);
11575 } else {
11576 new_selections.push(selection);
11577 new_selections.push(new_selection);
11578 }
11579
11580 continue 'outer;
11581 }
11582 }
11583 }
11584
11585 new_selections.push(selection);
11586 }
11587 } else {
11588 new_selections = selections;
11589 new_selections.retain(|s| s.id != last_added_selection);
11590 state.stack.pop();
11591 }
11592
11593 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11594 s.select(new_selections);
11595 });
11596 if state.stack.len() > 1 {
11597 self.add_selections_state = Some(state);
11598 }
11599 }
11600
11601 pub fn select_next_match_internal(
11602 &mut self,
11603 display_map: &DisplaySnapshot,
11604 replace_newest: bool,
11605 autoscroll: Option<Autoscroll>,
11606 window: &mut Window,
11607 cx: &mut Context<Self>,
11608 ) -> Result<()> {
11609 fn select_next_match_ranges(
11610 this: &mut Editor,
11611 range: Range<usize>,
11612 replace_newest: bool,
11613 auto_scroll: Option<Autoscroll>,
11614 window: &mut Window,
11615 cx: &mut Context<Editor>,
11616 ) {
11617 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11618 this.change_selections(auto_scroll, window, cx, |s| {
11619 if replace_newest {
11620 s.delete(s.newest_anchor().id);
11621 }
11622 s.insert_range(range.clone());
11623 });
11624 }
11625
11626 let buffer = &display_map.buffer_snapshot;
11627 let mut selections = self.selections.all::<usize>(cx);
11628 if let Some(mut select_next_state) = self.select_next_state.take() {
11629 let query = &select_next_state.query;
11630 if !select_next_state.done {
11631 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11632 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11633 let mut next_selected_range = None;
11634
11635 let bytes_after_last_selection =
11636 buffer.bytes_in_range(last_selection.end..buffer.len());
11637 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11638 let query_matches = query
11639 .stream_find_iter(bytes_after_last_selection)
11640 .map(|result| (last_selection.end, result))
11641 .chain(
11642 query
11643 .stream_find_iter(bytes_before_first_selection)
11644 .map(|result| (0, result)),
11645 );
11646
11647 for (start_offset, query_match) in query_matches {
11648 let query_match = query_match.unwrap(); // can only fail due to I/O
11649 let offset_range =
11650 start_offset + query_match.start()..start_offset + query_match.end();
11651 let display_range = offset_range.start.to_display_point(display_map)
11652 ..offset_range.end.to_display_point(display_map);
11653
11654 if !select_next_state.wordwise
11655 || (!movement::is_inside_word(display_map, display_range.start)
11656 && !movement::is_inside_word(display_map, display_range.end))
11657 {
11658 // TODO: This is n^2, because we might check all the selections
11659 if !selections
11660 .iter()
11661 .any(|selection| selection.range().overlaps(&offset_range))
11662 {
11663 next_selected_range = Some(offset_range);
11664 break;
11665 }
11666 }
11667 }
11668
11669 if let Some(next_selected_range) = next_selected_range {
11670 select_next_match_ranges(
11671 self,
11672 next_selected_range,
11673 replace_newest,
11674 autoscroll,
11675 window,
11676 cx,
11677 );
11678 } else {
11679 select_next_state.done = true;
11680 }
11681 }
11682
11683 self.select_next_state = Some(select_next_state);
11684 } else {
11685 let mut only_carets = true;
11686 let mut same_text_selected = true;
11687 let mut selected_text = None;
11688
11689 let mut selections_iter = selections.iter().peekable();
11690 while let Some(selection) = selections_iter.next() {
11691 if selection.start != selection.end {
11692 only_carets = false;
11693 }
11694
11695 if same_text_selected {
11696 if selected_text.is_none() {
11697 selected_text =
11698 Some(buffer.text_for_range(selection.range()).collect::<String>());
11699 }
11700
11701 if let Some(next_selection) = selections_iter.peek() {
11702 if next_selection.range().len() == selection.range().len() {
11703 let next_selected_text = buffer
11704 .text_for_range(next_selection.range())
11705 .collect::<String>();
11706 if Some(next_selected_text) != selected_text {
11707 same_text_selected = false;
11708 selected_text = None;
11709 }
11710 } else {
11711 same_text_selected = false;
11712 selected_text = None;
11713 }
11714 }
11715 }
11716 }
11717
11718 if only_carets {
11719 for selection in &mut selections {
11720 let word_range = movement::surrounding_word(
11721 display_map,
11722 selection.start.to_display_point(display_map),
11723 );
11724 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11725 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11726 selection.goal = SelectionGoal::None;
11727 selection.reversed = false;
11728 select_next_match_ranges(
11729 self,
11730 selection.start..selection.end,
11731 replace_newest,
11732 autoscroll,
11733 window,
11734 cx,
11735 );
11736 }
11737
11738 if selections.len() == 1 {
11739 let selection = selections
11740 .last()
11741 .expect("ensured that there's only one selection");
11742 let query = buffer
11743 .text_for_range(selection.start..selection.end)
11744 .collect::<String>();
11745 let is_empty = query.is_empty();
11746 let select_state = SelectNextState {
11747 query: AhoCorasick::new(&[query])?,
11748 wordwise: true,
11749 done: is_empty,
11750 };
11751 self.select_next_state = Some(select_state);
11752 } else {
11753 self.select_next_state = None;
11754 }
11755 } else if let Some(selected_text) = selected_text {
11756 self.select_next_state = Some(SelectNextState {
11757 query: AhoCorasick::new(&[selected_text])?,
11758 wordwise: false,
11759 done: false,
11760 });
11761 self.select_next_match_internal(
11762 display_map,
11763 replace_newest,
11764 autoscroll,
11765 window,
11766 cx,
11767 )?;
11768 }
11769 }
11770 Ok(())
11771 }
11772
11773 pub fn select_all_matches(
11774 &mut self,
11775 _action: &SelectAllMatches,
11776 window: &mut Window,
11777 cx: &mut Context<Self>,
11778 ) -> Result<()> {
11779 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11780
11781 self.push_to_selection_history();
11782 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11783
11784 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11785 let Some(select_next_state) = self.select_next_state.as_mut() else {
11786 return Ok(());
11787 };
11788 if select_next_state.done {
11789 return Ok(());
11790 }
11791
11792 let mut new_selections = Vec::new();
11793
11794 let reversed = self.selections.oldest::<usize>(cx).reversed;
11795 let buffer = &display_map.buffer_snapshot;
11796 let query_matches = select_next_state
11797 .query
11798 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11799
11800 for query_match in query_matches.into_iter() {
11801 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11802 let offset_range = if reversed {
11803 query_match.end()..query_match.start()
11804 } else {
11805 query_match.start()..query_match.end()
11806 };
11807 let display_range = offset_range.start.to_display_point(&display_map)
11808 ..offset_range.end.to_display_point(&display_map);
11809
11810 if !select_next_state.wordwise
11811 || (!movement::is_inside_word(&display_map, display_range.start)
11812 && !movement::is_inside_word(&display_map, display_range.end))
11813 {
11814 new_selections.push(offset_range.start..offset_range.end);
11815 }
11816 }
11817
11818 select_next_state.done = true;
11819 self.unfold_ranges(&new_selections.clone(), false, false, cx);
11820 self.change_selections(None, window, cx, |selections| {
11821 selections.select_ranges(new_selections)
11822 });
11823
11824 Ok(())
11825 }
11826
11827 pub fn select_next(
11828 &mut self,
11829 action: &SelectNext,
11830 window: &mut Window,
11831 cx: &mut Context<Self>,
11832 ) -> Result<()> {
11833 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11834 self.push_to_selection_history();
11835 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11836 self.select_next_match_internal(
11837 &display_map,
11838 action.replace_newest,
11839 Some(Autoscroll::newest()),
11840 window,
11841 cx,
11842 )?;
11843 Ok(())
11844 }
11845
11846 pub fn select_previous(
11847 &mut self,
11848 action: &SelectPrevious,
11849 window: &mut Window,
11850 cx: &mut Context<Self>,
11851 ) -> Result<()> {
11852 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11853 self.push_to_selection_history();
11854 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11855 let buffer = &display_map.buffer_snapshot;
11856 let mut selections = self.selections.all::<usize>(cx);
11857 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11858 let query = &select_prev_state.query;
11859 if !select_prev_state.done {
11860 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11861 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11862 let mut next_selected_range = None;
11863 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11864 let bytes_before_last_selection =
11865 buffer.reversed_bytes_in_range(0..last_selection.start);
11866 let bytes_after_first_selection =
11867 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11868 let query_matches = query
11869 .stream_find_iter(bytes_before_last_selection)
11870 .map(|result| (last_selection.start, result))
11871 .chain(
11872 query
11873 .stream_find_iter(bytes_after_first_selection)
11874 .map(|result| (buffer.len(), result)),
11875 );
11876 for (end_offset, query_match) in query_matches {
11877 let query_match = query_match.unwrap(); // can only fail due to I/O
11878 let offset_range =
11879 end_offset - query_match.end()..end_offset - query_match.start();
11880 let display_range = offset_range.start.to_display_point(&display_map)
11881 ..offset_range.end.to_display_point(&display_map);
11882
11883 if !select_prev_state.wordwise
11884 || (!movement::is_inside_word(&display_map, display_range.start)
11885 && !movement::is_inside_word(&display_map, display_range.end))
11886 {
11887 next_selected_range = Some(offset_range);
11888 break;
11889 }
11890 }
11891
11892 if let Some(next_selected_range) = next_selected_range {
11893 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11894 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11895 if action.replace_newest {
11896 s.delete(s.newest_anchor().id);
11897 }
11898 s.insert_range(next_selected_range);
11899 });
11900 } else {
11901 select_prev_state.done = true;
11902 }
11903 }
11904
11905 self.select_prev_state = Some(select_prev_state);
11906 } else {
11907 let mut only_carets = true;
11908 let mut same_text_selected = true;
11909 let mut selected_text = None;
11910
11911 let mut selections_iter = selections.iter().peekable();
11912 while let Some(selection) = selections_iter.next() {
11913 if selection.start != selection.end {
11914 only_carets = false;
11915 }
11916
11917 if same_text_selected {
11918 if selected_text.is_none() {
11919 selected_text =
11920 Some(buffer.text_for_range(selection.range()).collect::<String>());
11921 }
11922
11923 if let Some(next_selection) = selections_iter.peek() {
11924 if next_selection.range().len() == selection.range().len() {
11925 let next_selected_text = buffer
11926 .text_for_range(next_selection.range())
11927 .collect::<String>();
11928 if Some(next_selected_text) != selected_text {
11929 same_text_selected = false;
11930 selected_text = None;
11931 }
11932 } else {
11933 same_text_selected = false;
11934 selected_text = None;
11935 }
11936 }
11937 }
11938 }
11939
11940 if only_carets {
11941 for selection in &mut selections {
11942 let word_range = movement::surrounding_word(
11943 &display_map,
11944 selection.start.to_display_point(&display_map),
11945 );
11946 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11947 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11948 selection.goal = SelectionGoal::None;
11949 selection.reversed = false;
11950 }
11951 if selections.len() == 1 {
11952 let selection = selections
11953 .last()
11954 .expect("ensured that there's only one selection");
11955 let query = buffer
11956 .text_for_range(selection.start..selection.end)
11957 .collect::<String>();
11958 let is_empty = query.is_empty();
11959 let select_state = SelectNextState {
11960 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11961 wordwise: true,
11962 done: is_empty,
11963 };
11964 self.select_prev_state = Some(select_state);
11965 } else {
11966 self.select_prev_state = None;
11967 }
11968
11969 self.unfold_ranges(
11970 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11971 false,
11972 true,
11973 cx,
11974 );
11975 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11976 s.select(selections);
11977 });
11978 } else if let Some(selected_text) = selected_text {
11979 self.select_prev_state = Some(SelectNextState {
11980 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11981 wordwise: false,
11982 done: false,
11983 });
11984 self.select_previous(action, window, cx)?;
11985 }
11986 }
11987 Ok(())
11988 }
11989
11990 pub fn toggle_comments(
11991 &mut self,
11992 action: &ToggleComments,
11993 window: &mut Window,
11994 cx: &mut Context<Self>,
11995 ) {
11996 if self.read_only(cx) {
11997 return;
11998 }
11999 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12000 let text_layout_details = &self.text_layout_details(window);
12001 self.transact(window, cx, |this, window, cx| {
12002 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12003 let mut edits = Vec::new();
12004 let mut selection_edit_ranges = Vec::new();
12005 let mut last_toggled_row = None;
12006 let snapshot = this.buffer.read(cx).read(cx);
12007 let empty_str: Arc<str> = Arc::default();
12008 let mut suffixes_inserted = Vec::new();
12009 let ignore_indent = action.ignore_indent;
12010
12011 fn comment_prefix_range(
12012 snapshot: &MultiBufferSnapshot,
12013 row: MultiBufferRow,
12014 comment_prefix: &str,
12015 comment_prefix_whitespace: &str,
12016 ignore_indent: bool,
12017 ) -> Range<Point> {
12018 let indent_size = if ignore_indent {
12019 0
12020 } else {
12021 snapshot.indent_size_for_line(row).len
12022 };
12023
12024 let start = Point::new(row.0, indent_size);
12025
12026 let mut line_bytes = snapshot
12027 .bytes_in_range(start..snapshot.max_point())
12028 .flatten()
12029 .copied();
12030
12031 // If this line currently begins with the line comment prefix, then record
12032 // the range containing the prefix.
12033 if line_bytes
12034 .by_ref()
12035 .take(comment_prefix.len())
12036 .eq(comment_prefix.bytes())
12037 {
12038 // Include any whitespace that matches the comment prefix.
12039 let matching_whitespace_len = line_bytes
12040 .zip(comment_prefix_whitespace.bytes())
12041 .take_while(|(a, b)| a == b)
12042 .count() as u32;
12043 let end = Point::new(
12044 start.row,
12045 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12046 );
12047 start..end
12048 } else {
12049 start..start
12050 }
12051 }
12052
12053 fn comment_suffix_range(
12054 snapshot: &MultiBufferSnapshot,
12055 row: MultiBufferRow,
12056 comment_suffix: &str,
12057 comment_suffix_has_leading_space: bool,
12058 ) -> Range<Point> {
12059 let end = Point::new(row.0, snapshot.line_len(row));
12060 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12061
12062 let mut line_end_bytes = snapshot
12063 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12064 .flatten()
12065 .copied();
12066
12067 let leading_space_len = if suffix_start_column > 0
12068 && line_end_bytes.next() == Some(b' ')
12069 && comment_suffix_has_leading_space
12070 {
12071 1
12072 } else {
12073 0
12074 };
12075
12076 // If this line currently begins with the line comment prefix, then record
12077 // the range containing the prefix.
12078 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12079 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12080 start..end
12081 } else {
12082 end..end
12083 }
12084 }
12085
12086 // TODO: Handle selections that cross excerpts
12087 for selection in &mut selections {
12088 let start_column = snapshot
12089 .indent_size_for_line(MultiBufferRow(selection.start.row))
12090 .len;
12091 let language = if let Some(language) =
12092 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12093 {
12094 language
12095 } else {
12096 continue;
12097 };
12098
12099 selection_edit_ranges.clear();
12100
12101 // If multiple selections contain a given row, avoid processing that
12102 // row more than once.
12103 let mut start_row = MultiBufferRow(selection.start.row);
12104 if last_toggled_row == Some(start_row) {
12105 start_row = start_row.next_row();
12106 }
12107 let end_row =
12108 if selection.end.row > selection.start.row && selection.end.column == 0 {
12109 MultiBufferRow(selection.end.row - 1)
12110 } else {
12111 MultiBufferRow(selection.end.row)
12112 };
12113 last_toggled_row = Some(end_row);
12114
12115 if start_row > end_row {
12116 continue;
12117 }
12118
12119 // If the language has line comments, toggle those.
12120 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12121
12122 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12123 if ignore_indent {
12124 full_comment_prefixes = full_comment_prefixes
12125 .into_iter()
12126 .map(|s| Arc::from(s.trim_end()))
12127 .collect();
12128 }
12129
12130 if !full_comment_prefixes.is_empty() {
12131 let first_prefix = full_comment_prefixes
12132 .first()
12133 .expect("prefixes is non-empty");
12134 let prefix_trimmed_lengths = full_comment_prefixes
12135 .iter()
12136 .map(|p| p.trim_end_matches(' ').len())
12137 .collect::<SmallVec<[usize; 4]>>();
12138
12139 let mut all_selection_lines_are_comments = true;
12140
12141 for row in start_row.0..=end_row.0 {
12142 let row = MultiBufferRow(row);
12143 if start_row < end_row && snapshot.is_line_blank(row) {
12144 continue;
12145 }
12146
12147 let prefix_range = full_comment_prefixes
12148 .iter()
12149 .zip(prefix_trimmed_lengths.iter().copied())
12150 .map(|(prefix, trimmed_prefix_len)| {
12151 comment_prefix_range(
12152 snapshot.deref(),
12153 row,
12154 &prefix[..trimmed_prefix_len],
12155 &prefix[trimmed_prefix_len..],
12156 ignore_indent,
12157 )
12158 })
12159 .max_by_key(|range| range.end.column - range.start.column)
12160 .expect("prefixes is non-empty");
12161
12162 if prefix_range.is_empty() {
12163 all_selection_lines_are_comments = false;
12164 }
12165
12166 selection_edit_ranges.push(prefix_range);
12167 }
12168
12169 if all_selection_lines_are_comments {
12170 edits.extend(
12171 selection_edit_ranges
12172 .iter()
12173 .cloned()
12174 .map(|range| (range, empty_str.clone())),
12175 );
12176 } else {
12177 let min_column = selection_edit_ranges
12178 .iter()
12179 .map(|range| range.start.column)
12180 .min()
12181 .unwrap_or(0);
12182 edits.extend(selection_edit_ranges.iter().map(|range| {
12183 let position = Point::new(range.start.row, min_column);
12184 (position..position, first_prefix.clone())
12185 }));
12186 }
12187 } else if let Some((full_comment_prefix, comment_suffix)) =
12188 language.block_comment_delimiters()
12189 {
12190 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12191 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12192 let prefix_range = comment_prefix_range(
12193 snapshot.deref(),
12194 start_row,
12195 comment_prefix,
12196 comment_prefix_whitespace,
12197 ignore_indent,
12198 );
12199 let suffix_range = comment_suffix_range(
12200 snapshot.deref(),
12201 end_row,
12202 comment_suffix.trim_start_matches(' '),
12203 comment_suffix.starts_with(' '),
12204 );
12205
12206 if prefix_range.is_empty() || suffix_range.is_empty() {
12207 edits.push((
12208 prefix_range.start..prefix_range.start,
12209 full_comment_prefix.clone(),
12210 ));
12211 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12212 suffixes_inserted.push((end_row, comment_suffix.len()));
12213 } else {
12214 edits.push((prefix_range, empty_str.clone()));
12215 edits.push((suffix_range, empty_str.clone()));
12216 }
12217 } else {
12218 continue;
12219 }
12220 }
12221
12222 drop(snapshot);
12223 this.buffer.update(cx, |buffer, cx| {
12224 buffer.edit(edits, None, cx);
12225 });
12226
12227 // Adjust selections so that they end before any comment suffixes that
12228 // were inserted.
12229 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12230 let mut selections = this.selections.all::<Point>(cx);
12231 let snapshot = this.buffer.read(cx).read(cx);
12232 for selection in &mut selections {
12233 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12234 match row.cmp(&MultiBufferRow(selection.end.row)) {
12235 Ordering::Less => {
12236 suffixes_inserted.next();
12237 continue;
12238 }
12239 Ordering::Greater => break,
12240 Ordering::Equal => {
12241 if selection.end.column == snapshot.line_len(row) {
12242 if selection.is_empty() {
12243 selection.start.column -= suffix_len as u32;
12244 }
12245 selection.end.column -= suffix_len as u32;
12246 }
12247 break;
12248 }
12249 }
12250 }
12251 }
12252
12253 drop(snapshot);
12254 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12255 s.select(selections)
12256 });
12257
12258 let selections = this.selections.all::<Point>(cx);
12259 let selections_on_single_row = selections.windows(2).all(|selections| {
12260 selections[0].start.row == selections[1].start.row
12261 && selections[0].end.row == selections[1].end.row
12262 && selections[0].start.row == selections[0].end.row
12263 });
12264 let selections_selecting = selections
12265 .iter()
12266 .any(|selection| selection.start != selection.end);
12267 let advance_downwards = action.advance_downwards
12268 && selections_on_single_row
12269 && !selections_selecting
12270 && !matches!(this.mode, EditorMode::SingleLine { .. });
12271
12272 if advance_downwards {
12273 let snapshot = this.buffer.read(cx).snapshot(cx);
12274
12275 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12276 s.move_cursors_with(|display_snapshot, display_point, _| {
12277 let mut point = display_point.to_point(display_snapshot);
12278 point.row += 1;
12279 point = snapshot.clip_point(point, Bias::Left);
12280 let display_point = point.to_display_point(display_snapshot);
12281 let goal = SelectionGoal::HorizontalPosition(
12282 display_snapshot
12283 .x_for_display_point(display_point, text_layout_details)
12284 .into(),
12285 );
12286 (display_point, goal)
12287 })
12288 });
12289 }
12290 });
12291 }
12292
12293 pub fn select_enclosing_symbol(
12294 &mut self,
12295 _: &SelectEnclosingSymbol,
12296 window: &mut Window,
12297 cx: &mut Context<Self>,
12298 ) {
12299 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12300
12301 let buffer = self.buffer.read(cx).snapshot(cx);
12302 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12303
12304 fn update_selection(
12305 selection: &Selection<usize>,
12306 buffer_snap: &MultiBufferSnapshot,
12307 ) -> Option<Selection<usize>> {
12308 let cursor = selection.head();
12309 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12310 for symbol in symbols.iter().rev() {
12311 let start = symbol.range.start.to_offset(buffer_snap);
12312 let end = symbol.range.end.to_offset(buffer_snap);
12313 let new_range = start..end;
12314 if start < selection.start || end > selection.end {
12315 return Some(Selection {
12316 id: selection.id,
12317 start: new_range.start,
12318 end: new_range.end,
12319 goal: SelectionGoal::None,
12320 reversed: selection.reversed,
12321 });
12322 }
12323 }
12324 None
12325 }
12326
12327 let mut selected_larger_symbol = false;
12328 let new_selections = old_selections
12329 .iter()
12330 .map(|selection| match update_selection(selection, &buffer) {
12331 Some(new_selection) => {
12332 if new_selection.range() != selection.range() {
12333 selected_larger_symbol = true;
12334 }
12335 new_selection
12336 }
12337 None => selection.clone(),
12338 })
12339 .collect::<Vec<_>>();
12340
12341 if selected_larger_symbol {
12342 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12343 s.select(new_selections);
12344 });
12345 }
12346 }
12347
12348 pub fn select_larger_syntax_node(
12349 &mut self,
12350 _: &SelectLargerSyntaxNode,
12351 window: &mut Window,
12352 cx: &mut Context<Self>,
12353 ) {
12354 let Some(visible_row_count) = self.visible_row_count() else {
12355 return;
12356 };
12357 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12358 if old_selections.is_empty() {
12359 return;
12360 }
12361
12362 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12363
12364 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12365 let buffer = self.buffer.read(cx).snapshot(cx);
12366
12367 let mut selected_larger_node = false;
12368 let mut new_selections = old_selections
12369 .iter()
12370 .map(|selection| {
12371 let old_range = selection.start..selection.end;
12372 let mut new_range = old_range.clone();
12373 let mut new_node = None;
12374 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12375 {
12376 new_node = Some(node);
12377 new_range = match containing_range {
12378 MultiOrSingleBufferOffsetRange::Single(_) => break,
12379 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12380 };
12381 if !display_map.intersects_fold(new_range.start)
12382 && !display_map.intersects_fold(new_range.end)
12383 {
12384 break;
12385 }
12386 }
12387
12388 if let Some(node) = new_node {
12389 // Log the ancestor, to support using this action as a way to explore TreeSitter
12390 // nodes. Parent and grandparent are also logged because this operation will not
12391 // visit nodes that have the same range as their parent.
12392 log::info!("Node: {node:?}");
12393 let parent = node.parent();
12394 log::info!("Parent: {parent:?}");
12395 let grandparent = parent.and_then(|x| x.parent());
12396 log::info!("Grandparent: {grandparent:?}");
12397 }
12398
12399 selected_larger_node |= new_range != old_range;
12400 Selection {
12401 id: selection.id,
12402 start: new_range.start,
12403 end: new_range.end,
12404 goal: SelectionGoal::None,
12405 reversed: selection.reversed,
12406 }
12407 })
12408 .collect::<Vec<_>>();
12409
12410 if !selected_larger_node {
12411 return; // don't put this call in the history
12412 }
12413
12414 // scroll based on transformation done to the last selection created by the user
12415 let (last_old, last_new) = old_selections
12416 .last()
12417 .zip(new_selections.last().cloned())
12418 .expect("old_selections isn't empty");
12419
12420 // revert selection
12421 let is_selection_reversed = {
12422 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12423 new_selections.last_mut().expect("checked above").reversed =
12424 should_newest_selection_be_reversed;
12425 should_newest_selection_be_reversed
12426 };
12427
12428 if selected_larger_node {
12429 self.select_syntax_node_history.disable_clearing = true;
12430 self.change_selections(None, window, cx, |s| {
12431 s.select(new_selections.clone());
12432 });
12433 self.select_syntax_node_history.disable_clearing = false;
12434 }
12435
12436 let start_row = last_new.start.to_display_point(&display_map).row().0;
12437 let end_row = last_new.end.to_display_point(&display_map).row().0;
12438 let selection_height = end_row - start_row + 1;
12439 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12440
12441 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12442 let scroll_behavior = if fits_on_the_screen {
12443 self.request_autoscroll(Autoscroll::fit(), cx);
12444 SelectSyntaxNodeScrollBehavior::FitSelection
12445 } else if is_selection_reversed {
12446 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12447 SelectSyntaxNodeScrollBehavior::CursorTop
12448 } else {
12449 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12450 SelectSyntaxNodeScrollBehavior::CursorBottom
12451 };
12452
12453 self.select_syntax_node_history.push((
12454 old_selections,
12455 scroll_behavior,
12456 is_selection_reversed,
12457 ));
12458 }
12459
12460 pub fn select_smaller_syntax_node(
12461 &mut self,
12462 _: &SelectSmallerSyntaxNode,
12463 window: &mut Window,
12464 cx: &mut Context<Self>,
12465 ) {
12466 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12467
12468 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12469 self.select_syntax_node_history.pop()
12470 {
12471 if let Some(selection) = selections.last_mut() {
12472 selection.reversed = is_selection_reversed;
12473 }
12474
12475 self.select_syntax_node_history.disable_clearing = true;
12476 self.change_selections(None, window, cx, |s| {
12477 s.select(selections.to_vec());
12478 });
12479 self.select_syntax_node_history.disable_clearing = false;
12480
12481 match scroll_behavior {
12482 SelectSyntaxNodeScrollBehavior::CursorTop => {
12483 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12484 }
12485 SelectSyntaxNodeScrollBehavior::FitSelection => {
12486 self.request_autoscroll(Autoscroll::fit(), cx);
12487 }
12488 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12489 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12490 }
12491 }
12492 }
12493 }
12494
12495 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12496 if !EditorSettings::get_global(cx).gutter.runnables {
12497 self.clear_tasks();
12498 return Task::ready(());
12499 }
12500 let project = self.project.as_ref().map(Entity::downgrade);
12501 let task_sources = self.lsp_task_sources(cx);
12502 cx.spawn_in(window, async move |editor, cx| {
12503 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12504 let Some(project) = project.and_then(|p| p.upgrade()) else {
12505 return;
12506 };
12507 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12508 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12509 }) else {
12510 return;
12511 };
12512
12513 let hide_runnables = project
12514 .update(cx, |project, cx| {
12515 // Do not display any test indicators in non-dev server remote projects.
12516 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12517 })
12518 .unwrap_or(true);
12519 if hide_runnables {
12520 return;
12521 }
12522 let new_rows =
12523 cx.background_spawn({
12524 let snapshot = display_snapshot.clone();
12525 async move {
12526 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12527 }
12528 })
12529 .await;
12530 let Ok(lsp_tasks) =
12531 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12532 else {
12533 return;
12534 };
12535 let lsp_tasks = lsp_tasks.await;
12536
12537 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12538 lsp_tasks
12539 .into_iter()
12540 .flat_map(|(kind, tasks)| {
12541 tasks.into_iter().filter_map(move |(location, task)| {
12542 Some((kind.clone(), location?, task))
12543 })
12544 })
12545 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12546 let buffer = location.target.buffer;
12547 let buffer_snapshot = buffer.read(cx).snapshot();
12548 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12549 |(excerpt_id, snapshot, _)| {
12550 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12551 display_snapshot
12552 .buffer_snapshot
12553 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12554 } else {
12555 None
12556 }
12557 },
12558 );
12559 if let Some(offset) = offset {
12560 let task_buffer_range =
12561 location.target.range.to_point(&buffer_snapshot);
12562 let context_buffer_range =
12563 task_buffer_range.to_offset(&buffer_snapshot);
12564 let context_range = BufferOffset(context_buffer_range.start)
12565 ..BufferOffset(context_buffer_range.end);
12566
12567 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12568 .or_insert_with(|| RunnableTasks {
12569 templates: Vec::new(),
12570 offset,
12571 column: task_buffer_range.start.column,
12572 extra_variables: HashMap::default(),
12573 context_range,
12574 })
12575 .templates
12576 .push((kind, task.original_task().clone()));
12577 }
12578
12579 acc
12580 })
12581 }) else {
12582 return;
12583 };
12584
12585 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12586 editor
12587 .update(cx, |editor, _| {
12588 editor.clear_tasks();
12589 for (key, mut value) in rows {
12590 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12591 value.templates.extend(lsp_tasks.templates);
12592 }
12593
12594 editor.insert_tasks(key, value);
12595 }
12596 for (key, value) in lsp_tasks_by_rows {
12597 editor.insert_tasks(key, value);
12598 }
12599 })
12600 .ok();
12601 })
12602 }
12603 fn fetch_runnable_ranges(
12604 snapshot: &DisplaySnapshot,
12605 range: Range<Anchor>,
12606 ) -> Vec<language::RunnableRange> {
12607 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12608 }
12609
12610 fn runnable_rows(
12611 project: Entity<Project>,
12612 snapshot: DisplaySnapshot,
12613 runnable_ranges: Vec<RunnableRange>,
12614 mut cx: AsyncWindowContext,
12615 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12616 runnable_ranges
12617 .into_iter()
12618 .filter_map(|mut runnable| {
12619 let tasks = cx
12620 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12621 .ok()?;
12622 if tasks.is_empty() {
12623 return None;
12624 }
12625
12626 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12627
12628 let row = snapshot
12629 .buffer_snapshot
12630 .buffer_line_for_row(MultiBufferRow(point.row))?
12631 .1
12632 .start
12633 .row;
12634
12635 let context_range =
12636 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12637 Some((
12638 (runnable.buffer_id, row),
12639 RunnableTasks {
12640 templates: tasks,
12641 offset: snapshot
12642 .buffer_snapshot
12643 .anchor_before(runnable.run_range.start),
12644 context_range,
12645 column: point.column,
12646 extra_variables: runnable.extra_captures,
12647 },
12648 ))
12649 })
12650 .collect()
12651 }
12652
12653 fn templates_with_tags(
12654 project: &Entity<Project>,
12655 runnable: &mut Runnable,
12656 cx: &mut App,
12657 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12658 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12659 let (worktree_id, file) = project
12660 .buffer_for_id(runnable.buffer, cx)
12661 .and_then(|buffer| buffer.read(cx).file())
12662 .map(|file| (file.worktree_id(cx), file.clone()))
12663 .unzip();
12664
12665 (
12666 project.task_store().read(cx).task_inventory().cloned(),
12667 worktree_id,
12668 file,
12669 )
12670 });
12671
12672 let mut templates_with_tags = mem::take(&mut runnable.tags)
12673 .into_iter()
12674 .flat_map(|RunnableTag(tag)| {
12675 inventory
12676 .as_ref()
12677 .into_iter()
12678 .flat_map(|inventory| {
12679 inventory.read(cx).list_tasks(
12680 file.clone(),
12681 Some(runnable.language.clone()),
12682 worktree_id,
12683 cx,
12684 )
12685 })
12686 .filter(move |(_, template)| {
12687 template.tags.iter().any(|source_tag| source_tag == &tag)
12688 })
12689 })
12690 .sorted_by_key(|(kind, _)| kind.to_owned())
12691 .collect::<Vec<_>>();
12692 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12693 // Strongest source wins; if we have worktree tag binding, prefer that to
12694 // global and language bindings;
12695 // if we have a global binding, prefer that to language binding.
12696 let first_mismatch = templates_with_tags
12697 .iter()
12698 .position(|(tag_source, _)| tag_source != leading_tag_source);
12699 if let Some(index) = first_mismatch {
12700 templates_with_tags.truncate(index);
12701 }
12702 }
12703
12704 templates_with_tags
12705 }
12706
12707 pub fn move_to_enclosing_bracket(
12708 &mut self,
12709 _: &MoveToEnclosingBracket,
12710 window: &mut Window,
12711 cx: &mut Context<Self>,
12712 ) {
12713 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12714 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12715 s.move_offsets_with(|snapshot, selection| {
12716 let Some(enclosing_bracket_ranges) =
12717 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12718 else {
12719 return;
12720 };
12721
12722 let mut best_length = usize::MAX;
12723 let mut best_inside = false;
12724 let mut best_in_bracket_range = false;
12725 let mut best_destination = None;
12726 for (open, close) in enclosing_bracket_ranges {
12727 let close = close.to_inclusive();
12728 let length = close.end() - open.start;
12729 let inside = selection.start >= open.end && selection.end <= *close.start();
12730 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12731 || close.contains(&selection.head());
12732
12733 // If best is next to a bracket and current isn't, skip
12734 if !in_bracket_range && best_in_bracket_range {
12735 continue;
12736 }
12737
12738 // Prefer smaller lengths unless best is inside and current isn't
12739 if length > best_length && (best_inside || !inside) {
12740 continue;
12741 }
12742
12743 best_length = length;
12744 best_inside = inside;
12745 best_in_bracket_range = in_bracket_range;
12746 best_destination = Some(
12747 if close.contains(&selection.start) && close.contains(&selection.end) {
12748 if inside { open.end } else { open.start }
12749 } else if inside {
12750 *close.start()
12751 } else {
12752 *close.end()
12753 },
12754 );
12755 }
12756
12757 if let Some(destination) = best_destination {
12758 selection.collapse_to(destination, SelectionGoal::None);
12759 }
12760 })
12761 });
12762 }
12763
12764 pub fn undo_selection(
12765 &mut self,
12766 _: &UndoSelection,
12767 window: &mut Window,
12768 cx: &mut Context<Self>,
12769 ) {
12770 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12771 self.end_selection(window, cx);
12772 self.selection_history.mode = SelectionHistoryMode::Undoing;
12773 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12774 self.change_selections(None, window, cx, |s| {
12775 s.select_anchors(entry.selections.to_vec())
12776 });
12777 self.select_next_state = entry.select_next_state;
12778 self.select_prev_state = entry.select_prev_state;
12779 self.add_selections_state = entry.add_selections_state;
12780 self.request_autoscroll(Autoscroll::newest(), cx);
12781 }
12782 self.selection_history.mode = SelectionHistoryMode::Normal;
12783 }
12784
12785 pub fn redo_selection(
12786 &mut self,
12787 _: &RedoSelection,
12788 window: &mut Window,
12789 cx: &mut Context<Self>,
12790 ) {
12791 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12792 self.end_selection(window, cx);
12793 self.selection_history.mode = SelectionHistoryMode::Redoing;
12794 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12795 self.change_selections(None, window, cx, |s| {
12796 s.select_anchors(entry.selections.to_vec())
12797 });
12798 self.select_next_state = entry.select_next_state;
12799 self.select_prev_state = entry.select_prev_state;
12800 self.add_selections_state = entry.add_selections_state;
12801 self.request_autoscroll(Autoscroll::newest(), cx);
12802 }
12803 self.selection_history.mode = SelectionHistoryMode::Normal;
12804 }
12805
12806 pub fn expand_excerpts(
12807 &mut self,
12808 action: &ExpandExcerpts,
12809 _: &mut Window,
12810 cx: &mut Context<Self>,
12811 ) {
12812 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12813 }
12814
12815 pub fn expand_excerpts_down(
12816 &mut self,
12817 action: &ExpandExcerptsDown,
12818 _: &mut Window,
12819 cx: &mut Context<Self>,
12820 ) {
12821 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12822 }
12823
12824 pub fn expand_excerpts_up(
12825 &mut self,
12826 action: &ExpandExcerptsUp,
12827 _: &mut Window,
12828 cx: &mut Context<Self>,
12829 ) {
12830 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12831 }
12832
12833 pub fn expand_excerpts_for_direction(
12834 &mut self,
12835 lines: u32,
12836 direction: ExpandExcerptDirection,
12837
12838 cx: &mut Context<Self>,
12839 ) {
12840 let selections = self.selections.disjoint_anchors();
12841
12842 let lines = if lines == 0 {
12843 EditorSettings::get_global(cx).expand_excerpt_lines
12844 } else {
12845 lines
12846 };
12847
12848 self.buffer.update(cx, |buffer, cx| {
12849 let snapshot = buffer.snapshot(cx);
12850 let mut excerpt_ids = selections
12851 .iter()
12852 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12853 .collect::<Vec<_>>();
12854 excerpt_ids.sort();
12855 excerpt_ids.dedup();
12856 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12857 })
12858 }
12859
12860 pub fn expand_excerpt(
12861 &mut self,
12862 excerpt: ExcerptId,
12863 direction: ExpandExcerptDirection,
12864 window: &mut Window,
12865 cx: &mut Context<Self>,
12866 ) {
12867 let current_scroll_position = self.scroll_position(cx);
12868 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
12869 let mut should_scroll_up = false;
12870
12871 if direction == ExpandExcerptDirection::Down {
12872 let multi_buffer = self.buffer.read(cx);
12873 let snapshot = multi_buffer.snapshot(cx);
12874 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
12875 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12876 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
12877 let buffer_snapshot = buffer.read(cx).snapshot();
12878 let excerpt_end_row =
12879 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
12880 let last_row = buffer_snapshot.max_point().row;
12881 let lines_below = last_row.saturating_sub(excerpt_end_row);
12882 should_scroll_up = lines_below >= lines_to_expand;
12883 }
12884 }
12885 }
12886 }
12887
12888 self.buffer.update(cx, |buffer, cx| {
12889 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
12890 });
12891
12892 if should_scroll_up {
12893 let new_scroll_position =
12894 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
12895 self.set_scroll_position(new_scroll_position, window, cx);
12896 }
12897 }
12898
12899 pub fn go_to_singleton_buffer_point(
12900 &mut self,
12901 point: Point,
12902 window: &mut Window,
12903 cx: &mut Context<Self>,
12904 ) {
12905 self.go_to_singleton_buffer_range(point..point, window, cx);
12906 }
12907
12908 pub fn go_to_singleton_buffer_range(
12909 &mut self,
12910 range: Range<Point>,
12911 window: &mut Window,
12912 cx: &mut Context<Self>,
12913 ) {
12914 let multibuffer = self.buffer().read(cx);
12915 let Some(buffer) = multibuffer.as_singleton() else {
12916 return;
12917 };
12918 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12919 return;
12920 };
12921 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12922 return;
12923 };
12924 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12925 s.select_anchor_ranges([start..end])
12926 });
12927 }
12928
12929 fn go_to_diagnostic(
12930 &mut self,
12931 _: &GoToDiagnostic,
12932 window: &mut Window,
12933 cx: &mut Context<Self>,
12934 ) {
12935 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12936 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12937 }
12938
12939 fn go_to_prev_diagnostic(
12940 &mut self,
12941 _: &GoToPreviousDiagnostic,
12942 window: &mut Window,
12943 cx: &mut Context<Self>,
12944 ) {
12945 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12946 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12947 }
12948
12949 pub fn go_to_diagnostic_impl(
12950 &mut self,
12951 direction: Direction,
12952 window: &mut Window,
12953 cx: &mut Context<Self>,
12954 ) {
12955 let buffer = self.buffer.read(cx).snapshot(cx);
12956 let selection = self.selections.newest::<usize>(cx);
12957 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12958 if direction == Direction::Next {
12959 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12960 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12961 return;
12962 };
12963 self.activate_diagnostics(
12964 buffer_id,
12965 popover.local_diagnostic.diagnostic.group_id,
12966 window,
12967 cx,
12968 );
12969 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12970 let primary_range_start = active_diagnostics.primary_range.start;
12971 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12972 let mut new_selection = s.newest_anchor().clone();
12973 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12974 s.select_anchors(vec![new_selection.clone()]);
12975 });
12976 self.refresh_inline_completion(false, true, window, cx);
12977 }
12978 return;
12979 }
12980 }
12981
12982 let active_group_id = self
12983 .active_diagnostics
12984 .as_ref()
12985 .map(|active_group| active_group.group_id);
12986 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12987 active_diagnostics
12988 .primary_range
12989 .to_offset(&buffer)
12990 .to_inclusive()
12991 });
12992 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12993 if active_primary_range.contains(&selection.head()) {
12994 *active_primary_range.start()
12995 } else {
12996 selection.head()
12997 }
12998 } else {
12999 selection.head()
13000 };
13001
13002 let snapshot = self.snapshot(window, cx);
13003 let primary_diagnostics_before = buffer
13004 .diagnostics_in_range::<usize>(0..search_start)
13005 .filter(|entry| entry.diagnostic.is_primary)
13006 .filter(|entry| entry.range.start != entry.range.end)
13007 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13008 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
13009 .collect::<Vec<_>>();
13010 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
13011 primary_diagnostics_before
13012 .iter()
13013 .position(|entry| entry.diagnostic.group_id == active_group_id)
13014 });
13015
13016 let primary_diagnostics_after = buffer
13017 .diagnostics_in_range::<usize>(search_start..buffer.len())
13018 .filter(|entry| entry.diagnostic.is_primary)
13019 .filter(|entry| entry.range.start != entry.range.end)
13020 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13021 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
13022 .collect::<Vec<_>>();
13023 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
13024 primary_diagnostics_after
13025 .iter()
13026 .enumerate()
13027 .rev()
13028 .find_map(|(i, entry)| {
13029 if entry.diagnostic.group_id == active_group_id {
13030 Some(i)
13031 } else {
13032 None
13033 }
13034 })
13035 });
13036
13037 let next_primary_diagnostic = match direction {
13038 Direction::Prev => primary_diagnostics_before
13039 .iter()
13040 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
13041 .rev()
13042 .next(),
13043 Direction::Next => primary_diagnostics_after
13044 .iter()
13045 .skip(
13046 last_same_group_diagnostic_after
13047 .map(|index| index + 1)
13048 .unwrap_or(0),
13049 )
13050 .next(),
13051 };
13052
13053 // Cycle around to the start of the buffer, potentially moving back to the start of
13054 // the currently active diagnostic.
13055 let cycle_around = || match direction {
13056 Direction::Prev => primary_diagnostics_after
13057 .iter()
13058 .rev()
13059 .chain(primary_diagnostics_before.iter().rev())
13060 .next(),
13061 Direction::Next => primary_diagnostics_before
13062 .iter()
13063 .chain(primary_diagnostics_after.iter())
13064 .next(),
13065 };
13066
13067 if let Some((primary_range, group_id)) = next_primary_diagnostic
13068 .or_else(cycle_around)
13069 .map(|entry| (&entry.range, entry.diagnostic.group_id))
13070 {
13071 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
13072 return;
13073 };
13074 self.activate_diagnostics(buffer_id, group_id, window, cx);
13075 if self.active_diagnostics.is_some() {
13076 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13077 s.select(vec![Selection {
13078 id: selection.id,
13079 start: primary_range.start,
13080 end: primary_range.start,
13081 reversed: false,
13082 goal: SelectionGoal::None,
13083 }]);
13084 });
13085 self.refresh_inline_completion(false, true, window, cx);
13086 }
13087 }
13088 }
13089
13090 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13091 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13092 let snapshot = self.snapshot(window, cx);
13093 let selection = self.selections.newest::<Point>(cx);
13094 self.go_to_hunk_before_or_after_position(
13095 &snapshot,
13096 selection.head(),
13097 Direction::Next,
13098 window,
13099 cx,
13100 );
13101 }
13102
13103 pub fn go_to_hunk_before_or_after_position(
13104 &mut self,
13105 snapshot: &EditorSnapshot,
13106 position: Point,
13107 direction: Direction,
13108 window: &mut Window,
13109 cx: &mut Context<Editor>,
13110 ) {
13111 let row = if direction == Direction::Next {
13112 self.hunk_after_position(snapshot, position)
13113 .map(|hunk| hunk.row_range.start)
13114 } else {
13115 self.hunk_before_position(snapshot, position)
13116 };
13117
13118 if let Some(row) = row {
13119 let destination = Point::new(row.0, 0);
13120 let autoscroll = Autoscroll::center();
13121
13122 self.unfold_ranges(&[destination..destination], false, false, cx);
13123 self.change_selections(Some(autoscroll), window, cx, |s| {
13124 s.select_ranges([destination..destination]);
13125 });
13126 }
13127 }
13128
13129 fn hunk_after_position(
13130 &mut self,
13131 snapshot: &EditorSnapshot,
13132 position: Point,
13133 ) -> Option<MultiBufferDiffHunk> {
13134 snapshot
13135 .buffer_snapshot
13136 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13137 .find(|hunk| hunk.row_range.start.0 > position.row)
13138 .or_else(|| {
13139 snapshot
13140 .buffer_snapshot
13141 .diff_hunks_in_range(Point::zero()..position)
13142 .find(|hunk| hunk.row_range.end.0 < position.row)
13143 })
13144 }
13145
13146 fn go_to_prev_hunk(
13147 &mut self,
13148 _: &GoToPreviousHunk,
13149 window: &mut Window,
13150 cx: &mut Context<Self>,
13151 ) {
13152 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13153 let snapshot = self.snapshot(window, cx);
13154 let selection = self.selections.newest::<Point>(cx);
13155 self.go_to_hunk_before_or_after_position(
13156 &snapshot,
13157 selection.head(),
13158 Direction::Prev,
13159 window,
13160 cx,
13161 );
13162 }
13163
13164 fn hunk_before_position(
13165 &mut self,
13166 snapshot: &EditorSnapshot,
13167 position: Point,
13168 ) -> Option<MultiBufferRow> {
13169 snapshot
13170 .buffer_snapshot
13171 .diff_hunk_before(position)
13172 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13173 }
13174
13175 fn go_to_line<T: 'static>(
13176 &mut self,
13177 position: Anchor,
13178 highlight_color: Option<Hsla>,
13179 window: &mut Window,
13180 cx: &mut Context<Self>,
13181 ) {
13182 let snapshot = self.snapshot(window, cx).display_snapshot;
13183 let position = position.to_point(&snapshot.buffer_snapshot);
13184 let start = snapshot
13185 .buffer_snapshot
13186 .clip_point(Point::new(position.row, 0), Bias::Left);
13187 let end = start + Point::new(1, 0);
13188 let start = snapshot.buffer_snapshot.anchor_before(start);
13189 let end = snapshot.buffer_snapshot.anchor_before(end);
13190
13191 self.highlight_rows::<T>(
13192 start..end,
13193 highlight_color
13194 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13195 false,
13196 cx,
13197 );
13198 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13199 }
13200
13201 pub fn go_to_definition(
13202 &mut self,
13203 _: &GoToDefinition,
13204 window: &mut Window,
13205 cx: &mut Context<Self>,
13206 ) -> Task<Result<Navigated>> {
13207 let definition =
13208 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13209 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13210 cx.spawn_in(window, async move |editor, cx| {
13211 if definition.await? == Navigated::Yes {
13212 return Ok(Navigated::Yes);
13213 }
13214 match fallback_strategy {
13215 GoToDefinitionFallback::None => Ok(Navigated::No),
13216 GoToDefinitionFallback::FindAllReferences => {
13217 match editor.update_in(cx, |editor, window, cx| {
13218 editor.find_all_references(&FindAllReferences, window, cx)
13219 })? {
13220 Some(references) => references.await,
13221 None => Ok(Navigated::No),
13222 }
13223 }
13224 }
13225 })
13226 }
13227
13228 pub fn go_to_declaration(
13229 &mut self,
13230 _: &GoToDeclaration,
13231 window: &mut Window,
13232 cx: &mut Context<Self>,
13233 ) -> Task<Result<Navigated>> {
13234 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13235 }
13236
13237 pub fn go_to_declaration_split(
13238 &mut self,
13239 _: &GoToDeclaration,
13240 window: &mut Window,
13241 cx: &mut Context<Self>,
13242 ) -> Task<Result<Navigated>> {
13243 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13244 }
13245
13246 pub fn go_to_implementation(
13247 &mut self,
13248 _: &GoToImplementation,
13249 window: &mut Window,
13250 cx: &mut Context<Self>,
13251 ) -> Task<Result<Navigated>> {
13252 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13253 }
13254
13255 pub fn go_to_implementation_split(
13256 &mut self,
13257 _: &GoToImplementationSplit,
13258 window: &mut Window,
13259 cx: &mut Context<Self>,
13260 ) -> Task<Result<Navigated>> {
13261 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13262 }
13263
13264 pub fn go_to_type_definition(
13265 &mut self,
13266 _: &GoToTypeDefinition,
13267 window: &mut Window,
13268 cx: &mut Context<Self>,
13269 ) -> Task<Result<Navigated>> {
13270 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13271 }
13272
13273 pub fn go_to_definition_split(
13274 &mut self,
13275 _: &GoToDefinitionSplit,
13276 window: &mut Window,
13277 cx: &mut Context<Self>,
13278 ) -> Task<Result<Navigated>> {
13279 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13280 }
13281
13282 pub fn go_to_type_definition_split(
13283 &mut self,
13284 _: &GoToTypeDefinitionSplit,
13285 window: &mut Window,
13286 cx: &mut Context<Self>,
13287 ) -> Task<Result<Navigated>> {
13288 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13289 }
13290
13291 fn go_to_definition_of_kind(
13292 &mut self,
13293 kind: GotoDefinitionKind,
13294 split: bool,
13295 window: &mut Window,
13296 cx: &mut Context<Self>,
13297 ) -> Task<Result<Navigated>> {
13298 let Some(provider) = self.semantics_provider.clone() else {
13299 return Task::ready(Ok(Navigated::No));
13300 };
13301 let head = self.selections.newest::<usize>(cx).head();
13302 let buffer = self.buffer.read(cx);
13303 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13304 text_anchor
13305 } else {
13306 return Task::ready(Ok(Navigated::No));
13307 };
13308
13309 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13310 return Task::ready(Ok(Navigated::No));
13311 };
13312
13313 cx.spawn_in(window, async move |editor, cx| {
13314 let definitions = definitions.await?;
13315 let navigated = editor
13316 .update_in(cx, |editor, window, cx| {
13317 editor.navigate_to_hover_links(
13318 Some(kind),
13319 definitions
13320 .into_iter()
13321 .filter(|location| {
13322 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13323 })
13324 .map(HoverLink::Text)
13325 .collect::<Vec<_>>(),
13326 split,
13327 window,
13328 cx,
13329 )
13330 })?
13331 .await?;
13332 anyhow::Ok(navigated)
13333 })
13334 }
13335
13336 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13337 let selection = self.selections.newest_anchor();
13338 let head = selection.head();
13339 let tail = selection.tail();
13340
13341 let Some((buffer, start_position)) =
13342 self.buffer.read(cx).text_anchor_for_position(head, cx)
13343 else {
13344 return;
13345 };
13346
13347 let end_position = if head != tail {
13348 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13349 return;
13350 };
13351 Some(pos)
13352 } else {
13353 None
13354 };
13355
13356 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13357 let url = if let Some(end_pos) = end_position {
13358 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13359 } else {
13360 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13361 };
13362
13363 if let Some(url) = url {
13364 editor.update(cx, |_, cx| {
13365 cx.open_url(&url);
13366 })
13367 } else {
13368 Ok(())
13369 }
13370 });
13371
13372 url_finder.detach();
13373 }
13374
13375 pub fn open_selected_filename(
13376 &mut self,
13377 _: &OpenSelectedFilename,
13378 window: &mut Window,
13379 cx: &mut Context<Self>,
13380 ) {
13381 let Some(workspace) = self.workspace() else {
13382 return;
13383 };
13384
13385 let position = self.selections.newest_anchor().head();
13386
13387 let Some((buffer, buffer_position)) =
13388 self.buffer.read(cx).text_anchor_for_position(position, cx)
13389 else {
13390 return;
13391 };
13392
13393 let project = self.project.clone();
13394
13395 cx.spawn_in(window, async move |_, cx| {
13396 let result = find_file(&buffer, project, buffer_position, cx).await;
13397
13398 if let Some((_, path)) = result {
13399 workspace
13400 .update_in(cx, |workspace, window, cx| {
13401 workspace.open_resolved_path(path, window, cx)
13402 })?
13403 .await?;
13404 }
13405 anyhow::Ok(())
13406 })
13407 .detach();
13408 }
13409
13410 pub(crate) fn navigate_to_hover_links(
13411 &mut self,
13412 kind: Option<GotoDefinitionKind>,
13413 mut definitions: Vec<HoverLink>,
13414 split: bool,
13415 window: &mut Window,
13416 cx: &mut Context<Editor>,
13417 ) -> Task<Result<Navigated>> {
13418 // If there is one definition, just open it directly
13419 if definitions.len() == 1 {
13420 let definition = definitions.pop().unwrap();
13421
13422 enum TargetTaskResult {
13423 Location(Option<Location>),
13424 AlreadyNavigated,
13425 }
13426
13427 let target_task = match definition {
13428 HoverLink::Text(link) => {
13429 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13430 }
13431 HoverLink::InlayHint(lsp_location, server_id) => {
13432 let computation =
13433 self.compute_target_location(lsp_location, server_id, window, cx);
13434 cx.background_spawn(async move {
13435 let location = computation.await?;
13436 Ok(TargetTaskResult::Location(location))
13437 })
13438 }
13439 HoverLink::Url(url) => {
13440 cx.open_url(&url);
13441 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13442 }
13443 HoverLink::File(path) => {
13444 if let Some(workspace) = self.workspace() {
13445 cx.spawn_in(window, async move |_, cx| {
13446 workspace
13447 .update_in(cx, |workspace, window, cx| {
13448 workspace.open_resolved_path(path, window, cx)
13449 })?
13450 .await
13451 .map(|_| TargetTaskResult::AlreadyNavigated)
13452 })
13453 } else {
13454 Task::ready(Ok(TargetTaskResult::Location(None)))
13455 }
13456 }
13457 };
13458 cx.spawn_in(window, async move |editor, cx| {
13459 let target = match target_task.await.context("target resolution task")? {
13460 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13461 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13462 TargetTaskResult::Location(Some(target)) => target,
13463 };
13464
13465 editor.update_in(cx, |editor, window, cx| {
13466 let Some(workspace) = editor.workspace() else {
13467 return Navigated::No;
13468 };
13469 let pane = workspace.read(cx).active_pane().clone();
13470
13471 let range = target.range.to_point(target.buffer.read(cx));
13472 let range = editor.range_for_match(&range);
13473 let range = collapse_multiline_range(range);
13474
13475 if !split
13476 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13477 {
13478 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13479 } else {
13480 window.defer(cx, move |window, cx| {
13481 let target_editor: Entity<Self> =
13482 workspace.update(cx, |workspace, cx| {
13483 let pane = if split {
13484 workspace.adjacent_pane(window, cx)
13485 } else {
13486 workspace.active_pane().clone()
13487 };
13488
13489 workspace.open_project_item(
13490 pane,
13491 target.buffer.clone(),
13492 true,
13493 true,
13494 window,
13495 cx,
13496 )
13497 });
13498 target_editor.update(cx, |target_editor, cx| {
13499 // When selecting a definition in a different buffer, disable the nav history
13500 // to avoid creating a history entry at the previous cursor location.
13501 pane.update(cx, |pane, _| pane.disable_history());
13502 target_editor.go_to_singleton_buffer_range(range, window, cx);
13503 pane.update(cx, |pane, _| pane.enable_history());
13504 });
13505 });
13506 }
13507 Navigated::Yes
13508 })
13509 })
13510 } else if !definitions.is_empty() {
13511 cx.spawn_in(window, async move |editor, cx| {
13512 let (title, location_tasks, workspace) = editor
13513 .update_in(cx, |editor, window, cx| {
13514 let tab_kind = match kind {
13515 Some(GotoDefinitionKind::Implementation) => "Implementations",
13516 _ => "Definitions",
13517 };
13518 let title = definitions
13519 .iter()
13520 .find_map(|definition| match definition {
13521 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13522 let buffer = origin.buffer.read(cx);
13523 format!(
13524 "{} for {}",
13525 tab_kind,
13526 buffer
13527 .text_for_range(origin.range.clone())
13528 .collect::<String>()
13529 )
13530 }),
13531 HoverLink::InlayHint(_, _) => None,
13532 HoverLink::Url(_) => None,
13533 HoverLink::File(_) => None,
13534 })
13535 .unwrap_or(tab_kind.to_string());
13536 let location_tasks = definitions
13537 .into_iter()
13538 .map(|definition| match definition {
13539 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13540 HoverLink::InlayHint(lsp_location, server_id) => editor
13541 .compute_target_location(lsp_location, server_id, window, cx),
13542 HoverLink::Url(_) => Task::ready(Ok(None)),
13543 HoverLink::File(_) => Task::ready(Ok(None)),
13544 })
13545 .collect::<Vec<_>>();
13546 (title, location_tasks, editor.workspace().clone())
13547 })
13548 .context("location tasks preparation")?;
13549
13550 let locations = future::join_all(location_tasks)
13551 .await
13552 .into_iter()
13553 .filter_map(|location| location.transpose())
13554 .collect::<Result<_>>()
13555 .context("location tasks")?;
13556
13557 let Some(workspace) = workspace else {
13558 return Ok(Navigated::No);
13559 };
13560 let opened = workspace
13561 .update_in(cx, |workspace, window, cx| {
13562 Self::open_locations_in_multibuffer(
13563 workspace,
13564 locations,
13565 title,
13566 split,
13567 MultibufferSelectionMode::First,
13568 window,
13569 cx,
13570 )
13571 })
13572 .ok();
13573
13574 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13575 })
13576 } else {
13577 Task::ready(Ok(Navigated::No))
13578 }
13579 }
13580
13581 fn compute_target_location(
13582 &self,
13583 lsp_location: lsp::Location,
13584 server_id: LanguageServerId,
13585 window: &mut Window,
13586 cx: &mut Context<Self>,
13587 ) -> Task<anyhow::Result<Option<Location>>> {
13588 let Some(project) = self.project.clone() else {
13589 return Task::ready(Ok(None));
13590 };
13591
13592 cx.spawn_in(window, async move |editor, cx| {
13593 let location_task = editor.update(cx, |_, cx| {
13594 project.update(cx, |project, cx| {
13595 let language_server_name = project
13596 .language_server_statuses(cx)
13597 .find(|(id, _)| server_id == *id)
13598 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13599 language_server_name.map(|language_server_name| {
13600 project.open_local_buffer_via_lsp(
13601 lsp_location.uri.clone(),
13602 server_id,
13603 language_server_name,
13604 cx,
13605 )
13606 })
13607 })
13608 })?;
13609 let location = match location_task {
13610 Some(task) => Some({
13611 let target_buffer_handle = task.await.context("open local buffer")?;
13612 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13613 let target_start = target_buffer
13614 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13615 let target_end = target_buffer
13616 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13617 target_buffer.anchor_after(target_start)
13618 ..target_buffer.anchor_before(target_end)
13619 })?;
13620 Location {
13621 buffer: target_buffer_handle,
13622 range,
13623 }
13624 }),
13625 None => None,
13626 };
13627 Ok(location)
13628 })
13629 }
13630
13631 pub fn find_all_references(
13632 &mut self,
13633 _: &FindAllReferences,
13634 window: &mut Window,
13635 cx: &mut Context<Self>,
13636 ) -> Option<Task<Result<Navigated>>> {
13637 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13638
13639 let selection = self.selections.newest::<usize>(cx);
13640 let multi_buffer = self.buffer.read(cx);
13641 let head = selection.head();
13642
13643 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13644 let head_anchor = multi_buffer_snapshot.anchor_at(
13645 head,
13646 if head < selection.tail() {
13647 Bias::Right
13648 } else {
13649 Bias::Left
13650 },
13651 );
13652
13653 match self
13654 .find_all_references_task_sources
13655 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13656 {
13657 Ok(_) => {
13658 log::info!(
13659 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13660 );
13661 return None;
13662 }
13663 Err(i) => {
13664 self.find_all_references_task_sources.insert(i, head_anchor);
13665 }
13666 }
13667
13668 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13669 let workspace = self.workspace()?;
13670 let project = workspace.read(cx).project().clone();
13671 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13672 Some(cx.spawn_in(window, async move |editor, cx| {
13673 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13674 if let Ok(i) = editor
13675 .find_all_references_task_sources
13676 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13677 {
13678 editor.find_all_references_task_sources.remove(i);
13679 }
13680 });
13681
13682 let locations = references.await?;
13683 if locations.is_empty() {
13684 return anyhow::Ok(Navigated::No);
13685 }
13686
13687 workspace.update_in(cx, |workspace, window, cx| {
13688 let title = locations
13689 .first()
13690 .as_ref()
13691 .map(|location| {
13692 let buffer = location.buffer.read(cx);
13693 format!(
13694 "References to `{}`",
13695 buffer
13696 .text_for_range(location.range.clone())
13697 .collect::<String>()
13698 )
13699 })
13700 .unwrap();
13701 Self::open_locations_in_multibuffer(
13702 workspace,
13703 locations,
13704 title,
13705 false,
13706 MultibufferSelectionMode::First,
13707 window,
13708 cx,
13709 );
13710 Navigated::Yes
13711 })
13712 }))
13713 }
13714
13715 /// Opens a multibuffer with the given project locations in it
13716 pub fn open_locations_in_multibuffer(
13717 workspace: &mut Workspace,
13718 mut locations: Vec<Location>,
13719 title: String,
13720 split: bool,
13721 multibuffer_selection_mode: MultibufferSelectionMode,
13722 window: &mut Window,
13723 cx: &mut Context<Workspace>,
13724 ) {
13725 // If there are multiple definitions, open them in a multibuffer
13726 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13727 let mut locations = locations.into_iter().peekable();
13728 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13729 let capability = workspace.project().read(cx).capability();
13730
13731 let excerpt_buffer = cx.new(|cx| {
13732 let mut multibuffer = MultiBuffer::new(capability);
13733 while let Some(location) = locations.next() {
13734 let buffer = location.buffer.read(cx);
13735 let mut ranges_for_buffer = Vec::new();
13736 let range = location.range.to_point(buffer);
13737 ranges_for_buffer.push(range.clone());
13738
13739 while let Some(next_location) = locations.peek() {
13740 if next_location.buffer == location.buffer {
13741 ranges_for_buffer.push(next_location.range.to_point(buffer));
13742 locations.next();
13743 } else {
13744 break;
13745 }
13746 }
13747
13748 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13749 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13750 PathKey::for_buffer(&location.buffer, cx),
13751 location.buffer.clone(),
13752 ranges_for_buffer,
13753 DEFAULT_MULTIBUFFER_CONTEXT,
13754 cx,
13755 );
13756 ranges.extend(new_ranges)
13757 }
13758
13759 multibuffer.with_title(title)
13760 });
13761
13762 let editor = cx.new(|cx| {
13763 Editor::for_multibuffer(
13764 excerpt_buffer,
13765 Some(workspace.project().clone()),
13766 window,
13767 cx,
13768 )
13769 });
13770 editor.update(cx, |editor, cx| {
13771 match multibuffer_selection_mode {
13772 MultibufferSelectionMode::First => {
13773 if let Some(first_range) = ranges.first() {
13774 editor.change_selections(None, window, cx, |selections| {
13775 selections.clear_disjoint();
13776 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13777 });
13778 }
13779 editor.highlight_background::<Self>(
13780 &ranges,
13781 |theme| theme.editor_highlighted_line_background,
13782 cx,
13783 );
13784 }
13785 MultibufferSelectionMode::All => {
13786 editor.change_selections(None, window, cx, |selections| {
13787 selections.clear_disjoint();
13788 selections.select_anchor_ranges(ranges);
13789 });
13790 }
13791 }
13792 editor.register_buffers_with_language_servers(cx);
13793 });
13794
13795 let item = Box::new(editor);
13796 let item_id = item.item_id();
13797
13798 if split {
13799 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13800 } else {
13801 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13802 let (preview_item_id, preview_item_idx) =
13803 workspace.active_pane().update(cx, |pane, _| {
13804 (pane.preview_item_id(), pane.preview_item_idx())
13805 });
13806
13807 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13808
13809 if let Some(preview_item_id) = preview_item_id {
13810 workspace.active_pane().update(cx, |pane, cx| {
13811 pane.remove_item(preview_item_id, false, false, window, cx);
13812 });
13813 }
13814 } else {
13815 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13816 }
13817 }
13818 workspace.active_pane().update(cx, |pane, cx| {
13819 pane.set_preview_item_id(Some(item_id), cx);
13820 });
13821 }
13822
13823 pub fn rename(
13824 &mut self,
13825 _: &Rename,
13826 window: &mut Window,
13827 cx: &mut Context<Self>,
13828 ) -> Option<Task<Result<()>>> {
13829 use language::ToOffset as _;
13830
13831 let provider = self.semantics_provider.clone()?;
13832 let selection = self.selections.newest_anchor().clone();
13833 let (cursor_buffer, cursor_buffer_position) = self
13834 .buffer
13835 .read(cx)
13836 .text_anchor_for_position(selection.head(), cx)?;
13837 let (tail_buffer, cursor_buffer_position_end) = self
13838 .buffer
13839 .read(cx)
13840 .text_anchor_for_position(selection.tail(), cx)?;
13841 if tail_buffer != cursor_buffer {
13842 return None;
13843 }
13844
13845 let snapshot = cursor_buffer.read(cx).snapshot();
13846 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13847 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13848 let prepare_rename = provider
13849 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13850 .unwrap_or_else(|| Task::ready(Ok(None)));
13851 drop(snapshot);
13852
13853 Some(cx.spawn_in(window, async move |this, cx| {
13854 let rename_range = if let Some(range) = prepare_rename.await? {
13855 Some(range)
13856 } else {
13857 this.update(cx, |this, cx| {
13858 let buffer = this.buffer.read(cx).snapshot(cx);
13859 let mut buffer_highlights = this
13860 .document_highlights_for_position(selection.head(), &buffer)
13861 .filter(|highlight| {
13862 highlight.start.excerpt_id == selection.head().excerpt_id
13863 && highlight.end.excerpt_id == selection.head().excerpt_id
13864 });
13865 buffer_highlights
13866 .next()
13867 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13868 })?
13869 };
13870 if let Some(rename_range) = rename_range {
13871 this.update_in(cx, |this, window, cx| {
13872 let snapshot = cursor_buffer.read(cx).snapshot();
13873 let rename_buffer_range = rename_range.to_offset(&snapshot);
13874 let cursor_offset_in_rename_range =
13875 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13876 let cursor_offset_in_rename_range_end =
13877 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13878
13879 this.take_rename(false, window, cx);
13880 let buffer = this.buffer.read(cx).read(cx);
13881 let cursor_offset = selection.head().to_offset(&buffer);
13882 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13883 let rename_end = rename_start + rename_buffer_range.len();
13884 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13885 let mut old_highlight_id = None;
13886 let old_name: Arc<str> = buffer
13887 .chunks(rename_start..rename_end, true)
13888 .map(|chunk| {
13889 if old_highlight_id.is_none() {
13890 old_highlight_id = chunk.syntax_highlight_id;
13891 }
13892 chunk.text
13893 })
13894 .collect::<String>()
13895 .into();
13896
13897 drop(buffer);
13898
13899 // Position the selection in the rename editor so that it matches the current selection.
13900 this.show_local_selections = false;
13901 let rename_editor = cx.new(|cx| {
13902 let mut editor = Editor::single_line(window, cx);
13903 editor.buffer.update(cx, |buffer, cx| {
13904 buffer.edit([(0..0, old_name.clone())], None, cx)
13905 });
13906 let rename_selection_range = match cursor_offset_in_rename_range
13907 .cmp(&cursor_offset_in_rename_range_end)
13908 {
13909 Ordering::Equal => {
13910 editor.select_all(&SelectAll, window, cx);
13911 return editor;
13912 }
13913 Ordering::Less => {
13914 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13915 }
13916 Ordering::Greater => {
13917 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13918 }
13919 };
13920 if rename_selection_range.end > old_name.len() {
13921 editor.select_all(&SelectAll, window, cx);
13922 } else {
13923 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13924 s.select_ranges([rename_selection_range]);
13925 });
13926 }
13927 editor
13928 });
13929 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13930 if e == &EditorEvent::Focused {
13931 cx.emit(EditorEvent::FocusedIn)
13932 }
13933 })
13934 .detach();
13935
13936 let write_highlights =
13937 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13938 let read_highlights =
13939 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13940 let ranges = write_highlights
13941 .iter()
13942 .flat_map(|(_, ranges)| ranges.iter())
13943 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13944 .cloned()
13945 .collect();
13946
13947 this.highlight_text::<Rename>(
13948 ranges,
13949 HighlightStyle {
13950 fade_out: Some(0.6),
13951 ..Default::default()
13952 },
13953 cx,
13954 );
13955 let rename_focus_handle = rename_editor.focus_handle(cx);
13956 window.focus(&rename_focus_handle);
13957 let block_id = this.insert_blocks(
13958 [BlockProperties {
13959 style: BlockStyle::Flex,
13960 placement: BlockPlacement::Below(range.start),
13961 height: Some(1),
13962 render: Arc::new({
13963 let rename_editor = rename_editor.clone();
13964 move |cx: &mut BlockContext| {
13965 let mut text_style = cx.editor_style.text.clone();
13966 if let Some(highlight_style) = old_highlight_id
13967 .and_then(|h| h.style(&cx.editor_style.syntax))
13968 {
13969 text_style = text_style.highlight(highlight_style);
13970 }
13971 div()
13972 .block_mouse_down()
13973 .pl(cx.anchor_x)
13974 .child(EditorElement::new(
13975 &rename_editor,
13976 EditorStyle {
13977 background: cx.theme().system().transparent,
13978 local_player: cx.editor_style.local_player,
13979 text: text_style,
13980 scrollbar_width: cx.editor_style.scrollbar_width,
13981 syntax: cx.editor_style.syntax.clone(),
13982 status: cx.editor_style.status.clone(),
13983 inlay_hints_style: HighlightStyle {
13984 font_weight: Some(FontWeight::BOLD),
13985 ..make_inlay_hints_style(cx.app)
13986 },
13987 inline_completion_styles: make_suggestion_styles(
13988 cx.app,
13989 ),
13990 ..EditorStyle::default()
13991 },
13992 ))
13993 .into_any_element()
13994 }
13995 }),
13996 priority: 0,
13997 }],
13998 Some(Autoscroll::fit()),
13999 cx,
14000 )[0];
14001 this.pending_rename = Some(RenameState {
14002 range,
14003 old_name,
14004 editor: rename_editor,
14005 block_id,
14006 });
14007 })?;
14008 }
14009
14010 Ok(())
14011 }))
14012 }
14013
14014 pub fn confirm_rename(
14015 &mut self,
14016 _: &ConfirmRename,
14017 window: &mut Window,
14018 cx: &mut Context<Self>,
14019 ) -> Option<Task<Result<()>>> {
14020 let rename = self.take_rename(false, window, cx)?;
14021 let workspace = self.workspace()?.downgrade();
14022 let (buffer, start) = self
14023 .buffer
14024 .read(cx)
14025 .text_anchor_for_position(rename.range.start, cx)?;
14026 let (end_buffer, _) = self
14027 .buffer
14028 .read(cx)
14029 .text_anchor_for_position(rename.range.end, cx)?;
14030 if buffer != end_buffer {
14031 return None;
14032 }
14033
14034 let old_name = rename.old_name;
14035 let new_name = rename.editor.read(cx).text(cx);
14036
14037 let rename = self.semantics_provider.as_ref()?.perform_rename(
14038 &buffer,
14039 start,
14040 new_name.clone(),
14041 cx,
14042 )?;
14043
14044 Some(cx.spawn_in(window, async move |editor, cx| {
14045 let project_transaction = rename.await?;
14046 Self::open_project_transaction(
14047 &editor,
14048 workspace,
14049 project_transaction,
14050 format!("Rename: {} → {}", old_name, new_name),
14051 cx,
14052 )
14053 .await?;
14054
14055 editor.update(cx, |editor, cx| {
14056 editor.refresh_document_highlights(cx);
14057 })?;
14058 Ok(())
14059 }))
14060 }
14061
14062 fn take_rename(
14063 &mut self,
14064 moving_cursor: bool,
14065 window: &mut Window,
14066 cx: &mut Context<Self>,
14067 ) -> Option<RenameState> {
14068 let rename = self.pending_rename.take()?;
14069 if rename.editor.focus_handle(cx).is_focused(window) {
14070 window.focus(&self.focus_handle);
14071 }
14072
14073 self.remove_blocks(
14074 [rename.block_id].into_iter().collect(),
14075 Some(Autoscroll::fit()),
14076 cx,
14077 );
14078 self.clear_highlights::<Rename>(cx);
14079 self.show_local_selections = true;
14080
14081 if moving_cursor {
14082 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14083 editor.selections.newest::<usize>(cx).head()
14084 });
14085
14086 // Update the selection to match the position of the selection inside
14087 // the rename editor.
14088 let snapshot = self.buffer.read(cx).read(cx);
14089 let rename_range = rename.range.to_offset(&snapshot);
14090 let cursor_in_editor = snapshot
14091 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14092 .min(rename_range.end);
14093 drop(snapshot);
14094
14095 self.change_selections(None, window, cx, |s| {
14096 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14097 });
14098 } else {
14099 self.refresh_document_highlights(cx);
14100 }
14101
14102 Some(rename)
14103 }
14104
14105 pub fn pending_rename(&self) -> Option<&RenameState> {
14106 self.pending_rename.as_ref()
14107 }
14108
14109 fn format(
14110 &mut self,
14111 _: &Format,
14112 window: &mut Window,
14113 cx: &mut Context<Self>,
14114 ) -> Option<Task<Result<()>>> {
14115 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14116
14117 let project = match &self.project {
14118 Some(project) => project.clone(),
14119 None => return None,
14120 };
14121
14122 Some(self.perform_format(
14123 project,
14124 FormatTrigger::Manual,
14125 FormatTarget::Buffers,
14126 window,
14127 cx,
14128 ))
14129 }
14130
14131 fn format_selections(
14132 &mut self,
14133 _: &FormatSelections,
14134 window: &mut Window,
14135 cx: &mut Context<Self>,
14136 ) -> Option<Task<Result<()>>> {
14137 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14138
14139 let project = match &self.project {
14140 Some(project) => project.clone(),
14141 None => return None,
14142 };
14143
14144 let ranges = self
14145 .selections
14146 .all_adjusted(cx)
14147 .into_iter()
14148 .map(|selection| selection.range())
14149 .collect_vec();
14150
14151 Some(self.perform_format(
14152 project,
14153 FormatTrigger::Manual,
14154 FormatTarget::Ranges(ranges),
14155 window,
14156 cx,
14157 ))
14158 }
14159
14160 fn perform_format(
14161 &mut self,
14162 project: Entity<Project>,
14163 trigger: FormatTrigger,
14164 target: FormatTarget,
14165 window: &mut Window,
14166 cx: &mut Context<Self>,
14167 ) -> Task<Result<()>> {
14168 let buffer = self.buffer.clone();
14169 let (buffers, target) = match target {
14170 FormatTarget::Buffers => {
14171 let mut buffers = buffer.read(cx).all_buffers();
14172 if trigger == FormatTrigger::Save {
14173 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14174 }
14175 (buffers, LspFormatTarget::Buffers)
14176 }
14177 FormatTarget::Ranges(selection_ranges) => {
14178 let multi_buffer = buffer.read(cx);
14179 let snapshot = multi_buffer.read(cx);
14180 let mut buffers = HashSet::default();
14181 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14182 BTreeMap::new();
14183 for selection_range in selection_ranges {
14184 for (buffer, buffer_range, _) in
14185 snapshot.range_to_buffer_ranges(selection_range)
14186 {
14187 let buffer_id = buffer.remote_id();
14188 let start = buffer.anchor_before(buffer_range.start);
14189 let end = buffer.anchor_after(buffer_range.end);
14190 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14191 buffer_id_to_ranges
14192 .entry(buffer_id)
14193 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14194 .or_insert_with(|| vec![start..end]);
14195 }
14196 }
14197 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14198 }
14199 };
14200
14201 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14202 let selections_prev = transaction_id_prev
14203 .and_then(|transaction_id_prev| {
14204 // default to selections as they were after the last edit, if we have them,
14205 // instead of how they are now.
14206 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14207 // will take you back to where you made the last edit, instead of staying where you scrolled
14208 self.selection_history
14209 .transaction(transaction_id_prev)
14210 .map(|t| t.0.clone())
14211 })
14212 .unwrap_or_else(|| {
14213 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14214 self.selections.disjoint_anchors()
14215 });
14216
14217 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14218 let format = project.update(cx, |project, cx| {
14219 project.format(buffers, target, true, trigger, cx)
14220 });
14221
14222 cx.spawn_in(window, async move |editor, cx| {
14223 let transaction = futures::select_biased! {
14224 transaction = format.log_err().fuse() => transaction,
14225 () = timeout => {
14226 log::warn!("timed out waiting for formatting");
14227 None
14228 }
14229 };
14230
14231 buffer
14232 .update(cx, |buffer, cx| {
14233 if let Some(transaction) = transaction {
14234 if !buffer.is_singleton() {
14235 buffer.push_transaction(&transaction.0, cx);
14236 }
14237 }
14238 cx.notify();
14239 })
14240 .ok();
14241
14242 if let Some(transaction_id_now) =
14243 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14244 {
14245 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14246 if has_new_transaction {
14247 _ = editor.update(cx, |editor, _| {
14248 editor
14249 .selection_history
14250 .insert_transaction(transaction_id_now, selections_prev);
14251 });
14252 }
14253 }
14254
14255 Ok(())
14256 })
14257 }
14258
14259 fn organize_imports(
14260 &mut self,
14261 _: &OrganizeImports,
14262 window: &mut Window,
14263 cx: &mut Context<Self>,
14264 ) -> Option<Task<Result<()>>> {
14265 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14266 let project = match &self.project {
14267 Some(project) => project.clone(),
14268 None => return None,
14269 };
14270 Some(self.perform_code_action_kind(
14271 project,
14272 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14273 window,
14274 cx,
14275 ))
14276 }
14277
14278 fn perform_code_action_kind(
14279 &mut self,
14280 project: Entity<Project>,
14281 kind: CodeActionKind,
14282 window: &mut Window,
14283 cx: &mut Context<Self>,
14284 ) -> Task<Result<()>> {
14285 let buffer = self.buffer.clone();
14286 let buffers = buffer.read(cx).all_buffers();
14287 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14288 let apply_action = project.update(cx, |project, cx| {
14289 project.apply_code_action_kind(buffers, kind, true, cx)
14290 });
14291 cx.spawn_in(window, async move |_, cx| {
14292 let transaction = futures::select_biased! {
14293 () = timeout => {
14294 log::warn!("timed out waiting for executing code action");
14295 None
14296 }
14297 transaction = apply_action.log_err().fuse() => transaction,
14298 };
14299 buffer
14300 .update(cx, |buffer, cx| {
14301 // check if we need this
14302 if let Some(transaction) = transaction {
14303 if !buffer.is_singleton() {
14304 buffer.push_transaction(&transaction.0, cx);
14305 }
14306 }
14307 cx.notify();
14308 })
14309 .ok();
14310 Ok(())
14311 })
14312 }
14313
14314 fn restart_language_server(
14315 &mut self,
14316 _: &RestartLanguageServer,
14317 _: &mut Window,
14318 cx: &mut Context<Self>,
14319 ) {
14320 if let Some(project) = self.project.clone() {
14321 self.buffer.update(cx, |multi_buffer, cx| {
14322 project.update(cx, |project, cx| {
14323 project.restart_language_servers_for_buffers(
14324 multi_buffer.all_buffers().into_iter().collect(),
14325 cx,
14326 );
14327 });
14328 })
14329 }
14330 }
14331
14332 fn stop_language_server(
14333 &mut self,
14334 _: &StopLanguageServer,
14335 _: &mut Window,
14336 cx: &mut Context<Self>,
14337 ) {
14338 if let Some(project) = self.project.clone() {
14339 self.buffer.update(cx, |multi_buffer, cx| {
14340 project.update(cx, |project, cx| {
14341 project.stop_language_servers_for_buffers(
14342 multi_buffer.all_buffers().into_iter().collect(),
14343 cx,
14344 );
14345 cx.emit(project::Event::RefreshInlayHints);
14346 });
14347 });
14348 }
14349 }
14350
14351 fn cancel_language_server_work(
14352 workspace: &mut Workspace,
14353 _: &actions::CancelLanguageServerWork,
14354 _: &mut Window,
14355 cx: &mut Context<Workspace>,
14356 ) {
14357 let project = workspace.project();
14358 let buffers = workspace
14359 .active_item(cx)
14360 .and_then(|item| item.act_as::<Editor>(cx))
14361 .map_or(HashSet::default(), |editor| {
14362 editor.read(cx).buffer.read(cx).all_buffers()
14363 });
14364 project.update(cx, |project, cx| {
14365 project.cancel_language_server_work_for_buffers(buffers, cx);
14366 });
14367 }
14368
14369 fn show_character_palette(
14370 &mut self,
14371 _: &ShowCharacterPalette,
14372 window: &mut Window,
14373 _: &mut Context<Self>,
14374 ) {
14375 window.show_character_palette();
14376 }
14377
14378 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14379 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14380 let buffer = self.buffer.read(cx).snapshot(cx);
14381 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14382 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14383 let is_valid = buffer
14384 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14385 .any(|entry| {
14386 entry.diagnostic.is_primary
14387 && !entry.range.is_empty()
14388 && entry.range.start == primary_range_start
14389 && entry.diagnostic.message == active_diagnostics.primary_message
14390 });
14391
14392 if is_valid != active_diagnostics.is_valid {
14393 active_diagnostics.is_valid = is_valid;
14394 if is_valid {
14395 let mut new_styles = HashMap::default();
14396 for (block_id, diagnostic) in &active_diagnostics.blocks {
14397 new_styles.insert(
14398 *block_id,
14399 diagnostic_block_renderer(diagnostic.clone(), None, true),
14400 );
14401 }
14402 self.display_map.update(cx, |display_map, _cx| {
14403 display_map.replace_blocks(new_styles);
14404 });
14405 } else {
14406 self.dismiss_diagnostics(cx);
14407 }
14408 }
14409 }
14410 }
14411
14412 fn activate_diagnostics(
14413 &mut self,
14414 buffer_id: BufferId,
14415 group_id: usize,
14416 window: &mut Window,
14417 cx: &mut Context<Self>,
14418 ) {
14419 self.dismiss_diagnostics(cx);
14420 let snapshot = self.snapshot(window, cx);
14421 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14422 let buffer = self.buffer.read(cx).snapshot(cx);
14423
14424 let mut primary_range = None;
14425 let mut primary_message = None;
14426 let diagnostic_group = buffer
14427 .diagnostic_group(buffer_id, group_id)
14428 .filter_map(|entry| {
14429 let start = entry.range.start;
14430 let end = entry.range.end;
14431 if snapshot.is_line_folded(MultiBufferRow(start.row))
14432 && (start.row == end.row
14433 || snapshot.is_line_folded(MultiBufferRow(end.row)))
14434 {
14435 return None;
14436 }
14437 if entry.diagnostic.is_primary {
14438 primary_range = Some(entry.range.clone());
14439 primary_message = Some(entry.diagnostic.message.clone());
14440 }
14441 Some(entry)
14442 })
14443 .collect::<Vec<_>>();
14444 let primary_range = primary_range?;
14445 let primary_message = primary_message?;
14446
14447 let blocks = display_map
14448 .insert_blocks(
14449 diagnostic_group.iter().map(|entry| {
14450 let diagnostic = entry.diagnostic.clone();
14451 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14452 BlockProperties {
14453 style: BlockStyle::Fixed,
14454 placement: BlockPlacement::Below(
14455 buffer.anchor_after(entry.range.start),
14456 ),
14457 height: Some(message_height),
14458 render: diagnostic_block_renderer(diagnostic, None, true),
14459 priority: 0,
14460 }
14461 }),
14462 cx,
14463 )
14464 .into_iter()
14465 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14466 .collect();
14467
14468 Some(ActiveDiagnosticGroup {
14469 primary_range: buffer.anchor_before(primary_range.start)
14470 ..buffer.anchor_after(primary_range.end),
14471 primary_message,
14472 group_id,
14473 blocks,
14474 is_valid: true,
14475 })
14476 });
14477 }
14478
14479 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14480 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14481 self.display_map.update(cx, |display_map, cx| {
14482 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14483 });
14484 cx.notify();
14485 }
14486 }
14487
14488 /// Disable inline diagnostics rendering for this editor.
14489 pub fn disable_inline_diagnostics(&mut self) {
14490 self.inline_diagnostics_enabled = false;
14491 self.inline_diagnostics_update = Task::ready(());
14492 self.inline_diagnostics.clear();
14493 }
14494
14495 pub fn inline_diagnostics_enabled(&self) -> bool {
14496 self.inline_diagnostics_enabled
14497 }
14498
14499 pub fn show_inline_diagnostics(&self) -> bool {
14500 self.show_inline_diagnostics
14501 }
14502
14503 pub fn toggle_inline_diagnostics(
14504 &mut self,
14505 _: &ToggleInlineDiagnostics,
14506 window: &mut Window,
14507 cx: &mut Context<Editor>,
14508 ) {
14509 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14510 self.refresh_inline_diagnostics(false, window, cx);
14511 }
14512
14513 fn refresh_inline_diagnostics(
14514 &mut self,
14515 debounce: bool,
14516 window: &mut Window,
14517 cx: &mut Context<Self>,
14518 ) {
14519 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14520 self.inline_diagnostics_update = Task::ready(());
14521 self.inline_diagnostics.clear();
14522 return;
14523 }
14524
14525 let debounce_ms = ProjectSettings::get_global(cx)
14526 .diagnostics
14527 .inline
14528 .update_debounce_ms;
14529 let debounce = if debounce && debounce_ms > 0 {
14530 Some(Duration::from_millis(debounce_ms))
14531 } else {
14532 None
14533 };
14534 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14535 if let Some(debounce) = debounce {
14536 cx.background_executor().timer(debounce).await;
14537 }
14538 let Some(snapshot) = editor
14539 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14540 .ok()
14541 else {
14542 return;
14543 };
14544
14545 let new_inline_diagnostics = cx
14546 .background_spawn(async move {
14547 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14548 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14549 let message = diagnostic_entry
14550 .diagnostic
14551 .message
14552 .split_once('\n')
14553 .map(|(line, _)| line)
14554 .map(SharedString::new)
14555 .unwrap_or_else(|| {
14556 SharedString::from(diagnostic_entry.diagnostic.message)
14557 });
14558 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14559 let (Ok(i) | Err(i)) = inline_diagnostics
14560 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14561 inline_diagnostics.insert(
14562 i,
14563 (
14564 start_anchor,
14565 InlineDiagnostic {
14566 message,
14567 group_id: diagnostic_entry.diagnostic.group_id,
14568 start: diagnostic_entry.range.start.to_point(&snapshot),
14569 is_primary: diagnostic_entry.diagnostic.is_primary,
14570 severity: diagnostic_entry.diagnostic.severity,
14571 },
14572 ),
14573 );
14574 }
14575 inline_diagnostics
14576 })
14577 .await;
14578
14579 editor
14580 .update(cx, |editor, cx| {
14581 editor.inline_diagnostics = new_inline_diagnostics;
14582 cx.notify();
14583 })
14584 .ok();
14585 });
14586 }
14587
14588 pub fn set_selections_from_remote(
14589 &mut self,
14590 selections: Vec<Selection<Anchor>>,
14591 pending_selection: Option<Selection<Anchor>>,
14592 window: &mut Window,
14593 cx: &mut Context<Self>,
14594 ) {
14595 let old_cursor_position = self.selections.newest_anchor().head();
14596 self.selections.change_with(cx, |s| {
14597 s.select_anchors(selections);
14598 if let Some(pending_selection) = pending_selection {
14599 s.set_pending(pending_selection, SelectMode::Character);
14600 } else {
14601 s.clear_pending();
14602 }
14603 });
14604 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14605 }
14606
14607 fn push_to_selection_history(&mut self) {
14608 self.selection_history.push(SelectionHistoryEntry {
14609 selections: self.selections.disjoint_anchors(),
14610 select_next_state: self.select_next_state.clone(),
14611 select_prev_state: self.select_prev_state.clone(),
14612 add_selections_state: self.add_selections_state.clone(),
14613 });
14614 }
14615
14616 pub fn transact(
14617 &mut self,
14618 window: &mut Window,
14619 cx: &mut Context<Self>,
14620 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14621 ) -> Option<TransactionId> {
14622 self.start_transaction_at(Instant::now(), window, cx);
14623 update(self, window, cx);
14624 self.end_transaction_at(Instant::now(), cx)
14625 }
14626
14627 pub fn start_transaction_at(
14628 &mut self,
14629 now: Instant,
14630 window: &mut Window,
14631 cx: &mut Context<Self>,
14632 ) {
14633 self.end_selection(window, cx);
14634 if let Some(tx_id) = self
14635 .buffer
14636 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14637 {
14638 self.selection_history
14639 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14640 cx.emit(EditorEvent::TransactionBegun {
14641 transaction_id: tx_id,
14642 })
14643 }
14644 }
14645
14646 pub fn end_transaction_at(
14647 &mut self,
14648 now: Instant,
14649 cx: &mut Context<Self>,
14650 ) -> Option<TransactionId> {
14651 if let Some(transaction_id) = self
14652 .buffer
14653 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14654 {
14655 if let Some((_, end_selections)) =
14656 self.selection_history.transaction_mut(transaction_id)
14657 {
14658 *end_selections = Some(self.selections.disjoint_anchors());
14659 } else {
14660 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14661 }
14662
14663 cx.emit(EditorEvent::Edited { transaction_id });
14664 Some(transaction_id)
14665 } else {
14666 None
14667 }
14668 }
14669
14670 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14671 if self.selection_mark_mode {
14672 self.change_selections(None, window, cx, |s| {
14673 s.move_with(|_, sel| {
14674 sel.collapse_to(sel.head(), SelectionGoal::None);
14675 });
14676 })
14677 }
14678 self.selection_mark_mode = true;
14679 cx.notify();
14680 }
14681
14682 pub fn swap_selection_ends(
14683 &mut self,
14684 _: &actions::SwapSelectionEnds,
14685 window: &mut Window,
14686 cx: &mut Context<Self>,
14687 ) {
14688 self.change_selections(None, window, cx, |s| {
14689 s.move_with(|_, sel| {
14690 if sel.start != sel.end {
14691 sel.reversed = !sel.reversed
14692 }
14693 });
14694 });
14695 self.request_autoscroll(Autoscroll::newest(), cx);
14696 cx.notify();
14697 }
14698
14699 pub fn toggle_fold(
14700 &mut self,
14701 _: &actions::ToggleFold,
14702 window: &mut Window,
14703 cx: &mut Context<Self>,
14704 ) {
14705 if self.is_singleton(cx) {
14706 let selection = self.selections.newest::<Point>(cx);
14707
14708 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14709 let range = if selection.is_empty() {
14710 let point = selection.head().to_display_point(&display_map);
14711 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14712 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14713 .to_point(&display_map);
14714 start..end
14715 } else {
14716 selection.range()
14717 };
14718 if display_map.folds_in_range(range).next().is_some() {
14719 self.unfold_lines(&Default::default(), window, cx)
14720 } else {
14721 self.fold(&Default::default(), window, cx)
14722 }
14723 } else {
14724 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14725 let buffer_ids: HashSet<_> = self
14726 .selections
14727 .disjoint_anchor_ranges()
14728 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14729 .collect();
14730
14731 let should_unfold = buffer_ids
14732 .iter()
14733 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14734
14735 for buffer_id in buffer_ids {
14736 if should_unfold {
14737 self.unfold_buffer(buffer_id, cx);
14738 } else {
14739 self.fold_buffer(buffer_id, cx);
14740 }
14741 }
14742 }
14743 }
14744
14745 pub fn toggle_fold_recursive(
14746 &mut self,
14747 _: &actions::ToggleFoldRecursive,
14748 window: &mut Window,
14749 cx: &mut Context<Self>,
14750 ) {
14751 let selection = self.selections.newest::<Point>(cx);
14752
14753 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14754 let range = if selection.is_empty() {
14755 let point = selection.head().to_display_point(&display_map);
14756 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14757 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14758 .to_point(&display_map);
14759 start..end
14760 } else {
14761 selection.range()
14762 };
14763 if display_map.folds_in_range(range).next().is_some() {
14764 self.unfold_recursive(&Default::default(), window, cx)
14765 } else {
14766 self.fold_recursive(&Default::default(), window, cx)
14767 }
14768 }
14769
14770 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14771 if self.is_singleton(cx) {
14772 let mut to_fold = Vec::new();
14773 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14774 let selections = self.selections.all_adjusted(cx);
14775
14776 for selection in selections {
14777 let range = selection.range().sorted();
14778 let buffer_start_row = range.start.row;
14779
14780 if range.start.row != range.end.row {
14781 let mut found = false;
14782 let mut row = range.start.row;
14783 while row <= range.end.row {
14784 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14785 {
14786 found = true;
14787 row = crease.range().end.row + 1;
14788 to_fold.push(crease);
14789 } else {
14790 row += 1
14791 }
14792 }
14793 if found {
14794 continue;
14795 }
14796 }
14797
14798 for row in (0..=range.start.row).rev() {
14799 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14800 if crease.range().end.row >= buffer_start_row {
14801 to_fold.push(crease);
14802 if row <= range.start.row {
14803 break;
14804 }
14805 }
14806 }
14807 }
14808 }
14809
14810 self.fold_creases(to_fold, true, window, cx);
14811 } else {
14812 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14813 let buffer_ids = self
14814 .selections
14815 .disjoint_anchor_ranges()
14816 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14817 .collect::<HashSet<_>>();
14818 for buffer_id in buffer_ids {
14819 self.fold_buffer(buffer_id, cx);
14820 }
14821 }
14822 }
14823
14824 fn fold_at_level(
14825 &mut self,
14826 fold_at: &FoldAtLevel,
14827 window: &mut Window,
14828 cx: &mut Context<Self>,
14829 ) {
14830 if !self.buffer.read(cx).is_singleton() {
14831 return;
14832 }
14833
14834 let fold_at_level = fold_at.0;
14835 let snapshot = self.buffer.read(cx).snapshot(cx);
14836 let mut to_fold = Vec::new();
14837 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14838
14839 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14840 while start_row < end_row {
14841 match self
14842 .snapshot(window, cx)
14843 .crease_for_buffer_row(MultiBufferRow(start_row))
14844 {
14845 Some(crease) => {
14846 let nested_start_row = crease.range().start.row + 1;
14847 let nested_end_row = crease.range().end.row;
14848
14849 if current_level < fold_at_level {
14850 stack.push((nested_start_row, nested_end_row, current_level + 1));
14851 } else if current_level == fold_at_level {
14852 to_fold.push(crease);
14853 }
14854
14855 start_row = nested_end_row + 1;
14856 }
14857 None => start_row += 1,
14858 }
14859 }
14860 }
14861
14862 self.fold_creases(to_fold, true, window, cx);
14863 }
14864
14865 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14866 if self.buffer.read(cx).is_singleton() {
14867 let mut fold_ranges = Vec::new();
14868 let snapshot = self.buffer.read(cx).snapshot(cx);
14869
14870 for row in 0..snapshot.max_row().0 {
14871 if let Some(foldable_range) = self
14872 .snapshot(window, cx)
14873 .crease_for_buffer_row(MultiBufferRow(row))
14874 {
14875 fold_ranges.push(foldable_range);
14876 }
14877 }
14878
14879 self.fold_creases(fold_ranges, true, window, cx);
14880 } else {
14881 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14882 editor
14883 .update_in(cx, |editor, _, cx| {
14884 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14885 editor.fold_buffer(buffer_id, cx);
14886 }
14887 })
14888 .ok();
14889 });
14890 }
14891 }
14892
14893 pub fn fold_function_bodies(
14894 &mut self,
14895 _: &actions::FoldFunctionBodies,
14896 window: &mut Window,
14897 cx: &mut Context<Self>,
14898 ) {
14899 let snapshot = self.buffer.read(cx).snapshot(cx);
14900
14901 let ranges = snapshot
14902 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14903 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14904 .collect::<Vec<_>>();
14905
14906 let creases = ranges
14907 .into_iter()
14908 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14909 .collect();
14910
14911 self.fold_creases(creases, true, window, cx);
14912 }
14913
14914 pub fn fold_recursive(
14915 &mut self,
14916 _: &actions::FoldRecursive,
14917 window: &mut Window,
14918 cx: &mut Context<Self>,
14919 ) {
14920 let mut to_fold = Vec::new();
14921 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14922 let selections = self.selections.all_adjusted(cx);
14923
14924 for selection in selections {
14925 let range = selection.range().sorted();
14926 let buffer_start_row = range.start.row;
14927
14928 if range.start.row != range.end.row {
14929 let mut found = false;
14930 for row in range.start.row..=range.end.row {
14931 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14932 found = true;
14933 to_fold.push(crease);
14934 }
14935 }
14936 if found {
14937 continue;
14938 }
14939 }
14940
14941 for row in (0..=range.start.row).rev() {
14942 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14943 if crease.range().end.row >= buffer_start_row {
14944 to_fold.push(crease);
14945 } else {
14946 break;
14947 }
14948 }
14949 }
14950 }
14951
14952 self.fold_creases(to_fold, true, window, cx);
14953 }
14954
14955 pub fn fold_at(
14956 &mut self,
14957 buffer_row: MultiBufferRow,
14958 window: &mut Window,
14959 cx: &mut Context<Self>,
14960 ) {
14961 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14962
14963 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14964 let autoscroll = self
14965 .selections
14966 .all::<Point>(cx)
14967 .iter()
14968 .any(|selection| crease.range().overlaps(&selection.range()));
14969
14970 self.fold_creases(vec![crease], autoscroll, window, cx);
14971 }
14972 }
14973
14974 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14975 if self.is_singleton(cx) {
14976 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14977 let buffer = &display_map.buffer_snapshot;
14978 let selections = self.selections.all::<Point>(cx);
14979 let ranges = selections
14980 .iter()
14981 .map(|s| {
14982 let range = s.display_range(&display_map).sorted();
14983 let mut start = range.start.to_point(&display_map);
14984 let mut end = range.end.to_point(&display_map);
14985 start.column = 0;
14986 end.column = buffer.line_len(MultiBufferRow(end.row));
14987 start..end
14988 })
14989 .collect::<Vec<_>>();
14990
14991 self.unfold_ranges(&ranges, true, true, cx);
14992 } else {
14993 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14994 let buffer_ids = self
14995 .selections
14996 .disjoint_anchor_ranges()
14997 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14998 .collect::<HashSet<_>>();
14999 for buffer_id in buffer_ids {
15000 self.unfold_buffer(buffer_id, cx);
15001 }
15002 }
15003 }
15004
15005 pub fn unfold_recursive(
15006 &mut self,
15007 _: &UnfoldRecursive,
15008 _window: &mut Window,
15009 cx: &mut Context<Self>,
15010 ) {
15011 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15012 let selections = self.selections.all::<Point>(cx);
15013 let ranges = selections
15014 .iter()
15015 .map(|s| {
15016 let mut range = s.display_range(&display_map).sorted();
15017 *range.start.column_mut() = 0;
15018 *range.end.column_mut() = display_map.line_len(range.end.row());
15019 let start = range.start.to_point(&display_map);
15020 let end = range.end.to_point(&display_map);
15021 start..end
15022 })
15023 .collect::<Vec<_>>();
15024
15025 self.unfold_ranges(&ranges, true, true, cx);
15026 }
15027
15028 pub fn unfold_at(
15029 &mut self,
15030 buffer_row: MultiBufferRow,
15031 _window: &mut Window,
15032 cx: &mut Context<Self>,
15033 ) {
15034 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15035
15036 let intersection_range = Point::new(buffer_row.0, 0)
15037 ..Point::new(
15038 buffer_row.0,
15039 display_map.buffer_snapshot.line_len(buffer_row),
15040 );
15041
15042 let autoscroll = self
15043 .selections
15044 .all::<Point>(cx)
15045 .iter()
15046 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15047
15048 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15049 }
15050
15051 pub fn unfold_all(
15052 &mut self,
15053 _: &actions::UnfoldAll,
15054 _window: &mut Window,
15055 cx: &mut Context<Self>,
15056 ) {
15057 if self.buffer.read(cx).is_singleton() {
15058 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15059 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15060 } else {
15061 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15062 editor
15063 .update(cx, |editor, cx| {
15064 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15065 editor.unfold_buffer(buffer_id, cx);
15066 }
15067 })
15068 .ok();
15069 });
15070 }
15071 }
15072
15073 pub fn fold_selected_ranges(
15074 &mut self,
15075 _: &FoldSelectedRanges,
15076 window: &mut Window,
15077 cx: &mut Context<Self>,
15078 ) {
15079 let selections = self.selections.all_adjusted(cx);
15080 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15081 let ranges = selections
15082 .into_iter()
15083 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15084 .collect::<Vec<_>>();
15085 self.fold_creases(ranges, true, window, cx);
15086 }
15087
15088 pub fn fold_ranges<T: ToOffset + Clone>(
15089 &mut self,
15090 ranges: Vec<Range<T>>,
15091 auto_scroll: bool,
15092 window: &mut Window,
15093 cx: &mut Context<Self>,
15094 ) {
15095 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15096 let ranges = ranges
15097 .into_iter()
15098 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15099 .collect::<Vec<_>>();
15100 self.fold_creases(ranges, auto_scroll, window, cx);
15101 }
15102
15103 pub fn fold_creases<T: ToOffset + Clone>(
15104 &mut self,
15105 creases: Vec<Crease<T>>,
15106 auto_scroll: bool,
15107 window: &mut Window,
15108 cx: &mut Context<Self>,
15109 ) {
15110 if creases.is_empty() {
15111 return;
15112 }
15113
15114 let mut buffers_affected = HashSet::default();
15115 let multi_buffer = self.buffer().read(cx);
15116 for crease in &creases {
15117 if let Some((_, buffer, _)) =
15118 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15119 {
15120 buffers_affected.insert(buffer.read(cx).remote_id());
15121 };
15122 }
15123
15124 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15125
15126 if auto_scroll {
15127 self.request_autoscroll(Autoscroll::fit(), cx);
15128 }
15129
15130 cx.notify();
15131
15132 if let Some(active_diagnostics) = self.active_diagnostics.take() {
15133 // Clear diagnostics block when folding a range that contains it.
15134 let snapshot = self.snapshot(window, cx);
15135 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
15136 drop(snapshot);
15137 self.active_diagnostics = Some(active_diagnostics);
15138 self.dismiss_diagnostics(cx);
15139 } else {
15140 self.active_diagnostics = Some(active_diagnostics);
15141 }
15142 }
15143
15144 self.scrollbar_marker_state.dirty = true;
15145 self.folds_did_change(cx);
15146 }
15147
15148 /// Removes any folds whose ranges intersect any of the given ranges.
15149 pub fn unfold_ranges<T: ToOffset + Clone>(
15150 &mut self,
15151 ranges: &[Range<T>],
15152 inclusive: bool,
15153 auto_scroll: bool,
15154 cx: &mut Context<Self>,
15155 ) {
15156 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15157 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15158 });
15159 self.folds_did_change(cx);
15160 }
15161
15162 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15163 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15164 return;
15165 }
15166 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15167 self.display_map.update(cx, |display_map, cx| {
15168 display_map.fold_buffers([buffer_id], cx)
15169 });
15170 cx.emit(EditorEvent::BufferFoldToggled {
15171 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15172 folded: true,
15173 });
15174 cx.notify();
15175 }
15176
15177 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15178 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15179 return;
15180 }
15181 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15182 self.display_map.update(cx, |display_map, cx| {
15183 display_map.unfold_buffers([buffer_id], cx);
15184 });
15185 cx.emit(EditorEvent::BufferFoldToggled {
15186 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15187 folded: false,
15188 });
15189 cx.notify();
15190 }
15191
15192 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15193 self.display_map.read(cx).is_buffer_folded(buffer)
15194 }
15195
15196 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15197 self.display_map.read(cx).folded_buffers()
15198 }
15199
15200 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15201 self.display_map.update(cx, |display_map, cx| {
15202 display_map.disable_header_for_buffer(buffer_id, cx);
15203 });
15204 cx.notify();
15205 }
15206
15207 /// Removes any folds with the given ranges.
15208 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15209 &mut self,
15210 ranges: &[Range<T>],
15211 type_id: TypeId,
15212 auto_scroll: bool,
15213 cx: &mut Context<Self>,
15214 ) {
15215 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15216 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15217 });
15218 self.folds_did_change(cx);
15219 }
15220
15221 fn remove_folds_with<T: ToOffset + Clone>(
15222 &mut self,
15223 ranges: &[Range<T>],
15224 auto_scroll: bool,
15225 cx: &mut Context<Self>,
15226 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15227 ) {
15228 if ranges.is_empty() {
15229 return;
15230 }
15231
15232 let mut buffers_affected = HashSet::default();
15233 let multi_buffer = self.buffer().read(cx);
15234 for range in ranges {
15235 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15236 buffers_affected.insert(buffer.read(cx).remote_id());
15237 };
15238 }
15239
15240 self.display_map.update(cx, update);
15241
15242 if auto_scroll {
15243 self.request_autoscroll(Autoscroll::fit(), cx);
15244 }
15245
15246 cx.notify();
15247 self.scrollbar_marker_state.dirty = true;
15248 self.active_indent_guides_state.dirty = true;
15249 }
15250
15251 pub fn update_fold_widths(
15252 &mut self,
15253 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15254 cx: &mut Context<Self>,
15255 ) -> bool {
15256 self.display_map
15257 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15258 }
15259
15260 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15261 self.display_map.read(cx).fold_placeholder.clone()
15262 }
15263
15264 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15265 self.buffer.update(cx, |buffer, cx| {
15266 buffer.set_all_diff_hunks_expanded(cx);
15267 });
15268 }
15269
15270 pub fn expand_all_diff_hunks(
15271 &mut self,
15272 _: &ExpandAllDiffHunks,
15273 _window: &mut Window,
15274 cx: &mut Context<Self>,
15275 ) {
15276 self.buffer.update(cx, |buffer, cx| {
15277 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15278 });
15279 }
15280
15281 pub fn toggle_selected_diff_hunks(
15282 &mut self,
15283 _: &ToggleSelectedDiffHunks,
15284 _window: &mut Window,
15285 cx: &mut Context<Self>,
15286 ) {
15287 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15288 self.toggle_diff_hunks_in_ranges(ranges, cx);
15289 }
15290
15291 pub fn diff_hunks_in_ranges<'a>(
15292 &'a self,
15293 ranges: &'a [Range<Anchor>],
15294 buffer: &'a MultiBufferSnapshot,
15295 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15296 ranges.iter().flat_map(move |range| {
15297 let end_excerpt_id = range.end.excerpt_id;
15298 let range = range.to_point(buffer);
15299 let mut peek_end = range.end;
15300 if range.end.row < buffer.max_row().0 {
15301 peek_end = Point::new(range.end.row + 1, 0);
15302 }
15303 buffer
15304 .diff_hunks_in_range(range.start..peek_end)
15305 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15306 })
15307 }
15308
15309 pub fn has_stageable_diff_hunks_in_ranges(
15310 &self,
15311 ranges: &[Range<Anchor>],
15312 snapshot: &MultiBufferSnapshot,
15313 ) -> bool {
15314 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15315 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15316 }
15317
15318 pub fn toggle_staged_selected_diff_hunks(
15319 &mut self,
15320 _: &::git::ToggleStaged,
15321 _: &mut Window,
15322 cx: &mut Context<Self>,
15323 ) {
15324 let snapshot = self.buffer.read(cx).snapshot(cx);
15325 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15326 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15327 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15328 }
15329
15330 pub fn set_render_diff_hunk_controls(
15331 &mut self,
15332 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15333 cx: &mut Context<Self>,
15334 ) {
15335 self.render_diff_hunk_controls = render_diff_hunk_controls;
15336 cx.notify();
15337 }
15338
15339 pub fn stage_and_next(
15340 &mut self,
15341 _: &::git::StageAndNext,
15342 window: &mut Window,
15343 cx: &mut Context<Self>,
15344 ) {
15345 self.do_stage_or_unstage_and_next(true, window, cx);
15346 }
15347
15348 pub fn unstage_and_next(
15349 &mut self,
15350 _: &::git::UnstageAndNext,
15351 window: &mut Window,
15352 cx: &mut Context<Self>,
15353 ) {
15354 self.do_stage_or_unstage_and_next(false, window, cx);
15355 }
15356
15357 pub fn stage_or_unstage_diff_hunks(
15358 &mut self,
15359 stage: bool,
15360 ranges: Vec<Range<Anchor>>,
15361 cx: &mut Context<Self>,
15362 ) {
15363 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15364 cx.spawn(async move |this, cx| {
15365 task.await?;
15366 this.update(cx, |this, cx| {
15367 let snapshot = this.buffer.read(cx).snapshot(cx);
15368 let chunk_by = this
15369 .diff_hunks_in_ranges(&ranges, &snapshot)
15370 .chunk_by(|hunk| hunk.buffer_id);
15371 for (buffer_id, hunks) in &chunk_by {
15372 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15373 }
15374 })
15375 })
15376 .detach_and_log_err(cx);
15377 }
15378
15379 fn save_buffers_for_ranges_if_needed(
15380 &mut self,
15381 ranges: &[Range<Anchor>],
15382 cx: &mut Context<Editor>,
15383 ) -> Task<Result<()>> {
15384 let multibuffer = self.buffer.read(cx);
15385 let snapshot = multibuffer.read(cx);
15386 let buffer_ids: HashSet<_> = ranges
15387 .iter()
15388 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15389 .collect();
15390 drop(snapshot);
15391
15392 let mut buffers = HashSet::default();
15393 for buffer_id in buffer_ids {
15394 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15395 let buffer = buffer_entity.read(cx);
15396 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15397 {
15398 buffers.insert(buffer_entity);
15399 }
15400 }
15401 }
15402
15403 if let Some(project) = &self.project {
15404 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15405 } else {
15406 Task::ready(Ok(()))
15407 }
15408 }
15409
15410 fn do_stage_or_unstage_and_next(
15411 &mut self,
15412 stage: bool,
15413 window: &mut Window,
15414 cx: &mut Context<Self>,
15415 ) {
15416 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15417
15418 if ranges.iter().any(|range| range.start != range.end) {
15419 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15420 return;
15421 }
15422
15423 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15424 let snapshot = self.snapshot(window, cx);
15425 let position = self.selections.newest::<Point>(cx).head();
15426 let mut row = snapshot
15427 .buffer_snapshot
15428 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15429 .find(|hunk| hunk.row_range.start.0 > position.row)
15430 .map(|hunk| hunk.row_range.start);
15431
15432 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15433 // Outside of the project diff editor, wrap around to the beginning.
15434 if !all_diff_hunks_expanded {
15435 row = row.or_else(|| {
15436 snapshot
15437 .buffer_snapshot
15438 .diff_hunks_in_range(Point::zero()..position)
15439 .find(|hunk| hunk.row_range.end.0 < position.row)
15440 .map(|hunk| hunk.row_range.start)
15441 });
15442 }
15443
15444 if let Some(row) = row {
15445 let destination = Point::new(row.0, 0);
15446 let autoscroll = Autoscroll::center();
15447
15448 self.unfold_ranges(&[destination..destination], false, false, cx);
15449 self.change_selections(Some(autoscroll), window, cx, |s| {
15450 s.select_ranges([destination..destination]);
15451 });
15452 }
15453 }
15454
15455 fn do_stage_or_unstage(
15456 &self,
15457 stage: bool,
15458 buffer_id: BufferId,
15459 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15460 cx: &mut App,
15461 ) -> Option<()> {
15462 let project = self.project.as_ref()?;
15463 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15464 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15465 let buffer_snapshot = buffer.read(cx).snapshot();
15466 let file_exists = buffer_snapshot
15467 .file()
15468 .is_some_and(|file| file.disk_state().exists());
15469 diff.update(cx, |diff, cx| {
15470 diff.stage_or_unstage_hunks(
15471 stage,
15472 &hunks
15473 .map(|hunk| buffer_diff::DiffHunk {
15474 buffer_range: hunk.buffer_range,
15475 diff_base_byte_range: hunk.diff_base_byte_range,
15476 secondary_status: hunk.secondary_status,
15477 range: Point::zero()..Point::zero(), // unused
15478 })
15479 .collect::<Vec<_>>(),
15480 &buffer_snapshot,
15481 file_exists,
15482 cx,
15483 )
15484 });
15485 None
15486 }
15487
15488 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15489 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15490 self.buffer
15491 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15492 }
15493
15494 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15495 self.buffer.update(cx, |buffer, cx| {
15496 let ranges = vec![Anchor::min()..Anchor::max()];
15497 if !buffer.all_diff_hunks_expanded()
15498 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15499 {
15500 buffer.collapse_diff_hunks(ranges, cx);
15501 true
15502 } else {
15503 false
15504 }
15505 })
15506 }
15507
15508 fn toggle_diff_hunks_in_ranges(
15509 &mut self,
15510 ranges: Vec<Range<Anchor>>,
15511 cx: &mut Context<Editor>,
15512 ) {
15513 self.buffer.update(cx, |buffer, cx| {
15514 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15515 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15516 })
15517 }
15518
15519 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15520 self.buffer.update(cx, |buffer, cx| {
15521 let snapshot = buffer.snapshot(cx);
15522 let excerpt_id = range.end.excerpt_id;
15523 let point_range = range.to_point(&snapshot);
15524 let expand = !buffer.single_hunk_is_expanded(range, cx);
15525 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15526 })
15527 }
15528
15529 pub(crate) fn apply_all_diff_hunks(
15530 &mut self,
15531 _: &ApplyAllDiffHunks,
15532 window: &mut Window,
15533 cx: &mut Context<Self>,
15534 ) {
15535 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15536
15537 let buffers = self.buffer.read(cx).all_buffers();
15538 for branch_buffer in buffers {
15539 branch_buffer.update(cx, |branch_buffer, cx| {
15540 branch_buffer.merge_into_base(Vec::new(), cx);
15541 });
15542 }
15543
15544 if let Some(project) = self.project.clone() {
15545 self.save(true, project, window, cx).detach_and_log_err(cx);
15546 }
15547 }
15548
15549 pub(crate) fn apply_selected_diff_hunks(
15550 &mut self,
15551 _: &ApplyDiffHunk,
15552 window: &mut Window,
15553 cx: &mut Context<Self>,
15554 ) {
15555 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15556 let snapshot = self.snapshot(window, cx);
15557 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15558 let mut ranges_by_buffer = HashMap::default();
15559 self.transact(window, cx, |editor, _window, cx| {
15560 for hunk in hunks {
15561 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15562 ranges_by_buffer
15563 .entry(buffer.clone())
15564 .or_insert_with(Vec::new)
15565 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15566 }
15567 }
15568
15569 for (buffer, ranges) in ranges_by_buffer {
15570 buffer.update(cx, |buffer, cx| {
15571 buffer.merge_into_base(ranges, cx);
15572 });
15573 }
15574 });
15575
15576 if let Some(project) = self.project.clone() {
15577 self.save(true, project, window, cx).detach_and_log_err(cx);
15578 }
15579 }
15580
15581 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15582 if hovered != self.gutter_hovered {
15583 self.gutter_hovered = hovered;
15584 cx.notify();
15585 }
15586 }
15587
15588 pub fn insert_blocks(
15589 &mut self,
15590 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15591 autoscroll: Option<Autoscroll>,
15592 cx: &mut Context<Self>,
15593 ) -> Vec<CustomBlockId> {
15594 let blocks = self
15595 .display_map
15596 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15597 if let Some(autoscroll) = autoscroll {
15598 self.request_autoscroll(autoscroll, cx);
15599 }
15600 cx.notify();
15601 blocks
15602 }
15603
15604 pub fn resize_blocks(
15605 &mut self,
15606 heights: HashMap<CustomBlockId, u32>,
15607 autoscroll: Option<Autoscroll>,
15608 cx: &mut Context<Self>,
15609 ) {
15610 self.display_map
15611 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15612 if let Some(autoscroll) = autoscroll {
15613 self.request_autoscroll(autoscroll, cx);
15614 }
15615 cx.notify();
15616 }
15617
15618 pub fn replace_blocks(
15619 &mut self,
15620 renderers: HashMap<CustomBlockId, RenderBlock>,
15621 autoscroll: Option<Autoscroll>,
15622 cx: &mut Context<Self>,
15623 ) {
15624 self.display_map
15625 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15626 if let Some(autoscroll) = autoscroll {
15627 self.request_autoscroll(autoscroll, cx);
15628 }
15629 cx.notify();
15630 }
15631
15632 pub fn remove_blocks(
15633 &mut self,
15634 block_ids: HashSet<CustomBlockId>,
15635 autoscroll: Option<Autoscroll>,
15636 cx: &mut Context<Self>,
15637 ) {
15638 self.display_map.update(cx, |display_map, cx| {
15639 display_map.remove_blocks(block_ids, cx)
15640 });
15641 if let Some(autoscroll) = autoscroll {
15642 self.request_autoscroll(autoscroll, cx);
15643 }
15644 cx.notify();
15645 }
15646
15647 pub fn row_for_block(
15648 &self,
15649 block_id: CustomBlockId,
15650 cx: &mut Context<Self>,
15651 ) -> Option<DisplayRow> {
15652 self.display_map
15653 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15654 }
15655
15656 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15657 self.focused_block = Some(focused_block);
15658 }
15659
15660 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15661 self.focused_block.take()
15662 }
15663
15664 pub fn insert_creases(
15665 &mut self,
15666 creases: impl IntoIterator<Item = Crease<Anchor>>,
15667 cx: &mut Context<Self>,
15668 ) -> Vec<CreaseId> {
15669 self.display_map
15670 .update(cx, |map, cx| map.insert_creases(creases, cx))
15671 }
15672
15673 pub fn remove_creases(
15674 &mut self,
15675 ids: impl IntoIterator<Item = CreaseId>,
15676 cx: &mut Context<Self>,
15677 ) {
15678 self.display_map
15679 .update(cx, |map, cx| map.remove_creases(ids, cx));
15680 }
15681
15682 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15683 self.display_map
15684 .update(cx, |map, cx| map.snapshot(cx))
15685 .longest_row()
15686 }
15687
15688 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15689 self.display_map
15690 .update(cx, |map, cx| map.snapshot(cx))
15691 .max_point()
15692 }
15693
15694 pub fn text(&self, cx: &App) -> String {
15695 self.buffer.read(cx).read(cx).text()
15696 }
15697
15698 pub fn is_empty(&self, cx: &App) -> bool {
15699 self.buffer.read(cx).read(cx).is_empty()
15700 }
15701
15702 pub fn text_option(&self, cx: &App) -> Option<String> {
15703 let text = self.text(cx);
15704 let text = text.trim();
15705
15706 if text.is_empty() {
15707 return None;
15708 }
15709
15710 Some(text.to_string())
15711 }
15712
15713 pub fn set_text(
15714 &mut self,
15715 text: impl Into<Arc<str>>,
15716 window: &mut Window,
15717 cx: &mut Context<Self>,
15718 ) {
15719 self.transact(window, cx, |this, _, cx| {
15720 this.buffer
15721 .read(cx)
15722 .as_singleton()
15723 .expect("you can only call set_text on editors for singleton buffers")
15724 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15725 });
15726 }
15727
15728 pub fn display_text(&self, cx: &mut App) -> String {
15729 self.display_map
15730 .update(cx, |map, cx| map.snapshot(cx))
15731 .text()
15732 }
15733
15734 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15735 let mut wrap_guides = smallvec::smallvec![];
15736
15737 if self.show_wrap_guides == Some(false) {
15738 return wrap_guides;
15739 }
15740
15741 let settings = self.buffer.read(cx).language_settings(cx);
15742 if settings.show_wrap_guides {
15743 match self.soft_wrap_mode(cx) {
15744 SoftWrap::Column(soft_wrap) => {
15745 wrap_guides.push((soft_wrap as usize, true));
15746 }
15747 SoftWrap::Bounded(soft_wrap) => {
15748 wrap_guides.push((soft_wrap as usize, true));
15749 }
15750 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15751 }
15752 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15753 }
15754
15755 wrap_guides
15756 }
15757
15758 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15759 let settings = self.buffer.read(cx).language_settings(cx);
15760 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15761 match mode {
15762 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15763 SoftWrap::None
15764 }
15765 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15766 language_settings::SoftWrap::PreferredLineLength => {
15767 SoftWrap::Column(settings.preferred_line_length)
15768 }
15769 language_settings::SoftWrap::Bounded => {
15770 SoftWrap::Bounded(settings.preferred_line_length)
15771 }
15772 }
15773 }
15774
15775 pub fn set_soft_wrap_mode(
15776 &mut self,
15777 mode: language_settings::SoftWrap,
15778
15779 cx: &mut Context<Self>,
15780 ) {
15781 self.soft_wrap_mode_override = Some(mode);
15782 cx.notify();
15783 }
15784
15785 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15786 self.hard_wrap = hard_wrap;
15787 cx.notify();
15788 }
15789
15790 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15791 self.text_style_refinement = Some(style);
15792 }
15793
15794 /// called by the Element so we know what style we were most recently rendered with.
15795 pub(crate) fn set_style(
15796 &mut self,
15797 style: EditorStyle,
15798 window: &mut Window,
15799 cx: &mut Context<Self>,
15800 ) {
15801 let rem_size = window.rem_size();
15802 self.display_map.update(cx, |map, cx| {
15803 map.set_font(
15804 style.text.font(),
15805 style.text.font_size.to_pixels(rem_size),
15806 cx,
15807 )
15808 });
15809 self.style = Some(style);
15810 }
15811
15812 pub fn style(&self) -> Option<&EditorStyle> {
15813 self.style.as_ref()
15814 }
15815
15816 // Called by the element. This method is not designed to be called outside of the editor
15817 // element's layout code because it does not notify when rewrapping is computed synchronously.
15818 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15819 self.display_map
15820 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15821 }
15822
15823 pub fn set_soft_wrap(&mut self) {
15824 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15825 }
15826
15827 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15828 if self.soft_wrap_mode_override.is_some() {
15829 self.soft_wrap_mode_override.take();
15830 } else {
15831 let soft_wrap = match self.soft_wrap_mode(cx) {
15832 SoftWrap::GitDiff => return,
15833 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15834 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15835 language_settings::SoftWrap::None
15836 }
15837 };
15838 self.soft_wrap_mode_override = Some(soft_wrap);
15839 }
15840 cx.notify();
15841 }
15842
15843 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15844 let Some(workspace) = self.workspace() else {
15845 return;
15846 };
15847 let fs = workspace.read(cx).app_state().fs.clone();
15848 let current_show = TabBarSettings::get_global(cx).show;
15849 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15850 setting.show = Some(!current_show);
15851 });
15852 }
15853
15854 pub fn toggle_indent_guides(
15855 &mut self,
15856 _: &ToggleIndentGuides,
15857 _: &mut Window,
15858 cx: &mut Context<Self>,
15859 ) {
15860 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15861 self.buffer
15862 .read(cx)
15863 .language_settings(cx)
15864 .indent_guides
15865 .enabled
15866 });
15867 self.show_indent_guides = Some(!currently_enabled);
15868 cx.notify();
15869 }
15870
15871 fn should_show_indent_guides(&self) -> Option<bool> {
15872 self.show_indent_guides
15873 }
15874
15875 pub fn toggle_line_numbers(
15876 &mut self,
15877 _: &ToggleLineNumbers,
15878 _: &mut Window,
15879 cx: &mut Context<Self>,
15880 ) {
15881 let mut editor_settings = EditorSettings::get_global(cx).clone();
15882 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15883 EditorSettings::override_global(editor_settings, cx);
15884 }
15885
15886 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15887 if let Some(show_line_numbers) = self.show_line_numbers {
15888 return show_line_numbers;
15889 }
15890 EditorSettings::get_global(cx).gutter.line_numbers
15891 }
15892
15893 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15894 self.use_relative_line_numbers
15895 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15896 }
15897
15898 pub fn toggle_relative_line_numbers(
15899 &mut self,
15900 _: &ToggleRelativeLineNumbers,
15901 _: &mut Window,
15902 cx: &mut Context<Self>,
15903 ) {
15904 let is_relative = self.should_use_relative_line_numbers(cx);
15905 self.set_relative_line_number(Some(!is_relative), cx)
15906 }
15907
15908 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15909 self.use_relative_line_numbers = is_relative;
15910 cx.notify();
15911 }
15912
15913 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15914 self.show_gutter = show_gutter;
15915 cx.notify();
15916 }
15917
15918 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15919 self.show_scrollbars = show_scrollbars;
15920 cx.notify();
15921 }
15922
15923 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15924 self.show_line_numbers = Some(show_line_numbers);
15925 cx.notify();
15926 }
15927
15928 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15929 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15930 cx.notify();
15931 }
15932
15933 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15934 self.show_code_actions = Some(show_code_actions);
15935 cx.notify();
15936 }
15937
15938 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15939 self.show_runnables = Some(show_runnables);
15940 cx.notify();
15941 }
15942
15943 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15944 self.show_breakpoints = Some(show_breakpoints);
15945 cx.notify();
15946 }
15947
15948 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15949 if self.display_map.read(cx).masked != masked {
15950 self.display_map.update(cx, |map, _| map.masked = masked);
15951 }
15952 cx.notify()
15953 }
15954
15955 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15956 self.show_wrap_guides = Some(show_wrap_guides);
15957 cx.notify();
15958 }
15959
15960 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15961 self.show_indent_guides = Some(show_indent_guides);
15962 cx.notify();
15963 }
15964
15965 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15966 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15967 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15968 if let Some(dir) = file.abs_path(cx).parent() {
15969 return Some(dir.to_owned());
15970 }
15971 }
15972
15973 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15974 return Some(project_path.path.to_path_buf());
15975 }
15976 }
15977
15978 None
15979 }
15980
15981 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15982 self.active_excerpt(cx)?
15983 .1
15984 .read(cx)
15985 .file()
15986 .and_then(|f| f.as_local())
15987 }
15988
15989 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15990 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15991 let buffer = buffer.read(cx);
15992 if let Some(project_path) = buffer.project_path(cx) {
15993 let project = self.project.as_ref()?.read(cx);
15994 project.absolute_path(&project_path, cx)
15995 } else {
15996 buffer
15997 .file()
15998 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15999 }
16000 })
16001 }
16002
16003 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16004 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16005 let project_path = buffer.read(cx).project_path(cx)?;
16006 let project = self.project.as_ref()?.read(cx);
16007 let entry = project.entry_for_path(&project_path, cx)?;
16008 let path = entry.path.to_path_buf();
16009 Some(path)
16010 })
16011 }
16012
16013 pub fn reveal_in_finder(
16014 &mut self,
16015 _: &RevealInFileManager,
16016 _window: &mut Window,
16017 cx: &mut Context<Self>,
16018 ) {
16019 if let Some(target) = self.target_file(cx) {
16020 cx.reveal_path(&target.abs_path(cx));
16021 }
16022 }
16023
16024 pub fn copy_path(
16025 &mut self,
16026 _: &zed_actions::workspace::CopyPath,
16027 _window: &mut Window,
16028 cx: &mut Context<Self>,
16029 ) {
16030 if let Some(path) = self.target_file_abs_path(cx) {
16031 if let Some(path) = path.to_str() {
16032 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16033 }
16034 }
16035 }
16036
16037 pub fn copy_relative_path(
16038 &mut self,
16039 _: &zed_actions::workspace::CopyRelativePath,
16040 _window: &mut Window,
16041 cx: &mut Context<Self>,
16042 ) {
16043 if let Some(path) = self.target_file_path(cx) {
16044 if let Some(path) = path.to_str() {
16045 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16046 }
16047 }
16048 }
16049
16050 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16051 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16052 buffer.read(cx).project_path(cx)
16053 } else {
16054 None
16055 }
16056 }
16057
16058 // Returns true if the editor handled a go-to-line request
16059 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16060 maybe!({
16061 let breakpoint_store = self.breakpoint_store.as_ref()?;
16062
16063 let Some((_, _, active_position)) =
16064 breakpoint_store.read(cx).active_position().cloned()
16065 else {
16066 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16067 return None;
16068 };
16069
16070 let snapshot = self
16071 .project
16072 .as_ref()?
16073 .read(cx)
16074 .buffer_for_id(active_position.buffer_id?, cx)?
16075 .read(cx)
16076 .snapshot();
16077
16078 let mut handled = false;
16079 for (id, ExcerptRange { context, .. }) in self
16080 .buffer
16081 .read(cx)
16082 .excerpts_for_buffer(active_position.buffer_id?, cx)
16083 {
16084 if context.start.cmp(&active_position, &snapshot).is_ge()
16085 || context.end.cmp(&active_position, &snapshot).is_lt()
16086 {
16087 continue;
16088 }
16089 let snapshot = self.buffer.read(cx).snapshot(cx);
16090 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16091
16092 handled = true;
16093 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16094 self.go_to_line::<DebugCurrentRowHighlight>(
16095 multibuffer_anchor,
16096 Some(cx.theme().colors().editor_debugger_active_line_background),
16097 window,
16098 cx,
16099 );
16100
16101 cx.notify();
16102 }
16103 handled.then_some(())
16104 })
16105 .is_some()
16106 }
16107
16108 pub fn copy_file_name_without_extension(
16109 &mut self,
16110 _: &CopyFileNameWithoutExtension,
16111 _: &mut Window,
16112 cx: &mut Context<Self>,
16113 ) {
16114 if let Some(file) = self.target_file(cx) {
16115 if let Some(file_stem) = file.path().file_stem() {
16116 if let Some(name) = file_stem.to_str() {
16117 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16118 }
16119 }
16120 }
16121 }
16122
16123 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16124 if let Some(file) = self.target_file(cx) {
16125 if let Some(file_name) = file.path().file_name() {
16126 if let Some(name) = file_name.to_str() {
16127 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16128 }
16129 }
16130 }
16131 }
16132
16133 pub fn toggle_git_blame(
16134 &mut self,
16135 _: &::git::Blame,
16136 window: &mut Window,
16137 cx: &mut Context<Self>,
16138 ) {
16139 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16140
16141 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16142 self.start_git_blame(true, window, cx);
16143 }
16144
16145 cx.notify();
16146 }
16147
16148 pub fn toggle_git_blame_inline(
16149 &mut self,
16150 _: &ToggleGitBlameInline,
16151 window: &mut Window,
16152 cx: &mut Context<Self>,
16153 ) {
16154 self.toggle_git_blame_inline_internal(true, window, cx);
16155 cx.notify();
16156 }
16157
16158 pub fn open_git_blame_commit(
16159 &mut self,
16160 _: &OpenGitBlameCommit,
16161 window: &mut Window,
16162 cx: &mut Context<Self>,
16163 ) {
16164 self.open_git_blame_commit_internal(window, cx);
16165 }
16166
16167 fn open_git_blame_commit_internal(
16168 &mut self,
16169 window: &mut Window,
16170 cx: &mut Context<Self>,
16171 ) -> Option<()> {
16172 let blame = self.blame.as_ref()?;
16173 let snapshot = self.snapshot(window, cx);
16174 let cursor = self.selections.newest::<Point>(cx).head();
16175 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16176 let blame_entry = blame
16177 .update(cx, |blame, cx| {
16178 blame
16179 .blame_for_rows(
16180 &[RowInfo {
16181 buffer_id: Some(buffer.remote_id()),
16182 buffer_row: Some(point.row),
16183 ..Default::default()
16184 }],
16185 cx,
16186 )
16187 .next()
16188 })
16189 .flatten()?;
16190 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16191 let repo = blame.read(cx).repository(cx)?;
16192 let workspace = self.workspace()?.downgrade();
16193 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16194 None
16195 }
16196
16197 pub fn git_blame_inline_enabled(&self) -> bool {
16198 self.git_blame_inline_enabled
16199 }
16200
16201 pub fn toggle_selection_menu(
16202 &mut self,
16203 _: &ToggleSelectionMenu,
16204 _: &mut Window,
16205 cx: &mut Context<Self>,
16206 ) {
16207 self.show_selection_menu = self
16208 .show_selection_menu
16209 .map(|show_selections_menu| !show_selections_menu)
16210 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16211
16212 cx.notify();
16213 }
16214
16215 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16216 self.show_selection_menu
16217 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16218 }
16219
16220 fn start_git_blame(
16221 &mut self,
16222 user_triggered: bool,
16223 window: &mut Window,
16224 cx: &mut Context<Self>,
16225 ) {
16226 if let Some(project) = self.project.as_ref() {
16227 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16228 return;
16229 };
16230
16231 if buffer.read(cx).file().is_none() {
16232 return;
16233 }
16234
16235 let focused = self.focus_handle(cx).contains_focused(window, cx);
16236
16237 let project = project.clone();
16238 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16239 self.blame_subscription =
16240 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16241 self.blame = Some(blame);
16242 }
16243 }
16244
16245 fn toggle_git_blame_inline_internal(
16246 &mut self,
16247 user_triggered: bool,
16248 window: &mut Window,
16249 cx: &mut Context<Self>,
16250 ) {
16251 if self.git_blame_inline_enabled {
16252 self.git_blame_inline_enabled = false;
16253 self.show_git_blame_inline = false;
16254 self.show_git_blame_inline_delay_task.take();
16255 } else {
16256 self.git_blame_inline_enabled = true;
16257 self.start_git_blame_inline(user_triggered, window, cx);
16258 }
16259
16260 cx.notify();
16261 }
16262
16263 fn start_git_blame_inline(
16264 &mut self,
16265 user_triggered: bool,
16266 window: &mut Window,
16267 cx: &mut Context<Self>,
16268 ) {
16269 self.start_git_blame(user_triggered, window, cx);
16270
16271 if ProjectSettings::get_global(cx)
16272 .git
16273 .inline_blame_delay()
16274 .is_some()
16275 {
16276 self.start_inline_blame_timer(window, cx);
16277 } else {
16278 self.show_git_blame_inline = true
16279 }
16280 }
16281
16282 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16283 self.blame.as_ref()
16284 }
16285
16286 pub fn show_git_blame_gutter(&self) -> bool {
16287 self.show_git_blame_gutter
16288 }
16289
16290 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16291 self.show_git_blame_gutter && self.has_blame_entries(cx)
16292 }
16293
16294 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16295 self.show_git_blame_inline
16296 && (self.focus_handle.is_focused(window)
16297 || self
16298 .git_blame_inline_tooltip
16299 .as_ref()
16300 .and_then(|t| t.upgrade())
16301 .is_some())
16302 && !self.newest_selection_head_on_empty_line(cx)
16303 && self.has_blame_entries(cx)
16304 }
16305
16306 fn has_blame_entries(&self, cx: &App) -> bool {
16307 self.blame()
16308 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16309 }
16310
16311 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16312 let cursor_anchor = self.selections.newest_anchor().head();
16313
16314 let snapshot = self.buffer.read(cx).snapshot(cx);
16315 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16316
16317 snapshot.line_len(buffer_row) == 0
16318 }
16319
16320 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16321 let buffer_and_selection = maybe!({
16322 let selection = self.selections.newest::<Point>(cx);
16323 let selection_range = selection.range();
16324
16325 let multi_buffer = self.buffer().read(cx);
16326 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16327 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16328
16329 let (buffer, range, _) = if selection.reversed {
16330 buffer_ranges.first()
16331 } else {
16332 buffer_ranges.last()
16333 }?;
16334
16335 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16336 ..text::ToPoint::to_point(&range.end, &buffer).row;
16337 Some((
16338 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16339 selection,
16340 ))
16341 });
16342
16343 let Some((buffer, selection)) = buffer_and_selection else {
16344 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16345 };
16346
16347 let Some(project) = self.project.as_ref() else {
16348 return Task::ready(Err(anyhow!("editor does not have project")));
16349 };
16350
16351 project.update(cx, |project, cx| {
16352 project.get_permalink_to_line(&buffer, selection, cx)
16353 })
16354 }
16355
16356 pub fn copy_permalink_to_line(
16357 &mut self,
16358 _: &CopyPermalinkToLine,
16359 window: &mut Window,
16360 cx: &mut Context<Self>,
16361 ) {
16362 let permalink_task = self.get_permalink_to_line(cx);
16363 let workspace = self.workspace();
16364
16365 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16366 Ok(permalink) => {
16367 cx.update(|_, cx| {
16368 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16369 })
16370 .ok();
16371 }
16372 Err(err) => {
16373 let message = format!("Failed to copy permalink: {err}");
16374
16375 Err::<(), anyhow::Error>(err).log_err();
16376
16377 if let Some(workspace) = workspace {
16378 workspace
16379 .update_in(cx, |workspace, _, cx| {
16380 struct CopyPermalinkToLine;
16381
16382 workspace.show_toast(
16383 Toast::new(
16384 NotificationId::unique::<CopyPermalinkToLine>(),
16385 message,
16386 ),
16387 cx,
16388 )
16389 })
16390 .ok();
16391 }
16392 }
16393 })
16394 .detach();
16395 }
16396
16397 pub fn copy_file_location(
16398 &mut self,
16399 _: &CopyFileLocation,
16400 _: &mut Window,
16401 cx: &mut Context<Self>,
16402 ) {
16403 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16404 if let Some(file) = self.target_file(cx) {
16405 if let Some(path) = file.path().to_str() {
16406 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16407 }
16408 }
16409 }
16410
16411 pub fn open_permalink_to_line(
16412 &mut self,
16413 _: &OpenPermalinkToLine,
16414 window: &mut Window,
16415 cx: &mut Context<Self>,
16416 ) {
16417 let permalink_task = self.get_permalink_to_line(cx);
16418 let workspace = self.workspace();
16419
16420 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16421 Ok(permalink) => {
16422 cx.update(|_, cx| {
16423 cx.open_url(permalink.as_ref());
16424 })
16425 .ok();
16426 }
16427 Err(err) => {
16428 let message = format!("Failed to open permalink: {err}");
16429
16430 Err::<(), anyhow::Error>(err).log_err();
16431
16432 if let Some(workspace) = workspace {
16433 workspace
16434 .update(cx, |workspace, cx| {
16435 struct OpenPermalinkToLine;
16436
16437 workspace.show_toast(
16438 Toast::new(
16439 NotificationId::unique::<OpenPermalinkToLine>(),
16440 message,
16441 ),
16442 cx,
16443 )
16444 })
16445 .ok();
16446 }
16447 }
16448 })
16449 .detach();
16450 }
16451
16452 pub fn insert_uuid_v4(
16453 &mut self,
16454 _: &InsertUuidV4,
16455 window: &mut Window,
16456 cx: &mut Context<Self>,
16457 ) {
16458 self.insert_uuid(UuidVersion::V4, window, cx);
16459 }
16460
16461 pub fn insert_uuid_v7(
16462 &mut self,
16463 _: &InsertUuidV7,
16464 window: &mut Window,
16465 cx: &mut Context<Self>,
16466 ) {
16467 self.insert_uuid(UuidVersion::V7, window, cx);
16468 }
16469
16470 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16471 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16472 self.transact(window, cx, |this, window, cx| {
16473 let edits = this
16474 .selections
16475 .all::<Point>(cx)
16476 .into_iter()
16477 .map(|selection| {
16478 let uuid = match version {
16479 UuidVersion::V4 => uuid::Uuid::new_v4(),
16480 UuidVersion::V7 => uuid::Uuid::now_v7(),
16481 };
16482
16483 (selection.range(), uuid.to_string())
16484 });
16485 this.edit(edits, cx);
16486 this.refresh_inline_completion(true, false, window, cx);
16487 });
16488 }
16489
16490 pub fn open_selections_in_multibuffer(
16491 &mut self,
16492 _: &OpenSelectionsInMultibuffer,
16493 window: &mut Window,
16494 cx: &mut Context<Self>,
16495 ) {
16496 let multibuffer = self.buffer.read(cx);
16497
16498 let Some(buffer) = multibuffer.as_singleton() else {
16499 return;
16500 };
16501
16502 let Some(workspace) = self.workspace() else {
16503 return;
16504 };
16505
16506 let locations = self
16507 .selections
16508 .disjoint_anchors()
16509 .iter()
16510 .map(|range| Location {
16511 buffer: buffer.clone(),
16512 range: range.start.text_anchor..range.end.text_anchor,
16513 })
16514 .collect::<Vec<_>>();
16515
16516 let title = multibuffer.title(cx).to_string();
16517
16518 cx.spawn_in(window, async move |_, cx| {
16519 workspace.update_in(cx, |workspace, window, cx| {
16520 Self::open_locations_in_multibuffer(
16521 workspace,
16522 locations,
16523 format!("Selections for '{title}'"),
16524 false,
16525 MultibufferSelectionMode::All,
16526 window,
16527 cx,
16528 );
16529 })
16530 })
16531 .detach();
16532 }
16533
16534 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16535 /// last highlight added will be used.
16536 ///
16537 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16538 pub fn highlight_rows<T: 'static>(
16539 &mut self,
16540 range: Range<Anchor>,
16541 color: Hsla,
16542 should_autoscroll: bool,
16543 cx: &mut Context<Self>,
16544 ) {
16545 let snapshot = self.buffer().read(cx).snapshot(cx);
16546 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16547 let ix = row_highlights.binary_search_by(|highlight| {
16548 Ordering::Equal
16549 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16550 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16551 });
16552
16553 if let Err(mut ix) = ix {
16554 let index = post_inc(&mut self.highlight_order);
16555
16556 // If this range intersects with the preceding highlight, then merge it with
16557 // the preceding highlight. Otherwise insert a new highlight.
16558 let mut merged = false;
16559 if ix > 0 {
16560 let prev_highlight = &mut row_highlights[ix - 1];
16561 if prev_highlight
16562 .range
16563 .end
16564 .cmp(&range.start, &snapshot)
16565 .is_ge()
16566 {
16567 ix -= 1;
16568 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16569 prev_highlight.range.end = range.end;
16570 }
16571 merged = true;
16572 prev_highlight.index = index;
16573 prev_highlight.color = color;
16574 prev_highlight.should_autoscroll = should_autoscroll;
16575 }
16576 }
16577
16578 if !merged {
16579 row_highlights.insert(
16580 ix,
16581 RowHighlight {
16582 range: range.clone(),
16583 index,
16584 color,
16585 should_autoscroll,
16586 },
16587 );
16588 }
16589
16590 // If any of the following highlights intersect with this one, merge them.
16591 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16592 let highlight = &row_highlights[ix];
16593 if next_highlight
16594 .range
16595 .start
16596 .cmp(&highlight.range.end, &snapshot)
16597 .is_le()
16598 {
16599 if next_highlight
16600 .range
16601 .end
16602 .cmp(&highlight.range.end, &snapshot)
16603 .is_gt()
16604 {
16605 row_highlights[ix].range.end = next_highlight.range.end;
16606 }
16607 row_highlights.remove(ix + 1);
16608 } else {
16609 break;
16610 }
16611 }
16612 }
16613 }
16614
16615 /// Remove any highlighted row ranges of the given type that intersect the
16616 /// given ranges.
16617 pub fn remove_highlighted_rows<T: 'static>(
16618 &mut self,
16619 ranges_to_remove: Vec<Range<Anchor>>,
16620 cx: &mut Context<Self>,
16621 ) {
16622 let snapshot = self.buffer().read(cx).snapshot(cx);
16623 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16624 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16625 row_highlights.retain(|highlight| {
16626 while let Some(range_to_remove) = ranges_to_remove.peek() {
16627 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16628 Ordering::Less | Ordering::Equal => {
16629 ranges_to_remove.next();
16630 }
16631 Ordering::Greater => {
16632 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16633 Ordering::Less | Ordering::Equal => {
16634 return false;
16635 }
16636 Ordering::Greater => break,
16637 }
16638 }
16639 }
16640 }
16641
16642 true
16643 })
16644 }
16645
16646 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16647 pub fn clear_row_highlights<T: 'static>(&mut self) {
16648 self.highlighted_rows.remove(&TypeId::of::<T>());
16649 }
16650
16651 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16652 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16653 self.highlighted_rows
16654 .get(&TypeId::of::<T>())
16655 .map_or(&[] as &[_], |vec| vec.as_slice())
16656 .iter()
16657 .map(|highlight| (highlight.range.clone(), highlight.color))
16658 }
16659
16660 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16661 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16662 /// Allows to ignore certain kinds of highlights.
16663 pub fn highlighted_display_rows(
16664 &self,
16665 window: &mut Window,
16666 cx: &mut App,
16667 ) -> BTreeMap<DisplayRow, LineHighlight> {
16668 let snapshot = self.snapshot(window, cx);
16669 let mut used_highlight_orders = HashMap::default();
16670 self.highlighted_rows
16671 .iter()
16672 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16673 .fold(
16674 BTreeMap::<DisplayRow, LineHighlight>::new(),
16675 |mut unique_rows, highlight| {
16676 let start = highlight.range.start.to_display_point(&snapshot);
16677 let end = highlight.range.end.to_display_point(&snapshot);
16678 let start_row = start.row().0;
16679 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16680 && end.column() == 0
16681 {
16682 end.row().0.saturating_sub(1)
16683 } else {
16684 end.row().0
16685 };
16686 for row in start_row..=end_row {
16687 let used_index =
16688 used_highlight_orders.entry(row).or_insert(highlight.index);
16689 if highlight.index >= *used_index {
16690 *used_index = highlight.index;
16691 unique_rows.insert(DisplayRow(row), highlight.color.into());
16692 }
16693 }
16694 unique_rows
16695 },
16696 )
16697 }
16698
16699 pub fn highlighted_display_row_for_autoscroll(
16700 &self,
16701 snapshot: &DisplaySnapshot,
16702 ) -> Option<DisplayRow> {
16703 self.highlighted_rows
16704 .values()
16705 .flat_map(|highlighted_rows| highlighted_rows.iter())
16706 .filter_map(|highlight| {
16707 if highlight.should_autoscroll {
16708 Some(highlight.range.start.to_display_point(snapshot).row())
16709 } else {
16710 None
16711 }
16712 })
16713 .min()
16714 }
16715
16716 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16717 self.highlight_background::<SearchWithinRange>(
16718 ranges,
16719 |colors| colors.editor_document_highlight_read_background,
16720 cx,
16721 )
16722 }
16723
16724 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16725 self.breadcrumb_header = Some(new_header);
16726 }
16727
16728 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16729 self.clear_background_highlights::<SearchWithinRange>(cx);
16730 }
16731
16732 pub fn highlight_background<T: 'static>(
16733 &mut self,
16734 ranges: &[Range<Anchor>],
16735 color_fetcher: fn(&ThemeColors) -> Hsla,
16736 cx: &mut Context<Self>,
16737 ) {
16738 self.background_highlights
16739 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16740 self.scrollbar_marker_state.dirty = true;
16741 cx.notify();
16742 }
16743
16744 pub fn clear_background_highlights<T: 'static>(
16745 &mut self,
16746 cx: &mut Context<Self>,
16747 ) -> Option<BackgroundHighlight> {
16748 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16749 if !text_highlights.1.is_empty() {
16750 self.scrollbar_marker_state.dirty = true;
16751 cx.notify();
16752 }
16753 Some(text_highlights)
16754 }
16755
16756 pub fn highlight_gutter<T: 'static>(
16757 &mut self,
16758 ranges: &[Range<Anchor>],
16759 color_fetcher: fn(&App) -> Hsla,
16760 cx: &mut Context<Self>,
16761 ) {
16762 self.gutter_highlights
16763 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16764 cx.notify();
16765 }
16766
16767 pub fn clear_gutter_highlights<T: 'static>(
16768 &mut self,
16769 cx: &mut Context<Self>,
16770 ) -> Option<GutterHighlight> {
16771 cx.notify();
16772 self.gutter_highlights.remove(&TypeId::of::<T>())
16773 }
16774
16775 #[cfg(feature = "test-support")]
16776 pub fn all_text_background_highlights(
16777 &self,
16778 window: &mut Window,
16779 cx: &mut Context<Self>,
16780 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16781 let snapshot = self.snapshot(window, cx);
16782 let buffer = &snapshot.buffer_snapshot;
16783 let start = buffer.anchor_before(0);
16784 let end = buffer.anchor_after(buffer.len());
16785 let theme = cx.theme().colors();
16786 self.background_highlights_in_range(start..end, &snapshot, theme)
16787 }
16788
16789 #[cfg(feature = "test-support")]
16790 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16791 let snapshot = self.buffer().read(cx).snapshot(cx);
16792
16793 let highlights = self
16794 .background_highlights
16795 .get(&TypeId::of::<items::BufferSearchHighlights>());
16796
16797 if let Some((_color, ranges)) = highlights {
16798 ranges
16799 .iter()
16800 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16801 .collect_vec()
16802 } else {
16803 vec![]
16804 }
16805 }
16806
16807 fn document_highlights_for_position<'a>(
16808 &'a self,
16809 position: Anchor,
16810 buffer: &'a MultiBufferSnapshot,
16811 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16812 let read_highlights = self
16813 .background_highlights
16814 .get(&TypeId::of::<DocumentHighlightRead>())
16815 .map(|h| &h.1);
16816 let write_highlights = self
16817 .background_highlights
16818 .get(&TypeId::of::<DocumentHighlightWrite>())
16819 .map(|h| &h.1);
16820 let left_position = position.bias_left(buffer);
16821 let right_position = position.bias_right(buffer);
16822 read_highlights
16823 .into_iter()
16824 .chain(write_highlights)
16825 .flat_map(move |ranges| {
16826 let start_ix = match ranges.binary_search_by(|probe| {
16827 let cmp = probe.end.cmp(&left_position, buffer);
16828 if cmp.is_ge() {
16829 Ordering::Greater
16830 } else {
16831 Ordering::Less
16832 }
16833 }) {
16834 Ok(i) | Err(i) => i,
16835 };
16836
16837 ranges[start_ix..]
16838 .iter()
16839 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16840 })
16841 }
16842
16843 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16844 self.background_highlights
16845 .get(&TypeId::of::<T>())
16846 .map_or(false, |(_, highlights)| !highlights.is_empty())
16847 }
16848
16849 pub fn background_highlights_in_range(
16850 &self,
16851 search_range: Range<Anchor>,
16852 display_snapshot: &DisplaySnapshot,
16853 theme: &ThemeColors,
16854 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16855 let mut results = Vec::new();
16856 for (color_fetcher, ranges) in self.background_highlights.values() {
16857 let color = color_fetcher(theme);
16858 let start_ix = match ranges.binary_search_by(|probe| {
16859 let cmp = probe
16860 .end
16861 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16862 if cmp.is_gt() {
16863 Ordering::Greater
16864 } else {
16865 Ordering::Less
16866 }
16867 }) {
16868 Ok(i) | Err(i) => i,
16869 };
16870 for range in &ranges[start_ix..] {
16871 if range
16872 .start
16873 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16874 .is_ge()
16875 {
16876 break;
16877 }
16878
16879 let start = range.start.to_display_point(display_snapshot);
16880 let end = range.end.to_display_point(display_snapshot);
16881 results.push((start..end, color))
16882 }
16883 }
16884 results
16885 }
16886
16887 pub fn background_highlight_row_ranges<T: 'static>(
16888 &self,
16889 search_range: Range<Anchor>,
16890 display_snapshot: &DisplaySnapshot,
16891 count: usize,
16892 ) -> Vec<RangeInclusive<DisplayPoint>> {
16893 let mut results = Vec::new();
16894 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16895 return vec![];
16896 };
16897
16898 let start_ix = match ranges.binary_search_by(|probe| {
16899 let cmp = probe
16900 .end
16901 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16902 if cmp.is_gt() {
16903 Ordering::Greater
16904 } else {
16905 Ordering::Less
16906 }
16907 }) {
16908 Ok(i) | Err(i) => i,
16909 };
16910 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16911 if let (Some(start_display), Some(end_display)) = (start, end) {
16912 results.push(
16913 start_display.to_display_point(display_snapshot)
16914 ..=end_display.to_display_point(display_snapshot),
16915 );
16916 }
16917 };
16918 let mut start_row: Option<Point> = None;
16919 let mut end_row: Option<Point> = None;
16920 if ranges.len() > count {
16921 return Vec::new();
16922 }
16923 for range in &ranges[start_ix..] {
16924 if range
16925 .start
16926 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16927 .is_ge()
16928 {
16929 break;
16930 }
16931 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16932 if let Some(current_row) = &end_row {
16933 if end.row == current_row.row {
16934 continue;
16935 }
16936 }
16937 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16938 if start_row.is_none() {
16939 assert_eq!(end_row, None);
16940 start_row = Some(start);
16941 end_row = Some(end);
16942 continue;
16943 }
16944 if let Some(current_end) = end_row.as_mut() {
16945 if start.row > current_end.row + 1 {
16946 push_region(start_row, end_row);
16947 start_row = Some(start);
16948 end_row = Some(end);
16949 } else {
16950 // Merge two hunks.
16951 *current_end = end;
16952 }
16953 } else {
16954 unreachable!();
16955 }
16956 }
16957 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16958 push_region(start_row, end_row);
16959 results
16960 }
16961
16962 pub fn gutter_highlights_in_range(
16963 &self,
16964 search_range: Range<Anchor>,
16965 display_snapshot: &DisplaySnapshot,
16966 cx: &App,
16967 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16968 let mut results = Vec::new();
16969 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16970 let color = color_fetcher(cx);
16971 let start_ix = match ranges.binary_search_by(|probe| {
16972 let cmp = probe
16973 .end
16974 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16975 if cmp.is_gt() {
16976 Ordering::Greater
16977 } else {
16978 Ordering::Less
16979 }
16980 }) {
16981 Ok(i) | Err(i) => i,
16982 };
16983 for range in &ranges[start_ix..] {
16984 if range
16985 .start
16986 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16987 .is_ge()
16988 {
16989 break;
16990 }
16991
16992 let start = range.start.to_display_point(display_snapshot);
16993 let end = range.end.to_display_point(display_snapshot);
16994 results.push((start..end, color))
16995 }
16996 }
16997 results
16998 }
16999
17000 /// Get the text ranges corresponding to the redaction query
17001 pub fn redacted_ranges(
17002 &self,
17003 search_range: Range<Anchor>,
17004 display_snapshot: &DisplaySnapshot,
17005 cx: &App,
17006 ) -> Vec<Range<DisplayPoint>> {
17007 display_snapshot
17008 .buffer_snapshot
17009 .redacted_ranges(search_range, |file| {
17010 if let Some(file) = file {
17011 file.is_private()
17012 && EditorSettings::get(
17013 Some(SettingsLocation {
17014 worktree_id: file.worktree_id(cx),
17015 path: file.path().as_ref(),
17016 }),
17017 cx,
17018 )
17019 .redact_private_values
17020 } else {
17021 false
17022 }
17023 })
17024 .map(|range| {
17025 range.start.to_display_point(display_snapshot)
17026 ..range.end.to_display_point(display_snapshot)
17027 })
17028 .collect()
17029 }
17030
17031 pub fn highlight_text<T: 'static>(
17032 &mut self,
17033 ranges: Vec<Range<Anchor>>,
17034 style: HighlightStyle,
17035 cx: &mut Context<Self>,
17036 ) {
17037 self.display_map.update(cx, |map, _| {
17038 map.highlight_text(TypeId::of::<T>(), ranges, style)
17039 });
17040 cx.notify();
17041 }
17042
17043 pub(crate) fn highlight_inlays<T: 'static>(
17044 &mut self,
17045 highlights: Vec<InlayHighlight>,
17046 style: HighlightStyle,
17047 cx: &mut Context<Self>,
17048 ) {
17049 self.display_map.update(cx, |map, _| {
17050 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17051 });
17052 cx.notify();
17053 }
17054
17055 pub fn text_highlights<'a, T: 'static>(
17056 &'a self,
17057 cx: &'a App,
17058 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17059 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17060 }
17061
17062 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17063 let cleared = self
17064 .display_map
17065 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17066 if cleared {
17067 cx.notify();
17068 }
17069 }
17070
17071 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17072 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17073 && self.focus_handle.is_focused(window)
17074 }
17075
17076 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17077 self.show_cursor_when_unfocused = is_enabled;
17078 cx.notify();
17079 }
17080
17081 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17082 cx.notify();
17083 }
17084
17085 fn on_buffer_event(
17086 &mut self,
17087 multibuffer: &Entity<MultiBuffer>,
17088 event: &multi_buffer::Event,
17089 window: &mut Window,
17090 cx: &mut Context<Self>,
17091 ) {
17092 match event {
17093 multi_buffer::Event::Edited {
17094 singleton_buffer_edited,
17095 edited_buffer: buffer_edited,
17096 } => {
17097 self.scrollbar_marker_state.dirty = true;
17098 self.active_indent_guides_state.dirty = true;
17099 self.refresh_active_diagnostics(cx);
17100 self.refresh_code_actions(window, cx);
17101 if self.has_active_inline_completion() {
17102 self.update_visible_inline_completion(window, cx);
17103 }
17104 if let Some(buffer) = buffer_edited {
17105 let buffer_id = buffer.read(cx).remote_id();
17106 if !self.registered_buffers.contains_key(&buffer_id) {
17107 if let Some(project) = self.project.as_ref() {
17108 project.update(cx, |project, cx| {
17109 self.registered_buffers.insert(
17110 buffer_id,
17111 project.register_buffer_with_language_servers(&buffer, cx),
17112 );
17113 })
17114 }
17115 }
17116 }
17117 cx.emit(EditorEvent::BufferEdited);
17118 cx.emit(SearchEvent::MatchesInvalidated);
17119 if *singleton_buffer_edited {
17120 if let Some(project) = &self.project {
17121 #[allow(clippy::mutable_key_type)]
17122 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17123 multibuffer
17124 .all_buffers()
17125 .into_iter()
17126 .filter_map(|buffer| {
17127 buffer.update(cx, |buffer, cx| {
17128 let language = buffer.language()?;
17129 let should_discard = project.update(cx, |project, cx| {
17130 project.is_local()
17131 && !project.has_language_servers_for(buffer, cx)
17132 });
17133 should_discard.not().then_some(language.clone())
17134 })
17135 })
17136 .collect::<HashSet<_>>()
17137 });
17138 if !languages_affected.is_empty() {
17139 self.refresh_inlay_hints(
17140 InlayHintRefreshReason::BufferEdited(languages_affected),
17141 cx,
17142 );
17143 }
17144 }
17145 }
17146
17147 let Some(project) = &self.project else { return };
17148 let (telemetry, is_via_ssh) = {
17149 let project = project.read(cx);
17150 let telemetry = project.client().telemetry().clone();
17151 let is_via_ssh = project.is_via_ssh();
17152 (telemetry, is_via_ssh)
17153 };
17154 refresh_linked_ranges(self, window, cx);
17155 telemetry.log_edit_event("editor", is_via_ssh);
17156 }
17157 multi_buffer::Event::ExcerptsAdded {
17158 buffer,
17159 predecessor,
17160 excerpts,
17161 } => {
17162 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17163 let buffer_id = buffer.read(cx).remote_id();
17164 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17165 if let Some(project) = &self.project {
17166 get_uncommitted_diff_for_buffer(
17167 project,
17168 [buffer.clone()],
17169 self.buffer.clone(),
17170 cx,
17171 )
17172 .detach();
17173 }
17174 }
17175 cx.emit(EditorEvent::ExcerptsAdded {
17176 buffer: buffer.clone(),
17177 predecessor: *predecessor,
17178 excerpts: excerpts.clone(),
17179 });
17180 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17181 }
17182 multi_buffer::Event::ExcerptsRemoved { ids } => {
17183 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17184 let buffer = self.buffer.read(cx);
17185 self.registered_buffers
17186 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17187 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17188 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17189 }
17190 multi_buffer::Event::ExcerptsEdited {
17191 excerpt_ids,
17192 buffer_ids,
17193 } => {
17194 self.display_map.update(cx, |map, cx| {
17195 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17196 });
17197 cx.emit(EditorEvent::ExcerptsEdited {
17198 ids: excerpt_ids.clone(),
17199 })
17200 }
17201 multi_buffer::Event::ExcerptsExpanded { ids } => {
17202 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17203 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17204 }
17205 multi_buffer::Event::Reparsed(buffer_id) => {
17206 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17207 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17208
17209 cx.emit(EditorEvent::Reparsed(*buffer_id));
17210 }
17211 multi_buffer::Event::DiffHunksToggled => {
17212 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17213 }
17214 multi_buffer::Event::LanguageChanged(buffer_id) => {
17215 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17216 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17217 cx.emit(EditorEvent::Reparsed(*buffer_id));
17218 cx.notify();
17219 }
17220 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17221 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17222 multi_buffer::Event::FileHandleChanged
17223 | multi_buffer::Event::Reloaded
17224 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17225 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17226 multi_buffer::Event::DiagnosticsUpdated => {
17227 self.refresh_active_diagnostics(cx);
17228 self.refresh_inline_diagnostics(true, window, cx);
17229 self.scrollbar_marker_state.dirty = true;
17230 cx.notify();
17231 }
17232 _ => {}
17233 };
17234 }
17235
17236 fn on_display_map_changed(
17237 &mut self,
17238 _: Entity<DisplayMap>,
17239 _: &mut Window,
17240 cx: &mut Context<Self>,
17241 ) {
17242 cx.notify();
17243 }
17244
17245 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17246 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17247 self.update_edit_prediction_settings(cx);
17248 self.refresh_inline_completion(true, false, window, cx);
17249 self.refresh_inlay_hints(
17250 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17251 self.selections.newest_anchor().head(),
17252 &self.buffer.read(cx).snapshot(cx),
17253 cx,
17254 )),
17255 cx,
17256 );
17257
17258 let old_cursor_shape = self.cursor_shape;
17259
17260 {
17261 let editor_settings = EditorSettings::get_global(cx);
17262 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17263 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17264 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17265 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17266 }
17267
17268 if old_cursor_shape != self.cursor_shape {
17269 cx.emit(EditorEvent::CursorShapeChanged);
17270 }
17271
17272 let project_settings = ProjectSettings::get_global(cx);
17273 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17274
17275 if self.mode.is_full() {
17276 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17277 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17278 if self.show_inline_diagnostics != show_inline_diagnostics {
17279 self.show_inline_diagnostics = show_inline_diagnostics;
17280 self.refresh_inline_diagnostics(false, window, cx);
17281 }
17282
17283 if self.git_blame_inline_enabled != inline_blame_enabled {
17284 self.toggle_git_blame_inline_internal(false, window, cx);
17285 }
17286 }
17287
17288 cx.notify();
17289 }
17290
17291 pub fn set_searchable(&mut self, searchable: bool) {
17292 self.searchable = searchable;
17293 }
17294
17295 pub fn searchable(&self) -> bool {
17296 self.searchable
17297 }
17298
17299 fn open_proposed_changes_editor(
17300 &mut self,
17301 _: &OpenProposedChangesEditor,
17302 window: &mut Window,
17303 cx: &mut Context<Self>,
17304 ) {
17305 let Some(workspace) = self.workspace() else {
17306 cx.propagate();
17307 return;
17308 };
17309
17310 let selections = self.selections.all::<usize>(cx);
17311 let multi_buffer = self.buffer.read(cx);
17312 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17313 let mut new_selections_by_buffer = HashMap::default();
17314 for selection in selections {
17315 for (buffer, range, _) in
17316 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17317 {
17318 let mut range = range.to_point(buffer);
17319 range.start.column = 0;
17320 range.end.column = buffer.line_len(range.end.row);
17321 new_selections_by_buffer
17322 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17323 .or_insert(Vec::new())
17324 .push(range)
17325 }
17326 }
17327
17328 let proposed_changes_buffers = new_selections_by_buffer
17329 .into_iter()
17330 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17331 .collect::<Vec<_>>();
17332 let proposed_changes_editor = cx.new(|cx| {
17333 ProposedChangesEditor::new(
17334 "Proposed changes",
17335 proposed_changes_buffers,
17336 self.project.clone(),
17337 window,
17338 cx,
17339 )
17340 });
17341
17342 window.defer(cx, move |window, cx| {
17343 workspace.update(cx, |workspace, cx| {
17344 workspace.active_pane().update(cx, |pane, cx| {
17345 pane.add_item(
17346 Box::new(proposed_changes_editor),
17347 true,
17348 true,
17349 None,
17350 window,
17351 cx,
17352 );
17353 });
17354 });
17355 });
17356 }
17357
17358 pub fn open_excerpts_in_split(
17359 &mut self,
17360 _: &OpenExcerptsSplit,
17361 window: &mut Window,
17362 cx: &mut Context<Self>,
17363 ) {
17364 self.open_excerpts_common(None, true, window, cx)
17365 }
17366
17367 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17368 self.open_excerpts_common(None, false, window, cx)
17369 }
17370
17371 fn open_excerpts_common(
17372 &mut self,
17373 jump_data: Option<JumpData>,
17374 split: bool,
17375 window: &mut Window,
17376 cx: &mut Context<Self>,
17377 ) {
17378 let Some(workspace) = self.workspace() else {
17379 cx.propagate();
17380 return;
17381 };
17382
17383 if self.buffer.read(cx).is_singleton() {
17384 cx.propagate();
17385 return;
17386 }
17387
17388 let mut new_selections_by_buffer = HashMap::default();
17389 match &jump_data {
17390 Some(JumpData::MultiBufferPoint {
17391 excerpt_id,
17392 position,
17393 anchor,
17394 line_offset_from_top,
17395 }) => {
17396 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17397 if let Some(buffer) = multi_buffer_snapshot
17398 .buffer_id_for_excerpt(*excerpt_id)
17399 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17400 {
17401 let buffer_snapshot = buffer.read(cx).snapshot();
17402 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17403 language::ToPoint::to_point(anchor, &buffer_snapshot)
17404 } else {
17405 buffer_snapshot.clip_point(*position, Bias::Left)
17406 };
17407 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17408 new_selections_by_buffer.insert(
17409 buffer,
17410 (
17411 vec![jump_to_offset..jump_to_offset],
17412 Some(*line_offset_from_top),
17413 ),
17414 );
17415 }
17416 }
17417 Some(JumpData::MultiBufferRow {
17418 row,
17419 line_offset_from_top,
17420 }) => {
17421 let point = MultiBufferPoint::new(row.0, 0);
17422 if let Some((buffer, buffer_point, _)) =
17423 self.buffer.read(cx).point_to_buffer_point(point, cx)
17424 {
17425 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17426 new_selections_by_buffer
17427 .entry(buffer)
17428 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17429 .0
17430 .push(buffer_offset..buffer_offset)
17431 }
17432 }
17433 None => {
17434 let selections = self.selections.all::<usize>(cx);
17435 let multi_buffer = self.buffer.read(cx);
17436 for selection in selections {
17437 for (snapshot, range, _, anchor) in multi_buffer
17438 .snapshot(cx)
17439 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17440 {
17441 if let Some(anchor) = anchor {
17442 // selection is in a deleted hunk
17443 let Some(buffer_id) = anchor.buffer_id else {
17444 continue;
17445 };
17446 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17447 continue;
17448 };
17449 let offset = text::ToOffset::to_offset(
17450 &anchor.text_anchor,
17451 &buffer_handle.read(cx).snapshot(),
17452 );
17453 let range = offset..offset;
17454 new_selections_by_buffer
17455 .entry(buffer_handle)
17456 .or_insert((Vec::new(), None))
17457 .0
17458 .push(range)
17459 } else {
17460 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17461 else {
17462 continue;
17463 };
17464 new_selections_by_buffer
17465 .entry(buffer_handle)
17466 .or_insert((Vec::new(), None))
17467 .0
17468 .push(range)
17469 }
17470 }
17471 }
17472 }
17473 }
17474
17475 new_selections_by_buffer
17476 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17477
17478 if new_selections_by_buffer.is_empty() {
17479 return;
17480 }
17481
17482 // We defer the pane interaction because we ourselves are a workspace item
17483 // and activating a new item causes the pane to call a method on us reentrantly,
17484 // which panics if we're on the stack.
17485 window.defer(cx, move |window, cx| {
17486 workspace.update(cx, |workspace, cx| {
17487 let pane = if split {
17488 workspace.adjacent_pane(window, cx)
17489 } else {
17490 workspace.active_pane().clone()
17491 };
17492
17493 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17494 let editor = buffer
17495 .read(cx)
17496 .file()
17497 .is_none()
17498 .then(|| {
17499 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17500 // so `workspace.open_project_item` will never find them, always opening a new editor.
17501 // Instead, we try to activate the existing editor in the pane first.
17502 let (editor, pane_item_index) =
17503 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17504 let editor = item.downcast::<Editor>()?;
17505 let singleton_buffer =
17506 editor.read(cx).buffer().read(cx).as_singleton()?;
17507 if singleton_buffer == buffer {
17508 Some((editor, i))
17509 } else {
17510 None
17511 }
17512 })?;
17513 pane.update(cx, |pane, cx| {
17514 pane.activate_item(pane_item_index, true, true, window, cx)
17515 });
17516 Some(editor)
17517 })
17518 .flatten()
17519 .unwrap_or_else(|| {
17520 workspace.open_project_item::<Self>(
17521 pane.clone(),
17522 buffer,
17523 true,
17524 true,
17525 window,
17526 cx,
17527 )
17528 });
17529
17530 editor.update(cx, |editor, cx| {
17531 let autoscroll = match scroll_offset {
17532 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17533 None => Autoscroll::newest(),
17534 };
17535 let nav_history = editor.nav_history.take();
17536 editor.change_selections(Some(autoscroll), window, cx, |s| {
17537 s.select_ranges(ranges);
17538 });
17539 editor.nav_history = nav_history;
17540 });
17541 }
17542 })
17543 });
17544 }
17545
17546 // For now, don't allow opening excerpts in buffers that aren't backed by
17547 // regular project files.
17548 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17549 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17550 }
17551
17552 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17553 let snapshot = self.buffer.read(cx).read(cx);
17554 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17555 Some(
17556 ranges
17557 .iter()
17558 .map(move |range| {
17559 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17560 })
17561 .collect(),
17562 )
17563 }
17564
17565 fn selection_replacement_ranges(
17566 &self,
17567 range: Range<OffsetUtf16>,
17568 cx: &mut App,
17569 ) -> Vec<Range<OffsetUtf16>> {
17570 let selections = self.selections.all::<OffsetUtf16>(cx);
17571 let newest_selection = selections
17572 .iter()
17573 .max_by_key(|selection| selection.id)
17574 .unwrap();
17575 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17576 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17577 let snapshot = self.buffer.read(cx).read(cx);
17578 selections
17579 .into_iter()
17580 .map(|mut selection| {
17581 selection.start.0 =
17582 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17583 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17584 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17585 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17586 })
17587 .collect()
17588 }
17589
17590 fn report_editor_event(
17591 &self,
17592 event_type: &'static str,
17593 file_extension: Option<String>,
17594 cx: &App,
17595 ) {
17596 if cfg!(any(test, feature = "test-support")) {
17597 return;
17598 }
17599
17600 let Some(project) = &self.project else { return };
17601
17602 // If None, we are in a file without an extension
17603 let file = self
17604 .buffer
17605 .read(cx)
17606 .as_singleton()
17607 .and_then(|b| b.read(cx).file());
17608 let file_extension = file_extension.or(file
17609 .as_ref()
17610 .and_then(|file| Path::new(file.file_name(cx)).extension())
17611 .and_then(|e| e.to_str())
17612 .map(|a| a.to_string()));
17613
17614 let vim_mode = cx
17615 .global::<SettingsStore>()
17616 .raw_user_settings()
17617 .get("vim_mode")
17618 == Some(&serde_json::Value::Bool(true));
17619
17620 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17621 let copilot_enabled = edit_predictions_provider
17622 == language::language_settings::EditPredictionProvider::Copilot;
17623 let copilot_enabled_for_language = self
17624 .buffer
17625 .read(cx)
17626 .language_settings(cx)
17627 .show_edit_predictions;
17628
17629 let project = project.read(cx);
17630 telemetry::event!(
17631 event_type,
17632 file_extension,
17633 vim_mode,
17634 copilot_enabled,
17635 copilot_enabled_for_language,
17636 edit_predictions_provider,
17637 is_via_ssh = project.is_via_ssh(),
17638 );
17639 }
17640
17641 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17642 /// with each line being an array of {text, highlight} objects.
17643 fn copy_highlight_json(
17644 &mut self,
17645 _: &CopyHighlightJson,
17646 window: &mut Window,
17647 cx: &mut Context<Self>,
17648 ) {
17649 #[derive(Serialize)]
17650 struct Chunk<'a> {
17651 text: String,
17652 highlight: Option<&'a str>,
17653 }
17654
17655 let snapshot = self.buffer.read(cx).snapshot(cx);
17656 let range = self
17657 .selected_text_range(false, window, cx)
17658 .and_then(|selection| {
17659 if selection.range.is_empty() {
17660 None
17661 } else {
17662 Some(selection.range)
17663 }
17664 })
17665 .unwrap_or_else(|| 0..snapshot.len());
17666
17667 let chunks = snapshot.chunks(range, true);
17668 let mut lines = Vec::new();
17669 let mut line: VecDeque<Chunk> = VecDeque::new();
17670
17671 let Some(style) = self.style.as_ref() else {
17672 return;
17673 };
17674
17675 for chunk in chunks {
17676 let highlight = chunk
17677 .syntax_highlight_id
17678 .and_then(|id| id.name(&style.syntax));
17679 let mut chunk_lines = chunk.text.split('\n').peekable();
17680 while let Some(text) = chunk_lines.next() {
17681 let mut merged_with_last_token = false;
17682 if let Some(last_token) = line.back_mut() {
17683 if last_token.highlight == highlight {
17684 last_token.text.push_str(text);
17685 merged_with_last_token = true;
17686 }
17687 }
17688
17689 if !merged_with_last_token {
17690 line.push_back(Chunk {
17691 text: text.into(),
17692 highlight,
17693 });
17694 }
17695
17696 if chunk_lines.peek().is_some() {
17697 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17698 line.pop_front();
17699 }
17700 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17701 line.pop_back();
17702 }
17703
17704 lines.push(mem::take(&mut line));
17705 }
17706 }
17707 }
17708
17709 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17710 return;
17711 };
17712 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17713 }
17714
17715 pub fn open_context_menu(
17716 &mut self,
17717 _: &OpenContextMenu,
17718 window: &mut Window,
17719 cx: &mut Context<Self>,
17720 ) {
17721 self.request_autoscroll(Autoscroll::newest(), cx);
17722 let position = self.selections.newest_display(cx).start;
17723 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17724 }
17725
17726 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17727 &self.inlay_hint_cache
17728 }
17729
17730 pub fn replay_insert_event(
17731 &mut self,
17732 text: &str,
17733 relative_utf16_range: Option<Range<isize>>,
17734 window: &mut Window,
17735 cx: &mut Context<Self>,
17736 ) {
17737 if !self.input_enabled {
17738 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17739 return;
17740 }
17741 if let Some(relative_utf16_range) = relative_utf16_range {
17742 let selections = self.selections.all::<OffsetUtf16>(cx);
17743 self.change_selections(None, window, cx, |s| {
17744 let new_ranges = selections.into_iter().map(|range| {
17745 let start = OffsetUtf16(
17746 range
17747 .head()
17748 .0
17749 .saturating_add_signed(relative_utf16_range.start),
17750 );
17751 let end = OffsetUtf16(
17752 range
17753 .head()
17754 .0
17755 .saturating_add_signed(relative_utf16_range.end),
17756 );
17757 start..end
17758 });
17759 s.select_ranges(new_ranges);
17760 });
17761 }
17762
17763 self.handle_input(text, window, cx);
17764 }
17765
17766 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17767 let Some(provider) = self.semantics_provider.as_ref() else {
17768 return false;
17769 };
17770
17771 let mut supports = false;
17772 self.buffer().update(cx, |this, cx| {
17773 this.for_each_buffer(|buffer| {
17774 supports |= provider.supports_inlay_hints(buffer, cx);
17775 });
17776 });
17777
17778 supports
17779 }
17780
17781 pub fn is_focused(&self, window: &Window) -> bool {
17782 self.focus_handle.is_focused(window)
17783 }
17784
17785 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17786 cx.emit(EditorEvent::Focused);
17787
17788 if let Some(descendant) = self
17789 .last_focused_descendant
17790 .take()
17791 .and_then(|descendant| descendant.upgrade())
17792 {
17793 window.focus(&descendant);
17794 } else {
17795 if let Some(blame) = self.blame.as_ref() {
17796 blame.update(cx, GitBlame::focus)
17797 }
17798
17799 self.blink_manager.update(cx, BlinkManager::enable);
17800 self.show_cursor_names(window, cx);
17801 self.buffer.update(cx, |buffer, cx| {
17802 buffer.finalize_last_transaction(cx);
17803 if self.leader_peer_id.is_none() {
17804 buffer.set_active_selections(
17805 &self.selections.disjoint_anchors(),
17806 self.selections.line_mode,
17807 self.cursor_shape,
17808 cx,
17809 );
17810 }
17811 });
17812 }
17813 }
17814
17815 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17816 cx.emit(EditorEvent::FocusedIn)
17817 }
17818
17819 fn handle_focus_out(
17820 &mut self,
17821 event: FocusOutEvent,
17822 _window: &mut Window,
17823 cx: &mut Context<Self>,
17824 ) {
17825 if event.blurred != self.focus_handle {
17826 self.last_focused_descendant = Some(event.blurred);
17827 }
17828 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17829 }
17830
17831 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17832 self.blink_manager.update(cx, BlinkManager::disable);
17833 self.buffer
17834 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17835
17836 if let Some(blame) = self.blame.as_ref() {
17837 blame.update(cx, GitBlame::blur)
17838 }
17839 if !self.hover_state.focused(window, cx) {
17840 hide_hover(self, cx);
17841 }
17842 if !self
17843 .context_menu
17844 .borrow()
17845 .as_ref()
17846 .is_some_and(|context_menu| context_menu.focused(window, cx))
17847 {
17848 self.hide_context_menu(window, cx);
17849 }
17850 self.discard_inline_completion(false, cx);
17851 cx.emit(EditorEvent::Blurred);
17852 cx.notify();
17853 }
17854
17855 pub fn register_action<A: Action>(
17856 &mut self,
17857 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17858 ) -> Subscription {
17859 let id = self.next_editor_action_id.post_inc();
17860 let listener = Arc::new(listener);
17861 self.editor_actions.borrow_mut().insert(
17862 id,
17863 Box::new(move |window, _| {
17864 let listener = listener.clone();
17865 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17866 let action = action.downcast_ref().unwrap();
17867 if phase == DispatchPhase::Bubble {
17868 listener(action, window, cx)
17869 }
17870 })
17871 }),
17872 );
17873
17874 let editor_actions = self.editor_actions.clone();
17875 Subscription::new(move || {
17876 editor_actions.borrow_mut().remove(&id);
17877 })
17878 }
17879
17880 pub fn file_header_size(&self) -> u32 {
17881 FILE_HEADER_HEIGHT
17882 }
17883
17884 pub fn restore(
17885 &mut self,
17886 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17887 window: &mut Window,
17888 cx: &mut Context<Self>,
17889 ) {
17890 let workspace = self.workspace();
17891 let project = self.project.as_ref();
17892 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17893 let mut tasks = Vec::new();
17894 for (buffer_id, changes) in revert_changes {
17895 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17896 buffer.update(cx, |buffer, cx| {
17897 buffer.edit(
17898 changes
17899 .into_iter()
17900 .map(|(range, text)| (range, text.to_string())),
17901 None,
17902 cx,
17903 );
17904 });
17905
17906 if let Some(project) =
17907 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17908 {
17909 project.update(cx, |project, cx| {
17910 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17911 })
17912 }
17913 }
17914 }
17915 tasks
17916 });
17917 cx.spawn_in(window, async move |_, cx| {
17918 for (buffer, task) in save_tasks {
17919 let result = task.await;
17920 if result.is_err() {
17921 let Some(path) = buffer
17922 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17923 .ok()
17924 else {
17925 continue;
17926 };
17927 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17928 let Some(task) = cx
17929 .update_window_entity(&workspace, |workspace, window, cx| {
17930 workspace
17931 .open_path_preview(path, None, false, false, false, window, cx)
17932 })
17933 .ok()
17934 else {
17935 continue;
17936 };
17937 task.await.log_err();
17938 }
17939 }
17940 }
17941 })
17942 .detach();
17943 self.change_selections(None, window, cx, |selections| selections.refresh());
17944 }
17945
17946 pub fn to_pixel_point(
17947 &self,
17948 source: multi_buffer::Anchor,
17949 editor_snapshot: &EditorSnapshot,
17950 window: &mut Window,
17951 ) -> Option<gpui::Point<Pixels>> {
17952 let source_point = source.to_display_point(editor_snapshot);
17953 self.display_to_pixel_point(source_point, editor_snapshot, window)
17954 }
17955
17956 pub fn display_to_pixel_point(
17957 &self,
17958 source: DisplayPoint,
17959 editor_snapshot: &EditorSnapshot,
17960 window: &mut Window,
17961 ) -> Option<gpui::Point<Pixels>> {
17962 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17963 let text_layout_details = self.text_layout_details(window);
17964 let scroll_top = text_layout_details
17965 .scroll_anchor
17966 .scroll_position(editor_snapshot)
17967 .y;
17968
17969 if source.row().as_f32() < scroll_top.floor() {
17970 return None;
17971 }
17972 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17973 let source_y = line_height * (source.row().as_f32() - scroll_top);
17974 Some(gpui::Point::new(source_x, source_y))
17975 }
17976
17977 pub fn has_visible_completions_menu(&self) -> bool {
17978 !self.edit_prediction_preview_is_active()
17979 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17980 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17981 })
17982 }
17983
17984 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17985 self.addons
17986 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17987 }
17988
17989 pub fn unregister_addon<T: Addon>(&mut self) {
17990 self.addons.remove(&std::any::TypeId::of::<T>());
17991 }
17992
17993 pub fn addon<T: Addon>(&self) -> Option<&T> {
17994 let type_id = std::any::TypeId::of::<T>();
17995 self.addons
17996 .get(&type_id)
17997 .and_then(|item| item.to_any().downcast_ref::<T>())
17998 }
17999
18000 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18001 let text_layout_details = self.text_layout_details(window);
18002 let style = &text_layout_details.editor_style;
18003 let font_id = window.text_system().resolve_font(&style.text.font());
18004 let font_size = style.text.font_size.to_pixels(window.rem_size());
18005 let line_height = style.text.line_height_in_pixels(window.rem_size());
18006 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18007
18008 gpui::Size::new(em_width, line_height)
18009 }
18010
18011 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18012 self.load_diff_task.clone()
18013 }
18014
18015 fn read_metadata_from_db(
18016 &mut self,
18017 item_id: u64,
18018 workspace_id: WorkspaceId,
18019 window: &mut Window,
18020 cx: &mut Context<Editor>,
18021 ) {
18022 if self.is_singleton(cx)
18023 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18024 {
18025 let buffer_snapshot = OnceCell::new();
18026
18027 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18028 if !folds.is_empty() {
18029 let snapshot =
18030 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18031 self.fold_ranges(
18032 folds
18033 .into_iter()
18034 .map(|(start, end)| {
18035 snapshot.clip_offset(start, Bias::Left)
18036 ..snapshot.clip_offset(end, Bias::Right)
18037 })
18038 .collect(),
18039 false,
18040 window,
18041 cx,
18042 );
18043 }
18044 }
18045
18046 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18047 if !selections.is_empty() {
18048 let snapshot =
18049 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18050 self.change_selections(None, window, cx, |s| {
18051 s.select_ranges(selections.into_iter().map(|(start, end)| {
18052 snapshot.clip_offset(start, Bias::Left)
18053 ..snapshot.clip_offset(end, Bias::Right)
18054 }));
18055 });
18056 }
18057 };
18058 }
18059
18060 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18061 }
18062}
18063
18064// Consider user intent and default settings
18065fn choose_completion_range(
18066 completion: &Completion,
18067 intent: CompletionIntent,
18068 buffer: &Entity<Buffer>,
18069 cx: &mut Context<Editor>,
18070) -> Range<usize> {
18071 fn should_replace(
18072 completion: &Completion,
18073 insert_range: &Range<text::Anchor>,
18074 intent: CompletionIntent,
18075 completion_mode_setting: LspInsertMode,
18076 buffer: &Buffer,
18077 ) -> bool {
18078 // specific actions take precedence over settings
18079 match intent {
18080 CompletionIntent::CompleteWithInsert => return false,
18081 CompletionIntent::CompleteWithReplace => return true,
18082 CompletionIntent::Complete | CompletionIntent::Compose => {}
18083 }
18084
18085 match completion_mode_setting {
18086 LspInsertMode::Insert => false,
18087 LspInsertMode::Replace => true,
18088 LspInsertMode::ReplaceSubsequence => {
18089 let mut text_to_replace = buffer.chars_for_range(
18090 buffer.anchor_before(completion.replace_range.start)
18091 ..buffer.anchor_after(completion.replace_range.end),
18092 );
18093 let mut completion_text = completion.new_text.chars();
18094
18095 // is `text_to_replace` a subsequence of `completion_text`
18096 text_to_replace
18097 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18098 }
18099 LspInsertMode::ReplaceSuffix => {
18100 let range_after_cursor = insert_range.end..completion.replace_range.end;
18101
18102 let text_after_cursor = buffer
18103 .text_for_range(
18104 buffer.anchor_before(range_after_cursor.start)
18105 ..buffer.anchor_after(range_after_cursor.end),
18106 )
18107 .collect::<String>();
18108 completion.new_text.ends_with(&text_after_cursor)
18109 }
18110 }
18111 }
18112
18113 let buffer = buffer.read(cx);
18114
18115 if let CompletionSource::Lsp {
18116 insert_range: Some(insert_range),
18117 ..
18118 } = &completion.source
18119 {
18120 let completion_mode_setting =
18121 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18122 .completions
18123 .lsp_insert_mode;
18124
18125 if !should_replace(
18126 completion,
18127 &insert_range,
18128 intent,
18129 completion_mode_setting,
18130 buffer,
18131 ) {
18132 return insert_range.to_offset(buffer);
18133 }
18134 }
18135
18136 completion.replace_range.to_offset(buffer)
18137}
18138
18139fn insert_extra_newline_brackets(
18140 buffer: &MultiBufferSnapshot,
18141 range: Range<usize>,
18142 language: &language::LanguageScope,
18143) -> bool {
18144 let leading_whitespace_len = buffer
18145 .reversed_chars_at(range.start)
18146 .take_while(|c| c.is_whitespace() && *c != '\n')
18147 .map(|c| c.len_utf8())
18148 .sum::<usize>();
18149 let trailing_whitespace_len = buffer
18150 .chars_at(range.end)
18151 .take_while(|c| c.is_whitespace() && *c != '\n')
18152 .map(|c| c.len_utf8())
18153 .sum::<usize>();
18154 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18155
18156 language.brackets().any(|(pair, enabled)| {
18157 let pair_start = pair.start.trim_end();
18158 let pair_end = pair.end.trim_start();
18159
18160 enabled
18161 && pair.newline
18162 && buffer.contains_str_at(range.end, pair_end)
18163 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18164 })
18165}
18166
18167fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18168 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18169 [(buffer, range, _)] => (*buffer, range.clone()),
18170 _ => return false,
18171 };
18172 let pair = {
18173 let mut result: Option<BracketMatch> = None;
18174
18175 for pair in buffer
18176 .all_bracket_ranges(range.clone())
18177 .filter(move |pair| {
18178 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18179 })
18180 {
18181 let len = pair.close_range.end - pair.open_range.start;
18182
18183 if let Some(existing) = &result {
18184 let existing_len = existing.close_range.end - existing.open_range.start;
18185 if len > existing_len {
18186 continue;
18187 }
18188 }
18189
18190 result = Some(pair);
18191 }
18192
18193 result
18194 };
18195 let Some(pair) = pair else {
18196 return false;
18197 };
18198 pair.newline_only
18199 && buffer
18200 .chars_for_range(pair.open_range.end..range.start)
18201 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18202 .all(|c| c.is_whitespace() && c != '\n')
18203}
18204
18205fn get_uncommitted_diff_for_buffer(
18206 project: &Entity<Project>,
18207 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18208 buffer: Entity<MultiBuffer>,
18209 cx: &mut App,
18210) -> Task<()> {
18211 let mut tasks = Vec::new();
18212 project.update(cx, |project, cx| {
18213 for buffer in buffers {
18214 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18215 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18216 }
18217 }
18218 });
18219 cx.spawn(async move |cx| {
18220 let diffs = future::join_all(tasks).await;
18221 buffer
18222 .update(cx, |buffer, cx| {
18223 for diff in diffs.into_iter().flatten() {
18224 buffer.add_diff(diff, cx);
18225 }
18226 })
18227 .ok();
18228 })
18229}
18230
18231fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18232 let tab_size = tab_size.get() as usize;
18233 let mut width = offset;
18234
18235 for ch in text.chars() {
18236 width += if ch == '\t' {
18237 tab_size - (width % tab_size)
18238 } else {
18239 1
18240 };
18241 }
18242
18243 width - offset
18244}
18245
18246#[cfg(test)]
18247mod tests {
18248 use super::*;
18249
18250 #[test]
18251 fn test_string_size_with_expanded_tabs() {
18252 let nz = |val| NonZeroU32::new(val).unwrap();
18253 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18254 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18255 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18256 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18257 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18258 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18259 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18260 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18261 }
18262}
18263
18264/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18265struct WordBreakingTokenizer<'a> {
18266 input: &'a str,
18267}
18268
18269impl<'a> WordBreakingTokenizer<'a> {
18270 fn new(input: &'a str) -> Self {
18271 Self { input }
18272 }
18273}
18274
18275fn is_char_ideographic(ch: char) -> bool {
18276 use unicode_script::Script::*;
18277 use unicode_script::UnicodeScript;
18278 matches!(ch.script(), Han | Tangut | Yi)
18279}
18280
18281fn is_grapheme_ideographic(text: &str) -> bool {
18282 text.chars().any(is_char_ideographic)
18283}
18284
18285fn is_grapheme_whitespace(text: &str) -> bool {
18286 text.chars().any(|x| x.is_whitespace())
18287}
18288
18289fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18290 text.chars().next().map_or(false, |ch| {
18291 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18292 })
18293}
18294
18295#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18296enum WordBreakToken<'a> {
18297 Word { token: &'a str, grapheme_len: usize },
18298 InlineWhitespace { token: &'a str, grapheme_len: usize },
18299 Newline,
18300}
18301
18302impl<'a> Iterator for WordBreakingTokenizer<'a> {
18303 /// Yields a span, the count of graphemes in the token, and whether it was
18304 /// whitespace. Note that it also breaks at word boundaries.
18305 type Item = WordBreakToken<'a>;
18306
18307 fn next(&mut self) -> Option<Self::Item> {
18308 use unicode_segmentation::UnicodeSegmentation;
18309 if self.input.is_empty() {
18310 return None;
18311 }
18312
18313 let mut iter = self.input.graphemes(true).peekable();
18314 let mut offset = 0;
18315 let mut grapheme_len = 0;
18316 if let Some(first_grapheme) = iter.next() {
18317 let is_newline = first_grapheme == "\n";
18318 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18319 offset += first_grapheme.len();
18320 grapheme_len += 1;
18321 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18322 if let Some(grapheme) = iter.peek().copied() {
18323 if should_stay_with_preceding_ideograph(grapheme) {
18324 offset += grapheme.len();
18325 grapheme_len += 1;
18326 }
18327 }
18328 } else {
18329 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18330 let mut next_word_bound = words.peek().copied();
18331 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18332 next_word_bound = words.next();
18333 }
18334 while let Some(grapheme) = iter.peek().copied() {
18335 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18336 break;
18337 };
18338 if is_grapheme_whitespace(grapheme) != is_whitespace
18339 || (grapheme == "\n") != is_newline
18340 {
18341 break;
18342 };
18343 offset += grapheme.len();
18344 grapheme_len += 1;
18345 iter.next();
18346 }
18347 }
18348 let token = &self.input[..offset];
18349 self.input = &self.input[offset..];
18350 if token == "\n" {
18351 Some(WordBreakToken::Newline)
18352 } else if is_whitespace {
18353 Some(WordBreakToken::InlineWhitespace {
18354 token,
18355 grapheme_len,
18356 })
18357 } else {
18358 Some(WordBreakToken::Word {
18359 token,
18360 grapheme_len,
18361 })
18362 }
18363 } else {
18364 None
18365 }
18366 }
18367}
18368
18369#[test]
18370fn test_word_breaking_tokenizer() {
18371 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18372 ("", &[]),
18373 (" ", &[whitespace(" ", 2)]),
18374 ("Ʒ", &[word("Ʒ", 1)]),
18375 ("Ǽ", &[word("Ǽ", 1)]),
18376 ("⋑", &[word("⋑", 1)]),
18377 ("⋑⋑", &[word("⋑⋑", 2)]),
18378 (
18379 "原理,进而",
18380 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18381 ),
18382 (
18383 "hello world",
18384 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18385 ),
18386 (
18387 "hello, world",
18388 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18389 ),
18390 (
18391 " hello world",
18392 &[
18393 whitespace(" ", 2),
18394 word("hello", 5),
18395 whitespace(" ", 1),
18396 word("world", 5),
18397 ],
18398 ),
18399 (
18400 "这是什么 \n 钢笔",
18401 &[
18402 word("这", 1),
18403 word("是", 1),
18404 word("什", 1),
18405 word("么", 1),
18406 whitespace(" ", 1),
18407 newline(),
18408 whitespace(" ", 1),
18409 word("钢", 1),
18410 word("笔", 1),
18411 ],
18412 ),
18413 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18414 ];
18415
18416 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18417 WordBreakToken::Word {
18418 token,
18419 grapheme_len,
18420 }
18421 }
18422
18423 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18424 WordBreakToken::InlineWhitespace {
18425 token,
18426 grapheme_len,
18427 }
18428 }
18429
18430 fn newline() -> WordBreakToken<'static> {
18431 WordBreakToken::Newline
18432 }
18433
18434 for (input, result) in tests {
18435 assert_eq!(
18436 WordBreakingTokenizer::new(input)
18437 .collect::<Vec<_>>()
18438 .as_slice(),
18439 *result,
18440 );
18441 }
18442}
18443
18444fn wrap_with_prefix(
18445 line_prefix: String,
18446 unwrapped_text: String,
18447 wrap_column: usize,
18448 tab_size: NonZeroU32,
18449 preserve_existing_whitespace: bool,
18450) -> String {
18451 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18452 let mut wrapped_text = String::new();
18453 let mut current_line = line_prefix.clone();
18454
18455 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18456 let mut current_line_len = line_prefix_len;
18457 let mut in_whitespace = false;
18458 for token in tokenizer {
18459 let have_preceding_whitespace = in_whitespace;
18460 match token {
18461 WordBreakToken::Word {
18462 token,
18463 grapheme_len,
18464 } => {
18465 in_whitespace = false;
18466 if current_line_len + grapheme_len > wrap_column
18467 && current_line_len != line_prefix_len
18468 {
18469 wrapped_text.push_str(current_line.trim_end());
18470 wrapped_text.push('\n');
18471 current_line.truncate(line_prefix.len());
18472 current_line_len = line_prefix_len;
18473 }
18474 current_line.push_str(token);
18475 current_line_len += grapheme_len;
18476 }
18477 WordBreakToken::InlineWhitespace {
18478 mut token,
18479 mut grapheme_len,
18480 } => {
18481 in_whitespace = true;
18482 if have_preceding_whitespace && !preserve_existing_whitespace {
18483 continue;
18484 }
18485 if !preserve_existing_whitespace {
18486 token = " ";
18487 grapheme_len = 1;
18488 }
18489 if current_line_len + grapheme_len > wrap_column {
18490 wrapped_text.push_str(current_line.trim_end());
18491 wrapped_text.push('\n');
18492 current_line.truncate(line_prefix.len());
18493 current_line_len = line_prefix_len;
18494 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18495 current_line.push_str(token);
18496 current_line_len += grapheme_len;
18497 }
18498 }
18499 WordBreakToken::Newline => {
18500 in_whitespace = true;
18501 if preserve_existing_whitespace {
18502 wrapped_text.push_str(current_line.trim_end());
18503 wrapped_text.push('\n');
18504 current_line.truncate(line_prefix.len());
18505 current_line_len = line_prefix_len;
18506 } else if have_preceding_whitespace {
18507 continue;
18508 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18509 {
18510 wrapped_text.push_str(current_line.trim_end());
18511 wrapped_text.push('\n');
18512 current_line.truncate(line_prefix.len());
18513 current_line_len = line_prefix_len;
18514 } else if current_line_len != line_prefix_len {
18515 current_line.push(' ');
18516 current_line_len += 1;
18517 }
18518 }
18519 }
18520 }
18521
18522 if !current_line.is_empty() {
18523 wrapped_text.push_str(¤t_line);
18524 }
18525 wrapped_text
18526}
18527
18528#[test]
18529fn test_wrap_with_prefix() {
18530 assert_eq!(
18531 wrap_with_prefix(
18532 "# ".to_string(),
18533 "abcdefg".to_string(),
18534 4,
18535 NonZeroU32::new(4).unwrap(),
18536 false,
18537 ),
18538 "# abcdefg"
18539 );
18540 assert_eq!(
18541 wrap_with_prefix(
18542 "".to_string(),
18543 "\thello world".to_string(),
18544 8,
18545 NonZeroU32::new(4).unwrap(),
18546 false,
18547 ),
18548 "hello\nworld"
18549 );
18550 assert_eq!(
18551 wrap_with_prefix(
18552 "// ".to_string(),
18553 "xx \nyy zz aa bb cc".to_string(),
18554 12,
18555 NonZeroU32::new(4).unwrap(),
18556 false,
18557 ),
18558 "// xx yy zz\n// aa bb cc"
18559 );
18560 assert_eq!(
18561 wrap_with_prefix(
18562 String::new(),
18563 "这是什么 \n 钢笔".to_string(),
18564 3,
18565 NonZeroU32::new(4).unwrap(),
18566 false,
18567 ),
18568 "这是什\n么 钢\n笔"
18569 );
18570}
18571
18572pub trait CollaborationHub {
18573 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18574 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18575 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18576}
18577
18578impl CollaborationHub for Entity<Project> {
18579 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18580 self.read(cx).collaborators()
18581 }
18582
18583 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18584 self.read(cx).user_store().read(cx).participant_indices()
18585 }
18586
18587 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18588 let this = self.read(cx);
18589 let user_ids = this.collaborators().values().map(|c| c.user_id);
18590 this.user_store().read_with(cx, |user_store, cx| {
18591 user_store.participant_names(user_ids, cx)
18592 })
18593 }
18594}
18595
18596pub trait SemanticsProvider {
18597 fn hover(
18598 &self,
18599 buffer: &Entity<Buffer>,
18600 position: text::Anchor,
18601 cx: &mut App,
18602 ) -> Option<Task<Vec<project::Hover>>>;
18603
18604 fn inlay_hints(
18605 &self,
18606 buffer_handle: Entity<Buffer>,
18607 range: Range<text::Anchor>,
18608 cx: &mut App,
18609 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18610
18611 fn resolve_inlay_hint(
18612 &self,
18613 hint: InlayHint,
18614 buffer_handle: Entity<Buffer>,
18615 server_id: LanguageServerId,
18616 cx: &mut App,
18617 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18618
18619 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18620
18621 fn document_highlights(
18622 &self,
18623 buffer: &Entity<Buffer>,
18624 position: text::Anchor,
18625 cx: &mut App,
18626 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18627
18628 fn definitions(
18629 &self,
18630 buffer: &Entity<Buffer>,
18631 position: text::Anchor,
18632 kind: GotoDefinitionKind,
18633 cx: &mut App,
18634 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18635
18636 fn range_for_rename(
18637 &self,
18638 buffer: &Entity<Buffer>,
18639 position: text::Anchor,
18640 cx: &mut App,
18641 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18642
18643 fn perform_rename(
18644 &self,
18645 buffer: &Entity<Buffer>,
18646 position: text::Anchor,
18647 new_name: String,
18648 cx: &mut App,
18649 ) -> Option<Task<Result<ProjectTransaction>>>;
18650}
18651
18652pub trait CompletionProvider {
18653 fn completions(
18654 &self,
18655 excerpt_id: ExcerptId,
18656 buffer: &Entity<Buffer>,
18657 buffer_position: text::Anchor,
18658 trigger: CompletionContext,
18659 window: &mut Window,
18660 cx: &mut Context<Editor>,
18661 ) -> Task<Result<Option<Vec<Completion>>>>;
18662
18663 fn resolve_completions(
18664 &self,
18665 buffer: Entity<Buffer>,
18666 completion_indices: Vec<usize>,
18667 completions: Rc<RefCell<Box<[Completion]>>>,
18668 cx: &mut Context<Editor>,
18669 ) -> Task<Result<bool>>;
18670
18671 fn apply_additional_edits_for_completion(
18672 &self,
18673 _buffer: Entity<Buffer>,
18674 _completions: Rc<RefCell<Box<[Completion]>>>,
18675 _completion_index: usize,
18676 _push_to_history: bool,
18677 _cx: &mut Context<Editor>,
18678 ) -> Task<Result<Option<language::Transaction>>> {
18679 Task::ready(Ok(None))
18680 }
18681
18682 fn is_completion_trigger(
18683 &self,
18684 buffer: &Entity<Buffer>,
18685 position: language::Anchor,
18686 text: &str,
18687 trigger_in_words: bool,
18688 cx: &mut Context<Editor>,
18689 ) -> bool;
18690
18691 fn sort_completions(&self) -> bool {
18692 true
18693 }
18694
18695 fn filter_completions(&self) -> bool {
18696 true
18697 }
18698}
18699
18700pub trait CodeActionProvider {
18701 fn id(&self) -> Arc<str>;
18702
18703 fn code_actions(
18704 &self,
18705 buffer: &Entity<Buffer>,
18706 range: Range<text::Anchor>,
18707 window: &mut Window,
18708 cx: &mut App,
18709 ) -> Task<Result<Vec<CodeAction>>>;
18710
18711 fn apply_code_action(
18712 &self,
18713 buffer_handle: Entity<Buffer>,
18714 action: CodeAction,
18715 excerpt_id: ExcerptId,
18716 push_to_history: bool,
18717 window: &mut Window,
18718 cx: &mut App,
18719 ) -> Task<Result<ProjectTransaction>>;
18720}
18721
18722impl CodeActionProvider for Entity<Project> {
18723 fn id(&self) -> Arc<str> {
18724 "project".into()
18725 }
18726
18727 fn code_actions(
18728 &self,
18729 buffer: &Entity<Buffer>,
18730 range: Range<text::Anchor>,
18731 _window: &mut Window,
18732 cx: &mut App,
18733 ) -> Task<Result<Vec<CodeAction>>> {
18734 self.update(cx, |project, cx| {
18735 let code_lens = project.code_lens(buffer, range.clone(), cx);
18736 let code_actions = project.code_actions(buffer, range, None, cx);
18737 cx.background_spawn(async move {
18738 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18739 Ok(code_lens
18740 .context("code lens fetch")?
18741 .into_iter()
18742 .chain(code_actions.context("code action fetch")?)
18743 .collect())
18744 })
18745 })
18746 }
18747
18748 fn apply_code_action(
18749 &self,
18750 buffer_handle: Entity<Buffer>,
18751 action: CodeAction,
18752 _excerpt_id: ExcerptId,
18753 push_to_history: bool,
18754 _window: &mut Window,
18755 cx: &mut App,
18756 ) -> Task<Result<ProjectTransaction>> {
18757 self.update(cx, |project, cx| {
18758 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18759 })
18760 }
18761}
18762
18763fn snippet_completions(
18764 project: &Project,
18765 buffer: &Entity<Buffer>,
18766 buffer_position: text::Anchor,
18767 cx: &mut App,
18768) -> Task<Result<Vec<Completion>>> {
18769 let language = buffer.read(cx).language_at(buffer_position);
18770 let language_name = language.as_ref().map(|language| language.lsp_id());
18771 let snippet_store = project.snippets().read(cx);
18772 let snippets = snippet_store.snippets_for(language_name, cx);
18773
18774 if snippets.is_empty() {
18775 return Task::ready(Ok(vec![]));
18776 }
18777 let snapshot = buffer.read(cx).text_snapshot();
18778 let chars: String = snapshot
18779 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18780 .collect();
18781
18782 let scope = language.map(|language| language.default_scope());
18783 let executor = cx.background_executor().clone();
18784
18785 cx.background_spawn(async move {
18786 let classifier = CharClassifier::new(scope).for_completion(true);
18787 let mut last_word = chars
18788 .chars()
18789 .take_while(|c| classifier.is_word(*c))
18790 .collect::<String>();
18791 last_word = last_word.chars().rev().collect();
18792
18793 if last_word.is_empty() {
18794 return Ok(vec![]);
18795 }
18796
18797 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18798 let to_lsp = |point: &text::Anchor| {
18799 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18800 point_to_lsp(end)
18801 };
18802 let lsp_end = to_lsp(&buffer_position);
18803
18804 let candidates = snippets
18805 .iter()
18806 .enumerate()
18807 .flat_map(|(ix, snippet)| {
18808 snippet
18809 .prefix
18810 .iter()
18811 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18812 })
18813 .collect::<Vec<StringMatchCandidate>>();
18814
18815 let mut matches = fuzzy::match_strings(
18816 &candidates,
18817 &last_word,
18818 last_word.chars().any(|c| c.is_uppercase()),
18819 100,
18820 &Default::default(),
18821 executor,
18822 )
18823 .await;
18824
18825 // Remove all candidates where the query's start does not match the start of any word in the candidate
18826 if let Some(query_start) = last_word.chars().next() {
18827 matches.retain(|string_match| {
18828 split_words(&string_match.string).any(|word| {
18829 // Check that the first codepoint of the word as lowercase matches the first
18830 // codepoint of the query as lowercase
18831 word.chars()
18832 .flat_map(|codepoint| codepoint.to_lowercase())
18833 .zip(query_start.to_lowercase())
18834 .all(|(word_cp, query_cp)| word_cp == query_cp)
18835 })
18836 });
18837 }
18838
18839 let matched_strings = matches
18840 .into_iter()
18841 .map(|m| m.string)
18842 .collect::<HashSet<_>>();
18843
18844 let result: Vec<Completion> = snippets
18845 .into_iter()
18846 .filter_map(|snippet| {
18847 let matching_prefix = snippet
18848 .prefix
18849 .iter()
18850 .find(|prefix| matched_strings.contains(*prefix))?;
18851 let start = as_offset - last_word.len();
18852 let start = snapshot.anchor_before(start);
18853 let range = start..buffer_position;
18854 let lsp_start = to_lsp(&start);
18855 let lsp_range = lsp::Range {
18856 start: lsp_start,
18857 end: lsp_end,
18858 };
18859 Some(Completion {
18860 replace_range: range,
18861 new_text: snippet.body.clone(),
18862 source: CompletionSource::Lsp {
18863 insert_range: None,
18864 server_id: LanguageServerId(usize::MAX),
18865 resolved: true,
18866 lsp_completion: Box::new(lsp::CompletionItem {
18867 label: snippet.prefix.first().unwrap().clone(),
18868 kind: Some(CompletionItemKind::SNIPPET),
18869 label_details: snippet.description.as_ref().map(|description| {
18870 lsp::CompletionItemLabelDetails {
18871 detail: Some(description.clone()),
18872 description: None,
18873 }
18874 }),
18875 insert_text_format: Some(InsertTextFormat::SNIPPET),
18876 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18877 lsp::InsertReplaceEdit {
18878 new_text: snippet.body.clone(),
18879 insert: lsp_range,
18880 replace: lsp_range,
18881 },
18882 )),
18883 filter_text: Some(snippet.body.clone()),
18884 sort_text: Some(char::MAX.to_string()),
18885 ..lsp::CompletionItem::default()
18886 }),
18887 lsp_defaults: None,
18888 },
18889 label: CodeLabel {
18890 text: matching_prefix.clone(),
18891 runs: Vec::new(),
18892 filter_range: 0..matching_prefix.len(),
18893 },
18894 icon_path: None,
18895 documentation: snippet
18896 .description
18897 .clone()
18898 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18899 insert_text_mode: None,
18900 confirm: None,
18901 })
18902 })
18903 .collect();
18904
18905 Ok(result)
18906 })
18907}
18908
18909impl CompletionProvider for Entity<Project> {
18910 fn completions(
18911 &self,
18912 _excerpt_id: ExcerptId,
18913 buffer: &Entity<Buffer>,
18914 buffer_position: text::Anchor,
18915 options: CompletionContext,
18916 _window: &mut Window,
18917 cx: &mut Context<Editor>,
18918 ) -> Task<Result<Option<Vec<Completion>>>> {
18919 self.update(cx, |project, cx| {
18920 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18921 let project_completions = project.completions(buffer, buffer_position, options, cx);
18922 cx.background_spawn(async move {
18923 let snippets_completions = snippets.await?;
18924 match project_completions.await? {
18925 Some(mut completions) => {
18926 completions.extend(snippets_completions);
18927 Ok(Some(completions))
18928 }
18929 None => {
18930 if snippets_completions.is_empty() {
18931 Ok(None)
18932 } else {
18933 Ok(Some(snippets_completions))
18934 }
18935 }
18936 }
18937 })
18938 })
18939 }
18940
18941 fn resolve_completions(
18942 &self,
18943 buffer: Entity<Buffer>,
18944 completion_indices: Vec<usize>,
18945 completions: Rc<RefCell<Box<[Completion]>>>,
18946 cx: &mut Context<Editor>,
18947 ) -> Task<Result<bool>> {
18948 self.update(cx, |project, cx| {
18949 project.lsp_store().update(cx, |lsp_store, cx| {
18950 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18951 })
18952 })
18953 }
18954
18955 fn apply_additional_edits_for_completion(
18956 &self,
18957 buffer: Entity<Buffer>,
18958 completions: Rc<RefCell<Box<[Completion]>>>,
18959 completion_index: usize,
18960 push_to_history: bool,
18961 cx: &mut Context<Editor>,
18962 ) -> Task<Result<Option<language::Transaction>>> {
18963 self.update(cx, |project, cx| {
18964 project.lsp_store().update(cx, |lsp_store, cx| {
18965 lsp_store.apply_additional_edits_for_completion(
18966 buffer,
18967 completions,
18968 completion_index,
18969 push_to_history,
18970 cx,
18971 )
18972 })
18973 })
18974 }
18975
18976 fn is_completion_trigger(
18977 &self,
18978 buffer: &Entity<Buffer>,
18979 position: language::Anchor,
18980 text: &str,
18981 trigger_in_words: bool,
18982 cx: &mut Context<Editor>,
18983 ) -> bool {
18984 let mut chars = text.chars();
18985 let char = if let Some(char) = chars.next() {
18986 char
18987 } else {
18988 return false;
18989 };
18990 if chars.next().is_some() {
18991 return false;
18992 }
18993
18994 let buffer = buffer.read(cx);
18995 let snapshot = buffer.snapshot();
18996 if !snapshot.settings_at(position, cx).show_completions_on_input {
18997 return false;
18998 }
18999 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19000 if trigger_in_words && classifier.is_word(char) {
19001 return true;
19002 }
19003
19004 buffer.completion_triggers().contains(text)
19005 }
19006}
19007
19008impl SemanticsProvider for Entity<Project> {
19009 fn hover(
19010 &self,
19011 buffer: &Entity<Buffer>,
19012 position: text::Anchor,
19013 cx: &mut App,
19014 ) -> Option<Task<Vec<project::Hover>>> {
19015 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19016 }
19017
19018 fn document_highlights(
19019 &self,
19020 buffer: &Entity<Buffer>,
19021 position: text::Anchor,
19022 cx: &mut App,
19023 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19024 Some(self.update(cx, |project, cx| {
19025 project.document_highlights(buffer, position, cx)
19026 }))
19027 }
19028
19029 fn definitions(
19030 &self,
19031 buffer: &Entity<Buffer>,
19032 position: text::Anchor,
19033 kind: GotoDefinitionKind,
19034 cx: &mut App,
19035 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19036 Some(self.update(cx, |project, cx| match kind {
19037 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19038 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19039 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19040 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19041 }))
19042 }
19043
19044 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19045 // TODO: make this work for remote projects
19046 self.update(cx, |this, cx| {
19047 buffer.update(cx, |buffer, cx| {
19048 this.any_language_server_supports_inlay_hints(buffer, cx)
19049 })
19050 })
19051 }
19052
19053 fn inlay_hints(
19054 &self,
19055 buffer_handle: Entity<Buffer>,
19056 range: Range<text::Anchor>,
19057 cx: &mut App,
19058 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19059 Some(self.update(cx, |project, cx| {
19060 project.inlay_hints(buffer_handle, range, cx)
19061 }))
19062 }
19063
19064 fn resolve_inlay_hint(
19065 &self,
19066 hint: InlayHint,
19067 buffer_handle: Entity<Buffer>,
19068 server_id: LanguageServerId,
19069 cx: &mut App,
19070 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19071 Some(self.update(cx, |project, cx| {
19072 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19073 }))
19074 }
19075
19076 fn range_for_rename(
19077 &self,
19078 buffer: &Entity<Buffer>,
19079 position: text::Anchor,
19080 cx: &mut App,
19081 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19082 Some(self.update(cx, |project, cx| {
19083 let buffer = buffer.clone();
19084 let task = project.prepare_rename(buffer.clone(), position, cx);
19085 cx.spawn(async move |_, cx| {
19086 Ok(match task.await? {
19087 PrepareRenameResponse::Success(range) => Some(range),
19088 PrepareRenameResponse::InvalidPosition => None,
19089 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19090 // Fallback on using TreeSitter info to determine identifier range
19091 buffer.update(cx, |buffer, _| {
19092 let snapshot = buffer.snapshot();
19093 let (range, kind) = snapshot.surrounding_word(position);
19094 if kind != Some(CharKind::Word) {
19095 return None;
19096 }
19097 Some(
19098 snapshot.anchor_before(range.start)
19099 ..snapshot.anchor_after(range.end),
19100 )
19101 })?
19102 }
19103 })
19104 })
19105 }))
19106 }
19107
19108 fn perform_rename(
19109 &self,
19110 buffer: &Entity<Buffer>,
19111 position: text::Anchor,
19112 new_name: String,
19113 cx: &mut App,
19114 ) -> Option<Task<Result<ProjectTransaction>>> {
19115 Some(self.update(cx, |project, cx| {
19116 project.perform_rename(buffer.clone(), position, new_name, cx)
19117 }))
19118 }
19119}
19120
19121fn inlay_hint_settings(
19122 location: Anchor,
19123 snapshot: &MultiBufferSnapshot,
19124 cx: &mut Context<Editor>,
19125) -> InlayHintSettings {
19126 let file = snapshot.file_at(location);
19127 let language = snapshot.language_at(location).map(|l| l.name());
19128 language_settings(language, file, cx).inlay_hints
19129}
19130
19131fn consume_contiguous_rows(
19132 contiguous_row_selections: &mut Vec<Selection<Point>>,
19133 selection: &Selection<Point>,
19134 display_map: &DisplaySnapshot,
19135 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19136) -> (MultiBufferRow, MultiBufferRow) {
19137 contiguous_row_selections.push(selection.clone());
19138 let start_row = MultiBufferRow(selection.start.row);
19139 let mut end_row = ending_row(selection, display_map);
19140
19141 while let Some(next_selection) = selections.peek() {
19142 if next_selection.start.row <= end_row.0 {
19143 end_row = ending_row(next_selection, display_map);
19144 contiguous_row_selections.push(selections.next().unwrap().clone());
19145 } else {
19146 break;
19147 }
19148 }
19149 (start_row, end_row)
19150}
19151
19152fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19153 if next_selection.end.column > 0 || next_selection.is_empty() {
19154 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19155 } else {
19156 MultiBufferRow(next_selection.end.row)
19157 }
19158}
19159
19160impl EditorSnapshot {
19161 pub fn remote_selections_in_range<'a>(
19162 &'a self,
19163 range: &'a Range<Anchor>,
19164 collaboration_hub: &dyn CollaborationHub,
19165 cx: &'a App,
19166 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19167 let participant_names = collaboration_hub.user_names(cx);
19168 let participant_indices = collaboration_hub.user_participant_indices(cx);
19169 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19170 let collaborators_by_replica_id = collaborators_by_peer_id
19171 .iter()
19172 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19173 .collect::<HashMap<_, _>>();
19174 self.buffer_snapshot
19175 .selections_in_range(range, false)
19176 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19177 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19178 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19179 let user_name = participant_names.get(&collaborator.user_id).cloned();
19180 Some(RemoteSelection {
19181 replica_id,
19182 selection,
19183 cursor_shape,
19184 line_mode,
19185 participant_index,
19186 peer_id: collaborator.peer_id,
19187 user_name,
19188 })
19189 })
19190 }
19191
19192 pub fn hunks_for_ranges(
19193 &self,
19194 ranges: impl IntoIterator<Item = Range<Point>>,
19195 ) -> Vec<MultiBufferDiffHunk> {
19196 let mut hunks = Vec::new();
19197 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19198 HashMap::default();
19199 for query_range in ranges {
19200 let query_rows =
19201 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19202 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19203 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19204 ) {
19205 // Include deleted hunks that are adjacent to the query range, because
19206 // otherwise they would be missed.
19207 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19208 if hunk.status().is_deleted() {
19209 intersects_range |= hunk.row_range.start == query_rows.end;
19210 intersects_range |= hunk.row_range.end == query_rows.start;
19211 }
19212 if intersects_range {
19213 if !processed_buffer_rows
19214 .entry(hunk.buffer_id)
19215 .or_default()
19216 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19217 {
19218 continue;
19219 }
19220 hunks.push(hunk);
19221 }
19222 }
19223 }
19224
19225 hunks
19226 }
19227
19228 fn display_diff_hunks_for_rows<'a>(
19229 &'a self,
19230 display_rows: Range<DisplayRow>,
19231 folded_buffers: &'a HashSet<BufferId>,
19232 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19233 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19234 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19235
19236 self.buffer_snapshot
19237 .diff_hunks_in_range(buffer_start..buffer_end)
19238 .filter_map(|hunk| {
19239 if folded_buffers.contains(&hunk.buffer_id) {
19240 return None;
19241 }
19242
19243 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19244 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19245
19246 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19247 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19248
19249 let display_hunk = if hunk_display_start.column() != 0 {
19250 DisplayDiffHunk::Folded {
19251 display_row: hunk_display_start.row(),
19252 }
19253 } else {
19254 let mut end_row = hunk_display_end.row();
19255 if hunk_display_end.column() > 0 {
19256 end_row.0 += 1;
19257 }
19258 let is_created_file = hunk.is_created_file();
19259 DisplayDiffHunk::Unfolded {
19260 status: hunk.status(),
19261 diff_base_byte_range: hunk.diff_base_byte_range,
19262 display_row_range: hunk_display_start.row()..end_row,
19263 multi_buffer_range: Anchor::range_in_buffer(
19264 hunk.excerpt_id,
19265 hunk.buffer_id,
19266 hunk.buffer_range,
19267 ),
19268 is_created_file,
19269 }
19270 };
19271
19272 Some(display_hunk)
19273 })
19274 }
19275
19276 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19277 self.display_snapshot.buffer_snapshot.language_at(position)
19278 }
19279
19280 pub fn is_focused(&self) -> bool {
19281 self.is_focused
19282 }
19283
19284 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19285 self.placeholder_text.as_ref()
19286 }
19287
19288 pub fn scroll_position(&self) -> gpui::Point<f32> {
19289 self.scroll_anchor.scroll_position(&self.display_snapshot)
19290 }
19291
19292 fn gutter_dimensions(
19293 &self,
19294 font_id: FontId,
19295 font_size: Pixels,
19296 max_line_number_width: Pixels,
19297 cx: &App,
19298 ) -> Option<GutterDimensions> {
19299 if !self.show_gutter {
19300 return None;
19301 }
19302
19303 let descent = cx.text_system().descent(font_id, font_size);
19304 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19305 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19306
19307 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19308 matches!(
19309 ProjectSettings::get_global(cx).git.git_gutter,
19310 Some(GitGutterSetting::TrackedFiles)
19311 )
19312 });
19313 let gutter_settings = EditorSettings::get_global(cx).gutter;
19314 let show_line_numbers = self
19315 .show_line_numbers
19316 .unwrap_or(gutter_settings.line_numbers);
19317 let line_gutter_width = if show_line_numbers {
19318 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19319 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19320 max_line_number_width.max(min_width_for_number_on_gutter)
19321 } else {
19322 0.0.into()
19323 };
19324
19325 let show_code_actions = self
19326 .show_code_actions
19327 .unwrap_or(gutter_settings.code_actions);
19328
19329 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19330 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19331
19332 let git_blame_entries_width =
19333 self.git_blame_gutter_max_author_length
19334 .map(|max_author_length| {
19335 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19336 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19337
19338 /// The number of characters to dedicate to gaps and margins.
19339 const SPACING_WIDTH: usize = 4;
19340
19341 let max_char_count = max_author_length.min(renderer.max_author_length())
19342 + ::git::SHORT_SHA_LENGTH
19343 + MAX_RELATIVE_TIMESTAMP.len()
19344 + SPACING_WIDTH;
19345
19346 em_advance * max_char_count
19347 });
19348
19349 let is_singleton = self.buffer_snapshot.is_singleton();
19350
19351 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19352 left_padding += if !is_singleton {
19353 em_width * 4.0
19354 } else if show_code_actions || show_runnables || show_breakpoints {
19355 em_width * 3.0
19356 } else if show_git_gutter && show_line_numbers {
19357 em_width * 2.0
19358 } else if show_git_gutter || show_line_numbers {
19359 em_width
19360 } else {
19361 px(0.)
19362 };
19363
19364 let shows_folds = is_singleton && gutter_settings.folds;
19365
19366 let right_padding = if shows_folds && show_line_numbers {
19367 em_width * 4.0
19368 } else if shows_folds || (!is_singleton && show_line_numbers) {
19369 em_width * 3.0
19370 } else if show_line_numbers {
19371 em_width
19372 } else {
19373 px(0.)
19374 };
19375
19376 Some(GutterDimensions {
19377 left_padding,
19378 right_padding,
19379 width: line_gutter_width + left_padding + right_padding,
19380 margin: -descent,
19381 git_blame_entries_width,
19382 })
19383 }
19384
19385 pub fn render_crease_toggle(
19386 &self,
19387 buffer_row: MultiBufferRow,
19388 row_contains_cursor: bool,
19389 editor: Entity<Editor>,
19390 window: &mut Window,
19391 cx: &mut App,
19392 ) -> Option<AnyElement> {
19393 let folded = self.is_line_folded(buffer_row);
19394 let mut is_foldable = false;
19395
19396 if let Some(crease) = self
19397 .crease_snapshot
19398 .query_row(buffer_row, &self.buffer_snapshot)
19399 {
19400 is_foldable = true;
19401 match crease {
19402 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19403 if let Some(render_toggle) = render_toggle {
19404 let toggle_callback =
19405 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19406 if folded {
19407 editor.update(cx, |editor, cx| {
19408 editor.fold_at(buffer_row, window, cx)
19409 });
19410 } else {
19411 editor.update(cx, |editor, cx| {
19412 editor.unfold_at(buffer_row, window, cx)
19413 });
19414 }
19415 });
19416 return Some((render_toggle)(
19417 buffer_row,
19418 folded,
19419 toggle_callback,
19420 window,
19421 cx,
19422 ));
19423 }
19424 }
19425 }
19426 }
19427
19428 is_foldable |= self.starts_indent(buffer_row);
19429
19430 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19431 Some(
19432 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19433 .toggle_state(folded)
19434 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19435 if folded {
19436 this.unfold_at(buffer_row, window, cx);
19437 } else {
19438 this.fold_at(buffer_row, window, cx);
19439 }
19440 }))
19441 .into_any_element(),
19442 )
19443 } else {
19444 None
19445 }
19446 }
19447
19448 pub fn render_crease_trailer(
19449 &self,
19450 buffer_row: MultiBufferRow,
19451 window: &mut Window,
19452 cx: &mut App,
19453 ) -> Option<AnyElement> {
19454 let folded = self.is_line_folded(buffer_row);
19455 if let Crease::Inline { render_trailer, .. } = self
19456 .crease_snapshot
19457 .query_row(buffer_row, &self.buffer_snapshot)?
19458 {
19459 let render_trailer = render_trailer.as_ref()?;
19460 Some(render_trailer(buffer_row, folded, window, cx))
19461 } else {
19462 None
19463 }
19464 }
19465}
19466
19467impl Deref for EditorSnapshot {
19468 type Target = DisplaySnapshot;
19469
19470 fn deref(&self) -> &Self::Target {
19471 &self.display_snapshot
19472 }
19473}
19474
19475#[derive(Clone, Debug, PartialEq, Eq)]
19476pub enum EditorEvent {
19477 InputIgnored {
19478 text: Arc<str>,
19479 },
19480 InputHandled {
19481 utf16_range_to_replace: Option<Range<isize>>,
19482 text: Arc<str>,
19483 },
19484 ExcerptsAdded {
19485 buffer: Entity<Buffer>,
19486 predecessor: ExcerptId,
19487 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19488 },
19489 ExcerptsRemoved {
19490 ids: Vec<ExcerptId>,
19491 },
19492 BufferFoldToggled {
19493 ids: Vec<ExcerptId>,
19494 folded: bool,
19495 },
19496 ExcerptsEdited {
19497 ids: Vec<ExcerptId>,
19498 },
19499 ExcerptsExpanded {
19500 ids: Vec<ExcerptId>,
19501 },
19502 BufferEdited,
19503 Edited {
19504 transaction_id: clock::Lamport,
19505 },
19506 Reparsed(BufferId),
19507 Focused,
19508 FocusedIn,
19509 Blurred,
19510 DirtyChanged,
19511 Saved,
19512 TitleChanged,
19513 DiffBaseChanged,
19514 SelectionsChanged {
19515 local: bool,
19516 },
19517 ScrollPositionChanged {
19518 local: bool,
19519 autoscroll: bool,
19520 },
19521 Closed,
19522 TransactionUndone {
19523 transaction_id: clock::Lamport,
19524 },
19525 TransactionBegun {
19526 transaction_id: clock::Lamport,
19527 },
19528 Reloaded,
19529 CursorShapeChanged,
19530 PushedToNavHistory {
19531 anchor: Anchor,
19532 is_deactivate: bool,
19533 },
19534}
19535
19536impl EventEmitter<EditorEvent> for Editor {}
19537
19538impl Focusable for Editor {
19539 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19540 self.focus_handle.clone()
19541 }
19542}
19543
19544impl Render for Editor {
19545 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19546 let settings = ThemeSettings::get_global(cx);
19547
19548 let mut text_style = match self.mode {
19549 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19550 color: cx.theme().colors().editor_foreground,
19551 font_family: settings.ui_font.family.clone(),
19552 font_features: settings.ui_font.features.clone(),
19553 font_fallbacks: settings.ui_font.fallbacks.clone(),
19554 font_size: rems(0.875).into(),
19555 font_weight: settings.ui_font.weight,
19556 line_height: relative(settings.buffer_line_height.value()),
19557 ..Default::default()
19558 },
19559 EditorMode::Full { .. } => TextStyle {
19560 color: cx.theme().colors().editor_foreground,
19561 font_family: settings.buffer_font.family.clone(),
19562 font_features: settings.buffer_font.features.clone(),
19563 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19564 font_size: settings.buffer_font_size(cx).into(),
19565 font_weight: settings.buffer_font.weight,
19566 line_height: relative(settings.buffer_line_height.value()),
19567 ..Default::default()
19568 },
19569 };
19570 if let Some(text_style_refinement) = &self.text_style_refinement {
19571 text_style.refine(text_style_refinement)
19572 }
19573
19574 let background = match self.mode {
19575 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19576 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19577 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19578 };
19579
19580 EditorElement::new(
19581 &cx.entity(),
19582 EditorStyle {
19583 background,
19584 local_player: cx.theme().players().local(),
19585 text: text_style,
19586 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19587 syntax: cx.theme().syntax().clone(),
19588 status: cx.theme().status().clone(),
19589 inlay_hints_style: make_inlay_hints_style(cx),
19590 inline_completion_styles: make_suggestion_styles(cx),
19591 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19592 },
19593 )
19594 }
19595}
19596
19597impl EntityInputHandler for Editor {
19598 fn text_for_range(
19599 &mut self,
19600 range_utf16: Range<usize>,
19601 adjusted_range: &mut Option<Range<usize>>,
19602 _: &mut Window,
19603 cx: &mut Context<Self>,
19604 ) -> Option<String> {
19605 let snapshot = self.buffer.read(cx).read(cx);
19606 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19607 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19608 if (start.0..end.0) != range_utf16 {
19609 adjusted_range.replace(start.0..end.0);
19610 }
19611 Some(snapshot.text_for_range(start..end).collect())
19612 }
19613
19614 fn selected_text_range(
19615 &mut self,
19616 ignore_disabled_input: bool,
19617 _: &mut Window,
19618 cx: &mut Context<Self>,
19619 ) -> Option<UTF16Selection> {
19620 // Prevent the IME menu from appearing when holding down an alphabetic key
19621 // while input is disabled.
19622 if !ignore_disabled_input && !self.input_enabled {
19623 return None;
19624 }
19625
19626 let selection = self.selections.newest::<OffsetUtf16>(cx);
19627 let range = selection.range();
19628
19629 Some(UTF16Selection {
19630 range: range.start.0..range.end.0,
19631 reversed: selection.reversed,
19632 })
19633 }
19634
19635 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19636 let snapshot = self.buffer.read(cx).read(cx);
19637 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19638 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19639 }
19640
19641 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19642 self.clear_highlights::<InputComposition>(cx);
19643 self.ime_transaction.take();
19644 }
19645
19646 fn replace_text_in_range(
19647 &mut self,
19648 range_utf16: Option<Range<usize>>,
19649 text: &str,
19650 window: &mut Window,
19651 cx: &mut Context<Self>,
19652 ) {
19653 if !self.input_enabled {
19654 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19655 return;
19656 }
19657
19658 self.transact(window, cx, |this, window, cx| {
19659 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19660 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19661 Some(this.selection_replacement_ranges(range_utf16, cx))
19662 } else {
19663 this.marked_text_ranges(cx)
19664 };
19665
19666 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19667 let newest_selection_id = this.selections.newest_anchor().id;
19668 this.selections
19669 .all::<OffsetUtf16>(cx)
19670 .iter()
19671 .zip(ranges_to_replace.iter())
19672 .find_map(|(selection, range)| {
19673 if selection.id == newest_selection_id {
19674 Some(
19675 (range.start.0 as isize - selection.head().0 as isize)
19676 ..(range.end.0 as isize - selection.head().0 as isize),
19677 )
19678 } else {
19679 None
19680 }
19681 })
19682 });
19683
19684 cx.emit(EditorEvent::InputHandled {
19685 utf16_range_to_replace: range_to_replace,
19686 text: text.into(),
19687 });
19688
19689 if let Some(new_selected_ranges) = new_selected_ranges {
19690 this.change_selections(None, window, cx, |selections| {
19691 selections.select_ranges(new_selected_ranges)
19692 });
19693 this.backspace(&Default::default(), window, cx);
19694 }
19695
19696 this.handle_input(text, window, cx);
19697 });
19698
19699 if let Some(transaction) = self.ime_transaction {
19700 self.buffer.update(cx, |buffer, cx| {
19701 buffer.group_until_transaction(transaction, cx);
19702 });
19703 }
19704
19705 self.unmark_text(window, cx);
19706 }
19707
19708 fn replace_and_mark_text_in_range(
19709 &mut self,
19710 range_utf16: Option<Range<usize>>,
19711 text: &str,
19712 new_selected_range_utf16: Option<Range<usize>>,
19713 window: &mut Window,
19714 cx: &mut Context<Self>,
19715 ) {
19716 if !self.input_enabled {
19717 return;
19718 }
19719
19720 let transaction = self.transact(window, cx, |this, window, cx| {
19721 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19722 let snapshot = this.buffer.read(cx).read(cx);
19723 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19724 for marked_range in &mut marked_ranges {
19725 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19726 marked_range.start.0 += relative_range_utf16.start;
19727 marked_range.start =
19728 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19729 marked_range.end =
19730 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19731 }
19732 }
19733 Some(marked_ranges)
19734 } else if let Some(range_utf16) = range_utf16 {
19735 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19736 Some(this.selection_replacement_ranges(range_utf16, cx))
19737 } else {
19738 None
19739 };
19740
19741 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19742 let newest_selection_id = this.selections.newest_anchor().id;
19743 this.selections
19744 .all::<OffsetUtf16>(cx)
19745 .iter()
19746 .zip(ranges_to_replace.iter())
19747 .find_map(|(selection, range)| {
19748 if selection.id == newest_selection_id {
19749 Some(
19750 (range.start.0 as isize - selection.head().0 as isize)
19751 ..(range.end.0 as isize - selection.head().0 as isize),
19752 )
19753 } else {
19754 None
19755 }
19756 })
19757 });
19758
19759 cx.emit(EditorEvent::InputHandled {
19760 utf16_range_to_replace: range_to_replace,
19761 text: text.into(),
19762 });
19763
19764 if let Some(ranges) = ranges_to_replace {
19765 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19766 }
19767
19768 let marked_ranges = {
19769 let snapshot = this.buffer.read(cx).read(cx);
19770 this.selections
19771 .disjoint_anchors()
19772 .iter()
19773 .map(|selection| {
19774 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19775 })
19776 .collect::<Vec<_>>()
19777 };
19778
19779 if text.is_empty() {
19780 this.unmark_text(window, cx);
19781 } else {
19782 this.highlight_text::<InputComposition>(
19783 marked_ranges.clone(),
19784 HighlightStyle {
19785 underline: Some(UnderlineStyle {
19786 thickness: px(1.),
19787 color: None,
19788 wavy: false,
19789 }),
19790 ..Default::default()
19791 },
19792 cx,
19793 );
19794 }
19795
19796 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19797 let use_autoclose = this.use_autoclose;
19798 let use_auto_surround = this.use_auto_surround;
19799 this.set_use_autoclose(false);
19800 this.set_use_auto_surround(false);
19801 this.handle_input(text, window, cx);
19802 this.set_use_autoclose(use_autoclose);
19803 this.set_use_auto_surround(use_auto_surround);
19804
19805 if let Some(new_selected_range) = new_selected_range_utf16 {
19806 let snapshot = this.buffer.read(cx).read(cx);
19807 let new_selected_ranges = marked_ranges
19808 .into_iter()
19809 .map(|marked_range| {
19810 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19811 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19812 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19813 snapshot.clip_offset_utf16(new_start, Bias::Left)
19814 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19815 })
19816 .collect::<Vec<_>>();
19817
19818 drop(snapshot);
19819 this.change_selections(None, window, cx, |selections| {
19820 selections.select_ranges(new_selected_ranges)
19821 });
19822 }
19823 });
19824
19825 self.ime_transaction = self.ime_transaction.or(transaction);
19826 if let Some(transaction) = self.ime_transaction {
19827 self.buffer.update(cx, |buffer, cx| {
19828 buffer.group_until_transaction(transaction, cx);
19829 });
19830 }
19831
19832 if self.text_highlights::<InputComposition>(cx).is_none() {
19833 self.ime_transaction.take();
19834 }
19835 }
19836
19837 fn bounds_for_range(
19838 &mut self,
19839 range_utf16: Range<usize>,
19840 element_bounds: gpui::Bounds<Pixels>,
19841 window: &mut Window,
19842 cx: &mut Context<Self>,
19843 ) -> Option<gpui::Bounds<Pixels>> {
19844 let text_layout_details = self.text_layout_details(window);
19845 let gpui::Size {
19846 width: em_width,
19847 height: line_height,
19848 } = self.character_size(window);
19849
19850 let snapshot = self.snapshot(window, cx);
19851 let scroll_position = snapshot.scroll_position();
19852 let scroll_left = scroll_position.x * em_width;
19853
19854 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19855 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19856 + self.gutter_dimensions.width
19857 + self.gutter_dimensions.margin;
19858 let y = line_height * (start.row().as_f32() - scroll_position.y);
19859
19860 Some(Bounds {
19861 origin: element_bounds.origin + point(x, y),
19862 size: size(em_width, line_height),
19863 })
19864 }
19865
19866 fn character_index_for_point(
19867 &mut self,
19868 point: gpui::Point<Pixels>,
19869 _window: &mut Window,
19870 _cx: &mut Context<Self>,
19871 ) -> Option<usize> {
19872 let position_map = self.last_position_map.as_ref()?;
19873 if !position_map.text_hitbox.contains(&point) {
19874 return None;
19875 }
19876 let display_point = position_map.point_for_position(point).previous_valid;
19877 let anchor = position_map
19878 .snapshot
19879 .display_point_to_anchor(display_point, Bias::Left);
19880 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19881 Some(utf16_offset.0)
19882 }
19883}
19884
19885trait SelectionExt {
19886 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19887 fn spanned_rows(
19888 &self,
19889 include_end_if_at_line_start: bool,
19890 map: &DisplaySnapshot,
19891 ) -> Range<MultiBufferRow>;
19892}
19893
19894impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19895 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19896 let start = self
19897 .start
19898 .to_point(&map.buffer_snapshot)
19899 .to_display_point(map);
19900 let end = self
19901 .end
19902 .to_point(&map.buffer_snapshot)
19903 .to_display_point(map);
19904 if self.reversed {
19905 end..start
19906 } else {
19907 start..end
19908 }
19909 }
19910
19911 fn spanned_rows(
19912 &self,
19913 include_end_if_at_line_start: bool,
19914 map: &DisplaySnapshot,
19915 ) -> Range<MultiBufferRow> {
19916 let start = self.start.to_point(&map.buffer_snapshot);
19917 let mut end = self.end.to_point(&map.buffer_snapshot);
19918 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19919 end.row -= 1;
19920 }
19921
19922 let buffer_start = map.prev_line_boundary(start).0;
19923 let buffer_end = map.next_line_boundary(end).0;
19924 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19925 }
19926}
19927
19928impl<T: InvalidationRegion> InvalidationStack<T> {
19929 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19930 where
19931 S: Clone + ToOffset,
19932 {
19933 while let Some(region) = self.last() {
19934 let all_selections_inside_invalidation_ranges =
19935 if selections.len() == region.ranges().len() {
19936 selections
19937 .iter()
19938 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19939 .all(|(selection, invalidation_range)| {
19940 let head = selection.head().to_offset(buffer);
19941 invalidation_range.start <= head && invalidation_range.end >= head
19942 })
19943 } else {
19944 false
19945 };
19946
19947 if all_selections_inside_invalidation_ranges {
19948 break;
19949 } else {
19950 self.pop();
19951 }
19952 }
19953 }
19954}
19955
19956impl<T> Default for InvalidationStack<T> {
19957 fn default() -> Self {
19958 Self(Default::default())
19959 }
19960}
19961
19962impl<T> Deref for InvalidationStack<T> {
19963 type Target = Vec<T>;
19964
19965 fn deref(&self) -> &Self::Target {
19966 &self.0
19967 }
19968}
19969
19970impl<T> DerefMut for InvalidationStack<T> {
19971 fn deref_mut(&mut self) -> &mut Self::Target {
19972 &mut self.0
19973 }
19974}
19975
19976impl InvalidationRegion for SnippetState {
19977 fn ranges(&self) -> &[Range<Anchor>] {
19978 &self.ranges[self.active_index]
19979 }
19980}
19981
19982pub fn diagnostic_block_renderer(
19983 diagnostic: Diagnostic,
19984 max_message_rows: Option<u8>,
19985 allow_closing: bool,
19986) -> RenderBlock {
19987 let (text_without_backticks, code_ranges) =
19988 highlight_diagnostic_message(&diagnostic, max_message_rows);
19989
19990 Arc::new(move |cx: &mut BlockContext| {
19991 let group_id: SharedString = cx.block_id.to_string().into();
19992
19993 let mut text_style = cx.window.text_style().clone();
19994 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19995 let theme_settings = ThemeSettings::get_global(cx);
19996 text_style.font_family = theme_settings.buffer_font.family.clone();
19997 text_style.font_style = theme_settings.buffer_font.style;
19998 text_style.font_features = theme_settings.buffer_font.features.clone();
19999 text_style.font_weight = theme_settings.buffer_font.weight;
20000
20001 let multi_line_diagnostic = diagnostic.message.contains('\n');
20002
20003 let buttons = |diagnostic: &Diagnostic| {
20004 if multi_line_diagnostic {
20005 v_flex()
20006 } else {
20007 h_flex()
20008 }
20009 .when(allow_closing, |div| {
20010 div.children(diagnostic.is_primary.then(|| {
20011 IconButton::new("close-block", IconName::XCircle)
20012 .icon_color(Color::Muted)
20013 .size(ButtonSize::Compact)
20014 .style(ButtonStyle::Transparent)
20015 .visible_on_hover(group_id.clone())
20016 .on_click(move |_click, window, cx| {
20017 window.dispatch_action(Box::new(Cancel), cx)
20018 })
20019 .tooltip(|window, cx| {
20020 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
20021 })
20022 }))
20023 })
20024 .child(
20025 IconButton::new("copy-block", IconName::Copy)
20026 .icon_color(Color::Muted)
20027 .size(ButtonSize::Compact)
20028 .style(ButtonStyle::Transparent)
20029 .visible_on_hover(group_id.clone())
20030 .on_click({
20031 let message = diagnostic.message.clone();
20032 move |_click, _, cx| {
20033 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
20034 }
20035 })
20036 .tooltip(Tooltip::text("Copy diagnostic message")),
20037 )
20038 };
20039
20040 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
20041 AvailableSpace::min_size(),
20042 cx.window,
20043 cx.app,
20044 );
20045
20046 h_flex()
20047 .id(cx.block_id)
20048 .group(group_id.clone())
20049 .relative()
20050 .size_full()
20051 .block_mouse_down()
20052 .pl(cx.gutter_dimensions.width)
20053 .w(cx.max_width - cx.gutter_dimensions.full_width())
20054 .child(
20055 div()
20056 .flex()
20057 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
20058 .flex_shrink(),
20059 )
20060 .child(buttons(&diagnostic))
20061 .child(div().flex().flex_shrink_0().child(
20062 StyledText::new(text_without_backticks.clone()).with_default_highlights(
20063 &text_style,
20064 code_ranges.iter().map(|range| {
20065 (
20066 range.clone(),
20067 HighlightStyle {
20068 font_weight: Some(FontWeight::BOLD),
20069 ..Default::default()
20070 },
20071 )
20072 }),
20073 ),
20074 ))
20075 .into_any_element()
20076 })
20077}
20078
20079fn inline_completion_edit_text(
20080 current_snapshot: &BufferSnapshot,
20081 edits: &[(Range<Anchor>, String)],
20082 edit_preview: &EditPreview,
20083 include_deletions: bool,
20084 cx: &App,
20085) -> HighlightedText {
20086 let edits = edits
20087 .iter()
20088 .map(|(anchor, text)| {
20089 (
20090 anchor.start.text_anchor..anchor.end.text_anchor,
20091 text.clone(),
20092 )
20093 })
20094 .collect::<Vec<_>>();
20095
20096 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20097}
20098
20099pub fn highlight_diagnostic_message(
20100 diagnostic: &Diagnostic,
20101 mut max_message_rows: Option<u8>,
20102) -> (SharedString, Vec<Range<usize>>) {
20103 let mut text_without_backticks = String::new();
20104 let mut code_ranges = Vec::new();
20105
20106 if let Some(source) = &diagnostic.source {
20107 text_without_backticks.push_str(source);
20108 code_ranges.push(0..source.len());
20109 text_without_backticks.push_str(": ");
20110 }
20111
20112 let mut prev_offset = 0;
20113 let mut in_code_block = false;
20114 let has_row_limit = max_message_rows.is_some();
20115 let mut newline_indices = diagnostic
20116 .message
20117 .match_indices('\n')
20118 .filter(|_| has_row_limit)
20119 .map(|(ix, _)| ix)
20120 .fuse()
20121 .peekable();
20122
20123 for (quote_ix, _) in diagnostic
20124 .message
20125 .match_indices('`')
20126 .chain([(diagnostic.message.len(), "")])
20127 {
20128 let mut first_newline_ix = None;
20129 let mut last_newline_ix = None;
20130 while let Some(newline_ix) = newline_indices.peek() {
20131 if *newline_ix < quote_ix {
20132 if first_newline_ix.is_none() {
20133 first_newline_ix = Some(*newline_ix);
20134 }
20135 last_newline_ix = Some(*newline_ix);
20136
20137 if let Some(rows_left) = &mut max_message_rows {
20138 if *rows_left == 0 {
20139 break;
20140 } else {
20141 *rows_left -= 1;
20142 }
20143 }
20144 let _ = newline_indices.next();
20145 } else {
20146 break;
20147 }
20148 }
20149 let prev_len = text_without_backticks.len();
20150 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
20151 text_without_backticks.push_str(new_text);
20152 if in_code_block {
20153 code_ranges.push(prev_len..text_without_backticks.len());
20154 }
20155 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
20156 in_code_block = !in_code_block;
20157 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
20158 text_without_backticks.push_str("...");
20159 break;
20160 }
20161 }
20162
20163 (text_without_backticks.into(), code_ranges)
20164}
20165
20166fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20167 match severity {
20168 DiagnosticSeverity::ERROR => colors.error,
20169 DiagnosticSeverity::WARNING => colors.warning,
20170 DiagnosticSeverity::INFORMATION => colors.info,
20171 DiagnosticSeverity::HINT => colors.info,
20172 _ => colors.ignored,
20173 }
20174}
20175
20176pub fn styled_runs_for_code_label<'a>(
20177 label: &'a CodeLabel,
20178 syntax_theme: &'a theme::SyntaxTheme,
20179) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20180 let fade_out = HighlightStyle {
20181 fade_out: Some(0.35),
20182 ..Default::default()
20183 };
20184
20185 let mut prev_end = label.filter_range.end;
20186 label
20187 .runs
20188 .iter()
20189 .enumerate()
20190 .flat_map(move |(ix, (range, highlight_id))| {
20191 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20192 style
20193 } else {
20194 return Default::default();
20195 };
20196 let mut muted_style = style;
20197 muted_style.highlight(fade_out);
20198
20199 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20200 if range.start >= label.filter_range.end {
20201 if range.start > prev_end {
20202 runs.push((prev_end..range.start, fade_out));
20203 }
20204 runs.push((range.clone(), muted_style));
20205 } else if range.end <= label.filter_range.end {
20206 runs.push((range.clone(), style));
20207 } else {
20208 runs.push((range.start..label.filter_range.end, style));
20209 runs.push((label.filter_range.end..range.end, muted_style));
20210 }
20211 prev_end = cmp::max(prev_end, range.end);
20212
20213 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20214 runs.push((prev_end..label.text.len(), fade_out));
20215 }
20216
20217 runs
20218 })
20219}
20220
20221pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20222 let mut prev_index = 0;
20223 let mut prev_codepoint: Option<char> = None;
20224 text.char_indices()
20225 .chain([(text.len(), '\0')])
20226 .filter_map(move |(index, codepoint)| {
20227 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20228 let is_boundary = index == text.len()
20229 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20230 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20231 if is_boundary {
20232 let chunk = &text[prev_index..index];
20233 prev_index = index;
20234 Some(chunk)
20235 } else {
20236 None
20237 }
20238 })
20239}
20240
20241pub trait RangeToAnchorExt: Sized {
20242 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20243
20244 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20245 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20246 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20247 }
20248}
20249
20250impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20251 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20252 let start_offset = self.start.to_offset(snapshot);
20253 let end_offset = self.end.to_offset(snapshot);
20254 if start_offset == end_offset {
20255 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20256 } else {
20257 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20258 }
20259 }
20260}
20261
20262pub trait RowExt {
20263 fn as_f32(&self) -> f32;
20264
20265 fn next_row(&self) -> Self;
20266
20267 fn previous_row(&self) -> Self;
20268
20269 fn minus(&self, other: Self) -> u32;
20270}
20271
20272impl RowExt for DisplayRow {
20273 fn as_f32(&self) -> f32 {
20274 self.0 as f32
20275 }
20276
20277 fn next_row(&self) -> Self {
20278 Self(self.0 + 1)
20279 }
20280
20281 fn previous_row(&self) -> Self {
20282 Self(self.0.saturating_sub(1))
20283 }
20284
20285 fn minus(&self, other: Self) -> u32 {
20286 self.0 - other.0
20287 }
20288}
20289
20290impl RowExt for MultiBufferRow {
20291 fn as_f32(&self) -> f32 {
20292 self.0 as f32
20293 }
20294
20295 fn next_row(&self) -> Self {
20296 Self(self.0 + 1)
20297 }
20298
20299 fn previous_row(&self) -> Self {
20300 Self(self.0.saturating_sub(1))
20301 }
20302
20303 fn minus(&self, other: Self) -> u32 {
20304 self.0 - other.0
20305 }
20306}
20307
20308trait RowRangeExt {
20309 type Row;
20310
20311 fn len(&self) -> usize;
20312
20313 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20314}
20315
20316impl RowRangeExt for Range<MultiBufferRow> {
20317 type Row = MultiBufferRow;
20318
20319 fn len(&self) -> usize {
20320 (self.end.0 - self.start.0) as usize
20321 }
20322
20323 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20324 (self.start.0..self.end.0).map(MultiBufferRow)
20325 }
20326}
20327
20328impl RowRangeExt for Range<DisplayRow> {
20329 type Row = DisplayRow;
20330
20331 fn len(&self) -> usize {
20332 (self.end.0 - self.start.0) as usize
20333 }
20334
20335 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20336 (self.start.0..self.end.0).map(DisplayRow)
20337 }
20338}
20339
20340/// If select range has more than one line, we
20341/// just point the cursor to range.start.
20342fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20343 if range.start.row == range.end.row {
20344 range
20345 } else {
20346 range.start..range.start
20347 }
20348}
20349pub struct KillRing(ClipboardItem);
20350impl Global for KillRing {}
20351
20352const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20353
20354enum BreakpointPromptEditAction {
20355 Log,
20356 Condition,
20357 HitCondition,
20358}
20359
20360struct BreakpointPromptEditor {
20361 pub(crate) prompt: Entity<Editor>,
20362 editor: WeakEntity<Editor>,
20363 breakpoint_anchor: Anchor,
20364 breakpoint: Breakpoint,
20365 edit_action: BreakpointPromptEditAction,
20366 block_ids: HashSet<CustomBlockId>,
20367 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20368 _subscriptions: Vec<Subscription>,
20369}
20370
20371impl BreakpointPromptEditor {
20372 const MAX_LINES: u8 = 4;
20373
20374 fn new(
20375 editor: WeakEntity<Editor>,
20376 breakpoint_anchor: Anchor,
20377 breakpoint: Breakpoint,
20378 edit_action: BreakpointPromptEditAction,
20379 window: &mut Window,
20380 cx: &mut Context<Self>,
20381 ) -> Self {
20382 let base_text = match edit_action {
20383 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20384 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20385 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20386 }
20387 .map(|msg| msg.to_string())
20388 .unwrap_or_default();
20389
20390 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20391 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20392
20393 let prompt = cx.new(|cx| {
20394 let mut prompt = Editor::new(
20395 EditorMode::AutoHeight {
20396 max_lines: Self::MAX_LINES as usize,
20397 },
20398 buffer,
20399 None,
20400 window,
20401 cx,
20402 );
20403 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20404 prompt.set_show_cursor_when_unfocused(false, cx);
20405 prompt.set_placeholder_text(
20406 match edit_action {
20407 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20408 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20409 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20410 },
20411 cx,
20412 );
20413
20414 prompt
20415 });
20416
20417 Self {
20418 prompt,
20419 editor,
20420 breakpoint_anchor,
20421 breakpoint,
20422 edit_action,
20423 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20424 block_ids: Default::default(),
20425 _subscriptions: vec![],
20426 }
20427 }
20428
20429 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20430 self.block_ids.extend(block_ids)
20431 }
20432
20433 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20434 if let Some(editor) = self.editor.upgrade() {
20435 let message = self
20436 .prompt
20437 .read(cx)
20438 .buffer
20439 .read(cx)
20440 .as_singleton()
20441 .expect("A multi buffer in breakpoint prompt isn't possible")
20442 .read(cx)
20443 .as_rope()
20444 .to_string();
20445
20446 editor.update(cx, |editor, cx| {
20447 editor.edit_breakpoint_at_anchor(
20448 self.breakpoint_anchor,
20449 self.breakpoint.clone(),
20450 match self.edit_action {
20451 BreakpointPromptEditAction::Log => {
20452 BreakpointEditAction::EditLogMessage(message.into())
20453 }
20454 BreakpointPromptEditAction::Condition => {
20455 BreakpointEditAction::EditCondition(message.into())
20456 }
20457 BreakpointPromptEditAction::HitCondition => {
20458 BreakpointEditAction::EditHitCondition(message.into())
20459 }
20460 },
20461 cx,
20462 );
20463
20464 editor.remove_blocks(self.block_ids.clone(), None, cx);
20465 cx.focus_self(window);
20466 });
20467 }
20468 }
20469
20470 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20471 self.editor
20472 .update(cx, |editor, cx| {
20473 editor.remove_blocks(self.block_ids.clone(), None, cx);
20474 window.focus(&editor.focus_handle);
20475 })
20476 .log_err();
20477 }
20478
20479 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20480 let settings = ThemeSettings::get_global(cx);
20481 let text_style = TextStyle {
20482 color: if self.prompt.read(cx).read_only(cx) {
20483 cx.theme().colors().text_disabled
20484 } else {
20485 cx.theme().colors().text
20486 },
20487 font_family: settings.buffer_font.family.clone(),
20488 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20489 font_size: settings.buffer_font_size(cx).into(),
20490 font_weight: settings.buffer_font.weight,
20491 line_height: relative(settings.buffer_line_height.value()),
20492 ..Default::default()
20493 };
20494 EditorElement::new(
20495 &self.prompt,
20496 EditorStyle {
20497 background: cx.theme().colors().editor_background,
20498 local_player: cx.theme().players().local(),
20499 text: text_style,
20500 ..Default::default()
20501 },
20502 )
20503 }
20504}
20505
20506impl Render for BreakpointPromptEditor {
20507 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20508 let gutter_dimensions = *self.gutter_dimensions.lock();
20509 h_flex()
20510 .key_context("Editor")
20511 .bg(cx.theme().colors().editor_background)
20512 .border_y_1()
20513 .border_color(cx.theme().status().info_border)
20514 .size_full()
20515 .py(window.line_height() / 2.5)
20516 .on_action(cx.listener(Self::confirm))
20517 .on_action(cx.listener(Self::cancel))
20518 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20519 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20520 }
20521}
20522
20523impl Focusable for BreakpointPromptEditor {
20524 fn focus_handle(&self, cx: &App) -> FocusHandle {
20525 self.prompt.focus_handle(cx)
20526 }
20527}
20528
20529fn all_edits_insertions_or_deletions(
20530 edits: &Vec<(Range<Anchor>, String)>,
20531 snapshot: &MultiBufferSnapshot,
20532) -> bool {
20533 let mut all_insertions = true;
20534 let mut all_deletions = true;
20535
20536 for (range, new_text) in edits.iter() {
20537 let range_is_empty = range.to_offset(&snapshot).is_empty();
20538 let text_is_empty = new_text.is_empty();
20539
20540 if range_is_empty != text_is_empty {
20541 if range_is_empty {
20542 all_deletions = false;
20543 } else {
20544 all_insertions = false;
20545 }
20546 } else {
20547 return false;
20548 }
20549
20550 if !all_insertions && !all_deletions {
20551 return false;
20552 }
20553 }
20554 all_insertions || all_deletions
20555}
20556
20557struct MissingEditPredictionKeybindingTooltip;
20558
20559impl Render for MissingEditPredictionKeybindingTooltip {
20560 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20561 ui::tooltip_container(window, cx, |container, _, cx| {
20562 container
20563 .flex_shrink_0()
20564 .max_w_80()
20565 .min_h(rems_from_px(124.))
20566 .justify_between()
20567 .child(
20568 v_flex()
20569 .flex_1()
20570 .text_ui_sm(cx)
20571 .child(Label::new("Conflict with Accept Keybinding"))
20572 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20573 )
20574 .child(
20575 h_flex()
20576 .pb_1()
20577 .gap_1()
20578 .items_end()
20579 .w_full()
20580 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20581 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20582 }))
20583 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20584 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20585 })),
20586 )
20587 })
20588 }
20589}
20590
20591#[derive(Debug, Clone, Copy, PartialEq)]
20592pub struct LineHighlight {
20593 pub background: Background,
20594 pub border: Option<gpui::Hsla>,
20595}
20596
20597impl From<Hsla> for LineHighlight {
20598 fn from(hsla: Hsla) -> Self {
20599 Self {
20600 background: hsla.into(),
20601 border: None,
20602 }
20603 }
20604}
20605
20606impl From<Background> for LineHighlight {
20607 fn from(background: Background) -> Self {
20608 Self {
20609 background,
20610 border: None,
20611 }
20612 }
20613}
20614
20615fn render_diff_hunk_controls(
20616 row: u32,
20617 status: &DiffHunkStatus,
20618 hunk_range: Range<Anchor>,
20619 is_created_file: bool,
20620 line_height: Pixels,
20621 editor: &Entity<Editor>,
20622 _window: &mut Window,
20623 cx: &mut App,
20624) -> AnyElement {
20625 h_flex()
20626 .h(line_height)
20627 .mr_1()
20628 .gap_1()
20629 .px_0p5()
20630 .pb_1()
20631 .border_x_1()
20632 .border_b_1()
20633 .border_color(cx.theme().colors().border_variant)
20634 .rounded_b_lg()
20635 .bg(cx.theme().colors().editor_background)
20636 .gap_1()
20637 .occlude()
20638 .shadow_md()
20639 .child(if status.has_secondary_hunk() {
20640 Button::new(("stage", row as u64), "Stage")
20641 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20642 .tooltip({
20643 let focus_handle = editor.focus_handle(cx);
20644 move |window, cx| {
20645 Tooltip::for_action_in(
20646 "Stage Hunk",
20647 &::git::ToggleStaged,
20648 &focus_handle,
20649 window,
20650 cx,
20651 )
20652 }
20653 })
20654 .on_click({
20655 let editor = editor.clone();
20656 move |_event, _window, cx| {
20657 editor.update(cx, |editor, cx| {
20658 editor.stage_or_unstage_diff_hunks(
20659 true,
20660 vec![hunk_range.start..hunk_range.start],
20661 cx,
20662 );
20663 });
20664 }
20665 })
20666 } else {
20667 Button::new(("unstage", row as u64), "Unstage")
20668 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20669 .tooltip({
20670 let focus_handle = editor.focus_handle(cx);
20671 move |window, cx| {
20672 Tooltip::for_action_in(
20673 "Unstage Hunk",
20674 &::git::ToggleStaged,
20675 &focus_handle,
20676 window,
20677 cx,
20678 )
20679 }
20680 })
20681 .on_click({
20682 let editor = editor.clone();
20683 move |_event, _window, cx| {
20684 editor.update(cx, |editor, cx| {
20685 editor.stage_or_unstage_diff_hunks(
20686 false,
20687 vec![hunk_range.start..hunk_range.start],
20688 cx,
20689 );
20690 });
20691 }
20692 })
20693 })
20694 .child(
20695 Button::new(("restore", row as u64), "Restore")
20696 .tooltip({
20697 let focus_handle = editor.focus_handle(cx);
20698 move |window, cx| {
20699 Tooltip::for_action_in(
20700 "Restore Hunk",
20701 &::git::Restore,
20702 &focus_handle,
20703 window,
20704 cx,
20705 )
20706 }
20707 })
20708 .on_click({
20709 let editor = editor.clone();
20710 move |_event, window, cx| {
20711 editor.update(cx, |editor, cx| {
20712 let snapshot = editor.snapshot(window, cx);
20713 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20714 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20715 });
20716 }
20717 })
20718 .disabled(is_created_file),
20719 )
20720 .when(
20721 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20722 |el| {
20723 el.child(
20724 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20725 .shape(IconButtonShape::Square)
20726 .icon_size(IconSize::Small)
20727 // .disabled(!has_multiple_hunks)
20728 .tooltip({
20729 let focus_handle = editor.focus_handle(cx);
20730 move |window, cx| {
20731 Tooltip::for_action_in(
20732 "Next Hunk",
20733 &GoToHunk,
20734 &focus_handle,
20735 window,
20736 cx,
20737 )
20738 }
20739 })
20740 .on_click({
20741 let editor = editor.clone();
20742 move |_event, window, cx| {
20743 editor.update(cx, |editor, cx| {
20744 let snapshot = editor.snapshot(window, cx);
20745 let position =
20746 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20747 editor.go_to_hunk_before_or_after_position(
20748 &snapshot,
20749 position,
20750 Direction::Next,
20751 window,
20752 cx,
20753 );
20754 editor.expand_selected_diff_hunks(cx);
20755 });
20756 }
20757 }),
20758 )
20759 .child(
20760 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20761 .shape(IconButtonShape::Square)
20762 .icon_size(IconSize::Small)
20763 // .disabled(!has_multiple_hunks)
20764 .tooltip({
20765 let focus_handle = editor.focus_handle(cx);
20766 move |window, cx| {
20767 Tooltip::for_action_in(
20768 "Previous Hunk",
20769 &GoToPreviousHunk,
20770 &focus_handle,
20771 window,
20772 cx,
20773 )
20774 }
20775 })
20776 .on_click({
20777 let editor = editor.clone();
20778 move |_event, window, cx| {
20779 editor.update(cx, |editor, cx| {
20780 let snapshot = editor.snapshot(window, cx);
20781 let point =
20782 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20783 editor.go_to_hunk_before_or_after_position(
20784 &snapshot,
20785 point,
20786 Direction::Prev,
20787 window,
20788 cx,
20789 );
20790 editor.expand_selected_diff_hunks(cx);
20791 });
20792 }
20793 }),
20794 )
20795 },
20796 )
20797 .into_any_element()
20798}