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 {
400 auto_width: bool,
401 },
402 AutoHeight {
403 max_lines: usize,
404 },
405 Full {
406 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
407 scale_ui_elements_with_buffer_font_size: bool,
408 /// When set to `true`, the editor will render a background for the active line.
409 show_active_line_background: bool,
410 },
411}
412
413impl EditorMode {
414 pub fn full() -> Self {
415 Self::Full {
416 scale_ui_elements_with_buffer_font_size: true,
417 show_active_line_background: true,
418 }
419 }
420
421 pub fn is_full(&self) -> bool {
422 matches!(self, Self::Full { .. })
423 }
424}
425
426#[derive(Copy, Clone, Debug)]
427pub enum SoftWrap {
428 /// Prefer not to wrap at all.
429 ///
430 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
431 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
432 GitDiff,
433 /// Prefer a single line generally, unless an overly long line is encountered.
434 None,
435 /// Soft wrap lines that exceed the editor width.
436 EditorWidth,
437 /// Soft wrap lines at the preferred line length.
438 Column(u32),
439 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
440 Bounded(u32),
441}
442
443#[derive(Clone)]
444pub struct EditorStyle {
445 pub background: Hsla,
446 pub local_player: PlayerColor,
447 pub text: TextStyle,
448 pub scrollbar_width: Pixels,
449 pub syntax: Arc<SyntaxTheme>,
450 pub status: StatusColors,
451 pub inlay_hints_style: HighlightStyle,
452 pub inline_completion_styles: InlineCompletionStyles,
453 pub unnecessary_code_fade: f32,
454}
455
456impl Default for EditorStyle {
457 fn default() -> Self {
458 Self {
459 background: Hsla::default(),
460 local_player: PlayerColor::default(),
461 text: TextStyle::default(),
462 scrollbar_width: Pixels::default(),
463 syntax: Default::default(),
464 // HACK: Status colors don't have a real default.
465 // We should look into removing the status colors from the editor
466 // style and retrieve them directly from the theme.
467 status: StatusColors::dark(),
468 inlay_hints_style: HighlightStyle::default(),
469 inline_completion_styles: InlineCompletionStyles {
470 insertion: HighlightStyle::default(),
471 whitespace: HighlightStyle::default(),
472 },
473 unnecessary_code_fade: Default::default(),
474 }
475 }
476}
477
478pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
479 let show_background = language_settings::language_settings(None, None, cx)
480 .inlay_hints
481 .show_background;
482
483 HighlightStyle {
484 color: Some(cx.theme().status().hint),
485 background_color: show_background.then(|| cx.theme().status().hint_background),
486 ..HighlightStyle::default()
487 }
488}
489
490pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
491 InlineCompletionStyles {
492 insertion: HighlightStyle {
493 color: Some(cx.theme().status().predictive),
494 ..HighlightStyle::default()
495 },
496 whitespace: HighlightStyle {
497 background_color: Some(cx.theme().status().created_background),
498 ..HighlightStyle::default()
499 },
500 }
501}
502
503type CompletionId = usize;
504
505pub(crate) enum EditDisplayMode {
506 TabAccept,
507 DiffPopover,
508 Inline,
509}
510
511enum InlineCompletion {
512 Edit {
513 edits: Vec<(Range<Anchor>, String)>,
514 edit_preview: Option<EditPreview>,
515 display_mode: EditDisplayMode,
516 snapshot: BufferSnapshot,
517 },
518 Move {
519 target: Anchor,
520 snapshot: BufferSnapshot,
521 },
522}
523
524struct InlineCompletionState {
525 inlay_ids: Vec<InlayId>,
526 completion: InlineCompletion,
527 completion_id: Option<SharedString>,
528 invalidation_range: Range<Anchor>,
529}
530
531enum EditPredictionSettings {
532 Disabled,
533 Enabled {
534 show_in_menu: bool,
535 preview_requires_modifier: bool,
536 },
537}
538
539enum InlineCompletionHighlight {}
540
541#[derive(Debug, Clone)]
542struct InlineDiagnostic {
543 message: SharedString,
544 group_id: usize,
545 is_primary: bool,
546 start: Point,
547 severity: DiagnosticSeverity,
548}
549
550pub enum MenuInlineCompletionsPolicy {
551 Never,
552 ByProvider,
553}
554
555pub enum EditPredictionPreview {
556 /// Modifier is not pressed
557 Inactive { released_too_fast: bool },
558 /// Modifier pressed
559 Active {
560 since: Instant,
561 previous_scroll_position: Option<ScrollAnchor>,
562 },
563}
564
565impl EditPredictionPreview {
566 pub fn released_too_fast(&self) -> bool {
567 match self {
568 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
569 EditPredictionPreview::Active { .. } => false,
570 }
571 }
572
573 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
574 if let EditPredictionPreview::Active {
575 previous_scroll_position,
576 ..
577 } = self
578 {
579 *previous_scroll_position = scroll_position;
580 }
581 }
582}
583
584pub struct ContextMenuOptions {
585 pub min_entries_visible: usize,
586 pub max_entries_visible: usize,
587 pub placement: Option<ContextMenuPlacement>,
588}
589
590#[derive(Debug, Clone, PartialEq, Eq)]
591pub enum ContextMenuPlacement {
592 Above,
593 Below,
594}
595
596#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
597struct EditorActionId(usize);
598
599impl EditorActionId {
600 pub fn post_inc(&mut self) -> Self {
601 let answer = self.0;
602
603 *self = Self(answer + 1);
604
605 Self(answer)
606 }
607}
608
609// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
610// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
611
612type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
613type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
614
615#[derive(Default)]
616struct ScrollbarMarkerState {
617 scrollbar_size: Size<Pixels>,
618 dirty: bool,
619 markers: Arc<[PaintQuad]>,
620 pending_refresh: Option<Task<Result<()>>>,
621}
622
623impl ScrollbarMarkerState {
624 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
625 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
626 }
627}
628
629#[derive(Clone, Debug)]
630struct RunnableTasks {
631 templates: Vec<(TaskSourceKind, TaskTemplate)>,
632 offset: multi_buffer::Anchor,
633 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
634 column: u32,
635 // Values of all named captures, including those starting with '_'
636 extra_variables: HashMap<String, String>,
637 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
638 context_range: Range<BufferOffset>,
639}
640
641impl RunnableTasks {
642 fn resolve<'a>(
643 &'a self,
644 cx: &'a task::TaskContext,
645 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
646 self.templates.iter().filter_map(|(kind, template)| {
647 template
648 .resolve_task(&kind.to_id_base(), cx)
649 .map(|task| (kind.clone(), task))
650 })
651 }
652}
653
654#[derive(Clone)]
655struct ResolvedTasks {
656 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
657 position: Anchor,
658}
659
660#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
661struct BufferOffset(usize);
662
663// Addons allow storing per-editor state in other crates (e.g. Vim)
664pub trait Addon: 'static {
665 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
666
667 fn render_buffer_header_controls(
668 &self,
669 _: &ExcerptInfo,
670 _: &Window,
671 _: &App,
672 ) -> Option<AnyElement> {
673 None
674 }
675
676 fn to_any(&self) -> &dyn std::any::Any;
677}
678
679/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
680///
681/// See the [module level documentation](self) for more information.
682pub struct Editor {
683 focus_handle: FocusHandle,
684 last_focused_descendant: Option<WeakFocusHandle>,
685 /// The text buffer being edited
686 buffer: Entity<MultiBuffer>,
687 /// Map of how text in the buffer should be displayed.
688 /// Handles soft wraps, folds, fake inlay text insertions, etc.
689 pub display_map: Entity<DisplayMap>,
690 pub selections: SelectionsCollection,
691 pub scroll_manager: ScrollManager,
692 /// When inline assist editors are linked, they all render cursors because
693 /// typing enters text into each of them, even the ones that aren't focused.
694 pub(crate) show_cursor_when_unfocused: bool,
695 columnar_selection_tail: Option<Anchor>,
696 add_selections_state: Option<AddSelectionsState>,
697 select_next_state: Option<SelectNextState>,
698 select_prev_state: Option<SelectNextState>,
699 selection_history: SelectionHistory,
700 autoclose_regions: Vec<AutocloseRegion>,
701 snippet_stack: InvalidationStack<SnippetState>,
702 select_syntax_node_history: SelectSyntaxNodeHistory,
703 ime_transaction: Option<TransactionId>,
704 active_diagnostics: Option<ActiveDiagnosticGroup>,
705 show_inline_diagnostics: bool,
706 inline_diagnostics_update: Task<()>,
707 inline_diagnostics_enabled: bool,
708 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
709 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
710 hard_wrap: Option<usize>,
711
712 // TODO: make this a access method
713 pub project: Option<Entity<Project>>,
714 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
715 completion_provider: Option<Box<dyn CompletionProvider>>,
716 collaboration_hub: Option<Box<dyn CollaborationHub>>,
717 blink_manager: Entity<BlinkManager>,
718 show_cursor_names: bool,
719 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
720 pub show_local_selections: bool,
721 mode: EditorMode,
722 show_breadcrumbs: bool,
723 show_gutter: bool,
724 show_scrollbars: bool,
725 show_line_numbers: Option<bool>,
726 use_relative_line_numbers: Option<bool>,
727 show_git_diff_gutter: Option<bool>,
728 show_code_actions: Option<bool>,
729 show_runnables: Option<bool>,
730 show_breakpoints: Option<bool>,
731 show_wrap_guides: Option<bool>,
732 show_indent_guides: Option<bool>,
733 placeholder_text: Option<Arc<str>>,
734 highlight_order: usize,
735 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
736 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
737 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
738 scrollbar_marker_state: ScrollbarMarkerState,
739 active_indent_guides_state: ActiveIndentGuidesState,
740 nav_history: Option<ItemNavHistory>,
741 context_menu: RefCell<Option<CodeContextMenu>>,
742 context_menu_options: Option<ContextMenuOptions>,
743 mouse_context_menu: Option<MouseContextMenu>,
744 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
745 signature_help_state: SignatureHelpState,
746 auto_signature_help: Option<bool>,
747 find_all_references_task_sources: Vec<Anchor>,
748 next_completion_id: CompletionId,
749 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
750 code_actions_task: Option<Task<Result<()>>>,
751 selection_highlight_task: Option<Task<()>>,
752 document_highlights_task: Option<Task<()>>,
753 linked_editing_range_task: Option<Task<Option<()>>>,
754 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
755 pending_rename: Option<RenameState>,
756 searchable: bool,
757 cursor_shape: CursorShape,
758 current_line_highlight: Option<CurrentLineHighlight>,
759 collapse_matches: bool,
760 autoindent_mode: Option<AutoindentMode>,
761 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
762 input_enabled: bool,
763 use_modal_editing: bool,
764 read_only: bool,
765 leader_peer_id: Option<PeerId>,
766 remote_id: Option<ViewId>,
767 hover_state: HoverState,
768 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
769 gutter_hovered: bool,
770 hovered_link_state: Option<HoveredLinkState>,
771 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
772 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
773 active_inline_completion: Option<InlineCompletionState>,
774 /// Used to prevent flickering as the user types while the menu is open
775 stale_inline_completion_in_menu: Option<InlineCompletionState>,
776 edit_prediction_settings: EditPredictionSettings,
777 inline_completions_hidden_for_vim_mode: bool,
778 show_inline_completions_override: Option<bool>,
779 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
780 edit_prediction_preview: EditPredictionPreview,
781 edit_prediction_indent_conflict: bool,
782 edit_prediction_requires_modifier_in_indent_conflict: bool,
783 inlay_hint_cache: InlayHintCache,
784 next_inlay_id: usize,
785 _subscriptions: Vec<Subscription>,
786 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
787 gutter_dimensions: GutterDimensions,
788 style: Option<EditorStyle>,
789 text_style_refinement: Option<TextStyleRefinement>,
790 next_editor_action_id: EditorActionId,
791 editor_actions:
792 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
793 use_autoclose: bool,
794 use_auto_surround: bool,
795 auto_replace_emoji_shortcode: bool,
796 jsx_tag_auto_close_enabled_in_any_buffer: bool,
797 show_git_blame_gutter: bool,
798 show_git_blame_inline: bool,
799 show_git_blame_inline_delay_task: Option<Task<()>>,
800 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
801 git_blame_inline_enabled: bool,
802 render_diff_hunk_controls: RenderDiffHunkControlsFn,
803 serialize_dirty_buffers: bool,
804 show_selection_menu: Option<bool>,
805 blame: Option<Entity<GitBlame>>,
806 blame_subscription: Option<Subscription>,
807 custom_context_menu: Option<
808 Box<
809 dyn 'static
810 + Fn(
811 &mut Self,
812 DisplayPoint,
813 &mut Window,
814 &mut Context<Self>,
815 ) -> Option<Entity<ui::ContextMenu>>,
816 >,
817 >,
818 last_bounds: Option<Bounds<Pixels>>,
819 last_position_map: Option<Rc<PositionMap>>,
820 expect_bounds_change: Option<Bounds<Pixels>>,
821 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
822 tasks_update_task: Option<Task<()>>,
823 breakpoint_store: Option<Entity<BreakpointStore>>,
824 /// Allow's a user to create a breakpoint by selecting this indicator
825 /// It should be None while a user is not hovering over the gutter
826 /// Otherwise it represents the point that the breakpoint will be shown
827 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
828 in_project_search: bool,
829 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
830 breadcrumb_header: Option<String>,
831 focused_block: Option<FocusedBlock>,
832 next_scroll_position: NextScrollCursorCenterTopBottom,
833 addons: HashMap<TypeId, Box<dyn Addon>>,
834 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
835 load_diff_task: Option<Shared<Task<()>>>,
836 selection_mark_mode: bool,
837 toggle_fold_multiple_buffers: Task<()>,
838 _scroll_cursor_center_top_bottom_task: Task<()>,
839 serialize_selections: Task<()>,
840 serialize_folds: Task<()>,
841 mouse_cursor_hidden: bool,
842 hide_mouse_mode: HideMouseMode,
843}
844
845#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
846enum NextScrollCursorCenterTopBottom {
847 #[default]
848 Center,
849 Top,
850 Bottom,
851}
852
853impl NextScrollCursorCenterTopBottom {
854 fn next(&self) -> Self {
855 match self {
856 Self::Center => Self::Top,
857 Self::Top => Self::Bottom,
858 Self::Bottom => Self::Center,
859 }
860 }
861}
862
863#[derive(Clone)]
864pub struct EditorSnapshot {
865 pub mode: EditorMode,
866 show_gutter: bool,
867 show_line_numbers: Option<bool>,
868 show_git_diff_gutter: Option<bool>,
869 show_code_actions: Option<bool>,
870 show_runnables: Option<bool>,
871 show_breakpoints: Option<bool>,
872 git_blame_gutter_max_author_length: Option<usize>,
873 pub display_snapshot: DisplaySnapshot,
874 pub placeholder_text: Option<Arc<str>>,
875 is_focused: bool,
876 scroll_anchor: ScrollAnchor,
877 ongoing_scroll: OngoingScroll,
878 current_line_highlight: CurrentLineHighlight,
879 gutter_hovered: bool,
880}
881
882#[derive(Default, Debug, Clone, Copy)]
883pub struct GutterDimensions {
884 pub left_padding: Pixels,
885 pub right_padding: Pixels,
886 pub width: Pixels,
887 pub margin: Pixels,
888 pub git_blame_entries_width: Option<Pixels>,
889}
890
891impl GutterDimensions {
892 /// The full width of the space taken up by the gutter.
893 pub fn full_width(&self) -> Pixels {
894 self.margin + self.width
895 }
896
897 /// The width of the space reserved for the fold indicators,
898 /// use alongside 'justify_end' and `gutter_width` to
899 /// right align content with the line numbers
900 pub fn fold_area_width(&self) -> Pixels {
901 self.margin + self.right_padding
902 }
903}
904
905#[derive(Debug)]
906pub struct RemoteSelection {
907 pub replica_id: ReplicaId,
908 pub selection: Selection<Anchor>,
909 pub cursor_shape: CursorShape,
910 pub peer_id: PeerId,
911 pub line_mode: bool,
912 pub participant_index: Option<ParticipantIndex>,
913 pub user_name: Option<SharedString>,
914}
915
916#[derive(Clone, Debug)]
917struct SelectionHistoryEntry {
918 selections: Arc<[Selection<Anchor>]>,
919 select_next_state: Option<SelectNextState>,
920 select_prev_state: Option<SelectNextState>,
921 add_selections_state: Option<AddSelectionsState>,
922}
923
924enum SelectionHistoryMode {
925 Normal,
926 Undoing,
927 Redoing,
928}
929
930#[derive(Clone, PartialEq, Eq, Hash)]
931struct HoveredCursor {
932 replica_id: u16,
933 selection_id: usize,
934}
935
936impl Default for SelectionHistoryMode {
937 fn default() -> Self {
938 Self::Normal
939 }
940}
941
942#[derive(Default)]
943struct SelectionHistory {
944 #[allow(clippy::type_complexity)]
945 selections_by_transaction:
946 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
947 mode: SelectionHistoryMode,
948 undo_stack: VecDeque<SelectionHistoryEntry>,
949 redo_stack: VecDeque<SelectionHistoryEntry>,
950}
951
952impl SelectionHistory {
953 fn insert_transaction(
954 &mut self,
955 transaction_id: TransactionId,
956 selections: Arc<[Selection<Anchor>]>,
957 ) {
958 self.selections_by_transaction
959 .insert(transaction_id, (selections, None));
960 }
961
962 #[allow(clippy::type_complexity)]
963 fn transaction(
964 &self,
965 transaction_id: TransactionId,
966 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
967 self.selections_by_transaction.get(&transaction_id)
968 }
969
970 #[allow(clippy::type_complexity)]
971 fn transaction_mut(
972 &mut self,
973 transaction_id: TransactionId,
974 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
975 self.selections_by_transaction.get_mut(&transaction_id)
976 }
977
978 fn push(&mut self, entry: SelectionHistoryEntry) {
979 if !entry.selections.is_empty() {
980 match self.mode {
981 SelectionHistoryMode::Normal => {
982 self.push_undo(entry);
983 self.redo_stack.clear();
984 }
985 SelectionHistoryMode::Undoing => self.push_redo(entry),
986 SelectionHistoryMode::Redoing => self.push_undo(entry),
987 }
988 }
989 }
990
991 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
992 if self
993 .undo_stack
994 .back()
995 .map_or(true, |e| e.selections != entry.selections)
996 {
997 self.undo_stack.push_back(entry);
998 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
999 self.undo_stack.pop_front();
1000 }
1001 }
1002 }
1003
1004 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1005 if self
1006 .redo_stack
1007 .back()
1008 .map_or(true, |e| e.selections != entry.selections)
1009 {
1010 self.redo_stack.push_back(entry);
1011 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1012 self.redo_stack.pop_front();
1013 }
1014 }
1015 }
1016}
1017
1018struct RowHighlight {
1019 index: usize,
1020 range: Range<Anchor>,
1021 color: Hsla,
1022 should_autoscroll: bool,
1023}
1024
1025#[derive(Clone, Debug)]
1026struct AddSelectionsState {
1027 above: bool,
1028 stack: Vec<usize>,
1029}
1030
1031#[derive(Clone)]
1032struct SelectNextState {
1033 query: AhoCorasick,
1034 wordwise: bool,
1035 done: bool,
1036}
1037
1038impl std::fmt::Debug for SelectNextState {
1039 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1040 f.debug_struct(std::any::type_name::<Self>())
1041 .field("wordwise", &self.wordwise)
1042 .field("done", &self.done)
1043 .finish()
1044 }
1045}
1046
1047#[derive(Debug)]
1048struct AutocloseRegion {
1049 selection_id: usize,
1050 range: Range<Anchor>,
1051 pair: BracketPair,
1052}
1053
1054#[derive(Debug)]
1055struct SnippetState {
1056 ranges: Vec<Vec<Range<Anchor>>>,
1057 active_index: usize,
1058 choices: Vec<Option<Vec<String>>>,
1059}
1060
1061#[doc(hidden)]
1062pub struct RenameState {
1063 pub range: Range<Anchor>,
1064 pub old_name: Arc<str>,
1065 pub editor: Entity<Editor>,
1066 block_id: CustomBlockId,
1067}
1068
1069struct InvalidationStack<T>(Vec<T>);
1070
1071struct RegisteredInlineCompletionProvider {
1072 provider: Arc<dyn InlineCompletionProviderHandle>,
1073 _subscription: Subscription,
1074}
1075
1076#[derive(Debug, PartialEq, Eq)]
1077struct ActiveDiagnosticGroup {
1078 primary_range: Range<Anchor>,
1079 primary_message: String,
1080 group_id: usize,
1081 blocks: HashMap<CustomBlockId, Diagnostic>,
1082 is_valid: bool,
1083}
1084
1085#[derive(Serialize, Deserialize, Clone, Debug)]
1086pub struct ClipboardSelection {
1087 /// The number of bytes in this selection.
1088 pub len: usize,
1089 /// Whether this was a full-line selection.
1090 pub is_entire_line: bool,
1091 /// The indentation of the first line when this content was originally copied.
1092 pub first_line_indent: u32,
1093}
1094
1095// selections, scroll behavior, was newest selection reversed
1096type SelectSyntaxNodeHistoryState = (
1097 Box<[Selection<usize>]>,
1098 SelectSyntaxNodeScrollBehavior,
1099 bool,
1100);
1101
1102#[derive(Default)]
1103struct SelectSyntaxNodeHistory {
1104 stack: Vec<SelectSyntaxNodeHistoryState>,
1105 // disable temporarily to allow changing selections without losing the stack
1106 pub disable_clearing: bool,
1107}
1108
1109impl SelectSyntaxNodeHistory {
1110 pub fn try_clear(&mut self) {
1111 if !self.disable_clearing {
1112 self.stack.clear();
1113 }
1114 }
1115
1116 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1117 self.stack.push(selection);
1118 }
1119
1120 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1121 self.stack.pop()
1122 }
1123}
1124
1125enum SelectSyntaxNodeScrollBehavior {
1126 CursorTop,
1127 FitSelection,
1128 CursorBottom,
1129}
1130
1131#[derive(Debug)]
1132pub(crate) struct NavigationData {
1133 cursor_anchor: Anchor,
1134 cursor_position: Point,
1135 scroll_anchor: ScrollAnchor,
1136 scroll_top_row: u32,
1137}
1138
1139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1140pub enum GotoDefinitionKind {
1141 Symbol,
1142 Declaration,
1143 Type,
1144 Implementation,
1145}
1146
1147#[derive(Debug, Clone)]
1148enum InlayHintRefreshReason {
1149 ModifiersChanged(bool),
1150 Toggle(bool),
1151 SettingsChange(InlayHintSettings),
1152 NewLinesShown,
1153 BufferEdited(HashSet<Arc<Language>>),
1154 RefreshRequested,
1155 ExcerptsRemoved(Vec<ExcerptId>),
1156}
1157
1158impl InlayHintRefreshReason {
1159 fn description(&self) -> &'static str {
1160 match self {
1161 Self::ModifiersChanged(_) => "modifiers changed",
1162 Self::Toggle(_) => "toggle",
1163 Self::SettingsChange(_) => "settings change",
1164 Self::NewLinesShown => "new lines shown",
1165 Self::BufferEdited(_) => "buffer edited",
1166 Self::RefreshRequested => "refresh requested",
1167 Self::ExcerptsRemoved(_) => "excerpts removed",
1168 }
1169 }
1170}
1171
1172pub enum FormatTarget {
1173 Buffers,
1174 Ranges(Vec<Range<MultiBufferPoint>>),
1175}
1176
1177pub(crate) struct FocusedBlock {
1178 id: BlockId,
1179 focus_handle: WeakFocusHandle,
1180}
1181
1182#[derive(Clone)]
1183enum JumpData {
1184 MultiBufferRow {
1185 row: MultiBufferRow,
1186 line_offset_from_top: u32,
1187 },
1188 MultiBufferPoint {
1189 excerpt_id: ExcerptId,
1190 position: Point,
1191 anchor: text::Anchor,
1192 line_offset_from_top: u32,
1193 },
1194}
1195
1196pub enum MultibufferSelectionMode {
1197 First,
1198 All,
1199}
1200
1201#[derive(Clone, Copy, Debug, Default)]
1202pub struct RewrapOptions {
1203 pub override_language_settings: bool,
1204 pub preserve_existing_whitespace: bool,
1205}
1206
1207impl Editor {
1208 pub fn single_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(
1212 EditorMode::SingleLine { auto_width: false },
1213 buffer,
1214 None,
1215 window,
1216 cx,
1217 )
1218 }
1219
1220 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1221 let buffer = cx.new(|cx| Buffer::local("", cx));
1222 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1223 Self::new(EditorMode::full(), buffer, None, window, cx)
1224 }
1225
1226 pub fn auto_width(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::SingleLine { auto_width: true },
1231 buffer,
1232 None,
1233 window,
1234 cx,
1235 )
1236 }
1237
1238 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1239 let buffer = cx.new(|cx| Buffer::local("", cx));
1240 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1241 Self::new(
1242 EditorMode::AutoHeight { max_lines },
1243 buffer,
1244 None,
1245 window,
1246 cx,
1247 )
1248 }
1249
1250 pub fn for_buffer(
1251 buffer: Entity<Buffer>,
1252 project: Option<Entity<Project>>,
1253 window: &mut Window,
1254 cx: &mut Context<Self>,
1255 ) -> Self {
1256 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1257 Self::new(EditorMode::full(), buffer, project, window, cx)
1258 }
1259
1260 pub fn for_multibuffer(
1261 buffer: Entity<MultiBuffer>,
1262 project: Option<Entity<Project>>,
1263 window: &mut Window,
1264 cx: &mut Context<Self>,
1265 ) -> Self {
1266 Self::new(EditorMode::full(), buffer, project, window, cx)
1267 }
1268
1269 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1270 let mut clone = Self::new(
1271 self.mode,
1272 self.buffer.clone(),
1273 self.project.clone(),
1274 window,
1275 cx,
1276 );
1277 self.display_map.update(cx, |display_map, cx| {
1278 let snapshot = display_map.snapshot(cx);
1279 clone.display_map.update(cx, |display_map, cx| {
1280 display_map.set_state(&snapshot, cx);
1281 });
1282 });
1283 clone.folds_did_change(cx);
1284 clone.selections.clone_state(&self.selections);
1285 clone.scroll_manager.clone_state(&self.scroll_manager);
1286 clone.searchable = self.searchable;
1287 clone.read_only = self.read_only;
1288 clone
1289 }
1290
1291 pub fn new(
1292 mode: EditorMode,
1293 buffer: Entity<MultiBuffer>,
1294 project: Option<Entity<Project>>,
1295 window: &mut Window,
1296 cx: &mut Context<Self>,
1297 ) -> Self {
1298 let style = window.text_style();
1299 let font_size = style.font_size.to_pixels(window.rem_size());
1300 let editor = cx.entity().downgrade();
1301 let fold_placeholder = FoldPlaceholder {
1302 constrain_width: true,
1303 render: Arc::new(move |fold_id, fold_range, cx| {
1304 let editor = editor.clone();
1305 div()
1306 .id(fold_id)
1307 .bg(cx.theme().colors().ghost_element_background)
1308 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1309 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1310 .rounded_xs()
1311 .size_full()
1312 .cursor_pointer()
1313 .child("⋯")
1314 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1315 .on_click(move |_, _window, cx| {
1316 editor
1317 .update(cx, |editor, cx| {
1318 editor.unfold_ranges(
1319 &[fold_range.start..fold_range.end],
1320 true,
1321 false,
1322 cx,
1323 );
1324 cx.stop_propagation();
1325 })
1326 .ok();
1327 })
1328 .into_any()
1329 }),
1330 merge_adjacent: true,
1331 ..Default::default()
1332 };
1333 let display_map = cx.new(|cx| {
1334 DisplayMap::new(
1335 buffer.clone(),
1336 style.font(),
1337 font_size,
1338 None,
1339 FILE_HEADER_HEIGHT,
1340 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1341 fold_placeholder,
1342 cx,
1343 )
1344 });
1345
1346 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1347
1348 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1349
1350 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1351 .then(|| language_settings::SoftWrap::None);
1352
1353 let mut project_subscriptions = Vec::new();
1354 if mode.is_full() {
1355 if let Some(project) = project.as_ref() {
1356 project_subscriptions.push(cx.subscribe_in(
1357 project,
1358 window,
1359 |editor, _, event, window, cx| match event {
1360 project::Event::RefreshCodeLens => {
1361 // we always query lens with actions, without storing them, always refreshing them
1362 }
1363 project::Event::RefreshInlayHints => {
1364 editor
1365 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1366 }
1367 project::Event::SnippetEdit(id, snippet_edits) => {
1368 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1369 let focus_handle = editor.focus_handle(cx);
1370 if focus_handle.is_focused(window) {
1371 let snapshot = buffer.read(cx).snapshot();
1372 for (range, snippet) in snippet_edits {
1373 let editor_range =
1374 language::range_from_lsp(*range).to_offset(&snapshot);
1375 editor
1376 .insert_snippet(
1377 &[editor_range],
1378 snippet.clone(),
1379 window,
1380 cx,
1381 )
1382 .ok();
1383 }
1384 }
1385 }
1386 }
1387 _ => {}
1388 },
1389 ));
1390 if let Some(task_inventory) = project
1391 .read(cx)
1392 .task_store()
1393 .read(cx)
1394 .task_inventory()
1395 .cloned()
1396 {
1397 project_subscriptions.push(cx.observe_in(
1398 &task_inventory,
1399 window,
1400 |editor, _, window, cx| {
1401 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1402 },
1403 ));
1404 };
1405
1406 project_subscriptions.push(cx.subscribe_in(
1407 &project.read(cx).breakpoint_store(),
1408 window,
1409 |editor, _, event, window, cx| match event {
1410 BreakpointStoreEvent::ActiveDebugLineChanged => {
1411 if editor.go_to_active_debug_line(window, cx) {
1412 cx.stop_propagation();
1413 }
1414 }
1415 _ => {}
1416 },
1417 ));
1418 }
1419 }
1420
1421 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1422
1423 let inlay_hint_settings =
1424 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1425 let focus_handle = cx.focus_handle();
1426 cx.on_focus(&focus_handle, window, Self::handle_focus)
1427 .detach();
1428 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1429 .detach();
1430 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1431 .detach();
1432 cx.on_blur(&focus_handle, window, Self::handle_blur)
1433 .detach();
1434
1435 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1436 Some(false)
1437 } else {
1438 None
1439 };
1440
1441 let breakpoint_store = match (mode, project.as_ref()) {
1442 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1443 _ => None,
1444 };
1445
1446 let mut code_action_providers = Vec::new();
1447 let mut load_uncommitted_diff = None;
1448 if let Some(project) = project.clone() {
1449 load_uncommitted_diff = Some(
1450 get_uncommitted_diff_for_buffer(
1451 &project,
1452 buffer.read(cx).all_buffers(),
1453 buffer.clone(),
1454 cx,
1455 )
1456 .shared(),
1457 );
1458 code_action_providers.push(Rc::new(project) as Rc<_>);
1459 }
1460
1461 let mut this = Self {
1462 focus_handle,
1463 show_cursor_when_unfocused: false,
1464 last_focused_descendant: None,
1465 buffer: buffer.clone(),
1466 display_map: display_map.clone(),
1467 selections,
1468 scroll_manager: ScrollManager::new(cx),
1469 columnar_selection_tail: None,
1470 add_selections_state: None,
1471 select_next_state: None,
1472 select_prev_state: None,
1473 selection_history: Default::default(),
1474 autoclose_regions: Default::default(),
1475 snippet_stack: Default::default(),
1476 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1477 ime_transaction: Default::default(),
1478 active_diagnostics: None,
1479 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1480 inline_diagnostics_update: Task::ready(()),
1481 inline_diagnostics: Vec::new(),
1482 soft_wrap_mode_override,
1483 hard_wrap: None,
1484 completion_provider: project.clone().map(|project| Box::new(project) as _),
1485 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1486 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1487 project,
1488 blink_manager: blink_manager.clone(),
1489 show_local_selections: true,
1490 show_scrollbars: true,
1491 mode,
1492 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1493 show_gutter: mode.is_full(),
1494 show_line_numbers: None,
1495 use_relative_line_numbers: None,
1496 show_git_diff_gutter: None,
1497 show_code_actions: None,
1498 show_runnables: None,
1499 show_breakpoints: None,
1500 show_wrap_guides: None,
1501 show_indent_guides,
1502 placeholder_text: None,
1503 highlight_order: 0,
1504 highlighted_rows: HashMap::default(),
1505 background_highlights: Default::default(),
1506 gutter_highlights: TreeMap::default(),
1507 scrollbar_marker_state: ScrollbarMarkerState::default(),
1508 active_indent_guides_state: ActiveIndentGuidesState::default(),
1509 nav_history: None,
1510 context_menu: RefCell::new(None),
1511 context_menu_options: None,
1512 mouse_context_menu: None,
1513 completion_tasks: Default::default(),
1514 signature_help_state: SignatureHelpState::default(),
1515 auto_signature_help: None,
1516 find_all_references_task_sources: Vec::new(),
1517 next_completion_id: 0,
1518 next_inlay_id: 0,
1519 code_action_providers,
1520 available_code_actions: Default::default(),
1521 code_actions_task: Default::default(),
1522 selection_highlight_task: Default::default(),
1523 document_highlights_task: Default::default(),
1524 linked_editing_range_task: Default::default(),
1525 pending_rename: Default::default(),
1526 searchable: true,
1527 cursor_shape: EditorSettings::get_global(cx)
1528 .cursor_shape
1529 .unwrap_or_default(),
1530 current_line_highlight: None,
1531 autoindent_mode: Some(AutoindentMode::EachLine),
1532 collapse_matches: false,
1533 workspace: None,
1534 input_enabled: true,
1535 use_modal_editing: mode.is_full(),
1536 read_only: false,
1537 use_autoclose: true,
1538 use_auto_surround: true,
1539 auto_replace_emoji_shortcode: false,
1540 jsx_tag_auto_close_enabled_in_any_buffer: false,
1541 leader_peer_id: None,
1542 remote_id: None,
1543 hover_state: Default::default(),
1544 pending_mouse_down: None,
1545 hovered_link_state: Default::default(),
1546 edit_prediction_provider: None,
1547 active_inline_completion: None,
1548 stale_inline_completion_in_menu: None,
1549 edit_prediction_preview: EditPredictionPreview::Inactive {
1550 released_too_fast: false,
1551 },
1552 inline_diagnostics_enabled: mode.is_full(),
1553 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1554
1555 gutter_hovered: false,
1556 pixel_position_of_newest_cursor: None,
1557 last_bounds: None,
1558 last_position_map: None,
1559 expect_bounds_change: None,
1560 gutter_dimensions: GutterDimensions::default(),
1561 style: None,
1562 show_cursor_names: false,
1563 hovered_cursors: Default::default(),
1564 next_editor_action_id: EditorActionId::default(),
1565 editor_actions: Rc::default(),
1566 inline_completions_hidden_for_vim_mode: false,
1567 show_inline_completions_override: None,
1568 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1569 edit_prediction_settings: EditPredictionSettings::Disabled,
1570 edit_prediction_indent_conflict: false,
1571 edit_prediction_requires_modifier_in_indent_conflict: true,
1572 custom_context_menu: None,
1573 show_git_blame_gutter: false,
1574 show_git_blame_inline: false,
1575 show_selection_menu: None,
1576 show_git_blame_inline_delay_task: None,
1577 git_blame_inline_tooltip: None,
1578 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1579 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1580 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1581 .session
1582 .restore_unsaved_buffers,
1583 blame: None,
1584 blame_subscription: None,
1585 tasks: Default::default(),
1586
1587 breakpoint_store,
1588 gutter_breakpoint_indicator: (None, None),
1589 _subscriptions: vec![
1590 cx.observe(&buffer, Self::on_buffer_changed),
1591 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1592 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1593 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1594 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1595 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1596 cx.observe_window_activation(window, |editor, window, cx| {
1597 let active = window.is_window_active();
1598 editor.blink_manager.update(cx, |blink_manager, cx| {
1599 if active {
1600 blink_manager.enable(cx);
1601 } else {
1602 blink_manager.disable(cx);
1603 }
1604 });
1605 }),
1606 ],
1607 tasks_update_task: None,
1608 linked_edit_ranges: Default::default(),
1609 in_project_search: false,
1610 previous_search_ranges: None,
1611 breadcrumb_header: None,
1612 focused_block: None,
1613 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1614 addons: HashMap::default(),
1615 registered_buffers: HashMap::default(),
1616 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1617 selection_mark_mode: false,
1618 toggle_fold_multiple_buffers: Task::ready(()),
1619 serialize_selections: Task::ready(()),
1620 serialize_folds: Task::ready(()),
1621 text_style_refinement: None,
1622 load_diff_task: load_uncommitted_diff,
1623 mouse_cursor_hidden: false,
1624 hide_mouse_mode: EditorSettings::get_global(cx)
1625 .hide_mouse
1626 .unwrap_or_default(),
1627 };
1628 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1629 this._subscriptions
1630 .push(cx.observe(breakpoints, |_, _, cx| {
1631 cx.notify();
1632 }));
1633 }
1634 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1635 this._subscriptions.extend(project_subscriptions);
1636
1637 this._subscriptions.push(cx.subscribe_in(
1638 &cx.entity(),
1639 window,
1640 |editor, _, e: &EditorEvent, window, cx| {
1641 if let EditorEvent::SelectionsChanged { local } = e {
1642 if *local {
1643 let new_anchor = editor.scroll_manager.anchor();
1644 let snapshot = editor.snapshot(window, cx);
1645 editor.update_restoration_data(cx, move |data| {
1646 data.scroll_position = (
1647 new_anchor.top_row(&snapshot.buffer_snapshot),
1648 new_anchor.offset,
1649 );
1650 });
1651 }
1652 }
1653 },
1654 ));
1655
1656 this.end_selection(window, cx);
1657 this.scroll_manager.show_scrollbars(window, cx);
1658 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1659
1660 if mode.is_full() {
1661 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1662 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1663
1664 if this.git_blame_inline_enabled {
1665 this.git_blame_inline_enabled = true;
1666 this.start_git_blame_inline(false, window, cx);
1667 }
1668
1669 this.go_to_active_debug_line(window, cx);
1670
1671 if let Some(buffer) = buffer.read(cx).as_singleton() {
1672 if let Some(project) = this.project.as_ref() {
1673 let handle = project.update(cx, |project, cx| {
1674 project.register_buffer_with_language_servers(&buffer, cx)
1675 });
1676 this.registered_buffers
1677 .insert(buffer.read(cx).remote_id(), handle);
1678 }
1679 }
1680 }
1681
1682 this.report_editor_event("Editor Opened", None, cx);
1683 this
1684 }
1685
1686 pub fn deploy_mouse_context_menu(
1687 &mut self,
1688 position: gpui::Point<Pixels>,
1689 context_menu: Entity<ContextMenu>,
1690 window: &mut Window,
1691 cx: &mut Context<Self>,
1692 ) {
1693 self.mouse_context_menu = Some(MouseContextMenu::new(
1694 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1695 context_menu,
1696 window,
1697 cx,
1698 ));
1699 }
1700
1701 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1702 self.mouse_context_menu
1703 .as_ref()
1704 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1705 }
1706
1707 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1708 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1709 }
1710
1711 fn key_context_internal(
1712 &self,
1713 has_active_edit_prediction: bool,
1714 window: &Window,
1715 cx: &App,
1716 ) -> KeyContext {
1717 let mut key_context = KeyContext::new_with_defaults();
1718 key_context.add("Editor");
1719 let mode = match self.mode {
1720 EditorMode::SingleLine { .. } => "single_line",
1721 EditorMode::AutoHeight { .. } => "auto_height",
1722 EditorMode::Full { .. } => "full",
1723 };
1724
1725 if EditorSettings::jupyter_enabled(cx) {
1726 key_context.add("jupyter");
1727 }
1728
1729 key_context.set("mode", mode);
1730 if self.pending_rename.is_some() {
1731 key_context.add("renaming");
1732 }
1733
1734 match self.context_menu.borrow().as_ref() {
1735 Some(CodeContextMenu::Completions(_)) => {
1736 key_context.add("menu");
1737 key_context.add("showing_completions");
1738 }
1739 Some(CodeContextMenu::CodeActions(_)) => {
1740 key_context.add("menu");
1741 key_context.add("showing_code_actions")
1742 }
1743 None => {}
1744 }
1745
1746 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1747 if !self.focus_handle(cx).contains_focused(window, cx)
1748 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1749 {
1750 for addon in self.addons.values() {
1751 addon.extend_key_context(&mut key_context, cx)
1752 }
1753 }
1754
1755 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1756 if let Some(extension) = singleton_buffer
1757 .read(cx)
1758 .file()
1759 .and_then(|file| file.path().extension()?.to_str())
1760 {
1761 key_context.set("extension", extension.to_string());
1762 }
1763 } else {
1764 key_context.add("multibuffer");
1765 }
1766
1767 if has_active_edit_prediction {
1768 if self.edit_prediction_in_conflict() {
1769 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1770 } else {
1771 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1772 key_context.add("copilot_suggestion");
1773 }
1774 }
1775
1776 if self.selection_mark_mode {
1777 key_context.add("selection_mode");
1778 }
1779
1780 key_context
1781 }
1782
1783 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1784 self.mouse_cursor_hidden = match origin {
1785 HideMouseCursorOrigin::TypingAction => {
1786 matches!(
1787 self.hide_mouse_mode,
1788 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1789 )
1790 }
1791 HideMouseCursorOrigin::MovementAction => {
1792 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1793 }
1794 };
1795 }
1796
1797 pub fn edit_prediction_in_conflict(&self) -> bool {
1798 if !self.show_edit_predictions_in_menu() {
1799 return false;
1800 }
1801
1802 let showing_completions = self
1803 .context_menu
1804 .borrow()
1805 .as_ref()
1806 .map_or(false, |context| {
1807 matches!(context, CodeContextMenu::Completions(_))
1808 });
1809
1810 showing_completions
1811 || self.edit_prediction_requires_modifier()
1812 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1813 // bindings to insert tab characters.
1814 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1815 }
1816
1817 pub fn accept_edit_prediction_keybind(
1818 &self,
1819 window: &Window,
1820 cx: &App,
1821 ) -> AcceptEditPredictionBinding {
1822 let key_context = self.key_context_internal(true, window, cx);
1823 let in_conflict = self.edit_prediction_in_conflict();
1824
1825 AcceptEditPredictionBinding(
1826 window
1827 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1828 .into_iter()
1829 .filter(|binding| {
1830 !in_conflict
1831 || binding
1832 .keystrokes()
1833 .first()
1834 .map_or(false, |keystroke| keystroke.modifiers.modified())
1835 })
1836 .rev()
1837 .min_by_key(|binding| {
1838 binding
1839 .keystrokes()
1840 .first()
1841 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1842 }),
1843 )
1844 }
1845
1846 pub fn new_file(
1847 workspace: &mut Workspace,
1848 _: &workspace::NewFile,
1849 window: &mut Window,
1850 cx: &mut Context<Workspace>,
1851 ) {
1852 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1853 "Failed to create buffer",
1854 window,
1855 cx,
1856 |e, _, _| match e.error_code() {
1857 ErrorCode::RemoteUpgradeRequired => Some(format!(
1858 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1859 e.error_tag("required").unwrap_or("the latest version")
1860 )),
1861 _ => None,
1862 },
1863 );
1864 }
1865
1866 pub fn new_in_workspace(
1867 workspace: &mut Workspace,
1868 window: &mut Window,
1869 cx: &mut Context<Workspace>,
1870 ) -> Task<Result<Entity<Editor>>> {
1871 let project = workspace.project().clone();
1872 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1873
1874 cx.spawn_in(window, async move |workspace, cx| {
1875 let buffer = create.await?;
1876 workspace.update_in(cx, |workspace, window, cx| {
1877 let editor =
1878 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1879 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1880 editor
1881 })
1882 })
1883 }
1884
1885 fn new_file_vertical(
1886 workspace: &mut Workspace,
1887 _: &workspace::NewFileSplitVertical,
1888 window: &mut Window,
1889 cx: &mut Context<Workspace>,
1890 ) {
1891 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1892 }
1893
1894 fn new_file_horizontal(
1895 workspace: &mut Workspace,
1896 _: &workspace::NewFileSplitHorizontal,
1897 window: &mut Window,
1898 cx: &mut Context<Workspace>,
1899 ) {
1900 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1901 }
1902
1903 fn new_file_in_direction(
1904 workspace: &mut Workspace,
1905 direction: SplitDirection,
1906 window: &mut Window,
1907 cx: &mut Context<Workspace>,
1908 ) {
1909 let project = workspace.project().clone();
1910 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1911
1912 cx.spawn_in(window, async move |workspace, cx| {
1913 let buffer = create.await?;
1914 workspace.update_in(cx, move |workspace, window, cx| {
1915 workspace.split_item(
1916 direction,
1917 Box::new(
1918 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1919 ),
1920 window,
1921 cx,
1922 )
1923 })?;
1924 anyhow::Ok(())
1925 })
1926 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1927 match e.error_code() {
1928 ErrorCode::RemoteUpgradeRequired => Some(format!(
1929 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1930 e.error_tag("required").unwrap_or("the latest version")
1931 )),
1932 _ => None,
1933 }
1934 });
1935 }
1936
1937 pub fn leader_peer_id(&self) -> Option<PeerId> {
1938 self.leader_peer_id
1939 }
1940
1941 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1942 &self.buffer
1943 }
1944
1945 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1946 self.workspace.as_ref()?.0.upgrade()
1947 }
1948
1949 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1950 self.buffer().read(cx).title(cx)
1951 }
1952
1953 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1954 let git_blame_gutter_max_author_length = self
1955 .render_git_blame_gutter(cx)
1956 .then(|| {
1957 if let Some(blame) = self.blame.as_ref() {
1958 let max_author_length =
1959 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1960 Some(max_author_length)
1961 } else {
1962 None
1963 }
1964 })
1965 .flatten();
1966
1967 EditorSnapshot {
1968 mode: self.mode,
1969 show_gutter: self.show_gutter,
1970 show_line_numbers: self.show_line_numbers,
1971 show_git_diff_gutter: self.show_git_diff_gutter,
1972 show_code_actions: self.show_code_actions,
1973 show_runnables: self.show_runnables,
1974 show_breakpoints: self.show_breakpoints,
1975 git_blame_gutter_max_author_length,
1976 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1977 scroll_anchor: self.scroll_manager.anchor(),
1978 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1979 placeholder_text: self.placeholder_text.clone(),
1980 is_focused: self.focus_handle.is_focused(window),
1981 current_line_highlight: self
1982 .current_line_highlight
1983 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1984 gutter_hovered: self.gutter_hovered,
1985 }
1986 }
1987
1988 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1989 self.buffer.read(cx).language_at(point, cx)
1990 }
1991
1992 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1993 self.buffer.read(cx).read(cx).file_at(point).cloned()
1994 }
1995
1996 pub fn active_excerpt(
1997 &self,
1998 cx: &App,
1999 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2000 self.buffer
2001 .read(cx)
2002 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2003 }
2004
2005 pub fn mode(&self) -> EditorMode {
2006 self.mode
2007 }
2008
2009 pub fn set_mode(&mut self, mode: EditorMode) {
2010 self.mode = mode;
2011 }
2012
2013 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2014 self.collaboration_hub.as_deref()
2015 }
2016
2017 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2018 self.collaboration_hub = Some(hub);
2019 }
2020
2021 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2022 self.in_project_search = in_project_search;
2023 }
2024
2025 pub fn set_custom_context_menu(
2026 &mut self,
2027 f: impl 'static
2028 + Fn(
2029 &mut Self,
2030 DisplayPoint,
2031 &mut Window,
2032 &mut Context<Self>,
2033 ) -> Option<Entity<ui::ContextMenu>>,
2034 ) {
2035 self.custom_context_menu = Some(Box::new(f))
2036 }
2037
2038 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2039 self.completion_provider = provider;
2040 }
2041
2042 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2043 self.semantics_provider.clone()
2044 }
2045
2046 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2047 self.semantics_provider = provider;
2048 }
2049
2050 pub fn set_edit_prediction_provider<T>(
2051 &mut self,
2052 provider: Option<Entity<T>>,
2053 window: &mut Window,
2054 cx: &mut Context<Self>,
2055 ) where
2056 T: EditPredictionProvider,
2057 {
2058 self.edit_prediction_provider =
2059 provider.map(|provider| RegisteredInlineCompletionProvider {
2060 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2061 if this.focus_handle.is_focused(window) {
2062 this.update_visible_inline_completion(window, cx);
2063 }
2064 }),
2065 provider: Arc::new(provider),
2066 });
2067 self.update_edit_prediction_settings(cx);
2068 self.refresh_inline_completion(false, false, window, cx);
2069 }
2070
2071 pub fn placeholder_text(&self) -> Option<&str> {
2072 self.placeholder_text.as_deref()
2073 }
2074
2075 pub fn set_placeholder_text(
2076 &mut self,
2077 placeholder_text: impl Into<Arc<str>>,
2078 cx: &mut Context<Self>,
2079 ) {
2080 let placeholder_text = Some(placeholder_text.into());
2081 if self.placeholder_text != placeholder_text {
2082 self.placeholder_text = placeholder_text;
2083 cx.notify();
2084 }
2085 }
2086
2087 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2088 self.cursor_shape = cursor_shape;
2089
2090 // Disrupt blink for immediate user feedback that the cursor shape has changed
2091 self.blink_manager.update(cx, BlinkManager::show_cursor);
2092
2093 cx.notify();
2094 }
2095
2096 pub fn set_current_line_highlight(
2097 &mut self,
2098 current_line_highlight: Option<CurrentLineHighlight>,
2099 ) {
2100 self.current_line_highlight = current_line_highlight;
2101 }
2102
2103 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2104 self.collapse_matches = collapse_matches;
2105 }
2106
2107 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2108 let buffers = self.buffer.read(cx).all_buffers();
2109 let Some(project) = self.project.as_ref() else {
2110 return;
2111 };
2112 project.update(cx, |project, cx| {
2113 for buffer in buffers {
2114 self.registered_buffers
2115 .entry(buffer.read(cx).remote_id())
2116 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2117 }
2118 })
2119 }
2120
2121 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2122 if self.collapse_matches {
2123 return range.start..range.start;
2124 }
2125 range.clone()
2126 }
2127
2128 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2129 if self.display_map.read(cx).clip_at_line_ends != clip {
2130 self.display_map
2131 .update(cx, |map, _| map.clip_at_line_ends = clip);
2132 }
2133 }
2134
2135 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2136 self.input_enabled = input_enabled;
2137 }
2138
2139 pub fn set_inline_completions_hidden_for_vim_mode(
2140 &mut self,
2141 hidden: bool,
2142 window: &mut Window,
2143 cx: &mut Context<Self>,
2144 ) {
2145 if hidden != self.inline_completions_hidden_for_vim_mode {
2146 self.inline_completions_hidden_for_vim_mode = hidden;
2147 if hidden {
2148 self.update_visible_inline_completion(window, cx);
2149 } else {
2150 self.refresh_inline_completion(true, false, window, cx);
2151 }
2152 }
2153 }
2154
2155 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2156 self.menu_inline_completions_policy = value;
2157 }
2158
2159 pub fn set_autoindent(&mut self, autoindent: bool) {
2160 if autoindent {
2161 self.autoindent_mode = Some(AutoindentMode::EachLine);
2162 } else {
2163 self.autoindent_mode = None;
2164 }
2165 }
2166
2167 pub fn read_only(&self, cx: &App) -> bool {
2168 self.read_only || self.buffer.read(cx).read_only()
2169 }
2170
2171 pub fn set_read_only(&mut self, read_only: bool) {
2172 self.read_only = read_only;
2173 }
2174
2175 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2176 self.use_autoclose = autoclose;
2177 }
2178
2179 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2180 self.use_auto_surround = auto_surround;
2181 }
2182
2183 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2184 self.auto_replace_emoji_shortcode = auto_replace;
2185 }
2186
2187 pub fn toggle_edit_predictions(
2188 &mut self,
2189 _: &ToggleEditPrediction,
2190 window: &mut Window,
2191 cx: &mut Context<Self>,
2192 ) {
2193 if self.show_inline_completions_override.is_some() {
2194 self.set_show_edit_predictions(None, window, cx);
2195 } else {
2196 let show_edit_predictions = !self.edit_predictions_enabled();
2197 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2198 }
2199 }
2200
2201 pub fn set_show_edit_predictions(
2202 &mut self,
2203 show_edit_predictions: Option<bool>,
2204 window: &mut Window,
2205 cx: &mut Context<Self>,
2206 ) {
2207 self.show_inline_completions_override = show_edit_predictions;
2208 self.update_edit_prediction_settings(cx);
2209
2210 if let Some(false) = show_edit_predictions {
2211 self.discard_inline_completion(false, cx);
2212 } else {
2213 self.refresh_inline_completion(false, true, window, cx);
2214 }
2215 }
2216
2217 fn inline_completions_disabled_in_scope(
2218 &self,
2219 buffer: &Entity<Buffer>,
2220 buffer_position: language::Anchor,
2221 cx: &App,
2222 ) -> bool {
2223 let snapshot = buffer.read(cx).snapshot();
2224 let settings = snapshot.settings_at(buffer_position, cx);
2225
2226 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2227 return false;
2228 };
2229
2230 scope.override_name().map_or(false, |scope_name| {
2231 settings
2232 .edit_predictions_disabled_in
2233 .iter()
2234 .any(|s| s == scope_name)
2235 })
2236 }
2237
2238 pub fn set_use_modal_editing(&mut self, to: bool) {
2239 self.use_modal_editing = to;
2240 }
2241
2242 pub fn use_modal_editing(&self) -> bool {
2243 self.use_modal_editing
2244 }
2245
2246 fn selections_did_change(
2247 &mut self,
2248 local: bool,
2249 old_cursor_position: &Anchor,
2250 show_completions: bool,
2251 window: &mut Window,
2252 cx: &mut Context<Self>,
2253 ) {
2254 window.invalidate_character_coordinates();
2255
2256 // Copy selections to primary selection buffer
2257 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2258 if local {
2259 let selections = self.selections.all::<usize>(cx);
2260 let buffer_handle = self.buffer.read(cx).read(cx);
2261
2262 let mut text = String::new();
2263 for (index, selection) in selections.iter().enumerate() {
2264 let text_for_selection = buffer_handle
2265 .text_for_range(selection.start..selection.end)
2266 .collect::<String>();
2267
2268 text.push_str(&text_for_selection);
2269 if index != selections.len() - 1 {
2270 text.push('\n');
2271 }
2272 }
2273
2274 if !text.is_empty() {
2275 cx.write_to_primary(ClipboardItem::new_string(text));
2276 }
2277 }
2278
2279 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2280 self.buffer.update(cx, |buffer, cx| {
2281 buffer.set_active_selections(
2282 &self.selections.disjoint_anchors(),
2283 self.selections.line_mode,
2284 self.cursor_shape,
2285 cx,
2286 )
2287 });
2288 }
2289 let display_map = self
2290 .display_map
2291 .update(cx, |display_map, cx| display_map.snapshot(cx));
2292 let buffer = &display_map.buffer_snapshot;
2293 self.add_selections_state = None;
2294 self.select_next_state = None;
2295 self.select_prev_state = None;
2296 self.select_syntax_node_history.try_clear();
2297 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2298 self.snippet_stack
2299 .invalidate(&self.selections.disjoint_anchors(), buffer);
2300 self.take_rename(false, window, cx);
2301
2302 let new_cursor_position = self.selections.newest_anchor().head();
2303
2304 self.push_to_nav_history(
2305 *old_cursor_position,
2306 Some(new_cursor_position.to_point(buffer)),
2307 false,
2308 cx,
2309 );
2310
2311 if local {
2312 let new_cursor_position = self.selections.newest_anchor().head();
2313 let mut context_menu = self.context_menu.borrow_mut();
2314 let completion_menu = match context_menu.as_ref() {
2315 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2316 _ => {
2317 *context_menu = None;
2318 None
2319 }
2320 };
2321 if let Some(buffer_id) = new_cursor_position.buffer_id {
2322 if !self.registered_buffers.contains_key(&buffer_id) {
2323 if let Some(project) = self.project.as_ref() {
2324 project.update(cx, |project, cx| {
2325 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2326 return;
2327 };
2328 self.registered_buffers.insert(
2329 buffer_id,
2330 project.register_buffer_with_language_servers(&buffer, cx),
2331 );
2332 })
2333 }
2334 }
2335 }
2336
2337 if let Some(completion_menu) = completion_menu {
2338 let cursor_position = new_cursor_position.to_offset(buffer);
2339 let (word_range, kind) =
2340 buffer.surrounding_word(completion_menu.initial_position, true);
2341 if kind == Some(CharKind::Word)
2342 && word_range.to_inclusive().contains(&cursor_position)
2343 {
2344 let mut completion_menu = completion_menu.clone();
2345 drop(context_menu);
2346
2347 let query = Self::completion_query(buffer, cursor_position);
2348 cx.spawn(async move |this, cx| {
2349 completion_menu
2350 .filter(query.as_deref(), cx.background_executor().clone())
2351 .await;
2352
2353 this.update(cx, |this, cx| {
2354 let mut context_menu = this.context_menu.borrow_mut();
2355 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2356 else {
2357 return;
2358 };
2359
2360 if menu.id > completion_menu.id {
2361 return;
2362 }
2363
2364 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2365 drop(context_menu);
2366 cx.notify();
2367 })
2368 })
2369 .detach();
2370
2371 if show_completions {
2372 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2373 }
2374 } else {
2375 drop(context_menu);
2376 self.hide_context_menu(window, cx);
2377 }
2378 } else {
2379 drop(context_menu);
2380 }
2381
2382 hide_hover(self, cx);
2383
2384 if old_cursor_position.to_display_point(&display_map).row()
2385 != new_cursor_position.to_display_point(&display_map).row()
2386 {
2387 self.available_code_actions.take();
2388 }
2389 self.refresh_code_actions(window, cx);
2390 self.refresh_document_highlights(cx);
2391 self.refresh_selected_text_highlights(window, cx);
2392 refresh_matching_bracket_highlights(self, window, cx);
2393 self.update_visible_inline_completion(window, cx);
2394 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2395 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2396 if self.git_blame_inline_enabled {
2397 self.start_inline_blame_timer(window, cx);
2398 }
2399 }
2400
2401 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2402 cx.emit(EditorEvent::SelectionsChanged { local });
2403
2404 let selections = &self.selections.disjoint;
2405 if selections.len() == 1 {
2406 cx.emit(SearchEvent::ActiveMatchChanged)
2407 }
2408 if local {
2409 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2410 let inmemory_selections = selections
2411 .iter()
2412 .map(|s| {
2413 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2414 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2415 })
2416 .collect();
2417 self.update_restoration_data(cx, |data| {
2418 data.selections = inmemory_selections;
2419 });
2420
2421 if WorkspaceSettings::get(None, cx).restore_on_startup
2422 != RestoreOnStartupBehavior::None
2423 {
2424 if let Some(workspace_id) =
2425 self.workspace.as_ref().and_then(|workspace| workspace.1)
2426 {
2427 let snapshot = self.buffer().read(cx).snapshot(cx);
2428 let selections = selections.clone();
2429 let background_executor = cx.background_executor().clone();
2430 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2431 self.serialize_selections = cx.background_spawn(async move {
2432 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2433 let db_selections = selections
2434 .iter()
2435 .map(|selection| {
2436 (
2437 selection.start.to_offset(&snapshot),
2438 selection.end.to_offset(&snapshot),
2439 )
2440 })
2441 .collect();
2442
2443 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2444 .await
2445 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2446 .log_err();
2447 });
2448 }
2449 }
2450 }
2451 }
2452
2453 cx.notify();
2454 }
2455
2456 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2457 use text::ToOffset as _;
2458 use text::ToPoint as _;
2459
2460 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2461 return;
2462 }
2463
2464 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2465 return;
2466 };
2467
2468 let snapshot = singleton.read(cx).snapshot();
2469 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2470 let display_snapshot = display_map.snapshot(cx);
2471
2472 display_snapshot
2473 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2474 .map(|fold| {
2475 fold.range.start.text_anchor.to_point(&snapshot)
2476 ..fold.range.end.text_anchor.to_point(&snapshot)
2477 })
2478 .collect()
2479 });
2480 self.update_restoration_data(cx, |data| {
2481 data.folds = inmemory_folds;
2482 });
2483
2484 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2485 return;
2486 };
2487 let background_executor = cx.background_executor().clone();
2488 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2489 let db_folds = self.display_map.update(cx, |display_map, cx| {
2490 display_map
2491 .snapshot(cx)
2492 .folds_in_range(0..snapshot.len())
2493 .map(|fold| {
2494 (
2495 fold.range.start.text_anchor.to_offset(&snapshot),
2496 fold.range.end.text_anchor.to_offset(&snapshot),
2497 )
2498 })
2499 .collect()
2500 });
2501 self.serialize_folds = cx.background_spawn(async move {
2502 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2503 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2504 .await
2505 .with_context(|| {
2506 format!(
2507 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2508 )
2509 })
2510 .log_err();
2511 });
2512 }
2513
2514 pub fn sync_selections(
2515 &mut self,
2516 other: Entity<Editor>,
2517 cx: &mut Context<Self>,
2518 ) -> gpui::Subscription {
2519 let other_selections = other.read(cx).selections.disjoint.to_vec();
2520 self.selections.change_with(cx, |selections| {
2521 selections.select_anchors(other_selections);
2522 });
2523
2524 let other_subscription =
2525 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2526 EditorEvent::SelectionsChanged { local: true } => {
2527 let other_selections = other.read(cx).selections.disjoint.to_vec();
2528 if other_selections.is_empty() {
2529 return;
2530 }
2531 this.selections.change_with(cx, |selections| {
2532 selections.select_anchors(other_selections);
2533 });
2534 }
2535 _ => {}
2536 });
2537
2538 let this_subscription =
2539 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2540 EditorEvent::SelectionsChanged { local: true } => {
2541 let these_selections = this.selections.disjoint.to_vec();
2542 if these_selections.is_empty() {
2543 return;
2544 }
2545 other.update(cx, |other_editor, cx| {
2546 other_editor.selections.change_with(cx, |selections| {
2547 selections.select_anchors(these_selections);
2548 })
2549 });
2550 }
2551 _ => {}
2552 });
2553
2554 Subscription::join(other_subscription, this_subscription)
2555 }
2556
2557 pub fn change_selections<R>(
2558 &mut self,
2559 autoscroll: Option<Autoscroll>,
2560 window: &mut Window,
2561 cx: &mut Context<Self>,
2562 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2563 ) -> R {
2564 self.change_selections_inner(autoscroll, true, window, cx, change)
2565 }
2566
2567 fn change_selections_inner<R>(
2568 &mut self,
2569 autoscroll: Option<Autoscroll>,
2570 request_completions: bool,
2571 window: &mut Window,
2572 cx: &mut Context<Self>,
2573 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2574 ) -> R {
2575 let old_cursor_position = self.selections.newest_anchor().head();
2576 self.push_to_selection_history();
2577
2578 let (changed, result) = self.selections.change_with(cx, change);
2579
2580 if changed {
2581 if let Some(autoscroll) = autoscroll {
2582 self.request_autoscroll(autoscroll, cx);
2583 }
2584 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2585
2586 if self.should_open_signature_help_automatically(
2587 &old_cursor_position,
2588 self.signature_help_state.backspace_pressed(),
2589 cx,
2590 ) {
2591 self.show_signature_help(&ShowSignatureHelp, window, cx);
2592 }
2593 self.signature_help_state.set_backspace_pressed(false);
2594 }
2595
2596 result
2597 }
2598
2599 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2600 where
2601 I: IntoIterator<Item = (Range<S>, T)>,
2602 S: ToOffset,
2603 T: Into<Arc<str>>,
2604 {
2605 if self.read_only(cx) {
2606 return;
2607 }
2608
2609 self.buffer
2610 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2611 }
2612
2613 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2614 where
2615 I: IntoIterator<Item = (Range<S>, T)>,
2616 S: ToOffset,
2617 T: Into<Arc<str>>,
2618 {
2619 if self.read_only(cx) {
2620 return;
2621 }
2622
2623 self.buffer.update(cx, |buffer, cx| {
2624 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2625 });
2626 }
2627
2628 pub fn edit_with_block_indent<I, S, T>(
2629 &mut self,
2630 edits: I,
2631 original_indent_columns: Vec<Option<u32>>,
2632 cx: &mut Context<Self>,
2633 ) where
2634 I: IntoIterator<Item = (Range<S>, T)>,
2635 S: ToOffset,
2636 T: Into<Arc<str>>,
2637 {
2638 if self.read_only(cx) {
2639 return;
2640 }
2641
2642 self.buffer.update(cx, |buffer, cx| {
2643 buffer.edit(
2644 edits,
2645 Some(AutoindentMode::Block {
2646 original_indent_columns,
2647 }),
2648 cx,
2649 )
2650 });
2651 }
2652
2653 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2654 self.hide_context_menu(window, cx);
2655
2656 match phase {
2657 SelectPhase::Begin {
2658 position,
2659 add,
2660 click_count,
2661 } => self.begin_selection(position, add, click_count, window, cx),
2662 SelectPhase::BeginColumnar {
2663 position,
2664 goal_column,
2665 reset,
2666 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2667 SelectPhase::Extend {
2668 position,
2669 click_count,
2670 } => self.extend_selection(position, click_count, window, cx),
2671 SelectPhase::Update {
2672 position,
2673 goal_column,
2674 scroll_delta,
2675 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2676 SelectPhase::End => self.end_selection(window, cx),
2677 }
2678 }
2679
2680 fn extend_selection(
2681 &mut self,
2682 position: DisplayPoint,
2683 click_count: usize,
2684 window: &mut Window,
2685 cx: &mut Context<Self>,
2686 ) {
2687 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2688 let tail = self.selections.newest::<usize>(cx).tail();
2689 self.begin_selection(position, false, click_count, window, cx);
2690
2691 let position = position.to_offset(&display_map, Bias::Left);
2692 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2693
2694 let mut pending_selection = self
2695 .selections
2696 .pending_anchor()
2697 .expect("extend_selection not called with pending selection");
2698 if position >= tail {
2699 pending_selection.start = tail_anchor;
2700 } else {
2701 pending_selection.end = tail_anchor;
2702 pending_selection.reversed = true;
2703 }
2704
2705 let mut pending_mode = self.selections.pending_mode().unwrap();
2706 match &mut pending_mode {
2707 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2708 _ => {}
2709 }
2710
2711 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2712 s.set_pending(pending_selection, pending_mode)
2713 });
2714 }
2715
2716 fn begin_selection(
2717 &mut self,
2718 position: DisplayPoint,
2719 add: bool,
2720 click_count: usize,
2721 window: &mut Window,
2722 cx: &mut Context<Self>,
2723 ) {
2724 if !self.focus_handle.is_focused(window) {
2725 self.last_focused_descendant = None;
2726 window.focus(&self.focus_handle);
2727 }
2728
2729 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2730 let buffer = &display_map.buffer_snapshot;
2731 let newest_selection = self.selections.newest_anchor().clone();
2732 let position = display_map.clip_point(position, Bias::Left);
2733
2734 let start;
2735 let end;
2736 let mode;
2737 let mut auto_scroll;
2738 match click_count {
2739 1 => {
2740 start = buffer.anchor_before(position.to_point(&display_map));
2741 end = start;
2742 mode = SelectMode::Character;
2743 auto_scroll = true;
2744 }
2745 2 => {
2746 let range = movement::surrounding_word(&display_map, position);
2747 start = buffer.anchor_before(range.start.to_point(&display_map));
2748 end = buffer.anchor_before(range.end.to_point(&display_map));
2749 mode = SelectMode::Word(start..end);
2750 auto_scroll = true;
2751 }
2752 3 => {
2753 let position = display_map
2754 .clip_point(position, Bias::Left)
2755 .to_point(&display_map);
2756 let line_start = display_map.prev_line_boundary(position).0;
2757 let next_line_start = buffer.clip_point(
2758 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2759 Bias::Left,
2760 );
2761 start = buffer.anchor_before(line_start);
2762 end = buffer.anchor_before(next_line_start);
2763 mode = SelectMode::Line(start..end);
2764 auto_scroll = true;
2765 }
2766 _ => {
2767 start = buffer.anchor_before(0);
2768 end = buffer.anchor_before(buffer.len());
2769 mode = SelectMode::All;
2770 auto_scroll = false;
2771 }
2772 }
2773 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2774
2775 let point_to_delete: Option<usize> = {
2776 let selected_points: Vec<Selection<Point>> =
2777 self.selections.disjoint_in_range(start..end, cx);
2778
2779 if !add || click_count > 1 {
2780 None
2781 } else if !selected_points.is_empty() {
2782 Some(selected_points[0].id)
2783 } else {
2784 let clicked_point_already_selected =
2785 self.selections.disjoint.iter().find(|selection| {
2786 selection.start.to_point(buffer) == start.to_point(buffer)
2787 || selection.end.to_point(buffer) == end.to_point(buffer)
2788 });
2789
2790 clicked_point_already_selected.map(|selection| selection.id)
2791 }
2792 };
2793
2794 let selections_count = self.selections.count();
2795
2796 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2797 if let Some(point_to_delete) = point_to_delete {
2798 s.delete(point_to_delete);
2799
2800 if selections_count == 1 {
2801 s.set_pending_anchor_range(start..end, mode);
2802 }
2803 } else {
2804 if !add {
2805 s.clear_disjoint();
2806 } else if click_count > 1 {
2807 s.delete(newest_selection.id)
2808 }
2809
2810 s.set_pending_anchor_range(start..end, mode);
2811 }
2812 });
2813 }
2814
2815 fn begin_columnar_selection(
2816 &mut self,
2817 position: DisplayPoint,
2818 goal_column: u32,
2819 reset: bool,
2820 window: &mut Window,
2821 cx: &mut Context<Self>,
2822 ) {
2823 if !self.focus_handle.is_focused(window) {
2824 self.last_focused_descendant = None;
2825 window.focus(&self.focus_handle);
2826 }
2827
2828 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2829
2830 if reset {
2831 let pointer_position = display_map
2832 .buffer_snapshot
2833 .anchor_before(position.to_point(&display_map));
2834
2835 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2836 s.clear_disjoint();
2837 s.set_pending_anchor_range(
2838 pointer_position..pointer_position,
2839 SelectMode::Character,
2840 );
2841 });
2842 }
2843
2844 let tail = self.selections.newest::<Point>(cx).tail();
2845 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2846
2847 if !reset {
2848 self.select_columns(
2849 tail.to_display_point(&display_map),
2850 position,
2851 goal_column,
2852 &display_map,
2853 window,
2854 cx,
2855 );
2856 }
2857 }
2858
2859 fn update_selection(
2860 &mut self,
2861 position: DisplayPoint,
2862 goal_column: u32,
2863 scroll_delta: gpui::Point<f32>,
2864 window: &mut Window,
2865 cx: &mut Context<Self>,
2866 ) {
2867 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2868
2869 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2870 let tail = tail.to_display_point(&display_map);
2871 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2872 } else if let Some(mut pending) = self.selections.pending_anchor() {
2873 let buffer = self.buffer.read(cx).snapshot(cx);
2874 let head;
2875 let tail;
2876 let mode = self.selections.pending_mode().unwrap();
2877 match &mode {
2878 SelectMode::Character => {
2879 head = position.to_point(&display_map);
2880 tail = pending.tail().to_point(&buffer);
2881 }
2882 SelectMode::Word(original_range) => {
2883 let original_display_range = original_range.start.to_display_point(&display_map)
2884 ..original_range.end.to_display_point(&display_map);
2885 let original_buffer_range = original_display_range.start.to_point(&display_map)
2886 ..original_display_range.end.to_point(&display_map);
2887 if movement::is_inside_word(&display_map, position)
2888 || original_display_range.contains(&position)
2889 {
2890 let word_range = movement::surrounding_word(&display_map, position);
2891 if word_range.start < original_display_range.start {
2892 head = word_range.start.to_point(&display_map);
2893 } else {
2894 head = word_range.end.to_point(&display_map);
2895 }
2896 } else {
2897 head = position.to_point(&display_map);
2898 }
2899
2900 if head <= original_buffer_range.start {
2901 tail = original_buffer_range.end;
2902 } else {
2903 tail = original_buffer_range.start;
2904 }
2905 }
2906 SelectMode::Line(original_range) => {
2907 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2908
2909 let position = display_map
2910 .clip_point(position, Bias::Left)
2911 .to_point(&display_map);
2912 let line_start = display_map.prev_line_boundary(position).0;
2913 let next_line_start = buffer.clip_point(
2914 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2915 Bias::Left,
2916 );
2917
2918 if line_start < original_range.start {
2919 head = line_start
2920 } else {
2921 head = next_line_start
2922 }
2923
2924 if head <= original_range.start {
2925 tail = original_range.end;
2926 } else {
2927 tail = original_range.start;
2928 }
2929 }
2930 SelectMode::All => {
2931 return;
2932 }
2933 };
2934
2935 if head < tail {
2936 pending.start = buffer.anchor_before(head);
2937 pending.end = buffer.anchor_before(tail);
2938 pending.reversed = true;
2939 } else {
2940 pending.start = buffer.anchor_before(tail);
2941 pending.end = buffer.anchor_before(head);
2942 pending.reversed = false;
2943 }
2944
2945 self.change_selections(None, window, cx, |s| {
2946 s.set_pending(pending, mode);
2947 });
2948 } else {
2949 log::error!("update_selection dispatched with no pending selection");
2950 return;
2951 }
2952
2953 self.apply_scroll_delta(scroll_delta, window, cx);
2954 cx.notify();
2955 }
2956
2957 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2958 self.columnar_selection_tail.take();
2959 if self.selections.pending_anchor().is_some() {
2960 let selections = self.selections.all::<usize>(cx);
2961 self.change_selections(None, window, cx, |s| {
2962 s.select(selections);
2963 s.clear_pending();
2964 });
2965 }
2966 }
2967
2968 fn select_columns(
2969 &mut self,
2970 tail: DisplayPoint,
2971 head: DisplayPoint,
2972 goal_column: u32,
2973 display_map: &DisplaySnapshot,
2974 window: &mut Window,
2975 cx: &mut Context<Self>,
2976 ) {
2977 let start_row = cmp::min(tail.row(), head.row());
2978 let end_row = cmp::max(tail.row(), head.row());
2979 let start_column = cmp::min(tail.column(), goal_column);
2980 let end_column = cmp::max(tail.column(), goal_column);
2981 let reversed = start_column < tail.column();
2982
2983 let selection_ranges = (start_row.0..=end_row.0)
2984 .map(DisplayRow)
2985 .filter_map(|row| {
2986 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2987 let start = display_map
2988 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2989 .to_point(display_map);
2990 let end = display_map
2991 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2992 .to_point(display_map);
2993 if reversed {
2994 Some(end..start)
2995 } else {
2996 Some(start..end)
2997 }
2998 } else {
2999 None
3000 }
3001 })
3002 .collect::<Vec<_>>();
3003
3004 self.change_selections(None, window, cx, |s| {
3005 s.select_ranges(selection_ranges);
3006 });
3007 cx.notify();
3008 }
3009
3010 pub fn has_pending_nonempty_selection(&self) -> bool {
3011 let pending_nonempty_selection = match self.selections.pending_anchor() {
3012 Some(Selection { start, end, .. }) => start != end,
3013 None => false,
3014 };
3015
3016 pending_nonempty_selection
3017 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3018 }
3019
3020 pub fn has_pending_selection(&self) -> bool {
3021 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3022 }
3023
3024 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3025 self.selection_mark_mode = false;
3026
3027 if self.clear_expanded_diff_hunks(cx) {
3028 cx.notify();
3029 return;
3030 }
3031 if self.dismiss_menus_and_popups(true, window, cx) {
3032 return;
3033 }
3034
3035 if self.mode.is_full()
3036 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3037 {
3038 return;
3039 }
3040
3041 cx.propagate();
3042 }
3043
3044 pub fn dismiss_menus_and_popups(
3045 &mut self,
3046 is_user_requested: bool,
3047 window: &mut Window,
3048 cx: &mut Context<Self>,
3049 ) -> bool {
3050 if self.take_rename(false, window, cx).is_some() {
3051 return true;
3052 }
3053
3054 if hide_hover(self, cx) {
3055 return true;
3056 }
3057
3058 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3059 return true;
3060 }
3061
3062 if self.hide_context_menu(window, cx).is_some() {
3063 return true;
3064 }
3065
3066 if self.mouse_context_menu.take().is_some() {
3067 return true;
3068 }
3069
3070 if is_user_requested && self.discard_inline_completion(true, cx) {
3071 return true;
3072 }
3073
3074 if self.snippet_stack.pop().is_some() {
3075 return true;
3076 }
3077
3078 if self.mode.is_full() && self.active_diagnostics.is_some() {
3079 self.dismiss_diagnostics(cx);
3080 return true;
3081 }
3082
3083 false
3084 }
3085
3086 fn linked_editing_ranges_for(
3087 &self,
3088 selection: Range<text::Anchor>,
3089 cx: &App,
3090 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3091 if self.linked_edit_ranges.is_empty() {
3092 return None;
3093 }
3094 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3095 selection.end.buffer_id.and_then(|end_buffer_id| {
3096 if selection.start.buffer_id != Some(end_buffer_id) {
3097 return None;
3098 }
3099 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3100 let snapshot = buffer.read(cx).snapshot();
3101 self.linked_edit_ranges
3102 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3103 .map(|ranges| (ranges, snapshot, buffer))
3104 })?;
3105 use text::ToOffset as TO;
3106 // find offset from the start of current range to current cursor position
3107 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3108
3109 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3110 let start_difference = start_offset - start_byte_offset;
3111 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3112 let end_difference = end_offset - start_byte_offset;
3113 // Current range has associated linked ranges.
3114 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3115 for range in linked_ranges.iter() {
3116 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3117 let end_offset = start_offset + end_difference;
3118 let start_offset = start_offset + start_difference;
3119 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3120 continue;
3121 }
3122 if self.selections.disjoint_anchor_ranges().any(|s| {
3123 if s.start.buffer_id != selection.start.buffer_id
3124 || s.end.buffer_id != selection.end.buffer_id
3125 {
3126 return false;
3127 }
3128 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3129 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3130 }) {
3131 continue;
3132 }
3133 let start = buffer_snapshot.anchor_after(start_offset);
3134 let end = buffer_snapshot.anchor_after(end_offset);
3135 linked_edits
3136 .entry(buffer.clone())
3137 .or_default()
3138 .push(start..end);
3139 }
3140 Some(linked_edits)
3141 }
3142
3143 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3144 let text: Arc<str> = text.into();
3145
3146 if self.read_only(cx) {
3147 return;
3148 }
3149
3150 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3151
3152 let selections = self.selections.all_adjusted(cx);
3153 let mut bracket_inserted = false;
3154 let mut edits = Vec::new();
3155 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3156 let mut new_selections = Vec::with_capacity(selections.len());
3157 let mut new_autoclose_regions = Vec::new();
3158 let snapshot = self.buffer.read(cx).read(cx);
3159 let mut clear_linked_edit_ranges = false;
3160
3161 for (selection, autoclose_region) in
3162 self.selections_with_autoclose_regions(selections, &snapshot)
3163 {
3164 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3165 // Determine if the inserted text matches the opening or closing
3166 // bracket of any of this language's bracket pairs.
3167 let mut bracket_pair = None;
3168 let mut is_bracket_pair_start = false;
3169 let mut is_bracket_pair_end = false;
3170 if !text.is_empty() {
3171 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3172 // and they are removing the character that triggered IME popup.
3173 for (pair, enabled) in scope.brackets() {
3174 if !pair.close && !pair.surround {
3175 continue;
3176 }
3177
3178 if enabled && pair.start.ends_with(text.as_ref()) {
3179 let prefix_len = pair.start.len() - text.len();
3180 let preceding_text_matches_prefix = prefix_len == 0
3181 || (selection.start.column >= (prefix_len as u32)
3182 && snapshot.contains_str_at(
3183 Point::new(
3184 selection.start.row,
3185 selection.start.column - (prefix_len as u32),
3186 ),
3187 &pair.start[..prefix_len],
3188 ));
3189 if preceding_text_matches_prefix {
3190 bracket_pair = Some(pair.clone());
3191 is_bracket_pair_start = true;
3192 break;
3193 }
3194 }
3195 if pair.end.as_str() == text.as_ref() {
3196 bracket_pair = Some(pair.clone());
3197 is_bracket_pair_end = true;
3198 break;
3199 }
3200 }
3201 }
3202
3203 if let Some(bracket_pair) = bracket_pair {
3204 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3205 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3206 let auto_surround =
3207 self.use_auto_surround && snapshot_settings.use_auto_surround;
3208 if selection.is_empty() {
3209 if is_bracket_pair_start {
3210 // If the inserted text is a suffix of an opening bracket and the
3211 // selection is preceded by the rest of the opening bracket, then
3212 // insert the closing bracket.
3213 let following_text_allows_autoclose = snapshot
3214 .chars_at(selection.start)
3215 .next()
3216 .map_or(true, |c| scope.should_autoclose_before(c));
3217
3218 let preceding_text_allows_autoclose = selection.start.column == 0
3219 || snapshot.reversed_chars_at(selection.start).next().map_or(
3220 true,
3221 |c| {
3222 bracket_pair.start != bracket_pair.end
3223 || !snapshot
3224 .char_classifier_at(selection.start)
3225 .is_word(c)
3226 },
3227 );
3228
3229 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3230 && bracket_pair.start.len() == 1
3231 {
3232 let target = bracket_pair.start.chars().next().unwrap();
3233 let current_line_count = snapshot
3234 .reversed_chars_at(selection.start)
3235 .take_while(|&c| c != '\n')
3236 .filter(|&c| c == target)
3237 .count();
3238 current_line_count % 2 == 1
3239 } else {
3240 false
3241 };
3242
3243 if autoclose
3244 && bracket_pair.close
3245 && following_text_allows_autoclose
3246 && preceding_text_allows_autoclose
3247 && !is_closing_quote
3248 {
3249 let anchor = snapshot.anchor_before(selection.end);
3250 new_selections.push((selection.map(|_| anchor), text.len()));
3251 new_autoclose_regions.push((
3252 anchor,
3253 text.len(),
3254 selection.id,
3255 bracket_pair.clone(),
3256 ));
3257 edits.push((
3258 selection.range(),
3259 format!("{}{}", text, bracket_pair.end).into(),
3260 ));
3261 bracket_inserted = true;
3262 continue;
3263 }
3264 }
3265
3266 if let Some(region) = autoclose_region {
3267 // If the selection is followed by an auto-inserted closing bracket,
3268 // then don't insert that closing bracket again; just move the selection
3269 // past the closing bracket.
3270 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3271 && text.as_ref() == region.pair.end.as_str();
3272 if should_skip {
3273 let anchor = snapshot.anchor_after(selection.end);
3274 new_selections
3275 .push((selection.map(|_| anchor), region.pair.end.len()));
3276 continue;
3277 }
3278 }
3279
3280 let always_treat_brackets_as_autoclosed = snapshot
3281 .language_settings_at(selection.start, cx)
3282 .always_treat_brackets_as_autoclosed;
3283 if always_treat_brackets_as_autoclosed
3284 && is_bracket_pair_end
3285 && snapshot.contains_str_at(selection.end, text.as_ref())
3286 {
3287 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3288 // and the inserted text is a closing bracket and the selection is followed
3289 // by the closing bracket then move the selection past the closing bracket.
3290 let anchor = snapshot.anchor_after(selection.end);
3291 new_selections.push((selection.map(|_| anchor), text.len()));
3292 continue;
3293 }
3294 }
3295 // If an opening bracket is 1 character long and is typed while
3296 // text is selected, then surround that text with the bracket pair.
3297 else if auto_surround
3298 && bracket_pair.surround
3299 && is_bracket_pair_start
3300 && bracket_pair.start.chars().count() == 1
3301 {
3302 edits.push((selection.start..selection.start, text.clone()));
3303 edits.push((
3304 selection.end..selection.end,
3305 bracket_pair.end.as_str().into(),
3306 ));
3307 bracket_inserted = true;
3308 new_selections.push((
3309 Selection {
3310 id: selection.id,
3311 start: snapshot.anchor_after(selection.start),
3312 end: snapshot.anchor_before(selection.end),
3313 reversed: selection.reversed,
3314 goal: selection.goal,
3315 },
3316 0,
3317 ));
3318 continue;
3319 }
3320 }
3321 }
3322
3323 if self.auto_replace_emoji_shortcode
3324 && selection.is_empty()
3325 && text.as_ref().ends_with(':')
3326 {
3327 if let Some(possible_emoji_short_code) =
3328 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3329 {
3330 if !possible_emoji_short_code.is_empty() {
3331 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3332 let emoji_shortcode_start = Point::new(
3333 selection.start.row,
3334 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3335 );
3336
3337 // Remove shortcode from buffer
3338 edits.push((
3339 emoji_shortcode_start..selection.start,
3340 "".to_string().into(),
3341 ));
3342 new_selections.push((
3343 Selection {
3344 id: selection.id,
3345 start: snapshot.anchor_after(emoji_shortcode_start),
3346 end: snapshot.anchor_before(selection.start),
3347 reversed: selection.reversed,
3348 goal: selection.goal,
3349 },
3350 0,
3351 ));
3352
3353 // Insert emoji
3354 let selection_start_anchor = snapshot.anchor_after(selection.start);
3355 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3356 edits.push((selection.start..selection.end, emoji.to_string().into()));
3357
3358 continue;
3359 }
3360 }
3361 }
3362 }
3363
3364 // If not handling any auto-close operation, then just replace the selected
3365 // text with the given input and move the selection to the end of the
3366 // newly inserted text.
3367 let anchor = snapshot.anchor_after(selection.end);
3368 if !self.linked_edit_ranges.is_empty() {
3369 let start_anchor = snapshot.anchor_before(selection.start);
3370
3371 let is_word_char = text.chars().next().map_or(true, |char| {
3372 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3373 classifier.is_word(char)
3374 });
3375
3376 if is_word_char {
3377 if let Some(ranges) = self
3378 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3379 {
3380 for (buffer, edits) in ranges {
3381 linked_edits
3382 .entry(buffer.clone())
3383 .or_default()
3384 .extend(edits.into_iter().map(|range| (range, text.clone())));
3385 }
3386 }
3387 } else {
3388 clear_linked_edit_ranges = true;
3389 }
3390 }
3391
3392 new_selections.push((selection.map(|_| anchor), 0));
3393 edits.push((selection.start..selection.end, text.clone()));
3394 }
3395
3396 drop(snapshot);
3397
3398 self.transact(window, cx, |this, window, cx| {
3399 if clear_linked_edit_ranges {
3400 this.linked_edit_ranges.clear();
3401 }
3402 let initial_buffer_versions =
3403 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3404
3405 this.buffer.update(cx, |buffer, cx| {
3406 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3407 });
3408 for (buffer, edits) in linked_edits {
3409 buffer.update(cx, |buffer, cx| {
3410 let snapshot = buffer.snapshot();
3411 let edits = edits
3412 .into_iter()
3413 .map(|(range, text)| {
3414 use text::ToPoint as TP;
3415 let end_point = TP::to_point(&range.end, &snapshot);
3416 let start_point = TP::to_point(&range.start, &snapshot);
3417 (start_point..end_point, text)
3418 })
3419 .sorted_by_key(|(range, _)| range.start);
3420 buffer.edit(edits, None, cx);
3421 })
3422 }
3423 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3424 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3425 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3426 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3427 .zip(new_selection_deltas)
3428 .map(|(selection, delta)| Selection {
3429 id: selection.id,
3430 start: selection.start + delta,
3431 end: selection.end + delta,
3432 reversed: selection.reversed,
3433 goal: SelectionGoal::None,
3434 })
3435 .collect::<Vec<_>>();
3436
3437 let mut i = 0;
3438 for (position, delta, selection_id, pair) in new_autoclose_regions {
3439 let position = position.to_offset(&map.buffer_snapshot) + delta;
3440 let start = map.buffer_snapshot.anchor_before(position);
3441 let end = map.buffer_snapshot.anchor_after(position);
3442 while let Some(existing_state) = this.autoclose_regions.get(i) {
3443 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3444 Ordering::Less => i += 1,
3445 Ordering::Greater => break,
3446 Ordering::Equal => {
3447 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3448 Ordering::Less => i += 1,
3449 Ordering::Equal => break,
3450 Ordering::Greater => break,
3451 }
3452 }
3453 }
3454 }
3455 this.autoclose_regions.insert(
3456 i,
3457 AutocloseRegion {
3458 selection_id,
3459 range: start..end,
3460 pair,
3461 },
3462 );
3463 }
3464
3465 let had_active_inline_completion = this.has_active_inline_completion();
3466 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3467 s.select(new_selections)
3468 });
3469
3470 if !bracket_inserted {
3471 if let Some(on_type_format_task) =
3472 this.trigger_on_type_formatting(text.to_string(), window, cx)
3473 {
3474 on_type_format_task.detach_and_log_err(cx);
3475 }
3476 }
3477
3478 let editor_settings = EditorSettings::get_global(cx);
3479 if bracket_inserted
3480 && (editor_settings.auto_signature_help
3481 || editor_settings.show_signature_help_after_edits)
3482 {
3483 this.show_signature_help(&ShowSignatureHelp, window, cx);
3484 }
3485
3486 let trigger_in_words =
3487 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3488 if this.hard_wrap.is_some() {
3489 let latest: Range<Point> = this.selections.newest(cx).range();
3490 if latest.is_empty()
3491 && this
3492 .buffer()
3493 .read(cx)
3494 .snapshot(cx)
3495 .line_len(MultiBufferRow(latest.start.row))
3496 == latest.start.column
3497 {
3498 this.rewrap_impl(
3499 RewrapOptions {
3500 override_language_settings: true,
3501 preserve_existing_whitespace: true,
3502 },
3503 cx,
3504 )
3505 }
3506 }
3507 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3508 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3509 this.refresh_inline_completion(true, false, window, cx);
3510 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3511 });
3512 }
3513
3514 fn find_possible_emoji_shortcode_at_position(
3515 snapshot: &MultiBufferSnapshot,
3516 position: Point,
3517 ) -> Option<String> {
3518 let mut chars = Vec::new();
3519 let mut found_colon = false;
3520 for char in snapshot.reversed_chars_at(position).take(100) {
3521 // Found a possible emoji shortcode in the middle of the buffer
3522 if found_colon {
3523 if char.is_whitespace() {
3524 chars.reverse();
3525 return Some(chars.iter().collect());
3526 }
3527 // If the previous character is not a whitespace, we are in the middle of a word
3528 // and we only want to complete the shortcode if the word is made up of other emojis
3529 let mut containing_word = String::new();
3530 for ch in snapshot
3531 .reversed_chars_at(position)
3532 .skip(chars.len() + 1)
3533 .take(100)
3534 {
3535 if ch.is_whitespace() {
3536 break;
3537 }
3538 containing_word.push(ch);
3539 }
3540 let containing_word = containing_word.chars().rev().collect::<String>();
3541 if util::word_consists_of_emojis(containing_word.as_str()) {
3542 chars.reverse();
3543 return Some(chars.iter().collect());
3544 }
3545 }
3546
3547 if char.is_whitespace() || !char.is_ascii() {
3548 return None;
3549 }
3550 if char == ':' {
3551 found_colon = true;
3552 } else {
3553 chars.push(char);
3554 }
3555 }
3556 // Found a possible emoji shortcode at the beginning of the buffer
3557 chars.reverse();
3558 Some(chars.iter().collect())
3559 }
3560
3561 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3562 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3563 self.transact(window, cx, |this, window, cx| {
3564 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3565 let selections = this.selections.all::<usize>(cx);
3566 let multi_buffer = this.buffer.read(cx);
3567 let buffer = multi_buffer.snapshot(cx);
3568 selections
3569 .iter()
3570 .map(|selection| {
3571 let start_point = selection.start.to_point(&buffer);
3572 let mut indent =
3573 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3574 indent.len = cmp::min(indent.len, start_point.column);
3575 let start = selection.start;
3576 let end = selection.end;
3577 let selection_is_empty = start == end;
3578 let language_scope = buffer.language_scope_at(start);
3579 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3580 &language_scope
3581 {
3582 let insert_extra_newline =
3583 insert_extra_newline_brackets(&buffer, start..end, language)
3584 || insert_extra_newline_tree_sitter(&buffer, start..end);
3585
3586 // Comment extension on newline is allowed only for cursor selections
3587 let comment_delimiter = maybe!({
3588 if !selection_is_empty {
3589 return None;
3590 }
3591
3592 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3593 return None;
3594 }
3595
3596 let delimiters = language.line_comment_prefixes();
3597 let max_len_of_delimiter =
3598 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3599 let (snapshot, range) =
3600 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3601
3602 let mut index_of_first_non_whitespace = 0;
3603 let comment_candidate = snapshot
3604 .chars_for_range(range)
3605 .skip_while(|c| {
3606 let should_skip = c.is_whitespace();
3607 if should_skip {
3608 index_of_first_non_whitespace += 1;
3609 }
3610 should_skip
3611 })
3612 .take(max_len_of_delimiter)
3613 .collect::<String>();
3614 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3615 comment_candidate.starts_with(comment_prefix.as_ref())
3616 })?;
3617 let cursor_is_placed_after_comment_marker =
3618 index_of_first_non_whitespace + comment_prefix.len()
3619 <= start_point.column as usize;
3620 if cursor_is_placed_after_comment_marker {
3621 Some(comment_prefix.clone())
3622 } else {
3623 None
3624 }
3625 });
3626 (comment_delimiter, insert_extra_newline)
3627 } else {
3628 (None, false)
3629 };
3630
3631 let capacity_for_delimiter = comment_delimiter
3632 .as_deref()
3633 .map(str::len)
3634 .unwrap_or_default();
3635 let mut new_text =
3636 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3637 new_text.push('\n');
3638 new_text.extend(indent.chars());
3639 if let Some(delimiter) = &comment_delimiter {
3640 new_text.push_str(delimiter);
3641 }
3642 if insert_extra_newline {
3643 new_text = new_text.repeat(2);
3644 }
3645
3646 let anchor = buffer.anchor_after(end);
3647 let new_selection = selection.map(|_| anchor);
3648 (
3649 (start..end, new_text),
3650 (insert_extra_newline, new_selection),
3651 )
3652 })
3653 .unzip()
3654 };
3655
3656 this.edit_with_autoindent(edits, cx);
3657 let buffer = this.buffer.read(cx).snapshot(cx);
3658 let new_selections = selection_fixup_info
3659 .into_iter()
3660 .map(|(extra_newline_inserted, new_selection)| {
3661 let mut cursor = new_selection.end.to_point(&buffer);
3662 if extra_newline_inserted {
3663 cursor.row -= 1;
3664 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3665 }
3666 new_selection.map(|_| cursor)
3667 })
3668 .collect();
3669
3670 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3671 s.select(new_selections)
3672 });
3673 this.refresh_inline_completion(true, false, window, cx);
3674 });
3675 }
3676
3677 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3678 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3679
3680 let buffer = self.buffer.read(cx);
3681 let snapshot = buffer.snapshot(cx);
3682
3683 let mut edits = Vec::new();
3684 let mut rows = Vec::new();
3685
3686 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3687 let cursor = selection.head();
3688 let row = cursor.row;
3689
3690 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3691
3692 let newline = "\n".to_string();
3693 edits.push((start_of_line..start_of_line, newline));
3694
3695 rows.push(row + rows_inserted as u32);
3696 }
3697
3698 self.transact(window, cx, |editor, window, cx| {
3699 editor.edit(edits, cx);
3700
3701 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3702 let mut index = 0;
3703 s.move_cursors_with(|map, _, _| {
3704 let row = rows[index];
3705 index += 1;
3706
3707 let point = Point::new(row, 0);
3708 let boundary = map.next_line_boundary(point).1;
3709 let clipped = map.clip_point(boundary, Bias::Left);
3710
3711 (clipped, SelectionGoal::None)
3712 });
3713 });
3714
3715 let mut indent_edits = Vec::new();
3716 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3717 for row in rows {
3718 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3719 for (row, indent) in indents {
3720 if indent.len == 0 {
3721 continue;
3722 }
3723
3724 let text = match indent.kind {
3725 IndentKind::Space => " ".repeat(indent.len as usize),
3726 IndentKind::Tab => "\t".repeat(indent.len as usize),
3727 };
3728 let point = Point::new(row.0, 0);
3729 indent_edits.push((point..point, text));
3730 }
3731 }
3732 editor.edit(indent_edits, cx);
3733 });
3734 }
3735
3736 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3737 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3738
3739 let buffer = self.buffer.read(cx);
3740 let snapshot = buffer.snapshot(cx);
3741
3742 let mut edits = Vec::new();
3743 let mut rows = Vec::new();
3744 let mut rows_inserted = 0;
3745
3746 for selection in self.selections.all_adjusted(cx) {
3747 let cursor = selection.head();
3748 let row = cursor.row;
3749
3750 let point = Point::new(row + 1, 0);
3751 let start_of_line = snapshot.clip_point(point, Bias::Left);
3752
3753 let newline = "\n".to_string();
3754 edits.push((start_of_line..start_of_line, newline));
3755
3756 rows_inserted += 1;
3757 rows.push(row + rows_inserted);
3758 }
3759
3760 self.transact(window, cx, |editor, window, cx| {
3761 editor.edit(edits, cx);
3762
3763 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3764 let mut index = 0;
3765 s.move_cursors_with(|map, _, _| {
3766 let row = rows[index];
3767 index += 1;
3768
3769 let point = Point::new(row, 0);
3770 let boundary = map.next_line_boundary(point).1;
3771 let clipped = map.clip_point(boundary, Bias::Left);
3772
3773 (clipped, SelectionGoal::None)
3774 });
3775 });
3776
3777 let mut indent_edits = Vec::new();
3778 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3779 for row in rows {
3780 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3781 for (row, indent) in indents {
3782 if indent.len == 0 {
3783 continue;
3784 }
3785
3786 let text = match indent.kind {
3787 IndentKind::Space => " ".repeat(indent.len as usize),
3788 IndentKind::Tab => "\t".repeat(indent.len as usize),
3789 };
3790 let point = Point::new(row.0, 0);
3791 indent_edits.push((point..point, text));
3792 }
3793 }
3794 editor.edit(indent_edits, cx);
3795 });
3796 }
3797
3798 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3799 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3800 original_indent_columns: Vec::new(),
3801 });
3802 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3803 }
3804
3805 fn insert_with_autoindent_mode(
3806 &mut self,
3807 text: &str,
3808 autoindent_mode: Option<AutoindentMode>,
3809 window: &mut Window,
3810 cx: &mut Context<Self>,
3811 ) {
3812 if self.read_only(cx) {
3813 return;
3814 }
3815
3816 let text: Arc<str> = text.into();
3817 self.transact(window, cx, |this, window, cx| {
3818 let old_selections = this.selections.all_adjusted(cx);
3819 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3820 let anchors = {
3821 let snapshot = buffer.read(cx);
3822 old_selections
3823 .iter()
3824 .map(|s| {
3825 let anchor = snapshot.anchor_after(s.head());
3826 s.map(|_| anchor)
3827 })
3828 .collect::<Vec<_>>()
3829 };
3830 buffer.edit(
3831 old_selections
3832 .iter()
3833 .map(|s| (s.start..s.end, text.clone())),
3834 autoindent_mode,
3835 cx,
3836 );
3837 anchors
3838 });
3839
3840 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3841 s.select_anchors(selection_anchors);
3842 });
3843
3844 cx.notify();
3845 });
3846 }
3847
3848 fn trigger_completion_on_input(
3849 &mut self,
3850 text: &str,
3851 trigger_in_words: bool,
3852 window: &mut Window,
3853 cx: &mut Context<Self>,
3854 ) {
3855 let ignore_completion_provider = self
3856 .context_menu
3857 .borrow()
3858 .as_ref()
3859 .map(|menu| match menu {
3860 CodeContextMenu::Completions(completions_menu) => {
3861 completions_menu.ignore_completion_provider
3862 }
3863 CodeContextMenu::CodeActions(_) => false,
3864 })
3865 .unwrap_or(false);
3866
3867 if ignore_completion_provider {
3868 self.show_word_completions(&ShowWordCompletions, window, cx);
3869 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3870 self.show_completions(
3871 &ShowCompletions {
3872 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3873 },
3874 window,
3875 cx,
3876 );
3877 } else {
3878 self.hide_context_menu(window, cx);
3879 }
3880 }
3881
3882 fn is_completion_trigger(
3883 &self,
3884 text: &str,
3885 trigger_in_words: bool,
3886 cx: &mut Context<Self>,
3887 ) -> bool {
3888 let position = self.selections.newest_anchor().head();
3889 let multibuffer = self.buffer.read(cx);
3890 let Some(buffer) = position
3891 .buffer_id
3892 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3893 else {
3894 return false;
3895 };
3896
3897 if let Some(completion_provider) = &self.completion_provider {
3898 completion_provider.is_completion_trigger(
3899 &buffer,
3900 position.text_anchor,
3901 text,
3902 trigger_in_words,
3903 cx,
3904 )
3905 } else {
3906 false
3907 }
3908 }
3909
3910 /// If any empty selections is touching the start of its innermost containing autoclose
3911 /// region, expand it to select the brackets.
3912 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3913 let selections = self.selections.all::<usize>(cx);
3914 let buffer = self.buffer.read(cx).read(cx);
3915 let new_selections = self
3916 .selections_with_autoclose_regions(selections, &buffer)
3917 .map(|(mut selection, region)| {
3918 if !selection.is_empty() {
3919 return selection;
3920 }
3921
3922 if let Some(region) = region {
3923 let mut range = region.range.to_offset(&buffer);
3924 if selection.start == range.start && range.start >= region.pair.start.len() {
3925 range.start -= region.pair.start.len();
3926 if buffer.contains_str_at(range.start, ®ion.pair.start)
3927 && buffer.contains_str_at(range.end, ®ion.pair.end)
3928 {
3929 range.end += region.pair.end.len();
3930 selection.start = range.start;
3931 selection.end = range.end;
3932
3933 return selection;
3934 }
3935 }
3936 }
3937
3938 let always_treat_brackets_as_autoclosed = buffer
3939 .language_settings_at(selection.start, cx)
3940 .always_treat_brackets_as_autoclosed;
3941
3942 if !always_treat_brackets_as_autoclosed {
3943 return selection;
3944 }
3945
3946 if let Some(scope) = buffer.language_scope_at(selection.start) {
3947 for (pair, enabled) in scope.brackets() {
3948 if !enabled || !pair.close {
3949 continue;
3950 }
3951
3952 if buffer.contains_str_at(selection.start, &pair.end) {
3953 let pair_start_len = pair.start.len();
3954 if buffer.contains_str_at(
3955 selection.start.saturating_sub(pair_start_len),
3956 &pair.start,
3957 ) {
3958 selection.start -= pair_start_len;
3959 selection.end += pair.end.len();
3960
3961 return selection;
3962 }
3963 }
3964 }
3965 }
3966
3967 selection
3968 })
3969 .collect();
3970
3971 drop(buffer);
3972 self.change_selections(None, window, cx, |selections| {
3973 selections.select(new_selections)
3974 });
3975 }
3976
3977 /// Iterate the given selections, and for each one, find the smallest surrounding
3978 /// autoclose region. This uses the ordering of the selections and the autoclose
3979 /// regions to avoid repeated comparisons.
3980 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3981 &'a self,
3982 selections: impl IntoIterator<Item = Selection<D>>,
3983 buffer: &'a MultiBufferSnapshot,
3984 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3985 let mut i = 0;
3986 let mut regions = self.autoclose_regions.as_slice();
3987 selections.into_iter().map(move |selection| {
3988 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3989
3990 let mut enclosing = None;
3991 while let Some(pair_state) = regions.get(i) {
3992 if pair_state.range.end.to_offset(buffer) < range.start {
3993 regions = ®ions[i + 1..];
3994 i = 0;
3995 } else if pair_state.range.start.to_offset(buffer) > range.end {
3996 break;
3997 } else {
3998 if pair_state.selection_id == selection.id {
3999 enclosing = Some(pair_state);
4000 }
4001 i += 1;
4002 }
4003 }
4004
4005 (selection, enclosing)
4006 })
4007 }
4008
4009 /// Remove any autoclose regions that no longer contain their selection.
4010 fn invalidate_autoclose_regions(
4011 &mut self,
4012 mut selections: &[Selection<Anchor>],
4013 buffer: &MultiBufferSnapshot,
4014 ) {
4015 self.autoclose_regions.retain(|state| {
4016 let mut i = 0;
4017 while let Some(selection) = selections.get(i) {
4018 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4019 selections = &selections[1..];
4020 continue;
4021 }
4022 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4023 break;
4024 }
4025 if selection.id == state.selection_id {
4026 return true;
4027 } else {
4028 i += 1;
4029 }
4030 }
4031 false
4032 });
4033 }
4034
4035 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4036 let offset = position.to_offset(buffer);
4037 let (word_range, kind) = buffer.surrounding_word(offset, true);
4038 if offset > word_range.start && kind == Some(CharKind::Word) {
4039 Some(
4040 buffer
4041 .text_for_range(word_range.start..offset)
4042 .collect::<String>(),
4043 )
4044 } else {
4045 None
4046 }
4047 }
4048
4049 pub fn toggle_inlay_hints(
4050 &mut self,
4051 _: &ToggleInlayHints,
4052 _: &mut Window,
4053 cx: &mut Context<Self>,
4054 ) {
4055 self.refresh_inlay_hints(
4056 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4057 cx,
4058 );
4059 }
4060
4061 pub fn inlay_hints_enabled(&self) -> bool {
4062 self.inlay_hint_cache.enabled
4063 }
4064
4065 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4066 if self.semantics_provider.is_none() || !self.mode.is_full() {
4067 return;
4068 }
4069
4070 let reason_description = reason.description();
4071 let ignore_debounce = matches!(
4072 reason,
4073 InlayHintRefreshReason::SettingsChange(_)
4074 | InlayHintRefreshReason::Toggle(_)
4075 | InlayHintRefreshReason::ExcerptsRemoved(_)
4076 | InlayHintRefreshReason::ModifiersChanged(_)
4077 );
4078 let (invalidate_cache, required_languages) = match reason {
4079 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4080 match self.inlay_hint_cache.modifiers_override(enabled) {
4081 Some(enabled) => {
4082 if enabled {
4083 (InvalidationStrategy::RefreshRequested, None)
4084 } else {
4085 self.splice_inlays(
4086 &self
4087 .visible_inlay_hints(cx)
4088 .iter()
4089 .map(|inlay| inlay.id)
4090 .collect::<Vec<InlayId>>(),
4091 Vec::new(),
4092 cx,
4093 );
4094 return;
4095 }
4096 }
4097 None => return,
4098 }
4099 }
4100 InlayHintRefreshReason::Toggle(enabled) => {
4101 if self.inlay_hint_cache.toggle(enabled) {
4102 if enabled {
4103 (InvalidationStrategy::RefreshRequested, None)
4104 } else {
4105 self.splice_inlays(
4106 &self
4107 .visible_inlay_hints(cx)
4108 .iter()
4109 .map(|inlay| inlay.id)
4110 .collect::<Vec<InlayId>>(),
4111 Vec::new(),
4112 cx,
4113 );
4114 return;
4115 }
4116 } else {
4117 return;
4118 }
4119 }
4120 InlayHintRefreshReason::SettingsChange(new_settings) => {
4121 match self.inlay_hint_cache.update_settings(
4122 &self.buffer,
4123 new_settings,
4124 self.visible_inlay_hints(cx),
4125 cx,
4126 ) {
4127 ControlFlow::Break(Some(InlaySplice {
4128 to_remove,
4129 to_insert,
4130 })) => {
4131 self.splice_inlays(&to_remove, to_insert, cx);
4132 return;
4133 }
4134 ControlFlow::Break(None) => return,
4135 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4136 }
4137 }
4138 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4139 if let Some(InlaySplice {
4140 to_remove,
4141 to_insert,
4142 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4143 {
4144 self.splice_inlays(&to_remove, to_insert, cx);
4145 }
4146 return;
4147 }
4148 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4149 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4150 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4151 }
4152 InlayHintRefreshReason::RefreshRequested => {
4153 (InvalidationStrategy::RefreshRequested, None)
4154 }
4155 };
4156
4157 if let Some(InlaySplice {
4158 to_remove,
4159 to_insert,
4160 }) = self.inlay_hint_cache.spawn_hint_refresh(
4161 reason_description,
4162 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4163 invalidate_cache,
4164 ignore_debounce,
4165 cx,
4166 ) {
4167 self.splice_inlays(&to_remove, to_insert, cx);
4168 }
4169 }
4170
4171 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4172 self.display_map
4173 .read(cx)
4174 .current_inlays()
4175 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4176 .cloned()
4177 .collect()
4178 }
4179
4180 pub fn excerpts_for_inlay_hints_query(
4181 &self,
4182 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4183 cx: &mut Context<Editor>,
4184 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4185 let Some(project) = self.project.as_ref() else {
4186 return HashMap::default();
4187 };
4188 let project = project.read(cx);
4189 let multi_buffer = self.buffer().read(cx);
4190 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4191 let multi_buffer_visible_start = self
4192 .scroll_manager
4193 .anchor()
4194 .anchor
4195 .to_point(&multi_buffer_snapshot);
4196 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4197 multi_buffer_visible_start
4198 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4199 Bias::Left,
4200 );
4201 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4202 multi_buffer_snapshot
4203 .range_to_buffer_ranges(multi_buffer_visible_range)
4204 .into_iter()
4205 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4206 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4207 let buffer_file = project::File::from_dyn(buffer.file())?;
4208 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4209 let worktree_entry = buffer_worktree
4210 .read(cx)
4211 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4212 if worktree_entry.is_ignored {
4213 return None;
4214 }
4215
4216 let language = buffer.language()?;
4217 if let Some(restrict_to_languages) = restrict_to_languages {
4218 if !restrict_to_languages.contains(language) {
4219 return None;
4220 }
4221 }
4222 Some((
4223 excerpt_id,
4224 (
4225 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4226 buffer.version().clone(),
4227 excerpt_visible_range,
4228 ),
4229 ))
4230 })
4231 .collect()
4232 }
4233
4234 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4235 TextLayoutDetails {
4236 text_system: window.text_system().clone(),
4237 editor_style: self.style.clone().unwrap(),
4238 rem_size: window.rem_size(),
4239 scroll_anchor: self.scroll_manager.anchor(),
4240 visible_rows: self.visible_line_count(),
4241 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4242 }
4243 }
4244
4245 pub fn splice_inlays(
4246 &self,
4247 to_remove: &[InlayId],
4248 to_insert: Vec<Inlay>,
4249 cx: &mut Context<Self>,
4250 ) {
4251 self.display_map.update(cx, |display_map, cx| {
4252 display_map.splice_inlays(to_remove, to_insert, cx)
4253 });
4254 cx.notify();
4255 }
4256
4257 fn trigger_on_type_formatting(
4258 &self,
4259 input: String,
4260 window: &mut Window,
4261 cx: &mut Context<Self>,
4262 ) -> Option<Task<Result<()>>> {
4263 if input.len() != 1 {
4264 return None;
4265 }
4266
4267 let project = self.project.as_ref()?;
4268 let position = self.selections.newest_anchor().head();
4269 let (buffer, buffer_position) = self
4270 .buffer
4271 .read(cx)
4272 .text_anchor_for_position(position, cx)?;
4273
4274 let settings = language_settings::language_settings(
4275 buffer
4276 .read(cx)
4277 .language_at(buffer_position)
4278 .map(|l| l.name()),
4279 buffer.read(cx).file(),
4280 cx,
4281 );
4282 if !settings.use_on_type_format {
4283 return None;
4284 }
4285
4286 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4287 // hence we do LSP request & edit on host side only — add formats to host's history.
4288 let push_to_lsp_host_history = true;
4289 // If this is not the host, append its history with new edits.
4290 let push_to_client_history = project.read(cx).is_via_collab();
4291
4292 let on_type_formatting = project.update(cx, |project, cx| {
4293 project.on_type_format(
4294 buffer.clone(),
4295 buffer_position,
4296 input,
4297 push_to_lsp_host_history,
4298 cx,
4299 )
4300 });
4301 Some(cx.spawn_in(window, async move |editor, cx| {
4302 if let Some(transaction) = on_type_formatting.await? {
4303 if push_to_client_history {
4304 buffer
4305 .update(cx, |buffer, _| {
4306 buffer.push_transaction(transaction, Instant::now());
4307 buffer.finalize_last_transaction();
4308 })
4309 .ok();
4310 }
4311 editor.update(cx, |editor, cx| {
4312 editor.refresh_document_highlights(cx);
4313 })?;
4314 }
4315 Ok(())
4316 }))
4317 }
4318
4319 pub fn show_word_completions(
4320 &mut self,
4321 _: &ShowWordCompletions,
4322 window: &mut Window,
4323 cx: &mut Context<Self>,
4324 ) {
4325 self.open_completions_menu(true, None, window, cx);
4326 }
4327
4328 pub fn show_completions(
4329 &mut self,
4330 options: &ShowCompletions,
4331 window: &mut Window,
4332 cx: &mut Context<Self>,
4333 ) {
4334 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4335 }
4336
4337 fn open_completions_menu(
4338 &mut self,
4339 ignore_completion_provider: bool,
4340 trigger: Option<&str>,
4341 window: &mut Window,
4342 cx: &mut Context<Self>,
4343 ) {
4344 if self.pending_rename.is_some() {
4345 return;
4346 }
4347 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4348 return;
4349 }
4350
4351 let position = self.selections.newest_anchor().head();
4352 if position.diff_base_anchor.is_some() {
4353 return;
4354 }
4355 let (buffer, buffer_position) =
4356 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4357 output
4358 } else {
4359 return;
4360 };
4361 let buffer_snapshot = buffer.read(cx).snapshot();
4362 let show_completion_documentation = buffer_snapshot
4363 .settings_at(buffer_position, cx)
4364 .show_completion_documentation;
4365
4366 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4367
4368 let trigger_kind = match trigger {
4369 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4370 CompletionTriggerKind::TRIGGER_CHARACTER
4371 }
4372 _ => CompletionTriggerKind::INVOKED,
4373 };
4374 let completion_context = CompletionContext {
4375 trigger_character: trigger.and_then(|trigger| {
4376 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4377 Some(String::from(trigger))
4378 } else {
4379 None
4380 }
4381 }),
4382 trigger_kind,
4383 };
4384
4385 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4386 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4387 let word_to_exclude = buffer_snapshot
4388 .text_for_range(old_range.clone())
4389 .collect::<String>();
4390 (
4391 buffer_snapshot.anchor_before(old_range.start)
4392 ..buffer_snapshot.anchor_after(old_range.end),
4393 Some(word_to_exclude),
4394 )
4395 } else {
4396 (buffer_position..buffer_position, None)
4397 };
4398
4399 let completion_settings = language_settings(
4400 buffer_snapshot
4401 .language_at(buffer_position)
4402 .map(|language| language.name()),
4403 buffer_snapshot.file(),
4404 cx,
4405 )
4406 .completions;
4407
4408 // The document can be large, so stay in reasonable bounds when searching for words,
4409 // otherwise completion pop-up might be slow to appear.
4410 const WORD_LOOKUP_ROWS: u32 = 5_000;
4411 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4412 let min_word_search = buffer_snapshot.clip_point(
4413 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4414 Bias::Left,
4415 );
4416 let max_word_search = buffer_snapshot.clip_point(
4417 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4418 Bias::Right,
4419 );
4420 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4421 ..buffer_snapshot.point_to_offset(max_word_search);
4422
4423 let provider = self
4424 .completion_provider
4425 .as_ref()
4426 .filter(|_| !ignore_completion_provider);
4427 let skip_digits = query
4428 .as_ref()
4429 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4430
4431 let (mut words, provided_completions) = match provider {
4432 Some(provider) => {
4433 let completions = provider.completions(
4434 position.excerpt_id,
4435 &buffer,
4436 buffer_position,
4437 completion_context,
4438 window,
4439 cx,
4440 );
4441
4442 let words = match completion_settings.words {
4443 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4444 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4445 .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 };
4453
4454 (words, completions)
4455 }
4456 None => (
4457 cx.background_spawn(async move {
4458 buffer_snapshot.words_in_range(WordsQuery {
4459 fuzzy_contents: None,
4460 range: word_search_range,
4461 skip_digits,
4462 })
4463 }),
4464 Task::ready(Ok(None)),
4465 ),
4466 };
4467
4468 let sort_completions = provider
4469 .as_ref()
4470 .map_or(false, |provider| provider.sort_completions());
4471
4472 let filter_completions = provider
4473 .as_ref()
4474 .map_or(true, |provider| provider.filter_completions());
4475
4476 let id = post_inc(&mut self.next_completion_id);
4477 let task = cx.spawn_in(window, async move |editor, cx| {
4478 async move {
4479 editor.update(cx, |this, _| {
4480 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4481 })?;
4482
4483 let mut completions = Vec::new();
4484 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4485 completions.extend(provided_completions);
4486 if completion_settings.words == WordsCompletionMode::Fallback {
4487 words = Task::ready(BTreeMap::default());
4488 }
4489 }
4490
4491 let mut words = words.await;
4492 if let Some(word_to_exclude) = &word_to_exclude {
4493 words.remove(word_to_exclude);
4494 }
4495 for lsp_completion in &completions {
4496 words.remove(&lsp_completion.new_text);
4497 }
4498 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4499 replace_range: old_range.clone(),
4500 new_text: word.clone(),
4501 label: CodeLabel::plain(word, None),
4502 icon_path: None,
4503 documentation: None,
4504 source: CompletionSource::BufferWord {
4505 word_range,
4506 resolved: false,
4507 },
4508 insert_text_mode: Some(InsertTextMode::AS_IS),
4509 confirm: None,
4510 }));
4511
4512 let menu = if completions.is_empty() {
4513 None
4514 } else {
4515 let mut menu = CompletionsMenu::new(
4516 id,
4517 sort_completions,
4518 show_completion_documentation,
4519 ignore_completion_provider,
4520 position,
4521 buffer.clone(),
4522 completions.into(),
4523 );
4524
4525 menu.filter(
4526 if filter_completions {
4527 query.as_deref()
4528 } else {
4529 None
4530 },
4531 cx.background_executor().clone(),
4532 )
4533 .await;
4534
4535 menu.visible().then_some(menu)
4536 };
4537
4538 editor.update_in(cx, |editor, window, cx| {
4539 match editor.context_menu.borrow().as_ref() {
4540 None => {}
4541 Some(CodeContextMenu::Completions(prev_menu)) => {
4542 if prev_menu.id > id {
4543 return;
4544 }
4545 }
4546 _ => return,
4547 }
4548
4549 if editor.focus_handle.is_focused(window) && menu.is_some() {
4550 let mut menu = menu.unwrap();
4551 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4552
4553 *editor.context_menu.borrow_mut() =
4554 Some(CodeContextMenu::Completions(menu));
4555
4556 if editor.show_edit_predictions_in_menu() {
4557 editor.update_visible_inline_completion(window, cx);
4558 } else {
4559 editor.discard_inline_completion(false, cx);
4560 }
4561
4562 cx.notify();
4563 } else if editor.completion_tasks.len() <= 1 {
4564 // If there are no more completion tasks and the last menu was
4565 // empty, we should hide it.
4566 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4567 // If it was already hidden and we don't show inline
4568 // completions in the menu, we should also show the
4569 // inline-completion when available.
4570 if was_hidden && editor.show_edit_predictions_in_menu() {
4571 editor.update_visible_inline_completion(window, cx);
4572 }
4573 }
4574 })?;
4575
4576 anyhow::Ok(())
4577 }
4578 .log_err()
4579 .await
4580 });
4581
4582 self.completion_tasks.push((id, task));
4583 }
4584
4585 #[cfg(feature = "test-support")]
4586 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4587 let menu = self.context_menu.borrow();
4588 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4589 let completions = menu.completions.borrow();
4590 Some(completions.to_vec())
4591 } else {
4592 None
4593 }
4594 }
4595
4596 pub fn confirm_completion(
4597 &mut self,
4598 action: &ConfirmCompletion,
4599 window: &mut Window,
4600 cx: &mut Context<Self>,
4601 ) -> Option<Task<Result<()>>> {
4602 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4603 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4604 }
4605
4606 pub fn confirm_completion_insert(
4607 &mut self,
4608 _: &ConfirmCompletionInsert,
4609 window: &mut Window,
4610 cx: &mut Context<Self>,
4611 ) -> Option<Task<Result<()>>> {
4612 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4613 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4614 }
4615
4616 pub fn confirm_completion_replace(
4617 &mut self,
4618 _: &ConfirmCompletionReplace,
4619 window: &mut Window,
4620 cx: &mut Context<Self>,
4621 ) -> Option<Task<Result<()>>> {
4622 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4623 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4624 }
4625
4626 pub fn compose_completion(
4627 &mut self,
4628 action: &ComposeCompletion,
4629 window: &mut Window,
4630 cx: &mut Context<Self>,
4631 ) -> Option<Task<Result<()>>> {
4632 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4633 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4634 }
4635
4636 fn do_completion(
4637 &mut self,
4638 item_ix: Option<usize>,
4639 intent: CompletionIntent,
4640 window: &mut Window,
4641 cx: &mut Context<Editor>,
4642 ) -> Option<Task<Result<()>>> {
4643 use language::ToOffset as _;
4644
4645 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4646 else {
4647 return None;
4648 };
4649
4650 let candidate_id = {
4651 let entries = completions_menu.entries.borrow();
4652 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4653 if self.show_edit_predictions_in_menu() {
4654 self.discard_inline_completion(true, cx);
4655 }
4656 mat.candidate_id
4657 };
4658
4659 let buffer_handle = completions_menu.buffer;
4660 let completion = completions_menu
4661 .completions
4662 .borrow()
4663 .get(candidate_id)?
4664 .clone();
4665 cx.stop_propagation();
4666
4667 let snippet;
4668 let new_text;
4669 if completion.is_snippet() {
4670 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4671 new_text = snippet.as_ref().unwrap().text.clone();
4672 } else {
4673 snippet = None;
4674 new_text = completion.new_text.clone();
4675 };
4676 let selections = self.selections.all::<usize>(cx);
4677
4678 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4679 let buffer = buffer_handle.read(cx);
4680 let old_text = buffer
4681 .text_for_range(replace_range.clone())
4682 .collect::<String>();
4683
4684 let newest_selection = self.selections.newest_anchor();
4685 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4686 return None;
4687 }
4688
4689 let lookbehind = newest_selection
4690 .start
4691 .text_anchor
4692 .to_offset(buffer)
4693 .saturating_sub(replace_range.start);
4694 let lookahead = replace_range
4695 .end
4696 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4697 let mut common_prefix_len = 0;
4698 for (a, b) in old_text.chars().zip(new_text.chars()) {
4699 if a == b {
4700 common_prefix_len += a.len_utf8();
4701 } else {
4702 break;
4703 }
4704 }
4705
4706 let snapshot = self.buffer.read(cx).snapshot(cx);
4707 let mut range_to_replace: Option<Range<usize>> = None;
4708 let mut ranges = Vec::new();
4709 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4710 for selection in &selections {
4711 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4712 let start = selection.start.saturating_sub(lookbehind);
4713 let end = selection.end + lookahead;
4714 if selection.id == newest_selection.id {
4715 range_to_replace = Some(start + common_prefix_len..end);
4716 }
4717 ranges.push(start + common_prefix_len..end);
4718 } else {
4719 common_prefix_len = 0;
4720 ranges.clear();
4721 ranges.extend(selections.iter().map(|s| {
4722 if s.id == newest_selection.id {
4723 range_to_replace = Some(replace_range.clone());
4724 replace_range.clone()
4725 } else {
4726 s.start..s.end
4727 }
4728 }));
4729 break;
4730 }
4731 if !self.linked_edit_ranges.is_empty() {
4732 let start_anchor = snapshot.anchor_before(selection.head());
4733 let end_anchor = snapshot.anchor_after(selection.tail());
4734 if let Some(ranges) = self
4735 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4736 {
4737 for (buffer, edits) in ranges {
4738 linked_edits.entry(buffer.clone()).or_default().extend(
4739 edits
4740 .into_iter()
4741 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4742 );
4743 }
4744 }
4745 }
4746 }
4747 let text = &new_text[common_prefix_len..];
4748
4749 let utf16_range_to_replace = range_to_replace.map(|range| {
4750 let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
4751 let selection_start_utf16 = newest_selection.start.0 as isize;
4752
4753 range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4754 ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4755 });
4756 cx.emit(EditorEvent::InputHandled {
4757 utf16_range_to_replace,
4758 text: text.into(),
4759 });
4760
4761 self.transact(window, cx, |this, window, cx| {
4762 if let Some(mut snippet) = snippet {
4763 snippet.text = text.to_string();
4764 for tabstop in snippet
4765 .tabstops
4766 .iter_mut()
4767 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4768 {
4769 tabstop.start -= common_prefix_len as isize;
4770 tabstop.end -= common_prefix_len as isize;
4771 }
4772
4773 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4774 } else {
4775 this.buffer.update(cx, |buffer, cx| {
4776 let edits = ranges.iter().map(|range| (range.clone(), text));
4777 let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
4778 {
4779 None
4780 } else {
4781 this.autoindent_mode.clone()
4782 };
4783 buffer.edit(edits, auto_indent, cx);
4784 });
4785 }
4786 for (buffer, edits) in linked_edits {
4787 buffer.update(cx, |buffer, cx| {
4788 let snapshot = buffer.snapshot();
4789 let edits = edits
4790 .into_iter()
4791 .map(|(range, text)| {
4792 use text::ToPoint as TP;
4793 let end_point = TP::to_point(&range.end, &snapshot);
4794 let start_point = TP::to_point(&range.start, &snapshot);
4795 (start_point..end_point, text)
4796 })
4797 .sorted_by_key(|(range, _)| range.start);
4798 buffer.edit(edits, None, cx);
4799 })
4800 }
4801
4802 this.refresh_inline_completion(true, false, window, cx);
4803 });
4804
4805 let show_new_completions_on_confirm = completion
4806 .confirm
4807 .as_ref()
4808 .map_or(false, |confirm| confirm(intent, window, cx));
4809 if show_new_completions_on_confirm {
4810 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4811 }
4812
4813 let provider = self.completion_provider.as_ref()?;
4814 drop(completion);
4815 let apply_edits = provider.apply_additional_edits_for_completion(
4816 buffer_handle,
4817 completions_menu.completions.clone(),
4818 candidate_id,
4819 true,
4820 cx,
4821 );
4822
4823 let editor_settings = EditorSettings::get_global(cx);
4824 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4825 // After the code completion is finished, users often want to know what signatures are needed.
4826 // so we should automatically call signature_help
4827 self.show_signature_help(&ShowSignatureHelp, window, cx);
4828 }
4829
4830 Some(cx.foreground_executor().spawn(async move {
4831 apply_edits.await?;
4832 Ok(())
4833 }))
4834 }
4835
4836 pub fn toggle_code_actions(
4837 &mut self,
4838 action: &ToggleCodeActions,
4839 window: &mut Window,
4840 cx: &mut Context<Self>,
4841 ) {
4842 let mut context_menu = self.context_menu.borrow_mut();
4843 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4844 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4845 // Toggle if we're selecting the same one
4846 *context_menu = None;
4847 cx.notify();
4848 return;
4849 } else {
4850 // Otherwise, clear it and start a new one
4851 *context_menu = None;
4852 cx.notify();
4853 }
4854 }
4855 drop(context_menu);
4856 let snapshot = self.snapshot(window, cx);
4857 let deployed_from_indicator = action.deployed_from_indicator;
4858 let mut task = self.code_actions_task.take();
4859 let action = action.clone();
4860 cx.spawn_in(window, async move |editor, cx| {
4861 while let Some(prev_task) = task {
4862 prev_task.await.log_err();
4863 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4864 }
4865
4866 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4867 if editor.focus_handle.is_focused(window) {
4868 let multibuffer_point = action
4869 .deployed_from_indicator
4870 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4871 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4872 let (buffer, buffer_row) = snapshot
4873 .buffer_snapshot
4874 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4875 .and_then(|(buffer_snapshot, range)| {
4876 editor
4877 .buffer
4878 .read(cx)
4879 .buffer(buffer_snapshot.remote_id())
4880 .map(|buffer| (buffer, range.start.row))
4881 })?;
4882 let (_, code_actions) = editor
4883 .available_code_actions
4884 .clone()
4885 .and_then(|(location, code_actions)| {
4886 let snapshot = location.buffer.read(cx).snapshot();
4887 let point_range = location.range.to_point(&snapshot);
4888 let point_range = point_range.start.row..=point_range.end.row;
4889 if point_range.contains(&buffer_row) {
4890 Some((location, code_actions))
4891 } else {
4892 None
4893 }
4894 })
4895 .unzip();
4896 let buffer_id = buffer.read(cx).remote_id();
4897 let tasks = editor
4898 .tasks
4899 .get(&(buffer_id, buffer_row))
4900 .map(|t| Arc::new(t.to_owned()));
4901 if tasks.is_none() && code_actions.is_none() {
4902 return None;
4903 }
4904
4905 editor.completion_tasks.clear();
4906 editor.discard_inline_completion(false, cx);
4907 let task_context =
4908 tasks
4909 .as_ref()
4910 .zip(editor.project.clone())
4911 .map(|(tasks, project)| {
4912 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4913 });
4914
4915 let debugger_flag = cx.has_flag::<Debugger>();
4916
4917 Some(cx.spawn_in(window, async move |editor, cx| {
4918 let task_context = match task_context {
4919 Some(task_context) => task_context.await,
4920 None => None,
4921 };
4922 let resolved_tasks =
4923 tasks.zip(task_context).map(|(tasks, task_context)| {
4924 Rc::new(ResolvedTasks {
4925 templates: tasks.resolve(&task_context).collect(),
4926 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4927 multibuffer_point.row,
4928 tasks.column,
4929 )),
4930 })
4931 });
4932 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
4933 tasks
4934 .templates
4935 .iter()
4936 .filter(|task| {
4937 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4938 debugger_flag
4939 } else {
4940 true
4941 }
4942 })
4943 .count()
4944 == 1
4945 }) && code_actions
4946 .as_ref()
4947 .map_or(true, |actions| actions.is_empty());
4948 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4949 *editor.context_menu.borrow_mut() =
4950 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4951 buffer,
4952 actions: CodeActionContents {
4953 tasks: resolved_tasks,
4954 actions: code_actions,
4955 },
4956 selected_item: Default::default(),
4957 scroll_handle: UniformListScrollHandle::default(),
4958 deployed_from_indicator,
4959 }));
4960 if spawn_straight_away {
4961 if let Some(task) = editor.confirm_code_action(
4962 &ConfirmCodeAction { item_ix: Some(0) },
4963 window,
4964 cx,
4965 ) {
4966 cx.notify();
4967 return task;
4968 }
4969 }
4970 cx.notify();
4971 Task::ready(Ok(()))
4972 }) {
4973 task.await
4974 } else {
4975 Ok(())
4976 }
4977 }))
4978 } else {
4979 Some(Task::ready(Ok(())))
4980 }
4981 })?;
4982 if let Some(task) = spawned_test_task {
4983 task.await?;
4984 }
4985
4986 Ok::<_, anyhow::Error>(())
4987 })
4988 .detach_and_log_err(cx);
4989 }
4990
4991 pub fn confirm_code_action(
4992 &mut self,
4993 action: &ConfirmCodeAction,
4994 window: &mut Window,
4995 cx: &mut Context<Self>,
4996 ) -> Option<Task<Result<()>>> {
4997 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4998
4999 let actions_menu =
5000 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5001 menu
5002 } else {
5003 return None;
5004 };
5005
5006 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5007 let action = actions_menu.actions.get(action_ix)?;
5008 let title = action.label();
5009 let buffer = actions_menu.buffer;
5010 let workspace = self.workspace()?;
5011
5012 match action {
5013 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5014 match resolved_task.task_type() {
5015 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5016 workspace::tasks::schedule_resolved_task(
5017 workspace,
5018 task_source_kind,
5019 resolved_task,
5020 false,
5021 cx,
5022 );
5023
5024 Some(Task::ready(Ok(())))
5025 }),
5026 task::TaskType::Debug(debug_args) => {
5027 if debug_args.locator.is_some() {
5028 workspace.update(cx, |workspace, cx| {
5029 workspace::tasks::schedule_resolved_task(
5030 workspace,
5031 task_source_kind,
5032 resolved_task,
5033 false,
5034 cx,
5035 );
5036 });
5037
5038 return Some(Task::ready(Ok(())));
5039 }
5040
5041 if let Some(project) = self.project.as_ref() {
5042 project
5043 .update(cx, |project, cx| {
5044 project.start_debug_session(
5045 resolved_task.resolved_debug_adapter_config().unwrap(),
5046 cx,
5047 )
5048 })
5049 .detach_and_log_err(cx);
5050 Some(Task::ready(Ok(())))
5051 } else {
5052 Some(Task::ready(Ok(())))
5053 }
5054 }
5055 }
5056 }
5057 CodeActionsItem::CodeAction {
5058 excerpt_id,
5059 action,
5060 provider,
5061 } => {
5062 let apply_code_action =
5063 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5064 let workspace = workspace.downgrade();
5065 Some(cx.spawn_in(window, async move |editor, cx| {
5066 let project_transaction = apply_code_action.await?;
5067 Self::open_project_transaction(
5068 &editor,
5069 workspace,
5070 project_transaction,
5071 title,
5072 cx,
5073 )
5074 .await
5075 }))
5076 }
5077 }
5078 }
5079
5080 pub async fn open_project_transaction(
5081 this: &WeakEntity<Editor>,
5082 workspace: WeakEntity<Workspace>,
5083 transaction: ProjectTransaction,
5084 title: String,
5085 cx: &mut AsyncWindowContext,
5086 ) -> Result<()> {
5087 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5088 cx.update(|_, cx| {
5089 entries.sort_unstable_by_key(|(buffer, _)| {
5090 buffer.read(cx).file().map(|f| f.path().clone())
5091 });
5092 })?;
5093
5094 // If the project transaction's edits are all contained within this editor, then
5095 // avoid opening a new editor to display them.
5096
5097 if let Some((buffer, transaction)) = entries.first() {
5098 if entries.len() == 1 {
5099 let excerpt = this.update(cx, |editor, cx| {
5100 editor
5101 .buffer()
5102 .read(cx)
5103 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5104 })?;
5105 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5106 if excerpted_buffer == *buffer {
5107 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5108 let excerpt_range = excerpt_range.to_offset(buffer);
5109 buffer
5110 .edited_ranges_for_transaction::<usize>(transaction)
5111 .all(|range| {
5112 excerpt_range.start <= range.start
5113 && excerpt_range.end >= range.end
5114 })
5115 })?;
5116
5117 if all_edits_within_excerpt {
5118 return Ok(());
5119 }
5120 }
5121 }
5122 }
5123 } else {
5124 return Ok(());
5125 }
5126
5127 let mut ranges_to_highlight = Vec::new();
5128 let excerpt_buffer = cx.new(|cx| {
5129 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5130 for (buffer_handle, transaction) in &entries {
5131 let edited_ranges = buffer_handle
5132 .read(cx)
5133 .edited_ranges_for_transaction::<Point>(transaction)
5134 .collect::<Vec<_>>();
5135 let (ranges, _) = multibuffer.set_excerpts_for_path(
5136 PathKey::for_buffer(buffer_handle, cx),
5137 buffer_handle.clone(),
5138 edited_ranges,
5139 DEFAULT_MULTIBUFFER_CONTEXT,
5140 cx,
5141 );
5142
5143 ranges_to_highlight.extend(ranges);
5144 }
5145 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5146 multibuffer
5147 })?;
5148
5149 workspace.update_in(cx, |workspace, window, cx| {
5150 let project = workspace.project().clone();
5151 let editor =
5152 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5153 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5154 editor.update(cx, |editor, cx| {
5155 editor.highlight_background::<Self>(
5156 &ranges_to_highlight,
5157 |theme| theme.editor_highlighted_line_background,
5158 cx,
5159 );
5160 });
5161 })?;
5162
5163 Ok(())
5164 }
5165
5166 pub fn clear_code_action_providers(&mut self) {
5167 self.code_action_providers.clear();
5168 self.available_code_actions.take();
5169 }
5170
5171 pub fn add_code_action_provider(
5172 &mut self,
5173 provider: Rc<dyn CodeActionProvider>,
5174 window: &mut Window,
5175 cx: &mut Context<Self>,
5176 ) {
5177 if self
5178 .code_action_providers
5179 .iter()
5180 .any(|existing_provider| existing_provider.id() == provider.id())
5181 {
5182 return;
5183 }
5184
5185 self.code_action_providers.push(provider);
5186 self.refresh_code_actions(window, cx);
5187 }
5188
5189 pub fn remove_code_action_provider(
5190 &mut self,
5191 id: Arc<str>,
5192 window: &mut Window,
5193 cx: &mut Context<Self>,
5194 ) {
5195 self.code_action_providers
5196 .retain(|provider| provider.id() != id);
5197 self.refresh_code_actions(window, cx);
5198 }
5199
5200 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5201 let newest_selection = self.selections.newest_anchor().clone();
5202 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5203 let buffer = self.buffer.read(cx);
5204 if newest_selection.head().diff_base_anchor.is_some() {
5205 return None;
5206 }
5207 let (start_buffer, start) =
5208 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5209 let (end_buffer, end) =
5210 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5211 if start_buffer != end_buffer {
5212 return None;
5213 }
5214
5215 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5216 cx.background_executor()
5217 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5218 .await;
5219
5220 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5221 let providers = this.code_action_providers.clone();
5222 let tasks = this
5223 .code_action_providers
5224 .iter()
5225 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5226 .collect::<Vec<_>>();
5227 (providers, tasks)
5228 })?;
5229
5230 let mut actions = Vec::new();
5231 for (provider, provider_actions) in
5232 providers.into_iter().zip(future::join_all(tasks).await)
5233 {
5234 if let Some(provider_actions) = provider_actions.log_err() {
5235 actions.extend(provider_actions.into_iter().map(|action| {
5236 AvailableCodeAction {
5237 excerpt_id: newest_selection.start.excerpt_id,
5238 action,
5239 provider: provider.clone(),
5240 }
5241 }));
5242 }
5243 }
5244
5245 this.update(cx, |this, cx| {
5246 this.available_code_actions = if actions.is_empty() {
5247 None
5248 } else {
5249 Some((
5250 Location {
5251 buffer: start_buffer,
5252 range: start..end,
5253 },
5254 actions.into(),
5255 ))
5256 };
5257 cx.notify();
5258 })
5259 }));
5260 None
5261 }
5262
5263 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5264 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5265 self.show_git_blame_inline = false;
5266
5267 self.show_git_blame_inline_delay_task =
5268 Some(cx.spawn_in(window, async move |this, cx| {
5269 cx.background_executor().timer(delay).await;
5270
5271 this.update(cx, |this, cx| {
5272 this.show_git_blame_inline = true;
5273 cx.notify();
5274 })
5275 .log_err();
5276 }));
5277 }
5278 }
5279
5280 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5281 if self.pending_rename.is_some() {
5282 return None;
5283 }
5284
5285 let provider = self.semantics_provider.clone()?;
5286 let buffer = self.buffer.read(cx);
5287 let newest_selection = self.selections.newest_anchor().clone();
5288 let cursor_position = newest_selection.head();
5289 let (cursor_buffer, cursor_buffer_position) =
5290 buffer.text_anchor_for_position(cursor_position, cx)?;
5291 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5292 if cursor_buffer != tail_buffer {
5293 return None;
5294 }
5295 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5296 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5297 cx.background_executor()
5298 .timer(Duration::from_millis(debounce))
5299 .await;
5300
5301 let highlights = if let Some(highlights) = cx
5302 .update(|cx| {
5303 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5304 })
5305 .ok()
5306 .flatten()
5307 {
5308 highlights.await.log_err()
5309 } else {
5310 None
5311 };
5312
5313 if let Some(highlights) = highlights {
5314 this.update(cx, |this, cx| {
5315 if this.pending_rename.is_some() {
5316 return;
5317 }
5318
5319 let buffer_id = cursor_position.buffer_id;
5320 let buffer = this.buffer.read(cx);
5321 if !buffer
5322 .text_anchor_for_position(cursor_position, cx)
5323 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5324 {
5325 return;
5326 }
5327
5328 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5329 let mut write_ranges = Vec::new();
5330 let mut read_ranges = Vec::new();
5331 for highlight in highlights {
5332 for (excerpt_id, excerpt_range) in
5333 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5334 {
5335 let start = highlight
5336 .range
5337 .start
5338 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5339 let end = highlight
5340 .range
5341 .end
5342 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5343 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5344 continue;
5345 }
5346
5347 let range = Anchor {
5348 buffer_id,
5349 excerpt_id,
5350 text_anchor: start,
5351 diff_base_anchor: None,
5352 }..Anchor {
5353 buffer_id,
5354 excerpt_id,
5355 text_anchor: end,
5356 diff_base_anchor: None,
5357 };
5358 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5359 write_ranges.push(range);
5360 } else {
5361 read_ranges.push(range);
5362 }
5363 }
5364 }
5365
5366 this.highlight_background::<DocumentHighlightRead>(
5367 &read_ranges,
5368 |theme| theme.editor_document_highlight_read_background,
5369 cx,
5370 );
5371 this.highlight_background::<DocumentHighlightWrite>(
5372 &write_ranges,
5373 |theme| theme.editor_document_highlight_write_background,
5374 cx,
5375 );
5376 cx.notify();
5377 })
5378 .log_err();
5379 }
5380 }));
5381 None
5382 }
5383
5384 pub fn refresh_selected_text_highlights(
5385 &mut self,
5386 window: &mut Window,
5387 cx: &mut Context<Editor>,
5388 ) {
5389 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5390 return;
5391 }
5392 self.selection_highlight_task.take();
5393 if !EditorSettings::get_global(cx).selection_highlight {
5394 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5395 return;
5396 }
5397 if self.selections.count() != 1 || self.selections.line_mode {
5398 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5399 return;
5400 }
5401 let selection = self.selections.newest::<Point>(cx);
5402 if selection.is_empty() || selection.start.row != selection.end.row {
5403 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5404 return;
5405 }
5406 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5407 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5408 cx.background_executor()
5409 .timer(Duration::from_millis(debounce))
5410 .await;
5411 let Some(Some(matches_task)) = editor
5412 .update_in(cx, |editor, _, cx| {
5413 if editor.selections.count() != 1 || editor.selections.line_mode {
5414 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5415 return None;
5416 }
5417 let selection = editor.selections.newest::<Point>(cx);
5418 if selection.is_empty() || selection.start.row != selection.end.row {
5419 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5420 return None;
5421 }
5422 let buffer = editor.buffer().read(cx).snapshot(cx);
5423 let query = buffer.text_for_range(selection.range()).collect::<String>();
5424 if query.trim().is_empty() {
5425 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5426 return None;
5427 }
5428 Some(cx.background_spawn(async move {
5429 let mut ranges = Vec::new();
5430 let selection_anchors = selection.range().to_anchors(&buffer);
5431 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5432 for (search_buffer, search_range, excerpt_id) in
5433 buffer.range_to_buffer_ranges(range)
5434 {
5435 ranges.extend(
5436 project::search::SearchQuery::text(
5437 query.clone(),
5438 false,
5439 false,
5440 false,
5441 Default::default(),
5442 Default::default(),
5443 None,
5444 )
5445 .unwrap()
5446 .search(search_buffer, Some(search_range.clone()))
5447 .await
5448 .into_iter()
5449 .filter_map(
5450 |match_range| {
5451 let start = search_buffer.anchor_after(
5452 search_range.start + match_range.start,
5453 );
5454 let end = search_buffer.anchor_before(
5455 search_range.start + match_range.end,
5456 );
5457 let range = Anchor::range_in_buffer(
5458 excerpt_id,
5459 search_buffer.remote_id(),
5460 start..end,
5461 );
5462 (range != selection_anchors).then_some(range)
5463 },
5464 ),
5465 );
5466 }
5467 }
5468 ranges
5469 }))
5470 })
5471 .log_err()
5472 else {
5473 return;
5474 };
5475 let matches = matches_task.await;
5476 editor
5477 .update_in(cx, |editor, _, cx| {
5478 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5479 if !matches.is_empty() {
5480 editor.highlight_background::<SelectedTextHighlight>(
5481 &matches,
5482 |theme| theme.editor_document_highlight_bracket_background,
5483 cx,
5484 )
5485 }
5486 })
5487 .log_err();
5488 }));
5489 }
5490
5491 pub fn refresh_inline_completion(
5492 &mut self,
5493 debounce: bool,
5494 user_requested: bool,
5495 window: &mut Window,
5496 cx: &mut Context<Self>,
5497 ) -> Option<()> {
5498 let provider = self.edit_prediction_provider()?;
5499 let cursor = self.selections.newest_anchor().head();
5500 let (buffer, cursor_buffer_position) =
5501 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5502
5503 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5504 self.discard_inline_completion(false, cx);
5505 return None;
5506 }
5507
5508 if !user_requested
5509 && (!self.should_show_edit_predictions()
5510 || !self.is_focused(window)
5511 || buffer.read(cx).is_empty())
5512 {
5513 self.discard_inline_completion(false, cx);
5514 return None;
5515 }
5516
5517 self.update_visible_inline_completion(window, cx);
5518 provider.refresh(
5519 self.project.clone(),
5520 buffer,
5521 cursor_buffer_position,
5522 debounce,
5523 cx,
5524 );
5525 Some(())
5526 }
5527
5528 fn show_edit_predictions_in_menu(&self) -> bool {
5529 match self.edit_prediction_settings {
5530 EditPredictionSettings::Disabled => false,
5531 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5532 }
5533 }
5534
5535 pub fn edit_predictions_enabled(&self) -> bool {
5536 match self.edit_prediction_settings {
5537 EditPredictionSettings::Disabled => false,
5538 EditPredictionSettings::Enabled { .. } => true,
5539 }
5540 }
5541
5542 fn edit_prediction_requires_modifier(&self) -> bool {
5543 match self.edit_prediction_settings {
5544 EditPredictionSettings::Disabled => false,
5545 EditPredictionSettings::Enabled {
5546 preview_requires_modifier,
5547 ..
5548 } => preview_requires_modifier,
5549 }
5550 }
5551
5552 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5553 if self.edit_prediction_provider.is_none() {
5554 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5555 } else {
5556 let selection = self.selections.newest_anchor();
5557 let cursor = selection.head();
5558
5559 if let Some((buffer, cursor_buffer_position)) =
5560 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5561 {
5562 self.edit_prediction_settings =
5563 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5564 }
5565 }
5566 }
5567
5568 fn edit_prediction_settings_at_position(
5569 &self,
5570 buffer: &Entity<Buffer>,
5571 buffer_position: language::Anchor,
5572 cx: &App,
5573 ) -> EditPredictionSettings {
5574 if !self.mode.is_full()
5575 || !self.show_inline_completions_override.unwrap_or(true)
5576 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5577 {
5578 return EditPredictionSettings::Disabled;
5579 }
5580
5581 let buffer = buffer.read(cx);
5582
5583 let file = buffer.file();
5584
5585 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5586 return EditPredictionSettings::Disabled;
5587 };
5588
5589 let by_provider = matches!(
5590 self.menu_inline_completions_policy,
5591 MenuInlineCompletionsPolicy::ByProvider
5592 );
5593
5594 let show_in_menu = by_provider
5595 && self
5596 .edit_prediction_provider
5597 .as_ref()
5598 .map_or(false, |provider| {
5599 provider.provider.show_completions_in_menu()
5600 });
5601
5602 let preview_requires_modifier =
5603 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5604
5605 EditPredictionSettings::Enabled {
5606 show_in_menu,
5607 preview_requires_modifier,
5608 }
5609 }
5610
5611 fn should_show_edit_predictions(&self) -> bool {
5612 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5613 }
5614
5615 pub fn edit_prediction_preview_is_active(&self) -> bool {
5616 matches!(
5617 self.edit_prediction_preview,
5618 EditPredictionPreview::Active { .. }
5619 )
5620 }
5621
5622 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5623 let cursor = self.selections.newest_anchor().head();
5624 if let Some((buffer, cursor_position)) =
5625 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5626 {
5627 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5628 } else {
5629 false
5630 }
5631 }
5632
5633 fn edit_predictions_enabled_in_buffer(
5634 &self,
5635 buffer: &Entity<Buffer>,
5636 buffer_position: language::Anchor,
5637 cx: &App,
5638 ) -> bool {
5639 maybe!({
5640 if self.read_only(cx) {
5641 return Some(false);
5642 }
5643 let provider = self.edit_prediction_provider()?;
5644 if !provider.is_enabled(&buffer, buffer_position, cx) {
5645 return Some(false);
5646 }
5647 let buffer = buffer.read(cx);
5648 let Some(file) = buffer.file() else {
5649 return Some(true);
5650 };
5651 let settings = all_language_settings(Some(file), cx);
5652 Some(settings.edit_predictions_enabled_for_file(file, cx))
5653 })
5654 .unwrap_or(false)
5655 }
5656
5657 fn cycle_inline_completion(
5658 &mut self,
5659 direction: Direction,
5660 window: &mut Window,
5661 cx: &mut Context<Self>,
5662 ) -> Option<()> {
5663 let provider = self.edit_prediction_provider()?;
5664 let cursor = self.selections.newest_anchor().head();
5665 let (buffer, cursor_buffer_position) =
5666 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5667 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5668 return None;
5669 }
5670
5671 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5672 self.update_visible_inline_completion(window, cx);
5673
5674 Some(())
5675 }
5676
5677 pub fn show_inline_completion(
5678 &mut self,
5679 _: &ShowEditPrediction,
5680 window: &mut Window,
5681 cx: &mut Context<Self>,
5682 ) {
5683 if !self.has_active_inline_completion() {
5684 self.refresh_inline_completion(false, true, window, cx);
5685 return;
5686 }
5687
5688 self.update_visible_inline_completion(window, cx);
5689 }
5690
5691 pub fn display_cursor_names(
5692 &mut self,
5693 _: &DisplayCursorNames,
5694 window: &mut Window,
5695 cx: &mut Context<Self>,
5696 ) {
5697 self.show_cursor_names(window, cx);
5698 }
5699
5700 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5701 self.show_cursor_names = true;
5702 cx.notify();
5703 cx.spawn_in(window, async move |this, cx| {
5704 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5705 this.update(cx, |this, cx| {
5706 this.show_cursor_names = false;
5707 cx.notify()
5708 })
5709 .ok()
5710 })
5711 .detach();
5712 }
5713
5714 pub fn next_edit_prediction(
5715 &mut self,
5716 _: &NextEditPrediction,
5717 window: &mut Window,
5718 cx: &mut Context<Self>,
5719 ) {
5720 if self.has_active_inline_completion() {
5721 self.cycle_inline_completion(Direction::Next, window, cx);
5722 } else {
5723 let is_copilot_disabled = self
5724 .refresh_inline_completion(false, true, window, cx)
5725 .is_none();
5726 if is_copilot_disabled {
5727 cx.propagate();
5728 }
5729 }
5730 }
5731
5732 pub fn previous_edit_prediction(
5733 &mut self,
5734 _: &PreviousEditPrediction,
5735 window: &mut Window,
5736 cx: &mut Context<Self>,
5737 ) {
5738 if self.has_active_inline_completion() {
5739 self.cycle_inline_completion(Direction::Prev, window, cx);
5740 } else {
5741 let is_copilot_disabled = self
5742 .refresh_inline_completion(false, true, window, cx)
5743 .is_none();
5744 if is_copilot_disabled {
5745 cx.propagate();
5746 }
5747 }
5748 }
5749
5750 pub fn accept_edit_prediction(
5751 &mut self,
5752 _: &AcceptEditPrediction,
5753 window: &mut Window,
5754 cx: &mut Context<Self>,
5755 ) {
5756 if self.show_edit_predictions_in_menu() {
5757 self.hide_context_menu(window, cx);
5758 }
5759
5760 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5761 return;
5762 };
5763
5764 self.report_inline_completion_event(
5765 active_inline_completion.completion_id.clone(),
5766 true,
5767 cx,
5768 );
5769
5770 match &active_inline_completion.completion {
5771 InlineCompletion::Move { target, .. } => {
5772 let target = *target;
5773
5774 if let Some(position_map) = &self.last_position_map {
5775 if position_map
5776 .visible_row_range
5777 .contains(&target.to_display_point(&position_map.snapshot).row())
5778 || !self.edit_prediction_requires_modifier()
5779 {
5780 self.unfold_ranges(&[target..target], true, false, cx);
5781 // Note that this is also done in vim's handler of the Tab action.
5782 self.change_selections(
5783 Some(Autoscroll::newest()),
5784 window,
5785 cx,
5786 |selections| {
5787 selections.select_anchor_ranges([target..target]);
5788 },
5789 );
5790 self.clear_row_highlights::<EditPredictionPreview>();
5791
5792 self.edit_prediction_preview
5793 .set_previous_scroll_position(None);
5794 } else {
5795 self.edit_prediction_preview
5796 .set_previous_scroll_position(Some(
5797 position_map.snapshot.scroll_anchor,
5798 ));
5799
5800 self.highlight_rows::<EditPredictionPreview>(
5801 target..target,
5802 cx.theme().colors().editor_highlighted_line_background,
5803 true,
5804 cx,
5805 );
5806 self.request_autoscroll(Autoscroll::fit(), cx);
5807 }
5808 }
5809 }
5810 InlineCompletion::Edit { edits, .. } => {
5811 if let Some(provider) = self.edit_prediction_provider() {
5812 provider.accept(cx);
5813 }
5814
5815 let snapshot = self.buffer.read(cx).snapshot(cx);
5816 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5817
5818 self.buffer.update(cx, |buffer, cx| {
5819 buffer.edit(edits.iter().cloned(), None, cx)
5820 });
5821
5822 self.change_selections(None, window, cx, |s| {
5823 s.select_anchor_ranges([last_edit_end..last_edit_end])
5824 });
5825
5826 self.update_visible_inline_completion(window, cx);
5827 if self.active_inline_completion.is_none() {
5828 self.refresh_inline_completion(true, true, window, cx);
5829 }
5830
5831 cx.notify();
5832 }
5833 }
5834
5835 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5836 }
5837
5838 pub fn accept_partial_inline_completion(
5839 &mut self,
5840 _: &AcceptPartialEditPrediction,
5841 window: &mut Window,
5842 cx: &mut Context<Self>,
5843 ) {
5844 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5845 return;
5846 };
5847 if self.selections.count() != 1 {
5848 return;
5849 }
5850
5851 self.report_inline_completion_event(
5852 active_inline_completion.completion_id.clone(),
5853 true,
5854 cx,
5855 );
5856
5857 match &active_inline_completion.completion {
5858 InlineCompletion::Move { target, .. } => {
5859 let target = *target;
5860 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5861 selections.select_anchor_ranges([target..target]);
5862 });
5863 }
5864 InlineCompletion::Edit { edits, .. } => {
5865 // Find an insertion that starts at the cursor position.
5866 let snapshot = self.buffer.read(cx).snapshot(cx);
5867 let cursor_offset = self.selections.newest::<usize>(cx).head();
5868 let insertion = edits.iter().find_map(|(range, text)| {
5869 let range = range.to_offset(&snapshot);
5870 if range.is_empty() && range.start == cursor_offset {
5871 Some(text)
5872 } else {
5873 None
5874 }
5875 });
5876
5877 if let Some(text) = insertion {
5878 let mut partial_completion = text
5879 .chars()
5880 .by_ref()
5881 .take_while(|c| c.is_alphabetic())
5882 .collect::<String>();
5883 if partial_completion.is_empty() {
5884 partial_completion = text
5885 .chars()
5886 .by_ref()
5887 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5888 .collect::<String>();
5889 }
5890
5891 cx.emit(EditorEvent::InputHandled {
5892 utf16_range_to_replace: None,
5893 text: partial_completion.clone().into(),
5894 });
5895
5896 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5897
5898 self.refresh_inline_completion(true, true, window, cx);
5899 cx.notify();
5900 } else {
5901 self.accept_edit_prediction(&Default::default(), window, cx);
5902 }
5903 }
5904 }
5905 }
5906
5907 fn discard_inline_completion(
5908 &mut self,
5909 should_report_inline_completion_event: bool,
5910 cx: &mut Context<Self>,
5911 ) -> bool {
5912 if should_report_inline_completion_event {
5913 let completion_id = self
5914 .active_inline_completion
5915 .as_ref()
5916 .and_then(|active_completion| active_completion.completion_id.clone());
5917
5918 self.report_inline_completion_event(completion_id, false, cx);
5919 }
5920
5921 if let Some(provider) = self.edit_prediction_provider() {
5922 provider.discard(cx);
5923 }
5924
5925 self.take_active_inline_completion(cx)
5926 }
5927
5928 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5929 let Some(provider) = self.edit_prediction_provider() else {
5930 return;
5931 };
5932
5933 let Some((_, buffer, _)) = self
5934 .buffer
5935 .read(cx)
5936 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5937 else {
5938 return;
5939 };
5940
5941 let extension = buffer
5942 .read(cx)
5943 .file()
5944 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5945
5946 let event_type = match accepted {
5947 true => "Edit Prediction Accepted",
5948 false => "Edit Prediction Discarded",
5949 };
5950 telemetry::event!(
5951 event_type,
5952 provider = provider.name(),
5953 prediction_id = id,
5954 suggestion_accepted = accepted,
5955 file_extension = extension,
5956 );
5957 }
5958
5959 pub fn has_active_inline_completion(&self) -> bool {
5960 self.active_inline_completion.is_some()
5961 }
5962
5963 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5964 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5965 return false;
5966 };
5967
5968 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5969 self.clear_highlights::<InlineCompletionHighlight>(cx);
5970 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5971 true
5972 }
5973
5974 /// Returns true when we're displaying the edit prediction popover below the cursor
5975 /// like we are not previewing and the LSP autocomplete menu is visible
5976 /// or we are in `when_holding_modifier` mode.
5977 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5978 if self.edit_prediction_preview_is_active()
5979 || !self.show_edit_predictions_in_menu()
5980 || !self.edit_predictions_enabled()
5981 {
5982 return false;
5983 }
5984
5985 if self.has_visible_completions_menu() {
5986 return true;
5987 }
5988
5989 has_completion && self.edit_prediction_requires_modifier()
5990 }
5991
5992 fn handle_modifiers_changed(
5993 &mut self,
5994 modifiers: Modifiers,
5995 position_map: &PositionMap,
5996 window: &mut Window,
5997 cx: &mut Context<Self>,
5998 ) {
5999 if self.show_edit_predictions_in_menu() {
6000 self.update_edit_prediction_preview(&modifiers, window, cx);
6001 }
6002
6003 self.update_selection_mode(&modifiers, position_map, window, cx);
6004
6005 let mouse_position = window.mouse_position();
6006 if !position_map.text_hitbox.is_hovered(window) {
6007 return;
6008 }
6009
6010 self.update_hovered_link(
6011 position_map.point_for_position(mouse_position),
6012 &position_map.snapshot,
6013 modifiers,
6014 window,
6015 cx,
6016 )
6017 }
6018
6019 fn update_selection_mode(
6020 &mut self,
6021 modifiers: &Modifiers,
6022 position_map: &PositionMap,
6023 window: &mut Window,
6024 cx: &mut Context<Self>,
6025 ) {
6026 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6027 return;
6028 }
6029
6030 let mouse_position = window.mouse_position();
6031 let point_for_position = position_map.point_for_position(mouse_position);
6032 let position = point_for_position.previous_valid;
6033
6034 self.select(
6035 SelectPhase::BeginColumnar {
6036 position,
6037 reset: false,
6038 goal_column: point_for_position.exact_unclipped.column(),
6039 },
6040 window,
6041 cx,
6042 );
6043 }
6044
6045 fn update_edit_prediction_preview(
6046 &mut self,
6047 modifiers: &Modifiers,
6048 window: &mut Window,
6049 cx: &mut Context<Self>,
6050 ) {
6051 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6052 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6053 return;
6054 };
6055
6056 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6057 if matches!(
6058 self.edit_prediction_preview,
6059 EditPredictionPreview::Inactive { .. }
6060 ) {
6061 self.edit_prediction_preview = EditPredictionPreview::Active {
6062 previous_scroll_position: None,
6063 since: Instant::now(),
6064 };
6065
6066 self.update_visible_inline_completion(window, cx);
6067 cx.notify();
6068 }
6069 } else if let EditPredictionPreview::Active {
6070 previous_scroll_position,
6071 since,
6072 } = self.edit_prediction_preview
6073 {
6074 if let (Some(previous_scroll_position), Some(position_map)) =
6075 (previous_scroll_position, self.last_position_map.as_ref())
6076 {
6077 self.set_scroll_position(
6078 previous_scroll_position
6079 .scroll_position(&position_map.snapshot.display_snapshot),
6080 window,
6081 cx,
6082 );
6083 }
6084
6085 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6086 released_too_fast: since.elapsed() < Duration::from_millis(200),
6087 };
6088 self.clear_row_highlights::<EditPredictionPreview>();
6089 self.update_visible_inline_completion(window, cx);
6090 cx.notify();
6091 }
6092 }
6093
6094 fn update_visible_inline_completion(
6095 &mut self,
6096 _window: &mut Window,
6097 cx: &mut Context<Self>,
6098 ) -> Option<()> {
6099 let selection = self.selections.newest_anchor();
6100 let cursor = selection.head();
6101 let multibuffer = self.buffer.read(cx).snapshot(cx);
6102 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6103 let excerpt_id = cursor.excerpt_id;
6104
6105 let show_in_menu = self.show_edit_predictions_in_menu();
6106 let completions_menu_has_precedence = !show_in_menu
6107 && (self.context_menu.borrow().is_some()
6108 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6109
6110 if completions_menu_has_precedence
6111 || !offset_selection.is_empty()
6112 || self
6113 .active_inline_completion
6114 .as_ref()
6115 .map_or(false, |completion| {
6116 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6117 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6118 !invalidation_range.contains(&offset_selection.head())
6119 })
6120 {
6121 self.discard_inline_completion(false, cx);
6122 return None;
6123 }
6124
6125 self.take_active_inline_completion(cx);
6126 let Some(provider) = self.edit_prediction_provider() else {
6127 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6128 return None;
6129 };
6130
6131 let (buffer, cursor_buffer_position) =
6132 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6133
6134 self.edit_prediction_settings =
6135 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6136
6137 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6138
6139 if self.edit_prediction_indent_conflict {
6140 let cursor_point = cursor.to_point(&multibuffer);
6141
6142 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6143
6144 if let Some((_, indent)) = indents.iter().next() {
6145 if indent.len == cursor_point.column {
6146 self.edit_prediction_indent_conflict = false;
6147 }
6148 }
6149 }
6150
6151 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6152 let edits = inline_completion
6153 .edits
6154 .into_iter()
6155 .flat_map(|(range, new_text)| {
6156 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6157 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6158 Some((start..end, new_text))
6159 })
6160 .collect::<Vec<_>>();
6161 if edits.is_empty() {
6162 return None;
6163 }
6164
6165 let first_edit_start = edits.first().unwrap().0.start;
6166 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6167 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6168
6169 let last_edit_end = edits.last().unwrap().0.end;
6170 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6171 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6172
6173 let cursor_row = cursor.to_point(&multibuffer).row;
6174
6175 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6176
6177 let mut inlay_ids = Vec::new();
6178 let invalidation_row_range;
6179 let move_invalidation_row_range = if cursor_row < edit_start_row {
6180 Some(cursor_row..edit_end_row)
6181 } else if cursor_row > edit_end_row {
6182 Some(edit_start_row..cursor_row)
6183 } else {
6184 None
6185 };
6186 let is_move =
6187 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6188 let completion = if is_move {
6189 invalidation_row_range =
6190 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6191 let target = first_edit_start;
6192 InlineCompletion::Move { target, snapshot }
6193 } else {
6194 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6195 && !self.inline_completions_hidden_for_vim_mode;
6196
6197 if show_completions_in_buffer {
6198 if edits
6199 .iter()
6200 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6201 {
6202 let mut inlays = Vec::new();
6203 for (range, new_text) in &edits {
6204 let inlay = Inlay::inline_completion(
6205 post_inc(&mut self.next_inlay_id),
6206 range.start,
6207 new_text.as_str(),
6208 );
6209 inlay_ids.push(inlay.id);
6210 inlays.push(inlay);
6211 }
6212
6213 self.splice_inlays(&[], inlays, cx);
6214 } else {
6215 let background_color = cx.theme().status().deleted_background;
6216 self.highlight_text::<InlineCompletionHighlight>(
6217 edits.iter().map(|(range, _)| range.clone()).collect(),
6218 HighlightStyle {
6219 background_color: Some(background_color),
6220 ..Default::default()
6221 },
6222 cx,
6223 );
6224 }
6225 }
6226
6227 invalidation_row_range = edit_start_row..edit_end_row;
6228
6229 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6230 if provider.show_tab_accept_marker() {
6231 EditDisplayMode::TabAccept
6232 } else {
6233 EditDisplayMode::Inline
6234 }
6235 } else {
6236 EditDisplayMode::DiffPopover
6237 };
6238
6239 InlineCompletion::Edit {
6240 edits,
6241 edit_preview: inline_completion.edit_preview,
6242 display_mode,
6243 snapshot,
6244 }
6245 };
6246
6247 let invalidation_range = multibuffer
6248 .anchor_before(Point::new(invalidation_row_range.start, 0))
6249 ..multibuffer.anchor_after(Point::new(
6250 invalidation_row_range.end,
6251 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6252 ));
6253
6254 self.stale_inline_completion_in_menu = None;
6255 self.active_inline_completion = Some(InlineCompletionState {
6256 inlay_ids,
6257 completion,
6258 completion_id: inline_completion.id,
6259 invalidation_range,
6260 });
6261
6262 cx.notify();
6263
6264 Some(())
6265 }
6266
6267 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6268 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6269 }
6270
6271 fn render_code_actions_indicator(
6272 &self,
6273 _style: &EditorStyle,
6274 row: DisplayRow,
6275 is_active: bool,
6276 breakpoint: Option<&(Anchor, Breakpoint)>,
6277 cx: &mut Context<Self>,
6278 ) -> Option<IconButton> {
6279 let color = Color::Muted;
6280 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6281 let show_tooltip = !self.context_menu_visible();
6282
6283 if self.available_code_actions.is_some() {
6284 Some(
6285 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6286 .shape(ui::IconButtonShape::Square)
6287 .icon_size(IconSize::XSmall)
6288 .icon_color(color)
6289 .toggle_state(is_active)
6290 .when(show_tooltip, |this| {
6291 this.tooltip({
6292 let focus_handle = self.focus_handle.clone();
6293 move |window, cx| {
6294 Tooltip::for_action_in(
6295 "Toggle Code Actions",
6296 &ToggleCodeActions {
6297 deployed_from_indicator: None,
6298 },
6299 &focus_handle,
6300 window,
6301 cx,
6302 )
6303 }
6304 })
6305 })
6306 .on_click(cx.listener(move |editor, _e, window, cx| {
6307 window.focus(&editor.focus_handle(cx));
6308 editor.toggle_code_actions(
6309 &ToggleCodeActions {
6310 deployed_from_indicator: Some(row),
6311 },
6312 window,
6313 cx,
6314 );
6315 }))
6316 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6317 editor.set_breakpoint_context_menu(
6318 row,
6319 position,
6320 event.down.position,
6321 window,
6322 cx,
6323 );
6324 })),
6325 )
6326 } else {
6327 None
6328 }
6329 }
6330
6331 fn clear_tasks(&mut self) {
6332 self.tasks.clear()
6333 }
6334
6335 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6336 if self.tasks.insert(key, value).is_some() {
6337 // This case should hopefully be rare, but just in case...
6338 log::error!(
6339 "multiple different run targets found on a single line, only the last target will be rendered"
6340 )
6341 }
6342 }
6343
6344 /// Get all display points of breakpoints that will be rendered within editor
6345 ///
6346 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6347 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6348 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6349 fn active_breakpoints(
6350 &self,
6351 range: Range<DisplayRow>,
6352 window: &mut Window,
6353 cx: &mut Context<Self>,
6354 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6355 let mut breakpoint_display_points = HashMap::default();
6356
6357 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6358 return breakpoint_display_points;
6359 };
6360
6361 let snapshot = self.snapshot(window, cx);
6362
6363 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6364 let Some(project) = self.project.as_ref() else {
6365 return breakpoint_display_points;
6366 };
6367
6368 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6369 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6370
6371 for (buffer_snapshot, range, excerpt_id) in
6372 multi_buffer_snapshot.range_to_buffer_ranges(range)
6373 {
6374 let Some(buffer) = project.read_with(cx, |this, cx| {
6375 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6376 }) else {
6377 continue;
6378 };
6379 let breakpoints = breakpoint_store.read(cx).breakpoints(
6380 &buffer,
6381 Some(
6382 buffer_snapshot.anchor_before(range.start)
6383 ..buffer_snapshot.anchor_after(range.end),
6384 ),
6385 buffer_snapshot,
6386 cx,
6387 );
6388 for (anchor, breakpoint) in breakpoints {
6389 let multi_buffer_anchor =
6390 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6391 let position = multi_buffer_anchor
6392 .to_point(&multi_buffer_snapshot)
6393 .to_display_point(&snapshot);
6394
6395 breakpoint_display_points
6396 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6397 }
6398 }
6399
6400 breakpoint_display_points
6401 }
6402
6403 fn breakpoint_context_menu(
6404 &self,
6405 anchor: Anchor,
6406 window: &mut Window,
6407 cx: &mut Context<Self>,
6408 ) -> Entity<ui::ContextMenu> {
6409 let weak_editor = cx.weak_entity();
6410 let focus_handle = self.focus_handle(cx);
6411
6412 let row = self
6413 .buffer
6414 .read(cx)
6415 .snapshot(cx)
6416 .summary_for_anchor::<Point>(&anchor)
6417 .row;
6418
6419 let breakpoint = self
6420 .breakpoint_at_row(row, window, cx)
6421 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6422
6423 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6424 "Edit Log Breakpoint"
6425 } else {
6426 "Set Log Breakpoint"
6427 };
6428
6429 let condition_breakpoint_msg = if breakpoint
6430 .as_ref()
6431 .is_some_and(|bp| bp.1.condition.is_some())
6432 {
6433 "Edit Condition Breakpoint"
6434 } else {
6435 "Set Condition Breakpoint"
6436 };
6437
6438 let hit_condition_breakpoint_msg = if breakpoint
6439 .as_ref()
6440 .is_some_and(|bp| bp.1.hit_condition.is_some())
6441 {
6442 "Edit Hit Condition Breakpoint"
6443 } else {
6444 "Set Hit Condition Breakpoint"
6445 };
6446
6447 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6448 "Unset Breakpoint"
6449 } else {
6450 "Set Breakpoint"
6451 };
6452
6453 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6454 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6455
6456 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6457 BreakpointState::Enabled => Some("Disable"),
6458 BreakpointState::Disabled => Some("Enable"),
6459 });
6460
6461 let (anchor, breakpoint) =
6462 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6463
6464 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6465 menu.on_blur_subscription(Subscription::new(|| {}))
6466 .context(focus_handle)
6467 .when(run_to_cursor, |this| {
6468 let weak_editor = weak_editor.clone();
6469 this.entry("Run to cursor", None, move |window, cx| {
6470 weak_editor
6471 .update(cx, |editor, cx| {
6472 editor.change_selections(None, window, cx, |s| {
6473 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6474 });
6475 })
6476 .ok();
6477
6478 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6479 })
6480 .separator()
6481 })
6482 .when_some(toggle_state_msg, |this, msg| {
6483 this.entry(msg, None, {
6484 let weak_editor = weak_editor.clone();
6485 let breakpoint = breakpoint.clone();
6486 move |_window, cx| {
6487 weak_editor
6488 .update(cx, |this, cx| {
6489 this.edit_breakpoint_at_anchor(
6490 anchor,
6491 breakpoint.as_ref().clone(),
6492 BreakpointEditAction::InvertState,
6493 cx,
6494 );
6495 })
6496 .log_err();
6497 }
6498 })
6499 })
6500 .entry(set_breakpoint_msg, None, {
6501 let weak_editor = weak_editor.clone();
6502 let breakpoint = breakpoint.clone();
6503 move |_window, cx| {
6504 weak_editor
6505 .update(cx, |this, cx| {
6506 this.edit_breakpoint_at_anchor(
6507 anchor,
6508 breakpoint.as_ref().clone(),
6509 BreakpointEditAction::Toggle,
6510 cx,
6511 );
6512 })
6513 .log_err();
6514 }
6515 })
6516 .entry(log_breakpoint_msg, None, {
6517 let breakpoint = breakpoint.clone();
6518 let weak_editor = weak_editor.clone();
6519 move |window, cx| {
6520 weak_editor
6521 .update(cx, |this, cx| {
6522 this.add_edit_breakpoint_block(
6523 anchor,
6524 breakpoint.as_ref(),
6525 BreakpointPromptEditAction::Log,
6526 window,
6527 cx,
6528 );
6529 })
6530 .log_err();
6531 }
6532 })
6533 .entry(condition_breakpoint_msg, None, {
6534 let breakpoint = breakpoint.clone();
6535 let weak_editor = weak_editor.clone();
6536 move |window, cx| {
6537 weak_editor
6538 .update(cx, |this, cx| {
6539 this.add_edit_breakpoint_block(
6540 anchor,
6541 breakpoint.as_ref(),
6542 BreakpointPromptEditAction::Condition,
6543 window,
6544 cx,
6545 );
6546 })
6547 .log_err();
6548 }
6549 })
6550 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6551 weak_editor
6552 .update(cx, |this, cx| {
6553 this.add_edit_breakpoint_block(
6554 anchor,
6555 breakpoint.as_ref(),
6556 BreakpointPromptEditAction::HitCondition,
6557 window,
6558 cx,
6559 );
6560 })
6561 .log_err();
6562 })
6563 })
6564 }
6565
6566 fn render_breakpoint(
6567 &self,
6568 position: Anchor,
6569 row: DisplayRow,
6570 breakpoint: &Breakpoint,
6571 cx: &mut Context<Self>,
6572 ) -> IconButton {
6573 let (color, icon) = {
6574 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6575 (false, false) => ui::IconName::DebugBreakpoint,
6576 (true, false) => ui::IconName::DebugLogBreakpoint,
6577 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6578 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6579 };
6580
6581 let color = if self
6582 .gutter_breakpoint_indicator
6583 .0
6584 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6585 {
6586 Color::Hint
6587 } else {
6588 Color::Debugger
6589 };
6590
6591 (color, icon)
6592 };
6593
6594 let breakpoint = Arc::from(breakpoint.clone());
6595
6596 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6597 .icon_size(IconSize::XSmall)
6598 .size(ui::ButtonSize::None)
6599 .icon_color(color)
6600 .style(ButtonStyle::Transparent)
6601 .on_click(cx.listener({
6602 let breakpoint = breakpoint.clone();
6603
6604 move |editor, event: &ClickEvent, window, cx| {
6605 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6606 BreakpointEditAction::InvertState
6607 } else {
6608 BreakpointEditAction::Toggle
6609 };
6610
6611 window.focus(&editor.focus_handle(cx));
6612 editor.edit_breakpoint_at_anchor(
6613 position,
6614 breakpoint.as_ref().clone(),
6615 edit_action,
6616 cx,
6617 );
6618 }
6619 }))
6620 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6621 editor.set_breakpoint_context_menu(
6622 row,
6623 Some(position),
6624 event.down.position,
6625 window,
6626 cx,
6627 );
6628 }))
6629 }
6630
6631 fn build_tasks_context(
6632 project: &Entity<Project>,
6633 buffer: &Entity<Buffer>,
6634 buffer_row: u32,
6635 tasks: &Arc<RunnableTasks>,
6636 cx: &mut Context<Self>,
6637 ) -> Task<Option<task::TaskContext>> {
6638 let position = Point::new(buffer_row, tasks.column);
6639 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6640 let location = Location {
6641 buffer: buffer.clone(),
6642 range: range_start..range_start,
6643 };
6644 // Fill in the environmental variables from the tree-sitter captures
6645 let mut captured_task_variables = TaskVariables::default();
6646 for (capture_name, value) in tasks.extra_variables.clone() {
6647 captured_task_variables.insert(
6648 task::VariableName::Custom(capture_name.into()),
6649 value.clone(),
6650 );
6651 }
6652 project.update(cx, |project, cx| {
6653 project.task_store().update(cx, |task_store, cx| {
6654 task_store.task_context_for_location(captured_task_variables, location, cx)
6655 })
6656 })
6657 }
6658
6659 pub fn spawn_nearest_task(
6660 &mut self,
6661 action: &SpawnNearestTask,
6662 window: &mut Window,
6663 cx: &mut Context<Self>,
6664 ) {
6665 let Some((workspace, _)) = self.workspace.clone() else {
6666 return;
6667 };
6668 let Some(project) = self.project.clone() else {
6669 return;
6670 };
6671
6672 // Try to find a closest, enclosing node using tree-sitter that has a
6673 // task
6674 let Some((buffer, buffer_row, tasks)) = self
6675 .find_enclosing_node_task(cx)
6676 // Or find the task that's closest in row-distance.
6677 .or_else(|| self.find_closest_task(cx))
6678 else {
6679 return;
6680 };
6681
6682 let reveal_strategy = action.reveal;
6683 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6684 cx.spawn_in(window, async move |_, cx| {
6685 let context = task_context.await?;
6686 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6687
6688 let resolved = resolved_task.resolved.as_mut()?;
6689 resolved.reveal = reveal_strategy;
6690
6691 workspace
6692 .update(cx, |workspace, cx| {
6693 workspace::tasks::schedule_resolved_task(
6694 workspace,
6695 task_source_kind,
6696 resolved_task,
6697 false,
6698 cx,
6699 );
6700 })
6701 .ok()
6702 })
6703 .detach();
6704 }
6705
6706 fn find_closest_task(
6707 &mut self,
6708 cx: &mut Context<Self>,
6709 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6710 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6711
6712 let ((buffer_id, row), tasks) = self
6713 .tasks
6714 .iter()
6715 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6716
6717 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6718 let tasks = Arc::new(tasks.to_owned());
6719 Some((buffer, *row, tasks))
6720 }
6721
6722 fn find_enclosing_node_task(
6723 &mut self,
6724 cx: &mut Context<Self>,
6725 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6726 let snapshot = self.buffer.read(cx).snapshot(cx);
6727 let offset = self.selections.newest::<usize>(cx).head();
6728 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6729 let buffer_id = excerpt.buffer().remote_id();
6730
6731 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6732 let mut cursor = layer.node().walk();
6733
6734 while cursor.goto_first_child_for_byte(offset).is_some() {
6735 if cursor.node().end_byte() == offset {
6736 cursor.goto_next_sibling();
6737 }
6738 }
6739
6740 // Ascend to the smallest ancestor that contains the range and has a task.
6741 loop {
6742 let node = cursor.node();
6743 let node_range = node.byte_range();
6744 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6745
6746 // Check if this node contains our offset
6747 if node_range.start <= offset && node_range.end >= offset {
6748 // If it contains offset, check for task
6749 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6750 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6751 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6752 }
6753 }
6754
6755 if !cursor.goto_parent() {
6756 break;
6757 }
6758 }
6759 None
6760 }
6761
6762 fn render_run_indicator(
6763 &self,
6764 _style: &EditorStyle,
6765 is_active: bool,
6766 row: DisplayRow,
6767 breakpoint: Option<(Anchor, Breakpoint)>,
6768 cx: &mut Context<Self>,
6769 ) -> IconButton {
6770 let color = Color::Muted;
6771 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6772
6773 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6774 .shape(ui::IconButtonShape::Square)
6775 .icon_size(IconSize::XSmall)
6776 .icon_color(color)
6777 .toggle_state(is_active)
6778 .on_click(cx.listener(move |editor, _e, window, cx| {
6779 window.focus(&editor.focus_handle(cx));
6780 editor.toggle_code_actions(
6781 &ToggleCodeActions {
6782 deployed_from_indicator: Some(row),
6783 },
6784 window,
6785 cx,
6786 );
6787 }))
6788 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6789 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6790 }))
6791 }
6792
6793 pub fn context_menu_visible(&self) -> bool {
6794 !self.edit_prediction_preview_is_active()
6795 && self
6796 .context_menu
6797 .borrow()
6798 .as_ref()
6799 .map_or(false, |menu| menu.visible())
6800 }
6801
6802 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6803 self.context_menu
6804 .borrow()
6805 .as_ref()
6806 .map(|menu| menu.origin())
6807 }
6808
6809 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6810 self.context_menu_options = Some(options);
6811 }
6812
6813 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6814 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6815
6816 fn render_edit_prediction_popover(
6817 &mut self,
6818 text_bounds: &Bounds<Pixels>,
6819 content_origin: gpui::Point<Pixels>,
6820 editor_snapshot: &EditorSnapshot,
6821 visible_row_range: Range<DisplayRow>,
6822 scroll_top: f32,
6823 scroll_bottom: f32,
6824 line_layouts: &[LineWithInvisibles],
6825 line_height: Pixels,
6826 scroll_pixel_position: gpui::Point<Pixels>,
6827 newest_selection_head: Option<DisplayPoint>,
6828 editor_width: Pixels,
6829 style: &EditorStyle,
6830 window: &mut Window,
6831 cx: &mut App,
6832 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6833 let active_inline_completion = self.active_inline_completion.as_ref()?;
6834
6835 if self.edit_prediction_visible_in_cursor_popover(true) {
6836 return None;
6837 }
6838
6839 match &active_inline_completion.completion {
6840 InlineCompletion::Move { target, .. } => {
6841 let target_display_point = target.to_display_point(editor_snapshot);
6842
6843 if self.edit_prediction_requires_modifier() {
6844 if !self.edit_prediction_preview_is_active() {
6845 return None;
6846 }
6847
6848 self.render_edit_prediction_modifier_jump_popover(
6849 text_bounds,
6850 content_origin,
6851 visible_row_range,
6852 line_layouts,
6853 line_height,
6854 scroll_pixel_position,
6855 newest_selection_head,
6856 target_display_point,
6857 window,
6858 cx,
6859 )
6860 } else {
6861 self.render_edit_prediction_eager_jump_popover(
6862 text_bounds,
6863 content_origin,
6864 editor_snapshot,
6865 visible_row_range,
6866 scroll_top,
6867 scroll_bottom,
6868 line_height,
6869 scroll_pixel_position,
6870 target_display_point,
6871 editor_width,
6872 window,
6873 cx,
6874 )
6875 }
6876 }
6877 InlineCompletion::Edit {
6878 display_mode: EditDisplayMode::Inline,
6879 ..
6880 } => None,
6881 InlineCompletion::Edit {
6882 display_mode: EditDisplayMode::TabAccept,
6883 edits,
6884 ..
6885 } => {
6886 let range = &edits.first()?.0;
6887 let target_display_point = range.end.to_display_point(editor_snapshot);
6888
6889 self.render_edit_prediction_end_of_line_popover(
6890 "Accept",
6891 editor_snapshot,
6892 visible_row_range,
6893 target_display_point,
6894 line_height,
6895 scroll_pixel_position,
6896 content_origin,
6897 editor_width,
6898 window,
6899 cx,
6900 )
6901 }
6902 InlineCompletion::Edit {
6903 edits,
6904 edit_preview,
6905 display_mode: EditDisplayMode::DiffPopover,
6906 snapshot,
6907 } => self.render_edit_prediction_diff_popover(
6908 text_bounds,
6909 content_origin,
6910 editor_snapshot,
6911 visible_row_range,
6912 line_layouts,
6913 line_height,
6914 scroll_pixel_position,
6915 newest_selection_head,
6916 editor_width,
6917 style,
6918 edits,
6919 edit_preview,
6920 snapshot,
6921 window,
6922 cx,
6923 ),
6924 }
6925 }
6926
6927 fn render_edit_prediction_modifier_jump_popover(
6928 &mut self,
6929 text_bounds: &Bounds<Pixels>,
6930 content_origin: gpui::Point<Pixels>,
6931 visible_row_range: Range<DisplayRow>,
6932 line_layouts: &[LineWithInvisibles],
6933 line_height: Pixels,
6934 scroll_pixel_position: gpui::Point<Pixels>,
6935 newest_selection_head: Option<DisplayPoint>,
6936 target_display_point: DisplayPoint,
6937 window: &mut Window,
6938 cx: &mut App,
6939 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6940 let scrolled_content_origin =
6941 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6942
6943 const SCROLL_PADDING_Y: Pixels = px(12.);
6944
6945 if target_display_point.row() < visible_row_range.start {
6946 return self.render_edit_prediction_scroll_popover(
6947 |_| SCROLL_PADDING_Y,
6948 IconName::ArrowUp,
6949 visible_row_range,
6950 line_layouts,
6951 newest_selection_head,
6952 scrolled_content_origin,
6953 window,
6954 cx,
6955 );
6956 } else if target_display_point.row() >= visible_row_range.end {
6957 return self.render_edit_prediction_scroll_popover(
6958 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6959 IconName::ArrowDown,
6960 visible_row_range,
6961 line_layouts,
6962 newest_selection_head,
6963 scrolled_content_origin,
6964 window,
6965 cx,
6966 );
6967 }
6968
6969 const POLE_WIDTH: Pixels = px(2.);
6970
6971 let line_layout =
6972 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6973 let target_column = target_display_point.column() as usize;
6974
6975 let target_x = line_layout.x_for_index(target_column);
6976 let target_y =
6977 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6978
6979 let flag_on_right = target_x < text_bounds.size.width / 2.;
6980
6981 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6982 border_color.l += 0.001;
6983
6984 let mut element = v_flex()
6985 .items_end()
6986 .when(flag_on_right, |el| el.items_start())
6987 .child(if flag_on_right {
6988 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6989 .rounded_bl(px(0.))
6990 .rounded_tl(px(0.))
6991 .border_l_2()
6992 .border_color(border_color)
6993 } else {
6994 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6995 .rounded_br(px(0.))
6996 .rounded_tr(px(0.))
6997 .border_r_2()
6998 .border_color(border_color)
6999 })
7000 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7001 .into_any();
7002
7003 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7004
7005 let mut origin = scrolled_content_origin + point(target_x, target_y)
7006 - point(
7007 if flag_on_right {
7008 POLE_WIDTH
7009 } else {
7010 size.width - POLE_WIDTH
7011 },
7012 size.height - line_height,
7013 );
7014
7015 origin.x = origin.x.max(content_origin.x);
7016
7017 element.prepaint_at(origin, window, cx);
7018
7019 Some((element, origin))
7020 }
7021
7022 fn render_edit_prediction_scroll_popover(
7023 &mut self,
7024 to_y: impl Fn(Size<Pixels>) -> Pixels,
7025 scroll_icon: IconName,
7026 visible_row_range: Range<DisplayRow>,
7027 line_layouts: &[LineWithInvisibles],
7028 newest_selection_head: Option<DisplayPoint>,
7029 scrolled_content_origin: gpui::Point<Pixels>,
7030 window: &mut Window,
7031 cx: &mut App,
7032 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7033 let mut element = self
7034 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7035 .into_any();
7036
7037 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7038
7039 let cursor = newest_selection_head?;
7040 let cursor_row_layout =
7041 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7042 let cursor_column = cursor.column() as usize;
7043
7044 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7045
7046 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7047
7048 element.prepaint_at(origin, window, cx);
7049 Some((element, origin))
7050 }
7051
7052 fn render_edit_prediction_eager_jump_popover(
7053 &mut self,
7054 text_bounds: &Bounds<Pixels>,
7055 content_origin: gpui::Point<Pixels>,
7056 editor_snapshot: &EditorSnapshot,
7057 visible_row_range: Range<DisplayRow>,
7058 scroll_top: f32,
7059 scroll_bottom: f32,
7060 line_height: Pixels,
7061 scroll_pixel_position: gpui::Point<Pixels>,
7062 target_display_point: DisplayPoint,
7063 editor_width: Pixels,
7064 window: &mut Window,
7065 cx: &mut App,
7066 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7067 if target_display_point.row().as_f32() < scroll_top {
7068 let mut element = self
7069 .render_edit_prediction_line_popover(
7070 "Jump to Edit",
7071 Some(IconName::ArrowUp),
7072 window,
7073 cx,
7074 )?
7075 .into_any();
7076
7077 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7078 let offset = point(
7079 (text_bounds.size.width - size.width) / 2.,
7080 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7081 );
7082
7083 let origin = text_bounds.origin + offset;
7084 element.prepaint_at(origin, window, cx);
7085 Some((element, origin))
7086 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7087 let mut element = self
7088 .render_edit_prediction_line_popover(
7089 "Jump to Edit",
7090 Some(IconName::ArrowDown),
7091 window,
7092 cx,
7093 )?
7094 .into_any();
7095
7096 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7097 let offset = point(
7098 (text_bounds.size.width - size.width) / 2.,
7099 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7100 );
7101
7102 let origin = text_bounds.origin + offset;
7103 element.prepaint_at(origin, window, cx);
7104 Some((element, origin))
7105 } else {
7106 self.render_edit_prediction_end_of_line_popover(
7107 "Jump to Edit",
7108 editor_snapshot,
7109 visible_row_range,
7110 target_display_point,
7111 line_height,
7112 scroll_pixel_position,
7113 content_origin,
7114 editor_width,
7115 window,
7116 cx,
7117 )
7118 }
7119 }
7120
7121 fn render_edit_prediction_end_of_line_popover(
7122 self: &mut Editor,
7123 label: &'static str,
7124 editor_snapshot: &EditorSnapshot,
7125 visible_row_range: Range<DisplayRow>,
7126 target_display_point: DisplayPoint,
7127 line_height: Pixels,
7128 scroll_pixel_position: gpui::Point<Pixels>,
7129 content_origin: gpui::Point<Pixels>,
7130 editor_width: Pixels,
7131 window: &mut Window,
7132 cx: &mut App,
7133 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7134 let target_line_end = DisplayPoint::new(
7135 target_display_point.row(),
7136 editor_snapshot.line_len(target_display_point.row()),
7137 );
7138
7139 let mut element = self
7140 .render_edit_prediction_line_popover(label, None, window, cx)?
7141 .into_any();
7142
7143 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7144
7145 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7146
7147 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7148 let mut origin = start_point
7149 + line_origin
7150 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7151 origin.x = origin.x.max(content_origin.x);
7152
7153 let max_x = content_origin.x + editor_width - size.width;
7154
7155 if origin.x > max_x {
7156 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7157
7158 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7159 origin.y += offset;
7160 IconName::ArrowUp
7161 } else {
7162 origin.y -= offset;
7163 IconName::ArrowDown
7164 };
7165
7166 element = self
7167 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7168 .into_any();
7169
7170 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7171
7172 origin.x = content_origin.x + editor_width - size.width - px(2.);
7173 }
7174
7175 element.prepaint_at(origin, window, cx);
7176 Some((element, origin))
7177 }
7178
7179 fn render_edit_prediction_diff_popover(
7180 self: &Editor,
7181 text_bounds: &Bounds<Pixels>,
7182 content_origin: gpui::Point<Pixels>,
7183 editor_snapshot: &EditorSnapshot,
7184 visible_row_range: Range<DisplayRow>,
7185 line_layouts: &[LineWithInvisibles],
7186 line_height: Pixels,
7187 scroll_pixel_position: gpui::Point<Pixels>,
7188 newest_selection_head: Option<DisplayPoint>,
7189 editor_width: Pixels,
7190 style: &EditorStyle,
7191 edits: &Vec<(Range<Anchor>, String)>,
7192 edit_preview: &Option<language::EditPreview>,
7193 snapshot: &language::BufferSnapshot,
7194 window: &mut Window,
7195 cx: &mut App,
7196 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7197 let edit_start = edits
7198 .first()
7199 .unwrap()
7200 .0
7201 .start
7202 .to_display_point(editor_snapshot);
7203 let edit_end = edits
7204 .last()
7205 .unwrap()
7206 .0
7207 .end
7208 .to_display_point(editor_snapshot);
7209
7210 let is_visible = visible_row_range.contains(&edit_start.row())
7211 || visible_row_range.contains(&edit_end.row());
7212 if !is_visible {
7213 return None;
7214 }
7215
7216 let highlighted_edits =
7217 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7218
7219 let styled_text = highlighted_edits.to_styled_text(&style.text);
7220 let line_count = highlighted_edits.text.lines().count();
7221
7222 const BORDER_WIDTH: Pixels = px(1.);
7223
7224 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7225 let has_keybind = keybind.is_some();
7226
7227 let mut element = h_flex()
7228 .items_start()
7229 .child(
7230 h_flex()
7231 .bg(cx.theme().colors().editor_background)
7232 .border(BORDER_WIDTH)
7233 .shadow_sm()
7234 .border_color(cx.theme().colors().border)
7235 .rounded_l_lg()
7236 .when(line_count > 1, |el| el.rounded_br_lg())
7237 .pr_1()
7238 .child(styled_text),
7239 )
7240 .child(
7241 h_flex()
7242 .h(line_height + BORDER_WIDTH * 2.)
7243 .px_1p5()
7244 .gap_1()
7245 // Workaround: For some reason, there's a gap if we don't do this
7246 .ml(-BORDER_WIDTH)
7247 .shadow(smallvec![gpui::BoxShadow {
7248 color: gpui::black().opacity(0.05),
7249 offset: point(px(1.), px(1.)),
7250 blur_radius: px(2.),
7251 spread_radius: px(0.),
7252 }])
7253 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7254 .border(BORDER_WIDTH)
7255 .border_color(cx.theme().colors().border)
7256 .rounded_r_lg()
7257 .id("edit_prediction_diff_popover_keybind")
7258 .when(!has_keybind, |el| {
7259 let status_colors = cx.theme().status();
7260
7261 el.bg(status_colors.error_background)
7262 .border_color(status_colors.error.opacity(0.6))
7263 .child(Icon::new(IconName::Info).color(Color::Error))
7264 .cursor_default()
7265 .hoverable_tooltip(move |_window, cx| {
7266 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7267 })
7268 })
7269 .children(keybind),
7270 )
7271 .into_any();
7272
7273 let longest_row =
7274 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7275 let longest_line_width = if visible_row_range.contains(&longest_row) {
7276 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7277 } else {
7278 layout_line(
7279 longest_row,
7280 editor_snapshot,
7281 style,
7282 editor_width,
7283 |_| false,
7284 window,
7285 cx,
7286 )
7287 .width
7288 };
7289
7290 let viewport_bounds =
7291 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7292 right: -EditorElement::SCROLLBAR_WIDTH,
7293 ..Default::default()
7294 });
7295
7296 let x_after_longest =
7297 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7298 - scroll_pixel_position.x;
7299
7300 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7301
7302 // Fully visible if it can be displayed within the window (allow overlapping other
7303 // panes). However, this is only allowed if the popover starts within text_bounds.
7304 let can_position_to_the_right = x_after_longest < text_bounds.right()
7305 && x_after_longest + element_bounds.width < viewport_bounds.right();
7306
7307 let mut origin = if can_position_to_the_right {
7308 point(
7309 x_after_longest,
7310 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7311 - scroll_pixel_position.y,
7312 )
7313 } else {
7314 let cursor_row = newest_selection_head.map(|head| head.row());
7315 let above_edit = edit_start
7316 .row()
7317 .0
7318 .checked_sub(line_count as u32)
7319 .map(DisplayRow);
7320 let below_edit = Some(edit_end.row() + 1);
7321 let above_cursor =
7322 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7323 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7324
7325 // Place the edit popover adjacent to the edit if there is a location
7326 // available that is onscreen and does not obscure the cursor. Otherwise,
7327 // place it adjacent to the cursor.
7328 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7329 .into_iter()
7330 .flatten()
7331 .find(|&start_row| {
7332 let end_row = start_row + line_count as u32;
7333 visible_row_range.contains(&start_row)
7334 && visible_row_range.contains(&end_row)
7335 && cursor_row.map_or(true, |cursor_row| {
7336 !((start_row..end_row).contains(&cursor_row))
7337 })
7338 })?;
7339
7340 content_origin
7341 + point(
7342 -scroll_pixel_position.x,
7343 row_target.as_f32() * line_height - scroll_pixel_position.y,
7344 )
7345 };
7346
7347 origin.x -= BORDER_WIDTH;
7348
7349 window.defer_draw(element, origin, 1);
7350
7351 // Do not return an element, since it will already be drawn due to defer_draw.
7352 None
7353 }
7354
7355 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7356 px(30.)
7357 }
7358
7359 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7360 if self.read_only(cx) {
7361 cx.theme().players().read_only()
7362 } else {
7363 self.style.as_ref().unwrap().local_player
7364 }
7365 }
7366
7367 fn render_edit_prediction_accept_keybind(
7368 &self,
7369 window: &mut Window,
7370 cx: &App,
7371 ) -> Option<AnyElement> {
7372 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7373 let accept_keystroke = accept_binding.keystroke()?;
7374
7375 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7376
7377 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7378 Color::Accent
7379 } else {
7380 Color::Muted
7381 };
7382
7383 h_flex()
7384 .px_0p5()
7385 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7386 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7387 .text_size(TextSize::XSmall.rems(cx))
7388 .child(h_flex().children(ui::render_modifiers(
7389 &accept_keystroke.modifiers,
7390 PlatformStyle::platform(),
7391 Some(modifiers_color),
7392 Some(IconSize::XSmall.rems().into()),
7393 true,
7394 )))
7395 .when(is_platform_style_mac, |parent| {
7396 parent.child(accept_keystroke.key.clone())
7397 })
7398 .when(!is_platform_style_mac, |parent| {
7399 parent.child(
7400 Key::new(
7401 util::capitalize(&accept_keystroke.key),
7402 Some(Color::Default),
7403 )
7404 .size(Some(IconSize::XSmall.rems().into())),
7405 )
7406 })
7407 .into_any()
7408 .into()
7409 }
7410
7411 fn render_edit_prediction_line_popover(
7412 &self,
7413 label: impl Into<SharedString>,
7414 icon: Option<IconName>,
7415 window: &mut Window,
7416 cx: &App,
7417 ) -> Option<Stateful<Div>> {
7418 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7419
7420 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7421 let has_keybind = keybind.is_some();
7422
7423 let result = h_flex()
7424 .id("ep-line-popover")
7425 .py_0p5()
7426 .pl_1()
7427 .pr(padding_right)
7428 .gap_1()
7429 .rounded_md()
7430 .border_1()
7431 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7432 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7433 .shadow_sm()
7434 .when(!has_keybind, |el| {
7435 let status_colors = cx.theme().status();
7436
7437 el.bg(status_colors.error_background)
7438 .border_color(status_colors.error.opacity(0.6))
7439 .pl_2()
7440 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7441 .cursor_default()
7442 .hoverable_tooltip(move |_window, cx| {
7443 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7444 })
7445 })
7446 .children(keybind)
7447 .child(
7448 Label::new(label)
7449 .size(LabelSize::Small)
7450 .when(!has_keybind, |el| {
7451 el.color(cx.theme().status().error.into()).strikethrough()
7452 }),
7453 )
7454 .when(!has_keybind, |el| {
7455 el.child(
7456 h_flex().ml_1().child(
7457 Icon::new(IconName::Info)
7458 .size(IconSize::Small)
7459 .color(cx.theme().status().error.into()),
7460 ),
7461 )
7462 })
7463 .when_some(icon, |element, icon| {
7464 element.child(
7465 div()
7466 .mt(px(1.5))
7467 .child(Icon::new(icon).size(IconSize::Small)),
7468 )
7469 });
7470
7471 Some(result)
7472 }
7473
7474 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7475 let accent_color = cx.theme().colors().text_accent;
7476 let editor_bg_color = cx.theme().colors().editor_background;
7477 editor_bg_color.blend(accent_color.opacity(0.1))
7478 }
7479
7480 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7481 let accent_color = cx.theme().colors().text_accent;
7482 let editor_bg_color = cx.theme().colors().editor_background;
7483 editor_bg_color.blend(accent_color.opacity(0.6))
7484 }
7485
7486 fn render_edit_prediction_cursor_popover(
7487 &self,
7488 min_width: Pixels,
7489 max_width: Pixels,
7490 cursor_point: Point,
7491 style: &EditorStyle,
7492 accept_keystroke: Option<&gpui::Keystroke>,
7493 _window: &Window,
7494 cx: &mut Context<Editor>,
7495 ) -> Option<AnyElement> {
7496 let provider = self.edit_prediction_provider.as_ref()?;
7497
7498 if provider.provider.needs_terms_acceptance(cx) {
7499 return Some(
7500 h_flex()
7501 .min_w(min_width)
7502 .flex_1()
7503 .px_2()
7504 .py_1()
7505 .gap_3()
7506 .elevation_2(cx)
7507 .hover(|style| style.bg(cx.theme().colors().element_hover))
7508 .id("accept-terms")
7509 .cursor_pointer()
7510 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7511 .on_click(cx.listener(|this, _event, window, cx| {
7512 cx.stop_propagation();
7513 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7514 window.dispatch_action(
7515 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7516 cx,
7517 );
7518 }))
7519 .child(
7520 h_flex()
7521 .flex_1()
7522 .gap_2()
7523 .child(Icon::new(IconName::ZedPredict))
7524 .child(Label::new("Accept Terms of Service"))
7525 .child(div().w_full())
7526 .child(
7527 Icon::new(IconName::ArrowUpRight)
7528 .color(Color::Muted)
7529 .size(IconSize::Small),
7530 )
7531 .into_any_element(),
7532 )
7533 .into_any(),
7534 );
7535 }
7536
7537 let is_refreshing = provider.provider.is_refreshing(cx);
7538
7539 fn pending_completion_container() -> Div {
7540 h_flex()
7541 .h_full()
7542 .flex_1()
7543 .gap_2()
7544 .child(Icon::new(IconName::ZedPredict))
7545 }
7546
7547 let completion = match &self.active_inline_completion {
7548 Some(prediction) => {
7549 if !self.has_visible_completions_menu() {
7550 const RADIUS: Pixels = px(6.);
7551 const BORDER_WIDTH: Pixels = px(1.);
7552
7553 return Some(
7554 h_flex()
7555 .elevation_2(cx)
7556 .border(BORDER_WIDTH)
7557 .border_color(cx.theme().colors().border)
7558 .when(accept_keystroke.is_none(), |el| {
7559 el.border_color(cx.theme().status().error)
7560 })
7561 .rounded(RADIUS)
7562 .rounded_tl(px(0.))
7563 .overflow_hidden()
7564 .child(div().px_1p5().child(match &prediction.completion {
7565 InlineCompletion::Move { target, snapshot } => {
7566 use text::ToPoint as _;
7567 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7568 {
7569 Icon::new(IconName::ZedPredictDown)
7570 } else {
7571 Icon::new(IconName::ZedPredictUp)
7572 }
7573 }
7574 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7575 }))
7576 .child(
7577 h_flex()
7578 .gap_1()
7579 .py_1()
7580 .px_2()
7581 .rounded_r(RADIUS - BORDER_WIDTH)
7582 .border_l_1()
7583 .border_color(cx.theme().colors().border)
7584 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7585 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7586 el.child(
7587 Label::new("Hold")
7588 .size(LabelSize::Small)
7589 .when(accept_keystroke.is_none(), |el| {
7590 el.strikethrough()
7591 })
7592 .line_height_style(LineHeightStyle::UiLabel),
7593 )
7594 })
7595 .id("edit_prediction_cursor_popover_keybind")
7596 .when(accept_keystroke.is_none(), |el| {
7597 let status_colors = cx.theme().status();
7598
7599 el.bg(status_colors.error_background)
7600 .border_color(status_colors.error.opacity(0.6))
7601 .child(Icon::new(IconName::Info).color(Color::Error))
7602 .cursor_default()
7603 .hoverable_tooltip(move |_window, cx| {
7604 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7605 .into()
7606 })
7607 })
7608 .when_some(
7609 accept_keystroke.as_ref(),
7610 |el, accept_keystroke| {
7611 el.child(h_flex().children(ui::render_modifiers(
7612 &accept_keystroke.modifiers,
7613 PlatformStyle::platform(),
7614 Some(Color::Default),
7615 Some(IconSize::XSmall.rems().into()),
7616 false,
7617 )))
7618 },
7619 ),
7620 )
7621 .into_any(),
7622 );
7623 }
7624
7625 self.render_edit_prediction_cursor_popover_preview(
7626 prediction,
7627 cursor_point,
7628 style,
7629 cx,
7630 )?
7631 }
7632
7633 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7634 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7635 stale_completion,
7636 cursor_point,
7637 style,
7638 cx,
7639 )?,
7640
7641 None => {
7642 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7643 }
7644 },
7645
7646 None => pending_completion_container().child(Label::new("No Prediction")),
7647 };
7648
7649 let completion = if is_refreshing {
7650 completion
7651 .with_animation(
7652 "loading-completion",
7653 Animation::new(Duration::from_secs(2))
7654 .repeat()
7655 .with_easing(pulsating_between(0.4, 0.8)),
7656 |label, delta| label.opacity(delta),
7657 )
7658 .into_any_element()
7659 } else {
7660 completion.into_any_element()
7661 };
7662
7663 let has_completion = self.active_inline_completion.is_some();
7664
7665 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7666 Some(
7667 h_flex()
7668 .min_w(min_width)
7669 .max_w(max_width)
7670 .flex_1()
7671 .elevation_2(cx)
7672 .border_color(cx.theme().colors().border)
7673 .child(
7674 div()
7675 .flex_1()
7676 .py_1()
7677 .px_2()
7678 .overflow_hidden()
7679 .child(completion),
7680 )
7681 .when_some(accept_keystroke, |el, accept_keystroke| {
7682 if !accept_keystroke.modifiers.modified() {
7683 return el;
7684 }
7685
7686 el.child(
7687 h_flex()
7688 .h_full()
7689 .border_l_1()
7690 .rounded_r_lg()
7691 .border_color(cx.theme().colors().border)
7692 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7693 .gap_1()
7694 .py_1()
7695 .px_2()
7696 .child(
7697 h_flex()
7698 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7699 .when(is_platform_style_mac, |parent| parent.gap_1())
7700 .child(h_flex().children(ui::render_modifiers(
7701 &accept_keystroke.modifiers,
7702 PlatformStyle::platform(),
7703 Some(if !has_completion {
7704 Color::Muted
7705 } else {
7706 Color::Default
7707 }),
7708 None,
7709 false,
7710 ))),
7711 )
7712 .child(Label::new("Preview").into_any_element())
7713 .opacity(if has_completion { 1.0 } else { 0.4 }),
7714 )
7715 })
7716 .into_any(),
7717 )
7718 }
7719
7720 fn render_edit_prediction_cursor_popover_preview(
7721 &self,
7722 completion: &InlineCompletionState,
7723 cursor_point: Point,
7724 style: &EditorStyle,
7725 cx: &mut Context<Editor>,
7726 ) -> Option<Div> {
7727 use text::ToPoint as _;
7728
7729 fn render_relative_row_jump(
7730 prefix: impl Into<String>,
7731 current_row: u32,
7732 target_row: u32,
7733 ) -> Div {
7734 let (row_diff, arrow) = if target_row < current_row {
7735 (current_row - target_row, IconName::ArrowUp)
7736 } else {
7737 (target_row - current_row, IconName::ArrowDown)
7738 };
7739
7740 h_flex()
7741 .child(
7742 Label::new(format!("{}{}", prefix.into(), row_diff))
7743 .color(Color::Muted)
7744 .size(LabelSize::Small),
7745 )
7746 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7747 }
7748
7749 match &completion.completion {
7750 InlineCompletion::Move {
7751 target, snapshot, ..
7752 } => Some(
7753 h_flex()
7754 .px_2()
7755 .gap_2()
7756 .flex_1()
7757 .child(
7758 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7759 Icon::new(IconName::ZedPredictDown)
7760 } else {
7761 Icon::new(IconName::ZedPredictUp)
7762 },
7763 )
7764 .child(Label::new("Jump to Edit")),
7765 ),
7766
7767 InlineCompletion::Edit {
7768 edits,
7769 edit_preview,
7770 snapshot,
7771 display_mode: _,
7772 } => {
7773 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7774
7775 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7776 &snapshot,
7777 &edits,
7778 edit_preview.as_ref()?,
7779 true,
7780 cx,
7781 )
7782 .first_line_preview();
7783
7784 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7785 .with_default_highlights(&style.text, highlighted_edits.highlights);
7786
7787 let preview = h_flex()
7788 .gap_1()
7789 .min_w_16()
7790 .child(styled_text)
7791 .when(has_more_lines, |parent| parent.child("…"));
7792
7793 let left = if first_edit_row != cursor_point.row {
7794 render_relative_row_jump("", cursor_point.row, first_edit_row)
7795 .into_any_element()
7796 } else {
7797 Icon::new(IconName::ZedPredict).into_any_element()
7798 };
7799
7800 Some(
7801 h_flex()
7802 .h_full()
7803 .flex_1()
7804 .gap_2()
7805 .pr_1()
7806 .overflow_x_hidden()
7807 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7808 .child(left)
7809 .child(preview),
7810 )
7811 }
7812 }
7813 }
7814
7815 fn render_context_menu(
7816 &self,
7817 style: &EditorStyle,
7818 max_height_in_lines: u32,
7819 window: &mut Window,
7820 cx: &mut Context<Editor>,
7821 ) -> Option<AnyElement> {
7822 let menu = self.context_menu.borrow();
7823 let menu = menu.as_ref()?;
7824 if !menu.visible() {
7825 return None;
7826 };
7827 Some(menu.render(style, max_height_in_lines, window, cx))
7828 }
7829
7830 fn render_context_menu_aside(
7831 &mut self,
7832 max_size: Size<Pixels>,
7833 window: &mut Window,
7834 cx: &mut Context<Editor>,
7835 ) -> Option<AnyElement> {
7836 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7837 if menu.visible() {
7838 menu.render_aside(self, max_size, window, cx)
7839 } else {
7840 None
7841 }
7842 })
7843 }
7844
7845 fn hide_context_menu(
7846 &mut self,
7847 window: &mut Window,
7848 cx: &mut Context<Self>,
7849 ) -> Option<CodeContextMenu> {
7850 cx.notify();
7851 self.completion_tasks.clear();
7852 let context_menu = self.context_menu.borrow_mut().take();
7853 self.stale_inline_completion_in_menu.take();
7854 self.update_visible_inline_completion(window, cx);
7855 context_menu
7856 }
7857
7858 fn show_snippet_choices(
7859 &mut self,
7860 choices: &Vec<String>,
7861 selection: Range<Anchor>,
7862 cx: &mut Context<Self>,
7863 ) {
7864 if selection.start.buffer_id.is_none() {
7865 return;
7866 }
7867 let buffer_id = selection.start.buffer_id.unwrap();
7868 let buffer = self.buffer().read(cx).buffer(buffer_id);
7869 let id = post_inc(&mut self.next_completion_id);
7870
7871 if let Some(buffer) = buffer {
7872 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7873 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7874 ));
7875 }
7876 }
7877
7878 pub fn insert_snippet(
7879 &mut self,
7880 insertion_ranges: &[Range<usize>],
7881 snippet: Snippet,
7882 window: &mut Window,
7883 cx: &mut Context<Self>,
7884 ) -> Result<()> {
7885 struct Tabstop<T> {
7886 is_end_tabstop: bool,
7887 ranges: Vec<Range<T>>,
7888 choices: Option<Vec<String>>,
7889 }
7890
7891 let tabstops = self.buffer.update(cx, |buffer, cx| {
7892 let snippet_text: Arc<str> = snippet.text.clone().into();
7893 let edits = insertion_ranges
7894 .iter()
7895 .cloned()
7896 .map(|range| (range, snippet_text.clone()));
7897 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7898
7899 let snapshot = &*buffer.read(cx);
7900 let snippet = &snippet;
7901 snippet
7902 .tabstops
7903 .iter()
7904 .map(|tabstop| {
7905 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7906 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7907 });
7908 let mut tabstop_ranges = tabstop
7909 .ranges
7910 .iter()
7911 .flat_map(|tabstop_range| {
7912 let mut delta = 0_isize;
7913 insertion_ranges.iter().map(move |insertion_range| {
7914 let insertion_start = insertion_range.start as isize + delta;
7915 delta +=
7916 snippet.text.len() as isize - insertion_range.len() as isize;
7917
7918 let start = ((insertion_start + tabstop_range.start) as usize)
7919 .min(snapshot.len());
7920 let end = ((insertion_start + tabstop_range.end) as usize)
7921 .min(snapshot.len());
7922 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7923 })
7924 })
7925 .collect::<Vec<_>>();
7926 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7927
7928 Tabstop {
7929 is_end_tabstop,
7930 ranges: tabstop_ranges,
7931 choices: tabstop.choices.clone(),
7932 }
7933 })
7934 .collect::<Vec<_>>()
7935 });
7936 if let Some(tabstop) = tabstops.first() {
7937 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7938 s.select_ranges(tabstop.ranges.iter().cloned());
7939 });
7940
7941 if let Some(choices) = &tabstop.choices {
7942 if let Some(selection) = tabstop.ranges.first() {
7943 self.show_snippet_choices(choices, selection.clone(), cx)
7944 }
7945 }
7946
7947 // If we're already at the last tabstop and it's at the end of the snippet,
7948 // we're done, we don't need to keep the state around.
7949 if !tabstop.is_end_tabstop {
7950 let choices = tabstops
7951 .iter()
7952 .map(|tabstop| tabstop.choices.clone())
7953 .collect();
7954
7955 let ranges = tabstops
7956 .into_iter()
7957 .map(|tabstop| tabstop.ranges)
7958 .collect::<Vec<_>>();
7959
7960 self.snippet_stack.push(SnippetState {
7961 active_index: 0,
7962 ranges,
7963 choices,
7964 });
7965 }
7966
7967 // Check whether the just-entered snippet ends with an auto-closable bracket.
7968 if self.autoclose_regions.is_empty() {
7969 let snapshot = self.buffer.read(cx).snapshot(cx);
7970 for selection in &mut self.selections.all::<Point>(cx) {
7971 let selection_head = selection.head();
7972 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7973 continue;
7974 };
7975
7976 let mut bracket_pair = None;
7977 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7978 let prev_chars = snapshot
7979 .reversed_chars_at(selection_head)
7980 .collect::<String>();
7981 for (pair, enabled) in scope.brackets() {
7982 if enabled
7983 && pair.close
7984 && prev_chars.starts_with(pair.start.as_str())
7985 && next_chars.starts_with(pair.end.as_str())
7986 {
7987 bracket_pair = Some(pair.clone());
7988 break;
7989 }
7990 }
7991 if let Some(pair) = bracket_pair {
7992 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
7993 let autoclose_enabled =
7994 self.use_autoclose && snapshot_settings.use_autoclose;
7995 if autoclose_enabled {
7996 let start = snapshot.anchor_after(selection_head);
7997 let end = snapshot.anchor_after(selection_head);
7998 self.autoclose_regions.push(AutocloseRegion {
7999 selection_id: selection.id,
8000 range: start..end,
8001 pair,
8002 });
8003 }
8004 }
8005 }
8006 }
8007 }
8008 Ok(())
8009 }
8010
8011 pub fn move_to_next_snippet_tabstop(
8012 &mut self,
8013 window: &mut Window,
8014 cx: &mut Context<Self>,
8015 ) -> bool {
8016 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8017 }
8018
8019 pub fn move_to_prev_snippet_tabstop(
8020 &mut self,
8021 window: &mut Window,
8022 cx: &mut Context<Self>,
8023 ) -> bool {
8024 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8025 }
8026
8027 pub fn move_to_snippet_tabstop(
8028 &mut self,
8029 bias: Bias,
8030 window: &mut Window,
8031 cx: &mut Context<Self>,
8032 ) -> bool {
8033 if let Some(mut snippet) = self.snippet_stack.pop() {
8034 match bias {
8035 Bias::Left => {
8036 if snippet.active_index > 0 {
8037 snippet.active_index -= 1;
8038 } else {
8039 self.snippet_stack.push(snippet);
8040 return false;
8041 }
8042 }
8043 Bias::Right => {
8044 if snippet.active_index + 1 < snippet.ranges.len() {
8045 snippet.active_index += 1;
8046 } else {
8047 self.snippet_stack.push(snippet);
8048 return false;
8049 }
8050 }
8051 }
8052 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8053 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8054 s.select_anchor_ranges(current_ranges.iter().cloned())
8055 });
8056
8057 if let Some(choices) = &snippet.choices[snippet.active_index] {
8058 if let Some(selection) = current_ranges.first() {
8059 self.show_snippet_choices(&choices, selection.clone(), cx);
8060 }
8061 }
8062
8063 // If snippet state is not at the last tabstop, push it back on the stack
8064 if snippet.active_index + 1 < snippet.ranges.len() {
8065 self.snippet_stack.push(snippet);
8066 }
8067 return true;
8068 }
8069 }
8070
8071 false
8072 }
8073
8074 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8075 self.transact(window, cx, |this, window, cx| {
8076 this.select_all(&SelectAll, window, cx);
8077 this.insert("", window, cx);
8078 });
8079 }
8080
8081 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8082 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8083 self.transact(window, cx, |this, window, cx| {
8084 this.select_autoclose_pair(window, cx);
8085 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8086 if !this.linked_edit_ranges.is_empty() {
8087 let selections = this.selections.all::<MultiBufferPoint>(cx);
8088 let snapshot = this.buffer.read(cx).snapshot(cx);
8089
8090 for selection in selections.iter() {
8091 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8092 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8093 if selection_start.buffer_id != selection_end.buffer_id {
8094 continue;
8095 }
8096 if let Some(ranges) =
8097 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8098 {
8099 for (buffer, entries) in ranges {
8100 linked_ranges.entry(buffer).or_default().extend(entries);
8101 }
8102 }
8103 }
8104 }
8105
8106 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8107 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8108 for selection in &mut selections {
8109 if selection.is_empty() {
8110 let old_head = selection.head();
8111 let mut new_head =
8112 movement::left(&display_map, old_head.to_display_point(&display_map))
8113 .to_point(&display_map);
8114 if let Some((buffer, line_buffer_range)) = display_map
8115 .buffer_snapshot
8116 .buffer_line_for_row(MultiBufferRow(old_head.row))
8117 {
8118 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8119 let indent_len = match indent_size.kind {
8120 IndentKind::Space => {
8121 buffer.settings_at(line_buffer_range.start, cx).tab_size
8122 }
8123 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8124 };
8125 if old_head.column <= indent_size.len && old_head.column > 0 {
8126 let indent_len = indent_len.get();
8127 new_head = cmp::min(
8128 new_head,
8129 MultiBufferPoint::new(
8130 old_head.row,
8131 ((old_head.column - 1) / indent_len) * indent_len,
8132 ),
8133 );
8134 }
8135 }
8136
8137 selection.set_head(new_head, SelectionGoal::None);
8138 }
8139 }
8140
8141 this.signature_help_state.set_backspace_pressed(true);
8142 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8143 s.select(selections)
8144 });
8145 this.insert("", window, cx);
8146 let empty_str: Arc<str> = Arc::from("");
8147 for (buffer, edits) in linked_ranges {
8148 let snapshot = buffer.read(cx).snapshot();
8149 use text::ToPoint as TP;
8150
8151 let edits = edits
8152 .into_iter()
8153 .map(|range| {
8154 let end_point = TP::to_point(&range.end, &snapshot);
8155 let mut start_point = TP::to_point(&range.start, &snapshot);
8156
8157 if end_point == start_point {
8158 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8159 .saturating_sub(1);
8160 start_point =
8161 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8162 };
8163
8164 (start_point..end_point, empty_str.clone())
8165 })
8166 .sorted_by_key(|(range, _)| range.start)
8167 .collect::<Vec<_>>();
8168 buffer.update(cx, |this, cx| {
8169 this.edit(edits, None, cx);
8170 })
8171 }
8172 this.refresh_inline_completion(true, false, window, cx);
8173 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8174 });
8175 }
8176
8177 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8178 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8179 self.transact(window, cx, |this, window, cx| {
8180 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8181 s.move_with(|map, selection| {
8182 if selection.is_empty() {
8183 let cursor = movement::right(map, selection.head());
8184 selection.end = cursor;
8185 selection.reversed = true;
8186 selection.goal = SelectionGoal::None;
8187 }
8188 })
8189 });
8190 this.insert("", window, cx);
8191 this.refresh_inline_completion(true, false, window, cx);
8192 });
8193 }
8194
8195 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8196 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8197 if self.move_to_prev_snippet_tabstop(window, cx) {
8198 return;
8199 }
8200 self.outdent(&Outdent, window, cx);
8201 }
8202
8203 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8204 if self.move_to_next_snippet_tabstop(window, cx) {
8205 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8206 return;
8207 }
8208 if self.read_only(cx) {
8209 return;
8210 }
8211 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8212 let mut selections = self.selections.all_adjusted(cx);
8213 let buffer = self.buffer.read(cx);
8214 let snapshot = buffer.snapshot(cx);
8215 let rows_iter = selections.iter().map(|s| s.head().row);
8216 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8217
8218 let mut edits = Vec::new();
8219 let mut prev_edited_row = 0;
8220 let mut row_delta = 0;
8221 for selection in &mut selections {
8222 if selection.start.row != prev_edited_row {
8223 row_delta = 0;
8224 }
8225 prev_edited_row = selection.end.row;
8226
8227 // If the selection is non-empty, then increase the indentation of the selected lines.
8228 if !selection.is_empty() {
8229 row_delta =
8230 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8231 continue;
8232 }
8233
8234 // If the selection is empty and the cursor is in the leading whitespace before the
8235 // suggested indentation, then auto-indent the line.
8236 let cursor = selection.head();
8237 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8238 if let Some(suggested_indent) =
8239 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8240 {
8241 if cursor.column < suggested_indent.len
8242 && cursor.column <= current_indent.len
8243 && current_indent.len <= suggested_indent.len
8244 {
8245 selection.start = Point::new(cursor.row, suggested_indent.len);
8246 selection.end = selection.start;
8247 if row_delta == 0 {
8248 edits.extend(Buffer::edit_for_indent_size_adjustment(
8249 cursor.row,
8250 current_indent,
8251 suggested_indent,
8252 ));
8253 row_delta = suggested_indent.len - current_indent.len;
8254 }
8255 continue;
8256 }
8257 }
8258
8259 // Otherwise, insert a hard or soft tab.
8260 let settings = buffer.language_settings_at(cursor, cx);
8261 let tab_size = if settings.hard_tabs {
8262 IndentSize::tab()
8263 } else {
8264 let tab_size = settings.tab_size.get();
8265 let indent_remainder = snapshot
8266 .text_for_range(Point::new(cursor.row, 0)..cursor)
8267 .flat_map(str::chars)
8268 .fold(row_delta % tab_size, |counter: u32, c| {
8269 if c == '\t' {
8270 0
8271 } else {
8272 (counter + 1) % tab_size
8273 }
8274 });
8275
8276 let chars_to_next_tab_stop = tab_size - indent_remainder;
8277 IndentSize::spaces(chars_to_next_tab_stop)
8278 };
8279 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8280 selection.end = selection.start;
8281 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8282 row_delta += tab_size.len;
8283 }
8284
8285 self.transact(window, cx, |this, window, cx| {
8286 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8287 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8288 s.select(selections)
8289 });
8290 this.refresh_inline_completion(true, false, window, cx);
8291 });
8292 }
8293
8294 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8295 if self.read_only(cx) {
8296 return;
8297 }
8298 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8299 let mut selections = self.selections.all::<Point>(cx);
8300 let mut prev_edited_row = 0;
8301 let mut row_delta = 0;
8302 let mut edits = Vec::new();
8303 let buffer = self.buffer.read(cx);
8304 let snapshot = buffer.snapshot(cx);
8305 for selection in &mut selections {
8306 if selection.start.row != prev_edited_row {
8307 row_delta = 0;
8308 }
8309 prev_edited_row = selection.end.row;
8310
8311 row_delta =
8312 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8313 }
8314
8315 self.transact(window, cx, |this, window, cx| {
8316 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8317 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8318 s.select(selections)
8319 });
8320 });
8321 }
8322
8323 fn indent_selection(
8324 buffer: &MultiBuffer,
8325 snapshot: &MultiBufferSnapshot,
8326 selection: &mut Selection<Point>,
8327 edits: &mut Vec<(Range<Point>, String)>,
8328 delta_for_start_row: u32,
8329 cx: &App,
8330 ) -> u32 {
8331 let settings = buffer.language_settings_at(selection.start, cx);
8332 let tab_size = settings.tab_size.get();
8333 let indent_kind = if settings.hard_tabs {
8334 IndentKind::Tab
8335 } else {
8336 IndentKind::Space
8337 };
8338 let mut start_row = selection.start.row;
8339 let mut end_row = selection.end.row + 1;
8340
8341 // If a selection ends at the beginning of a line, don't indent
8342 // that last line.
8343 if selection.end.column == 0 && selection.end.row > selection.start.row {
8344 end_row -= 1;
8345 }
8346
8347 // Avoid re-indenting a row that has already been indented by a
8348 // previous selection, but still update this selection's column
8349 // to reflect that indentation.
8350 if delta_for_start_row > 0 {
8351 start_row += 1;
8352 selection.start.column += delta_for_start_row;
8353 if selection.end.row == selection.start.row {
8354 selection.end.column += delta_for_start_row;
8355 }
8356 }
8357
8358 let mut delta_for_end_row = 0;
8359 let has_multiple_rows = start_row + 1 != end_row;
8360 for row in start_row..end_row {
8361 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8362 let indent_delta = match (current_indent.kind, indent_kind) {
8363 (IndentKind::Space, IndentKind::Space) => {
8364 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8365 IndentSize::spaces(columns_to_next_tab_stop)
8366 }
8367 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8368 (_, IndentKind::Tab) => IndentSize::tab(),
8369 };
8370
8371 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8372 0
8373 } else {
8374 selection.start.column
8375 };
8376 let row_start = Point::new(row, start);
8377 edits.push((
8378 row_start..row_start,
8379 indent_delta.chars().collect::<String>(),
8380 ));
8381
8382 // Update this selection's endpoints to reflect the indentation.
8383 if row == selection.start.row {
8384 selection.start.column += indent_delta.len;
8385 }
8386 if row == selection.end.row {
8387 selection.end.column += indent_delta.len;
8388 delta_for_end_row = indent_delta.len;
8389 }
8390 }
8391
8392 if selection.start.row == selection.end.row {
8393 delta_for_start_row + delta_for_end_row
8394 } else {
8395 delta_for_end_row
8396 }
8397 }
8398
8399 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8400 if self.read_only(cx) {
8401 return;
8402 }
8403 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8404 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8405 let selections = self.selections.all::<Point>(cx);
8406 let mut deletion_ranges = Vec::new();
8407 let mut last_outdent = None;
8408 {
8409 let buffer = self.buffer.read(cx);
8410 let snapshot = buffer.snapshot(cx);
8411 for selection in &selections {
8412 let settings = buffer.language_settings_at(selection.start, cx);
8413 let tab_size = settings.tab_size.get();
8414 let mut rows = selection.spanned_rows(false, &display_map);
8415
8416 // Avoid re-outdenting a row that has already been outdented by a
8417 // previous selection.
8418 if let Some(last_row) = last_outdent {
8419 if last_row == rows.start {
8420 rows.start = rows.start.next_row();
8421 }
8422 }
8423 let has_multiple_rows = rows.len() > 1;
8424 for row in rows.iter_rows() {
8425 let indent_size = snapshot.indent_size_for_line(row);
8426 if indent_size.len > 0 {
8427 let deletion_len = match indent_size.kind {
8428 IndentKind::Space => {
8429 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8430 if columns_to_prev_tab_stop == 0 {
8431 tab_size
8432 } else {
8433 columns_to_prev_tab_stop
8434 }
8435 }
8436 IndentKind::Tab => 1,
8437 };
8438 let start = if has_multiple_rows
8439 || deletion_len > selection.start.column
8440 || indent_size.len < selection.start.column
8441 {
8442 0
8443 } else {
8444 selection.start.column - deletion_len
8445 };
8446 deletion_ranges.push(
8447 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8448 );
8449 last_outdent = Some(row);
8450 }
8451 }
8452 }
8453 }
8454
8455 self.transact(window, cx, |this, window, cx| {
8456 this.buffer.update(cx, |buffer, cx| {
8457 let empty_str: Arc<str> = Arc::default();
8458 buffer.edit(
8459 deletion_ranges
8460 .into_iter()
8461 .map(|range| (range, empty_str.clone())),
8462 None,
8463 cx,
8464 );
8465 });
8466 let selections = this.selections.all::<usize>(cx);
8467 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8468 s.select(selections)
8469 });
8470 });
8471 }
8472
8473 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8474 if self.read_only(cx) {
8475 return;
8476 }
8477 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8478 let selections = self
8479 .selections
8480 .all::<usize>(cx)
8481 .into_iter()
8482 .map(|s| s.range());
8483
8484 self.transact(window, cx, |this, window, cx| {
8485 this.buffer.update(cx, |buffer, cx| {
8486 buffer.autoindent_ranges(selections, cx);
8487 });
8488 let selections = this.selections.all::<usize>(cx);
8489 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8490 s.select(selections)
8491 });
8492 });
8493 }
8494
8495 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8496 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8497 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8498 let selections = self.selections.all::<Point>(cx);
8499
8500 let mut new_cursors = Vec::new();
8501 let mut edit_ranges = Vec::new();
8502 let mut selections = selections.iter().peekable();
8503 while let Some(selection) = selections.next() {
8504 let mut rows = selection.spanned_rows(false, &display_map);
8505 let goal_display_column = selection.head().to_display_point(&display_map).column();
8506
8507 // Accumulate contiguous regions of rows that we want to delete.
8508 while let Some(next_selection) = selections.peek() {
8509 let next_rows = next_selection.spanned_rows(false, &display_map);
8510 if next_rows.start <= rows.end {
8511 rows.end = next_rows.end;
8512 selections.next().unwrap();
8513 } else {
8514 break;
8515 }
8516 }
8517
8518 let buffer = &display_map.buffer_snapshot;
8519 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8520 let edit_end;
8521 let cursor_buffer_row;
8522 if buffer.max_point().row >= rows.end.0 {
8523 // If there's a line after the range, delete the \n from the end of the row range
8524 // and position the cursor on the next line.
8525 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8526 cursor_buffer_row = rows.end;
8527 } else {
8528 // If there isn't a line after the range, delete the \n from the line before the
8529 // start of the row range and position the cursor there.
8530 edit_start = edit_start.saturating_sub(1);
8531 edit_end = buffer.len();
8532 cursor_buffer_row = rows.start.previous_row();
8533 }
8534
8535 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8536 *cursor.column_mut() =
8537 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8538
8539 new_cursors.push((
8540 selection.id,
8541 buffer.anchor_after(cursor.to_point(&display_map)),
8542 ));
8543 edit_ranges.push(edit_start..edit_end);
8544 }
8545
8546 self.transact(window, cx, |this, window, cx| {
8547 let buffer = this.buffer.update(cx, |buffer, cx| {
8548 let empty_str: Arc<str> = Arc::default();
8549 buffer.edit(
8550 edit_ranges
8551 .into_iter()
8552 .map(|range| (range, empty_str.clone())),
8553 None,
8554 cx,
8555 );
8556 buffer.snapshot(cx)
8557 });
8558 let new_selections = new_cursors
8559 .into_iter()
8560 .map(|(id, cursor)| {
8561 let cursor = cursor.to_point(&buffer);
8562 Selection {
8563 id,
8564 start: cursor,
8565 end: cursor,
8566 reversed: false,
8567 goal: SelectionGoal::None,
8568 }
8569 })
8570 .collect();
8571
8572 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8573 s.select(new_selections);
8574 });
8575 });
8576 }
8577
8578 pub fn join_lines_impl(
8579 &mut self,
8580 insert_whitespace: bool,
8581 window: &mut Window,
8582 cx: &mut Context<Self>,
8583 ) {
8584 if self.read_only(cx) {
8585 return;
8586 }
8587 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8588 for selection in self.selections.all::<Point>(cx) {
8589 let start = MultiBufferRow(selection.start.row);
8590 // Treat single line selections as if they include the next line. Otherwise this action
8591 // would do nothing for single line selections individual cursors.
8592 let end = if selection.start.row == selection.end.row {
8593 MultiBufferRow(selection.start.row + 1)
8594 } else {
8595 MultiBufferRow(selection.end.row)
8596 };
8597
8598 if let Some(last_row_range) = row_ranges.last_mut() {
8599 if start <= last_row_range.end {
8600 last_row_range.end = end;
8601 continue;
8602 }
8603 }
8604 row_ranges.push(start..end);
8605 }
8606
8607 let snapshot = self.buffer.read(cx).snapshot(cx);
8608 let mut cursor_positions = Vec::new();
8609 for row_range in &row_ranges {
8610 let anchor = snapshot.anchor_before(Point::new(
8611 row_range.end.previous_row().0,
8612 snapshot.line_len(row_range.end.previous_row()),
8613 ));
8614 cursor_positions.push(anchor..anchor);
8615 }
8616
8617 self.transact(window, cx, |this, window, cx| {
8618 for row_range in row_ranges.into_iter().rev() {
8619 for row in row_range.iter_rows().rev() {
8620 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8621 let next_line_row = row.next_row();
8622 let indent = snapshot.indent_size_for_line(next_line_row);
8623 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8624
8625 let replace =
8626 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8627 " "
8628 } else {
8629 ""
8630 };
8631
8632 this.buffer.update(cx, |buffer, cx| {
8633 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8634 });
8635 }
8636 }
8637
8638 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8639 s.select_anchor_ranges(cursor_positions)
8640 });
8641 });
8642 }
8643
8644 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8645 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8646 self.join_lines_impl(true, window, cx);
8647 }
8648
8649 pub fn sort_lines_case_sensitive(
8650 &mut self,
8651 _: &SortLinesCaseSensitive,
8652 window: &mut Window,
8653 cx: &mut Context<Self>,
8654 ) {
8655 self.manipulate_lines(window, cx, |lines| lines.sort())
8656 }
8657
8658 pub fn sort_lines_case_insensitive(
8659 &mut self,
8660 _: &SortLinesCaseInsensitive,
8661 window: &mut Window,
8662 cx: &mut Context<Self>,
8663 ) {
8664 self.manipulate_lines(window, cx, |lines| {
8665 lines.sort_by_key(|line| line.to_lowercase())
8666 })
8667 }
8668
8669 pub fn unique_lines_case_insensitive(
8670 &mut self,
8671 _: &UniqueLinesCaseInsensitive,
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.to_lowercase()));
8678 })
8679 }
8680
8681 pub fn unique_lines_case_sensitive(
8682 &mut self,
8683 _: &UniqueLinesCaseSensitive,
8684 window: &mut Window,
8685 cx: &mut Context<Self>,
8686 ) {
8687 self.manipulate_lines(window, cx, |lines| {
8688 let mut seen = HashSet::default();
8689 lines.retain(|line| seen.insert(*line));
8690 })
8691 }
8692
8693 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8694 let Some(project) = self.project.clone() else {
8695 return;
8696 };
8697 self.reload(project, window, cx)
8698 .detach_and_notify_err(window, cx);
8699 }
8700
8701 pub fn restore_file(
8702 &mut self,
8703 _: &::git::RestoreFile,
8704 window: &mut Window,
8705 cx: &mut Context<Self>,
8706 ) {
8707 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8708 let mut buffer_ids = HashSet::default();
8709 let snapshot = self.buffer().read(cx).snapshot(cx);
8710 for selection in self.selections.all::<usize>(cx) {
8711 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8712 }
8713
8714 let buffer = self.buffer().read(cx);
8715 let ranges = buffer_ids
8716 .into_iter()
8717 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8718 .collect::<Vec<_>>();
8719
8720 self.restore_hunks_in_ranges(ranges, window, cx);
8721 }
8722
8723 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8724 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8725 let selections = self
8726 .selections
8727 .all(cx)
8728 .into_iter()
8729 .map(|s| s.range())
8730 .collect();
8731 self.restore_hunks_in_ranges(selections, window, cx);
8732 }
8733
8734 pub fn restore_hunks_in_ranges(
8735 &mut self,
8736 ranges: Vec<Range<Point>>,
8737 window: &mut Window,
8738 cx: &mut Context<Editor>,
8739 ) {
8740 let mut revert_changes = HashMap::default();
8741 let chunk_by = self
8742 .snapshot(window, cx)
8743 .hunks_for_ranges(ranges)
8744 .into_iter()
8745 .chunk_by(|hunk| hunk.buffer_id);
8746 for (buffer_id, hunks) in &chunk_by {
8747 let hunks = hunks.collect::<Vec<_>>();
8748 for hunk in &hunks {
8749 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8750 }
8751 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8752 }
8753 drop(chunk_by);
8754 if !revert_changes.is_empty() {
8755 self.transact(window, cx, |editor, window, cx| {
8756 editor.restore(revert_changes, window, cx);
8757 });
8758 }
8759 }
8760
8761 pub fn open_active_item_in_terminal(
8762 &mut self,
8763 _: &OpenInTerminal,
8764 window: &mut Window,
8765 cx: &mut Context<Self>,
8766 ) {
8767 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8768 let project_path = buffer.read(cx).project_path(cx)?;
8769 let project = self.project.as_ref()?.read(cx);
8770 let entry = project.entry_for_path(&project_path, cx)?;
8771 let parent = match &entry.canonical_path {
8772 Some(canonical_path) => canonical_path.to_path_buf(),
8773 None => project.absolute_path(&project_path, cx)?,
8774 }
8775 .parent()?
8776 .to_path_buf();
8777 Some(parent)
8778 }) {
8779 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8780 }
8781 }
8782
8783 fn set_breakpoint_context_menu(
8784 &mut self,
8785 display_row: DisplayRow,
8786 position: Option<Anchor>,
8787 clicked_point: gpui::Point<Pixels>,
8788 window: &mut Window,
8789 cx: &mut Context<Self>,
8790 ) {
8791 if !cx.has_flag::<Debugger>() {
8792 return;
8793 }
8794 let source = self
8795 .buffer
8796 .read(cx)
8797 .snapshot(cx)
8798 .anchor_before(Point::new(display_row.0, 0u32));
8799
8800 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8801
8802 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8803 self,
8804 source,
8805 clicked_point,
8806 context_menu,
8807 window,
8808 cx,
8809 );
8810 }
8811
8812 fn add_edit_breakpoint_block(
8813 &mut self,
8814 anchor: Anchor,
8815 breakpoint: &Breakpoint,
8816 edit_action: BreakpointPromptEditAction,
8817 window: &mut Window,
8818 cx: &mut Context<Self>,
8819 ) {
8820 let weak_editor = cx.weak_entity();
8821 let bp_prompt = cx.new(|cx| {
8822 BreakpointPromptEditor::new(
8823 weak_editor,
8824 anchor,
8825 breakpoint.clone(),
8826 edit_action,
8827 window,
8828 cx,
8829 )
8830 });
8831
8832 let height = bp_prompt.update(cx, |this, cx| {
8833 this.prompt
8834 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8835 });
8836 let cloned_prompt = bp_prompt.clone();
8837 let blocks = vec![BlockProperties {
8838 style: BlockStyle::Sticky,
8839 placement: BlockPlacement::Above(anchor),
8840 height: Some(height),
8841 render: Arc::new(move |cx| {
8842 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8843 cloned_prompt.clone().into_any_element()
8844 }),
8845 priority: 0,
8846 }];
8847
8848 let focus_handle = bp_prompt.focus_handle(cx);
8849 window.focus(&focus_handle);
8850
8851 let block_ids = self.insert_blocks(blocks, None, cx);
8852 bp_prompt.update(cx, |prompt, _| {
8853 prompt.add_block_ids(block_ids);
8854 });
8855 }
8856
8857 pub(crate) fn breakpoint_at_row(
8858 &self,
8859 row: u32,
8860 window: &mut Window,
8861 cx: &mut Context<Self>,
8862 ) -> Option<(Anchor, Breakpoint)> {
8863 let snapshot = self.snapshot(window, cx);
8864 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8865
8866 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
8867 }
8868
8869 pub(crate) fn breakpoint_at_anchor(
8870 &self,
8871 breakpoint_position: Anchor,
8872 snapshot: &EditorSnapshot,
8873 cx: &mut Context<Self>,
8874 ) -> Option<(Anchor, Breakpoint)> {
8875 let project = self.project.clone()?;
8876
8877 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8878 snapshot
8879 .buffer_snapshot
8880 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8881 })?;
8882
8883 let enclosing_excerpt = breakpoint_position.excerpt_id;
8884 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8885 let buffer_snapshot = buffer.read(cx).snapshot();
8886
8887 let row = buffer_snapshot
8888 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8889 .row;
8890
8891 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8892 let anchor_end = snapshot
8893 .buffer_snapshot
8894 .anchor_after(Point::new(row, line_len));
8895
8896 let bp = self
8897 .breakpoint_store
8898 .as_ref()?
8899 .read_with(cx, |breakpoint_store, cx| {
8900 breakpoint_store
8901 .breakpoints(
8902 &buffer,
8903 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8904 &buffer_snapshot,
8905 cx,
8906 )
8907 .next()
8908 .and_then(|(anchor, bp)| {
8909 let breakpoint_row = buffer_snapshot
8910 .summary_for_anchor::<text::PointUtf16>(anchor)
8911 .row;
8912
8913 if breakpoint_row == row {
8914 snapshot
8915 .buffer_snapshot
8916 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8917 .map(|anchor| (anchor, bp.clone()))
8918 } else {
8919 None
8920 }
8921 })
8922 });
8923 bp
8924 }
8925
8926 pub fn edit_log_breakpoint(
8927 &mut self,
8928 _: &EditLogBreakpoint,
8929 window: &mut Window,
8930 cx: &mut Context<Self>,
8931 ) {
8932 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
8933 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
8934 message: None,
8935 state: BreakpointState::Enabled,
8936 condition: None,
8937 hit_condition: None,
8938 });
8939
8940 self.add_edit_breakpoint_block(
8941 anchor,
8942 &breakpoint,
8943 BreakpointPromptEditAction::Log,
8944 window,
8945 cx,
8946 );
8947 }
8948 }
8949
8950 fn breakpoints_at_cursors(
8951 &self,
8952 window: &mut Window,
8953 cx: &mut Context<Self>,
8954 ) -> Vec<(Anchor, Option<Breakpoint>)> {
8955 let snapshot = self.snapshot(window, cx);
8956 let cursors = self
8957 .selections
8958 .disjoint_anchors()
8959 .into_iter()
8960 .map(|selection| {
8961 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
8962
8963 let breakpoint_position = self
8964 .breakpoint_at_row(cursor_position.row, window, cx)
8965 .map(|bp| bp.0)
8966 .unwrap_or_else(|| {
8967 snapshot
8968 .display_snapshot
8969 .buffer_snapshot
8970 .anchor_after(Point::new(cursor_position.row, 0))
8971 });
8972
8973 let breakpoint = self
8974 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
8975 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
8976
8977 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
8978 })
8979 // There might be multiple cursors on the same line; all of them should have the same anchors though as their breakpoints positions, which makes it possible to sort and dedup the list.
8980 .collect::<HashMap<Anchor, _>>();
8981
8982 cursors.into_iter().collect()
8983 }
8984
8985 pub fn enable_breakpoint(
8986 &mut self,
8987 _: &crate::actions::EnableBreakpoint,
8988 window: &mut Window,
8989 cx: &mut Context<Self>,
8990 ) {
8991 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
8992 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
8993 continue;
8994 };
8995 self.edit_breakpoint_at_anchor(
8996 anchor,
8997 breakpoint,
8998 BreakpointEditAction::InvertState,
8999 cx,
9000 );
9001 }
9002 }
9003
9004 pub fn disable_breakpoint(
9005 &mut self,
9006 _: &crate::actions::DisableBreakpoint,
9007 window: &mut Window,
9008 cx: &mut Context<Self>,
9009 ) {
9010 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9011 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9012 continue;
9013 };
9014 self.edit_breakpoint_at_anchor(
9015 anchor,
9016 breakpoint,
9017 BreakpointEditAction::InvertState,
9018 cx,
9019 );
9020 }
9021 }
9022
9023 pub fn toggle_breakpoint(
9024 &mut self,
9025 _: &crate::actions::ToggleBreakpoint,
9026 window: &mut Window,
9027 cx: &mut Context<Self>,
9028 ) {
9029 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9030 if let Some(breakpoint) = breakpoint {
9031 self.edit_breakpoint_at_anchor(
9032 anchor,
9033 breakpoint,
9034 BreakpointEditAction::Toggle,
9035 cx,
9036 );
9037 } else {
9038 self.edit_breakpoint_at_anchor(
9039 anchor,
9040 Breakpoint::new_standard(),
9041 BreakpointEditAction::Toggle,
9042 cx,
9043 );
9044 }
9045 }
9046 }
9047
9048 pub fn edit_breakpoint_at_anchor(
9049 &mut self,
9050 breakpoint_position: Anchor,
9051 breakpoint: Breakpoint,
9052 edit_action: BreakpointEditAction,
9053 cx: &mut Context<Self>,
9054 ) {
9055 let Some(breakpoint_store) = &self.breakpoint_store else {
9056 return;
9057 };
9058
9059 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9060 if breakpoint_position == Anchor::min() {
9061 self.buffer()
9062 .read(cx)
9063 .excerpt_buffer_ids()
9064 .into_iter()
9065 .next()
9066 } else {
9067 None
9068 }
9069 }) else {
9070 return;
9071 };
9072
9073 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9074 return;
9075 };
9076
9077 breakpoint_store.update(cx, |breakpoint_store, cx| {
9078 breakpoint_store.toggle_breakpoint(
9079 buffer,
9080 (breakpoint_position.text_anchor, breakpoint),
9081 edit_action,
9082 cx,
9083 );
9084 });
9085
9086 cx.notify();
9087 }
9088
9089 #[cfg(any(test, feature = "test-support"))]
9090 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9091 self.breakpoint_store.clone()
9092 }
9093
9094 pub fn prepare_restore_change(
9095 &self,
9096 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9097 hunk: &MultiBufferDiffHunk,
9098 cx: &mut App,
9099 ) -> Option<()> {
9100 if hunk.is_created_file() {
9101 return None;
9102 }
9103 let buffer = self.buffer.read(cx);
9104 let diff = buffer.diff_for(hunk.buffer_id)?;
9105 let buffer = buffer.buffer(hunk.buffer_id)?;
9106 let buffer = buffer.read(cx);
9107 let original_text = diff
9108 .read(cx)
9109 .base_text()
9110 .as_rope()
9111 .slice(hunk.diff_base_byte_range.clone());
9112 let buffer_snapshot = buffer.snapshot();
9113 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9114 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9115 probe
9116 .0
9117 .start
9118 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9119 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9120 }) {
9121 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9122 Some(())
9123 } else {
9124 None
9125 }
9126 }
9127
9128 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9129 self.manipulate_lines(window, cx, |lines| lines.reverse())
9130 }
9131
9132 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9133 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9134 }
9135
9136 fn manipulate_lines<Fn>(
9137 &mut self,
9138 window: &mut Window,
9139 cx: &mut Context<Self>,
9140 mut callback: Fn,
9141 ) where
9142 Fn: FnMut(&mut Vec<&str>),
9143 {
9144 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9145
9146 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9147 let buffer = self.buffer.read(cx).snapshot(cx);
9148
9149 let mut edits = Vec::new();
9150
9151 let selections = self.selections.all::<Point>(cx);
9152 let mut selections = selections.iter().peekable();
9153 let mut contiguous_row_selections = Vec::new();
9154 let mut new_selections = Vec::new();
9155 let mut added_lines = 0;
9156 let mut removed_lines = 0;
9157
9158 while let Some(selection) = selections.next() {
9159 let (start_row, end_row) = consume_contiguous_rows(
9160 &mut contiguous_row_selections,
9161 selection,
9162 &display_map,
9163 &mut selections,
9164 );
9165
9166 let start_point = Point::new(start_row.0, 0);
9167 let end_point = Point::new(
9168 end_row.previous_row().0,
9169 buffer.line_len(end_row.previous_row()),
9170 );
9171 let text = buffer
9172 .text_for_range(start_point..end_point)
9173 .collect::<String>();
9174
9175 let mut lines = text.split('\n').collect_vec();
9176
9177 let lines_before = lines.len();
9178 callback(&mut lines);
9179 let lines_after = lines.len();
9180
9181 edits.push((start_point..end_point, lines.join("\n")));
9182
9183 // Selections must change based on added and removed line count
9184 let start_row =
9185 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9186 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9187 new_selections.push(Selection {
9188 id: selection.id,
9189 start: start_row,
9190 end: end_row,
9191 goal: SelectionGoal::None,
9192 reversed: selection.reversed,
9193 });
9194
9195 if lines_after > lines_before {
9196 added_lines += lines_after - lines_before;
9197 } else if lines_before > lines_after {
9198 removed_lines += lines_before - lines_after;
9199 }
9200 }
9201
9202 self.transact(window, cx, |this, window, cx| {
9203 let buffer = this.buffer.update(cx, |buffer, cx| {
9204 buffer.edit(edits, None, cx);
9205 buffer.snapshot(cx)
9206 });
9207
9208 // Recalculate offsets on newly edited buffer
9209 let new_selections = new_selections
9210 .iter()
9211 .map(|s| {
9212 let start_point = Point::new(s.start.0, 0);
9213 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9214 Selection {
9215 id: s.id,
9216 start: buffer.point_to_offset(start_point),
9217 end: buffer.point_to_offset(end_point),
9218 goal: s.goal,
9219 reversed: s.reversed,
9220 }
9221 })
9222 .collect();
9223
9224 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9225 s.select(new_selections);
9226 });
9227
9228 this.request_autoscroll(Autoscroll::fit(), cx);
9229 });
9230 }
9231
9232 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9233 self.manipulate_text(window, cx, |text| {
9234 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9235 if has_upper_case_characters {
9236 text.to_lowercase()
9237 } else {
9238 text.to_uppercase()
9239 }
9240 })
9241 }
9242
9243 pub fn convert_to_upper_case(
9244 &mut self,
9245 _: &ConvertToUpperCase,
9246 window: &mut Window,
9247 cx: &mut Context<Self>,
9248 ) {
9249 self.manipulate_text(window, cx, |text| text.to_uppercase())
9250 }
9251
9252 pub fn convert_to_lower_case(
9253 &mut self,
9254 _: &ConvertToLowerCase,
9255 window: &mut Window,
9256 cx: &mut Context<Self>,
9257 ) {
9258 self.manipulate_text(window, cx, |text| text.to_lowercase())
9259 }
9260
9261 pub fn convert_to_title_case(
9262 &mut self,
9263 _: &ConvertToTitleCase,
9264 window: &mut Window,
9265 cx: &mut Context<Self>,
9266 ) {
9267 self.manipulate_text(window, cx, |text| {
9268 text.split('\n')
9269 .map(|line| line.to_case(Case::Title))
9270 .join("\n")
9271 })
9272 }
9273
9274 pub fn convert_to_snake_case(
9275 &mut self,
9276 _: &ConvertToSnakeCase,
9277 window: &mut Window,
9278 cx: &mut Context<Self>,
9279 ) {
9280 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9281 }
9282
9283 pub fn convert_to_kebab_case(
9284 &mut self,
9285 _: &ConvertToKebabCase,
9286 window: &mut Window,
9287 cx: &mut Context<Self>,
9288 ) {
9289 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9290 }
9291
9292 pub fn convert_to_upper_camel_case(
9293 &mut self,
9294 _: &ConvertToUpperCamelCase,
9295 window: &mut Window,
9296 cx: &mut Context<Self>,
9297 ) {
9298 self.manipulate_text(window, cx, |text| {
9299 text.split('\n')
9300 .map(|line| line.to_case(Case::UpperCamel))
9301 .join("\n")
9302 })
9303 }
9304
9305 pub fn convert_to_lower_camel_case(
9306 &mut self,
9307 _: &ConvertToLowerCamelCase,
9308 window: &mut Window,
9309 cx: &mut Context<Self>,
9310 ) {
9311 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9312 }
9313
9314 pub fn convert_to_opposite_case(
9315 &mut self,
9316 _: &ConvertToOppositeCase,
9317 window: &mut Window,
9318 cx: &mut Context<Self>,
9319 ) {
9320 self.manipulate_text(window, cx, |text| {
9321 text.chars()
9322 .fold(String::with_capacity(text.len()), |mut t, c| {
9323 if c.is_uppercase() {
9324 t.extend(c.to_lowercase());
9325 } else {
9326 t.extend(c.to_uppercase());
9327 }
9328 t
9329 })
9330 })
9331 }
9332
9333 pub fn convert_to_rot13(
9334 &mut self,
9335 _: &ConvertToRot13,
9336 window: &mut Window,
9337 cx: &mut Context<Self>,
9338 ) {
9339 self.manipulate_text(window, cx, |text| {
9340 text.chars()
9341 .map(|c| match c {
9342 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9343 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9344 _ => c,
9345 })
9346 .collect()
9347 })
9348 }
9349
9350 pub fn convert_to_rot47(
9351 &mut self,
9352 _: &ConvertToRot47,
9353 window: &mut Window,
9354 cx: &mut Context<Self>,
9355 ) {
9356 self.manipulate_text(window, cx, |text| {
9357 text.chars()
9358 .map(|c| {
9359 let code_point = c as u32;
9360 if code_point >= 33 && code_point <= 126 {
9361 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9362 }
9363 c
9364 })
9365 .collect()
9366 })
9367 }
9368
9369 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9370 where
9371 Fn: FnMut(&str) -> String,
9372 {
9373 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9374 let buffer = self.buffer.read(cx).snapshot(cx);
9375
9376 let mut new_selections = Vec::new();
9377 let mut edits = Vec::new();
9378 let mut selection_adjustment = 0i32;
9379
9380 for selection in self.selections.all::<usize>(cx) {
9381 let selection_is_empty = selection.is_empty();
9382
9383 let (start, end) = if selection_is_empty {
9384 let word_range = movement::surrounding_word(
9385 &display_map,
9386 selection.start.to_display_point(&display_map),
9387 );
9388 let start = word_range.start.to_offset(&display_map, Bias::Left);
9389 let end = word_range.end.to_offset(&display_map, Bias::Left);
9390 (start, end)
9391 } else {
9392 (selection.start, selection.end)
9393 };
9394
9395 let text = buffer.text_for_range(start..end).collect::<String>();
9396 let old_length = text.len() as i32;
9397 let text = callback(&text);
9398
9399 new_selections.push(Selection {
9400 start: (start as i32 - selection_adjustment) as usize,
9401 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9402 goal: SelectionGoal::None,
9403 ..selection
9404 });
9405
9406 selection_adjustment += old_length - text.len() as i32;
9407
9408 edits.push((start..end, text));
9409 }
9410
9411 self.transact(window, cx, |this, window, cx| {
9412 this.buffer.update(cx, |buffer, cx| {
9413 buffer.edit(edits, None, cx);
9414 });
9415
9416 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9417 s.select(new_selections);
9418 });
9419
9420 this.request_autoscroll(Autoscroll::fit(), cx);
9421 });
9422 }
9423
9424 pub fn duplicate(
9425 &mut self,
9426 upwards: bool,
9427 whole_lines: bool,
9428 window: &mut Window,
9429 cx: &mut Context<Self>,
9430 ) {
9431 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9432
9433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9434 let buffer = &display_map.buffer_snapshot;
9435 let selections = self.selections.all::<Point>(cx);
9436
9437 let mut edits = Vec::new();
9438 let mut selections_iter = selections.iter().peekable();
9439 while let Some(selection) = selections_iter.next() {
9440 let mut rows = selection.spanned_rows(false, &display_map);
9441 // duplicate line-wise
9442 if whole_lines || selection.start == selection.end {
9443 // Avoid duplicating the same lines twice.
9444 while let Some(next_selection) = selections_iter.peek() {
9445 let next_rows = next_selection.spanned_rows(false, &display_map);
9446 if next_rows.start < rows.end {
9447 rows.end = next_rows.end;
9448 selections_iter.next().unwrap();
9449 } else {
9450 break;
9451 }
9452 }
9453
9454 // Copy the text from the selected row region and splice it either at the start
9455 // or end of the region.
9456 let start = Point::new(rows.start.0, 0);
9457 let end = Point::new(
9458 rows.end.previous_row().0,
9459 buffer.line_len(rows.end.previous_row()),
9460 );
9461 let text = buffer
9462 .text_for_range(start..end)
9463 .chain(Some("\n"))
9464 .collect::<String>();
9465 let insert_location = if upwards {
9466 Point::new(rows.end.0, 0)
9467 } else {
9468 start
9469 };
9470 edits.push((insert_location..insert_location, text));
9471 } else {
9472 // duplicate character-wise
9473 let start = selection.start;
9474 let end = selection.end;
9475 let text = buffer.text_for_range(start..end).collect::<String>();
9476 edits.push((selection.end..selection.end, text));
9477 }
9478 }
9479
9480 self.transact(window, cx, |this, _, cx| {
9481 this.buffer.update(cx, |buffer, cx| {
9482 buffer.edit(edits, None, cx);
9483 });
9484
9485 this.request_autoscroll(Autoscroll::fit(), cx);
9486 });
9487 }
9488
9489 pub fn duplicate_line_up(
9490 &mut self,
9491 _: &DuplicateLineUp,
9492 window: &mut Window,
9493 cx: &mut Context<Self>,
9494 ) {
9495 self.duplicate(true, true, window, cx);
9496 }
9497
9498 pub fn duplicate_line_down(
9499 &mut self,
9500 _: &DuplicateLineDown,
9501 window: &mut Window,
9502 cx: &mut Context<Self>,
9503 ) {
9504 self.duplicate(false, true, window, cx);
9505 }
9506
9507 pub fn duplicate_selection(
9508 &mut self,
9509 _: &DuplicateSelection,
9510 window: &mut Window,
9511 cx: &mut Context<Self>,
9512 ) {
9513 self.duplicate(false, false, window, cx);
9514 }
9515
9516 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9517 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9518
9519 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9520 let buffer = self.buffer.read(cx).snapshot(cx);
9521
9522 let mut edits = Vec::new();
9523 let mut unfold_ranges = Vec::new();
9524 let mut refold_creases = Vec::new();
9525
9526 let selections = self.selections.all::<Point>(cx);
9527 let mut selections = selections.iter().peekable();
9528 let mut contiguous_row_selections = Vec::new();
9529 let mut new_selections = Vec::new();
9530
9531 while let Some(selection) = selections.next() {
9532 // Find all the selections that span a contiguous row range
9533 let (start_row, end_row) = consume_contiguous_rows(
9534 &mut contiguous_row_selections,
9535 selection,
9536 &display_map,
9537 &mut selections,
9538 );
9539
9540 // Move the text spanned by the row range to be before the line preceding the row range
9541 if start_row.0 > 0 {
9542 let range_to_move = Point::new(
9543 start_row.previous_row().0,
9544 buffer.line_len(start_row.previous_row()),
9545 )
9546 ..Point::new(
9547 end_row.previous_row().0,
9548 buffer.line_len(end_row.previous_row()),
9549 );
9550 let insertion_point = display_map
9551 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9552 .0;
9553
9554 // Don't move lines across excerpts
9555 if buffer
9556 .excerpt_containing(insertion_point..range_to_move.end)
9557 .is_some()
9558 {
9559 let text = buffer
9560 .text_for_range(range_to_move.clone())
9561 .flat_map(|s| s.chars())
9562 .skip(1)
9563 .chain(['\n'])
9564 .collect::<String>();
9565
9566 edits.push((
9567 buffer.anchor_after(range_to_move.start)
9568 ..buffer.anchor_before(range_to_move.end),
9569 String::new(),
9570 ));
9571 let insertion_anchor = buffer.anchor_after(insertion_point);
9572 edits.push((insertion_anchor..insertion_anchor, text));
9573
9574 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9575
9576 // Move selections up
9577 new_selections.extend(contiguous_row_selections.drain(..).map(
9578 |mut selection| {
9579 selection.start.row -= row_delta;
9580 selection.end.row -= row_delta;
9581 selection
9582 },
9583 ));
9584
9585 // Move folds up
9586 unfold_ranges.push(range_to_move.clone());
9587 for fold in display_map.folds_in_range(
9588 buffer.anchor_before(range_to_move.start)
9589 ..buffer.anchor_after(range_to_move.end),
9590 ) {
9591 let mut start = fold.range.start.to_point(&buffer);
9592 let mut end = fold.range.end.to_point(&buffer);
9593 start.row -= row_delta;
9594 end.row -= row_delta;
9595 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9596 }
9597 }
9598 }
9599
9600 // If we didn't move line(s), preserve the existing selections
9601 new_selections.append(&mut contiguous_row_selections);
9602 }
9603
9604 self.transact(window, cx, |this, window, cx| {
9605 this.unfold_ranges(&unfold_ranges, true, true, cx);
9606 this.buffer.update(cx, |buffer, cx| {
9607 for (range, text) in edits {
9608 buffer.edit([(range, text)], None, cx);
9609 }
9610 });
9611 this.fold_creases(refold_creases, true, window, cx);
9612 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9613 s.select(new_selections);
9614 })
9615 });
9616 }
9617
9618 pub fn move_line_down(
9619 &mut self,
9620 _: &MoveLineDown,
9621 window: &mut Window,
9622 cx: &mut Context<Self>,
9623 ) {
9624 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9625
9626 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9627 let buffer = self.buffer.read(cx).snapshot(cx);
9628
9629 let mut edits = Vec::new();
9630 let mut unfold_ranges = Vec::new();
9631 let mut refold_creases = Vec::new();
9632
9633 let selections = self.selections.all::<Point>(cx);
9634 let mut selections = selections.iter().peekable();
9635 let mut contiguous_row_selections = Vec::new();
9636 let mut new_selections = Vec::new();
9637
9638 while let Some(selection) = selections.next() {
9639 // Find all the selections that span a contiguous row range
9640 let (start_row, end_row) = consume_contiguous_rows(
9641 &mut contiguous_row_selections,
9642 selection,
9643 &display_map,
9644 &mut selections,
9645 );
9646
9647 // Move the text spanned by the row range to be after the last line of the row range
9648 if end_row.0 <= buffer.max_point().row {
9649 let range_to_move =
9650 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9651 let insertion_point = display_map
9652 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9653 .0;
9654
9655 // Don't move lines across excerpt boundaries
9656 if buffer
9657 .excerpt_containing(range_to_move.start..insertion_point)
9658 .is_some()
9659 {
9660 let mut text = String::from("\n");
9661 text.extend(buffer.text_for_range(range_to_move.clone()));
9662 text.pop(); // Drop trailing newline
9663 edits.push((
9664 buffer.anchor_after(range_to_move.start)
9665 ..buffer.anchor_before(range_to_move.end),
9666 String::new(),
9667 ));
9668 let insertion_anchor = buffer.anchor_after(insertion_point);
9669 edits.push((insertion_anchor..insertion_anchor, text));
9670
9671 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9672
9673 // Move selections down
9674 new_selections.extend(contiguous_row_selections.drain(..).map(
9675 |mut selection| {
9676 selection.start.row += row_delta;
9677 selection.end.row += row_delta;
9678 selection
9679 },
9680 ));
9681
9682 // Move folds down
9683 unfold_ranges.push(range_to_move.clone());
9684 for fold in display_map.folds_in_range(
9685 buffer.anchor_before(range_to_move.start)
9686 ..buffer.anchor_after(range_to_move.end),
9687 ) {
9688 let mut start = fold.range.start.to_point(&buffer);
9689 let mut end = fold.range.end.to_point(&buffer);
9690 start.row += row_delta;
9691 end.row += row_delta;
9692 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9693 }
9694 }
9695 }
9696
9697 // If we didn't move line(s), preserve the existing selections
9698 new_selections.append(&mut contiguous_row_selections);
9699 }
9700
9701 self.transact(window, cx, |this, window, cx| {
9702 this.unfold_ranges(&unfold_ranges, true, true, cx);
9703 this.buffer.update(cx, |buffer, cx| {
9704 for (range, text) in edits {
9705 buffer.edit([(range, text)], None, cx);
9706 }
9707 });
9708 this.fold_creases(refold_creases, true, window, cx);
9709 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9710 s.select(new_selections)
9711 });
9712 });
9713 }
9714
9715 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9716 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9717 let text_layout_details = &self.text_layout_details(window);
9718 self.transact(window, cx, |this, window, cx| {
9719 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9720 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9721 s.move_with(|display_map, selection| {
9722 if !selection.is_empty() {
9723 return;
9724 }
9725
9726 let mut head = selection.head();
9727 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9728 if head.column() == display_map.line_len(head.row()) {
9729 transpose_offset = display_map
9730 .buffer_snapshot
9731 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9732 }
9733
9734 if transpose_offset == 0 {
9735 return;
9736 }
9737
9738 *head.column_mut() += 1;
9739 head = display_map.clip_point(head, Bias::Right);
9740 let goal = SelectionGoal::HorizontalPosition(
9741 display_map
9742 .x_for_display_point(head, text_layout_details)
9743 .into(),
9744 );
9745 selection.collapse_to(head, goal);
9746
9747 let transpose_start = display_map
9748 .buffer_snapshot
9749 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9750 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9751 let transpose_end = display_map
9752 .buffer_snapshot
9753 .clip_offset(transpose_offset + 1, Bias::Right);
9754 if let Some(ch) =
9755 display_map.buffer_snapshot.chars_at(transpose_start).next()
9756 {
9757 edits.push((transpose_start..transpose_offset, String::new()));
9758 edits.push((transpose_end..transpose_end, ch.to_string()));
9759 }
9760 }
9761 });
9762 edits
9763 });
9764 this.buffer
9765 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9766 let selections = this.selections.all::<usize>(cx);
9767 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9768 s.select(selections);
9769 });
9770 });
9771 }
9772
9773 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9774 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9775 self.rewrap_impl(RewrapOptions::default(), cx)
9776 }
9777
9778 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9779 let buffer = self.buffer.read(cx).snapshot(cx);
9780 let selections = self.selections.all::<Point>(cx);
9781 let mut selections = selections.iter().peekable();
9782
9783 let mut edits = Vec::new();
9784 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9785
9786 while let Some(selection) = selections.next() {
9787 let mut start_row = selection.start.row;
9788 let mut end_row = selection.end.row;
9789
9790 // Skip selections that overlap with a range that has already been rewrapped.
9791 let selection_range = start_row..end_row;
9792 if rewrapped_row_ranges
9793 .iter()
9794 .any(|range| range.overlaps(&selection_range))
9795 {
9796 continue;
9797 }
9798
9799 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9800
9801 // Since not all lines in the selection may be at the same indent
9802 // level, choose the indent size that is the most common between all
9803 // of the lines.
9804 //
9805 // If there is a tie, we use the deepest indent.
9806 let (indent_size, indent_end) = {
9807 let mut indent_size_occurrences = HashMap::default();
9808 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9809
9810 for row in start_row..=end_row {
9811 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9812 rows_by_indent_size.entry(indent).or_default().push(row);
9813 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9814 }
9815
9816 let indent_size = indent_size_occurrences
9817 .into_iter()
9818 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9819 .map(|(indent, _)| indent)
9820 .unwrap_or_default();
9821 let row = rows_by_indent_size[&indent_size][0];
9822 let indent_end = Point::new(row, indent_size.len);
9823
9824 (indent_size, indent_end)
9825 };
9826
9827 let mut line_prefix = indent_size.chars().collect::<String>();
9828
9829 let mut inside_comment = false;
9830 if let Some(comment_prefix) =
9831 buffer
9832 .language_scope_at(selection.head())
9833 .and_then(|language| {
9834 language
9835 .line_comment_prefixes()
9836 .iter()
9837 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9838 .cloned()
9839 })
9840 {
9841 line_prefix.push_str(&comment_prefix);
9842 inside_comment = true;
9843 }
9844
9845 let language_settings = buffer.language_settings_at(selection.head(), cx);
9846 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9847 RewrapBehavior::InComments => inside_comment,
9848 RewrapBehavior::InSelections => !selection.is_empty(),
9849 RewrapBehavior::Anywhere => true,
9850 };
9851
9852 let should_rewrap = options.override_language_settings
9853 || allow_rewrap_based_on_language
9854 || self.hard_wrap.is_some();
9855 if !should_rewrap {
9856 continue;
9857 }
9858
9859 if selection.is_empty() {
9860 'expand_upwards: while start_row > 0 {
9861 let prev_row = start_row - 1;
9862 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9863 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9864 {
9865 start_row = prev_row;
9866 } else {
9867 break 'expand_upwards;
9868 }
9869 }
9870
9871 'expand_downwards: while end_row < buffer.max_point().row {
9872 let next_row = end_row + 1;
9873 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9874 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9875 {
9876 end_row = next_row;
9877 } else {
9878 break 'expand_downwards;
9879 }
9880 }
9881 }
9882
9883 let start = Point::new(start_row, 0);
9884 let start_offset = start.to_offset(&buffer);
9885 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9886 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9887 let Some(lines_without_prefixes) = selection_text
9888 .lines()
9889 .map(|line| {
9890 line.strip_prefix(&line_prefix)
9891 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9892 .ok_or_else(|| {
9893 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9894 })
9895 })
9896 .collect::<Result<Vec<_>, _>>()
9897 .log_err()
9898 else {
9899 continue;
9900 };
9901
9902 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9903 buffer
9904 .language_settings_at(Point::new(start_row, 0), cx)
9905 .preferred_line_length as usize
9906 });
9907 let wrapped_text = wrap_with_prefix(
9908 line_prefix,
9909 lines_without_prefixes.join("\n"),
9910 wrap_column,
9911 tab_size,
9912 options.preserve_existing_whitespace,
9913 );
9914
9915 // TODO: should always use char-based diff while still supporting cursor behavior that
9916 // matches vim.
9917 let mut diff_options = DiffOptions::default();
9918 if options.override_language_settings {
9919 diff_options.max_word_diff_len = 0;
9920 diff_options.max_word_diff_line_count = 0;
9921 } else {
9922 diff_options.max_word_diff_len = usize::MAX;
9923 diff_options.max_word_diff_line_count = usize::MAX;
9924 }
9925
9926 for (old_range, new_text) in
9927 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9928 {
9929 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9930 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9931 edits.push((edit_start..edit_end, new_text));
9932 }
9933
9934 rewrapped_row_ranges.push(start_row..=end_row);
9935 }
9936
9937 self.buffer
9938 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9939 }
9940
9941 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9942 let mut text = String::new();
9943 let buffer = self.buffer.read(cx).snapshot(cx);
9944 let mut selections = self.selections.all::<Point>(cx);
9945 let mut clipboard_selections = Vec::with_capacity(selections.len());
9946 {
9947 let max_point = buffer.max_point();
9948 let mut is_first = true;
9949 for selection in &mut selections {
9950 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9951 if is_entire_line {
9952 selection.start = Point::new(selection.start.row, 0);
9953 if !selection.is_empty() && selection.end.column == 0 {
9954 selection.end = cmp::min(max_point, selection.end);
9955 } else {
9956 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9957 }
9958 selection.goal = SelectionGoal::None;
9959 }
9960 if is_first {
9961 is_first = false;
9962 } else {
9963 text += "\n";
9964 }
9965 let mut len = 0;
9966 for chunk in buffer.text_for_range(selection.start..selection.end) {
9967 text.push_str(chunk);
9968 len += chunk.len();
9969 }
9970 clipboard_selections.push(ClipboardSelection {
9971 len,
9972 is_entire_line,
9973 first_line_indent: buffer
9974 .indent_size_for_line(MultiBufferRow(selection.start.row))
9975 .len,
9976 });
9977 }
9978 }
9979
9980 self.transact(window, cx, |this, window, cx| {
9981 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9982 s.select(selections);
9983 });
9984 this.insert("", window, cx);
9985 });
9986 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9987 }
9988
9989 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9990 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9991 let item = self.cut_common(window, cx);
9992 cx.write_to_clipboard(item);
9993 }
9994
9995 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9996 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9997 self.change_selections(None, window, cx, |s| {
9998 s.move_with(|snapshot, sel| {
9999 if sel.is_empty() {
10000 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10001 }
10002 });
10003 });
10004 let item = self.cut_common(window, cx);
10005 cx.set_global(KillRing(item))
10006 }
10007
10008 pub fn kill_ring_yank(
10009 &mut self,
10010 _: &KillRingYank,
10011 window: &mut Window,
10012 cx: &mut Context<Self>,
10013 ) {
10014 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10015 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10016 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10017 (kill_ring.text().to_string(), kill_ring.metadata_json())
10018 } else {
10019 return;
10020 }
10021 } else {
10022 return;
10023 };
10024 self.do_paste(&text, metadata, false, window, cx);
10025 }
10026
10027 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10028 self.do_copy(true, cx);
10029 }
10030
10031 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10032 self.do_copy(false, cx);
10033 }
10034
10035 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10036 let selections = self.selections.all::<Point>(cx);
10037 let buffer = self.buffer.read(cx).read(cx);
10038 let mut text = String::new();
10039
10040 let mut clipboard_selections = Vec::with_capacity(selections.len());
10041 {
10042 let max_point = buffer.max_point();
10043 let mut is_first = true;
10044 for selection in &selections {
10045 let mut start = selection.start;
10046 let mut end = selection.end;
10047 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10048 if is_entire_line {
10049 start = Point::new(start.row, 0);
10050 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10051 }
10052
10053 let mut trimmed_selections = Vec::new();
10054 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10055 let row = MultiBufferRow(start.row);
10056 let first_indent = buffer.indent_size_for_line(row);
10057 if first_indent.len == 0 || start.column > first_indent.len {
10058 trimmed_selections.push(start..end);
10059 } else {
10060 trimmed_selections.push(
10061 Point::new(row.0, first_indent.len)
10062 ..Point::new(row.0, buffer.line_len(row)),
10063 );
10064 for row in start.row + 1..=end.row {
10065 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10066 if row_indent_size.len >= first_indent.len {
10067 trimmed_selections.push(
10068 Point::new(row, first_indent.len)
10069 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10070 );
10071 } else {
10072 trimmed_selections.clear();
10073 trimmed_selections.push(start..end);
10074 break;
10075 }
10076 }
10077 }
10078 } else {
10079 trimmed_selections.push(start..end);
10080 }
10081
10082 for trimmed_range in trimmed_selections {
10083 if is_first {
10084 is_first = false;
10085 } else {
10086 text += "\n";
10087 }
10088 let mut len = 0;
10089 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10090 text.push_str(chunk);
10091 len += chunk.len();
10092 }
10093 clipboard_selections.push(ClipboardSelection {
10094 len,
10095 is_entire_line,
10096 first_line_indent: buffer
10097 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10098 .len,
10099 });
10100 }
10101 }
10102 }
10103
10104 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10105 text,
10106 clipboard_selections,
10107 ));
10108 }
10109
10110 pub fn do_paste(
10111 &mut self,
10112 text: &String,
10113 clipboard_selections: Option<Vec<ClipboardSelection>>,
10114 handle_entire_lines: bool,
10115 window: &mut Window,
10116 cx: &mut Context<Self>,
10117 ) {
10118 if self.read_only(cx) {
10119 return;
10120 }
10121
10122 let clipboard_text = Cow::Borrowed(text);
10123
10124 self.transact(window, cx, |this, window, cx| {
10125 if let Some(mut clipboard_selections) = clipboard_selections {
10126 let old_selections = this.selections.all::<usize>(cx);
10127 let all_selections_were_entire_line =
10128 clipboard_selections.iter().all(|s| s.is_entire_line);
10129 let first_selection_indent_column =
10130 clipboard_selections.first().map(|s| s.first_line_indent);
10131 if clipboard_selections.len() != old_selections.len() {
10132 clipboard_selections.drain(..);
10133 }
10134 let cursor_offset = this.selections.last::<usize>(cx).head();
10135 let mut auto_indent_on_paste = true;
10136
10137 this.buffer.update(cx, |buffer, cx| {
10138 let snapshot = buffer.read(cx);
10139 auto_indent_on_paste = snapshot
10140 .language_settings_at(cursor_offset, cx)
10141 .auto_indent_on_paste;
10142
10143 let mut start_offset = 0;
10144 let mut edits = Vec::new();
10145 let mut original_indent_columns = Vec::new();
10146 for (ix, selection) in old_selections.iter().enumerate() {
10147 let to_insert;
10148 let entire_line;
10149 let original_indent_column;
10150 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10151 let end_offset = start_offset + clipboard_selection.len;
10152 to_insert = &clipboard_text[start_offset..end_offset];
10153 entire_line = clipboard_selection.is_entire_line;
10154 start_offset = end_offset + 1;
10155 original_indent_column = Some(clipboard_selection.first_line_indent);
10156 } else {
10157 to_insert = clipboard_text.as_str();
10158 entire_line = all_selections_were_entire_line;
10159 original_indent_column = first_selection_indent_column
10160 }
10161
10162 // If the corresponding selection was empty when this slice of the
10163 // clipboard text was written, then the entire line containing the
10164 // selection was copied. If this selection is also currently empty,
10165 // then paste the line before the current line of the buffer.
10166 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10167 let column = selection.start.to_point(&snapshot).column as usize;
10168 let line_start = selection.start - column;
10169 line_start..line_start
10170 } else {
10171 selection.range()
10172 };
10173
10174 edits.push((range, to_insert));
10175 original_indent_columns.push(original_indent_column);
10176 }
10177 drop(snapshot);
10178
10179 buffer.edit(
10180 edits,
10181 if auto_indent_on_paste {
10182 Some(AutoindentMode::Block {
10183 original_indent_columns,
10184 })
10185 } else {
10186 None
10187 },
10188 cx,
10189 );
10190 });
10191
10192 let selections = this.selections.all::<usize>(cx);
10193 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10194 s.select(selections)
10195 });
10196 } else {
10197 this.insert(&clipboard_text, window, cx);
10198 }
10199 });
10200 }
10201
10202 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10203 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10204 if let Some(item) = cx.read_from_clipboard() {
10205 let entries = item.entries();
10206
10207 match entries.first() {
10208 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10209 // of all the pasted entries.
10210 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10211 .do_paste(
10212 clipboard_string.text(),
10213 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10214 true,
10215 window,
10216 cx,
10217 ),
10218 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10219 }
10220 }
10221 }
10222
10223 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10224 if self.read_only(cx) {
10225 return;
10226 }
10227
10228 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10229
10230 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10231 if let Some((selections, _)) =
10232 self.selection_history.transaction(transaction_id).cloned()
10233 {
10234 self.change_selections(None, window, cx, |s| {
10235 s.select_anchors(selections.to_vec());
10236 });
10237 } else {
10238 log::error!(
10239 "No entry in selection_history found for undo. \
10240 This may correspond to a bug where undo does not update the selection. \
10241 If this is occurring, please add details to \
10242 https://github.com/zed-industries/zed/issues/22692"
10243 );
10244 }
10245 self.request_autoscroll(Autoscroll::fit(), cx);
10246 self.unmark_text(window, cx);
10247 self.refresh_inline_completion(true, false, window, cx);
10248 cx.emit(EditorEvent::Edited { transaction_id });
10249 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10250 }
10251 }
10252
10253 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10254 if self.read_only(cx) {
10255 return;
10256 }
10257
10258 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10259
10260 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10261 if let Some((_, Some(selections))) =
10262 self.selection_history.transaction(transaction_id).cloned()
10263 {
10264 self.change_selections(None, window, cx, |s| {
10265 s.select_anchors(selections.to_vec());
10266 });
10267 } else {
10268 log::error!(
10269 "No entry in selection_history found for redo. \
10270 This may correspond to a bug where undo does not update the selection. \
10271 If this is occurring, please add details to \
10272 https://github.com/zed-industries/zed/issues/22692"
10273 );
10274 }
10275 self.request_autoscroll(Autoscroll::fit(), cx);
10276 self.unmark_text(window, cx);
10277 self.refresh_inline_completion(true, false, window, cx);
10278 cx.emit(EditorEvent::Edited { transaction_id });
10279 }
10280 }
10281
10282 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10283 self.buffer
10284 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10285 }
10286
10287 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10288 self.buffer
10289 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10290 }
10291
10292 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10293 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10294 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10295 s.move_with(|map, selection| {
10296 let cursor = if selection.is_empty() {
10297 movement::left(map, selection.start)
10298 } else {
10299 selection.start
10300 };
10301 selection.collapse_to(cursor, SelectionGoal::None);
10302 });
10303 })
10304 }
10305
10306 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10307 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10308 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10309 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10310 })
10311 }
10312
10313 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10314 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10315 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10316 s.move_with(|map, selection| {
10317 let cursor = if selection.is_empty() {
10318 movement::right(map, selection.end)
10319 } else {
10320 selection.end
10321 };
10322 selection.collapse_to(cursor, SelectionGoal::None)
10323 });
10324 })
10325 }
10326
10327 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10328 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10329 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10330 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10331 })
10332 }
10333
10334 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10335 if self.take_rename(true, window, cx).is_some() {
10336 return;
10337 }
10338
10339 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10340 cx.propagate();
10341 return;
10342 }
10343
10344 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10345
10346 let text_layout_details = &self.text_layout_details(window);
10347 let selection_count = self.selections.count();
10348 let first_selection = self.selections.first_anchor();
10349
10350 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10351 s.move_with(|map, selection| {
10352 if !selection.is_empty() {
10353 selection.goal = SelectionGoal::None;
10354 }
10355 let (cursor, goal) = movement::up(
10356 map,
10357 selection.start,
10358 selection.goal,
10359 false,
10360 text_layout_details,
10361 );
10362 selection.collapse_to(cursor, goal);
10363 });
10364 });
10365
10366 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10367 {
10368 cx.propagate();
10369 }
10370 }
10371
10372 pub fn move_up_by_lines(
10373 &mut self,
10374 action: &MoveUpByLines,
10375 window: &mut Window,
10376 cx: &mut Context<Self>,
10377 ) {
10378 if self.take_rename(true, window, cx).is_some() {
10379 return;
10380 }
10381
10382 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10383 cx.propagate();
10384 return;
10385 }
10386
10387 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10388
10389 let text_layout_details = &self.text_layout_details(window);
10390
10391 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10392 s.move_with(|map, selection| {
10393 if !selection.is_empty() {
10394 selection.goal = SelectionGoal::None;
10395 }
10396 let (cursor, goal) = movement::up_by_rows(
10397 map,
10398 selection.start,
10399 action.lines,
10400 selection.goal,
10401 false,
10402 text_layout_details,
10403 );
10404 selection.collapse_to(cursor, goal);
10405 });
10406 })
10407 }
10408
10409 pub fn move_down_by_lines(
10410 &mut self,
10411 action: &MoveDownByLines,
10412 window: &mut Window,
10413 cx: &mut Context<Self>,
10414 ) {
10415 if self.take_rename(true, window, cx).is_some() {
10416 return;
10417 }
10418
10419 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10420 cx.propagate();
10421 return;
10422 }
10423
10424 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10425
10426 let text_layout_details = &self.text_layout_details(window);
10427
10428 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10429 s.move_with(|map, selection| {
10430 if !selection.is_empty() {
10431 selection.goal = SelectionGoal::None;
10432 }
10433 let (cursor, goal) = movement::down_by_rows(
10434 map,
10435 selection.start,
10436 action.lines,
10437 selection.goal,
10438 false,
10439 text_layout_details,
10440 );
10441 selection.collapse_to(cursor, goal);
10442 });
10443 })
10444 }
10445
10446 pub fn select_down_by_lines(
10447 &mut self,
10448 action: &SelectDownByLines,
10449 window: &mut Window,
10450 cx: &mut Context<Self>,
10451 ) {
10452 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10453 let text_layout_details = &self.text_layout_details(window);
10454 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10455 s.move_heads_with(|map, head, goal| {
10456 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10457 })
10458 })
10459 }
10460
10461 pub fn select_up_by_lines(
10462 &mut self,
10463 action: &SelectUpByLines,
10464 window: &mut Window,
10465 cx: &mut Context<Self>,
10466 ) {
10467 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10468 let text_layout_details = &self.text_layout_details(window);
10469 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10470 s.move_heads_with(|map, head, goal| {
10471 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10472 })
10473 })
10474 }
10475
10476 pub fn select_page_up(
10477 &mut self,
10478 _: &SelectPageUp,
10479 window: &mut Window,
10480 cx: &mut Context<Self>,
10481 ) {
10482 let Some(row_count) = self.visible_row_count() else {
10483 return;
10484 };
10485
10486 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10487
10488 let text_layout_details = &self.text_layout_details(window);
10489
10490 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10491 s.move_heads_with(|map, head, goal| {
10492 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10493 })
10494 })
10495 }
10496
10497 pub fn move_page_up(
10498 &mut self,
10499 action: &MovePageUp,
10500 window: &mut Window,
10501 cx: &mut Context<Self>,
10502 ) {
10503 if self.take_rename(true, window, cx).is_some() {
10504 return;
10505 }
10506
10507 if self
10508 .context_menu
10509 .borrow_mut()
10510 .as_mut()
10511 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10512 .unwrap_or(false)
10513 {
10514 return;
10515 }
10516
10517 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10518 cx.propagate();
10519 return;
10520 }
10521
10522 let Some(row_count) = self.visible_row_count() else {
10523 return;
10524 };
10525
10526 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10527
10528 let autoscroll = if action.center_cursor {
10529 Autoscroll::center()
10530 } else {
10531 Autoscroll::fit()
10532 };
10533
10534 let text_layout_details = &self.text_layout_details(window);
10535
10536 self.change_selections(Some(autoscroll), window, cx, |s| {
10537 s.move_with(|map, selection| {
10538 if !selection.is_empty() {
10539 selection.goal = SelectionGoal::None;
10540 }
10541 let (cursor, goal) = movement::up_by_rows(
10542 map,
10543 selection.end,
10544 row_count,
10545 selection.goal,
10546 false,
10547 text_layout_details,
10548 );
10549 selection.collapse_to(cursor, goal);
10550 });
10551 });
10552 }
10553
10554 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10555 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10556 let text_layout_details = &self.text_layout_details(window);
10557 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10558 s.move_heads_with(|map, head, goal| {
10559 movement::up(map, head, goal, false, text_layout_details)
10560 })
10561 })
10562 }
10563
10564 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10565 self.take_rename(true, window, cx);
10566
10567 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10568 cx.propagate();
10569 return;
10570 }
10571
10572 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10573
10574 let text_layout_details = &self.text_layout_details(window);
10575 let selection_count = self.selections.count();
10576 let first_selection = self.selections.first_anchor();
10577
10578 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10579 s.move_with(|map, selection| {
10580 if !selection.is_empty() {
10581 selection.goal = SelectionGoal::None;
10582 }
10583 let (cursor, goal) = movement::down(
10584 map,
10585 selection.end,
10586 selection.goal,
10587 false,
10588 text_layout_details,
10589 );
10590 selection.collapse_to(cursor, goal);
10591 });
10592 });
10593
10594 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10595 {
10596 cx.propagate();
10597 }
10598 }
10599
10600 pub fn select_page_down(
10601 &mut self,
10602 _: &SelectPageDown,
10603 window: &mut Window,
10604 cx: &mut Context<Self>,
10605 ) {
10606 let Some(row_count) = self.visible_row_count() else {
10607 return;
10608 };
10609
10610 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10611
10612 let text_layout_details = &self.text_layout_details(window);
10613
10614 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10615 s.move_heads_with(|map, head, goal| {
10616 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10617 })
10618 })
10619 }
10620
10621 pub fn move_page_down(
10622 &mut self,
10623 action: &MovePageDown,
10624 window: &mut Window,
10625 cx: &mut Context<Self>,
10626 ) {
10627 if self.take_rename(true, window, cx).is_some() {
10628 return;
10629 }
10630
10631 if self
10632 .context_menu
10633 .borrow_mut()
10634 .as_mut()
10635 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10636 .unwrap_or(false)
10637 {
10638 return;
10639 }
10640
10641 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10642 cx.propagate();
10643 return;
10644 }
10645
10646 let Some(row_count) = self.visible_row_count() else {
10647 return;
10648 };
10649
10650 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10651
10652 let autoscroll = if action.center_cursor {
10653 Autoscroll::center()
10654 } else {
10655 Autoscroll::fit()
10656 };
10657
10658 let text_layout_details = &self.text_layout_details(window);
10659 self.change_selections(Some(autoscroll), window, cx, |s| {
10660 s.move_with(|map, selection| {
10661 if !selection.is_empty() {
10662 selection.goal = SelectionGoal::None;
10663 }
10664 let (cursor, goal) = movement::down_by_rows(
10665 map,
10666 selection.end,
10667 row_count,
10668 selection.goal,
10669 false,
10670 text_layout_details,
10671 );
10672 selection.collapse_to(cursor, goal);
10673 });
10674 });
10675 }
10676
10677 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10678 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10679 let text_layout_details = &self.text_layout_details(window);
10680 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10681 s.move_heads_with(|map, head, goal| {
10682 movement::down(map, head, goal, false, text_layout_details)
10683 })
10684 });
10685 }
10686
10687 pub fn context_menu_first(
10688 &mut self,
10689 _: &ContextMenuFirst,
10690 _window: &mut Window,
10691 cx: &mut Context<Self>,
10692 ) {
10693 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10694 context_menu.select_first(self.completion_provider.as_deref(), cx);
10695 }
10696 }
10697
10698 pub fn context_menu_prev(
10699 &mut self,
10700 _: &ContextMenuPrevious,
10701 _window: &mut Window,
10702 cx: &mut Context<Self>,
10703 ) {
10704 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10705 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10706 }
10707 }
10708
10709 pub fn context_menu_next(
10710 &mut self,
10711 _: &ContextMenuNext,
10712 _window: &mut Window,
10713 cx: &mut Context<Self>,
10714 ) {
10715 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10716 context_menu.select_next(self.completion_provider.as_deref(), cx);
10717 }
10718 }
10719
10720 pub fn context_menu_last(
10721 &mut self,
10722 _: &ContextMenuLast,
10723 _window: &mut Window,
10724 cx: &mut Context<Self>,
10725 ) {
10726 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10727 context_menu.select_last(self.completion_provider.as_deref(), cx);
10728 }
10729 }
10730
10731 pub fn move_to_previous_word_start(
10732 &mut self,
10733 _: &MoveToPreviousWordStart,
10734 window: &mut Window,
10735 cx: &mut Context<Self>,
10736 ) {
10737 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10738 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10739 s.move_cursors_with(|map, head, _| {
10740 (
10741 movement::previous_word_start(map, head),
10742 SelectionGoal::None,
10743 )
10744 });
10745 })
10746 }
10747
10748 pub fn move_to_previous_subword_start(
10749 &mut self,
10750 _: &MoveToPreviousSubwordStart,
10751 window: &mut Window,
10752 cx: &mut Context<Self>,
10753 ) {
10754 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10755 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10756 s.move_cursors_with(|map, head, _| {
10757 (
10758 movement::previous_subword_start(map, head),
10759 SelectionGoal::None,
10760 )
10761 });
10762 })
10763 }
10764
10765 pub fn select_to_previous_word_start(
10766 &mut self,
10767 _: &SelectToPreviousWordStart,
10768 window: &mut Window,
10769 cx: &mut Context<Self>,
10770 ) {
10771 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10773 s.move_heads_with(|map, head, _| {
10774 (
10775 movement::previous_word_start(map, head),
10776 SelectionGoal::None,
10777 )
10778 });
10779 })
10780 }
10781
10782 pub fn select_to_previous_subword_start(
10783 &mut self,
10784 _: &SelectToPreviousSubwordStart,
10785 window: &mut Window,
10786 cx: &mut Context<Self>,
10787 ) {
10788 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10789 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10790 s.move_heads_with(|map, head, _| {
10791 (
10792 movement::previous_subword_start(map, head),
10793 SelectionGoal::None,
10794 )
10795 });
10796 })
10797 }
10798
10799 pub fn delete_to_previous_word_start(
10800 &mut self,
10801 action: &DeleteToPreviousWordStart,
10802 window: &mut Window,
10803 cx: &mut Context<Self>,
10804 ) {
10805 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10806 self.transact(window, cx, |this, window, cx| {
10807 this.select_autoclose_pair(window, cx);
10808 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10809 s.move_with(|map, selection| {
10810 if selection.is_empty() {
10811 let cursor = if action.ignore_newlines {
10812 movement::previous_word_start(map, selection.head())
10813 } else {
10814 movement::previous_word_start_or_newline(map, selection.head())
10815 };
10816 selection.set_head(cursor, SelectionGoal::None);
10817 }
10818 });
10819 });
10820 this.insert("", window, cx);
10821 });
10822 }
10823
10824 pub fn delete_to_previous_subword_start(
10825 &mut self,
10826 _: &DeleteToPreviousSubwordStart,
10827 window: &mut Window,
10828 cx: &mut Context<Self>,
10829 ) {
10830 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10831 self.transact(window, cx, |this, window, cx| {
10832 this.select_autoclose_pair(window, cx);
10833 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10834 s.move_with(|map, selection| {
10835 if selection.is_empty() {
10836 let cursor = movement::previous_subword_start(map, selection.head());
10837 selection.set_head(cursor, SelectionGoal::None);
10838 }
10839 });
10840 });
10841 this.insert("", window, cx);
10842 });
10843 }
10844
10845 pub fn move_to_next_word_end(
10846 &mut self,
10847 _: &MoveToNextWordEnd,
10848 window: &mut Window,
10849 cx: &mut Context<Self>,
10850 ) {
10851 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10852 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10853 s.move_cursors_with(|map, head, _| {
10854 (movement::next_word_end(map, head), SelectionGoal::None)
10855 });
10856 })
10857 }
10858
10859 pub fn move_to_next_subword_end(
10860 &mut self,
10861 _: &MoveToNextSubwordEnd,
10862 window: &mut Window,
10863 cx: &mut Context<Self>,
10864 ) {
10865 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10866 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10867 s.move_cursors_with(|map, head, _| {
10868 (movement::next_subword_end(map, head), SelectionGoal::None)
10869 });
10870 })
10871 }
10872
10873 pub fn select_to_next_word_end(
10874 &mut self,
10875 _: &SelectToNextWordEnd,
10876 window: &mut Window,
10877 cx: &mut Context<Self>,
10878 ) {
10879 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10880 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10881 s.move_heads_with(|map, head, _| {
10882 (movement::next_word_end(map, head), SelectionGoal::None)
10883 });
10884 })
10885 }
10886
10887 pub fn select_to_next_subword_end(
10888 &mut self,
10889 _: &SelectToNextSubwordEnd,
10890 window: &mut Window,
10891 cx: &mut Context<Self>,
10892 ) {
10893 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10894 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10895 s.move_heads_with(|map, head, _| {
10896 (movement::next_subword_end(map, head), SelectionGoal::None)
10897 });
10898 })
10899 }
10900
10901 pub fn delete_to_next_word_end(
10902 &mut self,
10903 action: &DeleteToNextWordEnd,
10904 window: &mut Window,
10905 cx: &mut Context<Self>,
10906 ) {
10907 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10908 self.transact(window, cx, |this, window, cx| {
10909 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10910 s.move_with(|map, selection| {
10911 if selection.is_empty() {
10912 let cursor = if action.ignore_newlines {
10913 movement::next_word_end(map, selection.head())
10914 } else {
10915 movement::next_word_end_or_newline(map, selection.head())
10916 };
10917 selection.set_head(cursor, SelectionGoal::None);
10918 }
10919 });
10920 });
10921 this.insert("", window, cx);
10922 });
10923 }
10924
10925 pub fn delete_to_next_subword_end(
10926 &mut self,
10927 _: &DeleteToNextSubwordEnd,
10928 window: &mut Window,
10929 cx: &mut Context<Self>,
10930 ) {
10931 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10932 self.transact(window, cx, |this, window, cx| {
10933 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10934 s.move_with(|map, selection| {
10935 if selection.is_empty() {
10936 let cursor = movement::next_subword_end(map, selection.head());
10937 selection.set_head(cursor, SelectionGoal::None);
10938 }
10939 });
10940 });
10941 this.insert("", window, cx);
10942 });
10943 }
10944
10945 pub fn move_to_beginning_of_line(
10946 &mut self,
10947 action: &MoveToBeginningOfLine,
10948 window: &mut Window,
10949 cx: &mut Context<Self>,
10950 ) {
10951 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10952 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10953 s.move_cursors_with(|map, head, _| {
10954 (
10955 movement::indented_line_beginning(
10956 map,
10957 head,
10958 action.stop_at_soft_wraps,
10959 action.stop_at_indent,
10960 ),
10961 SelectionGoal::None,
10962 )
10963 });
10964 })
10965 }
10966
10967 pub fn select_to_beginning_of_line(
10968 &mut self,
10969 action: &SelectToBeginningOfLine,
10970 window: &mut Window,
10971 cx: &mut Context<Self>,
10972 ) {
10973 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10974 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10975 s.move_heads_with(|map, head, _| {
10976 (
10977 movement::indented_line_beginning(
10978 map,
10979 head,
10980 action.stop_at_soft_wraps,
10981 action.stop_at_indent,
10982 ),
10983 SelectionGoal::None,
10984 )
10985 });
10986 });
10987 }
10988
10989 pub fn delete_to_beginning_of_line(
10990 &mut self,
10991 action: &DeleteToBeginningOfLine,
10992 window: &mut Window,
10993 cx: &mut Context<Self>,
10994 ) {
10995 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10996 self.transact(window, cx, |this, window, cx| {
10997 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10998 s.move_with(|_, selection| {
10999 selection.reversed = true;
11000 });
11001 });
11002
11003 this.select_to_beginning_of_line(
11004 &SelectToBeginningOfLine {
11005 stop_at_soft_wraps: false,
11006 stop_at_indent: action.stop_at_indent,
11007 },
11008 window,
11009 cx,
11010 );
11011 this.backspace(&Backspace, window, cx);
11012 });
11013 }
11014
11015 pub fn move_to_end_of_line(
11016 &mut self,
11017 action: &MoveToEndOfLine,
11018 window: &mut Window,
11019 cx: &mut Context<Self>,
11020 ) {
11021 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11022 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11023 s.move_cursors_with(|map, head, _| {
11024 (
11025 movement::line_end(map, head, action.stop_at_soft_wraps),
11026 SelectionGoal::None,
11027 )
11028 });
11029 })
11030 }
11031
11032 pub fn select_to_end_of_line(
11033 &mut self,
11034 action: &SelectToEndOfLine,
11035 window: &mut Window,
11036 cx: &mut Context<Self>,
11037 ) {
11038 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11039 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11040 s.move_heads_with(|map, head, _| {
11041 (
11042 movement::line_end(map, head, action.stop_at_soft_wraps),
11043 SelectionGoal::None,
11044 )
11045 });
11046 })
11047 }
11048
11049 pub fn delete_to_end_of_line(
11050 &mut self,
11051 _: &DeleteToEndOfLine,
11052 window: &mut Window,
11053 cx: &mut Context<Self>,
11054 ) {
11055 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11056 self.transact(window, cx, |this, window, cx| {
11057 this.select_to_end_of_line(
11058 &SelectToEndOfLine {
11059 stop_at_soft_wraps: false,
11060 },
11061 window,
11062 cx,
11063 );
11064 this.delete(&Delete, window, cx);
11065 });
11066 }
11067
11068 pub fn cut_to_end_of_line(
11069 &mut self,
11070 _: &CutToEndOfLine,
11071 window: &mut Window,
11072 cx: &mut Context<Self>,
11073 ) {
11074 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11075 self.transact(window, cx, |this, window, cx| {
11076 this.select_to_end_of_line(
11077 &SelectToEndOfLine {
11078 stop_at_soft_wraps: false,
11079 },
11080 window,
11081 cx,
11082 );
11083 this.cut(&Cut, window, cx);
11084 });
11085 }
11086
11087 pub fn move_to_start_of_paragraph(
11088 &mut self,
11089 _: &MoveToStartOfParagraph,
11090 window: &mut Window,
11091 cx: &mut Context<Self>,
11092 ) {
11093 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11094 cx.propagate();
11095 return;
11096 }
11097 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11098 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11099 s.move_with(|map, selection| {
11100 selection.collapse_to(
11101 movement::start_of_paragraph(map, selection.head(), 1),
11102 SelectionGoal::None,
11103 )
11104 });
11105 })
11106 }
11107
11108 pub fn move_to_end_of_paragraph(
11109 &mut self,
11110 _: &MoveToEndOfParagraph,
11111 window: &mut Window,
11112 cx: &mut Context<Self>,
11113 ) {
11114 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11115 cx.propagate();
11116 return;
11117 }
11118 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11119 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11120 s.move_with(|map, selection| {
11121 selection.collapse_to(
11122 movement::end_of_paragraph(map, selection.head(), 1),
11123 SelectionGoal::None,
11124 )
11125 });
11126 })
11127 }
11128
11129 pub fn select_to_start_of_paragraph(
11130 &mut self,
11131 _: &SelectToStartOfParagraph,
11132 window: &mut Window,
11133 cx: &mut Context<Self>,
11134 ) {
11135 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11136 cx.propagate();
11137 return;
11138 }
11139 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11140 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11141 s.move_heads_with(|map, head, _| {
11142 (
11143 movement::start_of_paragraph(map, head, 1),
11144 SelectionGoal::None,
11145 )
11146 });
11147 })
11148 }
11149
11150 pub fn select_to_end_of_paragraph(
11151 &mut self,
11152 _: &SelectToEndOfParagraph,
11153 window: &mut Window,
11154 cx: &mut Context<Self>,
11155 ) {
11156 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11157 cx.propagate();
11158 return;
11159 }
11160 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11161 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11162 s.move_heads_with(|map, head, _| {
11163 (
11164 movement::end_of_paragraph(map, head, 1),
11165 SelectionGoal::None,
11166 )
11167 });
11168 })
11169 }
11170
11171 pub fn move_to_start_of_excerpt(
11172 &mut self,
11173 _: &MoveToStartOfExcerpt,
11174 window: &mut Window,
11175 cx: &mut Context<Self>,
11176 ) {
11177 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11178 cx.propagate();
11179 return;
11180 }
11181 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11182 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11183 s.move_with(|map, selection| {
11184 selection.collapse_to(
11185 movement::start_of_excerpt(
11186 map,
11187 selection.head(),
11188 workspace::searchable::Direction::Prev,
11189 ),
11190 SelectionGoal::None,
11191 )
11192 });
11193 })
11194 }
11195
11196 pub fn move_to_start_of_next_excerpt(
11197 &mut self,
11198 _: &MoveToStartOfNextExcerpt,
11199 window: &mut Window,
11200 cx: &mut Context<Self>,
11201 ) {
11202 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11203 cx.propagate();
11204 return;
11205 }
11206
11207 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11208 s.move_with(|map, selection| {
11209 selection.collapse_to(
11210 movement::start_of_excerpt(
11211 map,
11212 selection.head(),
11213 workspace::searchable::Direction::Next,
11214 ),
11215 SelectionGoal::None,
11216 )
11217 });
11218 })
11219 }
11220
11221 pub fn move_to_end_of_excerpt(
11222 &mut self,
11223 _: &MoveToEndOfExcerpt,
11224 window: &mut Window,
11225 cx: &mut Context<Self>,
11226 ) {
11227 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11228 cx.propagate();
11229 return;
11230 }
11231 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11232 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11233 s.move_with(|map, selection| {
11234 selection.collapse_to(
11235 movement::end_of_excerpt(
11236 map,
11237 selection.head(),
11238 workspace::searchable::Direction::Next,
11239 ),
11240 SelectionGoal::None,
11241 )
11242 });
11243 })
11244 }
11245
11246 pub fn move_to_end_of_previous_excerpt(
11247 &mut self,
11248 _: &MoveToEndOfPreviousExcerpt,
11249 window: &mut Window,
11250 cx: &mut Context<Self>,
11251 ) {
11252 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11253 cx.propagate();
11254 return;
11255 }
11256 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11257 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11258 s.move_with(|map, selection| {
11259 selection.collapse_to(
11260 movement::end_of_excerpt(
11261 map,
11262 selection.head(),
11263 workspace::searchable::Direction::Prev,
11264 ),
11265 SelectionGoal::None,
11266 )
11267 });
11268 })
11269 }
11270
11271 pub fn select_to_start_of_excerpt(
11272 &mut self,
11273 _: &SelectToStartOfExcerpt,
11274 window: &mut Window,
11275 cx: &mut Context<Self>,
11276 ) {
11277 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11278 cx.propagate();
11279 return;
11280 }
11281 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11282 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11283 s.move_heads_with(|map, head, _| {
11284 (
11285 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11286 SelectionGoal::None,
11287 )
11288 });
11289 })
11290 }
11291
11292 pub fn select_to_start_of_next_excerpt(
11293 &mut self,
11294 _: &SelectToStartOfNextExcerpt,
11295 window: &mut Window,
11296 cx: &mut Context<Self>,
11297 ) {
11298 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11299 cx.propagate();
11300 return;
11301 }
11302 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11303 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11304 s.move_heads_with(|map, head, _| {
11305 (
11306 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11307 SelectionGoal::None,
11308 )
11309 });
11310 })
11311 }
11312
11313 pub fn select_to_end_of_excerpt(
11314 &mut self,
11315 _: &SelectToEndOfExcerpt,
11316 window: &mut Window,
11317 cx: &mut Context<Self>,
11318 ) {
11319 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11320 cx.propagate();
11321 return;
11322 }
11323 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11324 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11325 s.move_heads_with(|map, head, _| {
11326 (
11327 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11328 SelectionGoal::None,
11329 )
11330 });
11331 })
11332 }
11333
11334 pub fn select_to_end_of_previous_excerpt(
11335 &mut self,
11336 _: &SelectToEndOfPreviousExcerpt,
11337 window: &mut Window,
11338 cx: &mut Context<Self>,
11339 ) {
11340 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11341 cx.propagate();
11342 return;
11343 }
11344 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11345 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11346 s.move_heads_with(|map, head, _| {
11347 (
11348 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11349 SelectionGoal::None,
11350 )
11351 });
11352 })
11353 }
11354
11355 pub fn move_to_beginning(
11356 &mut self,
11357 _: &MoveToBeginning,
11358 window: &mut Window,
11359 cx: &mut Context<Self>,
11360 ) {
11361 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11362 cx.propagate();
11363 return;
11364 }
11365 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11366 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11367 s.select_ranges(vec![0..0]);
11368 });
11369 }
11370
11371 pub fn select_to_beginning(
11372 &mut self,
11373 _: &SelectToBeginning,
11374 window: &mut Window,
11375 cx: &mut Context<Self>,
11376 ) {
11377 let mut selection = self.selections.last::<Point>(cx);
11378 selection.set_head(Point::zero(), SelectionGoal::None);
11379 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11380 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11381 s.select(vec![selection]);
11382 });
11383 }
11384
11385 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11386 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11387 cx.propagate();
11388 return;
11389 }
11390 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11391 let cursor = self.buffer.read(cx).read(cx).len();
11392 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11393 s.select_ranges(vec![cursor..cursor])
11394 });
11395 }
11396
11397 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11398 self.nav_history = nav_history;
11399 }
11400
11401 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11402 self.nav_history.as_ref()
11403 }
11404
11405 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11406 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11407 }
11408
11409 fn push_to_nav_history(
11410 &mut self,
11411 cursor_anchor: Anchor,
11412 new_position: Option<Point>,
11413 is_deactivate: bool,
11414 cx: &mut Context<Self>,
11415 ) {
11416 if let Some(nav_history) = self.nav_history.as_mut() {
11417 let buffer = self.buffer.read(cx).read(cx);
11418 let cursor_position = cursor_anchor.to_point(&buffer);
11419 let scroll_state = self.scroll_manager.anchor();
11420 let scroll_top_row = scroll_state.top_row(&buffer);
11421 drop(buffer);
11422
11423 if let Some(new_position) = new_position {
11424 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11425 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11426 return;
11427 }
11428 }
11429
11430 nav_history.push(
11431 Some(NavigationData {
11432 cursor_anchor,
11433 cursor_position,
11434 scroll_anchor: scroll_state,
11435 scroll_top_row,
11436 }),
11437 cx,
11438 );
11439 cx.emit(EditorEvent::PushedToNavHistory {
11440 anchor: cursor_anchor,
11441 is_deactivate,
11442 })
11443 }
11444 }
11445
11446 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11447 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11448 let buffer = self.buffer.read(cx).snapshot(cx);
11449 let mut selection = self.selections.first::<usize>(cx);
11450 selection.set_head(buffer.len(), SelectionGoal::None);
11451 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11452 s.select(vec![selection]);
11453 });
11454 }
11455
11456 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11457 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11458 let end = self.buffer.read(cx).read(cx).len();
11459 self.change_selections(None, window, cx, |s| {
11460 s.select_ranges(vec![0..end]);
11461 });
11462 }
11463
11464 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11465 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11466 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11467 let mut selections = self.selections.all::<Point>(cx);
11468 let max_point = display_map.buffer_snapshot.max_point();
11469 for selection in &mut selections {
11470 let rows = selection.spanned_rows(true, &display_map);
11471 selection.start = Point::new(rows.start.0, 0);
11472 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11473 selection.reversed = false;
11474 }
11475 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11476 s.select(selections);
11477 });
11478 }
11479
11480 pub fn split_selection_into_lines(
11481 &mut self,
11482 _: &SplitSelectionIntoLines,
11483 window: &mut Window,
11484 cx: &mut Context<Self>,
11485 ) {
11486 let selections = self
11487 .selections
11488 .all::<Point>(cx)
11489 .into_iter()
11490 .map(|selection| selection.start..selection.end)
11491 .collect::<Vec<_>>();
11492 self.unfold_ranges(&selections, true, true, cx);
11493
11494 let mut new_selection_ranges = Vec::new();
11495 {
11496 let buffer = self.buffer.read(cx).read(cx);
11497 for selection in selections {
11498 for row in selection.start.row..selection.end.row {
11499 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11500 new_selection_ranges.push(cursor..cursor);
11501 }
11502
11503 let is_multiline_selection = selection.start.row != selection.end.row;
11504 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11505 // so this action feels more ergonomic when paired with other selection operations
11506 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11507 if !should_skip_last {
11508 new_selection_ranges.push(selection.end..selection.end);
11509 }
11510 }
11511 }
11512 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11513 s.select_ranges(new_selection_ranges);
11514 });
11515 }
11516
11517 pub fn add_selection_above(
11518 &mut self,
11519 _: &AddSelectionAbove,
11520 window: &mut Window,
11521 cx: &mut Context<Self>,
11522 ) {
11523 self.add_selection(true, window, cx);
11524 }
11525
11526 pub fn add_selection_below(
11527 &mut self,
11528 _: &AddSelectionBelow,
11529 window: &mut Window,
11530 cx: &mut Context<Self>,
11531 ) {
11532 self.add_selection(false, window, cx);
11533 }
11534
11535 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11536 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11537
11538 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11539 let mut selections = self.selections.all::<Point>(cx);
11540 let text_layout_details = self.text_layout_details(window);
11541 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11542 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11543 let range = oldest_selection.display_range(&display_map).sorted();
11544
11545 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11546 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11547 let positions = start_x.min(end_x)..start_x.max(end_x);
11548
11549 selections.clear();
11550 let mut stack = Vec::new();
11551 for row in range.start.row().0..=range.end.row().0 {
11552 if let Some(selection) = self.selections.build_columnar_selection(
11553 &display_map,
11554 DisplayRow(row),
11555 &positions,
11556 oldest_selection.reversed,
11557 &text_layout_details,
11558 ) {
11559 stack.push(selection.id);
11560 selections.push(selection);
11561 }
11562 }
11563
11564 if above {
11565 stack.reverse();
11566 }
11567
11568 AddSelectionsState { above, stack }
11569 });
11570
11571 let last_added_selection = *state.stack.last().unwrap();
11572 let mut new_selections = Vec::new();
11573 if above == state.above {
11574 let end_row = if above {
11575 DisplayRow(0)
11576 } else {
11577 display_map.max_point().row()
11578 };
11579
11580 'outer: for selection in selections {
11581 if selection.id == last_added_selection {
11582 let range = selection.display_range(&display_map).sorted();
11583 debug_assert_eq!(range.start.row(), range.end.row());
11584 let mut row = range.start.row();
11585 let positions =
11586 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11587 px(start)..px(end)
11588 } else {
11589 let start_x =
11590 display_map.x_for_display_point(range.start, &text_layout_details);
11591 let end_x =
11592 display_map.x_for_display_point(range.end, &text_layout_details);
11593 start_x.min(end_x)..start_x.max(end_x)
11594 };
11595
11596 while row != end_row {
11597 if above {
11598 row.0 -= 1;
11599 } else {
11600 row.0 += 1;
11601 }
11602
11603 if let Some(new_selection) = self.selections.build_columnar_selection(
11604 &display_map,
11605 row,
11606 &positions,
11607 selection.reversed,
11608 &text_layout_details,
11609 ) {
11610 state.stack.push(new_selection.id);
11611 if above {
11612 new_selections.push(new_selection);
11613 new_selections.push(selection);
11614 } else {
11615 new_selections.push(selection);
11616 new_selections.push(new_selection);
11617 }
11618
11619 continue 'outer;
11620 }
11621 }
11622 }
11623
11624 new_selections.push(selection);
11625 }
11626 } else {
11627 new_selections = selections;
11628 new_selections.retain(|s| s.id != last_added_selection);
11629 state.stack.pop();
11630 }
11631
11632 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11633 s.select(new_selections);
11634 });
11635 if state.stack.len() > 1 {
11636 self.add_selections_state = Some(state);
11637 }
11638 }
11639
11640 pub fn select_next_match_internal(
11641 &mut self,
11642 display_map: &DisplaySnapshot,
11643 replace_newest: bool,
11644 autoscroll: Option<Autoscroll>,
11645 window: &mut Window,
11646 cx: &mut Context<Self>,
11647 ) -> Result<()> {
11648 fn select_next_match_ranges(
11649 this: &mut Editor,
11650 range: Range<usize>,
11651 replace_newest: bool,
11652 auto_scroll: Option<Autoscroll>,
11653 window: &mut Window,
11654 cx: &mut Context<Editor>,
11655 ) {
11656 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11657 this.change_selections(auto_scroll, window, cx, |s| {
11658 if replace_newest {
11659 s.delete(s.newest_anchor().id);
11660 }
11661 s.insert_range(range.clone());
11662 });
11663 }
11664
11665 let buffer = &display_map.buffer_snapshot;
11666 let mut selections = self.selections.all::<usize>(cx);
11667 if let Some(mut select_next_state) = self.select_next_state.take() {
11668 let query = &select_next_state.query;
11669 if !select_next_state.done {
11670 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11671 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11672 let mut next_selected_range = None;
11673
11674 let bytes_after_last_selection =
11675 buffer.bytes_in_range(last_selection.end..buffer.len());
11676 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11677 let query_matches = query
11678 .stream_find_iter(bytes_after_last_selection)
11679 .map(|result| (last_selection.end, result))
11680 .chain(
11681 query
11682 .stream_find_iter(bytes_before_first_selection)
11683 .map(|result| (0, result)),
11684 );
11685
11686 for (start_offset, query_match) in query_matches {
11687 let query_match = query_match.unwrap(); // can only fail due to I/O
11688 let offset_range =
11689 start_offset + query_match.start()..start_offset + query_match.end();
11690 let display_range = offset_range.start.to_display_point(display_map)
11691 ..offset_range.end.to_display_point(display_map);
11692
11693 if !select_next_state.wordwise
11694 || (!movement::is_inside_word(display_map, display_range.start)
11695 && !movement::is_inside_word(display_map, display_range.end))
11696 {
11697 // TODO: This is n^2, because we might check all the selections
11698 if !selections
11699 .iter()
11700 .any(|selection| selection.range().overlaps(&offset_range))
11701 {
11702 next_selected_range = Some(offset_range);
11703 break;
11704 }
11705 }
11706 }
11707
11708 if let Some(next_selected_range) = next_selected_range {
11709 select_next_match_ranges(
11710 self,
11711 next_selected_range,
11712 replace_newest,
11713 autoscroll,
11714 window,
11715 cx,
11716 );
11717 } else {
11718 select_next_state.done = true;
11719 }
11720 }
11721
11722 self.select_next_state = Some(select_next_state);
11723 } else {
11724 let mut only_carets = true;
11725 let mut same_text_selected = true;
11726 let mut selected_text = None;
11727
11728 let mut selections_iter = selections.iter().peekable();
11729 while let Some(selection) = selections_iter.next() {
11730 if selection.start != selection.end {
11731 only_carets = false;
11732 }
11733
11734 if same_text_selected {
11735 if selected_text.is_none() {
11736 selected_text =
11737 Some(buffer.text_for_range(selection.range()).collect::<String>());
11738 }
11739
11740 if let Some(next_selection) = selections_iter.peek() {
11741 if next_selection.range().len() == selection.range().len() {
11742 let next_selected_text = buffer
11743 .text_for_range(next_selection.range())
11744 .collect::<String>();
11745 if Some(next_selected_text) != selected_text {
11746 same_text_selected = false;
11747 selected_text = None;
11748 }
11749 } else {
11750 same_text_selected = false;
11751 selected_text = None;
11752 }
11753 }
11754 }
11755 }
11756
11757 if only_carets {
11758 for selection in &mut selections {
11759 let word_range = movement::surrounding_word(
11760 display_map,
11761 selection.start.to_display_point(display_map),
11762 );
11763 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11764 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11765 selection.goal = SelectionGoal::None;
11766 selection.reversed = false;
11767 select_next_match_ranges(
11768 self,
11769 selection.start..selection.end,
11770 replace_newest,
11771 autoscroll,
11772 window,
11773 cx,
11774 );
11775 }
11776
11777 if selections.len() == 1 {
11778 let selection = selections
11779 .last()
11780 .expect("ensured that there's only one selection");
11781 let query = buffer
11782 .text_for_range(selection.start..selection.end)
11783 .collect::<String>();
11784 let is_empty = query.is_empty();
11785 let select_state = SelectNextState {
11786 query: AhoCorasick::new(&[query])?,
11787 wordwise: true,
11788 done: is_empty,
11789 };
11790 self.select_next_state = Some(select_state);
11791 } else {
11792 self.select_next_state = None;
11793 }
11794 } else if let Some(selected_text) = selected_text {
11795 self.select_next_state = Some(SelectNextState {
11796 query: AhoCorasick::new(&[selected_text])?,
11797 wordwise: false,
11798 done: false,
11799 });
11800 self.select_next_match_internal(
11801 display_map,
11802 replace_newest,
11803 autoscroll,
11804 window,
11805 cx,
11806 )?;
11807 }
11808 }
11809 Ok(())
11810 }
11811
11812 pub fn select_all_matches(
11813 &mut self,
11814 _action: &SelectAllMatches,
11815 window: &mut Window,
11816 cx: &mut Context<Self>,
11817 ) -> Result<()> {
11818 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11819
11820 self.push_to_selection_history();
11821 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11822
11823 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11824 let Some(select_next_state) = self.select_next_state.as_mut() else {
11825 return Ok(());
11826 };
11827 if select_next_state.done {
11828 return Ok(());
11829 }
11830
11831 let mut new_selections = Vec::new();
11832
11833 let reversed = self.selections.oldest::<usize>(cx).reversed;
11834 let buffer = &display_map.buffer_snapshot;
11835 let query_matches = select_next_state
11836 .query
11837 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11838
11839 for query_match in query_matches.into_iter() {
11840 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11841 let offset_range = if reversed {
11842 query_match.end()..query_match.start()
11843 } else {
11844 query_match.start()..query_match.end()
11845 };
11846 let display_range = offset_range.start.to_display_point(&display_map)
11847 ..offset_range.end.to_display_point(&display_map);
11848
11849 if !select_next_state.wordwise
11850 || (!movement::is_inside_word(&display_map, display_range.start)
11851 && !movement::is_inside_word(&display_map, display_range.end))
11852 {
11853 new_selections.push(offset_range.start..offset_range.end);
11854 }
11855 }
11856
11857 select_next_state.done = true;
11858 self.unfold_ranges(&new_selections.clone(), false, false, cx);
11859 self.change_selections(None, window, cx, |selections| {
11860 selections.select_ranges(new_selections)
11861 });
11862
11863 Ok(())
11864 }
11865
11866 pub fn select_next(
11867 &mut self,
11868 action: &SelectNext,
11869 window: &mut Window,
11870 cx: &mut Context<Self>,
11871 ) -> Result<()> {
11872 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11873 self.push_to_selection_history();
11874 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11875 self.select_next_match_internal(
11876 &display_map,
11877 action.replace_newest,
11878 Some(Autoscroll::newest()),
11879 window,
11880 cx,
11881 )?;
11882 Ok(())
11883 }
11884
11885 pub fn select_previous(
11886 &mut self,
11887 action: &SelectPrevious,
11888 window: &mut Window,
11889 cx: &mut Context<Self>,
11890 ) -> Result<()> {
11891 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11892 self.push_to_selection_history();
11893 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11894 let buffer = &display_map.buffer_snapshot;
11895 let mut selections = self.selections.all::<usize>(cx);
11896 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11897 let query = &select_prev_state.query;
11898 if !select_prev_state.done {
11899 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11900 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11901 let mut next_selected_range = None;
11902 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11903 let bytes_before_last_selection =
11904 buffer.reversed_bytes_in_range(0..last_selection.start);
11905 let bytes_after_first_selection =
11906 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11907 let query_matches = query
11908 .stream_find_iter(bytes_before_last_selection)
11909 .map(|result| (last_selection.start, result))
11910 .chain(
11911 query
11912 .stream_find_iter(bytes_after_first_selection)
11913 .map(|result| (buffer.len(), result)),
11914 );
11915 for (end_offset, query_match) in query_matches {
11916 let query_match = query_match.unwrap(); // can only fail due to I/O
11917 let offset_range =
11918 end_offset - query_match.end()..end_offset - query_match.start();
11919 let display_range = offset_range.start.to_display_point(&display_map)
11920 ..offset_range.end.to_display_point(&display_map);
11921
11922 if !select_prev_state.wordwise
11923 || (!movement::is_inside_word(&display_map, display_range.start)
11924 && !movement::is_inside_word(&display_map, display_range.end))
11925 {
11926 next_selected_range = Some(offset_range);
11927 break;
11928 }
11929 }
11930
11931 if let Some(next_selected_range) = next_selected_range {
11932 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11933 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11934 if action.replace_newest {
11935 s.delete(s.newest_anchor().id);
11936 }
11937 s.insert_range(next_selected_range);
11938 });
11939 } else {
11940 select_prev_state.done = true;
11941 }
11942 }
11943
11944 self.select_prev_state = Some(select_prev_state);
11945 } else {
11946 let mut only_carets = true;
11947 let mut same_text_selected = true;
11948 let mut selected_text = None;
11949
11950 let mut selections_iter = selections.iter().peekable();
11951 while let Some(selection) = selections_iter.next() {
11952 if selection.start != selection.end {
11953 only_carets = false;
11954 }
11955
11956 if same_text_selected {
11957 if selected_text.is_none() {
11958 selected_text =
11959 Some(buffer.text_for_range(selection.range()).collect::<String>());
11960 }
11961
11962 if let Some(next_selection) = selections_iter.peek() {
11963 if next_selection.range().len() == selection.range().len() {
11964 let next_selected_text = buffer
11965 .text_for_range(next_selection.range())
11966 .collect::<String>();
11967 if Some(next_selected_text) != selected_text {
11968 same_text_selected = false;
11969 selected_text = None;
11970 }
11971 } else {
11972 same_text_selected = false;
11973 selected_text = None;
11974 }
11975 }
11976 }
11977 }
11978
11979 if only_carets {
11980 for selection in &mut selections {
11981 let word_range = movement::surrounding_word(
11982 &display_map,
11983 selection.start.to_display_point(&display_map),
11984 );
11985 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11986 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11987 selection.goal = SelectionGoal::None;
11988 selection.reversed = false;
11989 }
11990 if selections.len() == 1 {
11991 let selection = selections
11992 .last()
11993 .expect("ensured that there's only one selection");
11994 let query = buffer
11995 .text_for_range(selection.start..selection.end)
11996 .collect::<String>();
11997 let is_empty = query.is_empty();
11998 let select_state = SelectNextState {
11999 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12000 wordwise: true,
12001 done: is_empty,
12002 };
12003 self.select_prev_state = Some(select_state);
12004 } else {
12005 self.select_prev_state = None;
12006 }
12007
12008 self.unfold_ranges(
12009 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12010 false,
12011 true,
12012 cx,
12013 );
12014 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12015 s.select(selections);
12016 });
12017 } else if let Some(selected_text) = selected_text {
12018 self.select_prev_state = Some(SelectNextState {
12019 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12020 wordwise: false,
12021 done: false,
12022 });
12023 self.select_previous(action, window, cx)?;
12024 }
12025 }
12026 Ok(())
12027 }
12028
12029 pub fn find_next_match(
12030 &mut self,
12031 _: &FindNextMatch,
12032 window: &mut Window,
12033 cx: &mut Context<Self>,
12034 ) -> Result<()> {
12035 let selections = self.selections.disjoint_anchors();
12036 match selections.first() {
12037 Some(first) if selections.len() >= 2 => {
12038 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12039 s.select_ranges([first.range()]);
12040 });
12041 }
12042 _ => self.select_next(
12043 &SelectNext {
12044 replace_newest: true,
12045 },
12046 window,
12047 cx,
12048 )?,
12049 }
12050 Ok(())
12051 }
12052
12053 pub fn find_previous_match(
12054 &mut self,
12055 _: &FindPreviousMatch,
12056 window: &mut Window,
12057 cx: &mut Context<Self>,
12058 ) -> Result<()> {
12059 let selections = self.selections.disjoint_anchors();
12060 match selections.last() {
12061 Some(last) if selections.len() >= 2 => {
12062 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12063 s.select_ranges([last.range()]);
12064 });
12065 }
12066 _ => self.select_previous(
12067 &SelectPrevious {
12068 replace_newest: true,
12069 },
12070 window,
12071 cx,
12072 )?,
12073 }
12074 Ok(())
12075 }
12076
12077 pub fn toggle_comments(
12078 &mut self,
12079 action: &ToggleComments,
12080 window: &mut Window,
12081 cx: &mut Context<Self>,
12082 ) {
12083 if self.read_only(cx) {
12084 return;
12085 }
12086 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12087 let text_layout_details = &self.text_layout_details(window);
12088 self.transact(window, cx, |this, window, cx| {
12089 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12090 let mut edits = Vec::new();
12091 let mut selection_edit_ranges = Vec::new();
12092 let mut last_toggled_row = None;
12093 let snapshot = this.buffer.read(cx).read(cx);
12094 let empty_str: Arc<str> = Arc::default();
12095 let mut suffixes_inserted = Vec::new();
12096 let ignore_indent = action.ignore_indent;
12097
12098 fn comment_prefix_range(
12099 snapshot: &MultiBufferSnapshot,
12100 row: MultiBufferRow,
12101 comment_prefix: &str,
12102 comment_prefix_whitespace: &str,
12103 ignore_indent: bool,
12104 ) -> Range<Point> {
12105 let indent_size = if ignore_indent {
12106 0
12107 } else {
12108 snapshot.indent_size_for_line(row).len
12109 };
12110
12111 let start = Point::new(row.0, indent_size);
12112
12113 let mut line_bytes = snapshot
12114 .bytes_in_range(start..snapshot.max_point())
12115 .flatten()
12116 .copied();
12117
12118 // If this line currently begins with the line comment prefix, then record
12119 // the range containing the prefix.
12120 if line_bytes
12121 .by_ref()
12122 .take(comment_prefix.len())
12123 .eq(comment_prefix.bytes())
12124 {
12125 // Include any whitespace that matches the comment prefix.
12126 let matching_whitespace_len = line_bytes
12127 .zip(comment_prefix_whitespace.bytes())
12128 .take_while(|(a, b)| a == b)
12129 .count() as u32;
12130 let end = Point::new(
12131 start.row,
12132 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12133 );
12134 start..end
12135 } else {
12136 start..start
12137 }
12138 }
12139
12140 fn comment_suffix_range(
12141 snapshot: &MultiBufferSnapshot,
12142 row: MultiBufferRow,
12143 comment_suffix: &str,
12144 comment_suffix_has_leading_space: bool,
12145 ) -> Range<Point> {
12146 let end = Point::new(row.0, snapshot.line_len(row));
12147 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12148
12149 let mut line_end_bytes = snapshot
12150 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12151 .flatten()
12152 .copied();
12153
12154 let leading_space_len = if suffix_start_column > 0
12155 && line_end_bytes.next() == Some(b' ')
12156 && comment_suffix_has_leading_space
12157 {
12158 1
12159 } else {
12160 0
12161 };
12162
12163 // If this line currently begins with the line comment prefix, then record
12164 // the range containing the prefix.
12165 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12166 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12167 start..end
12168 } else {
12169 end..end
12170 }
12171 }
12172
12173 // TODO: Handle selections that cross excerpts
12174 for selection in &mut selections {
12175 let start_column = snapshot
12176 .indent_size_for_line(MultiBufferRow(selection.start.row))
12177 .len;
12178 let language = if let Some(language) =
12179 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12180 {
12181 language
12182 } else {
12183 continue;
12184 };
12185
12186 selection_edit_ranges.clear();
12187
12188 // If multiple selections contain a given row, avoid processing that
12189 // row more than once.
12190 let mut start_row = MultiBufferRow(selection.start.row);
12191 if last_toggled_row == Some(start_row) {
12192 start_row = start_row.next_row();
12193 }
12194 let end_row =
12195 if selection.end.row > selection.start.row && selection.end.column == 0 {
12196 MultiBufferRow(selection.end.row - 1)
12197 } else {
12198 MultiBufferRow(selection.end.row)
12199 };
12200 last_toggled_row = Some(end_row);
12201
12202 if start_row > end_row {
12203 continue;
12204 }
12205
12206 // If the language has line comments, toggle those.
12207 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12208
12209 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12210 if ignore_indent {
12211 full_comment_prefixes = full_comment_prefixes
12212 .into_iter()
12213 .map(|s| Arc::from(s.trim_end()))
12214 .collect();
12215 }
12216
12217 if !full_comment_prefixes.is_empty() {
12218 let first_prefix = full_comment_prefixes
12219 .first()
12220 .expect("prefixes is non-empty");
12221 let prefix_trimmed_lengths = full_comment_prefixes
12222 .iter()
12223 .map(|p| p.trim_end_matches(' ').len())
12224 .collect::<SmallVec<[usize; 4]>>();
12225
12226 let mut all_selection_lines_are_comments = true;
12227
12228 for row in start_row.0..=end_row.0 {
12229 let row = MultiBufferRow(row);
12230 if start_row < end_row && snapshot.is_line_blank(row) {
12231 continue;
12232 }
12233
12234 let prefix_range = full_comment_prefixes
12235 .iter()
12236 .zip(prefix_trimmed_lengths.iter().copied())
12237 .map(|(prefix, trimmed_prefix_len)| {
12238 comment_prefix_range(
12239 snapshot.deref(),
12240 row,
12241 &prefix[..trimmed_prefix_len],
12242 &prefix[trimmed_prefix_len..],
12243 ignore_indent,
12244 )
12245 })
12246 .max_by_key(|range| range.end.column - range.start.column)
12247 .expect("prefixes is non-empty");
12248
12249 if prefix_range.is_empty() {
12250 all_selection_lines_are_comments = false;
12251 }
12252
12253 selection_edit_ranges.push(prefix_range);
12254 }
12255
12256 if all_selection_lines_are_comments {
12257 edits.extend(
12258 selection_edit_ranges
12259 .iter()
12260 .cloned()
12261 .map(|range| (range, empty_str.clone())),
12262 );
12263 } else {
12264 let min_column = selection_edit_ranges
12265 .iter()
12266 .map(|range| range.start.column)
12267 .min()
12268 .unwrap_or(0);
12269 edits.extend(selection_edit_ranges.iter().map(|range| {
12270 let position = Point::new(range.start.row, min_column);
12271 (position..position, first_prefix.clone())
12272 }));
12273 }
12274 } else if let Some((full_comment_prefix, comment_suffix)) =
12275 language.block_comment_delimiters()
12276 {
12277 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12278 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12279 let prefix_range = comment_prefix_range(
12280 snapshot.deref(),
12281 start_row,
12282 comment_prefix,
12283 comment_prefix_whitespace,
12284 ignore_indent,
12285 );
12286 let suffix_range = comment_suffix_range(
12287 snapshot.deref(),
12288 end_row,
12289 comment_suffix.trim_start_matches(' '),
12290 comment_suffix.starts_with(' '),
12291 );
12292
12293 if prefix_range.is_empty() || suffix_range.is_empty() {
12294 edits.push((
12295 prefix_range.start..prefix_range.start,
12296 full_comment_prefix.clone(),
12297 ));
12298 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12299 suffixes_inserted.push((end_row, comment_suffix.len()));
12300 } else {
12301 edits.push((prefix_range, empty_str.clone()));
12302 edits.push((suffix_range, empty_str.clone()));
12303 }
12304 } else {
12305 continue;
12306 }
12307 }
12308
12309 drop(snapshot);
12310 this.buffer.update(cx, |buffer, cx| {
12311 buffer.edit(edits, None, cx);
12312 });
12313
12314 // Adjust selections so that they end before any comment suffixes that
12315 // were inserted.
12316 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12317 let mut selections = this.selections.all::<Point>(cx);
12318 let snapshot = this.buffer.read(cx).read(cx);
12319 for selection in &mut selections {
12320 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12321 match row.cmp(&MultiBufferRow(selection.end.row)) {
12322 Ordering::Less => {
12323 suffixes_inserted.next();
12324 continue;
12325 }
12326 Ordering::Greater => break,
12327 Ordering::Equal => {
12328 if selection.end.column == snapshot.line_len(row) {
12329 if selection.is_empty() {
12330 selection.start.column -= suffix_len as u32;
12331 }
12332 selection.end.column -= suffix_len as u32;
12333 }
12334 break;
12335 }
12336 }
12337 }
12338 }
12339
12340 drop(snapshot);
12341 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12342 s.select(selections)
12343 });
12344
12345 let selections = this.selections.all::<Point>(cx);
12346 let selections_on_single_row = selections.windows(2).all(|selections| {
12347 selections[0].start.row == selections[1].start.row
12348 && selections[0].end.row == selections[1].end.row
12349 && selections[0].start.row == selections[0].end.row
12350 });
12351 let selections_selecting = selections
12352 .iter()
12353 .any(|selection| selection.start != selection.end);
12354 let advance_downwards = action.advance_downwards
12355 && selections_on_single_row
12356 && !selections_selecting
12357 && !matches!(this.mode, EditorMode::SingleLine { .. });
12358
12359 if advance_downwards {
12360 let snapshot = this.buffer.read(cx).snapshot(cx);
12361
12362 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12363 s.move_cursors_with(|display_snapshot, display_point, _| {
12364 let mut point = display_point.to_point(display_snapshot);
12365 point.row += 1;
12366 point = snapshot.clip_point(point, Bias::Left);
12367 let display_point = point.to_display_point(display_snapshot);
12368 let goal = SelectionGoal::HorizontalPosition(
12369 display_snapshot
12370 .x_for_display_point(display_point, text_layout_details)
12371 .into(),
12372 );
12373 (display_point, goal)
12374 })
12375 });
12376 }
12377 });
12378 }
12379
12380 pub fn select_enclosing_symbol(
12381 &mut self,
12382 _: &SelectEnclosingSymbol,
12383 window: &mut Window,
12384 cx: &mut Context<Self>,
12385 ) {
12386 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12387
12388 let buffer = self.buffer.read(cx).snapshot(cx);
12389 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12390
12391 fn update_selection(
12392 selection: &Selection<usize>,
12393 buffer_snap: &MultiBufferSnapshot,
12394 ) -> Option<Selection<usize>> {
12395 let cursor = selection.head();
12396 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12397 for symbol in symbols.iter().rev() {
12398 let start = symbol.range.start.to_offset(buffer_snap);
12399 let end = symbol.range.end.to_offset(buffer_snap);
12400 let new_range = start..end;
12401 if start < selection.start || end > selection.end {
12402 return Some(Selection {
12403 id: selection.id,
12404 start: new_range.start,
12405 end: new_range.end,
12406 goal: SelectionGoal::None,
12407 reversed: selection.reversed,
12408 });
12409 }
12410 }
12411 None
12412 }
12413
12414 let mut selected_larger_symbol = false;
12415 let new_selections = old_selections
12416 .iter()
12417 .map(|selection| match update_selection(selection, &buffer) {
12418 Some(new_selection) => {
12419 if new_selection.range() != selection.range() {
12420 selected_larger_symbol = true;
12421 }
12422 new_selection
12423 }
12424 None => selection.clone(),
12425 })
12426 .collect::<Vec<_>>();
12427
12428 if selected_larger_symbol {
12429 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12430 s.select(new_selections);
12431 });
12432 }
12433 }
12434
12435 pub fn select_larger_syntax_node(
12436 &mut self,
12437 _: &SelectLargerSyntaxNode,
12438 window: &mut Window,
12439 cx: &mut Context<Self>,
12440 ) {
12441 let Some(visible_row_count) = self.visible_row_count() else {
12442 return;
12443 };
12444 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12445 if old_selections.is_empty() {
12446 return;
12447 }
12448
12449 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12450
12451 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12452 let buffer = self.buffer.read(cx).snapshot(cx);
12453
12454 let mut selected_larger_node = false;
12455 let mut new_selections = old_selections
12456 .iter()
12457 .map(|selection| {
12458 let old_range = selection.start..selection.end;
12459 let mut new_range = old_range.clone();
12460 let mut new_node = None;
12461 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12462 {
12463 new_node = Some(node);
12464 new_range = match containing_range {
12465 MultiOrSingleBufferOffsetRange::Single(_) => break,
12466 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12467 };
12468 if !display_map.intersects_fold(new_range.start)
12469 && !display_map.intersects_fold(new_range.end)
12470 {
12471 break;
12472 }
12473 }
12474
12475 if let Some(node) = new_node {
12476 // Log the ancestor, to support using this action as a way to explore TreeSitter
12477 // nodes. Parent and grandparent are also logged because this operation will not
12478 // visit nodes that have the same range as their parent.
12479 log::info!("Node: {node:?}");
12480 let parent = node.parent();
12481 log::info!("Parent: {parent:?}");
12482 let grandparent = parent.and_then(|x| x.parent());
12483 log::info!("Grandparent: {grandparent:?}");
12484 }
12485
12486 selected_larger_node |= new_range != old_range;
12487 Selection {
12488 id: selection.id,
12489 start: new_range.start,
12490 end: new_range.end,
12491 goal: SelectionGoal::None,
12492 reversed: selection.reversed,
12493 }
12494 })
12495 .collect::<Vec<_>>();
12496
12497 if !selected_larger_node {
12498 return; // don't put this call in the history
12499 }
12500
12501 // scroll based on transformation done to the last selection created by the user
12502 let (last_old, last_new) = old_selections
12503 .last()
12504 .zip(new_selections.last().cloned())
12505 .expect("old_selections isn't empty");
12506
12507 // revert selection
12508 let is_selection_reversed = {
12509 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12510 new_selections.last_mut().expect("checked above").reversed =
12511 should_newest_selection_be_reversed;
12512 should_newest_selection_be_reversed
12513 };
12514
12515 if selected_larger_node {
12516 self.select_syntax_node_history.disable_clearing = true;
12517 self.change_selections(None, window, cx, |s| {
12518 s.select(new_selections.clone());
12519 });
12520 self.select_syntax_node_history.disable_clearing = false;
12521 }
12522
12523 let start_row = last_new.start.to_display_point(&display_map).row().0;
12524 let end_row = last_new.end.to_display_point(&display_map).row().0;
12525 let selection_height = end_row - start_row + 1;
12526 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12527
12528 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12529 let scroll_behavior = if fits_on_the_screen {
12530 self.request_autoscroll(Autoscroll::fit(), cx);
12531 SelectSyntaxNodeScrollBehavior::FitSelection
12532 } else if is_selection_reversed {
12533 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12534 SelectSyntaxNodeScrollBehavior::CursorTop
12535 } else {
12536 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12537 SelectSyntaxNodeScrollBehavior::CursorBottom
12538 };
12539
12540 self.select_syntax_node_history.push((
12541 old_selections,
12542 scroll_behavior,
12543 is_selection_reversed,
12544 ));
12545 }
12546
12547 pub fn select_smaller_syntax_node(
12548 &mut self,
12549 _: &SelectSmallerSyntaxNode,
12550 window: &mut Window,
12551 cx: &mut Context<Self>,
12552 ) {
12553 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12554
12555 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12556 self.select_syntax_node_history.pop()
12557 {
12558 if let Some(selection) = selections.last_mut() {
12559 selection.reversed = is_selection_reversed;
12560 }
12561
12562 self.select_syntax_node_history.disable_clearing = true;
12563 self.change_selections(None, window, cx, |s| {
12564 s.select(selections.to_vec());
12565 });
12566 self.select_syntax_node_history.disable_clearing = false;
12567
12568 match scroll_behavior {
12569 SelectSyntaxNodeScrollBehavior::CursorTop => {
12570 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12571 }
12572 SelectSyntaxNodeScrollBehavior::FitSelection => {
12573 self.request_autoscroll(Autoscroll::fit(), cx);
12574 }
12575 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12576 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12577 }
12578 }
12579 }
12580 }
12581
12582 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12583 if !EditorSettings::get_global(cx).gutter.runnables {
12584 self.clear_tasks();
12585 return Task::ready(());
12586 }
12587 let project = self.project.as_ref().map(Entity::downgrade);
12588 let task_sources = self.lsp_task_sources(cx);
12589 cx.spawn_in(window, async move |editor, cx| {
12590 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12591 let Some(project) = project.and_then(|p| p.upgrade()) else {
12592 return;
12593 };
12594 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12595 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12596 }) else {
12597 return;
12598 };
12599
12600 let hide_runnables = project
12601 .update(cx, |project, cx| {
12602 // Do not display any test indicators in non-dev server remote projects.
12603 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12604 })
12605 .unwrap_or(true);
12606 if hide_runnables {
12607 return;
12608 }
12609 let new_rows =
12610 cx.background_spawn({
12611 let snapshot = display_snapshot.clone();
12612 async move {
12613 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12614 }
12615 })
12616 .await;
12617 let Ok(lsp_tasks) =
12618 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12619 else {
12620 return;
12621 };
12622 let lsp_tasks = lsp_tasks.await;
12623
12624 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12625 lsp_tasks
12626 .into_iter()
12627 .flat_map(|(kind, tasks)| {
12628 tasks.into_iter().filter_map(move |(location, task)| {
12629 Some((kind.clone(), location?, task))
12630 })
12631 })
12632 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12633 let buffer = location.target.buffer;
12634 let buffer_snapshot = buffer.read(cx).snapshot();
12635 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12636 |(excerpt_id, snapshot, _)| {
12637 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12638 display_snapshot
12639 .buffer_snapshot
12640 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12641 } else {
12642 None
12643 }
12644 },
12645 );
12646 if let Some(offset) = offset {
12647 let task_buffer_range =
12648 location.target.range.to_point(&buffer_snapshot);
12649 let context_buffer_range =
12650 task_buffer_range.to_offset(&buffer_snapshot);
12651 let context_range = BufferOffset(context_buffer_range.start)
12652 ..BufferOffset(context_buffer_range.end);
12653
12654 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12655 .or_insert_with(|| RunnableTasks {
12656 templates: Vec::new(),
12657 offset,
12658 column: task_buffer_range.start.column,
12659 extra_variables: HashMap::default(),
12660 context_range,
12661 })
12662 .templates
12663 .push((kind, task.original_task().clone()));
12664 }
12665
12666 acc
12667 })
12668 }) else {
12669 return;
12670 };
12671
12672 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12673 editor
12674 .update(cx, |editor, _| {
12675 editor.clear_tasks();
12676 for (key, mut value) in rows {
12677 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12678 value.templates.extend(lsp_tasks.templates);
12679 }
12680
12681 editor.insert_tasks(key, value);
12682 }
12683 for (key, value) in lsp_tasks_by_rows {
12684 editor.insert_tasks(key, value);
12685 }
12686 })
12687 .ok();
12688 })
12689 }
12690 fn fetch_runnable_ranges(
12691 snapshot: &DisplaySnapshot,
12692 range: Range<Anchor>,
12693 ) -> Vec<language::RunnableRange> {
12694 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12695 }
12696
12697 fn runnable_rows(
12698 project: Entity<Project>,
12699 snapshot: DisplaySnapshot,
12700 runnable_ranges: Vec<RunnableRange>,
12701 mut cx: AsyncWindowContext,
12702 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12703 runnable_ranges
12704 .into_iter()
12705 .filter_map(|mut runnable| {
12706 let tasks = cx
12707 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12708 .ok()?;
12709 if tasks.is_empty() {
12710 return None;
12711 }
12712
12713 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12714
12715 let row = snapshot
12716 .buffer_snapshot
12717 .buffer_line_for_row(MultiBufferRow(point.row))?
12718 .1
12719 .start
12720 .row;
12721
12722 let context_range =
12723 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12724 Some((
12725 (runnable.buffer_id, row),
12726 RunnableTasks {
12727 templates: tasks,
12728 offset: snapshot
12729 .buffer_snapshot
12730 .anchor_before(runnable.run_range.start),
12731 context_range,
12732 column: point.column,
12733 extra_variables: runnable.extra_captures,
12734 },
12735 ))
12736 })
12737 .collect()
12738 }
12739
12740 fn templates_with_tags(
12741 project: &Entity<Project>,
12742 runnable: &mut Runnable,
12743 cx: &mut App,
12744 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12745 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12746 let (worktree_id, file) = project
12747 .buffer_for_id(runnable.buffer, cx)
12748 .and_then(|buffer| buffer.read(cx).file())
12749 .map(|file| (file.worktree_id(cx), file.clone()))
12750 .unzip();
12751
12752 (
12753 project.task_store().read(cx).task_inventory().cloned(),
12754 worktree_id,
12755 file,
12756 )
12757 });
12758
12759 let mut templates_with_tags = mem::take(&mut runnable.tags)
12760 .into_iter()
12761 .flat_map(|RunnableTag(tag)| {
12762 inventory
12763 .as_ref()
12764 .into_iter()
12765 .flat_map(|inventory| {
12766 inventory.read(cx).list_tasks(
12767 file.clone(),
12768 Some(runnable.language.clone()),
12769 worktree_id,
12770 cx,
12771 )
12772 })
12773 .filter(move |(_, template)| {
12774 template.tags.iter().any(|source_tag| source_tag == &tag)
12775 })
12776 })
12777 .sorted_by_key(|(kind, _)| kind.to_owned())
12778 .collect::<Vec<_>>();
12779 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12780 // Strongest source wins; if we have worktree tag binding, prefer that to
12781 // global and language bindings;
12782 // if we have a global binding, prefer that to language binding.
12783 let first_mismatch = templates_with_tags
12784 .iter()
12785 .position(|(tag_source, _)| tag_source != leading_tag_source);
12786 if let Some(index) = first_mismatch {
12787 templates_with_tags.truncate(index);
12788 }
12789 }
12790
12791 templates_with_tags
12792 }
12793
12794 pub fn move_to_enclosing_bracket(
12795 &mut self,
12796 _: &MoveToEnclosingBracket,
12797 window: &mut Window,
12798 cx: &mut Context<Self>,
12799 ) {
12800 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12801 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12802 s.move_offsets_with(|snapshot, selection| {
12803 let Some(enclosing_bracket_ranges) =
12804 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12805 else {
12806 return;
12807 };
12808
12809 let mut best_length = usize::MAX;
12810 let mut best_inside = false;
12811 let mut best_in_bracket_range = false;
12812 let mut best_destination = None;
12813 for (open, close) in enclosing_bracket_ranges {
12814 let close = close.to_inclusive();
12815 let length = close.end() - open.start;
12816 let inside = selection.start >= open.end && selection.end <= *close.start();
12817 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12818 || close.contains(&selection.head());
12819
12820 // If best is next to a bracket and current isn't, skip
12821 if !in_bracket_range && best_in_bracket_range {
12822 continue;
12823 }
12824
12825 // Prefer smaller lengths unless best is inside and current isn't
12826 if length > best_length && (best_inside || !inside) {
12827 continue;
12828 }
12829
12830 best_length = length;
12831 best_inside = inside;
12832 best_in_bracket_range = in_bracket_range;
12833 best_destination = Some(
12834 if close.contains(&selection.start) && close.contains(&selection.end) {
12835 if inside { open.end } else { open.start }
12836 } else if inside {
12837 *close.start()
12838 } else {
12839 *close.end()
12840 },
12841 );
12842 }
12843
12844 if let Some(destination) = best_destination {
12845 selection.collapse_to(destination, SelectionGoal::None);
12846 }
12847 })
12848 });
12849 }
12850
12851 pub fn undo_selection(
12852 &mut self,
12853 _: &UndoSelection,
12854 window: &mut Window,
12855 cx: &mut Context<Self>,
12856 ) {
12857 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12858 self.end_selection(window, cx);
12859 self.selection_history.mode = SelectionHistoryMode::Undoing;
12860 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12861 self.change_selections(None, window, cx, |s| {
12862 s.select_anchors(entry.selections.to_vec())
12863 });
12864 self.select_next_state = entry.select_next_state;
12865 self.select_prev_state = entry.select_prev_state;
12866 self.add_selections_state = entry.add_selections_state;
12867 self.request_autoscroll(Autoscroll::newest(), cx);
12868 }
12869 self.selection_history.mode = SelectionHistoryMode::Normal;
12870 }
12871
12872 pub fn redo_selection(
12873 &mut self,
12874 _: &RedoSelection,
12875 window: &mut Window,
12876 cx: &mut Context<Self>,
12877 ) {
12878 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12879 self.end_selection(window, cx);
12880 self.selection_history.mode = SelectionHistoryMode::Redoing;
12881 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12882 self.change_selections(None, window, cx, |s| {
12883 s.select_anchors(entry.selections.to_vec())
12884 });
12885 self.select_next_state = entry.select_next_state;
12886 self.select_prev_state = entry.select_prev_state;
12887 self.add_selections_state = entry.add_selections_state;
12888 self.request_autoscroll(Autoscroll::newest(), cx);
12889 }
12890 self.selection_history.mode = SelectionHistoryMode::Normal;
12891 }
12892
12893 pub fn expand_excerpts(
12894 &mut self,
12895 action: &ExpandExcerpts,
12896 _: &mut Window,
12897 cx: &mut Context<Self>,
12898 ) {
12899 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12900 }
12901
12902 pub fn expand_excerpts_down(
12903 &mut self,
12904 action: &ExpandExcerptsDown,
12905 _: &mut Window,
12906 cx: &mut Context<Self>,
12907 ) {
12908 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12909 }
12910
12911 pub fn expand_excerpts_up(
12912 &mut self,
12913 action: &ExpandExcerptsUp,
12914 _: &mut Window,
12915 cx: &mut Context<Self>,
12916 ) {
12917 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12918 }
12919
12920 pub fn expand_excerpts_for_direction(
12921 &mut self,
12922 lines: u32,
12923 direction: ExpandExcerptDirection,
12924
12925 cx: &mut Context<Self>,
12926 ) {
12927 let selections = self.selections.disjoint_anchors();
12928
12929 let lines = if lines == 0 {
12930 EditorSettings::get_global(cx).expand_excerpt_lines
12931 } else {
12932 lines
12933 };
12934
12935 self.buffer.update(cx, |buffer, cx| {
12936 let snapshot = buffer.snapshot(cx);
12937 let mut excerpt_ids = selections
12938 .iter()
12939 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12940 .collect::<Vec<_>>();
12941 excerpt_ids.sort();
12942 excerpt_ids.dedup();
12943 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12944 })
12945 }
12946
12947 pub fn expand_excerpt(
12948 &mut self,
12949 excerpt: ExcerptId,
12950 direction: ExpandExcerptDirection,
12951 window: &mut Window,
12952 cx: &mut Context<Self>,
12953 ) {
12954 let current_scroll_position = self.scroll_position(cx);
12955 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
12956 let mut should_scroll_up = false;
12957
12958 if direction == ExpandExcerptDirection::Down {
12959 let multi_buffer = self.buffer.read(cx);
12960 let snapshot = multi_buffer.snapshot(cx);
12961 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
12962 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12963 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
12964 let buffer_snapshot = buffer.read(cx).snapshot();
12965 let excerpt_end_row =
12966 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
12967 let last_row = buffer_snapshot.max_point().row;
12968 let lines_below = last_row.saturating_sub(excerpt_end_row);
12969 should_scroll_up = lines_below >= lines_to_expand;
12970 }
12971 }
12972 }
12973 }
12974
12975 self.buffer.update(cx, |buffer, cx| {
12976 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
12977 });
12978
12979 if should_scroll_up {
12980 let new_scroll_position =
12981 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
12982 self.set_scroll_position(new_scroll_position, window, cx);
12983 }
12984 }
12985
12986 pub fn go_to_singleton_buffer_point(
12987 &mut self,
12988 point: Point,
12989 window: &mut Window,
12990 cx: &mut Context<Self>,
12991 ) {
12992 self.go_to_singleton_buffer_range(point..point, window, cx);
12993 }
12994
12995 pub fn go_to_singleton_buffer_range(
12996 &mut self,
12997 range: Range<Point>,
12998 window: &mut Window,
12999 cx: &mut Context<Self>,
13000 ) {
13001 let multibuffer = self.buffer().read(cx);
13002 let Some(buffer) = multibuffer.as_singleton() else {
13003 return;
13004 };
13005 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13006 return;
13007 };
13008 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13009 return;
13010 };
13011 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13012 s.select_anchor_ranges([start..end])
13013 });
13014 }
13015
13016 fn go_to_diagnostic(
13017 &mut self,
13018 _: &GoToDiagnostic,
13019 window: &mut Window,
13020 cx: &mut Context<Self>,
13021 ) {
13022 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13023 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13024 }
13025
13026 fn go_to_prev_diagnostic(
13027 &mut self,
13028 _: &GoToPreviousDiagnostic,
13029 window: &mut Window,
13030 cx: &mut Context<Self>,
13031 ) {
13032 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13033 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13034 }
13035
13036 pub fn go_to_diagnostic_impl(
13037 &mut self,
13038 direction: Direction,
13039 window: &mut Window,
13040 cx: &mut Context<Self>,
13041 ) {
13042 let buffer = self.buffer.read(cx).snapshot(cx);
13043 let selection = self.selections.newest::<usize>(cx);
13044 // If there is an active Diagnostic Popover jump to its diagnostic instead.
13045 if direction == Direction::Next {
13046 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
13047 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
13048 return;
13049 };
13050 self.activate_diagnostics(
13051 buffer_id,
13052 popover.local_diagnostic.diagnostic.group_id,
13053 window,
13054 cx,
13055 );
13056 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
13057 let primary_range_start = active_diagnostics.primary_range.start;
13058 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13059 let mut new_selection = s.newest_anchor().clone();
13060 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
13061 s.select_anchors(vec![new_selection.clone()]);
13062 });
13063 self.refresh_inline_completion(false, true, window, cx);
13064 }
13065 return;
13066 }
13067 }
13068
13069 let active_group_id = self
13070 .active_diagnostics
13071 .as_ref()
13072 .map(|active_group| active_group.group_id);
13073 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
13074 active_diagnostics
13075 .primary_range
13076 .to_offset(&buffer)
13077 .to_inclusive()
13078 });
13079 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
13080 if active_primary_range.contains(&selection.head()) {
13081 *active_primary_range.start()
13082 } else {
13083 selection.head()
13084 }
13085 } else {
13086 selection.head()
13087 };
13088
13089 let snapshot = self.snapshot(window, cx);
13090 let primary_diagnostics_before = buffer
13091 .diagnostics_in_range::<usize>(0..search_start)
13092 .filter(|entry| entry.diagnostic.is_primary)
13093 .filter(|entry| entry.range.start != entry.range.end)
13094 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13095 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
13096 .collect::<Vec<_>>();
13097 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
13098 primary_diagnostics_before
13099 .iter()
13100 .position(|entry| entry.diagnostic.group_id == active_group_id)
13101 });
13102
13103 let primary_diagnostics_after = buffer
13104 .diagnostics_in_range::<usize>(search_start..buffer.len())
13105 .filter(|entry| entry.diagnostic.is_primary)
13106 .filter(|entry| entry.range.start != entry.range.end)
13107 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
13108 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
13109 .collect::<Vec<_>>();
13110 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
13111 primary_diagnostics_after
13112 .iter()
13113 .enumerate()
13114 .rev()
13115 .find_map(|(i, entry)| {
13116 if entry.diagnostic.group_id == active_group_id {
13117 Some(i)
13118 } else {
13119 None
13120 }
13121 })
13122 });
13123
13124 let next_primary_diagnostic = match direction {
13125 Direction::Prev => primary_diagnostics_before
13126 .iter()
13127 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
13128 .rev()
13129 .next(),
13130 Direction::Next => primary_diagnostics_after
13131 .iter()
13132 .skip(
13133 last_same_group_diagnostic_after
13134 .map(|index| index + 1)
13135 .unwrap_or(0),
13136 )
13137 .next(),
13138 };
13139
13140 // Cycle around to the start of the buffer, potentially moving back to the start of
13141 // the currently active diagnostic.
13142 let cycle_around = || match direction {
13143 Direction::Prev => primary_diagnostics_after
13144 .iter()
13145 .rev()
13146 .chain(primary_diagnostics_before.iter().rev())
13147 .next(),
13148 Direction::Next => primary_diagnostics_before
13149 .iter()
13150 .chain(primary_diagnostics_after.iter())
13151 .next(),
13152 };
13153
13154 if let Some((primary_range, group_id)) = next_primary_diagnostic
13155 .or_else(cycle_around)
13156 .map(|entry| (&entry.range, entry.diagnostic.group_id))
13157 {
13158 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
13159 return;
13160 };
13161 self.activate_diagnostics(buffer_id, group_id, window, cx);
13162 if self.active_diagnostics.is_some() {
13163 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13164 s.select(vec![Selection {
13165 id: selection.id,
13166 start: primary_range.start,
13167 end: primary_range.start,
13168 reversed: false,
13169 goal: SelectionGoal::None,
13170 }]);
13171 });
13172 self.refresh_inline_completion(false, true, window, cx);
13173 }
13174 }
13175 }
13176
13177 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13178 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13179 let snapshot = self.snapshot(window, cx);
13180 let selection = self.selections.newest::<Point>(cx);
13181 self.go_to_hunk_before_or_after_position(
13182 &snapshot,
13183 selection.head(),
13184 Direction::Next,
13185 window,
13186 cx,
13187 );
13188 }
13189
13190 pub fn go_to_hunk_before_or_after_position(
13191 &mut self,
13192 snapshot: &EditorSnapshot,
13193 position: Point,
13194 direction: Direction,
13195 window: &mut Window,
13196 cx: &mut Context<Editor>,
13197 ) {
13198 let row = if direction == Direction::Next {
13199 self.hunk_after_position(snapshot, position)
13200 .map(|hunk| hunk.row_range.start)
13201 } else {
13202 self.hunk_before_position(snapshot, position)
13203 };
13204
13205 if let Some(row) = row {
13206 let destination = Point::new(row.0, 0);
13207 let autoscroll = Autoscroll::center();
13208
13209 self.unfold_ranges(&[destination..destination], false, false, cx);
13210 self.change_selections(Some(autoscroll), window, cx, |s| {
13211 s.select_ranges([destination..destination]);
13212 });
13213 }
13214 }
13215
13216 fn hunk_after_position(
13217 &mut self,
13218 snapshot: &EditorSnapshot,
13219 position: Point,
13220 ) -> Option<MultiBufferDiffHunk> {
13221 snapshot
13222 .buffer_snapshot
13223 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13224 .find(|hunk| hunk.row_range.start.0 > position.row)
13225 .or_else(|| {
13226 snapshot
13227 .buffer_snapshot
13228 .diff_hunks_in_range(Point::zero()..position)
13229 .find(|hunk| hunk.row_range.end.0 < position.row)
13230 })
13231 }
13232
13233 fn go_to_prev_hunk(
13234 &mut self,
13235 _: &GoToPreviousHunk,
13236 window: &mut Window,
13237 cx: &mut Context<Self>,
13238 ) {
13239 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13240 let snapshot = self.snapshot(window, cx);
13241 let selection = self.selections.newest::<Point>(cx);
13242 self.go_to_hunk_before_or_after_position(
13243 &snapshot,
13244 selection.head(),
13245 Direction::Prev,
13246 window,
13247 cx,
13248 );
13249 }
13250
13251 fn hunk_before_position(
13252 &mut self,
13253 snapshot: &EditorSnapshot,
13254 position: Point,
13255 ) -> Option<MultiBufferRow> {
13256 snapshot
13257 .buffer_snapshot
13258 .diff_hunk_before(position)
13259 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13260 }
13261
13262 fn go_to_line<T: 'static>(
13263 &mut self,
13264 position: Anchor,
13265 highlight_color: Option<Hsla>,
13266 window: &mut Window,
13267 cx: &mut Context<Self>,
13268 ) {
13269 let snapshot = self.snapshot(window, cx).display_snapshot;
13270 let position = position.to_point(&snapshot.buffer_snapshot);
13271 let start = snapshot
13272 .buffer_snapshot
13273 .clip_point(Point::new(position.row, 0), Bias::Left);
13274 let end = start + Point::new(1, 0);
13275 let start = snapshot.buffer_snapshot.anchor_before(start);
13276 let end = snapshot.buffer_snapshot.anchor_before(end);
13277
13278 self.highlight_rows::<T>(
13279 start..end,
13280 highlight_color
13281 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13282 false,
13283 cx,
13284 );
13285 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13286 }
13287
13288 pub fn go_to_definition(
13289 &mut self,
13290 _: &GoToDefinition,
13291 window: &mut Window,
13292 cx: &mut Context<Self>,
13293 ) -> Task<Result<Navigated>> {
13294 let definition =
13295 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13296 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13297 cx.spawn_in(window, async move |editor, cx| {
13298 if definition.await? == Navigated::Yes {
13299 return Ok(Navigated::Yes);
13300 }
13301 match fallback_strategy {
13302 GoToDefinitionFallback::None => Ok(Navigated::No),
13303 GoToDefinitionFallback::FindAllReferences => {
13304 match editor.update_in(cx, |editor, window, cx| {
13305 editor.find_all_references(&FindAllReferences, window, cx)
13306 })? {
13307 Some(references) => references.await,
13308 None => Ok(Navigated::No),
13309 }
13310 }
13311 }
13312 })
13313 }
13314
13315 pub fn go_to_declaration(
13316 &mut self,
13317 _: &GoToDeclaration,
13318 window: &mut Window,
13319 cx: &mut Context<Self>,
13320 ) -> Task<Result<Navigated>> {
13321 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13322 }
13323
13324 pub fn go_to_declaration_split(
13325 &mut self,
13326 _: &GoToDeclaration,
13327 window: &mut Window,
13328 cx: &mut Context<Self>,
13329 ) -> Task<Result<Navigated>> {
13330 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13331 }
13332
13333 pub fn go_to_implementation(
13334 &mut self,
13335 _: &GoToImplementation,
13336 window: &mut Window,
13337 cx: &mut Context<Self>,
13338 ) -> Task<Result<Navigated>> {
13339 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13340 }
13341
13342 pub fn go_to_implementation_split(
13343 &mut self,
13344 _: &GoToImplementationSplit,
13345 window: &mut Window,
13346 cx: &mut Context<Self>,
13347 ) -> Task<Result<Navigated>> {
13348 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13349 }
13350
13351 pub fn go_to_type_definition(
13352 &mut self,
13353 _: &GoToTypeDefinition,
13354 window: &mut Window,
13355 cx: &mut Context<Self>,
13356 ) -> Task<Result<Navigated>> {
13357 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13358 }
13359
13360 pub fn go_to_definition_split(
13361 &mut self,
13362 _: &GoToDefinitionSplit,
13363 window: &mut Window,
13364 cx: &mut Context<Self>,
13365 ) -> Task<Result<Navigated>> {
13366 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13367 }
13368
13369 pub fn go_to_type_definition_split(
13370 &mut self,
13371 _: &GoToTypeDefinitionSplit,
13372 window: &mut Window,
13373 cx: &mut Context<Self>,
13374 ) -> Task<Result<Navigated>> {
13375 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13376 }
13377
13378 fn go_to_definition_of_kind(
13379 &mut self,
13380 kind: GotoDefinitionKind,
13381 split: bool,
13382 window: &mut Window,
13383 cx: &mut Context<Self>,
13384 ) -> Task<Result<Navigated>> {
13385 let Some(provider) = self.semantics_provider.clone() else {
13386 return Task::ready(Ok(Navigated::No));
13387 };
13388 let head = self.selections.newest::<usize>(cx).head();
13389 let buffer = self.buffer.read(cx);
13390 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13391 text_anchor
13392 } else {
13393 return Task::ready(Ok(Navigated::No));
13394 };
13395
13396 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13397 return Task::ready(Ok(Navigated::No));
13398 };
13399
13400 cx.spawn_in(window, async move |editor, cx| {
13401 let definitions = definitions.await?;
13402 let navigated = editor
13403 .update_in(cx, |editor, window, cx| {
13404 editor.navigate_to_hover_links(
13405 Some(kind),
13406 definitions
13407 .into_iter()
13408 .filter(|location| {
13409 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13410 })
13411 .map(HoverLink::Text)
13412 .collect::<Vec<_>>(),
13413 split,
13414 window,
13415 cx,
13416 )
13417 })?
13418 .await?;
13419 anyhow::Ok(navigated)
13420 })
13421 }
13422
13423 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13424 let selection = self.selections.newest_anchor();
13425 let head = selection.head();
13426 let tail = selection.tail();
13427
13428 let Some((buffer, start_position)) =
13429 self.buffer.read(cx).text_anchor_for_position(head, cx)
13430 else {
13431 return;
13432 };
13433
13434 let end_position = if head != tail {
13435 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13436 return;
13437 };
13438 Some(pos)
13439 } else {
13440 None
13441 };
13442
13443 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13444 let url = if let Some(end_pos) = end_position {
13445 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13446 } else {
13447 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13448 };
13449
13450 if let Some(url) = url {
13451 editor.update(cx, |_, cx| {
13452 cx.open_url(&url);
13453 })
13454 } else {
13455 Ok(())
13456 }
13457 });
13458
13459 url_finder.detach();
13460 }
13461
13462 pub fn open_selected_filename(
13463 &mut self,
13464 _: &OpenSelectedFilename,
13465 window: &mut Window,
13466 cx: &mut Context<Self>,
13467 ) {
13468 let Some(workspace) = self.workspace() else {
13469 return;
13470 };
13471
13472 let position = self.selections.newest_anchor().head();
13473
13474 let Some((buffer, buffer_position)) =
13475 self.buffer.read(cx).text_anchor_for_position(position, cx)
13476 else {
13477 return;
13478 };
13479
13480 let project = self.project.clone();
13481
13482 cx.spawn_in(window, async move |_, cx| {
13483 let result = find_file(&buffer, project, buffer_position, cx).await;
13484
13485 if let Some((_, path)) = result {
13486 workspace
13487 .update_in(cx, |workspace, window, cx| {
13488 workspace.open_resolved_path(path, window, cx)
13489 })?
13490 .await?;
13491 }
13492 anyhow::Ok(())
13493 })
13494 .detach();
13495 }
13496
13497 pub(crate) fn navigate_to_hover_links(
13498 &mut self,
13499 kind: Option<GotoDefinitionKind>,
13500 mut definitions: Vec<HoverLink>,
13501 split: bool,
13502 window: &mut Window,
13503 cx: &mut Context<Editor>,
13504 ) -> Task<Result<Navigated>> {
13505 // If there is one definition, just open it directly
13506 if definitions.len() == 1 {
13507 let definition = definitions.pop().unwrap();
13508
13509 enum TargetTaskResult {
13510 Location(Option<Location>),
13511 AlreadyNavigated,
13512 }
13513
13514 let target_task = match definition {
13515 HoverLink::Text(link) => {
13516 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13517 }
13518 HoverLink::InlayHint(lsp_location, server_id) => {
13519 let computation =
13520 self.compute_target_location(lsp_location, server_id, window, cx);
13521 cx.background_spawn(async move {
13522 let location = computation.await?;
13523 Ok(TargetTaskResult::Location(location))
13524 })
13525 }
13526 HoverLink::Url(url) => {
13527 cx.open_url(&url);
13528 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13529 }
13530 HoverLink::File(path) => {
13531 if let Some(workspace) = self.workspace() {
13532 cx.spawn_in(window, async move |_, cx| {
13533 workspace
13534 .update_in(cx, |workspace, window, cx| {
13535 workspace.open_resolved_path(path, window, cx)
13536 })?
13537 .await
13538 .map(|_| TargetTaskResult::AlreadyNavigated)
13539 })
13540 } else {
13541 Task::ready(Ok(TargetTaskResult::Location(None)))
13542 }
13543 }
13544 };
13545 cx.spawn_in(window, async move |editor, cx| {
13546 let target = match target_task.await.context("target resolution task")? {
13547 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13548 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13549 TargetTaskResult::Location(Some(target)) => target,
13550 };
13551
13552 editor.update_in(cx, |editor, window, cx| {
13553 let Some(workspace) = editor.workspace() else {
13554 return Navigated::No;
13555 };
13556 let pane = workspace.read(cx).active_pane().clone();
13557
13558 let range = target.range.to_point(target.buffer.read(cx));
13559 let range = editor.range_for_match(&range);
13560 let range = collapse_multiline_range(range);
13561
13562 if !split
13563 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13564 {
13565 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13566 } else {
13567 window.defer(cx, move |window, cx| {
13568 let target_editor: Entity<Self> =
13569 workspace.update(cx, |workspace, cx| {
13570 let pane = if split {
13571 workspace.adjacent_pane(window, cx)
13572 } else {
13573 workspace.active_pane().clone()
13574 };
13575
13576 workspace.open_project_item(
13577 pane,
13578 target.buffer.clone(),
13579 true,
13580 true,
13581 window,
13582 cx,
13583 )
13584 });
13585 target_editor.update(cx, |target_editor, cx| {
13586 // When selecting a definition in a different buffer, disable the nav history
13587 // to avoid creating a history entry at the previous cursor location.
13588 pane.update(cx, |pane, _| pane.disable_history());
13589 target_editor.go_to_singleton_buffer_range(range, window, cx);
13590 pane.update(cx, |pane, _| pane.enable_history());
13591 });
13592 });
13593 }
13594 Navigated::Yes
13595 })
13596 })
13597 } else if !definitions.is_empty() {
13598 cx.spawn_in(window, async move |editor, cx| {
13599 let (title, location_tasks, workspace) = editor
13600 .update_in(cx, |editor, window, cx| {
13601 let tab_kind = match kind {
13602 Some(GotoDefinitionKind::Implementation) => "Implementations",
13603 _ => "Definitions",
13604 };
13605 let title = definitions
13606 .iter()
13607 .find_map(|definition| match definition {
13608 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13609 let buffer = origin.buffer.read(cx);
13610 format!(
13611 "{} for {}",
13612 tab_kind,
13613 buffer
13614 .text_for_range(origin.range.clone())
13615 .collect::<String>()
13616 )
13617 }),
13618 HoverLink::InlayHint(_, _) => None,
13619 HoverLink::Url(_) => None,
13620 HoverLink::File(_) => None,
13621 })
13622 .unwrap_or(tab_kind.to_string());
13623 let location_tasks = definitions
13624 .into_iter()
13625 .map(|definition| match definition {
13626 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13627 HoverLink::InlayHint(lsp_location, server_id) => editor
13628 .compute_target_location(lsp_location, server_id, window, cx),
13629 HoverLink::Url(_) => Task::ready(Ok(None)),
13630 HoverLink::File(_) => Task::ready(Ok(None)),
13631 })
13632 .collect::<Vec<_>>();
13633 (title, location_tasks, editor.workspace().clone())
13634 })
13635 .context("location tasks preparation")?;
13636
13637 let locations = future::join_all(location_tasks)
13638 .await
13639 .into_iter()
13640 .filter_map(|location| location.transpose())
13641 .collect::<Result<_>>()
13642 .context("location tasks")?;
13643
13644 let Some(workspace) = workspace else {
13645 return Ok(Navigated::No);
13646 };
13647 let opened = workspace
13648 .update_in(cx, |workspace, window, cx| {
13649 Self::open_locations_in_multibuffer(
13650 workspace,
13651 locations,
13652 title,
13653 split,
13654 MultibufferSelectionMode::First,
13655 window,
13656 cx,
13657 )
13658 })
13659 .ok();
13660
13661 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13662 })
13663 } else {
13664 Task::ready(Ok(Navigated::No))
13665 }
13666 }
13667
13668 fn compute_target_location(
13669 &self,
13670 lsp_location: lsp::Location,
13671 server_id: LanguageServerId,
13672 window: &mut Window,
13673 cx: &mut Context<Self>,
13674 ) -> Task<anyhow::Result<Option<Location>>> {
13675 let Some(project) = self.project.clone() else {
13676 return Task::ready(Ok(None));
13677 };
13678
13679 cx.spawn_in(window, async move |editor, cx| {
13680 let location_task = editor.update(cx, |_, cx| {
13681 project.update(cx, |project, cx| {
13682 let language_server_name = project
13683 .language_server_statuses(cx)
13684 .find(|(id, _)| server_id == *id)
13685 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13686 language_server_name.map(|language_server_name| {
13687 project.open_local_buffer_via_lsp(
13688 lsp_location.uri.clone(),
13689 server_id,
13690 language_server_name,
13691 cx,
13692 )
13693 })
13694 })
13695 })?;
13696 let location = match location_task {
13697 Some(task) => Some({
13698 let target_buffer_handle = task.await.context("open local buffer")?;
13699 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13700 let target_start = target_buffer
13701 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13702 let target_end = target_buffer
13703 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13704 target_buffer.anchor_after(target_start)
13705 ..target_buffer.anchor_before(target_end)
13706 })?;
13707 Location {
13708 buffer: target_buffer_handle,
13709 range,
13710 }
13711 }),
13712 None => None,
13713 };
13714 Ok(location)
13715 })
13716 }
13717
13718 pub fn find_all_references(
13719 &mut self,
13720 _: &FindAllReferences,
13721 window: &mut Window,
13722 cx: &mut Context<Self>,
13723 ) -> Option<Task<Result<Navigated>>> {
13724 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13725
13726 let selection = self.selections.newest::<usize>(cx);
13727 let multi_buffer = self.buffer.read(cx);
13728 let head = selection.head();
13729
13730 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13731 let head_anchor = multi_buffer_snapshot.anchor_at(
13732 head,
13733 if head < selection.tail() {
13734 Bias::Right
13735 } else {
13736 Bias::Left
13737 },
13738 );
13739
13740 match self
13741 .find_all_references_task_sources
13742 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13743 {
13744 Ok(_) => {
13745 log::info!(
13746 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13747 );
13748 return None;
13749 }
13750 Err(i) => {
13751 self.find_all_references_task_sources.insert(i, head_anchor);
13752 }
13753 }
13754
13755 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13756 let workspace = self.workspace()?;
13757 let project = workspace.read(cx).project().clone();
13758 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13759 Some(cx.spawn_in(window, async move |editor, cx| {
13760 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13761 if let Ok(i) = editor
13762 .find_all_references_task_sources
13763 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13764 {
13765 editor.find_all_references_task_sources.remove(i);
13766 }
13767 });
13768
13769 let locations = references.await?;
13770 if locations.is_empty() {
13771 return anyhow::Ok(Navigated::No);
13772 }
13773
13774 workspace.update_in(cx, |workspace, window, cx| {
13775 let title = locations
13776 .first()
13777 .as_ref()
13778 .map(|location| {
13779 let buffer = location.buffer.read(cx);
13780 format!(
13781 "References to `{}`",
13782 buffer
13783 .text_for_range(location.range.clone())
13784 .collect::<String>()
13785 )
13786 })
13787 .unwrap();
13788 Self::open_locations_in_multibuffer(
13789 workspace,
13790 locations,
13791 title,
13792 false,
13793 MultibufferSelectionMode::First,
13794 window,
13795 cx,
13796 );
13797 Navigated::Yes
13798 })
13799 }))
13800 }
13801
13802 /// Opens a multibuffer with the given project locations in it
13803 pub fn open_locations_in_multibuffer(
13804 workspace: &mut Workspace,
13805 mut locations: Vec<Location>,
13806 title: String,
13807 split: bool,
13808 multibuffer_selection_mode: MultibufferSelectionMode,
13809 window: &mut Window,
13810 cx: &mut Context<Workspace>,
13811 ) {
13812 // If there are multiple definitions, open them in a multibuffer
13813 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13814 let mut locations = locations.into_iter().peekable();
13815 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13816 let capability = workspace.project().read(cx).capability();
13817
13818 let excerpt_buffer = cx.new(|cx| {
13819 let mut multibuffer = MultiBuffer::new(capability);
13820 while let Some(location) = locations.next() {
13821 let buffer = location.buffer.read(cx);
13822 let mut ranges_for_buffer = Vec::new();
13823 let range = location.range.to_point(buffer);
13824 ranges_for_buffer.push(range.clone());
13825
13826 while let Some(next_location) = locations.peek() {
13827 if next_location.buffer == location.buffer {
13828 ranges_for_buffer.push(next_location.range.to_point(buffer));
13829 locations.next();
13830 } else {
13831 break;
13832 }
13833 }
13834
13835 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13836 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13837 PathKey::for_buffer(&location.buffer, cx),
13838 location.buffer.clone(),
13839 ranges_for_buffer,
13840 DEFAULT_MULTIBUFFER_CONTEXT,
13841 cx,
13842 );
13843 ranges.extend(new_ranges)
13844 }
13845
13846 multibuffer.with_title(title)
13847 });
13848
13849 let editor = cx.new(|cx| {
13850 Editor::for_multibuffer(
13851 excerpt_buffer,
13852 Some(workspace.project().clone()),
13853 window,
13854 cx,
13855 )
13856 });
13857 editor.update(cx, |editor, cx| {
13858 match multibuffer_selection_mode {
13859 MultibufferSelectionMode::First => {
13860 if let Some(first_range) = ranges.first() {
13861 editor.change_selections(None, window, cx, |selections| {
13862 selections.clear_disjoint();
13863 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13864 });
13865 }
13866 editor.highlight_background::<Self>(
13867 &ranges,
13868 |theme| theme.editor_highlighted_line_background,
13869 cx,
13870 );
13871 }
13872 MultibufferSelectionMode::All => {
13873 editor.change_selections(None, window, cx, |selections| {
13874 selections.clear_disjoint();
13875 selections.select_anchor_ranges(ranges);
13876 });
13877 }
13878 }
13879 editor.register_buffers_with_language_servers(cx);
13880 });
13881
13882 let item = Box::new(editor);
13883 let item_id = item.item_id();
13884
13885 if split {
13886 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13887 } else {
13888 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13889 let (preview_item_id, preview_item_idx) =
13890 workspace.active_pane().update(cx, |pane, _| {
13891 (pane.preview_item_id(), pane.preview_item_idx())
13892 });
13893
13894 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13895
13896 if let Some(preview_item_id) = preview_item_id {
13897 workspace.active_pane().update(cx, |pane, cx| {
13898 pane.remove_item(preview_item_id, false, false, window, cx);
13899 });
13900 }
13901 } else {
13902 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13903 }
13904 }
13905 workspace.active_pane().update(cx, |pane, cx| {
13906 pane.set_preview_item_id(Some(item_id), cx);
13907 });
13908 }
13909
13910 pub fn rename(
13911 &mut self,
13912 _: &Rename,
13913 window: &mut Window,
13914 cx: &mut Context<Self>,
13915 ) -> Option<Task<Result<()>>> {
13916 use language::ToOffset as _;
13917
13918 let provider = self.semantics_provider.clone()?;
13919 let selection = self.selections.newest_anchor().clone();
13920 let (cursor_buffer, cursor_buffer_position) = self
13921 .buffer
13922 .read(cx)
13923 .text_anchor_for_position(selection.head(), cx)?;
13924 let (tail_buffer, cursor_buffer_position_end) = self
13925 .buffer
13926 .read(cx)
13927 .text_anchor_for_position(selection.tail(), cx)?;
13928 if tail_buffer != cursor_buffer {
13929 return None;
13930 }
13931
13932 let snapshot = cursor_buffer.read(cx).snapshot();
13933 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13934 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13935 let prepare_rename = provider
13936 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13937 .unwrap_or_else(|| Task::ready(Ok(None)));
13938 drop(snapshot);
13939
13940 Some(cx.spawn_in(window, async move |this, cx| {
13941 let rename_range = if let Some(range) = prepare_rename.await? {
13942 Some(range)
13943 } else {
13944 this.update(cx, |this, cx| {
13945 let buffer = this.buffer.read(cx).snapshot(cx);
13946 let mut buffer_highlights = this
13947 .document_highlights_for_position(selection.head(), &buffer)
13948 .filter(|highlight| {
13949 highlight.start.excerpt_id == selection.head().excerpt_id
13950 && highlight.end.excerpt_id == selection.head().excerpt_id
13951 });
13952 buffer_highlights
13953 .next()
13954 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13955 })?
13956 };
13957 if let Some(rename_range) = rename_range {
13958 this.update_in(cx, |this, window, cx| {
13959 let snapshot = cursor_buffer.read(cx).snapshot();
13960 let rename_buffer_range = rename_range.to_offset(&snapshot);
13961 let cursor_offset_in_rename_range =
13962 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13963 let cursor_offset_in_rename_range_end =
13964 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13965
13966 this.take_rename(false, window, cx);
13967 let buffer = this.buffer.read(cx).read(cx);
13968 let cursor_offset = selection.head().to_offset(&buffer);
13969 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13970 let rename_end = rename_start + rename_buffer_range.len();
13971 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13972 let mut old_highlight_id = None;
13973 let old_name: Arc<str> = buffer
13974 .chunks(rename_start..rename_end, true)
13975 .map(|chunk| {
13976 if old_highlight_id.is_none() {
13977 old_highlight_id = chunk.syntax_highlight_id;
13978 }
13979 chunk.text
13980 })
13981 .collect::<String>()
13982 .into();
13983
13984 drop(buffer);
13985
13986 // Position the selection in the rename editor so that it matches the current selection.
13987 this.show_local_selections = false;
13988 let rename_editor = cx.new(|cx| {
13989 let mut editor = Editor::single_line(window, cx);
13990 editor.buffer.update(cx, |buffer, cx| {
13991 buffer.edit([(0..0, old_name.clone())], None, cx)
13992 });
13993 let rename_selection_range = match cursor_offset_in_rename_range
13994 .cmp(&cursor_offset_in_rename_range_end)
13995 {
13996 Ordering::Equal => {
13997 editor.select_all(&SelectAll, window, cx);
13998 return editor;
13999 }
14000 Ordering::Less => {
14001 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14002 }
14003 Ordering::Greater => {
14004 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14005 }
14006 };
14007 if rename_selection_range.end > old_name.len() {
14008 editor.select_all(&SelectAll, window, cx);
14009 } else {
14010 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14011 s.select_ranges([rename_selection_range]);
14012 });
14013 }
14014 editor
14015 });
14016 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14017 if e == &EditorEvent::Focused {
14018 cx.emit(EditorEvent::FocusedIn)
14019 }
14020 })
14021 .detach();
14022
14023 let write_highlights =
14024 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14025 let read_highlights =
14026 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14027 let ranges = write_highlights
14028 .iter()
14029 .flat_map(|(_, ranges)| ranges.iter())
14030 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14031 .cloned()
14032 .collect();
14033
14034 this.highlight_text::<Rename>(
14035 ranges,
14036 HighlightStyle {
14037 fade_out: Some(0.6),
14038 ..Default::default()
14039 },
14040 cx,
14041 );
14042 let rename_focus_handle = rename_editor.focus_handle(cx);
14043 window.focus(&rename_focus_handle);
14044 let block_id = this.insert_blocks(
14045 [BlockProperties {
14046 style: BlockStyle::Flex,
14047 placement: BlockPlacement::Below(range.start),
14048 height: Some(1),
14049 render: Arc::new({
14050 let rename_editor = rename_editor.clone();
14051 move |cx: &mut BlockContext| {
14052 let mut text_style = cx.editor_style.text.clone();
14053 if let Some(highlight_style) = old_highlight_id
14054 .and_then(|h| h.style(&cx.editor_style.syntax))
14055 {
14056 text_style = text_style.highlight(highlight_style);
14057 }
14058 div()
14059 .block_mouse_down()
14060 .pl(cx.anchor_x)
14061 .child(EditorElement::new(
14062 &rename_editor,
14063 EditorStyle {
14064 background: cx.theme().system().transparent,
14065 local_player: cx.editor_style.local_player,
14066 text: text_style,
14067 scrollbar_width: cx.editor_style.scrollbar_width,
14068 syntax: cx.editor_style.syntax.clone(),
14069 status: cx.editor_style.status.clone(),
14070 inlay_hints_style: HighlightStyle {
14071 font_weight: Some(FontWeight::BOLD),
14072 ..make_inlay_hints_style(cx.app)
14073 },
14074 inline_completion_styles: make_suggestion_styles(
14075 cx.app,
14076 ),
14077 ..EditorStyle::default()
14078 },
14079 ))
14080 .into_any_element()
14081 }
14082 }),
14083 priority: 0,
14084 }],
14085 Some(Autoscroll::fit()),
14086 cx,
14087 )[0];
14088 this.pending_rename = Some(RenameState {
14089 range,
14090 old_name,
14091 editor: rename_editor,
14092 block_id,
14093 });
14094 })?;
14095 }
14096
14097 Ok(())
14098 }))
14099 }
14100
14101 pub fn confirm_rename(
14102 &mut self,
14103 _: &ConfirmRename,
14104 window: &mut Window,
14105 cx: &mut Context<Self>,
14106 ) -> Option<Task<Result<()>>> {
14107 let rename = self.take_rename(false, window, cx)?;
14108 let workspace = self.workspace()?.downgrade();
14109 let (buffer, start) = self
14110 .buffer
14111 .read(cx)
14112 .text_anchor_for_position(rename.range.start, cx)?;
14113 let (end_buffer, _) = self
14114 .buffer
14115 .read(cx)
14116 .text_anchor_for_position(rename.range.end, cx)?;
14117 if buffer != end_buffer {
14118 return None;
14119 }
14120
14121 let old_name = rename.old_name;
14122 let new_name = rename.editor.read(cx).text(cx);
14123
14124 let rename = self.semantics_provider.as_ref()?.perform_rename(
14125 &buffer,
14126 start,
14127 new_name.clone(),
14128 cx,
14129 )?;
14130
14131 Some(cx.spawn_in(window, async move |editor, cx| {
14132 let project_transaction = rename.await?;
14133 Self::open_project_transaction(
14134 &editor,
14135 workspace,
14136 project_transaction,
14137 format!("Rename: {} → {}", old_name, new_name),
14138 cx,
14139 )
14140 .await?;
14141
14142 editor.update(cx, |editor, cx| {
14143 editor.refresh_document_highlights(cx);
14144 })?;
14145 Ok(())
14146 }))
14147 }
14148
14149 fn take_rename(
14150 &mut self,
14151 moving_cursor: bool,
14152 window: &mut Window,
14153 cx: &mut Context<Self>,
14154 ) -> Option<RenameState> {
14155 let rename = self.pending_rename.take()?;
14156 if rename.editor.focus_handle(cx).is_focused(window) {
14157 window.focus(&self.focus_handle);
14158 }
14159
14160 self.remove_blocks(
14161 [rename.block_id].into_iter().collect(),
14162 Some(Autoscroll::fit()),
14163 cx,
14164 );
14165 self.clear_highlights::<Rename>(cx);
14166 self.show_local_selections = true;
14167
14168 if moving_cursor {
14169 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14170 editor.selections.newest::<usize>(cx).head()
14171 });
14172
14173 // Update the selection to match the position of the selection inside
14174 // the rename editor.
14175 let snapshot = self.buffer.read(cx).read(cx);
14176 let rename_range = rename.range.to_offset(&snapshot);
14177 let cursor_in_editor = snapshot
14178 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14179 .min(rename_range.end);
14180 drop(snapshot);
14181
14182 self.change_selections(None, window, cx, |s| {
14183 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14184 });
14185 } else {
14186 self.refresh_document_highlights(cx);
14187 }
14188
14189 Some(rename)
14190 }
14191
14192 pub fn pending_rename(&self) -> Option<&RenameState> {
14193 self.pending_rename.as_ref()
14194 }
14195
14196 fn format(
14197 &mut self,
14198 _: &Format,
14199 window: &mut Window,
14200 cx: &mut Context<Self>,
14201 ) -> Option<Task<Result<()>>> {
14202 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14203
14204 let project = match &self.project {
14205 Some(project) => project.clone(),
14206 None => return None,
14207 };
14208
14209 Some(self.perform_format(
14210 project,
14211 FormatTrigger::Manual,
14212 FormatTarget::Buffers,
14213 window,
14214 cx,
14215 ))
14216 }
14217
14218 fn format_selections(
14219 &mut self,
14220 _: &FormatSelections,
14221 window: &mut Window,
14222 cx: &mut Context<Self>,
14223 ) -> Option<Task<Result<()>>> {
14224 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14225
14226 let project = match &self.project {
14227 Some(project) => project.clone(),
14228 None => return None,
14229 };
14230
14231 let ranges = self
14232 .selections
14233 .all_adjusted(cx)
14234 .into_iter()
14235 .map(|selection| selection.range())
14236 .collect_vec();
14237
14238 Some(self.perform_format(
14239 project,
14240 FormatTrigger::Manual,
14241 FormatTarget::Ranges(ranges),
14242 window,
14243 cx,
14244 ))
14245 }
14246
14247 fn perform_format(
14248 &mut self,
14249 project: Entity<Project>,
14250 trigger: FormatTrigger,
14251 target: FormatTarget,
14252 window: &mut Window,
14253 cx: &mut Context<Self>,
14254 ) -> Task<Result<()>> {
14255 let buffer = self.buffer.clone();
14256 let (buffers, target) = match target {
14257 FormatTarget::Buffers => {
14258 let mut buffers = buffer.read(cx).all_buffers();
14259 if trigger == FormatTrigger::Save {
14260 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14261 }
14262 (buffers, LspFormatTarget::Buffers)
14263 }
14264 FormatTarget::Ranges(selection_ranges) => {
14265 let multi_buffer = buffer.read(cx);
14266 let snapshot = multi_buffer.read(cx);
14267 let mut buffers = HashSet::default();
14268 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14269 BTreeMap::new();
14270 for selection_range in selection_ranges {
14271 for (buffer, buffer_range, _) in
14272 snapshot.range_to_buffer_ranges(selection_range)
14273 {
14274 let buffer_id = buffer.remote_id();
14275 let start = buffer.anchor_before(buffer_range.start);
14276 let end = buffer.anchor_after(buffer_range.end);
14277 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14278 buffer_id_to_ranges
14279 .entry(buffer_id)
14280 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14281 .or_insert_with(|| vec![start..end]);
14282 }
14283 }
14284 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14285 }
14286 };
14287
14288 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14289 let selections_prev = transaction_id_prev
14290 .and_then(|transaction_id_prev| {
14291 // default to selections as they were after the last edit, if we have them,
14292 // instead of how they are now.
14293 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14294 // will take you back to where you made the last edit, instead of staying where you scrolled
14295 self.selection_history
14296 .transaction(transaction_id_prev)
14297 .map(|t| t.0.clone())
14298 })
14299 .unwrap_or_else(|| {
14300 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14301 self.selections.disjoint_anchors()
14302 });
14303
14304 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14305 let format = project.update(cx, |project, cx| {
14306 project.format(buffers, target, true, trigger, cx)
14307 });
14308
14309 cx.spawn_in(window, async move |editor, cx| {
14310 let transaction = futures::select_biased! {
14311 transaction = format.log_err().fuse() => transaction,
14312 () = timeout => {
14313 log::warn!("timed out waiting for formatting");
14314 None
14315 }
14316 };
14317
14318 buffer
14319 .update(cx, |buffer, cx| {
14320 if let Some(transaction) = transaction {
14321 if !buffer.is_singleton() {
14322 buffer.push_transaction(&transaction.0, cx);
14323 }
14324 }
14325 cx.notify();
14326 })
14327 .ok();
14328
14329 if let Some(transaction_id_now) =
14330 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14331 {
14332 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14333 if has_new_transaction {
14334 _ = editor.update(cx, |editor, _| {
14335 editor
14336 .selection_history
14337 .insert_transaction(transaction_id_now, selections_prev);
14338 });
14339 }
14340 }
14341
14342 Ok(())
14343 })
14344 }
14345
14346 fn organize_imports(
14347 &mut self,
14348 _: &OrganizeImports,
14349 window: &mut Window,
14350 cx: &mut Context<Self>,
14351 ) -> Option<Task<Result<()>>> {
14352 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14353 let project = match &self.project {
14354 Some(project) => project.clone(),
14355 None => return None,
14356 };
14357 Some(self.perform_code_action_kind(
14358 project,
14359 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14360 window,
14361 cx,
14362 ))
14363 }
14364
14365 fn perform_code_action_kind(
14366 &mut self,
14367 project: Entity<Project>,
14368 kind: CodeActionKind,
14369 window: &mut Window,
14370 cx: &mut Context<Self>,
14371 ) -> Task<Result<()>> {
14372 let buffer = self.buffer.clone();
14373 let buffers = buffer.read(cx).all_buffers();
14374 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14375 let apply_action = project.update(cx, |project, cx| {
14376 project.apply_code_action_kind(buffers, kind, true, cx)
14377 });
14378 cx.spawn_in(window, async move |_, cx| {
14379 let transaction = futures::select_biased! {
14380 () = timeout => {
14381 log::warn!("timed out waiting for executing code action");
14382 None
14383 }
14384 transaction = apply_action.log_err().fuse() => transaction,
14385 };
14386 buffer
14387 .update(cx, |buffer, cx| {
14388 // check if we need this
14389 if let Some(transaction) = transaction {
14390 if !buffer.is_singleton() {
14391 buffer.push_transaction(&transaction.0, cx);
14392 }
14393 }
14394 cx.notify();
14395 })
14396 .ok();
14397 Ok(())
14398 })
14399 }
14400
14401 fn restart_language_server(
14402 &mut self,
14403 _: &RestartLanguageServer,
14404 _: &mut Window,
14405 cx: &mut Context<Self>,
14406 ) {
14407 if let Some(project) = self.project.clone() {
14408 self.buffer.update(cx, |multi_buffer, cx| {
14409 project.update(cx, |project, cx| {
14410 project.restart_language_servers_for_buffers(
14411 multi_buffer.all_buffers().into_iter().collect(),
14412 cx,
14413 );
14414 });
14415 })
14416 }
14417 }
14418
14419 fn stop_language_server(
14420 &mut self,
14421 _: &StopLanguageServer,
14422 _: &mut Window,
14423 cx: &mut Context<Self>,
14424 ) {
14425 if let Some(project) = self.project.clone() {
14426 self.buffer.update(cx, |multi_buffer, cx| {
14427 project.update(cx, |project, cx| {
14428 project.stop_language_servers_for_buffers(
14429 multi_buffer.all_buffers().into_iter().collect(),
14430 cx,
14431 );
14432 cx.emit(project::Event::RefreshInlayHints);
14433 });
14434 });
14435 }
14436 }
14437
14438 fn cancel_language_server_work(
14439 workspace: &mut Workspace,
14440 _: &actions::CancelLanguageServerWork,
14441 _: &mut Window,
14442 cx: &mut Context<Workspace>,
14443 ) {
14444 let project = workspace.project();
14445 let buffers = workspace
14446 .active_item(cx)
14447 .and_then(|item| item.act_as::<Editor>(cx))
14448 .map_or(HashSet::default(), |editor| {
14449 editor.read(cx).buffer.read(cx).all_buffers()
14450 });
14451 project.update(cx, |project, cx| {
14452 project.cancel_language_server_work_for_buffers(buffers, cx);
14453 });
14454 }
14455
14456 fn show_character_palette(
14457 &mut self,
14458 _: &ShowCharacterPalette,
14459 window: &mut Window,
14460 _: &mut Context<Self>,
14461 ) {
14462 window.show_character_palette();
14463 }
14464
14465 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14466 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14467 let buffer = self.buffer.read(cx).snapshot(cx);
14468 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14469 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14470 let is_valid = buffer
14471 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14472 .any(|entry| {
14473 entry.diagnostic.is_primary
14474 && !entry.range.is_empty()
14475 && entry.range.start == primary_range_start
14476 && entry.diagnostic.message == active_diagnostics.primary_message
14477 });
14478
14479 if is_valid != active_diagnostics.is_valid {
14480 active_diagnostics.is_valid = is_valid;
14481 if is_valid {
14482 let mut new_styles = HashMap::default();
14483 for (block_id, diagnostic) in &active_diagnostics.blocks {
14484 new_styles.insert(
14485 *block_id,
14486 diagnostic_block_renderer(diagnostic.clone(), None, true),
14487 );
14488 }
14489 self.display_map.update(cx, |display_map, _cx| {
14490 display_map.replace_blocks(new_styles);
14491 });
14492 } else {
14493 self.dismiss_diagnostics(cx);
14494 }
14495 }
14496 }
14497 }
14498
14499 fn activate_diagnostics(
14500 &mut self,
14501 buffer_id: BufferId,
14502 group_id: usize,
14503 window: &mut Window,
14504 cx: &mut Context<Self>,
14505 ) {
14506 self.dismiss_diagnostics(cx);
14507 let snapshot = self.snapshot(window, cx);
14508 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14509 let buffer = self.buffer.read(cx).snapshot(cx);
14510
14511 let mut primary_range = None;
14512 let mut primary_message = None;
14513 let diagnostic_group = buffer
14514 .diagnostic_group(buffer_id, group_id)
14515 .filter_map(|entry| {
14516 let start = entry.range.start;
14517 let end = entry.range.end;
14518 if snapshot.is_line_folded(MultiBufferRow(start.row))
14519 && (start.row == end.row
14520 || snapshot.is_line_folded(MultiBufferRow(end.row)))
14521 {
14522 return None;
14523 }
14524 if entry.diagnostic.is_primary {
14525 primary_range = Some(entry.range.clone());
14526 primary_message = Some(entry.diagnostic.message.clone());
14527 }
14528 Some(entry)
14529 })
14530 .collect::<Vec<_>>();
14531 let primary_range = primary_range?;
14532 let primary_message = primary_message?;
14533
14534 let blocks = display_map
14535 .insert_blocks(
14536 diagnostic_group.iter().map(|entry| {
14537 let diagnostic = entry.diagnostic.clone();
14538 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14539 BlockProperties {
14540 style: BlockStyle::Fixed,
14541 placement: BlockPlacement::Below(
14542 buffer.anchor_after(entry.range.start),
14543 ),
14544 height: Some(message_height),
14545 render: diagnostic_block_renderer(diagnostic, None, true),
14546 priority: 0,
14547 }
14548 }),
14549 cx,
14550 )
14551 .into_iter()
14552 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14553 .collect();
14554
14555 Some(ActiveDiagnosticGroup {
14556 primary_range: buffer.anchor_before(primary_range.start)
14557 ..buffer.anchor_after(primary_range.end),
14558 primary_message,
14559 group_id,
14560 blocks,
14561 is_valid: true,
14562 })
14563 });
14564 }
14565
14566 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14567 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14568 self.display_map.update(cx, |display_map, cx| {
14569 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14570 });
14571 cx.notify();
14572 }
14573 }
14574
14575 /// Disable inline diagnostics rendering for this editor.
14576 pub fn disable_inline_diagnostics(&mut self) {
14577 self.inline_diagnostics_enabled = false;
14578 self.inline_diagnostics_update = Task::ready(());
14579 self.inline_diagnostics.clear();
14580 }
14581
14582 pub fn inline_diagnostics_enabled(&self) -> bool {
14583 self.inline_diagnostics_enabled
14584 }
14585
14586 pub fn show_inline_diagnostics(&self) -> bool {
14587 self.show_inline_diagnostics
14588 }
14589
14590 pub fn toggle_inline_diagnostics(
14591 &mut self,
14592 _: &ToggleInlineDiagnostics,
14593 window: &mut Window,
14594 cx: &mut Context<Editor>,
14595 ) {
14596 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14597 self.refresh_inline_diagnostics(false, window, cx);
14598 }
14599
14600 fn refresh_inline_diagnostics(
14601 &mut self,
14602 debounce: bool,
14603 window: &mut Window,
14604 cx: &mut Context<Self>,
14605 ) {
14606 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14607 self.inline_diagnostics_update = Task::ready(());
14608 self.inline_diagnostics.clear();
14609 return;
14610 }
14611
14612 let debounce_ms = ProjectSettings::get_global(cx)
14613 .diagnostics
14614 .inline
14615 .update_debounce_ms;
14616 let debounce = if debounce && debounce_ms > 0 {
14617 Some(Duration::from_millis(debounce_ms))
14618 } else {
14619 None
14620 };
14621 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14622 if let Some(debounce) = debounce {
14623 cx.background_executor().timer(debounce).await;
14624 }
14625 let Some(snapshot) = editor
14626 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14627 .ok()
14628 else {
14629 return;
14630 };
14631
14632 let new_inline_diagnostics = cx
14633 .background_spawn(async move {
14634 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14635 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14636 let message = diagnostic_entry
14637 .diagnostic
14638 .message
14639 .split_once('\n')
14640 .map(|(line, _)| line)
14641 .map(SharedString::new)
14642 .unwrap_or_else(|| {
14643 SharedString::from(diagnostic_entry.diagnostic.message)
14644 });
14645 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14646 let (Ok(i) | Err(i)) = inline_diagnostics
14647 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14648 inline_diagnostics.insert(
14649 i,
14650 (
14651 start_anchor,
14652 InlineDiagnostic {
14653 message,
14654 group_id: diagnostic_entry.diagnostic.group_id,
14655 start: diagnostic_entry.range.start.to_point(&snapshot),
14656 is_primary: diagnostic_entry.diagnostic.is_primary,
14657 severity: diagnostic_entry.diagnostic.severity,
14658 },
14659 ),
14660 );
14661 }
14662 inline_diagnostics
14663 })
14664 .await;
14665
14666 editor
14667 .update(cx, |editor, cx| {
14668 editor.inline_diagnostics = new_inline_diagnostics;
14669 cx.notify();
14670 })
14671 .ok();
14672 });
14673 }
14674
14675 pub fn set_selections_from_remote(
14676 &mut self,
14677 selections: Vec<Selection<Anchor>>,
14678 pending_selection: Option<Selection<Anchor>>,
14679 window: &mut Window,
14680 cx: &mut Context<Self>,
14681 ) {
14682 let old_cursor_position = self.selections.newest_anchor().head();
14683 self.selections.change_with(cx, |s| {
14684 s.select_anchors(selections);
14685 if let Some(pending_selection) = pending_selection {
14686 s.set_pending(pending_selection, SelectMode::Character);
14687 } else {
14688 s.clear_pending();
14689 }
14690 });
14691 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14692 }
14693
14694 fn push_to_selection_history(&mut self) {
14695 self.selection_history.push(SelectionHistoryEntry {
14696 selections: self.selections.disjoint_anchors(),
14697 select_next_state: self.select_next_state.clone(),
14698 select_prev_state: self.select_prev_state.clone(),
14699 add_selections_state: self.add_selections_state.clone(),
14700 });
14701 }
14702
14703 pub fn transact(
14704 &mut self,
14705 window: &mut Window,
14706 cx: &mut Context<Self>,
14707 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14708 ) -> Option<TransactionId> {
14709 self.start_transaction_at(Instant::now(), window, cx);
14710 update(self, window, cx);
14711 self.end_transaction_at(Instant::now(), cx)
14712 }
14713
14714 pub fn start_transaction_at(
14715 &mut self,
14716 now: Instant,
14717 window: &mut Window,
14718 cx: &mut Context<Self>,
14719 ) {
14720 self.end_selection(window, cx);
14721 if let Some(tx_id) = self
14722 .buffer
14723 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14724 {
14725 self.selection_history
14726 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14727 cx.emit(EditorEvent::TransactionBegun {
14728 transaction_id: tx_id,
14729 })
14730 }
14731 }
14732
14733 pub fn end_transaction_at(
14734 &mut self,
14735 now: Instant,
14736 cx: &mut Context<Self>,
14737 ) -> Option<TransactionId> {
14738 if let Some(transaction_id) = self
14739 .buffer
14740 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14741 {
14742 if let Some((_, end_selections)) =
14743 self.selection_history.transaction_mut(transaction_id)
14744 {
14745 *end_selections = Some(self.selections.disjoint_anchors());
14746 } else {
14747 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14748 }
14749
14750 cx.emit(EditorEvent::Edited { transaction_id });
14751 Some(transaction_id)
14752 } else {
14753 None
14754 }
14755 }
14756
14757 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14758 if self.selection_mark_mode {
14759 self.change_selections(None, window, cx, |s| {
14760 s.move_with(|_, sel| {
14761 sel.collapse_to(sel.head(), SelectionGoal::None);
14762 });
14763 })
14764 }
14765 self.selection_mark_mode = true;
14766 cx.notify();
14767 }
14768
14769 pub fn swap_selection_ends(
14770 &mut self,
14771 _: &actions::SwapSelectionEnds,
14772 window: &mut Window,
14773 cx: &mut Context<Self>,
14774 ) {
14775 self.change_selections(None, window, cx, |s| {
14776 s.move_with(|_, sel| {
14777 if sel.start != sel.end {
14778 sel.reversed = !sel.reversed
14779 }
14780 });
14781 });
14782 self.request_autoscroll(Autoscroll::newest(), cx);
14783 cx.notify();
14784 }
14785
14786 pub fn toggle_fold(
14787 &mut self,
14788 _: &actions::ToggleFold,
14789 window: &mut Window,
14790 cx: &mut Context<Self>,
14791 ) {
14792 if self.is_singleton(cx) {
14793 let selection = self.selections.newest::<Point>(cx);
14794
14795 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14796 let range = if selection.is_empty() {
14797 let point = selection.head().to_display_point(&display_map);
14798 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14799 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14800 .to_point(&display_map);
14801 start..end
14802 } else {
14803 selection.range()
14804 };
14805 if display_map.folds_in_range(range).next().is_some() {
14806 self.unfold_lines(&Default::default(), window, cx)
14807 } else {
14808 self.fold(&Default::default(), window, cx)
14809 }
14810 } else {
14811 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14812 let buffer_ids: HashSet<_> = self
14813 .selections
14814 .disjoint_anchor_ranges()
14815 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14816 .collect();
14817
14818 let should_unfold = buffer_ids
14819 .iter()
14820 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14821
14822 for buffer_id in buffer_ids {
14823 if should_unfold {
14824 self.unfold_buffer(buffer_id, cx);
14825 } else {
14826 self.fold_buffer(buffer_id, cx);
14827 }
14828 }
14829 }
14830 }
14831
14832 pub fn toggle_fold_recursive(
14833 &mut self,
14834 _: &actions::ToggleFoldRecursive,
14835 window: &mut Window,
14836 cx: &mut Context<Self>,
14837 ) {
14838 let selection = self.selections.newest::<Point>(cx);
14839
14840 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14841 let range = if selection.is_empty() {
14842 let point = selection.head().to_display_point(&display_map);
14843 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14844 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14845 .to_point(&display_map);
14846 start..end
14847 } else {
14848 selection.range()
14849 };
14850 if display_map.folds_in_range(range).next().is_some() {
14851 self.unfold_recursive(&Default::default(), window, cx)
14852 } else {
14853 self.fold_recursive(&Default::default(), window, cx)
14854 }
14855 }
14856
14857 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14858 if self.is_singleton(cx) {
14859 let mut to_fold = Vec::new();
14860 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14861 let selections = self.selections.all_adjusted(cx);
14862
14863 for selection in selections {
14864 let range = selection.range().sorted();
14865 let buffer_start_row = range.start.row;
14866
14867 if range.start.row != range.end.row {
14868 let mut found = false;
14869 let mut row = range.start.row;
14870 while row <= range.end.row {
14871 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14872 {
14873 found = true;
14874 row = crease.range().end.row + 1;
14875 to_fold.push(crease);
14876 } else {
14877 row += 1
14878 }
14879 }
14880 if found {
14881 continue;
14882 }
14883 }
14884
14885 for row in (0..=range.start.row).rev() {
14886 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14887 if crease.range().end.row >= buffer_start_row {
14888 to_fold.push(crease);
14889 if row <= range.start.row {
14890 break;
14891 }
14892 }
14893 }
14894 }
14895 }
14896
14897 self.fold_creases(to_fold, true, window, cx);
14898 } else {
14899 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14900 let buffer_ids = self
14901 .selections
14902 .disjoint_anchor_ranges()
14903 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14904 .collect::<HashSet<_>>();
14905 for buffer_id in buffer_ids {
14906 self.fold_buffer(buffer_id, cx);
14907 }
14908 }
14909 }
14910
14911 fn fold_at_level(
14912 &mut self,
14913 fold_at: &FoldAtLevel,
14914 window: &mut Window,
14915 cx: &mut Context<Self>,
14916 ) {
14917 if !self.buffer.read(cx).is_singleton() {
14918 return;
14919 }
14920
14921 let fold_at_level = fold_at.0;
14922 let snapshot = self.buffer.read(cx).snapshot(cx);
14923 let mut to_fold = Vec::new();
14924 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14925
14926 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14927 while start_row < end_row {
14928 match self
14929 .snapshot(window, cx)
14930 .crease_for_buffer_row(MultiBufferRow(start_row))
14931 {
14932 Some(crease) => {
14933 let nested_start_row = crease.range().start.row + 1;
14934 let nested_end_row = crease.range().end.row;
14935
14936 if current_level < fold_at_level {
14937 stack.push((nested_start_row, nested_end_row, current_level + 1));
14938 } else if current_level == fold_at_level {
14939 to_fold.push(crease);
14940 }
14941
14942 start_row = nested_end_row + 1;
14943 }
14944 None => start_row += 1,
14945 }
14946 }
14947 }
14948
14949 self.fold_creases(to_fold, true, window, cx);
14950 }
14951
14952 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14953 if self.buffer.read(cx).is_singleton() {
14954 let mut fold_ranges = Vec::new();
14955 let snapshot = self.buffer.read(cx).snapshot(cx);
14956
14957 for row in 0..snapshot.max_row().0 {
14958 if let Some(foldable_range) = self
14959 .snapshot(window, cx)
14960 .crease_for_buffer_row(MultiBufferRow(row))
14961 {
14962 fold_ranges.push(foldable_range);
14963 }
14964 }
14965
14966 self.fold_creases(fold_ranges, true, window, cx);
14967 } else {
14968 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14969 editor
14970 .update_in(cx, |editor, _, cx| {
14971 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14972 editor.fold_buffer(buffer_id, cx);
14973 }
14974 })
14975 .ok();
14976 });
14977 }
14978 }
14979
14980 pub fn fold_function_bodies(
14981 &mut self,
14982 _: &actions::FoldFunctionBodies,
14983 window: &mut Window,
14984 cx: &mut Context<Self>,
14985 ) {
14986 let snapshot = self.buffer.read(cx).snapshot(cx);
14987
14988 let ranges = snapshot
14989 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14990 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14991 .collect::<Vec<_>>();
14992
14993 let creases = ranges
14994 .into_iter()
14995 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14996 .collect();
14997
14998 self.fold_creases(creases, true, window, cx);
14999 }
15000
15001 pub fn fold_recursive(
15002 &mut self,
15003 _: &actions::FoldRecursive,
15004 window: &mut Window,
15005 cx: &mut Context<Self>,
15006 ) {
15007 let mut to_fold = Vec::new();
15008 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15009 let selections = self.selections.all_adjusted(cx);
15010
15011 for selection in selections {
15012 let range = selection.range().sorted();
15013 let buffer_start_row = range.start.row;
15014
15015 if range.start.row != range.end.row {
15016 let mut found = false;
15017 for row in range.start.row..=range.end.row {
15018 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15019 found = true;
15020 to_fold.push(crease);
15021 }
15022 }
15023 if found {
15024 continue;
15025 }
15026 }
15027
15028 for row in (0..=range.start.row).rev() {
15029 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15030 if crease.range().end.row >= buffer_start_row {
15031 to_fold.push(crease);
15032 } else {
15033 break;
15034 }
15035 }
15036 }
15037 }
15038
15039 self.fold_creases(to_fold, true, window, cx);
15040 }
15041
15042 pub fn fold_at(
15043 &mut self,
15044 buffer_row: MultiBufferRow,
15045 window: &mut Window,
15046 cx: &mut Context<Self>,
15047 ) {
15048 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15049
15050 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15051 let autoscroll = self
15052 .selections
15053 .all::<Point>(cx)
15054 .iter()
15055 .any(|selection| crease.range().overlaps(&selection.range()));
15056
15057 self.fold_creases(vec![crease], autoscroll, window, cx);
15058 }
15059 }
15060
15061 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15062 if self.is_singleton(cx) {
15063 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15064 let buffer = &display_map.buffer_snapshot;
15065 let selections = self.selections.all::<Point>(cx);
15066 let ranges = selections
15067 .iter()
15068 .map(|s| {
15069 let range = s.display_range(&display_map).sorted();
15070 let mut start = range.start.to_point(&display_map);
15071 let mut end = range.end.to_point(&display_map);
15072 start.column = 0;
15073 end.column = buffer.line_len(MultiBufferRow(end.row));
15074 start..end
15075 })
15076 .collect::<Vec<_>>();
15077
15078 self.unfold_ranges(&ranges, true, true, cx);
15079 } else {
15080 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15081 let buffer_ids = self
15082 .selections
15083 .disjoint_anchor_ranges()
15084 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15085 .collect::<HashSet<_>>();
15086 for buffer_id in buffer_ids {
15087 self.unfold_buffer(buffer_id, cx);
15088 }
15089 }
15090 }
15091
15092 pub fn unfold_recursive(
15093 &mut self,
15094 _: &UnfoldRecursive,
15095 _window: &mut Window,
15096 cx: &mut Context<Self>,
15097 ) {
15098 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15099 let selections = self.selections.all::<Point>(cx);
15100 let ranges = selections
15101 .iter()
15102 .map(|s| {
15103 let mut range = s.display_range(&display_map).sorted();
15104 *range.start.column_mut() = 0;
15105 *range.end.column_mut() = display_map.line_len(range.end.row());
15106 let start = range.start.to_point(&display_map);
15107 let end = range.end.to_point(&display_map);
15108 start..end
15109 })
15110 .collect::<Vec<_>>();
15111
15112 self.unfold_ranges(&ranges, true, true, cx);
15113 }
15114
15115 pub fn unfold_at(
15116 &mut self,
15117 buffer_row: MultiBufferRow,
15118 _window: &mut Window,
15119 cx: &mut Context<Self>,
15120 ) {
15121 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15122
15123 let intersection_range = Point::new(buffer_row.0, 0)
15124 ..Point::new(
15125 buffer_row.0,
15126 display_map.buffer_snapshot.line_len(buffer_row),
15127 );
15128
15129 let autoscroll = self
15130 .selections
15131 .all::<Point>(cx)
15132 .iter()
15133 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15134
15135 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15136 }
15137
15138 pub fn unfold_all(
15139 &mut self,
15140 _: &actions::UnfoldAll,
15141 _window: &mut Window,
15142 cx: &mut Context<Self>,
15143 ) {
15144 if self.buffer.read(cx).is_singleton() {
15145 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15146 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15147 } else {
15148 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15149 editor
15150 .update(cx, |editor, cx| {
15151 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15152 editor.unfold_buffer(buffer_id, cx);
15153 }
15154 })
15155 .ok();
15156 });
15157 }
15158 }
15159
15160 pub fn fold_selected_ranges(
15161 &mut self,
15162 _: &FoldSelectedRanges,
15163 window: &mut Window,
15164 cx: &mut Context<Self>,
15165 ) {
15166 let selections = self.selections.all_adjusted(cx);
15167 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15168 let ranges = selections
15169 .into_iter()
15170 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15171 .collect::<Vec<_>>();
15172 self.fold_creases(ranges, true, window, cx);
15173 }
15174
15175 pub fn fold_ranges<T: ToOffset + Clone>(
15176 &mut self,
15177 ranges: Vec<Range<T>>,
15178 auto_scroll: bool,
15179 window: &mut Window,
15180 cx: &mut Context<Self>,
15181 ) {
15182 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15183 let ranges = ranges
15184 .into_iter()
15185 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15186 .collect::<Vec<_>>();
15187 self.fold_creases(ranges, auto_scroll, window, cx);
15188 }
15189
15190 pub fn fold_creases<T: ToOffset + Clone>(
15191 &mut self,
15192 creases: Vec<Crease<T>>,
15193 auto_scroll: bool,
15194 window: &mut Window,
15195 cx: &mut Context<Self>,
15196 ) {
15197 if creases.is_empty() {
15198 return;
15199 }
15200
15201 let mut buffers_affected = HashSet::default();
15202 let multi_buffer = self.buffer().read(cx);
15203 for crease in &creases {
15204 if let Some((_, buffer, _)) =
15205 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15206 {
15207 buffers_affected.insert(buffer.read(cx).remote_id());
15208 };
15209 }
15210
15211 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15212
15213 if auto_scroll {
15214 self.request_autoscroll(Autoscroll::fit(), cx);
15215 }
15216
15217 cx.notify();
15218
15219 if let Some(active_diagnostics) = self.active_diagnostics.take() {
15220 // Clear diagnostics block when folding a range that contains it.
15221 let snapshot = self.snapshot(window, cx);
15222 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
15223 drop(snapshot);
15224 self.active_diagnostics = Some(active_diagnostics);
15225 self.dismiss_diagnostics(cx);
15226 } else {
15227 self.active_diagnostics = Some(active_diagnostics);
15228 }
15229 }
15230
15231 self.scrollbar_marker_state.dirty = true;
15232 self.folds_did_change(cx);
15233 }
15234
15235 /// Removes any folds whose ranges intersect any of the given ranges.
15236 pub fn unfold_ranges<T: ToOffset + Clone>(
15237 &mut self,
15238 ranges: &[Range<T>],
15239 inclusive: bool,
15240 auto_scroll: bool,
15241 cx: &mut Context<Self>,
15242 ) {
15243 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15244 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15245 });
15246 self.folds_did_change(cx);
15247 }
15248
15249 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15250 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15251 return;
15252 }
15253 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15254 self.display_map.update(cx, |display_map, cx| {
15255 display_map.fold_buffers([buffer_id], cx)
15256 });
15257 cx.emit(EditorEvent::BufferFoldToggled {
15258 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15259 folded: true,
15260 });
15261 cx.notify();
15262 }
15263
15264 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15265 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15266 return;
15267 }
15268 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15269 self.display_map.update(cx, |display_map, cx| {
15270 display_map.unfold_buffers([buffer_id], cx);
15271 });
15272 cx.emit(EditorEvent::BufferFoldToggled {
15273 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15274 folded: false,
15275 });
15276 cx.notify();
15277 }
15278
15279 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15280 self.display_map.read(cx).is_buffer_folded(buffer)
15281 }
15282
15283 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15284 self.display_map.read(cx).folded_buffers()
15285 }
15286
15287 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15288 self.display_map.update(cx, |display_map, cx| {
15289 display_map.disable_header_for_buffer(buffer_id, cx);
15290 });
15291 cx.notify();
15292 }
15293
15294 /// Removes any folds with the given ranges.
15295 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15296 &mut self,
15297 ranges: &[Range<T>],
15298 type_id: TypeId,
15299 auto_scroll: bool,
15300 cx: &mut Context<Self>,
15301 ) {
15302 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15303 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15304 });
15305 self.folds_did_change(cx);
15306 }
15307
15308 fn remove_folds_with<T: ToOffset + Clone>(
15309 &mut self,
15310 ranges: &[Range<T>],
15311 auto_scroll: bool,
15312 cx: &mut Context<Self>,
15313 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15314 ) {
15315 if ranges.is_empty() {
15316 return;
15317 }
15318
15319 let mut buffers_affected = HashSet::default();
15320 let multi_buffer = self.buffer().read(cx);
15321 for range in ranges {
15322 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15323 buffers_affected.insert(buffer.read(cx).remote_id());
15324 };
15325 }
15326
15327 self.display_map.update(cx, update);
15328
15329 if auto_scroll {
15330 self.request_autoscroll(Autoscroll::fit(), cx);
15331 }
15332
15333 cx.notify();
15334 self.scrollbar_marker_state.dirty = true;
15335 self.active_indent_guides_state.dirty = true;
15336 }
15337
15338 pub fn update_fold_widths(
15339 &mut self,
15340 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15341 cx: &mut Context<Self>,
15342 ) -> bool {
15343 self.display_map
15344 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15345 }
15346
15347 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15348 self.display_map.read(cx).fold_placeholder.clone()
15349 }
15350
15351 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15352 self.buffer.update(cx, |buffer, cx| {
15353 buffer.set_all_diff_hunks_expanded(cx);
15354 });
15355 }
15356
15357 pub fn expand_all_diff_hunks(
15358 &mut self,
15359 _: &ExpandAllDiffHunks,
15360 _window: &mut Window,
15361 cx: &mut Context<Self>,
15362 ) {
15363 self.buffer.update(cx, |buffer, cx| {
15364 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15365 });
15366 }
15367
15368 pub fn toggle_selected_diff_hunks(
15369 &mut self,
15370 _: &ToggleSelectedDiffHunks,
15371 _window: &mut Window,
15372 cx: &mut Context<Self>,
15373 ) {
15374 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15375 self.toggle_diff_hunks_in_ranges(ranges, cx);
15376 }
15377
15378 pub fn diff_hunks_in_ranges<'a>(
15379 &'a self,
15380 ranges: &'a [Range<Anchor>],
15381 buffer: &'a MultiBufferSnapshot,
15382 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15383 ranges.iter().flat_map(move |range| {
15384 let end_excerpt_id = range.end.excerpt_id;
15385 let range = range.to_point(buffer);
15386 let mut peek_end = range.end;
15387 if range.end.row < buffer.max_row().0 {
15388 peek_end = Point::new(range.end.row + 1, 0);
15389 }
15390 buffer
15391 .diff_hunks_in_range(range.start..peek_end)
15392 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15393 })
15394 }
15395
15396 pub fn has_stageable_diff_hunks_in_ranges(
15397 &self,
15398 ranges: &[Range<Anchor>],
15399 snapshot: &MultiBufferSnapshot,
15400 ) -> bool {
15401 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15402 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15403 }
15404
15405 pub fn toggle_staged_selected_diff_hunks(
15406 &mut self,
15407 _: &::git::ToggleStaged,
15408 _: &mut Window,
15409 cx: &mut Context<Self>,
15410 ) {
15411 let snapshot = self.buffer.read(cx).snapshot(cx);
15412 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15413 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15414 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15415 }
15416
15417 pub fn set_render_diff_hunk_controls(
15418 &mut self,
15419 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15420 cx: &mut Context<Self>,
15421 ) {
15422 self.render_diff_hunk_controls = render_diff_hunk_controls;
15423 cx.notify();
15424 }
15425
15426 pub fn stage_and_next(
15427 &mut self,
15428 _: &::git::StageAndNext,
15429 window: &mut Window,
15430 cx: &mut Context<Self>,
15431 ) {
15432 self.do_stage_or_unstage_and_next(true, window, cx);
15433 }
15434
15435 pub fn unstage_and_next(
15436 &mut self,
15437 _: &::git::UnstageAndNext,
15438 window: &mut Window,
15439 cx: &mut Context<Self>,
15440 ) {
15441 self.do_stage_or_unstage_and_next(false, window, cx);
15442 }
15443
15444 pub fn stage_or_unstage_diff_hunks(
15445 &mut self,
15446 stage: bool,
15447 ranges: Vec<Range<Anchor>>,
15448 cx: &mut Context<Self>,
15449 ) {
15450 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15451 cx.spawn(async move |this, cx| {
15452 task.await?;
15453 this.update(cx, |this, cx| {
15454 let snapshot = this.buffer.read(cx).snapshot(cx);
15455 let chunk_by = this
15456 .diff_hunks_in_ranges(&ranges, &snapshot)
15457 .chunk_by(|hunk| hunk.buffer_id);
15458 for (buffer_id, hunks) in &chunk_by {
15459 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15460 }
15461 })
15462 })
15463 .detach_and_log_err(cx);
15464 }
15465
15466 fn save_buffers_for_ranges_if_needed(
15467 &mut self,
15468 ranges: &[Range<Anchor>],
15469 cx: &mut Context<Editor>,
15470 ) -> Task<Result<()>> {
15471 let multibuffer = self.buffer.read(cx);
15472 let snapshot = multibuffer.read(cx);
15473 let buffer_ids: HashSet<_> = ranges
15474 .iter()
15475 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15476 .collect();
15477 drop(snapshot);
15478
15479 let mut buffers = HashSet::default();
15480 for buffer_id in buffer_ids {
15481 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15482 let buffer = buffer_entity.read(cx);
15483 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15484 {
15485 buffers.insert(buffer_entity);
15486 }
15487 }
15488 }
15489
15490 if let Some(project) = &self.project {
15491 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15492 } else {
15493 Task::ready(Ok(()))
15494 }
15495 }
15496
15497 fn do_stage_or_unstage_and_next(
15498 &mut self,
15499 stage: bool,
15500 window: &mut Window,
15501 cx: &mut Context<Self>,
15502 ) {
15503 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15504
15505 if ranges.iter().any(|range| range.start != range.end) {
15506 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15507 return;
15508 }
15509
15510 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15511 let snapshot = self.snapshot(window, cx);
15512 let position = self.selections.newest::<Point>(cx).head();
15513 let mut row = snapshot
15514 .buffer_snapshot
15515 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15516 .find(|hunk| hunk.row_range.start.0 > position.row)
15517 .map(|hunk| hunk.row_range.start);
15518
15519 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15520 // Outside of the project diff editor, wrap around to the beginning.
15521 if !all_diff_hunks_expanded {
15522 row = row.or_else(|| {
15523 snapshot
15524 .buffer_snapshot
15525 .diff_hunks_in_range(Point::zero()..position)
15526 .find(|hunk| hunk.row_range.end.0 < position.row)
15527 .map(|hunk| hunk.row_range.start)
15528 });
15529 }
15530
15531 if let Some(row) = row {
15532 let destination = Point::new(row.0, 0);
15533 let autoscroll = Autoscroll::center();
15534
15535 self.unfold_ranges(&[destination..destination], false, false, cx);
15536 self.change_selections(Some(autoscroll), window, cx, |s| {
15537 s.select_ranges([destination..destination]);
15538 });
15539 }
15540 }
15541
15542 fn do_stage_or_unstage(
15543 &self,
15544 stage: bool,
15545 buffer_id: BufferId,
15546 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15547 cx: &mut App,
15548 ) -> Option<()> {
15549 let project = self.project.as_ref()?;
15550 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15551 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15552 let buffer_snapshot = buffer.read(cx).snapshot();
15553 let file_exists = buffer_snapshot
15554 .file()
15555 .is_some_and(|file| file.disk_state().exists());
15556 diff.update(cx, |diff, cx| {
15557 diff.stage_or_unstage_hunks(
15558 stage,
15559 &hunks
15560 .map(|hunk| buffer_diff::DiffHunk {
15561 buffer_range: hunk.buffer_range,
15562 diff_base_byte_range: hunk.diff_base_byte_range,
15563 secondary_status: hunk.secondary_status,
15564 range: Point::zero()..Point::zero(), // unused
15565 })
15566 .collect::<Vec<_>>(),
15567 &buffer_snapshot,
15568 file_exists,
15569 cx,
15570 )
15571 });
15572 None
15573 }
15574
15575 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15576 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15577 self.buffer
15578 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15579 }
15580
15581 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15582 self.buffer.update(cx, |buffer, cx| {
15583 let ranges = vec![Anchor::min()..Anchor::max()];
15584 if !buffer.all_diff_hunks_expanded()
15585 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15586 {
15587 buffer.collapse_diff_hunks(ranges, cx);
15588 true
15589 } else {
15590 false
15591 }
15592 })
15593 }
15594
15595 fn toggle_diff_hunks_in_ranges(
15596 &mut self,
15597 ranges: Vec<Range<Anchor>>,
15598 cx: &mut Context<Editor>,
15599 ) {
15600 self.buffer.update(cx, |buffer, cx| {
15601 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15602 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15603 })
15604 }
15605
15606 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15607 self.buffer.update(cx, |buffer, cx| {
15608 let snapshot = buffer.snapshot(cx);
15609 let excerpt_id = range.end.excerpt_id;
15610 let point_range = range.to_point(&snapshot);
15611 let expand = !buffer.single_hunk_is_expanded(range, cx);
15612 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15613 })
15614 }
15615
15616 pub(crate) fn apply_all_diff_hunks(
15617 &mut self,
15618 _: &ApplyAllDiffHunks,
15619 window: &mut Window,
15620 cx: &mut Context<Self>,
15621 ) {
15622 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15623
15624 let buffers = self.buffer.read(cx).all_buffers();
15625 for branch_buffer in buffers {
15626 branch_buffer.update(cx, |branch_buffer, cx| {
15627 branch_buffer.merge_into_base(Vec::new(), cx);
15628 });
15629 }
15630
15631 if let Some(project) = self.project.clone() {
15632 self.save(true, project, window, cx).detach_and_log_err(cx);
15633 }
15634 }
15635
15636 pub(crate) fn apply_selected_diff_hunks(
15637 &mut self,
15638 _: &ApplyDiffHunk,
15639 window: &mut Window,
15640 cx: &mut Context<Self>,
15641 ) {
15642 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15643 let snapshot = self.snapshot(window, cx);
15644 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15645 let mut ranges_by_buffer = HashMap::default();
15646 self.transact(window, cx, |editor, _window, cx| {
15647 for hunk in hunks {
15648 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15649 ranges_by_buffer
15650 .entry(buffer.clone())
15651 .or_insert_with(Vec::new)
15652 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15653 }
15654 }
15655
15656 for (buffer, ranges) in ranges_by_buffer {
15657 buffer.update(cx, |buffer, cx| {
15658 buffer.merge_into_base(ranges, cx);
15659 });
15660 }
15661 });
15662
15663 if let Some(project) = self.project.clone() {
15664 self.save(true, project, window, cx).detach_and_log_err(cx);
15665 }
15666 }
15667
15668 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15669 if hovered != self.gutter_hovered {
15670 self.gutter_hovered = hovered;
15671 cx.notify();
15672 }
15673 }
15674
15675 pub fn insert_blocks(
15676 &mut self,
15677 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15678 autoscroll: Option<Autoscroll>,
15679 cx: &mut Context<Self>,
15680 ) -> Vec<CustomBlockId> {
15681 let blocks = self
15682 .display_map
15683 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15684 if let Some(autoscroll) = autoscroll {
15685 self.request_autoscroll(autoscroll, cx);
15686 }
15687 cx.notify();
15688 blocks
15689 }
15690
15691 pub fn resize_blocks(
15692 &mut self,
15693 heights: HashMap<CustomBlockId, u32>,
15694 autoscroll: Option<Autoscroll>,
15695 cx: &mut Context<Self>,
15696 ) {
15697 self.display_map
15698 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15699 if let Some(autoscroll) = autoscroll {
15700 self.request_autoscroll(autoscroll, cx);
15701 }
15702 cx.notify();
15703 }
15704
15705 pub fn replace_blocks(
15706 &mut self,
15707 renderers: HashMap<CustomBlockId, RenderBlock>,
15708 autoscroll: Option<Autoscroll>,
15709 cx: &mut Context<Self>,
15710 ) {
15711 self.display_map
15712 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15713 if let Some(autoscroll) = autoscroll {
15714 self.request_autoscroll(autoscroll, cx);
15715 }
15716 cx.notify();
15717 }
15718
15719 pub fn remove_blocks(
15720 &mut self,
15721 block_ids: HashSet<CustomBlockId>,
15722 autoscroll: Option<Autoscroll>,
15723 cx: &mut Context<Self>,
15724 ) {
15725 self.display_map.update(cx, |display_map, cx| {
15726 display_map.remove_blocks(block_ids, cx)
15727 });
15728 if let Some(autoscroll) = autoscroll {
15729 self.request_autoscroll(autoscroll, cx);
15730 }
15731 cx.notify();
15732 }
15733
15734 pub fn row_for_block(
15735 &self,
15736 block_id: CustomBlockId,
15737 cx: &mut Context<Self>,
15738 ) -> Option<DisplayRow> {
15739 self.display_map
15740 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15741 }
15742
15743 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15744 self.focused_block = Some(focused_block);
15745 }
15746
15747 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15748 self.focused_block.take()
15749 }
15750
15751 pub fn insert_creases(
15752 &mut self,
15753 creases: impl IntoIterator<Item = Crease<Anchor>>,
15754 cx: &mut Context<Self>,
15755 ) -> Vec<CreaseId> {
15756 self.display_map
15757 .update(cx, |map, cx| map.insert_creases(creases, cx))
15758 }
15759
15760 pub fn remove_creases(
15761 &mut self,
15762 ids: impl IntoIterator<Item = CreaseId>,
15763 cx: &mut Context<Self>,
15764 ) {
15765 self.display_map
15766 .update(cx, |map, cx| map.remove_creases(ids, cx));
15767 }
15768
15769 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15770 self.display_map
15771 .update(cx, |map, cx| map.snapshot(cx))
15772 .longest_row()
15773 }
15774
15775 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15776 self.display_map
15777 .update(cx, |map, cx| map.snapshot(cx))
15778 .max_point()
15779 }
15780
15781 pub fn text(&self, cx: &App) -> String {
15782 self.buffer.read(cx).read(cx).text()
15783 }
15784
15785 pub fn is_empty(&self, cx: &App) -> bool {
15786 self.buffer.read(cx).read(cx).is_empty()
15787 }
15788
15789 pub fn text_option(&self, cx: &App) -> Option<String> {
15790 let text = self.text(cx);
15791 let text = text.trim();
15792
15793 if text.is_empty() {
15794 return None;
15795 }
15796
15797 Some(text.to_string())
15798 }
15799
15800 pub fn set_text(
15801 &mut self,
15802 text: impl Into<Arc<str>>,
15803 window: &mut Window,
15804 cx: &mut Context<Self>,
15805 ) {
15806 self.transact(window, cx, |this, _, cx| {
15807 this.buffer
15808 .read(cx)
15809 .as_singleton()
15810 .expect("you can only call set_text on editors for singleton buffers")
15811 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15812 });
15813 }
15814
15815 pub fn display_text(&self, cx: &mut App) -> String {
15816 self.display_map
15817 .update(cx, |map, cx| map.snapshot(cx))
15818 .text()
15819 }
15820
15821 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15822 let mut wrap_guides = smallvec::smallvec![];
15823
15824 if self.show_wrap_guides == Some(false) {
15825 return wrap_guides;
15826 }
15827
15828 let settings = self.buffer.read(cx).language_settings(cx);
15829 if settings.show_wrap_guides {
15830 match self.soft_wrap_mode(cx) {
15831 SoftWrap::Column(soft_wrap) => {
15832 wrap_guides.push((soft_wrap as usize, true));
15833 }
15834 SoftWrap::Bounded(soft_wrap) => {
15835 wrap_guides.push((soft_wrap as usize, true));
15836 }
15837 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15838 }
15839 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15840 }
15841
15842 wrap_guides
15843 }
15844
15845 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15846 let settings = self.buffer.read(cx).language_settings(cx);
15847 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15848 match mode {
15849 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15850 SoftWrap::None
15851 }
15852 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15853 language_settings::SoftWrap::PreferredLineLength => {
15854 SoftWrap::Column(settings.preferred_line_length)
15855 }
15856 language_settings::SoftWrap::Bounded => {
15857 SoftWrap::Bounded(settings.preferred_line_length)
15858 }
15859 }
15860 }
15861
15862 pub fn set_soft_wrap_mode(
15863 &mut self,
15864 mode: language_settings::SoftWrap,
15865
15866 cx: &mut Context<Self>,
15867 ) {
15868 self.soft_wrap_mode_override = Some(mode);
15869 cx.notify();
15870 }
15871
15872 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15873 self.hard_wrap = hard_wrap;
15874 cx.notify();
15875 }
15876
15877 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15878 self.text_style_refinement = Some(style);
15879 }
15880
15881 /// called by the Element so we know what style we were most recently rendered with.
15882 pub(crate) fn set_style(
15883 &mut self,
15884 style: EditorStyle,
15885 window: &mut Window,
15886 cx: &mut Context<Self>,
15887 ) {
15888 let rem_size = window.rem_size();
15889 self.display_map.update(cx, |map, cx| {
15890 map.set_font(
15891 style.text.font(),
15892 style.text.font_size.to_pixels(rem_size),
15893 cx,
15894 )
15895 });
15896 self.style = Some(style);
15897 }
15898
15899 pub fn style(&self) -> Option<&EditorStyle> {
15900 self.style.as_ref()
15901 }
15902
15903 // Called by the element. This method is not designed to be called outside of the editor
15904 // element's layout code because it does not notify when rewrapping is computed synchronously.
15905 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15906 self.display_map
15907 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15908 }
15909
15910 pub fn set_soft_wrap(&mut self) {
15911 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15912 }
15913
15914 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15915 if self.soft_wrap_mode_override.is_some() {
15916 self.soft_wrap_mode_override.take();
15917 } else {
15918 let soft_wrap = match self.soft_wrap_mode(cx) {
15919 SoftWrap::GitDiff => return,
15920 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15921 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15922 language_settings::SoftWrap::None
15923 }
15924 };
15925 self.soft_wrap_mode_override = Some(soft_wrap);
15926 }
15927 cx.notify();
15928 }
15929
15930 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15931 let Some(workspace) = self.workspace() else {
15932 return;
15933 };
15934 let fs = workspace.read(cx).app_state().fs.clone();
15935 let current_show = TabBarSettings::get_global(cx).show;
15936 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15937 setting.show = Some(!current_show);
15938 });
15939 }
15940
15941 pub fn toggle_indent_guides(
15942 &mut self,
15943 _: &ToggleIndentGuides,
15944 _: &mut Window,
15945 cx: &mut Context<Self>,
15946 ) {
15947 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15948 self.buffer
15949 .read(cx)
15950 .language_settings(cx)
15951 .indent_guides
15952 .enabled
15953 });
15954 self.show_indent_guides = Some(!currently_enabled);
15955 cx.notify();
15956 }
15957
15958 fn should_show_indent_guides(&self) -> Option<bool> {
15959 self.show_indent_guides
15960 }
15961
15962 pub fn toggle_line_numbers(
15963 &mut self,
15964 _: &ToggleLineNumbers,
15965 _: &mut Window,
15966 cx: &mut Context<Self>,
15967 ) {
15968 let mut editor_settings = EditorSettings::get_global(cx).clone();
15969 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15970 EditorSettings::override_global(editor_settings, cx);
15971 }
15972
15973 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15974 if let Some(show_line_numbers) = self.show_line_numbers {
15975 return show_line_numbers;
15976 }
15977 EditorSettings::get_global(cx).gutter.line_numbers
15978 }
15979
15980 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15981 self.use_relative_line_numbers
15982 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15983 }
15984
15985 pub fn toggle_relative_line_numbers(
15986 &mut self,
15987 _: &ToggleRelativeLineNumbers,
15988 _: &mut Window,
15989 cx: &mut Context<Self>,
15990 ) {
15991 let is_relative = self.should_use_relative_line_numbers(cx);
15992 self.set_relative_line_number(Some(!is_relative), cx)
15993 }
15994
15995 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15996 self.use_relative_line_numbers = is_relative;
15997 cx.notify();
15998 }
15999
16000 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16001 self.show_gutter = show_gutter;
16002 cx.notify();
16003 }
16004
16005 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16006 self.show_scrollbars = show_scrollbars;
16007 cx.notify();
16008 }
16009
16010 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16011 self.show_line_numbers = Some(show_line_numbers);
16012 cx.notify();
16013 }
16014
16015 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16016 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16017 cx.notify();
16018 }
16019
16020 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16021 self.show_code_actions = Some(show_code_actions);
16022 cx.notify();
16023 }
16024
16025 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16026 self.show_runnables = Some(show_runnables);
16027 cx.notify();
16028 }
16029
16030 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16031 self.show_breakpoints = Some(show_breakpoints);
16032 cx.notify();
16033 }
16034
16035 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16036 if self.display_map.read(cx).masked != masked {
16037 self.display_map.update(cx, |map, _| map.masked = masked);
16038 }
16039 cx.notify()
16040 }
16041
16042 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16043 self.show_wrap_guides = Some(show_wrap_guides);
16044 cx.notify();
16045 }
16046
16047 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16048 self.show_indent_guides = Some(show_indent_guides);
16049 cx.notify();
16050 }
16051
16052 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16053 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16054 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16055 if let Some(dir) = file.abs_path(cx).parent() {
16056 return Some(dir.to_owned());
16057 }
16058 }
16059
16060 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16061 return Some(project_path.path.to_path_buf());
16062 }
16063 }
16064
16065 None
16066 }
16067
16068 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16069 self.active_excerpt(cx)?
16070 .1
16071 .read(cx)
16072 .file()
16073 .and_then(|f| f.as_local())
16074 }
16075
16076 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16077 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16078 let buffer = buffer.read(cx);
16079 if let Some(project_path) = buffer.project_path(cx) {
16080 let project = self.project.as_ref()?.read(cx);
16081 project.absolute_path(&project_path, cx)
16082 } else {
16083 buffer
16084 .file()
16085 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16086 }
16087 })
16088 }
16089
16090 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16091 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16092 let project_path = buffer.read(cx).project_path(cx)?;
16093 let project = self.project.as_ref()?.read(cx);
16094 let entry = project.entry_for_path(&project_path, cx)?;
16095 let path = entry.path.to_path_buf();
16096 Some(path)
16097 })
16098 }
16099
16100 pub fn reveal_in_finder(
16101 &mut self,
16102 _: &RevealInFileManager,
16103 _window: &mut Window,
16104 cx: &mut Context<Self>,
16105 ) {
16106 if let Some(target) = self.target_file(cx) {
16107 cx.reveal_path(&target.abs_path(cx));
16108 }
16109 }
16110
16111 pub fn copy_path(
16112 &mut self,
16113 _: &zed_actions::workspace::CopyPath,
16114 _window: &mut Window,
16115 cx: &mut Context<Self>,
16116 ) {
16117 if let Some(path) = self.target_file_abs_path(cx) {
16118 if let Some(path) = path.to_str() {
16119 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16120 }
16121 }
16122 }
16123
16124 pub fn copy_relative_path(
16125 &mut self,
16126 _: &zed_actions::workspace::CopyRelativePath,
16127 _window: &mut Window,
16128 cx: &mut Context<Self>,
16129 ) {
16130 if let Some(path) = self.target_file_path(cx) {
16131 if let Some(path) = path.to_str() {
16132 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16133 }
16134 }
16135 }
16136
16137 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16138 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16139 buffer.read(cx).project_path(cx)
16140 } else {
16141 None
16142 }
16143 }
16144
16145 // Returns true if the editor handled a go-to-line request
16146 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16147 maybe!({
16148 let breakpoint_store = self.breakpoint_store.as_ref()?;
16149
16150 let Some((_, _, active_position)) =
16151 breakpoint_store.read(cx).active_position().cloned()
16152 else {
16153 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16154 return None;
16155 };
16156
16157 let snapshot = self
16158 .project
16159 .as_ref()?
16160 .read(cx)
16161 .buffer_for_id(active_position.buffer_id?, cx)?
16162 .read(cx)
16163 .snapshot();
16164
16165 let mut handled = false;
16166 for (id, ExcerptRange { context, .. }) in self
16167 .buffer
16168 .read(cx)
16169 .excerpts_for_buffer(active_position.buffer_id?, cx)
16170 {
16171 if context.start.cmp(&active_position, &snapshot).is_ge()
16172 || context.end.cmp(&active_position, &snapshot).is_lt()
16173 {
16174 continue;
16175 }
16176 let snapshot = self.buffer.read(cx).snapshot(cx);
16177 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16178
16179 handled = true;
16180 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16181 self.go_to_line::<DebugCurrentRowHighlight>(
16182 multibuffer_anchor,
16183 Some(cx.theme().colors().editor_debugger_active_line_background),
16184 window,
16185 cx,
16186 );
16187
16188 cx.notify();
16189 }
16190 handled.then_some(())
16191 })
16192 .is_some()
16193 }
16194
16195 pub fn copy_file_name_without_extension(
16196 &mut self,
16197 _: &CopyFileNameWithoutExtension,
16198 _: &mut Window,
16199 cx: &mut Context<Self>,
16200 ) {
16201 if let Some(file) = self.target_file(cx) {
16202 if let Some(file_stem) = file.path().file_stem() {
16203 if let Some(name) = file_stem.to_str() {
16204 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16205 }
16206 }
16207 }
16208 }
16209
16210 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16211 if let Some(file) = self.target_file(cx) {
16212 if let Some(file_name) = file.path().file_name() {
16213 if let Some(name) = file_name.to_str() {
16214 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16215 }
16216 }
16217 }
16218 }
16219
16220 pub fn toggle_git_blame(
16221 &mut self,
16222 _: &::git::Blame,
16223 window: &mut Window,
16224 cx: &mut Context<Self>,
16225 ) {
16226 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16227
16228 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16229 self.start_git_blame(true, window, cx);
16230 }
16231
16232 cx.notify();
16233 }
16234
16235 pub fn toggle_git_blame_inline(
16236 &mut self,
16237 _: &ToggleGitBlameInline,
16238 window: &mut Window,
16239 cx: &mut Context<Self>,
16240 ) {
16241 self.toggle_git_blame_inline_internal(true, window, cx);
16242 cx.notify();
16243 }
16244
16245 pub fn open_git_blame_commit(
16246 &mut self,
16247 _: &OpenGitBlameCommit,
16248 window: &mut Window,
16249 cx: &mut Context<Self>,
16250 ) {
16251 self.open_git_blame_commit_internal(window, cx);
16252 }
16253
16254 fn open_git_blame_commit_internal(
16255 &mut self,
16256 window: &mut Window,
16257 cx: &mut Context<Self>,
16258 ) -> Option<()> {
16259 let blame = self.blame.as_ref()?;
16260 let snapshot = self.snapshot(window, cx);
16261 let cursor = self.selections.newest::<Point>(cx).head();
16262 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16263 let blame_entry = blame
16264 .update(cx, |blame, cx| {
16265 blame
16266 .blame_for_rows(
16267 &[RowInfo {
16268 buffer_id: Some(buffer.remote_id()),
16269 buffer_row: Some(point.row),
16270 ..Default::default()
16271 }],
16272 cx,
16273 )
16274 .next()
16275 })
16276 .flatten()?;
16277 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16278 let repo = blame.read(cx).repository(cx)?;
16279 let workspace = self.workspace()?.downgrade();
16280 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16281 None
16282 }
16283
16284 pub fn git_blame_inline_enabled(&self) -> bool {
16285 self.git_blame_inline_enabled
16286 }
16287
16288 pub fn toggle_selection_menu(
16289 &mut self,
16290 _: &ToggleSelectionMenu,
16291 _: &mut Window,
16292 cx: &mut Context<Self>,
16293 ) {
16294 self.show_selection_menu = self
16295 .show_selection_menu
16296 .map(|show_selections_menu| !show_selections_menu)
16297 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16298
16299 cx.notify();
16300 }
16301
16302 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16303 self.show_selection_menu
16304 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16305 }
16306
16307 fn start_git_blame(
16308 &mut self,
16309 user_triggered: bool,
16310 window: &mut Window,
16311 cx: &mut Context<Self>,
16312 ) {
16313 if let Some(project) = self.project.as_ref() {
16314 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16315 return;
16316 };
16317
16318 if buffer.read(cx).file().is_none() {
16319 return;
16320 }
16321
16322 let focused = self.focus_handle(cx).contains_focused(window, cx);
16323
16324 let project = project.clone();
16325 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16326 self.blame_subscription =
16327 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16328 self.blame = Some(blame);
16329 }
16330 }
16331
16332 fn toggle_git_blame_inline_internal(
16333 &mut self,
16334 user_triggered: bool,
16335 window: &mut Window,
16336 cx: &mut Context<Self>,
16337 ) {
16338 if self.git_blame_inline_enabled {
16339 self.git_blame_inline_enabled = false;
16340 self.show_git_blame_inline = false;
16341 self.show_git_blame_inline_delay_task.take();
16342 } else {
16343 self.git_blame_inline_enabled = true;
16344 self.start_git_blame_inline(user_triggered, window, cx);
16345 }
16346
16347 cx.notify();
16348 }
16349
16350 fn start_git_blame_inline(
16351 &mut self,
16352 user_triggered: bool,
16353 window: &mut Window,
16354 cx: &mut Context<Self>,
16355 ) {
16356 self.start_git_blame(user_triggered, window, cx);
16357
16358 if ProjectSettings::get_global(cx)
16359 .git
16360 .inline_blame_delay()
16361 .is_some()
16362 {
16363 self.start_inline_blame_timer(window, cx);
16364 } else {
16365 self.show_git_blame_inline = true
16366 }
16367 }
16368
16369 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16370 self.blame.as_ref()
16371 }
16372
16373 pub fn show_git_blame_gutter(&self) -> bool {
16374 self.show_git_blame_gutter
16375 }
16376
16377 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16378 self.show_git_blame_gutter && self.has_blame_entries(cx)
16379 }
16380
16381 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16382 self.show_git_blame_inline
16383 && (self.focus_handle.is_focused(window)
16384 || self
16385 .git_blame_inline_tooltip
16386 .as_ref()
16387 .and_then(|t| t.upgrade())
16388 .is_some())
16389 && !self.newest_selection_head_on_empty_line(cx)
16390 && self.has_blame_entries(cx)
16391 }
16392
16393 fn has_blame_entries(&self, cx: &App) -> bool {
16394 self.blame()
16395 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16396 }
16397
16398 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16399 let cursor_anchor = self.selections.newest_anchor().head();
16400
16401 let snapshot = self.buffer.read(cx).snapshot(cx);
16402 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16403
16404 snapshot.line_len(buffer_row) == 0
16405 }
16406
16407 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16408 let buffer_and_selection = maybe!({
16409 let selection = self.selections.newest::<Point>(cx);
16410 let selection_range = selection.range();
16411
16412 let multi_buffer = self.buffer().read(cx);
16413 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16414 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16415
16416 let (buffer, range, _) = if selection.reversed {
16417 buffer_ranges.first()
16418 } else {
16419 buffer_ranges.last()
16420 }?;
16421
16422 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16423 ..text::ToPoint::to_point(&range.end, &buffer).row;
16424 Some((
16425 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16426 selection,
16427 ))
16428 });
16429
16430 let Some((buffer, selection)) = buffer_and_selection else {
16431 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16432 };
16433
16434 let Some(project) = self.project.as_ref() else {
16435 return Task::ready(Err(anyhow!("editor does not have project")));
16436 };
16437
16438 project.update(cx, |project, cx| {
16439 project.get_permalink_to_line(&buffer, selection, cx)
16440 })
16441 }
16442
16443 pub fn copy_permalink_to_line(
16444 &mut self,
16445 _: &CopyPermalinkToLine,
16446 window: &mut Window,
16447 cx: &mut Context<Self>,
16448 ) {
16449 let permalink_task = self.get_permalink_to_line(cx);
16450 let workspace = self.workspace();
16451
16452 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16453 Ok(permalink) => {
16454 cx.update(|_, cx| {
16455 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16456 })
16457 .ok();
16458 }
16459 Err(err) => {
16460 let message = format!("Failed to copy permalink: {err}");
16461
16462 Err::<(), anyhow::Error>(err).log_err();
16463
16464 if let Some(workspace) = workspace {
16465 workspace
16466 .update_in(cx, |workspace, _, cx| {
16467 struct CopyPermalinkToLine;
16468
16469 workspace.show_toast(
16470 Toast::new(
16471 NotificationId::unique::<CopyPermalinkToLine>(),
16472 message,
16473 ),
16474 cx,
16475 )
16476 })
16477 .ok();
16478 }
16479 }
16480 })
16481 .detach();
16482 }
16483
16484 pub fn copy_file_location(
16485 &mut self,
16486 _: &CopyFileLocation,
16487 _: &mut Window,
16488 cx: &mut Context<Self>,
16489 ) {
16490 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16491 if let Some(file) = self.target_file(cx) {
16492 if let Some(path) = file.path().to_str() {
16493 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16494 }
16495 }
16496 }
16497
16498 pub fn open_permalink_to_line(
16499 &mut self,
16500 _: &OpenPermalinkToLine,
16501 window: &mut Window,
16502 cx: &mut Context<Self>,
16503 ) {
16504 let permalink_task = self.get_permalink_to_line(cx);
16505 let workspace = self.workspace();
16506
16507 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16508 Ok(permalink) => {
16509 cx.update(|_, cx| {
16510 cx.open_url(permalink.as_ref());
16511 })
16512 .ok();
16513 }
16514 Err(err) => {
16515 let message = format!("Failed to open permalink: {err}");
16516
16517 Err::<(), anyhow::Error>(err).log_err();
16518
16519 if let Some(workspace) = workspace {
16520 workspace
16521 .update(cx, |workspace, cx| {
16522 struct OpenPermalinkToLine;
16523
16524 workspace.show_toast(
16525 Toast::new(
16526 NotificationId::unique::<OpenPermalinkToLine>(),
16527 message,
16528 ),
16529 cx,
16530 )
16531 })
16532 .ok();
16533 }
16534 }
16535 })
16536 .detach();
16537 }
16538
16539 pub fn insert_uuid_v4(
16540 &mut self,
16541 _: &InsertUuidV4,
16542 window: &mut Window,
16543 cx: &mut Context<Self>,
16544 ) {
16545 self.insert_uuid(UuidVersion::V4, window, cx);
16546 }
16547
16548 pub fn insert_uuid_v7(
16549 &mut self,
16550 _: &InsertUuidV7,
16551 window: &mut Window,
16552 cx: &mut Context<Self>,
16553 ) {
16554 self.insert_uuid(UuidVersion::V7, window, cx);
16555 }
16556
16557 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16558 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16559 self.transact(window, cx, |this, window, cx| {
16560 let edits = this
16561 .selections
16562 .all::<Point>(cx)
16563 .into_iter()
16564 .map(|selection| {
16565 let uuid = match version {
16566 UuidVersion::V4 => uuid::Uuid::new_v4(),
16567 UuidVersion::V7 => uuid::Uuid::now_v7(),
16568 };
16569
16570 (selection.range(), uuid.to_string())
16571 });
16572 this.edit(edits, cx);
16573 this.refresh_inline_completion(true, false, window, cx);
16574 });
16575 }
16576
16577 pub fn open_selections_in_multibuffer(
16578 &mut self,
16579 _: &OpenSelectionsInMultibuffer,
16580 window: &mut Window,
16581 cx: &mut Context<Self>,
16582 ) {
16583 let multibuffer = self.buffer.read(cx);
16584
16585 let Some(buffer) = multibuffer.as_singleton() else {
16586 return;
16587 };
16588
16589 let Some(workspace) = self.workspace() else {
16590 return;
16591 };
16592
16593 let locations = self
16594 .selections
16595 .disjoint_anchors()
16596 .iter()
16597 .map(|range| Location {
16598 buffer: buffer.clone(),
16599 range: range.start.text_anchor..range.end.text_anchor,
16600 })
16601 .collect::<Vec<_>>();
16602
16603 let title = multibuffer.title(cx).to_string();
16604
16605 cx.spawn_in(window, async move |_, cx| {
16606 workspace.update_in(cx, |workspace, window, cx| {
16607 Self::open_locations_in_multibuffer(
16608 workspace,
16609 locations,
16610 format!("Selections for '{title}'"),
16611 false,
16612 MultibufferSelectionMode::All,
16613 window,
16614 cx,
16615 );
16616 })
16617 })
16618 .detach();
16619 }
16620
16621 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16622 /// last highlight added will be used.
16623 ///
16624 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16625 pub fn highlight_rows<T: 'static>(
16626 &mut self,
16627 range: Range<Anchor>,
16628 color: Hsla,
16629 should_autoscroll: bool,
16630 cx: &mut Context<Self>,
16631 ) {
16632 let snapshot = self.buffer().read(cx).snapshot(cx);
16633 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16634 let ix = row_highlights.binary_search_by(|highlight| {
16635 Ordering::Equal
16636 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16637 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16638 });
16639
16640 if let Err(mut ix) = ix {
16641 let index = post_inc(&mut self.highlight_order);
16642
16643 // If this range intersects with the preceding highlight, then merge it with
16644 // the preceding highlight. Otherwise insert a new highlight.
16645 let mut merged = false;
16646 if ix > 0 {
16647 let prev_highlight = &mut row_highlights[ix - 1];
16648 if prev_highlight
16649 .range
16650 .end
16651 .cmp(&range.start, &snapshot)
16652 .is_ge()
16653 {
16654 ix -= 1;
16655 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16656 prev_highlight.range.end = range.end;
16657 }
16658 merged = true;
16659 prev_highlight.index = index;
16660 prev_highlight.color = color;
16661 prev_highlight.should_autoscroll = should_autoscroll;
16662 }
16663 }
16664
16665 if !merged {
16666 row_highlights.insert(
16667 ix,
16668 RowHighlight {
16669 range: range.clone(),
16670 index,
16671 color,
16672 should_autoscroll,
16673 },
16674 );
16675 }
16676
16677 // If any of the following highlights intersect with this one, merge them.
16678 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16679 let highlight = &row_highlights[ix];
16680 if next_highlight
16681 .range
16682 .start
16683 .cmp(&highlight.range.end, &snapshot)
16684 .is_le()
16685 {
16686 if next_highlight
16687 .range
16688 .end
16689 .cmp(&highlight.range.end, &snapshot)
16690 .is_gt()
16691 {
16692 row_highlights[ix].range.end = next_highlight.range.end;
16693 }
16694 row_highlights.remove(ix + 1);
16695 } else {
16696 break;
16697 }
16698 }
16699 }
16700 }
16701
16702 /// Remove any highlighted row ranges of the given type that intersect the
16703 /// given ranges.
16704 pub fn remove_highlighted_rows<T: 'static>(
16705 &mut self,
16706 ranges_to_remove: Vec<Range<Anchor>>,
16707 cx: &mut Context<Self>,
16708 ) {
16709 let snapshot = self.buffer().read(cx).snapshot(cx);
16710 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16711 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16712 row_highlights.retain(|highlight| {
16713 while let Some(range_to_remove) = ranges_to_remove.peek() {
16714 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16715 Ordering::Less | Ordering::Equal => {
16716 ranges_to_remove.next();
16717 }
16718 Ordering::Greater => {
16719 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16720 Ordering::Less | Ordering::Equal => {
16721 return false;
16722 }
16723 Ordering::Greater => break,
16724 }
16725 }
16726 }
16727 }
16728
16729 true
16730 })
16731 }
16732
16733 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16734 pub fn clear_row_highlights<T: 'static>(&mut self) {
16735 self.highlighted_rows.remove(&TypeId::of::<T>());
16736 }
16737
16738 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16739 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16740 self.highlighted_rows
16741 .get(&TypeId::of::<T>())
16742 .map_or(&[] as &[_], |vec| vec.as_slice())
16743 .iter()
16744 .map(|highlight| (highlight.range.clone(), highlight.color))
16745 }
16746
16747 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16748 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16749 /// Allows to ignore certain kinds of highlights.
16750 pub fn highlighted_display_rows(
16751 &self,
16752 window: &mut Window,
16753 cx: &mut App,
16754 ) -> BTreeMap<DisplayRow, LineHighlight> {
16755 let snapshot = self.snapshot(window, cx);
16756 let mut used_highlight_orders = HashMap::default();
16757 self.highlighted_rows
16758 .iter()
16759 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16760 .fold(
16761 BTreeMap::<DisplayRow, LineHighlight>::new(),
16762 |mut unique_rows, highlight| {
16763 let start = highlight.range.start.to_display_point(&snapshot);
16764 let end = highlight.range.end.to_display_point(&snapshot);
16765 let start_row = start.row().0;
16766 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16767 && end.column() == 0
16768 {
16769 end.row().0.saturating_sub(1)
16770 } else {
16771 end.row().0
16772 };
16773 for row in start_row..=end_row {
16774 let used_index =
16775 used_highlight_orders.entry(row).or_insert(highlight.index);
16776 if highlight.index >= *used_index {
16777 *used_index = highlight.index;
16778 unique_rows.insert(DisplayRow(row), highlight.color.into());
16779 }
16780 }
16781 unique_rows
16782 },
16783 )
16784 }
16785
16786 pub fn highlighted_display_row_for_autoscroll(
16787 &self,
16788 snapshot: &DisplaySnapshot,
16789 ) -> Option<DisplayRow> {
16790 self.highlighted_rows
16791 .values()
16792 .flat_map(|highlighted_rows| highlighted_rows.iter())
16793 .filter_map(|highlight| {
16794 if highlight.should_autoscroll {
16795 Some(highlight.range.start.to_display_point(snapshot).row())
16796 } else {
16797 None
16798 }
16799 })
16800 .min()
16801 }
16802
16803 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16804 self.highlight_background::<SearchWithinRange>(
16805 ranges,
16806 |colors| colors.editor_document_highlight_read_background,
16807 cx,
16808 )
16809 }
16810
16811 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16812 self.breadcrumb_header = Some(new_header);
16813 }
16814
16815 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16816 self.clear_background_highlights::<SearchWithinRange>(cx);
16817 }
16818
16819 pub fn highlight_background<T: 'static>(
16820 &mut self,
16821 ranges: &[Range<Anchor>],
16822 color_fetcher: fn(&ThemeColors) -> Hsla,
16823 cx: &mut Context<Self>,
16824 ) {
16825 self.background_highlights
16826 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16827 self.scrollbar_marker_state.dirty = true;
16828 cx.notify();
16829 }
16830
16831 pub fn clear_background_highlights<T: 'static>(
16832 &mut self,
16833 cx: &mut Context<Self>,
16834 ) -> Option<BackgroundHighlight> {
16835 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16836 if !text_highlights.1.is_empty() {
16837 self.scrollbar_marker_state.dirty = true;
16838 cx.notify();
16839 }
16840 Some(text_highlights)
16841 }
16842
16843 pub fn highlight_gutter<T: 'static>(
16844 &mut self,
16845 ranges: &[Range<Anchor>],
16846 color_fetcher: fn(&App) -> Hsla,
16847 cx: &mut Context<Self>,
16848 ) {
16849 self.gutter_highlights
16850 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16851 cx.notify();
16852 }
16853
16854 pub fn clear_gutter_highlights<T: 'static>(
16855 &mut self,
16856 cx: &mut Context<Self>,
16857 ) -> Option<GutterHighlight> {
16858 cx.notify();
16859 self.gutter_highlights.remove(&TypeId::of::<T>())
16860 }
16861
16862 #[cfg(feature = "test-support")]
16863 pub fn all_text_background_highlights(
16864 &self,
16865 window: &mut Window,
16866 cx: &mut Context<Self>,
16867 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16868 let snapshot = self.snapshot(window, cx);
16869 let buffer = &snapshot.buffer_snapshot;
16870 let start = buffer.anchor_before(0);
16871 let end = buffer.anchor_after(buffer.len());
16872 let theme = cx.theme().colors();
16873 self.background_highlights_in_range(start..end, &snapshot, theme)
16874 }
16875
16876 #[cfg(feature = "test-support")]
16877 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16878 let snapshot = self.buffer().read(cx).snapshot(cx);
16879
16880 let highlights = self
16881 .background_highlights
16882 .get(&TypeId::of::<items::BufferSearchHighlights>());
16883
16884 if let Some((_color, ranges)) = highlights {
16885 ranges
16886 .iter()
16887 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16888 .collect_vec()
16889 } else {
16890 vec![]
16891 }
16892 }
16893
16894 fn document_highlights_for_position<'a>(
16895 &'a self,
16896 position: Anchor,
16897 buffer: &'a MultiBufferSnapshot,
16898 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16899 let read_highlights = self
16900 .background_highlights
16901 .get(&TypeId::of::<DocumentHighlightRead>())
16902 .map(|h| &h.1);
16903 let write_highlights = self
16904 .background_highlights
16905 .get(&TypeId::of::<DocumentHighlightWrite>())
16906 .map(|h| &h.1);
16907 let left_position = position.bias_left(buffer);
16908 let right_position = position.bias_right(buffer);
16909 read_highlights
16910 .into_iter()
16911 .chain(write_highlights)
16912 .flat_map(move |ranges| {
16913 let start_ix = match ranges.binary_search_by(|probe| {
16914 let cmp = probe.end.cmp(&left_position, buffer);
16915 if cmp.is_ge() {
16916 Ordering::Greater
16917 } else {
16918 Ordering::Less
16919 }
16920 }) {
16921 Ok(i) | Err(i) => i,
16922 };
16923
16924 ranges[start_ix..]
16925 .iter()
16926 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16927 })
16928 }
16929
16930 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16931 self.background_highlights
16932 .get(&TypeId::of::<T>())
16933 .map_or(false, |(_, highlights)| !highlights.is_empty())
16934 }
16935
16936 pub fn background_highlights_in_range(
16937 &self,
16938 search_range: Range<Anchor>,
16939 display_snapshot: &DisplaySnapshot,
16940 theme: &ThemeColors,
16941 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16942 let mut results = Vec::new();
16943 for (color_fetcher, ranges) in self.background_highlights.values() {
16944 let color = color_fetcher(theme);
16945 let start_ix = match ranges.binary_search_by(|probe| {
16946 let cmp = probe
16947 .end
16948 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16949 if cmp.is_gt() {
16950 Ordering::Greater
16951 } else {
16952 Ordering::Less
16953 }
16954 }) {
16955 Ok(i) | Err(i) => i,
16956 };
16957 for range in &ranges[start_ix..] {
16958 if range
16959 .start
16960 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16961 .is_ge()
16962 {
16963 break;
16964 }
16965
16966 let start = range.start.to_display_point(display_snapshot);
16967 let end = range.end.to_display_point(display_snapshot);
16968 results.push((start..end, color))
16969 }
16970 }
16971 results
16972 }
16973
16974 pub fn background_highlight_row_ranges<T: 'static>(
16975 &self,
16976 search_range: Range<Anchor>,
16977 display_snapshot: &DisplaySnapshot,
16978 count: usize,
16979 ) -> Vec<RangeInclusive<DisplayPoint>> {
16980 let mut results = Vec::new();
16981 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16982 return vec![];
16983 };
16984
16985 let start_ix = match ranges.binary_search_by(|probe| {
16986 let cmp = probe
16987 .end
16988 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16989 if cmp.is_gt() {
16990 Ordering::Greater
16991 } else {
16992 Ordering::Less
16993 }
16994 }) {
16995 Ok(i) | Err(i) => i,
16996 };
16997 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16998 if let (Some(start_display), Some(end_display)) = (start, end) {
16999 results.push(
17000 start_display.to_display_point(display_snapshot)
17001 ..=end_display.to_display_point(display_snapshot),
17002 );
17003 }
17004 };
17005 let mut start_row: Option<Point> = None;
17006 let mut end_row: Option<Point> = None;
17007 if ranges.len() > count {
17008 return Vec::new();
17009 }
17010 for range in &ranges[start_ix..] {
17011 if range
17012 .start
17013 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17014 .is_ge()
17015 {
17016 break;
17017 }
17018 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17019 if let Some(current_row) = &end_row {
17020 if end.row == current_row.row {
17021 continue;
17022 }
17023 }
17024 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17025 if start_row.is_none() {
17026 assert_eq!(end_row, None);
17027 start_row = Some(start);
17028 end_row = Some(end);
17029 continue;
17030 }
17031 if let Some(current_end) = end_row.as_mut() {
17032 if start.row > current_end.row + 1 {
17033 push_region(start_row, end_row);
17034 start_row = Some(start);
17035 end_row = Some(end);
17036 } else {
17037 // Merge two hunks.
17038 *current_end = end;
17039 }
17040 } else {
17041 unreachable!();
17042 }
17043 }
17044 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17045 push_region(start_row, end_row);
17046 results
17047 }
17048
17049 pub fn gutter_highlights_in_range(
17050 &self,
17051 search_range: Range<Anchor>,
17052 display_snapshot: &DisplaySnapshot,
17053 cx: &App,
17054 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17055 let mut results = Vec::new();
17056 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17057 let color = color_fetcher(cx);
17058 let start_ix = match ranges.binary_search_by(|probe| {
17059 let cmp = probe
17060 .end
17061 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17062 if cmp.is_gt() {
17063 Ordering::Greater
17064 } else {
17065 Ordering::Less
17066 }
17067 }) {
17068 Ok(i) | Err(i) => i,
17069 };
17070 for range in &ranges[start_ix..] {
17071 if range
17072 .start
17073 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17074 .is_ge()
17075 {
17076 break;
17077 }
17078
17079 let start = range.start.to_display_point(display_snapshot);
17080 let end = range.end.to_display_point(display_snapshot);
17081 results.push((start..end, color))
17082 }
17083 }
17084 results
17085 }
17086
17087 /// Get the text ranges corresponding to the redaction query
17088 pub fn redacted_ranges(
17089 &self,
17090 search_range: Range<Anchor>,
17091 display_snapshot: &DisplaySnapshot,
17092 cx: &App,
17093 ) -> Vec<Range<DisplayPoint>> {
17094 display_snapshot
17095 .buffer_snapshot
17096 .redacted_ranges(search_range, |file| {
17097 if let Some(file) = file {
17098 file.is_private()
17099 && EditorSettings::get(
17100 Some(SettingsLocation {
17101 worktree_id: file.worktree_id(cx),
17102 path: file.path().as_ref(),
17103 }),
17104 cx,
17105 )
17106 .redact_private_values
17107 } else {
17108 false
17109 }
17110 })
17111 .map(|range| {
17112 range.start.to_display_point(display_snapshot)
17113 ..range.end.to_display_point(display_snapshot)
17114 })
17115 .collect()
17116 }
17117
17118 pub fn highlight_text<T: 'static>(
17119 &mut self,
17120 ranges: Vec<Range<Anchor>>,
17121 style: HighlightStyle,
17122 cx: &mut Context<Self>,
17123 ) {
17124 self.display_map.update(cx, |map, _| {
17125 map.highlight_text(TypeId::of::<T>(), ranges, style)
17126 });
17127 cx.notify();
17128 }
17129
17130 pub(crate) fn highlight_inlays<T: 'static>(
17131 &mut self,
17132 highlights: Vec<InlayHighlight>,
17133 style: HighlightStyle,
17134 cx: &mut Context<Self>,
17135 ) {
17136 self.display_map.update(cx, |map, _| {
17137 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17138 });
17139 cx.notify();
17140 }
17141
17142 pub fn text_highlights<'a, T: 'static>(
17143 &'a self,
17144 cx: &'a App,
17145 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17146 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17147 }
17148
17149 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17150 let cleared = self
17151 .display_map
17152 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17153 if cleared {
17154 cx.notify();
17155 }
17156 }
17157
17158 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17159 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17160 && self.focus_handle.is_focused(window)
17161 }
17162
17163 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17164 self.show_cursor_when_unfocused = is_enabled;
17165 cx.notify();
17166 }
17167
17168 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17169 cx.notify();
17170 }
17171
17172 fn on_buffer_event(
17173 &mut self,
17174 multibuffer: &Entity<MultiBuffer>,
17175 event: &multi_buffer::Event,
17176 window: &mut Window,
17177 cx: &mut Context<Self>,
17178 ) {
17179 match event {
17180 multi_buffer::Event::Edited {
17181 singleton_buffer_edited,
17182 edited_buffer: buffer_edited,
17183 } => {
17184 self.scrollbar_marker_state.dirty = true;
17185 self.active_indent_guides_state.dirty = true;
17186 self.refresh_active_diagnostics(cx);
17187 self.refresh_code_actions(window, cx);
17188 if self.has_active_inline_completion() {
17189 self.update_visible_inline_completion(window, cx);
17190 }
17191 if let Some(buffer) = buffer_edited {
17192 let buffer_id = buffer.read(cx).remote_id();
17193 if !self.registered_buffers.contains_key(&buffer_id) {
17194 if let Some(project) = self.project.as_ref() {
17195 project.update(cx, |project, cx| {
17196 self.registered_buffers.insert(
17197 buffer_id,
17198 project.register_buffer_with_language_servers(&buffer, cx),
17199 );
17200 })
17201 }
17202 }
17203 }
17204 cx.emit(EditorEvent::BufferEdited);
17205 cx.emit(SearchEvent::MatchesInvalidated);
17206 if *singleton_buffer_edited {
17207 if let Some(project) = &self.project {
17208 #[allow(clippy::mutable_key_type)]
17209 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17210 multibuffer
17211 .all_buffers()
17212 .into_iter()
17213 .filter_map(|buffer| {
17214 buffer.update(cx, |buffer, cx| {
17215 let language = buffer.language()?;
17216 let should_discard = project.update(cx, |project, cx| {
17217 project.is_local()
17218 && !project.has_language_servers_for(buffer, cx)
17219 });
17220 should_discard.not().then_some(language.clone())
17221 })
17222 })
17223 .collect::<HashSet<_>>()
17224 });
17225 if !languages_affected.is_empty() {
17226 self.refresh_inlay_hints(
17227 InlayHintRefreshReason::BufferEdited(languages_affected),
17228 cx,
17229 );
17230 }
17231 }
17232 }
17233
17234 let Some(project) = &self.project else { return };
17235 let (telemetry, is_via_ssh) = {
17236 let project = project.read(cx);
17237 let telemetry = project.client().telemetry().clone();
17238 let is_via_ssh = project.is_via_ssh();
17239 (telemetry, is_via_ssh)
17240 };
17241 refresh_linked_ranges(self, window, cx);
17242 telemetry.log_edit_event("editor", is_via_ssh);
17243 }
17244 multi_buffer::Event::ExcerptsAdded {
17245 buffer,
17246 predecessor,
17247 excerpts,
17248 } => {
17249 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17250 let buffer_id = buffer.read(cx).remote_id();
17251 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17252 if let Some(project) = &self.project {
17253 get_uncommitted_diff_for_buffer(
17254 project,
17255 [buffer.clone()],
17256 self.buffer.clone(),
17257 cx,
17258 )
17259 .detach();
17260 }
17261 }
17262 cx.emit(EditorEvent::ExcerptsAdded {
17263 buffer: buffer.clone(),
17264 predecessor: *predecessor,
17265 excerpts: excerpts.clone(),
17266 });
17267 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17268 }
17269 multi_buffer::Event::ExcerptsRemoved { ids } => {
17270 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17271 let buffer = self.buffer.read(cx);
17272 self.registered_buffers
17273 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17274 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17275 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17276 }
17277 multi_buffer::Event::ExcerptsEdited {
17278 excerpt_ids,
17279 buffer_ids,
17280 } => {
17281 self.display_map.update(cx, |map, cx| {
17282 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17283 });
17284 cx.emit(EditorEvent::ExcerptsEdited {
17285 ids: excerpt_ids.clone(),
17286 })
17287 }
17288 multi_buffer::Event::ExcerptsExpanded { ids } => {
17289 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17290 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17291 }
17292 multi_buffer::Event::Reparsed(buffer_id) => {
17293 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17294 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17295
17296 cx.emit(EditorEvent::Reparsed(*buffer_id));
17297 }
17298 multi_buffer::Event::DiffHunksToggled => {
17299 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17300 }
17301 multi_buffer::Event::LanguageChanged(buffer_id) => {
17302 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17303 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17304 cx.emit(EditorEvent::Reparsed(*buffer_id));
17305 cx.notify();
17306 }
17307 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17308 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17309 multi_buffer::Event::FileHandleChanged
17310 | multi_buffer::Event::Reloaded
17311 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17312 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17313 multi_buffer::Event::DiagnosticsUpdated => {
17314 self.refresh_active_diagnostics(cx);
17315 self.refresh_inline_diagnostics(true, window, cx);
17316 self.scrollbar_marker_state.dirty = true;
17317 cx.notify();
17318 }
17319 _ => {}
17320 };
17321 }
17322
17323 fn on_display_map_changed(
17324 &mut self,
17325 _: Entity<DisplayMap>,
17326 _: &mut Window,
17327 cx: &mut Context<Self>,
17328 ) {
17329 cx.notify();
17330 }
17331
17332 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17333 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17334 self.update_edit_prediction_settings(cx);
17335 self.refresh_inline_completion(true, false, window, cx);
17336 self.refresh_inlay_hints(
17337 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17338 self.selections.newest_anchor().head(),
17339 &self.buffer.read(cx).snapshot(cx),
17340 cx,
17341 )),
17342 cx,
17343 );
17344
17345 let old_cursor_shape = self.cursor_shape;
17346
17347 {
17348 let editor_settings = EditorSettings::get_global(cx);
17349 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17350 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17351 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17352 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17353 }
17354
17355 if old_cursor_shape != self.cursor_shape {
17356 cx.emit(EditorEvent::CursorShapeChanged);
17357 }
17358
17359 let project_settings = ProjectSettings::get_global(cx);
17360 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17361
17362 if self.mode.is_full() {
17363 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17364 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17365 if self.show_inline_diagnostics != show_inline_diagnostics {
17366 self.show_inline_diagnostics = show_inline_diagnostics;
17367 self.refresh_inline_diagnostics(false, window, cx);
17368 }
17369
17370 if self.git_blame_inline_enabled != inline_blame_enabled {
17371 self.toggle_git_blame_inline_internal(false, window, cx);
17372 }
17373 }
17374
17375 cx.notify();
17376 }
17377
17378 pub fn set_searchable(&mut self, searchable: bool) {
17379 self.searchable = searchable;
17380 }
17381
17382 pub fn searchable(&self) -> bool {
17383 self.searchable
17384 }
17385
17386 fn open_proposed_changes_editor(
17387 &mut self,
17388 _: &OpenProposedChangesEditor,
17389 window: &mut Window,
17390 cx: &mut Context<Self>,
17391 ) {
17392 let Some(workspace) = self.workspace() else {
17393 cx.propagate();
17394 return;
17395 };
17396
17397 let selections = self.selections.all::<usize>(cx);
17398 let multi_buffer = self.buffer.read(cx);
17399 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17400 let mut new_selections_by_buffer = HashMap::default();
17401 for selection in selections {
17402 for (buffer, range, _) in
17403 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17404 {
17405 let mut range = range.to_point(buffer);
17406 range.start.column = 0;
17407 range.end.column = buffer.line_len(range.end.row);
17408 new_selections_by_buffer
17409 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17410 .or_insert(Vec::new())
17411 .push(range)
17412 }
17413 }
17414
17415 let proposed_changes_buffers = new_selections_by_buffer
17416 .into_iter()
17417 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17418 .collect::<Vec<_>>();
17419 let proposed_changes_editor = cx.new(|cx| {
17420 ProposedChangesEditor::new(
17421 "Proposed changes",
17422 proposed_changes_buffers,
17423 self.project.clone(),
17424 window,
17425 cx,
17426 )
17427 });
17428
17429 window.defer(cx, move |window, cx| {
17430 workspace.update(cx, |workspace, cx| {
17431 workspace.active_pane().update(cx, |pane, cx| {
17432 pane.add_item(
17433 Box::new(proposed_changes_editor),
17434 true,
17435 true,
17436 None,
17437 window,
17438 cx,
17439 );
17440 });
17441 });
17442 });
17443 }
17444
17445 pub fn open_excerpts_in_split(
17446 &mut self,
17447 _: &OpenExcerptsSplit,
17448 window: &mut Window,
17449 cx: &mut Context<Self>,
17450 ) {
17451 self.open_excerpts_common(None, true, window, cx)
17452 }
17453
17454 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17455 self.open_excerpts_common(None, false, window, cx)
17456 }
17457
17458 fn open_excerpts_common(
17459 &mut self,
17460 jump_data: Option<JumpData>,
17461 split: bool,
17462 window: &mut Window,
17463 cx: &mut Context<Self>,
17464 ) {
17465 let Some(workspace) = self.workspace() else {
17466 cx.propagate();
17467 return;
17468 };
17469
17470 if self.buffer.read(cx).is_singleton() {
17471 cx.propagate();
17472 return;
17473 }
17474
17475 let mut new_selections_by_buffer = HashMap::default();
17476 match &jump_data {
17477 Some(JumpData::MultiBufferPoint {
17478 excerpt_id,
17479 position,
17480 anchor,
17481 line_offset_from_top,
17482 }) => {
17483 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17484 if let Some(buffer) = multi_buffer_snapshot
17485 .buffer_id_for_excerpt(*excerpt_id)
17486 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17487 {
17488 let buffer_snapshot = buffer.read(cx).snapshot();
17489 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17490 language::ToPoint::to_point(anchor, &buffer_snapshot)
17491 } else {
17492 buffer_snapshot.clip_point(*position, Bias::Left)
17493 };
17494 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17495 new_selections_by_buffer.insert(
17496 buffer,
17497 (
17498 vec![jump_to_offset..jump_to_offset],
17499 Some(*line_offset_from_top),
17500 ),
17501 );
17502 }
17503 }
17504 Some(JumpData::MultiBufferRow {
17505 row,
17506 line_offset_from_top,
17507 }) => {
17508 let point = MultiBufferPoint::new(row.0, 0);
17509 if let Some((buffer, buffer_point, _)) =
17510 self.buffer.read(cx).point_to_buffer_point(point, cx)
17511 {
17512 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17513 new_selections_by_buffer
17514 .entry(buffer)
17515 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17516 .0
17517 .push(buffer_offset..buffer_offset)
17518 }
17519 }
17520 None => {
17521 let selections = self.selections.all::<usize>(cx);
17522 let multi_buffer = self.buffer.read(cx);
17523 for selection in selections {
17524 for (snapshot, range, _, anchor) in multi_buffer
17525 .snapshot(cx)
17526 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17527 {
17528 if let Some(anchor) = anchor {
17529 // selection is in a deleted hunk
17530 let Some(buffer_id) = anchor.buffer_id else {
17531 continue;
17532 };
17533 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17534 continue;
17535 };
17536 let offset = text::ToOffset::to_offset(
17537 &anchor.text_anchor,
17538 &buffer_handle.read(cx).snapshot(),
17539 );
17540 let range = offset..offset;
17541 new_selections_by_buffer
17542 .entry(buffer_handle)
17543 .or_insert((Vec::new(), None))
17544 .0
17545 .push(range)
17546 } else {
17547 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17548 else {
17549 continue;
17550 };
17551 new_selections_by_buffer
17552 .entry(buffer_handle)
17553 .or_insert((Vec::new(), None))
17554 .0
17555 .push(range)
17556 }
17557 }
17558 }
17559 }
17560 }
17561
17562 new_selections_by_buffer
17563 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17564
17565 if new_selections_by_buffer.is_empty() {
17566 return;
17567 }
17568
17569 // We defer the pane interaction because we ourselves are a workspace item
17570 // and activating a new item causes the pane to call a method on us reentrantly,
17571 // which panics if we're on the stack.
17572 window.defer(cx, move |window, cx| {
17573 workspace.update(cx, |workspace, cx| {
17574 let pane = if split {
17575 workspace.adjacent_pane(window, cx)
17576 } else {
17577 workspace.active_pane().clone()
17578 };
17579
17580 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17581 let editor = buffer
17582 .read(cx)
17583 .file()
17584 .is_none()
17585 .then(|| {
17586 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17587 // so `workspace.open_project_item` will never find them, always opening a new editor.
17588 // Instead, we try to activate the existing editor in the pane first.
17589 let (editor, pane_item_index) =
17590 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17591 let editor = item.downcast::<Editor>()?;
17592 let singleton_buffer =
17593 editor.read(cx).buffer().read(cx).as_singleton()?;
17594 if singleton_buffer == buffer {
17595 Some((editor, i))
17596 } else {
17597 None
17598 }
17599 })?;
17600 pane.update(cx, |pane, cx| {
17601 pane.activate_item(pane_item_index, true, true, window, cx)
17602 });
17603 Some(editor)
17604 })
17605 .flatten()
17606 .unwrap_or_else(|| {
17607 workspace.open_project_item::<Self>(
17608 pane.clone(),
17609 buffer,
17610 true,
17611 true,
17612 window,
17613 cx,
17614 )
17615 });
17616
17617 editor.update(cx, |editor, cx| {
17618 let autoscroll = match scroll_offset {
17619 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17620 None => Autoscroll::newest(),
17621 };
17622 let nav_history = editor.nav_history.take();
17623 editor.change_selections(Some(autoscroll), window, cx, |s| {
17624 s.select_ranges(ranges);
17625 });
17626 editor.nav_history = nav_history;
17627 });
17628 }
17629 })
17630 });
17631 }
17632
17633 // For now, don't allow opening excerpts in buffers that aren't backed by
17634 // regular project files.
17635 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17636 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17637 }
17638
17639 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17640 let snapshot = self.buffer.read(cx).read(cx);
17641 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17642 Some(
17643 ranges
17644 .iter()
17645 .map(move |range| {
17646 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17647 })
17648 .collect(),
17649 )
17650 }
17651
17652 fn selection_replacement_ranges(
17653 &self,
17654 range: Range<OffsetUtf16>,
17655 cx: &mut App,
17656 ) -> Vec<Range<OffsetUtf16>> {
17657 let selections = self.selections.all::<OffsetUtf16>(cx);
17658 let newest_selection = selections
17659 .iter()
17660 .max_by_key(|selection| selection.id)
17661 .unwrap();
17662 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17663 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17664 let snapshot = self.buffer.read(cx).read(cx);
17665 selections
17666 .into_iter()
17667 .map(|mut selection| {
17668 selection.start.0 =
17669 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17670 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17671 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17672 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17673 })
17674 .collect()
17675 }
17676
17677 fn report_editor_event(
17678 &self,
17679 event_type: &'static str,
17680 file_extension: Option<String>,
17681 cx: &App,
17682 ) {
17683 if cfg!(any(test, feature = "test-support")) {
17684 return;
17685 }
17686
17687 let Some(project) = &self.project else { return };
17688
17689 // If None, we are in a file without an extension
17690 let file = self
17691 .buffer
17692 .read(cx)
17693 .as_singleton()
17694 .and_then(|b| b.read(cx).file());
17695 let file_extension = file_extension.or(file
17696 .as_ref()
17697 .and_then(|file| Path::new(file.file_name(cx)).extension())
17698 .and_then(|e| e.to_str())
17699 .map(|a| a.to_string()));
17700
17701 let vim_mode = cx
17702 .global::<SettingsStore>()
17703 .raw_user_settings()
17704 .get("vim_mode")
17705 == Some(&serde_json::Value::Bool(true));
17706
17707 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17708 let copilot_enabled = edit_predictions_provider
17709 == language::language_settings::EditPredictionProvider::Copilot;
17710 let copilot_enabled_for_language = self
17711 .buffer
17712 .read(cx)
17713 .language_settings(cx)
17714 .show_edit_predictions;
17715
17716 let project = project.read(cx);
17717 telemetry::event!(
17718 event_type,
17719 file_extension,
17720 vim_mode,
17721 copilot_enabled,
17722 copilot_enabled_for_language,
17723 edit_predictions_provider,
17724 is_via_ssh = project.is_via_ssh(),
17725 );
17726 }
17727
17728 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17729 /// with each line being an array of {text, highlight} objects.
17730 fn copy_highlight_json(
17731 &mut self,
17732 _: &CopyHighlightJson,
17733 window: &mut Window,
17734 cx: &mut Context<Self>,
17735 ) {
17736 #[derive(Serialize)]
17737 struct Chunk<'a> {
17738 text: String,
17739 highlight: Option<&'a str>,
17740 }
17741
17742 let snapshot = self.buffer.read(cx).snapshot(cx);
17743 let range = self
17744 .selected_text_range(false, window, cx)
17745 .and_then(|selection| {
17746 if selection.range.is_empty() {
17747 None
17748 } else {
17749 Some(selection.range)
17750 }
17751 })
17752 .unwrap_or_else(|| 0..snapshot.len());
17753
17754 let chunks = snapshot.chunks(range, true);
17755 let mut lines = Vec::new();
17756 let mut line: VecDeque<Chunk> = VecDeque::new();
17757
17758 let Some(style) = self.style.as_ref() else {
17759 return;
17760 };
17761
17762 for chunk in chunks {
17763 let highlight = chunk
17764 .syntax_highlight_id
17765 .and_then(|id| id.name(&style.syntax));
17766 let mut chunk_lines = chunk.text.split('\n').peekable();
17767 while let Some(text) = chunk_lines.next() {
17768 let mut merged_with_last_token = false;
17769 if let Some(last_token) = line.back_mut() {
17770 if last_token.highlight == highlight {
17771 last_token.text.push_str(text);
17772 merged_with_last_token = true;
17773 }
17774 }
17775
17776 if !merged_with_last_token {
17777 line.push_back(Chunk {
17778 text: text.into(),
17779 highlight,
17780 });
17781 }
17782
17783 if chunk_lines.peek().is_some() {
17784 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17785 line.pop_front();
17786 }
17787 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17788 line.pop_back();
17789 }
17790
17791 lines.push(mem::take(&mut line));
17792 }
17793 }
17794 }
17795
17796 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17797 return;
17798 };
17799 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17800 }
17801
17802 pub fn open_context_menu(
17803 &mut self,
17804 _: &OpenContextMenu,
17805 window: &mut Window,
17806 cx: &mut Context<Self>,
17807 ) {
17808 self.request_autoscroll(Autoscroll::newest(), cx);
17809 let position = self.selections.newest_display(cx).start;
17810 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17811 }
17812
17813 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17814 &self.inlay_hint_cache
17815 }
17816
17817 pub fn replay_insert_event(
17818 &mut self,
17819 text: &str,
17820 relative_utf16_range: Option<Range<isize>>,
17821 window: &mut Window,
17822 cx: &mut Context<Self>,
17823 ) {
17824 if !self.input_enabled {
17825 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17826 return;
17827 }
17828 if let Some(relative_utf16_range) = relative_utf16_range {
17829 let selections = self.selections.all::<OffsetUtf16>(cx);
17830 self.change_selections(None, window, cx, |s| {
17831 let new_ranges = selections.into_iter().map(|range| {
17832 let start = OffsetUtf16(
17833 range
17834 .head()
17835 .0
17836 .saturating_add_signed(relative_utf16_range.start),
17837 );
17838 let end = OffsetUtf16(
17839 range
17840 .head()
17841 .0
17842 .saturating_add_signed(relative_utf16_range.end),
17843 );
17844 start..end
17845 });
17846 s.select_ranges(new_ranges);
17847 });
17848 }
17849
17850 self.handle_input(text, window, cx);
17851 }
17852
17853 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17854 let Some(provider) = self.semantics_provider.as_ref() else {
17855 return false;
17856 };
17857
17858 let mut supports = false;
17859 self.buffer().update(cx, |this, cx| {
17860 this.for_each_buffer(|buffer| {
17861 supports |= provider.supports_inlay_hints(buffer, cx);
17862 });
17863 });
17864
17865 supports
17866 }
17867
17868 pub fn is_focused(&self, window: &Window) -> bool {
17869 self.focus_handle.is_focused(window)
17870 }
17871
17872 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17873 cx.emit(EditorEvent::Focused);
17874
17875 if let Some(descendant) = self
17876 .last_focused_descendant
17877 .take()
17878 .and_then(|descendant| descendant.upgrade())
17879 {
17880 window.focus(&descendant);
17881 } else {
17882 if let Some(blame) = self.blame.as_ref() {
17883 blame.update(cx, GitBlame::focus)
17884 }
17885
17886 self.blink_manager.update(cx, BlinkManager::enable);
17887 self.show_cursor_names(window, cx);
17888 self.buffer.update(cx, |buffer, cx| {
17889 buffer.finalize_last_transaction(cx);
17890 if self.leader_peer_id.is_none() {
17891 buffer.set_active_selections(
17892 &self.selections.disjoint_anchors(),
17893 self.selections.line_mode,
17894 self.cursor_shape,
17895 cx,
17896 );
17897 }
17898 });
17899 }
17900 }
17901
17902 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17903 cx.emit(EditorEvent::FocusedIn)
17904 }
17905
17906 fn handle_focus_out(
17907 &mut self,
17908 event: FocusOutEvent,
17909 _window: &mut Window,
17910 cx: &mut Context<Self>,
17911 ) {
17912 if event.blurred != self.focus_handle {
17913 self.last_focused_descendant = Some(event.blurred);
17914 }
17915 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17916 }
17917
17918 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17919 self.blink_manager.update(cx, BlinkManager::disable);
17920 self.buffer
17921 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17922
17923 if let Some(blame) = self.blame.as_ref() {
17924 blame.update(cx, GitBlame::blur)
17925 }
17926 if !self.hover_state.focused(window, cx) {
17927 hide_hover(self, cx);
17928 }
17929 if !self
17930 .context_menu
17931 .borrow()
17932 .as_ref()
17933 .is_some_and(|context_menu| context_menu.focused(window, cx))
17934 {
17935 self.hide_context_menu(window, cx);
17936 }
17937 self.discard_inline_completion(false, cx);
17938 cx.emit(EditorEvent::Blurred);
17939 cx.notify();
17940 }
17941
17942 pub fn register_action<A: Action>(
17943 &mut self,
17944 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17945 ) -> Subscription {
17946 let id = self.next_editor_action_id.post_inc();
17947 let listener = Arc::new(listener);
17948 self.editor_actions.borrow_mut().insert(
17949 id,
17950 Box::new(move |window, _| {
17951 let listener = listener.clone();
17952 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17953 let action = action.downcast_ref().unwrap();
17954 if phase == DispatchPhase::Bubble {
17955 listener(action, window, cx)
17956 }
17957 })
17958 }),
17959 );
17960
17961 let editor_actions = self.editor_actions.clone();
17962 Subscription::new(move || {
17963 editor_actions.borrow_mut().remove(&id);
17964 })
17965 }
17966
17967 pub fn file_header_size(&self) -> u32 {
17968 FILE_HEADER_HEIGHT
17969 }
17970
17971 pub fn restore(
17972 &mut self,
17973 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17974 window: &mut Window,
17975 cx: &mut Context<Self>,
17976 ) {
17977 let workspace = self.workspace();
17978 let project = self.project.as_ref();
17979 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17980 let mut tasks = Vec::new();
17981 for (buffer_id, changes) in revert_changes {
17982 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17983 buffer.update(cx, |buffer, cx| {
17984 buffer.edit(
17985 changes
17986 .into_iter()
17987 .map(|(range, text)| (range, text.to_string())),
17988 None,
17989 cx,
17990 );
17991 });
17992
17993 if let Some(project) =
17994 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17995 {
17996 project.update(cx, |project, cx| {
17997 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17998 })
17999 }
18000 }
18001 }
18002 tasks
18003 });
18004 cx.spawn_in(window, async move |_, cx| {
18005 for (buffer, task) in save_tasks {
18006 let result = task.await;
18007 if result.is_err() {
18008 let Some(path) = buffer
18009 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18010 .ok()
18011 else {
18012 continue;
18013 };
18014 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18015 let Some(task) = cx
18016 .update_window_entity(&workspace, |workspace, window, cx| {
18017 workspace
18018 .open_path_preview(path, None, false, false, false, window, cx)
18019 })
18020 .ok()
18021 else {
18022 continue;
18023 };
18024 task.await.log_err();
18025 }
18026 }
18027 }
18028 })
18029 .detach();
18030 self.change_selections(None, window, cx, |selections| selections.refresh());
18031 }
18032
18033 pub fn to_pixel_point(
18034 &self,
18035 source: multi_buffer::Anchor,
18036 editor_snapshot: &EditorSnapshot,
18037 window: &mut Window,
18038 ) -> Option<gpui::Point<Pixels>> {
18039 let source_point = source.to_display_point(editor_snapshot);
18040 self.display_to_pixel_point(source_point, editor_snapshot, window)
18041 }
18042
18043 pub fn display_to_pixel_point(
18044 &self,
18045 source: DisplayPoint,
18046 editor_snapshot: &EditorSnapshot,
18047 window: &mut Window,
18048 ) -> Option<gpui::Point<Pixels>> {
18049 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18050 let text_layout_details = self.text_layout_details(window);
18051 let scroll_top = text_layout_details
18052 .scroll_anchor
18053 .scroll_position(editor_snapshot)
18054 .y;
18055
18056 if source.row().as_f32() < scroll_top.floor() {
18057 return None;
18058 }
18059 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18060 let source_y = line_height * (source.row().as_f32() - scroll_top);
18061 Some(gpui::Point::new(source_x, source_y))
18062 }
18063
18064 pub fn has_visible_completions_menu(&self) -> bool {
18065 !self.edit_prediction_preview_is_active()
18066 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18067 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18068 })
18069 }
18070
18071 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18072 self.addons
18073 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18074 }
18075
18076 pub fn unregister_addon<T: Addon>(&mut self) {
18077 self.addons.remove(&std::any::TypeId::of::<T>());
18078 }
18079
18080 pub fn addon<T: Addon>(&self) -> Option<&T> {
18081 let type_id = std::any::TypeId::of::<T>();
18082 self.addons
18083 .get(&type_id)
18084 .and_then(|item| item.to_any().downcast_ref::<T>())
18085 }
18086
18087 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18088 let text_layout_details = self.text_layout_details(window);
18089 let style = &text_layout_details.editor_style;
18090 let font_id = window.text_system().resolve_font(&style.text.font());
18091 let font_size = style.text.font_size.to_pixels(window.rem_size());
18092 let line_height = style.text.line_height_in_pixels(window.rem_size());
18093 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18094
18095 gpui::Size::new(em_width, line_height)
18096 }
18097
18098 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18099 self.load_diff_task.clone()
18100 }
18101
18102 fn read_metadata_from_db(
18103 &mut self,
18104 item_id: u64,
18105 workspace_id: WorkspaceId,
18106 window: &mut Window,
18107 cx: &mut Context<Editor>,
18108 ) {
18109 if self.is_singleton(cx)
18110 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18111 {
18112 let buffer_snapshot = OnceCell::new();
18113
18114 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18115 if !folds.is_empty() {
18116 let snapshot =
18117 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18118 self.fold_ranges(
18119 folds
18120 .into_iter()
18121 .map(|(start, end)| {
18122 snapshot.clip_offset(start, Bias::Left)
18123 ..snapshot.clip_offset(end, Bias::Right)
18124 })
18125 .collect(),
18126 false,
18127 window,
18128 cx,
18129 );
18130 }
18131 }
18132
18133 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18134 if !selections.is_empty() {
18135 let snapshot =
18136 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18137 self.change_selections(None, window, cx, |s| {
18138 s.select_ranges(selections.into_iter().map(|(start, end)| {
18139 snapshot.clip_offset(start, Bias::Left)
18140 ..snapshot.clip_offset(end, Bias::Right)
18141 }));
18142 });
18143 }
18144 };
18145 }
18146
18147 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18148 }
18149}
18150
18151// Consider user intent and default settings
18152fn choose_completion_range(
18153 completion: &Completion,
18154 intent: CompletionIntent,
18155 buffer: &Entity<Buffer>,
18156 cx: &mut Context<Editor>,
18157) -> Range<usize> {
18158 fn should_replace(
18159 completion: &Completion,
18160 insert_range: &Range<text::Anchor>,
18161 intent: CompletionIntent,
18162 completion_mode_setting: LspInsertMode,
18163 buffer: &Buffer,
18164 ) -> bool {
18165 // specific actions take precedence over settings
18166 match intent {
18167 CompletionIntent::CompleteWithInsert => return false,
18168 CompletionIntent::CompleteWithReplace => return true,
18169 CompletionIntent::Complete | CompletionIntent::Compose => {}
18170 }
18171
18172 match completion_mode_setting {
18173 LspInsertMode::Insert => false,
18174 LspInsertMode::Replace => true,
18175 LspInsertMode::ReplaceSubsequence => {
18176 let mut text_to_replace = buffer.chars_for_range(
18177 buffer.anchor_before(completion.replace_range.start)
18178 ..buffer.anchor_after(completion.replace_range.end),
18179 );
18180 let mut completion_text = completion.new_text.chars();
18181
18182 // is `text_to_replace` a subsequence of `completion_text`
18183 text_to_replace
18184 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18185 }
18186 LspInsertMode::ReplaceSuffix => {
18187 let range_after_cursor = insert_range.end..completion.replace_range.end;
18188
18189 let text_after_cursor = buffer
18190 .text_for_range(
18191 buffer.anchor_before(range_after_cursor.start)
18192 ..buffer.anchor_after(range_after_cursor.end),
18193 )
18194 .collect::<String>();
18195 completion.new_text.ends_with(&text_after_cursor)
18196 }
18197 }
18198 }
18199
18200 let buffer = buffer.read(cx);
18201
18202 if let CompletionSource::Lsp {
18203 insert_range: Some(insert_range),
18204 ..
18205 } = &completion.source
18206 {
18207 let completion_mode_setting =
18208 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18209 .completions
18210 .lsp_insert_mode;
18211
18212 if !should_replace(
18213 completion,
18214 &insert_range,
18215 intent,
18216 completion_mode_setting,
18217 buffer,
18218 ) {
18219 return insert_range.to_offset(buffer);
18220 }
18221 }
18222
18223 completion.replace_range.to_offset(buffer)
18224}
18225
18226fn insert_extra_newline_brackets(
18227 buffer: &MultiBufferSnapshot,
18228 range: Range<usize>,
18229 language: &language::LanguageScope,
18230) -> bool {
18231 let leading_whitespace_len = buffer
18232 .reversed_chars_at(range.start)
18233 .take_while(|c| c.is_whitespace() && *c != '\n')
18234 .map(|c| c.len_utf8())
18235 .sum::<usize>();
18236 let trailing_whitespace_len = buffer
18237 .chars_at(range.end)
18238 .take_while(|c| c.is_whitespace() && *c != '\n')
18239 .map(|c| c.len_utf8())
18240 .sum::<usize>();
18241 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18242
18243 language.brackets().any(|(pair, enabled)| {
18244 let pair_start = pair.start.trim_end();
18245 let pair_end = pair.end.trim_start();
18246
18247 enabled
18248 && pair.newline
18249 && buffer.contains_str_at(range.end, pair_end)
18250 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18251 })
18252}
18253
18254fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18255 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18256 [(buffer, range, _)] => (*buffer, range.clone()),
18257 _ => return false,
18258 };
18259 let pair = {
18260 let mut result: Option<BracketMatch> = None;
18261
18262 for pair in buffer
18263 .all_bracket_ranges(range.clone())
18264 .filter(move |pair| {
18265 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18266 })
18267 {
18268 let len = pair.close_range.end - pair.open_range.start;
18269
18270 if let Some(existing) = &result {
18271 let existing_len = existing.close_range.end - existing.open_range.start;
18272 if len > existing_len {
18273 continue;
18274 }
18275 }
18276
18277 result = Some(pair);
18278 }
18279
18280 result
18281 };
18282 let Some(pair) = pair else {
18283 return false;
18284 };
18285 pair.newline_only
18286 && buffer
18287 .chars_for_range(pair.open_range.end..range.start)
18288 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18289 .all(|c| c.is_whitespace() && c != '\n')
18290}
18291
18292fn get_uncommitted_diff_for_buffer(
18293 project: &Entity<Project>,
18294 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18295 buffer: Entity<MultiBuffer>,
18296 cx: &mut App,
18297) -> Task<()> {
18298 let mut tasks = Vec::new();
18299 project.update(cx, |project, cx| {
18300 for buffer in buffers {
18301 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18302 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18303 }
18304 }
18305 });
18306 cx.spawn(async move |cx| {
18307 let diffs = future::join_all(tasks).await;
18308 buffer
18309 .update(cx, |buffer, cx| {
18310 for diff in diffs.into_iter().flatten() {
18311 buffer.add_diff(diff, cx);
18312 }
18313 })
18314 .ok();
18315 })
18316}
18317
18318fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18319 let tab_size = tab_size.get() as usize;
18320 let mut width = offset;
18321
18322 for ch in text.chars() {
18323 width += if ch == '\t' {
18324 tab_size - (width % tab_size)
18325 } else {
18326 1
18327 };
18328 }
18329
18330 width - offset
18331}
18332
18333#[cfg(test)]
18334mod tests {
18335 use super::*;
18336
18337 #[test]
18338 fn test_string_size_with_expanded_tabs() {
18339 let nz = |val| NonZeroU32::new(val).unwrap();
18340 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18341 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18342 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18343 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18344 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18345 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18346 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18347 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18348 }
18349}
18350
18351/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18352struct WordBreakingTokenizer<'a> {
18353 input: &'a str,
18354}
18355
18356impl<'a> WordBreakingTokenizer<'a> {
18357 fn new(input: &'a str) -> Self {
18358 Self { input }
18359 }
18360}
18361
18362fn is_char_ideographic(ch: char) -> bool {
18363 use unicode_script::Script::*;
18364 use unicode_script::UnicodeScript;
18365 matches!(ch.script(), Han | Tangut | Yi)
18366}
18367
18368fn is_grapheme_ideographic(text: &str) -> bool {
18369 text.chars().any(is_char_ideographic)
18370}
18371
18372fn is_grapheme_whitespace(text: &str) -> bool {
18373 text.chars().any(|x| x.is_whitespace())
18374}
18375
18376fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18377 text.chars().next().map_or(false, |ch| {
18378 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18379 })
18380}
18381
18382#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18383enum WordBreakToken<'a> {
18384 Word { token: &'a str, grapheme_len: usize },
18385 InlineWhitespace { token: &'a str, grapheme_len: usize },
18386 Newline,
18387}
18388
18389impl<'a> Iterator for WordBreakingTokenizer<'a> {
18390 /// Yields a span, the count of graphemes in the token, and whether it was
18391 /// whitespace. Note that it also breaks at word boundaries.
18392 type Item = WordBreakToken<'a>;
18393
18394 fn next(&mut self) -> Option<Self::Item> {
18395 use unicode_segmentation::UnicodeSegmentation;
18396 if self.input.is_empty() {
18397 return None;
18398 }
18399
18400 let mut iter = self.input.graphemes(true).peekable();
18401 let mut offset = 0;
18402 let mut grapheme_len = 0;
18403 if let Some(first_grapheme) = iter.next() {
18404 let is_newline = first_grapheme == "\n";
18405 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18406 offset += first_grapheme.len();
18407 grapheme_len += 1;
18408 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18409 if let Some(grapheme) = iter.peek().copied() {
18410 if should_stay_with_preceding_ideograph(grapheme) {
18411 offset += grapheme.len();
18412 grapheme_len += 1;
18413 }
18414 }
18415 } else {
18416 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18417 let mut next_word_bound = words.peek().copied();
18418 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18419 next_word_bound = words.next();
18420 }
18421 while let Some(grapheme) = iter.peek().copied() {
18422 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18423 break;
18424 };
18425 if is_grapheme_whitespace(grapheme) != is_whitespace
18426 || (grapheme == "\n") != is_newline
18427 {
18428 break;
18429 };
18430 offset += grapheme.len();
18431 grapheme_len += 1;
18432 iter.next();
18433 }
18434 }
18435 let token = &self.input[..offset];
18436 self.input = &self.input[offset..];
18437 if token == "\n" {
18438 Some(WordBreakToken::Newline)
18439 } else if is_whitespace {
18440 Some(WordBreakToken::InlineWhitespace {
18441 token,
18442 grapheme_len,
18443 })
18444 } else {
18445 Some(WordBreakToken::Word {
18446 token,
18447 grapheme_len,
18448 })
18449 }
18450 } else {
18451 None
18452 }
18453 }
18454}
18455
18456#[test]
18457fn test_word_breaking_tokenizer() {
18458 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18459 ("", &[]),
18460 (" ", &[whitespace(" ", 2)]),
18461 ("Ʒ", &[word("Ʒ", 1)]),
18462 ("Ǽ", &[word("Ǽ", 1)]),
18463 ("⋑", &[word("⋑", 1)]),
18464 ("⋑⋑", &[word("⋑⋑", 2)]),
18465 (
18466 "原理,进而",
18467 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18468 ),
18469 (
18470 "hello world",
18471 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18472 ),
18473 (
18474 "hello, world",
18475 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18476 ),
18477 (
18478 " hello world",
18479 &[
18480 whitespace(" ", 2),
18481 word("hello", 5),
18482 whitespace(" ", 1),
18483 word("world", 5),
18484 ],
18485 ),
18486 (
18487 "这是什么 \n 钢笔",
18488 &[
18489 word("这", 1),
18490 word("是", 1),
18491 word("什", 1),
18492 word("么", 1),
18493 whitespace(" ", 1),
18494 newline(),
18495 whitespace(" ", 1),
18496 word("钢", 1),
18497 word("笔", 1),
18498 ],
18499 ),
18500 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18501 ];
18502
18503 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18504 WordBreakToken::Word {
18505 token,
18506 grapheme_len,
18507 }
18508 }
18509
18510 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18511 WordBreakToken::InlineWhitespace {
18512 token,
18513 grapheme_len,
18514 }
18515 }
18516
18517 fn newline() -> WordBreakToken<'static> {
18518 WordBreakToken::Newline
18519 }
18520
18521 for (input, result) in tests {
18522 assert_eq!(
18523 WordBreakingTokenizer::new(input)
18524 .collect::<Vec<_>>()
18525 .as_slice(),
18526 *result,
18527 );
18528 }
18529}
18530
18531fn wrap_with_prefix(
18532 line_prefix: String,
18533 unwrapped_text: String,
18534 wrap_column: usize,
18535 tab_size: NonZeroU32,
18536 preserve_existing_whitespace: bool,
18537) -> String {
18538 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18539 let mut wrapped_text = String::new();
18540 let mut current_line = line_prefix.clone();
18541
18542 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18543 let mut current_line_len = line_prefix_len;
18544 let mut in_whitespace = false;
18545 for token in tokenizer {
18546 let have_preceding_whitespace = in_whitespace;
18547 match token {
18548 WordBreakToken::Word {
18549 token,
18550 grapheme_len,
18551 } => {
18552 in_whitespace = false;
18553 if current_line_len + grapheme_len > wrap_column
18554 && current_line_len != line_prefix_len
18555 {
18556 wrapped_text.push_str(current_line.trim_end());
18557 wrapped_text.push('\n');
18558 current_line.truncate(line_prefix.len());
18559 current_line_len = line_prefix_len;
18560 }
18561 current_line.push_str(token);
18562 current_line_len += grapheme_len;
18563 }
18564 WordBreakToken::InlineWhitespace {
18565 mut token,
18566 mut grapheme_len,
18567 } => {
18568 in_whitespace = true;
18569 if have_preceding_whitespace && !preserve_existing_whitespace {
18570 continue;
18571 }
18572 if !preserve_existing_whitespace {
18573 token = " ";
18574 grapheme_len = 1;
18575 }
18576 if current_line_len + grapheme_len > wrap_column {
18577 wrapped_text.push_str(current_line.trim_end());
18578 wrapped_text.push('\n');
18579 current_line.truncate(line_prefix.len());
18580 current_line_len = line_prefix_len;
18581 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18582 current_line.push_str(token);
18583 current_line_len += grapheme_len;
18584 }
18585 }
18586 WordBreakToken::Newline => {
18587 in_whitespace = true;
18588 if preserve_existing_whitespace {
18589 wrapped_text.push_str(current_line.trim_end());
18590 wrapped_text.push('\n');
18591 current_line.truncate(line_prefix.len());
18592 current_line_len = line_prefix_len;
18593 } else if have_preceding_whitespace {
18594 continue;
18595 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18596 {
18597 wrapped_text.push_str(current_line.trim_end());
18598 wrapped_text.push('\n');
18599 current_line.truncate(line_prefix.len());
18600 current_line_len = line_prefix_len;
18601 } else if current_line_len != line_prefix_len {
18602 current_line.push(' ');
18603 current_line_len += 1;
18604 }
18605 }
18606 }
18607 }
18608
18609 if !current_line.is_empty() {
18610 wrapped_text.push_str(¤t_line);
18611 }
18612 wrapped_text
18613}
18614
18615#[test]
18616fn test_wrap_with_prefix() {
18617 assert_eq!(
18618 wrap_with_prefix(
18619 "# ".to_string(),
18620 "abcdefg".to_string(),
18621 4,
18622 NonZeroU32::new(4).unwrap(),
18623 false,
18624 ),
18625 "# abcdefg"
18626 );
18627 assert_eq!(
18628 wrap_with_prefix(
18629 "".to_string(),
18630 "\thello world".to_string(),
18631 8,
18632 NonZeroU32::new(4).unwrap(),
18633 false,
18634 ),
18635 "hello\nworld"
18636 );
18637 assert_eq!(
18638 wrap_with_prefix(
18639 "// ".to_string(),
18640 "xx \nyy zz aa bb cc".to_string(),
18641 12,
18642 NonZeroU32::new(4).unwrap(),
18643 false,
18644 ),
18645 "// xx yy zz\n// aa bb cc"
18646 );
18647 assert_eq!(
18648 wrap_with_prefix(
18649 String::new(),
18650 "这是什么 \n 钢笔".to_string(),
18651 3,
18652 NonZeroU32::new(4).unwrap(),
18653 false,
18654 ),
18655 "这是什\n么 钢\n笔"
18656 );
18657}
18658
18659pub trait CollaborationHub {
18660 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18661 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18662 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18663}
18664
18665impl CollaborationHub for Entity<Project> {
18666 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18667 self.read(cx).collaborators()
18668 }
18669
18670 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18671 self.read(cx).user_store().read(cx).participant_indices()
18672 }
18673
18674 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18675 let this = self.read(cx);
18676 let user_ids = this.collaborators().values().map(|c| c.user_id);
18677 this.user_store().read_with(cx, |user_store, cx| {
18678 user_store.participant_names(user_ids, cx)
18679 })
18680 }
18681}
18682
18683pub trait SemanticsProvider {
18684 fn hover(
18685 &self,
18686 buffer: &Entity<Buffer>,
18687 position: text::Anchor,
18688 cx: &mut App,
18689 ) -> Option<Task<Vec<project::Hover>>>;
18690
18691 fn inlay_hints(
18692 &self,
18693 buffer_handle: Entity<Buffer>,
18694 range: Range<text::Anchor>,
18695 cx: &mut App,
18696 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18697
18698 fn resolve_inlay_hint(
18699 &self,
18700 hint: InlayHint,
18701 buffer_handle: Entity<Buffer>,
18702 server_id: LanguageServerId,
18703 cx: &mut App,
18704 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18705
18706 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18707
18708 fn document_highlights(
18709 &self,
18710 buffer: &Entity<Buffer>,
18711 position: text::Anchor,
18712 cx: &mut App,
18713 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18714
18715 fn definitions(
18716 &self,
18717 buffer: &Entity<Buffer>,
18718 position: text::Anchor,
18719 kind: GotoDefinitionKind,
18720 cx: &mut App,
18721 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18722
18723 fn range_for_rename(
18724 &self,
18725 buffer: &Entity<Buffer>,
18726 position: text::Anchor,
18727 cx: &mut App,
18728 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18729
18730 fn perform_rename(
18731 &self,
18732 buffer: &Entity<Buffer>,
18733 position: text::Anchor,
18734 new_name: String,
18735 cx: &mut App,
18736 ) -> Option<Task<Result<ProjectTransaction>>>;
18737}
18738
18739pub trait CompletionProvider {
18740 fn completions(
18741 &self,
18742 excerpt_id: ExcerptId,
18743 buffer: &Entity<Buffer>,
18744 buffer_position: text::Anchor,
18745 trigger: CompletionContext,
18746 window: &mut Window,
18747 cx: &mut Context<Editor>,
18748 ) -> Task<Result<Option<Vec<Completion>>>>;
18749
18750 fn resolve_completions(
18751 &self,
18752 buffer: Entity<Buffer>,
18753 completion_indices: Vec<usize>,
18754 completions: Rc<RefCell<Box<[Completion]>>>,
18755 cx: &mut Context<Editor>,
18756 ) -> Task<Result<bool>>;
18757
18758 fn apply_additional_edits_for_completion(
18759 &self,
18760 _buffer: Entity<Buffer>,
18761 _completions: Rc<RefCell<Box<[Completion]>>>,
18762 _completion_index: usize,
18763 _push_to_history: bool,
18764 _cx: &mut Context<Editor>,
18765 ) -> Task<Result<Option<language::Transaction>>> {
18766 Task::ready(Ok(None))
18767 }
18768
18769 fn is_completion_trigger(
18770 &self,
18771 buffer: &Entity<Buffer>,
18772 position: language::Anchor,
18773 text: &str,
18774 trigger_in_words: bool,
18775 cx: &mut Context<Editor>,
18776 ) -> bool;
18777
18778 fn sort_completions(&self) -> bool {
18779 true
18780 }
18781
18782 fn filter_completions(&self) -> bool {
18783 true
18784 }
18785}
18786
18787pub trait CodeActionProvider {
18788 fn id(&self) -> Arc<str>;
18789
18790 fn code_actions(
18791 &self,
18792 buffer: &Entity<Buffer>,
18793 range: Range<text::Anchor>,
18794 window: &mut Window,
18795 cx: &mut App,
18796 ) -> Task<Result<Vec<CodeAction>>>;
18797
18798 fn apply_code_action(
18799 &self,
18800 buffer_handle: Entity<Buffer>,
18801 action: CodeAction,
18802 excerpt_id: ExcerptId,
18803 push_to_history: bool,
18804 window: &mut Window,
18805 cx: &mut App,
18806 ) -> Task<Result<ProjectTransaction>>;
18807}
18808
18809impl CodeActionProvider for Entity<Project> {
18810 fn id(&self) -> Arc<str> {
18811 "project".into()
18812 }
18813
18814 fn code_actions(
18815 &self,
18816 buffer: &Entity<Buffer>,
18817 range: Range<text::Anchor>,
18818 _window: &mut Window,
18819 cx: &mut App,
18820 ) -> Task<Result<Vec<CodeAction>>> {
18821 self.update(cx, |project, cx| {
18822 let code_lens = project.code_lens(buffer, range.clone(), cx);
18823 let code_actions = project.code_actions(buffer, range, None, cx);
18824 cx.background_spawn(async move {
18825 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18826 Ok(code_lens
18827 .context("code lens fetch")?
18828 .into_iter()
18829 .chain(code_actions.context("code action fetch")?)
18830 .collect())
18831 })
18832 })
18833 }
18834
18835 fn apply_code_action(
18836 &self,
18837 buffer_handle: Entity<Buffer>,
18838 action: CodeAction,
18839 _excerpt_id: ExcerptId,
18840 push_to_history: bool,
18841 _window: &mut Window,
18842 cx: &mut App,
18843 ) -> Task<Result<ProjectTransaction>> {
18844 self.update(cx, |project, cx| {
18845 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18846 })
18847 }
18848}
18849
18850fn snippet_completions(
18851 project: &Project,
18852 buffer: &Entity<Buffer>,
18853 buffer_position: text::Anchor,
18854 cx: &mut App,
18855) -> Task<Result<Vec<Completion>>> {
18856 let languages = buffer.read(cx).languages_at(buffer_position);
18857 let snippet_store = project.snippets().read(cx);
18858
18859 let scopes: Vec<_> = languages
18860 .iter()
18861 .filter_map(|language| {
18862 let language_name = language.lsp_id();
18863 let snippets = snippet_store.snippets_for(Some(language_name), cx);
18864
18865 if snippets.is_empty() {
18866 None
18867 } else {
18868 Some((language.default_scope(), snippets))
18869 }
18870 })
18871 .collect();
18872
18873 if scopes.is_empty() {
18874 return Task::ready(Ok(vec![]));
18875 }
18876
18877 let snapshot = buffer.read(cx).text_snapshot();
18878 let chars: String = snapshot
18879 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18880 .collect();
18881 let executor = cx.background_executor().clone();
18882
18883 cx.background_spawn(async move {
18884 let mut all_results: Vec<Completion> = Vec::new();
18885 for (scope, snippets) in scopes.into_iter() {
18886 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18887 let mut last_word = chars
18888 .chars()
18889 .take_while(|c| classifier.is_word(*c))
18890 .collect::<String>();
18891 last_word = last_word.chars().rev().collect();
18892
18893 if last_word.is_empty() {
18894 return Ok(vec![]);
18895 }
18896
18897 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18898 let to_lsp = |point: &text::Anchor| {
18899 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18900 point_to_lsp(end)
18901 };
18902 let lsp_end = to_lsp(&buffer_position);
18903
18904 let candidates = snippets
18905 .iter()
18906 .enumerate()
18907 .flat_map(|(ix, snippet)| {
18908 snippet
18909 .prefix
18910 .iter()
18911 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18912 })
18913 .collect::<Vec<StringMatchCandidate>>();
18914
18915 let mut matches = fuzzy::match_strings(
18916 &candidates,
18917 &last_word,
18918 last_word.chars().any(|c| c.is_uppercase()),
18919 100,
18920 &Default::default(),
18921 executor.clone(),
18922 )
18923 .await;
18924
18925 // Remove all candidates where the query's start does not match the start of any word in the candidate
18926 if let Some(query_start) = last_word.chars().next() {
18927 matches.retain(|string_match| {
18928 split_words(&string_match.string).any(|word| {
18929 // Check that the first codepoint of the word as lowercase matches the first
18930 // codepoint of the query as lowercase
18931 word.chars()
18932 .flat_map(|codepoint| codepoint.to_lowercase())
18933 .zip(query_start.to_lowercase())
18934 .all(|(word_cp, query_cp)| word_cp == query_cp)
18935 })
18936 });
18937 }
18938
18939 let matched_strings = matches
18940 .into_iter()
18941 .map(|m| m.string)
18942 .collect::<HashSet<_>>();
18943
18944 let mut result: Vec<Completion> = snippets
18945 .iter()
18946 .filter_map(|snippet| {
18947 let matching_prefix = snippet
18948 .prefix
18949 .iter()
18950 .find(|prefix| matched_strings.contains(*prefix))?;
18951 let start = as_offset - last_word.len();
18952 let start = snapshot.anchor_before(start);
18953 let range = start..buffer_position;
18954 let lsp_start = to_lsp(&start);
18955 let lsp_range = lsp::Range {
18956 start: lsp_start,
18957 end: lsp_end,
18958 };
18959 Some(Completion {
18960 replace_range: range,
18961 new_text: snippet.body.clone(),
18962 source: CompletionSource::Lsp {
18963 insert_range: None,
18964 server_id: LanguageServerId(usize::MAX),
18965 resolved: true,
18966 lsp_completion: Box::new(lsp::CompletionItem {
18967 label: snippet.prefix.first().unwrap().clone(),
18968 kind: Some(CompletionItemKind::SNIPPET),
18969 label_details: snippet.description.as_ref().map(|description| {
18970 lsp::CompletionItemLabelDetails {
18971 detail: Some(description.clone()),
18972 description: None,
18973 }
18974 }),
18975 insert_text_format: Some(InsertTextFormat::SNIPPET),
18976 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18977 lsp::InsertReplaceEdit {
18978 new_text: snippet.body.clone(),
18979 insert: lsp_range,
18980 replace: lsp_range,
18981 },
18982 )),
18983 filter_text: Some(snippet.body.clone()),
18984 sort_text: Some(char::MAX.to_string()),
18985 ..lsp::CompletionItem::default()
18986 }),
18987 lsp_defaults: None,
18988 },
18989 label: CodeLabel {
18990 text: matching_prefix.clone(),
18991 runs: Vec::new(),
18992 filter_range: 0..matching_prefix.len(),
18993 },
18994 icon_path: None,
18995 documentation: snippet.description.clone().map(|description| {
18996 CompletionDocumentation::SingleLine(description.into())
18997 }),
18998 insert_text_mode: None,
18999 confirm: None,
19000 })
19001 })
19002 .collect();
19003
19004 all_results.append(&mut result);
19005 }
19006
19007 Ok(all_results)
19008 })
19009}
19010
19011impl CompletionProvider for Entity<Project> {
19012 fn completions(
19013 &self,
19014 _excerpt_id: ExcerptId,
19015 buffer: &Entity<Buffer>,
19016 buffer_position: text::Anchor,
19017 options: CompletionContext,
19018 _window: &mut Window,
19019 cx: &mut Context<Editor>,
19020 ) -> Task<Result<Option<Vec<Completion>>>> {
19021 self.update(cx, |project, cx| {
19022 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19023 let project_completions = project.completions(buffer, buffer_position, options, cx);
19024 cx.background_spawn(async move {
19025 let snippets_completions = snippets.await?;
19026 match project_completions.await? {
19027 Some(mut completions) => {
19028 completions.extend(snippets_completions);
19029 Ok(Some(completions))
19030 }
19031 None => {
19032 if snippets_completions.is_empty() {
19033 Ok(None)
19034 } else {
19035 Ok(Some(snippets_completions))
19036 }
19037 }
19038 }
19039 })
19040 })
19041 }
19042
19043 fn resolve_completions(
19044 &self,
19045 buffer: Entity<Buffer>,
19046 completion_indices: Vec<usize>,
19047 completions: Rc<RefCell<Box<[Completion]>>>,
19048 cx: &mut Context<Editor>,
19049 ) -> Task<Result<bool>> {
19050 self.update(cx, |project, cx| {
19051 project.lsp_store().update(cx, |lsp_store, cx| {
19052 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19053 })
19054 })
19055 }
19056
19057 fn apply_additional_edits_for_completion(
19058 &self,
19059 buffer: Entity<Buffer>,
19060 completions: Rc<RefCell<Box<[Completion]>>>,
19061 completion_index: usize,
19062 push_to_history: bool,
19063 cx: &mut Context<Editor>,
19064 ) -> Task<Result<Option<language::Transaction>>> {
19065 self.update(cx, |project, cx| {
19066 project.lsp_store().update(cx, |lsp_store, cx| {
19067 lsp_store.apply_additional_edits_for_completion(
19068 buffer,
19069 completions,
19070 completion_index,
19071 push_to_history,
19072 cx,
19073 )
19074 })
19075 })
19076 }
19077
19078 fn is_completion_trigger(
19079 &self,
19080 buffer: &Entity<Buffer>,
19081 position: language::Anchor,
19082 text: &str,
19083 trigger_in_words: bool,
19084 cx: &mut Context<Editor>,
19085 ) -> bool {
19086 let mut chars = text.chars();
19087 let char = if let Some(char) = chars.next() {
19088 char
19089 } else {
19090 return false;
19091 };
19092 if chars.next().is_some() {
19093 return false;
19094 }
19095
19096 let buffer = buffer.read(cx);
19097 let snapshot = buffer.snapshot();
19098 if !snapshot.settings_at(position, cx).show_completions_on_input {
19099 return false;
19100 }
19101 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19102 if trigger_in_words && classifier.is_word(char) {
19103 return true;
19104 }
19105
19106 buffer.completion_triggers().contains(text)
19107 }
19108}
19109
19110impl SemanticsProvider for Entity<Project> {
19111 fn hover(
19112 &self,
19113 buffer: &Entity<Buffer>,
19114 position: text::Anchor,
19115 cx: &mut App,
19116 ) -> Option<Task<Vec<project::Hover>>> {
19117 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19118 }
19119
19120 fn document_highlights(
19121 &self,
19122 buffer: &Entity<Buffer>,
19123 position: text::Anchor,
19124 cx: &mut App,
19125 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19126 Some(self.update(cx, |project, cx| {
19127 project.document_highlights(buffer, position, cx)
19128 }))
19129 }
19130
19131 fn definitions(
19132 &self,
19133 buffer: &Entity<Buffer>,
19134 position: text::Anchor,
19135 kind: GotoDefinitionKind,
19136 cx: &mut App,
19137 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19138 Some(self.update(cx, |project, cx| match kind {
19139 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19140 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19141 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19142 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19143 }))
19144 }
19145
19146 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19147 // TODO: make this work for remote projects
19148 self.update(cx, |this, cx| {
19149 buffer.update(cx, |buffer, cx| {
19150 this.any_language_server_supports_inlay_hints(buffer, cx)
19151 })
19152 })
19153 }
19154
19155 fn inlay_hints(
19156 &self,
19157 buffer_handle: Entity<Buffer>,
19158 range: Range<text::Anchor>,
19159 cx: &mut App,
19160 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19161 Some(self.update(cx, |project, cx| {
19162 project.inlay_hints(buffer_handle, range, cx)
19163 }))
19164 }
19165
19166 fn resolve_inlay_hint(
19167 &self,
19168 hint: InlayHint,
19169 buffer_handle: Entity<Buffer>,
19170 server_id: LanguageServerId,
19171 cx: &mut App,
19172 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19173 Some(self.update(cx, |project, cx| {
19174 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19175 }))
19176 }
19177
19178 fn range_for_rename(
19179 &self,
19180 buffer: &Entity<Buffer>,
19181 position: text::Anchor,
19182 cx: &mut App,
19183 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19184 Some(self.update(cx, |project, cx| {
19185 let buffer = buffer.clone();
19186 let task = project.prepare_rename(buffer.clone(), position, cx);
19187 cx.spawn(async move |_, cx| {
19188 Ok(match task.await? {
19189 PrepareRenameResponse::Success(range) => Some(range),
19190 PrepareRenameResponse::InvalidPosition => None,
19191 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19192 // Fallback on using TreeSitter info to determine identifier range
19193 buffer.update(cx, |buffer, _| {
19194 let snapshot = buffer.snapshot();
19195 let (range, kind) = snapshot.surrounding_word(position);
19196 if kind != Some(CharKind::Word) {
19197 return None;
19198 }
19199 Some(
19200 snapshot.anchor_before(range.start)
19201 ..snapshot.anchor_after(range.end),
19202 )
19203 })?
19204 }
19205 })
19206 })
19207 }))
19208 }
19209
19210 fn perform_rename(
19211 &self,
19212 buffer: &Entity<Buffer>,
19213 position: text::Anchor,
19214 new_name: String,
19215 cx: &mut App,
19216 ) -> Option<Task<Result<ProjectTransaction>>> {
19217 Some(self.update(cx, |project, cx| {
19218 project.perform_rename(buffer.clone(), position, new_name, cx)
19219 }))
19220 }
19221}
19222
19223fn inlay_hint_settings(
19224 location: Anchor,
19225 snapshot: &MultiBufferSnapshot,
19226 cx: &mut Context<Editor>,
19227) -> InlayHintSettings {
19228 let file = snapshot.file_at(location);
19229 let language = snapshot.language_at(location).map(|l| l.name());
19230 language_settings(language, file, cx).inlay_hints
19231}
19232
19233fn consume_contiguous_rows(
19234 contiguous_row_selections: &mut Vec<Selection<Point>>,
19235 selection: &Selection<Point>,
19236 display_map: &DisplaySnapshot,
19237 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19238) -> (MultiBufferRow, MultiBufferRow) {
19239 contiguous_row_selections.push(selection.clone());
19240 let start_row = MultiBufferRow(selection.start.row);
19241 let mut end_row = ending_row(selection, display_map);
19242
19243 while let Some(next_selection) = selections.peek() {
19244 if next_selection.start.row <= end_row.0 {
19245 end_row = ending_row(next_selection, display_map);
19246 contiguous_row_selections.push(selections.next().unwrap().clone());
19247 } else {
19248 break;
19249 }
19250 }
19251 (start_row, end_row)
19252}
19253
19254fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19255 if next_selection.end.column > 0 || next_selection.is_empty() {
19256 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19257 } else {
19258 MultiBufferRow(next_selection.end.row)
19259 }
19260}
19261
19262impl EditorSnapshot {
19263 pub fn remote_selections_in_range<'a>(
19264 &'a self,
19265 range: &'a Range<Anchor>,
19266 collaboration_hub: &dyn CollaborationHub,
19267 cx: &'a App,
19268 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19269 let participant_names = collaboration_hub.user_names(cx);
19270 let participant_indices = collaboration_hub.user_participant_indices(cx);
19271 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19272 let collaborators_by_replica_id = collaborators_by_peer_id
19273 .iter()
19274 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19275 .collect::<HashMap<_, _>>();
19276 self.buffer_snapshot
19277 .selections_in_range(range, false)
19278 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19279 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19280 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19281 let user_name = participant_names.get(&collaborator.user_id).cloned();
19282 Some(RemoteSelection {
19283 replica_id,
19284 selection,
19285 cursor_shape,
19286 line_mode,
19287 participant_index,
19288 peer_id: collaborator.peer_id,
19289 user_name,
19290 })
19291 })
19292 }
19293
19294 pub fn hunks_for_ranges(
19295 &self,
19296 ranges: impl IntoIterator<Item = Range<Point>>,
19297 ) -> Vec<MultiBufferDiffHunk> {
19298 let mut hunks = Vec::new();
19299 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19300 HashMap::default();
19301 for query_range in ranges {
19302 let query_rows =
19303 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19304 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19305 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19306 ) {
19307 // Include deleted hunks that are adjacent to the query range, because
19308 // otherwise they would be missed.
19309 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19310 if hunk.status().is_deleted() {
19311 intersects_range |= hunk.row_range.start == query_rows.end;
19312 intersects_range |= hunk.row_range.end == query_rows.start;
19313 }
19314 if intersects_range {
19315 if !processed_buffer_rows
19316 .entry(hunk.buffer_id)
19317 .or_default()
19318 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19319 {
19320 continue;
19321 }
19322 hunks.push(hunk);
19323 }
19324 }
19325 }
19326
19327 hunks
19328 }
19329
19330 fn display_diff_hunks_for_rows<'a>(
19331 &'a self,
19332 display_rows: Range<DisplayRow>,
19333 folded_buffers: &'a HashSet<BufferId>,
19334 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19335 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19336 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19337
19338 self.buffer_snapshot
19339 .diff_hunks_in_range(buffer_start..buffer_end)
19340 .filter_map(|hunk| {
19341 if folded_buffers.contains(&hunk.buffer_id) {
19342 return None;
19343 }
19344
19345 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19346 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19347
19348 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19349 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19350
19351 let display_hunk = if hunk_display_start.column() != 0 {
19352 DisplayDiffHunk::Folded {
19353 display_row: hunk_display_start.row(),
19354 }
19355 } else {
19356 let mut end_row = hunk_display_end.row();
19357 if hunk_display_end.column() > 0 {
19358 end_row.0 += 1;
19359 }
19360 let is_created_file = hunk.is_created_file();
19361 DisplayDiffHunk::Unfolded {
19362 status: hunk.status(),
19363 diff_base_byte_range: hunk.diff_base_byte_range,
19364 display_row_range: hunk_display_start.row()..end_row,
19365 multi_buffer_range: Anchor::range_in_buffer(
19366 hunk.excerpt_id,
19367 hunk.buffer_id,
19368 hunk.buffer_range,
19369 ),
19370 is_created_file,
19371 }
19372 };
19373
19374 Some(display_hunk)
19375 })
19376 }
19377
19378 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19379 self.display_snapshot.buffer_snapshot.language_at(position)
19380 }
19381
19382 pub fn is_focused(&self) -> bool {
19383 self.is_focused
19384 }
19385
19386 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19387 self.placeholder_text.as_ref()
19388 }
19389
19390 pub fn scroll_position(&self) -> gpui::Point<f32> {
19391 self.scroll_anchor.scroll_position(&self.display_snapshot)
19392 }
19393
19394 fn gutter_dimensions(
19395 &self,
19396 font_id: FontId,
19397 font_size: Pixels,
19398 max_line_number_width: Pixels,
19399 cx: &App,
19400 ) -> Option<GutterDimensions> {
19401 if !self.show_gutter {
19402 return None;
19403 }
19404
19405 let descent = cx.text_system().descent(font_id, font_size);
19406 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19407 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19408
19409 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19410 matches!(
19411 ProjectSettings::get_global(cx).git.git_gutter,
19412 Some(GitGutterSetting::TrackedFiles)
19413 )
19414 });
19415 let gutter_settings = EditorSettings::get_global(cx).gutter;
19416 let show_line_numbers = self
19417 .show_line_numbers
19418 .unwrap_or(gutter_settings.line_numbers);
19419 let line_gutter_width = if show_line_numbers {
19420 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19421 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19422 max_line_number_width.max(min_width_for_number_on_gutter)
19423 } else {
19424 0.0.into()
19425 };
19426
19427 let show_code_actions = self
19428 .show_code_actions
19429 .unwrap_or(gutter_settings.code_actions);
19430
19431 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19432 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19433
19434 let git_blame_entries_width =
19435 self.git_blame_gutter_max_author_length
19436 .map(|max_author_length| {
19437 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19438 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19439
19440 /// The number of characters to dedicate to gaps and margins.
19441 const SPACING_WIDTH: usize = 4;
19442
19443 let max_char_count = max_author_length.min(renderer.max_author_length())
19444 + ::git::SHORT_SHA_LENGTH
19445 + MAX_RELATIVE_TIMESTAMP.len()
19446 + SPACING_WIDTH;
19447
19448 em_advance * max_char_count
19449 });
19450
19451 let is_singleton = self.buffer_snapshot.is_singleton();
19452
19453 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19454 left_padding += if !is_singleton {
19455 em_width * 4.0
19456 } else if show_code_actions || show_runnables || show_breakpoints {
19457 em_width * 3.0
19458 } else if show_git_gutter && show_line_numbers {
19459 em_width * 2.0
19460 } else if show_git_gutter || show_line_numbers {
19461 em_width
19462 } else {
19463 px(0.)
19464 };
19465
19466 let shows_folds = is_singleton && gutter_settings.folds;
19467
19468 let right_padding = if shows_folds && show_line_numbers {
19469 em_width * 4.0
19470 } else if shows_folds || (!is_singleton && show_line_numbers) {
19471 em_width * 3.0
19472 } else if show_line_numbers {
19473 em_width
19474 } else {
19475 px(0.)
19476 };
19477
19478 Some(GutterDimensions {
19479 left_padding,
19480 right_padding,
19481 width: line_gutter_width + left_padding + right_padding,
19482 margin: -descent,
19483 git_blame_entries_width,
19484 })
19485 }
19486
19487 pub fn render_crease_toggle(
19488 &self,
19489 buffer_row: MultiBufferRow,
19490 row_contains_cursor: bool,
19491 editor: Entity<Editor>,
19492 window: &mut Window,
19493 cx: &mut App,
19494 ) -> Option<AnyElement> {
19495 let folded = self.is_line_folded(buffer_row);
19496 let mut is_foldable = false;
19497
19498 if let Some(crease) = self
19499 .crease_snapshot
19500 .query_row(buffer_row, &self.buffer_snapshot)
19501 {
19502 is_foldable = true;
19503 match crease {
19504 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19505 if let Some(render_toggle) = render_toggle {
19506 let toggle_callback =
19507 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19508 if folded {
19509 editor.update(cx, |editor, cx| {
19510 editor.fold_at(buffer_row, window, cx)
19511 });
19512 } else {
19513 editor.update(cx, |editor, cx| {
19514 editor.unfold_at(buffer_row, window, cx)
19515 });
19516 }
19517 });
19518 return Some((render_toggle)(
19519 buffer_row,
19520 folded,
19521 toggle_callback,
19522 window,
19523 cx,
19524 ));
19525 }
19526 }
19527 }
19528 }
19529
19530 is_foldable |= self.starts_indent(buffer_row);
19531
19532 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19533 Some(
19534 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19535 .toggle_state(folded)
19536 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19537 if folded {
19538 this.unfold_at(buffer_row, window, cx);
19539 } else {
19540 this.fold_at(buffer_row, window, cx);
19541 }
19542 }))
19543 .into_any_element(),
19544 )
19545 } else {
19546 None
19547 }
19548 }
19549
19550 pub fn render_crease_trailer(
19551 &self,
19552 buffer_row: MultiBufferRow,
19553 window: &mut Window,
19554 cx: &mut App,
19555 ) -> Option<AnyElement> {
19556 let folded = self.is_line_folded(buffer_row);
19557 if let Crease::Inline { render_trailer, .. } = self
19558 .crease_snapshot
19559 .query_row(buffer_row, &self.buffer_snapshot)?
19560 {
19561 let render_trailer = render_trailer.as_ref()?;
19562 Some(render_trailer(buffer_row, folded, window, cx))
19563 } else {
19564 None
19565 }
19566 }
19567}
19568
19569impl Deref for EditorSnapshot {
19570 type Target = DisplaySnapshot;
19571
19572 fn deref(&self) -> &Self::Target {
19573 &self.display_snapshot
19574 }
19575}
19576
19577#[derive(Clone, Debug, PartialEq, Eq)]
19578pub enum EditorEvent {
19579 InputIgnored {
19580 text: Arc<str>,
19581 },
19582 InputHandled {
19583 utf16_range_to_replace: Option<Range<isize>>,
19584 text: Arc<str>,
19585 },
19586 ExcerptsAdded {
19587 buffer: Entity<Buffer>,
19588 predecessor: ExcerptId,
19589 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19590 },
19591 ExcerptsRemoved {
19592 ids: Vec<ExcerptId>,
19593 },
19594 BufferFoldToggled {
19595 ids: Vec<ExcerptId>,
19596 folded: bool,
19597 },
19598 ExcerptsEdited {
19599 ids: Vec<ExcerptId>,
19600 },
19601 ExcerptsExpanded {
19602 ids: Vec<ExcerptId>,
19603 },
19604 BufferEdited,
19605 Edited {
19606 transaction_id: clock::Lamport,
19607 },
19608 Reparsed(BufferId),
19609 Focused,
19610 FocusedIn,
19611 Blurred,
19612 DirtyChanged,
19613 Saved,
19614 TitleChanged,
19615 DiffBaseChanged,
19616 SelectionsChanged {
19617 local: bool,
19618 },
19619 ScrollPositionChanged {
19620 local: bool,
19621 autoscroll: bool,
19622 },
19623 Closed,
19624 TransactionUndone {
19625 transaction_id: clock::Lamport,
19626 },
19627 TransactionBegun {
19628 transaction_id: clock::Lamport,
19629 },
19630 Reloaded,
19631 CursorShapeChanged,
19632 PushedToNavHistory {
19633 anchor: Anchor,
19634 is_deactivate: bool,
19635 },
19636}
19637
19638impl EventEmitter<EditorEvent> for Editor {}
19639
19640impl Focusable for Editor {
19641 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19642 self.focus_handle.clone()
19643 }
19644}
19645
19646impl Render for Editor {
19647 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19648 let settings = ThemeSettings::get_global(cx);
19649
19650 let mut text_style = match self.mode {
19651 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19652 color: cx.theme().colors().editor_foreground,
19653 font_family: settings.ui_font.family.clone(),
19654 font_features: settings.ui_font.features.clone(),
19655 font_fallbacks: settings.ui_font.fallbacks.clone(),
19656 font_size: rems(0.875).into(),
19657 font_weight: settings.ui_font.weight,
19658 line_height: relative(settings.buffer_line_height.value()),
19659 ..Default::default()
19660 },
19661 EditorMode::Full { .. } => TextStyle {
19662 color: cx.theme().colors().editor_foreground,
19663 font_family: settings.buffer_font.family.clone(),
19664 font_features: settings.buffer_font.features.clone(),
19665 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19666 font_size: settings.buffer_font_size(cx).into(),
19667 font_weight: settings.buffer_font.weight,
19668 line_height: relative(settings.buffer_line_height.value()),
19669 ..Default::default()
19670 },
19671 };
19672 if let Some(text_style_refinement) = &self.text_style_refinement {
19673 text_style.refine(text_style_refinement)
19674 }
19675
19676 let background = match self.mode {
19677 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19678 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19679 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19680 };
19681
19682 EditorElement::new(
19683 &cx.entity(),
19684 EditorStyle {
19685 background,
19686 local_player: cx.theme().players().local(),
19687 text: text_style,
19688 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19689 syntax: cx.theme().syntax().clone(),
19690 status: cx.theme().status().clone(),
19691 inlay_hints_style: make_inlay_hints_style(cx),
19692 inline_completion_styles: make_suggestion_styles(cx),
19693 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19694 },
19695 )
19696 }
19697}
19698
19699impl EntityInputHandler for Editor {
19700 fn text_for_range(
19701 &mut self,
19702 range_utf16: Range<usize>,
19703 adjusted_range: &mut Option<Range<usize>>,
19704 _: &mut Window,
19705 cx: &mut Context<Self>,
19706 ) -> Option<String> {
19707 let snapshot = self.buffer.read(cx).read(cx);
19708 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19709 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19710 if (start.0..end.0) != range_utf16 {
19711 adjusted_range.replace(start.0..end.0);
19712 }
19713 Some(snapshot.text_for_range(start..end).collect())
19714 }
19715
19716 fn selected_text_range(
19717 &mut self,
19718 ignore_disabled_input: bool,
19719 _: &mut Window,
19720 cx: &mut Context<Self>,
19721 ) -> Option<UTF16Selection> {
19722 // Prevent the IME menu from appearing when holding down an alphabetic key
19723 // while input is disabled.
19724 if !ignore_disabled_input && !self.input_enabled {
19725 return None;
19726 }
19727
19728 let selection = self.selections.newest::<OffsetUtf16>(cx);
19729 let range = selection.range();
19730
19731 Some(UTF16Selection {
19732 range: range.start.0..range.end.0,
19733 reversed: selection.reversed,
19734 })
19735 }
19736
19737 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19738 let snapshot = self.buffer.read(cx).read(cx);
19739 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19740 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19741 }
19742
19743 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19744 self.clear_highlights::<InputComposition>(cx);
19745 self.ime_transaction.take();
19746 }
19747
19748 fn replace_text_in_range(
19749 &mut self,
19750 range_utf16: Option<Range<usize>>,
19751 text: &str,
19752 window: &mut Window,
19753 cx: &mut Context<Self>,
19754 ) {
19755 if !self.input_enabled {
19756 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19757 return;
19758 }
19759
19760 self.transact(window, cx, |this, window, cx| {
19761 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19762 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19763 Some(this.selection_replacement_ranges(range_utf16, cx))
19764 } else {
19765 this.marked_text_ranges(cx)
19766 };
19767
19768 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19769 let newest_selection_id = this.selections.newest_anchor().id;
19770 this.selections
19771 .all::<OffsetUtf16>(cx)
19772 .iter()
19773 .zip(ranges_to_replace.iter())
19774 .find_map(|(selection, range)| {
19775 if selection.id == newest_selection_id {
19776 Some(
19777 (range.start.0 as isize - selection.head().0 as isize)
19778 ..(range.end.0 as isize - selection.head().0 as isize),
19779 )
19780 } else {
19781 None
19782 }
19783 })
19784 });
19785
19786 cx.emit(EditorEvent::InputHandled {
19787 utf16_range_to_replace: range_to_replace,
19788 text: text.into(),
19789 });
19790
19791 if let Some(new_selected_ranges) = new_selected_ranges {
19792 this.change_selections(None, window, cx, |selections| {
19793 selections.select_ranges(new_selected_ranges)
19794 });
19795 this.backspace(&Default::default(), window, cx);
19796 }
19797
19798 this.handle_input(text, window, cx);
19799 });
19800
19801 if let Some(transaction) = self.ime_transaction {
19802 self.buffer.update(cx, |buffer, cx| {
19803 buffer.group_until_transaction(transaction, cx);
19804 });
19805 }
19806
19807 self.unmark_text(window, cx);
19808 }
19809
19810 fn replace_and_mark_text_in_range(
19811 &mut self,
19812 range_utf16: Option<Range<usize>>,
19813 text: &str,
19814 new_selected_range_utf16: Option<Range<usize>>,
19815 window: &mut Window,
19816 cx: &mut Context<Self>,
19817 ) {
19818 if !self.input_enabled {
19819 return;
19820 }
19821
19822 let transaction = self.transact(window, cx, |this, window, cx| {
19823 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19824 let snapshot = this.buffer.read(cx).read(cx);
19825 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19826 for marked_range in &mut marked_ranges {
19827 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19828 marked_range.start.0 += relative_range_utf16.start;
19829 marked_range.start =
19830 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19831 marked_range.end =
19832 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19833 }
19834 }
19835 Some(marked_ranges)
19836 } else if let Some(range_utf16) = range_utf16 {
19837 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19838 Some(this.selection_replacement_ranges(range_utf16, cx))
19839 } else {
19840 None
19841 };
19842
19843 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19844 let newest_selection_id = this.selections.newest_anchor().id;
19845 this.selections
19846 .all::<OffsetUtf16>(cx)
19847 .iter()
19848 .zip(ranges_to_replace.iter())
19849 .find_map(|(selection, range)| {
19850 if selection.id == newest_selection_id {
19851 Some(
19852 (range.start.0 as isize - selection.head().0 as isize)
19853 ..(range.end.0 as isize - selection.head().0 as isize),
19854 )
19855 } else {
19856 None
19857 }
19858 })
19859 });
19860
19861 cx.emit(EditorEvent::InputHandled {
19862 utf16_range_to_replace: range_to_replace,
19863 text: text.into(),
19864 });
19865
19866 if let Some(ranges) = ranges_to_replace {
19867 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19868 }
19869
19870 let marked_ranges = {
19871 let snapshot = this.buffer.read(cx).read(cx);
19872 this.selections
19873 .disjoint_anchors()
19874 .iter()
19875 .map(|selection| {
19876 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19877 })
19878 .collect::<Vec<_>>()
19879 };
19880
19881 if text.is_empty() {
19882 this.unmark_text(window, cx);
19883 } else {
19884 this.highlight_text::<InputComposition>(
19885 marked_ranges.clone(),
19886 HighlightStyle {
19887 underline: Some(UnderlineStyle {
19888 thickness: px(1.),
19889 color: None,
19890 wavy: false,
19891 }),
19892 ..Default::default()
19893 },
19894 cx,
19895 );
19896 }
19897
19898 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19899 let use_autoclose = this.use_autoclose;
19900 let use_auto_surround = this.use_auto_surround;
19901 this.set_use_autoclose(false);
19902 this.set_use_auto_surround(false);
19903 this.handle_input(text, window, cx);
19904 this.set_use_autoclose(use_autoclose);
19905 this.set_use_auto_surround(use_auto_surround);
19906
19907 if let Some(new_selected_range) = new_selected_range_utf16 {
19908 let snapshot = this.buffer.read(cx).read(cx);
19909 let new_selected_ranges = marked_ranges
19910 .into_iter()
19911 .map(|marked_range| {
19912 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19913 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19914 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19915 snapshot.clip_offset_utf16(new_start, Bias::Left)
19916 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19917 })
19918 .collect::<Vec<_>>();
19919
19920 drop(snapshot);
19921 this.change_selections(None, window, cx, |selections| {
19922 selections.select_ranges(new_selected_ranges)
19923 });
19924 }
19925 });
19926
19927 self.ime_transaction = self.ime_transaction.or(transaction);
19928 if let Some(transaction) = self.ime_transaction {
19929 self.buffer.update(cx, |buffer, cx| {
19930 buffer.group_until_transaction(transaction, cx);
19931 });
19932 }
19933
19934 if self.text_highlights::<InputComposition>(cx).is_none() {
19935 self.ime_transaction.take();
19936 }
19937 }
19938
19939 fn bounds_for_range(
19940 &mut self,
19941 range_utf16: Range<usize>,
19942 element_bounds: gpui::Bounds<Pixels>,
19943 window: &mut Window,
19944 cx: &mut Context<Self>,
19945 ) -> Option<gpui::Bounds<Pixels>> {
19946 let text_layout_details = self.text_layout_details(window);
19947 let gpui::Size {
19948 width: em_width,
19949 height: line_height,
19950 } = self.character_size(window);
19951
19952 let snapshot = self.snapshot(window, cx);
19953 let scroll_position = snapshot.scroll_position();
19954 let scroll_left = scroll_position.x * em_width;
19955
19956 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19957 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19958 + self.gutter_dimensions.width
19959 + self.gutter_dimensions.margin;
19960 let y = line_height * (start.row().as_f32() - scroll_position.y);
19961
19962 Some(Bounds {
19963 origin: element_bounds.origin + point(x, y),
19964 size: size(em_width, line_height),
19965 })
19966 }
19967
19968 fn character_index_for_point(
19969 &mut self,
19970 point: gpui::Point<Pixels>,
19971 _window: &mut Window,
19972 _cx: &mut Context<Self>,
19973 ) -> Option<usize> {
19974 let position_map = self.last_position_map.as_ref()?;
19975 if !position_map.text_hitbox.contains(&point) {
19976 return None;
19977 }
19978 let display_point = position_map.point_for_position(point).previous_valid;
19979 let anchor = position_map
19980 .snapshot
19981 .display_point_to_anchor(display_point, Bias::Left);
19982 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19983 Some(utf16_offset.0)
19984 }
19985}
19986
19987trait SelectionExt {
19988 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19989 fn spanned_rows(
19990 &self,
19991 include_end_if_at_line_start: bool,
19992 map: &DisplaySnapshot,
19993 ) -> Range<MultiBufferRow>;
19994}
19995
19996impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19997 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19998 let start = self
19999 .start
20000 .to_point(&map.buffer_snapshot)
20001 .to_display_point(map);
20002 let end = self
20003 .end
20004 .to_point(&map.buffer_snapshot)
20005 .to_display_point(map);
20006 if self.reversed {
20007 end..start
20008 } else {
20009 start..end
20010 }
20011 }
20012
20013 fn spanned_rows(
20014 &self,
20015 include_end_if_at_line_start: bool,
20016 map: &DisplaySnapshot,
20017 ) -> Range<MultiBufferRow> {
20018 let start = self.start.to_point(&map.buffer_snapshot);
20019 let mut end = self.end.to_point(&map.buffer_snapshot);
20020 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20021 end.row -= 1;
20022 }
20023
20024 let buffer_start = map.prev_line_boundary(start).0;
20025 let buffer_end = map.next_line_boundary(end).0;
20026 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20027 }
20028}
20029
20030impl<T: InvalidationRegion> InvalidationStack<T> {
20031 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20032 where
20033 S: Clone + ToOffset,
20034 {
20035 while let Some(region) = self.last() {
20036 let all_selections_inside_invalidation_ranges =
20037 if selections.len() == region.ranges().len() {
20038 selections
20039 .iter()
20040 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20041 .all(|(selection, invalidation_range)| {
20042 let head = selection.head().to_offset(buffer);
20043 invalidation_range.start <= head && invalidation_range.end >= head
20044 })
20045 } else {
20046 false
20047 };
20048
20049 if all_selections_inside_invalidation_ranges {
20050 break;
20051 } else {
20052 self.pop();
20053 }
20054 }
20055 }
20056}
20057
20058impl<T> Default for InvalidationStack<T> {
20059 fn default() -> Self {
20060 Self(Default::default())
20061 }
20062}
20063
20064impl<T> Deref for InvalidationStack<T> {
20065 type Target = Vec<T>;
20066
20067 fn deref(&self) -> &Self::Target {
20068 &self.0
20069 }
20070}
20071
20072impl<T> DerefMut for InvalidationStack<T> {
20073 fn deref_mut(&mut self) -> &mut Self::Target {
20074 &mut self.0
20075 }
20076}
20077
20078impl InvalidationRegion for SnippetState {
20079 fn ranges(&self) -> &[Range<Anchor>] {
20080 &self.ranges[self.active_index]
20081 }
20082}
20083
20084pub fn diagnostic_block_renderer(
20085 diagnostic: Diagnostic,
20086 max_message_rows: Option<u8>,
20087 allow_closing: bool,
20088) -> RenderBlock {
20089 let (text_without_backticks, code_ranges) =
20090 highlight_diagnostic_message(&diagnostic, max_message_rows);
20091
20092 Arc::new(move |cx: &mut BlockContext| {
20093 let group_id: SharedString = cx.block_id.to_string().into();
20094
20095 let mut text_style = cx.window.text_style().clone();
20096 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
20097 let theme_settings = ThemeSettings::get_global(cx);
20098 text_style.font_family = theme_settings.buffer_font.family.clone();
20099 text_style.font_style = theme_settings.buffer_font.style;
20100 text_style.font_features = theme_settings.buffer_font.features.clone();
20101 text_style.font_weight = theme_settings.buffer_font.weight;
20102
20103 let multi_line_diagnostic = diagnostic.message.contains('\n');
20104
20105 let buttons = |diagnostic: &Diagnostic| {
20106 if multi_line_diagnostic {
20107 v_flex()
20108 } else {
20109 h_flex()
20110 }
20111 .when(allow_closing, |div| {
20112 div.children(diagnostic.is_primary.then(|| {
20113 IconButton::new("close-block", IconName::XCircle)
20114 .icon_color(Color::Muted)
20115 .size(ButtonSize::Compact)
20116 .style(ButtonStyle::Transparent)
20117 .visible_on_hover(group_id.clone())
20118 .on_click(move |_click, window, cx| {
20119 window.dispatch_action(Box::new(Cancel), cx)
20120 })
20121 .tooltip(|window, cx| {
20122 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
20123 })
20124 }))
20125 })
20126 .child(
20127 IconButton::new("copy-block", IconName::Copy)
20128 .icon_color(Color::Muted)
20129 .size(ButtonSize::Compact)
20130 .style(ButtonStyle::Transparent)
20131 .visible_on_hover(group_id.clone())
20132 .on_click({
20133 let message = diagnostic.message.clone();
20134 move |_click, _, cx| {
20135 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
20136 }
20137 })
20138 .tooltip(Tooltip::text("Copy diagnostic message")),
20139 )
20140 };
20141
20142 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
20143 AvailableSpace::min_size(),
20144 cx.window,
20145 cx.app,
20146 );
20147
20148 h_flex()
20149 .id(cx.block_id)
20150 .group(group_id.clone())
20151 .relative()
20152 .size_full()
20153 .block_mouse_down()
20154 .pl(cx.gutter_dimensions.width)
20155 .w(cx.max_width - cx.gutter_dimensions.full_width())
20156 .child(
20157 div()
20158 .flex()
20159 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
20160 .flex_shrink(),
20161 )
20162 .child(buttons(&diagnostic))
20163 .child(div().flex().flex_shrink_0().child(
20164 StyledText::new(text_without_backticks.clone()).with_default_highlights(
20165 &text_style,
20166 code_ranges.iter().map(|range| {
20167 (
20168 range.clone(),
20169 HighlightStyle {
20170 font_weight: Some(FontWeight::BOLD),
20171 ..Default::default()
20172 },
20173 )
20174 }),
20175 ),
20176 ))
20177 .into_any_element()
20178 })
20179}
20180
20181fn inline_completion_edit_text(
20182 current_snapshot: &BufferSnapshot,
20183 edits: &[(Range<Anchor>, String)],
20184 edit_preview: &EditPreview,
20185 include_deletions: bool,
20186 cx: &App,
20187) -> HighlightedText {
20188 let edits = edits
20189 .iter()
20190 .map(|(anchor, text)| {
20191 (
20192 anchor.start.text_anchor..anchor.end.text_anchor,
20193 text.clone(),
20194 )
20195 })
20196 .collect::<Vec<_>>();
20197
20198 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20199}
20200
20201pub fn highlight_diagnostic_message(
20202 diagnostic: &Diagnostic,
20203 mut max_message_rows: Option<u8>,
20204) -> (SharedString, Vec<Range<usize>>) {
20205 let mut text_without_backticks = String::new();
20206 let mut code_ranges = Vec::new();
20207
20208 if let Some(source) = &diagnostic.source {
20209 text_without_backticks.push_str(source);
20210 code_ranges.push(0..source.len());
20211 text_without_backticks.push_str(": ");
20212 }
20213
20214 let mut prev_offset = 0;
20215 let mut in_code_block = false;
20216 let has_row_limit = max_message_rows.is_some();
20217 let mut newline_indices = diagnostic
20218 .message
20219 .match_indices('\n')
20220 .filter(|_| has_row_limit)
20221 .map(|(ix, _)| ix)
20222 .fuse()
20223 .peekable();
20224
20225 for (quote_ix, _) in diagnostic
20226 .message
20227 .match_indices('`')
20228 .chain([(diagnostic.message.len(), "")])
20229 {
20230 let mut first_newline_ix = None;
20231 let mut last_newline_ix = None;
20232 while let Some(newline_ix) = newline_indices.peek() {
20233 if *newline_ix < quote_ix {
20234 if first_newline_ix.is_none() {
20235 first_newline_ix = Some(*newline_ix);
20236 }
20237 last_newline_ix = Some(*newline_ix);
20238
20239 if let Some(rows_left) = &mut max_message_rows {
20240 if *rows_left == 0 {
20241 break;
20242 } else {
20243 *rows_left -= 1;
20244 }
20245 }
20246 let _ = newline_indices.next();
20247 } else {
20248 break;
20249 }
20250 }
20251 let prev_len = text_without_backticks.len();
20252 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
20253 text_without_backticks.push_str(new_text);
20254 if in_code_block {
20255 code_ranges.push(prev_len..text_without_backticks.len());
20256 }
20257 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
20258 in_code_block = !in_code_block;
20259 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
20260 text_without_backticks.push_str("...");
20261 break;
20262 }
20263 }
20264
20265 (text_without_backticks.into(), code_ranges)
20266}
20267
20268fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20269 match severity {
20270 DiagnosticSeverity::ERROR => colors.error,
20271 DiagnosticSeverity::WARNING => colors.warning,
20272 DiagnosticSeverity::INFORMATION => colors.info,
20273 DiagnosticSeverity::HINT => colors.info,
20274 _ => colors.ignored,
20275 }
20276}
20277
20278pub fn styled_runs_for_code_label<'a>(
20279 label: &'a CodeLabel,
20280 syntax_theme: &'a theme::SyntaxTheme,
20281) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20282 let fade_out = HighlightStyle {
20283 fade_out: Some(0.35),
20284 ..Default::default()
20285 };
20286
20287 let mut prev_end = label.filter_range.end;
20288 label
20289 .runs
20290 .iter()
20291 .enumerate()
20292 .flat_map(move |(ix, (range, highlight_id))| {
20293 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20294 style
20295 } else {
20296 return Default::default();
20297 };
20298 let mut muted_style = style;
20299 muted_style.highlight(fade_out);
20300
20301 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20302 if range.start >= label.filter_range.end {
20303 if range.start > prev_end {
20304 runs.push((prev_end..range.start, fade_out));
20305 }
20306 runs.push((range.clone(), muted_style));
20307 } else if range.end <= label.filter_range.end {
20308 runs.push((range.clone(), style));
20309 } else {
20310 runs.push((range.start..label.filter_range.end, style));
20311 runs.push((label.filter_range.end..range.end, muted_style));
20312 }
20313 prev_end = cmp::max(prev_end, range.end);
20314
20315 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20316 runs.push((prev_end..label.text.len(), fade_out));
20317 }
20318
20319 runs
20320 })
20321}
20322
20323pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20324 let mut prev_index = 0;
20325 let mut prev_codepoint: Option<char> = None;
20326 text.char_indices()
20327 .chain([(text.len(), '\0')])
20328 .filter_map(move |(index, codepoint)| {
20329 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20330 let is_boundary = index == text.len()
20331 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20332 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20333 if is_boundary {
20334 let chunk = &text[prev_index..index];
20335 prev_index = index;
20336 Some(chunk)
20337 } else {
20338 None
20339 }
20340 })
20341}
20342
20343pub trait RangeToAnchorExt: Sized {
20344 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20345
20346 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20347 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20348 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20349 }
20350}
20351
20352impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20353 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20354 let start_offset = self.start.to_offset(snapshot);
20355 let end_offset = self.end.to_offset(snapshot);
20356 if start_offset == end_offset {
20357 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20358 } else {
20359 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20360 }
20361 }
20362}
20363
20364pub trait RowExt {
20365 fn as_f32(&self) -> f32;
20366
20367 fn next_row(&self) -> Self;
20368
20369 fn previous_row(&self) -> Self;
20370
20371 fn minus(&self, other: Self) -> u32;
20372}
20373
20374impl RowExt for DisplayRow {
20375 fn as_f32(&self) -> f32 {
20376 self.0 as f32
20377 }
20378
20379 fn next_row(&self) -> Self {
20380 Self(self.0 + 1)
20381 }
20382
20383 fn previous_row(&self) -> Self {
20384 Self(self.0.saturating_sub(1))
20385 }
20386
20387 fn minus(&self, other: Self) -> u32 {
20388 self.0 - other.0
20389 }
20390}
20391
20392impl RowExt for MultiBufferRow {
20393 fn as_f32(&self) -> f32 {
20394 self.0 as f32
20395 }
20396
20397 fn next_row(&self) -> Self {
20398 Self(self.0 + 1)
20399 }
20400
20401 fn previous_row(&self) -> Self {
20402 Self(self.0.saturating_sub(1))
20403 }
20404
20405 fn minus(&self, other: Self) -> u32 {
20406 self.0 - other.0
20407 }
20408}
20409
20410trait RowRangeExt {
20411 type Row;
20412
20413 fn len(&self) -> usize;
20414
20415 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20416}
20417
20418impl RowRangeExt for Range<MultiBufferRow> {
20419 type Row = MultiBufferRow;
20420
20421 fn len(&self) -> usize {
20422 (self.end.0 - self.start.0) as usize
20423 }
20424
20425 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20426 (self.start.0..self.end.0).map(MultiBufferRow)
20427 }
20428}
20429
20430impl RowRangeExt for Range<DisplayRow> {
20431 type Row = DisplayRow;
20432
20433 fn len(&self) -> usize {
20434 (self.end.0 - self.start.0) as usize
20435 }
20436
20437 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20438 (self.start.0..self.end.0).map(DisplayRow)
20439 }
20440}
20441
20442/// If select range has more than one line, we
20443/// just point the cursor to range.start.
20444fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20445 if range.start.row == range.end.row {
20446 range
20447 } else {
20448 range.start..range.start
20449 }
20450}
20451pub struct KillRing(ClipboardItem);
20452impl Global for KillRing {}
20453
20454const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20455
20456enum BreakpointPromptEditAction {
20457 Log,
20458 Condition,
20459 HitCondition,
20460}
20461
20462struct BreakpointPromptEditor {
20463 pub(crate) prompt: Entity<Editor>,
20464 editor: WeakEntity<Editor>,
20465 breakpoint_anchor: Anchor,
20466 breakpoint: Breakpoint,
20467 edit_action: BreakpointPromptEditAction,
20468 block_ids: HashSet<CustomBlockId>,
20469 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20470 _subscriptions: Vec<Subscription>,
20471}
20472
20473impl BreakpointPromptEditor {
20474 const MAX_LINES: u8 = 4;
20475
20476 fn new(
20477 editor: WeakEntity<Editor>,
20478 breakpoint_anchor: Anchor,
20479 breakpoint: Breakpoint,
20480 edit_action: BreakpointPromptEditAction,
20481 window: &mut Window,
20482 cx: &mut Context<Self>,
20483 ) -> Self {
20484 let base_text = match edit_action {
20485 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20486 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20487 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20488 }
20489 .map(|msg| msg.to_string())
20490 .unwrap_or_default();
20491
20492 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20493 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20494
20495 let prompt = cx.new(|cx| {
20496 let mut prompt = Editor::new(
20497 EditorMode::AutoHeight {
20498 max_lines: Self::MAX_LINES as usize,
20499 },
20500 buffer,
20501 None,
20502 window,
20503 cx,
20504 );
20505 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20506 prompt.set_show_cursor_when_unfocused(false, cx);
20507 prompt.set_placeholder_text(
20508 match edit_action {
20509 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20510 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20511 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20512 },
20513 cx,
20514 );
20515
20516 prompt
20517 });
20518
20519 Self {
20520 prompt,
20521 editor,
20522 breakpoint_anchor,
20523 breakpoint,
20524 edit_action,
20525 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20526 block_ids: Default::default(),
20527 _subscriptions: vec![],
20528 }
20529 }
20530
20531 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20532 self.block_ids.extend(block_ids)
20533 }
20534
20535 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20536 if let Some(editor) = self.editor.upgrade() {
20537 let message = self
20538 .prompt
20539 .read(cx)
20540 .buffer
20541 .read(cx)
20542 .as_singleton()
20543 .expect("A multi buffer in breakpoint prompt isn't possible")
20544 .read(cx)
20545 .as_rope()
20546 .to_string();
20547
20548 editor.update(cx, |editor, cx| {
20549 editor.edit_breakpoint_at_anchor(
20550 self.breakpoint_anchor,
20551 self.breakpoint.clone(),
20552 match self.edit_action {
20553 BreakpointPromptEditAction::Log => {
20554 BreakpointEditAction::EditLogMessage(message.into())
20555 }
20556 BreakpointPromptEditAction::Condition => {
20557 BreakpointEditAction::EditCondition(message.into())
20558 }
20559 BreakpointPromptEditAction::HitCondition => {
20560 BreakpointEditAction::EditHitCondition(message.into())
20561 }
20562 },
20563 cx,
20564 );
20565
20566 editor.remove_blocks(self.block_ids.clone(), None, cx);
20567 cx.focus_self(window);
20568 });
20569 }
20570 }
20571
20572 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20573 self.editor
20574 .update(cx, |editor, cx| {
20575 editor.remove_blocks(self.block_ids.clone(), None, cx);
20576 window.focus(&editor.focus_handle);
20577 })
20578 .log_err();
20579 }
20580
20581 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20582 let settings = ThemeSettings::get_global(cx);
20583 let text_style = TextStyle {
20584 color: if self.prompt.read(cx).read_only(cx) {
20585 cx.theme().colors().text_disabled
20586 } else {
20587 cx.theme().colors().text
20588 },
20589 font_family: settings.buffer_font.family.clone(),
20590 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20591 font_size: settings.buffer_font_size(cx).into(),
20592 font_weight: settings.buffer_font.weight,
20593 line_height: relative(settings.buffer_line_height.value()),
20594 ..Default::default()
20595 };
20596 EditorElement::new(
20597 &self.prompt,
20598 EditorStyle {
20599 background: cx.theme().colors().editor_background,
20600 local_player: cx.theme().players().local(),
20601 text: text_style,
20602 ..Default::default()
20603 },
20604 )
20605 }
20606}
20607
20608impl Render for BreakpointPromptEditor {
20609 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20610 let gutter_dimensions = *self.gutter_dimensions.lock();
20611 h_flex()
20612 .key_context("Editor")
20613 .bg(cx.theme().colors().editor_background)
20614 .border_y_1()
20615 .border_color(cx.theme().status().info_border)
20616 .size_full()
20617 .py(window.line_height() / 2.5)
20618 .on_action(cx.listener(Self::confirm))
20619 .on_action(cx.listener(Self::cancel))
20620 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20621 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20622 }
20623}
20624
20625impl Focusable for BreakpointPromptEditor {
20626 fn focus_handle(&self, cx: &App) -> FocusHandle {
20627 self.prompt.focus_handle(cx)
20628 }
20629}
20630
20631fn all_edits_insertions_or_deletions(
20632 edits: &Vec<(Range<Anchor>, String)>,
20633 snapshot: &MultiBufferSnapshot,
20634) -> bool {
20635 let mut all_insertions = true;
20636 let mut all_deletions = true;
20637
20638 for (range, new_text) in edits.iter() {
20639 let range_is_empty = range.to_offset(&snapshot).is_empty();
20640 let text_is_empty = new_text.is_empty();
20641
20642 if range_is_empty != text_is_empty {
20643 if range_is_empty {
20644 all_deletions = false;
20645 } else {
20646 all_insertions = false;
20647 }
20648 } else {
20649 return false;
20650 }
20651
20652 if !all_insertions && !all_deletions {
20653 return false;
20654 }
20655 }
20656 all_insertions || all_deletions
20657}
20658
20659struct MissingEditPredictionKeybindingTooltip;
20660
20661impl Render for MissingEditPredictionKeybindingTooltip {
20662 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20663 ui::tooltip_container(window, cx, |container, _, cx| {
20664 container
20665 .flex_shrink_0()
20666 .max_w_80()
20667 .min_h(rems_from_px(124.))
20668 .justify_between()
20669 .child(
20670 v_flex()
20671 .flex_1()
20672 .text_ui_sm(cx)
20673 .child(Label::new("Conflict with Accept Keybinding"))
20674 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20675 )
20676 .child(
20677 h_flex()
20678 .pb_1()
20679 .gap_1()
20680 .items_end()
20681 .w_full()
20682 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20683 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20684 }))
20685 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20686 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20687 })),
20688 )
20689 })
20690 }
20691}
20692
20693#[derive(Debug, Clone, Copy, PartialEq)]
20694pub struct LineHighlight {
20695 pub background: Background,
20696 pub border: Option<gpui::Hsla>,
20697}
20698
20699impl From<Hsla> for LineHighlight {
20700 fn from(hsla: Hsla) -> Self {
20701 Self {
20702 background: hsla.into(),
20703 border: None,
20704 }
20705 }
20706}
20707
20708impl From<Background> for LineHighlight {
20709 fn from(background: Background) -> Self {
20710 Self {
20711 background,
20712 border: None,
20713 }
20714 }
20715}
20716
20717fn render_diff_hunk_controls(
20718 row: u32,
20719 status: &DiffHunkStatus,
20720 hunk_range: Range<Anchor>,
20721 is_created_file: bool,
20722 line_height: Pixels,
20723 editor: &Entity<Editor>,
20724 _window: &mut Window,
20725 cx: &mut App,
20726) -> AnyElement {
20727 h_flex()
20728 .h(line_height)
20729 .mr_1()
20730 .gap_1()
20731 .px_0p5()
20732 .pb_1()
20733 .border_x_1()
20734 .border_b_1()
20735 .border_color(cx.theme().colors().border_variant)
20736 .rounded_b_lg()
20737 .bg(cx.theme().colors().editor_background)
20738 .gap_1()
20739 .occlude()
20740 .shadow_md()
20741 .child(if status.has_secondary_hunk() {
20742 Button::new(("stage", row as u64), "Stage")
20743 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20744 .tooltip({
20745 let focus_handle = editor.focus_handle(cx);
20746 move |window, cx| {
20747 Tooltip::for_action_in(
20748 "Stage Hunk",
20749 &::git::ToggleStaged,
20750 &focus_handle,
20751 window,
20752 cx,
20753 )
20754 }
20755 })
20756 .on_click({
20757 let editor = editor.clone();
20758 move |_event, _window, cx| {
20759 editor.update(cx, |editor, cx| {
20760 editor.stage_or_unstage_diff_hunks(
20761 true,
20762 vec![hunk_range.start..hunk_range.start],
20763 cx,
20764 );
20765 });
20766 }
20767 })
20768 } else {
20769 Button::new(("unstage", row as u64), "Unstage")
20770 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20771 .tooltip({
20772 let focus_handle = editor.focus_handle(cx);
20773 move |window, cx| {
20774 Tooltip::for_action_in(
20775 "Unstage Hunk",
20776 &::git::ToggleStaged,
20777 &focus_handle,
20778 window,
20779 cx,
20780 )
20781 }
20782 })
20783 .on_click({
20784 let editor = editor.clone();
20785 move |_event, _window, cx| {
20786 editor.update(cx, |editor, cx| {
20787 editor.stage_or_unstage_diff_hunks(
20788 false,
20789 vec![hunk_range.start..hunk_range.start],
20790 cx,
20791 );
20792 });
20793 }
20794 })
20795 })
20796 .child(
20797 Button::new(("restore", row as u64), "Restore")
20798 .tooltip({
20799 let focus_handle = editor.focus_handle(cx);
20800 move |window, cx| {
20801 Tooltip::for_action_in(
20802 "Restore Hunk",
20803 &::git::Restore,
20804 &focus_handle,
20805 window,
20806 cx,
20807 )
20808 }
20809 })
20810 .on_click({
20811 let editor = editor.clone();
20812 move |_event, window, cx| {
20813 editor.update(cx, |editor, cx| {
20814 let snapshot = editor.snapshot(window, cx);
20815 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20816 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20817 });
20818 }
20819 })
20820 .disabled(is_created_file),
20821 )
20822 .when(
20823 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20824 |el| {
20825 el.child(
20826 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20827 .shape(IconButtonShape::Square)
20828 .icon_size(IconSize::Small)
20829 // .disabled(!has_multiple_hunks)
20830 .tooltip({
20831 let focus_handle = editor.focus_handle(cx);
20832 move |window, cx| {
20833 Tooltip::for_action_in(
20834 "Next Hunk",
20835 &GoToHunk,
20836 &focus_handle,
20837 window,
20838 cx,
20839 )
20840 }
20841 })
20842 .on_click({
20843 let editor = editor.clone();
20844 move |_event, window, cx| {
20845 editor.update(cx, |editor, cx| {
20846 let snapshot = editor.snapshot(window, cx);
20847 let position =
20848 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20849 editor.go_to_hunk_before_or_after_position(
20850 &snapshot,
20851 position,
20852 Direction::Next,
20853 window,
20854 cx,
20855 );
20856 editor.expand_selected_diff_hunks(cx);
20857 });
20858 }
20859 }),
20860 )
20861 .child(
20862 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20863 .shape(IconButtonShape::Square)
20864 .icon_size(IconSize::Small)
20865 // .disabled(!has_multiple_hunks)
20866 .tooltip({
20867 let focus_handle = editor.focus_handle(cx);
20868 move |window, cx| {
20869 Tooltip::for_action_in(
20870 "Previous Hunk",
20871 &GoToPreviousHunk,
20872 &focus_handle,
20873 window,
20874 cx,
20875 )
20876 }
20877 })
20878 .on_click({
20879 let editor = editor.clone();
20880 move |_event, window, cx| {
20881 editor.update(cx, |editor, cx| {
20882 let snapshot = editor.snapshot(window, cx);
20883 let point =
20884 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20885 editor.go_to_hunk_before_or_after_position(
20886 &snapshot,
20887 point,
20888 Direction::Prev,
20889 window,
20890 cx,
20891 );
20892 editor.expand_selected_diff_hunks(cx);
20893 });
20894 }
20895 }),
20896 )
20897 },
20898 )
20899 .into_any_element()
20900}