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;
26pub mod 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, Subscription, Task, TextStyle, TextStyleRefinement,
92 UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
93 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
94};
95use highlight_matching_bracket::refresh_matching_bracket_highlights;
96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
97pub use hover_popover::hover_markdown_style;
98use hover_popover::{HoverState, hide_hover};
99use indent_guides::ActiveIndentGuidesState;
100use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
101pub use inline_completion::Direction;
102use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
103pub use items::MAX_TAB_TITLE_LEN;
104use itertools::Itertools;
105use language::{
106 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
107 CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
108 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
109 TransactionId, TreeSitterOptions, WordsQuery,
110 language_settings::{
111 self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
112 all_language_settings, language_settings,
113 },
114 point_from_lsp, text_diff_with_options,
115};
116use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
117use linked_editing_ranges::refresh_linked_ranges;
118use mouse_context_menu::MouseContextMenu;
119use persistence::DB;
120use project::{
121 ProjectPath,
122 debugger::breakpoint_store::{
123 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
124 },
125};
126
127pub use git::blame::BlameRenderer;
128pub use proposed_changes_editor::{
129 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
130};
131use smallvec::smallvec;
132use std::{cell::OnceCell, iter::Peekable};
133use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
134
135pub use lsp::CompletionContext;
136use lsp::{
137 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
138 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
139};
140
141use language::BufferSnapshot;
142pub use lsp_ext::lsp_tasks;
143use movement::TextLayoutDetails;
144pub use multi_buffer::{
145 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
146 RowInfo, ToOffset, ToPoint,
147};
148use multi_buffer::{
149 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
150 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
151};
152use parking_lot::Mutex;
153use project::{
154 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
155 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
156 TaskSourceKind,
157 debugger::breakpoint_store::Breakpoint,
158 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
159 project_settings::{GitGutterSetting, ProjectSettings},
160};
161use rand::prelude::*;
162use rpc::{ErrorExt, proto::*};
163use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
164use selections_collection::{
165 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
166};
167use serde::{Deserialize, Serialize};
168use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
169use smallvec::SmallVec;
170use snippet::Snippet;
171use std::sync::Arc;
172use std::{
173 any::TypeId,
174 borrow::Cow,
175 cell::RefCell,
176 cmp::{self, Ordering, Reverse},
177 mem,
178 num::NonZeroU32,
179 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
180 path::{Path, PathBuf},
181 rc::Rc,
182 time::{Duration, Instant},
183};
184pub use sum_tree::Bias;
185use sum_tree::TreeMap;
186use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
187use theme::{
188 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
189 observe_buffer_font_size_adjustment,
190};
191use ui::{
192 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
193 IconSize, Key, Tooltip, h_flex, prelude::*,
194};
195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
196use workspace::{
197 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
198 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
199 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
200 item::{ItemHandle, PreviewTabsSettings},
201 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
202 searchable::SearchEvent,
203};
204
205use crate::hover_links::{find_url, find_url_from_range};
206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
207
208pub const FILE_HEADER_HEIGHT: u32 = 2;
209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
212const MAX_LINE_LEN: usize = 1024;
213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
216#[doc(hidden)]
217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
218const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
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 trait DiagnosticRenderer {
360 fn render_group(
361 &self,
362 diagnostic_group: Vec<DiagnosticEntry<Point>>,
363 buffer_id: BufferId,
364 snapshot: EditorSnapshot,
365 editor: WeakEntity<Editor>,
366 cx: &mut App,
367 ) -> Vec<BlockProperties<Anchor>>;
368}
369
370pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
371
372impl gpui::Global for GlobalDiagnosticRenderer {}
373pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
374 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
375}
376
377pub struct SearchWithinRange;
378
379trait InvalidationRegion {
380 fn ranges(&self) -> &[Range<Anchor>];
381}
382
383#[derive(Clone, Debug, PartialEq)]
384pub enum SelectPhase {
385 Begin {
386 position: DisplayPoint,
387 add: bool,
388 click_count: usize,
389 },
390 BeginColumnar {
391 position: DisplayPoint,
392 reset: bool,
393 goal_column: u32,
394 },
395 Extend {
396 position: DisplayPoint,
397 click_count: usize,
398 },
399 Update {
400 position: DisplayPoint,
401 goal_column: u32,
402 scroll_delta: gpui::Point<f32>,
403 },
404 End,
405}
406
407#[derive(Clone, Debug)]
408pub enum SelectMode {
409 Character,
410 Word(Range<Anchor>),
411 Line(Range<Anchor>),
412 All,
413}
414
415#[derive(Copy, Clone, PartialEq, Eq, Debug)]
416pub enum EditorMode {
417 SingleLine {
418 auto_width: bool,
419 },
420 AutoHeight {
421 max_lines: usize,
422 },
423 Full {
424 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
425 scale_ui_elements_with_buffer_font_size: bool,
426 /// When set to `true`, the editor will render a background for the active line.
427 show_active_line_background: bool,
428 },
429}
430
431impl EditorMode {
432 pub fn full() -> Self {
433 Self::Full {
434 scale_ui_elements_with_buffer_font_size: true,
435 show_active_line_background: true,
436 }
437 }
438
439 pub fn is_full(&self) -> bool {
440 matches!(self, Self::Full { .. })
441 }
442}
443
444#[derive(Copy, Clone, Debug)]
445pub enum SoftWrap {
446 /// Prefer not to wrap at all.
447 ///
448 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
449 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
450 GitDiff,
451 /// Prefer a single line generally, unless an overly long line is encountered.
452 None,
453 /// Soft wrap lines that exceed the editor width.
454 EditorWidth,
455 /// Soft wrap lines at the preferred line length.
456 Column(u32),
457 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
458 Bounded(u32),
459}
460
461#[derive(Clone)]
462pub struct EditorStyle {
463 pub background: Hsla,
464 pub local_player: PlayerColor,
465 pub text: TextStyle,
466 pub scrollbar_width: Pixels,
467 pub syntax: Arc<SyntaxTheme>,
468 pub status: StatusColors,
469 pub inlay_hints_style: HighlightStyle,
470 pub inline_completion_styles: InlineCompletionStyles,
471 pub unnecessary_code_fade: f32,
472}
473
474impl Default for EditorStyle {
475 fn default() -> Self {
476 Self {
477 background: Hsla::default(),
478 local_player: PlayerColor::default(),
479 text: TextStyle::default(),
480 scrollbar_width: Pixels::default(),
481 syntax: Default::default(),
482 // HACK: Status colors don't have a real default.
483 // We should look into removing the status colors from the editor
484 // style and retrieve them directly from the theme.
485 status: StatusColors::dark(),
486 inlay_hints_style: HighlightStyle::default(),
487 inline_completion_styles: InlineCompletionStyles {
488 insertion: HighlightStyle::default(),
489 whitespace: HighlightStyle::default(),
490 },
491 unnecessary_code_fade: Default::default(),
492 }
493 }
494}
495
496pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
497 let show_background = language_settings::language_settings(None, None, cx)
498 .inlay_hints
499 .show_background;
500
501 HighlightStyle {
502 color: Some(cx.theme().status().hint),
503 background_color: show_background.then(|| cx.theme().status().hint_background),
504 ..HighlightStyle::default()
505 }
506}
507
508pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
509 InlineCompletionStyles {
510 insertion: HighlightStyle {
511 color: Some(cx.theme().status().predictive),
512 ..HighlightStyle::default()
513 },
514 whitespace: HighlightStyle {
515 background_color: Some(cx.theme().status().created_background),
516 ..HighlightStyle::default()
517 },
518 }
519}
520
521type CompletionId = usize;
522
523pub(crate) enum EditDisplayMode {
524 TabAccept,
525 DiffPopover,
526 Inline,
527}
528
529enum InlineCompletion {
530 Edit {
531 edits: Vec<(Range<Anchor>, String)>,
532 edit_preview: Option<EditPreview>,
533 display_mode: EditDisplayMode,
534 snapshot: BufferSnapshot,
535 },
536 Move {
537 target: Anchor,
538 snapshot: BufferSnapshot,
539 },
540}
541
542struct InlineCompletionState {
543 inlay_ids: Vec<InlayId>,
544 completion: InlineCompletion,
545 completion_id: Option<SharedString>,
546 invalidation_range: Range<Anchor>,
547}
548
549enum EditPredictionSettings {
550 Disabled,
551 Enabled {
552 show_in_menu: bool,
553 preview_requires_modifier: bool,
554 },
555}
556
557enum InlineCompletionHighlight {}
558
559#[derive(Debug, Clone)]
560struct InlineDiagnostic {
561 message: SharedString,
562 group_id: usize,
563 is_primary: bool,
564 start: Point,
565 severity: DiagnosticSeverity,
566}
567
568pub enum MenuInlineCompletionsPolicy {
569 Never,
570 ByProvider,
571}
572
573pub enum EditPredictionPreview {
574 /// Modifier is not pressed
575 Inactive { released_too_fast: bool },
576 /// Modifier pressed
577 Active {
578 since: Instant,
579 previous_scroll_position: Option<ScrollAnchor>,
580 },
581}
582
583impl EditPredictionPreview {
584 pub fn released_too_fast(&self) -> bool {
585 match self {
586 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
587 EditPredictionPreview::Active { .. } => false,
588 }
589 }
590
591 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
592 if let EditPredictionPreview::Active {
593 previous_scroll_position,
594 ..
595 } = self
596 {
597 *previous_scroll_position = scroll_position;
598 }
599 }
600}
601
602pub struct ContextMenuOptions {
603 pub min_entries_visible: usize,
604 pub max_entries_visible: usize,
605 pub placement: Option<ContextMenuPlacement>,
606}
607
608#[derive(Debug, Clone, PartialEq, Eq)]
609pub enum ContextMenuPlacement {
610 Above,
611 Below,
612}
613
614#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
615struct EditorActionId(usize);
616
617impl EditorActionId {
618 pub fn post_inc(&mut self) -> Self {
619 let answer = self.0;
620
621 *self = Self(answer + 1);
622
623 Self(answer)
624 }
625}
626
627// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
628// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
629
630type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
631type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
632
633#[derive(Default)]
634struct ScrollbarMarkerState {
635 scrollbar_size: Size<Pixels>,
636 dirty: bool,
637 markers: Arc<[PaintQuad]>,
638 pending_refresh: Option<Task<Result<()>>>,
639}
640
641impl ScrollbarMarkerState {
642 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
643 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
644 }
645}
646
647#[derive(Clone, Debug)]
648struct RunnableTasks {
649 templates: Vec<(TaskSourceKind, TaskTemplate)>,
650 offset: multi_buffer::Anchor,
651 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
652 column: u32,
653 // Values of all named captures, including those starting with '_'
654 extra_variables: HashMap<String, String>,
655 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
656 context_range: Range<BufferOffset>,
657}
658
659impl RunnableTasks {
660 fn resolve<'a>(
661 &'a self,
662 cx: &'a task::TaskContext,
663 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
664 self.templates.iter().filter_map(|(kind, template)| {
665 template
666 .resolve_task(&kind.to_id_base(), cx)
667 .map(|task| (kind.clone(), task))
668 })
669 }
670}
671
672#[derive(Clone)]
673struct ResolvedTasks {
674 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
675 position: Anchor,
676}
677
678#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
679struct BufferOffset(usize);
680
681// Addons allow storing per-editor state in other crates (e.g. Vim)
682pub trait Addon: 'static {
683 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
684
685 fn render_buffer_header_controls(
686 &self,
687 _: &ExcerptInfo,
688 _: &Window,
689 _: &App,
690 ) -> Option<AnyElement> {
691 None
692 }
693
694 fn to_any(&self) -> &dyn std::any::Any;
695}
696
697/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
698///
699/// See the [module level documentation](self) for more information.
700pub struct Editor {
701 focus_handle: FocusHandle,
702 last_focused_descendant: Option<WeakFocusHandle>,
703 /// The text buffer being edited
704 buffer: Entity<MultiBuffer>,
705 /// Map of how text in the buffer should be displayed.
706 /// Handles soft wraps, folds, fake inlay text insertions, etc.
707 pub display_map: Entity<DisplayMap>,
708 pub selections: SelectionsCollection,
709 pub scroll_manager: ScrollManager,
710 /// When inline assist editors are linked, they all render cursors because
711 /// typing enters text into each of them, even the ones that aren't focused.
712 pub(crate) show_cursor_when_unfocused: bool,
713 columnar_selection_tail: Option<Anchor>,
714 add_selections_state: Option<AddSelectionsState>,
715 select_next_state: Option<SelectNextState>,
716 select_prev_state: Option<SelectNextState>,
717 selection_history: SelectionHistory,
718 autoclose_regions: Vec<AutocloseRegion>,
719 snippet_stack: InvalidationStack<SnippetState>,
720 select_syntax_node_history: SelectSyntaxNodeHistory,
721 ime_transaction: Option<TransactionId>,
722 active_diagnostics: ActiveDiagnostic,
723 show_inline_diagnostics: bool,
724 inline_diagnostics_update: Task<()>,
725 inline_diagnostics_enabled: bool,
726 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
727 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
728 hard_wrap: Option<usize>,
729
730 // TODO: make this a access method
731 pub project: Option<Entity<Project>>,
732 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
733 completion_provider: Option<Box<dyn CompletionProvider>>,
734 collaboration_hub: Option<Box<dyn CollaborationHub>>,
735 blink_manager: Entity<BlinkManager>,
736 show_cursor_names: bool,
737 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
738 pub show_local_selections: bool,
739 mode: EditorMode,
740 show_breadcrumbs: bool,
741 show_gutter: bool,
742 show_scrollbars: bool,
743 show_line_numbers: Option<bool>,
744 use_relative_line_numbers: Option<bool>,
745 show_git_diff_gutter: Option<bool>,
746 show_code_actions: Option<bool>,
747 show_runnables: Option<bool>,
748 show_breakpoints: Option<bool>,
749 show_wrap_guides: Option<bool>,
750 show_indent_guides: Option<bool>,
751 placeholder_text: Option<Arc<str>>,
752 highlight_order: usize,
753 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
754 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
755 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
756 scrollbar_marker_state: ScrollbarMarkerState,
757 active_indent_guides_state: ActiveIndentGuidesState,
758 nav_history: Option<ItemNavHistory>,
759 context_menu: RefCell<Option<CodeContextMenu>>,
760 context_menu_options: Option<ContextMenuOptions>,
761 mouse_context_menu: Option<MouseContextMenu>,
762 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
763 signature_help_state: SignatureHelpState,
764 auto_signature_help: Option<bool>,
765 find_all_references_task_sources: Vec<Anchor>,
766 next_completion_id: CompletionId,
767 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
768 code_actions_task: Option<Task<Result<()>>>,
769 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
770 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
771 document_highlights_task: Option<Task<()>>,
772 linked_editing_range_task: Option<Task<Option<()>>>,
773 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
774 pending_rename: Option<RenameState>,
775 searchable: bool,
776 cursor_shape: CursorShape,
777 current_line_highlight: Option<CurrentLineHighlight>,
778 collapse_matches: bool,
779 autoindent_mode: Option<AutoindentMode>,
780 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
781 input_enabled: bool,
782 use_modal_editing: bool,
783 read_only: bool,
784 leader_peer_id: Option<PeerId>,
785 remote_id: Option<ViewId>,
786 hover_state: HoverState,
787 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
788 gutter_hovered: bool,
789 hovered_link_state: Option<HoveredLinkState>,
790 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
791 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
792 active_inline_completion: Option<InlineCompletionState>,
793 /// Used to prevent flickering as the user types while the menu is open
794 stale_inline_completion_in_menu: Option<InlineCompletionState>,
795 edit_prediction_settings: EditPredictionSettings,
796 inline_completions_hidden_for_vim_mode: bool,
797 show_inline_completions_override: Option<bool>,
798 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
799 edit_prediction_preview: EditPredictionPreview,
800 edit_prediction_indent_conflict: bool,
801 edit_prediction_requires_modifier_in_indent_conflict: bool,
802 inlay_hint_cache: InlayHintCache,
803 next_inlay_id: usize,
804 _subscriptions: Vec<Subscription>,
805 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
806 gutter_dimensions: GutterDimensions,
807 style: Option<EditorStyle>,
808 text_style_refinement: Option<TextStyleRefinement>,
809 next_editor_action_id: EditorActionId,
810 editor_actions:
811 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
812 use_autoclose: bool,
813 use_auto_surround: bool,
814 auto_replace_emoji_shortcode: bool,
815 jsx_tag_auto_close_enabled_in_any_buffer: bool,
816 show_git_blame_gutter: bool,
817 show_git_blame_inline: bool,
818 show_git_blame_inline_delay_task: Option<Task<()>>,
819 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
820 git_blame_inline_enabled: bool,
821 render_diff_hunk_controls: RenderDiffHunkControlsFn,
822 serialize_dirty_buffers: bool,
823 show_selection_menu: Option<bool>,
824 blame: Option<Entity<GitBlame>>,
825 blame_subscription: Option<Subscription>,
826 custom_context_menu: Option<
827 Box<
828 dyn 'static
829 + Fn(
830 &mut Self,
831 DisplayPoint,
832 &mut Window,
833 &mut Context<Self>,
834 ) -> Option<Entity<ui::ContextMenu>>,
835 >,
836 >,
837 last_bounds: Option<Bounds<Pixels>>,
838 last_position_map: Option<Rc<PositionMap>>,
839 expect_bounds_change: Option<Bounds<Pixels>>,
840 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
841 tasks_update_task: Option<Task<()>>,
842 breakpoint_store: Option<Entity<BreakpointStore>>,
843 /// Allow's a user to create a breakpoint by selecting this indicator
844 /// It should be None while a user is not hovering over the gutter
845 /// Otherwise it represents the point that the breakpoint will be shown
846 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
847 in_project_search: bool,
848 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
849 breadcrumb_header: Option<String>,
850 focused_block: Option<FocusedBlock>,
851 next_scroll_position: NextScrollCursorCenterTopBottom,
852 addons: HashMap<TypeId, Box<dyn Addon>>,
853 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
854 load_diff_task: Option<Shared<Task<()>>>,
855 selection_mark_mode: bool,
856 toggle_fold_multiple_buffers: Task<()>,
857 _scroll_cursor_center_top_bottom_task: Task<()>,
858 serialize_selections: Task<()>,
859 serialize_folds: Task<()>,
860 mouse_cursor_hidden: bool,
861 hide_mouse_mode: HideMouseMode,
862}
863
864#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
865enum NextScrollCursorCenterTopBottom {
866 #[default]
867 Center,
868 Top,
869 Bottom,
870}
871
872impl NextScrollCursorCenterTopBottom {
873 fn next(&self) -> Self {
874 match self {
875 Self::Center => Self::Top,
876 Self::Top => Self::Bottom,
877 Self::Bottom => Self::Center,
878 }
879 }
880}
881
882#[derive(Clone)]
883pub struct EditorSnapshot {
884 pub mode: EditorMode,
885 show_gutter: bool,
886 show_line_numbers: Option<bool>,
887 show_git_diff_gutter: Option<bool>,
888 show_code_actions: Option<bool>,
889 show_runnables: Option<bool>,
890 show_breakpoints: Option<bool>,
891 git_blame_gutter_max_author_length: Option<usize>,
892 pub display_snapshot: DisplaySnapshot,
893 pub placeholder_text: Option<Arc<str>>,
894 is_focused: bool,
895 scroll_anchor: ScrollAnchor,
896 ongoing_scroll: OngoingScroll,
897 current_line_highlight: CurrentLineHighlight,
898 gutter_hovered: bool,
899}
900
901#[derive(Default, Debug, Clone, Copy)]
902pub struct GutterDimensions {
903 pub left_padding: Pixels,
904 pub right_padding: Pixels,
905 pub width: Pixels,
906 pub margin: Pixels,
907 pub git_blame_entries_width: Option<Pixels>,
908}
909
910impl GutterDimensions {
911 /// The full width of the space taken up by the gutter.
912 pub fn full_width(&self) -> Pixels {
913 self.margin + self.width
914 }
915
916 /// The width of the space reserved for the fold indicators,
917 /// use alongside 'justify_end' and `gutter_width` to
918 /// right align content with the line numbers
919 pub fn fold_area_width(&self) -> Pixels {
920 self.margin + self.right_padding
921 }
922}
923
924#[derive(Debug)]
925pub struct RemoteSelection {
926 pub replica_id: ReplicaId,
927 pub selection: Selection<Anchor>,
928 pub cursor_shape: CursorShape,
929 pub peer_id: PeerId,
930 pub line_mode: bool,
931 pub participant_index: Option<ParticipantIndex>,
932 pub user_name: Option<SharedString>,
933}
934
935#[derive(Clone, Debug)]
936struct SelectionHistoryEntry {
937 selections: Arc<[Selection<Anchor>]>,
938 select_next_state: Option<SelectNextState>,
939 select_prev_state: Option<SelectNextState>,
940 add_selections_state: Option<AddSelectionsState>,
941}
942
943enum SelectionHistoryMode {
944 Normal,
945 Undoing,
946 Redoing,
947}
948
949#[derive(Clone, PartialEq, Eq, Hash)]
950struct HoveredCursor {
951 replica_id: u16,
952 selection_id: usize,
953}
954
955impl Default for SelectionHistoryMode {
956 fn default() -> Self {
957 Self::Normal
958 }
959}
960
961#[derive(Default)]
962struct SelectionHistory {
963 #[allow(clippy::type_complexity)]
964 selections_by_transaction:
965 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
966 mode: SelectionHistoryMode,
967 undo_stack: VecDeque<SelectionHistoryEntry>,
968 redo_stack: VecDeque<SelectionHistoryEntry>,
969}
970
971impl SelectionHistory {
972 fn insert_transaction(
973 &mut self,
974 transaction_id: TransactionId,
975 selections: Arc<[Selection<Anchor>]>,
976 ) {
977 self.selections_by_transaction
978 .insert(transaction_id, (selections, None));
979 }
980
981 #[allow(clippy::type_complexity)]
982 fn transaction(
983 &self,
984 transaction_id: TransactionId,
985 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
986 self.selections_by_transaction.get(&transaction_id)
987 }
988
989 #[allow(clippy::type_complexity)]
990 fn transaction_mut(
991 &mut self,
992 transaction_id: TransactionId,
993 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
994 self.selections_by_transaction.get_mut(&transaction_id)
995 }
996
997 fn push(&mut self, entry: SelectionHistoryEntry) {
998 if !entry.selections.is_empty() {
999 match self.mode {
1000 SelectionHistoryMode::Normal => {
1001 self.push_undo(entry);
1002 self.redo_stack.clear();
1003 }
1004 SelectionHistoryMode::Undoing => self.push_redo(entry),
1005 SelectionHistoryMode::Redoing => self.push_undo(entry),
1006 }
1007 }
1008 }
1009
1010 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1011 if self
1012 .undo_stack
1013 .back()
1014 .map_or(true, |e| e.selections != entry.selections)
1015 {
1016 self.undo_stack.push_back(entry);
1017 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1018 self.undo_stack.pop_front();
1019 }
1020 }
1021 }
1022
1023 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1024 if self
1025 .redo_stack
1026 .back()
1027 .map_or(true, |e| e.selections != entry.selections)
1028 {
1029 self.redo_stack.push_back(entry);
1030 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1031 self.redo_stack.pop_front();
1032 }
1033 }
1034 }
1035}
1036
1037struct RowHighlight {
1038 index: usize,
1039 range: Range<Anchor>,
1040 color: Hsla,
1041 should_autoscroll: bool,
1042}
1043
1044#[derive(Clone, Debug)]
1045struct AddSelectionsState {
1046 above: bool,
1047 stack: Vec<usize>,
1048}
1049
1050#[derive(Clone)]
1051struct SelectNextState {
1052 query: AhoCorasick,
1053 wordwise: bool,
1054 done: bool,
1055}
1056
1057impl std::fmt::Debug for SelectNextState {
1058 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1059 f.debug_struct(std::any::type_name::<Self>())
1060 .field("wordwise", &self.wordwise)
1061 .field("done", &self.done)
1062 .finish()
1063 }
1064}
1065
1066#[derive(Debug)]
1067struct AutocloseRegion {
1068 selection_id: usize,
1069 range: Range<Anchor>,
1070 pair: BracketPair,
1071}
1072
1073#[derive(Debug)]
1074struct SnippetState {
1075 ranges: Vec<Vec<Range<Anchor>>>,
1076 active_index: usize,
1077 choices: Vec<Option<Vec<String>>>,
1078}
1079
1080#[doc(hidden)]
1081pub struct RenameState {
1082 pub range: Range<Anchor>,
1083 pub old_name: Arc<str>,
1084 pub editor: Entity<Editor>,
1085 block_id: CustomBlockId,
1086}
1087
1088struct InvalidationStack<T>(Vec<T>);
1089
1090struct RegisteredInlineCompletionProvider {
1091 provider: Arc<dyn InlineCompletionProviderHandle>,
1092 _subscription: Subscription,
1093}
1094
1095#[derive(Debug, PartialEq, Eq)]
1096pub struct ActiveDiagnosticGroup {
1097 pub active_range: Range<Anchor>,
1098 pub active_message: String,
1099 pub group_id: usize,
1100 pub blocks: HashSet<CustomBlockId>,
1101}
1102
1103#[derive(Debug, PartialEq, Eq)]
1104#[allow(clippy::large_enum_variant)]
1105pub(crate) enum ActiveDiagnostic {
1106 None,
1107 All,
1108 Group(ActiveDiagnosticGroup),
1109}
1110
1111#[derive(Serialize, Deserialize, Clone, Debug)]
1112pub struct ClipboardSelection {
1113 /// The number of bytes in this selection.
1114 pub len: usize,
1115 /// Whether this was a full-line selection.
1116 pub is_entire_line: bool,
1117 /// The indentation of the first line when this content was originally copied.
1118 pub first_line_indent: u32,
1119}
1120
1121// selections, scroll behavior, was newest selection reversed
1122type SelectSyntaxNodeHistoryState = (
1123 Box<[Selection<usize>]>,
1124 SelectSyntaxNodeScrollBehavior,
1125 bool,
1126);
1127
1128#[derive(Default)]
1129struct SelectSyntaxNodeHistory {
1130 stack: Vec<SelectSyntaxNodeHistoryState>,
1131 // disable temporarily to allow changing selections without losing the stack
1132 pub disable_clearing: bool,
1133}
1134
1135impl SelectSyntaxNodeHistory {
1136 pub fn try_clear(&mut self) {
1137 if !self.disable_clearing {
1138 self.stack.clear();
1139 }
1140 }
1141
1142 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1143 self.stack.push(selection);
1144 }
1145
1146 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1147 self.stack.pop()
1148 }
1149}
1150
1151enum SelectSyntaxNodeScrollBehavior {
1152 CursorTop,
1153 FitSelection,
1154 CursorBottom,
1155}
1156
1157#[derive(Debug)]
1158pub(crate) struct NavigationData {
1159 cursor_anchor: Anchor,
1160 cursor_position: Point,
1161 scroll_anchor: ScrollAnchor,
1162 scroll_top_row: u32,
1163}
1164
1165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1166pub enum GotoDefinitionKind {
1167 Symbol,
1168 Declaration,
1169 Type,
1170 Implementation,
1171}
1172
1173#[derive(Debug, Clone)]
1174enum InlayHintRefreshReason {
1175 ModifiersChanged(bool),
1176 Toggle(bool),
1177 SettingsChange(InlayHintSettings),
1178 NewLinesShown,
1179 BufferEdited(HashSet<Arc<Language>>),
1180 RefreshRequested,
1181 ExcerptsRemoved(Vec<ExcerptId>),
1182}
1183
1184impl InlayHintRefreshReason {
1185 fn description(&self) -> &'static str {
1186 match self {
1187 Self::ModifiersChanged(_) => "modifiers changed",
1188 Self::Toggle(_) => "toggle",
1189 Self::SettingsChange(_) => "settings change",
1190 Self::NewLinesShown => "new lines shown",
1191 Self::BufferEdited(_) => "buffer edited",
1192 Self::RefreshRequested => "refresh requested",
1193 Self::ExcerptsRemoved(_) => "excerpts removed",
1194 }
1195 }
1196}
1197
1198pub enum FormatTarget {
1199 Buffers,
1200 Ranges(Vec<Range<MultiBufferPoint>>),
1201}
1202
1203pub(crate) struct FocusedBlock {
1204 id: BlockId,
1205 focus_handle: WeakFocusHandle,
1206}
1207
1208#[derive(Clone)]
1209enum JumpData {
1210 MultiBufferRow {
1211 row: MultiBufferRow,
1212 line_offset_from_top: u32,
1213 },
1214 MultiBufferPoint {
1215 excerpt_id: ExcerptId,
1216 position: Point,
1217 anchor: text::Anchor,
1218 line_offset_from_top: u32,
1219 },
1220}
1221
1222pub enum MultibufferSelectionMode {
1223 First,
1224 All,
1225}
1226
1227#[derive(Clone, Copy, Debug, Default)]
1228pub struct RewrapOptions {
1229 pub override_language_settings: bool,
1230 pub preserve_existing_whitespace: bool,
1231}
1232
1233impl Editor {
1234 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1235 let buffer = cx.new(|cx| Buffer::local("", cx));
1236 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1237 Self::new(
1238 EditorMode::SingleLine { auto_width: false },
1239 buffer,
1240 None,
1241 window,
1242 cx,
1243 )
1244 }
1245
1246 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1247 let buffer = cx.new(|cx| Buffer::local("", cx));
1248 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1249 Self::new(EditorMode::full(), buffer, None, window, cx)
1250 }
1251
1252 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1253 let buffer = cx.new(|cx| Buffer::local("", cx));
1254 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1255 Self::new(
1256 EditorMode::SingleLine { auto_width: true },
1257 buffer,
1258 None,
1259 window,
1260 cx,
1261 )
1262 }
1263
1264 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1265 let buffer = cx.new(|cx| Buffer::local("", cx));
1266 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1267 Self::new(
1268 EditorMode::AutoHeight { max_lines },
1269 buffer,
1270 None,
1271 window,
1272 cx,
1273 )
1274 }
1275
1276 pub fn for_buffer(
1277 buffer: Entity<Buffer>,
1278 project: Option<Entity<Project>>,
1279 window: &mut Window,
1280 cx: &mut Context<Self>,
1281 ) -> Self {
1282 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1283 Self::new(EditorMode::full(), buffer, project, window, cx)
1284 }
1285
1286 pub fn for_multibuffer(
1287 buffer: Entity<MultiBuffer>,
1288 project: Option<Entity<Project>>,
1289 window: &mut Window,
1290 cx: &mut Context<Self>,
1291 ) -> Self {
1292 Self::new(EditorMode::full(), buffer, project, window, cx)
1293 }
1294
1295 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1296 let mut clone = Self::new(
1297 self.mode,
1298 self.buffer.clone(),
1299 self.project.clone(),
1300 window,
1301 cx,
1302 );
1303 self.display_map.update(cx, |display_map, cx| {
1304 let snapshot = display_map.snapshot(cx);
1305 clone.display_map.update(cx, |display_map, cx| {
1306 display_map.set_state(&snapshot, cx);
1307 });
1308 });
1309 clone.folds_did_change(cx);
1310 clone.selections.clone_state(&self.selections);
1311 clone.scroll_manager.clone_state(&self.scroll_manager);
1312 clone.searchable = self.searchable;
1313 clone.read_only = self.read_only;
1314 clone
1315 }
1316
1317 pub fn new(
1318 mode: EditorMode,
1319 buffer: Entity<MultiBuffer>,
1320 project: Option<Entity<Project>>,
1321 window: &mut Window,
1322 cx: &mut Context<Self>,
1323 ) -> Self {
1324 let style = window.text_style();
1325 let font_size = style.font_size.to_pixels(window.rem_size());
1326 let editor = cx.entity().downgrade();
1327 let fold_placeholder = FoldPlaceholder {
1328 constrain_width: true,
1329 render: Arc::new(move |fold_id, fold_range, cx| {
1330 let editor = editor.clone();
1331 div()
1332 .id(fold_id)
1333 .bg(cx.theme().colors().ghost_element_background)
1334 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1335 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1336 .rounded_xs()
1337 .size_full()
1338 .cursor_pointer()
1339 .child("⋯")
1340 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1341 .on_click(move |_, _window, cx| {
1342 editor
1343 .update(cx, |editor, cx| {
1344 editor.unfold_ranges(
1345 &[fold_range.start..fold_range.end],
1346 true,
1347 false,
1348 cx,
1349 );
1350 cx.stop_propagation();
1351 })
1352 .ok();
1353 })
1354 .into_any()
1355 }),
1356 merge_adjacent: true,
1357 ..Default::default()
1358 };
1359 let display_map = cx.new(|cx| {
1360 DisplayMap::new(
1361 buffer.clone(),
1362 style.font(),
1363 font_size,
1364 None,
1365 FILE_HEADER_HEIGHT,
1366 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1367 fold_placeholder,
1368 cx,
1369 )
1370 });
1371
1372 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1373
1374 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1375
1376 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1377 .then(|| language_settings::SoftWrap::None);
1378
1379 let mut project_subscriptions = Vec::new();
1380 if mode.is_full() {
1381 if let Some(project) = project.as_ref() {
1382 project_subscriptions.push(cx.subscribe_in(
1383 project,
1384 window,
1385 |editor, _, event, window, cx| match event {
1386 project::Event::RefreshCodeLens => {
1387 // we always query lens with actions, without storing them, always refreshing them
1388 }
1389 project::Event::RefreshInlayHints => {
1390 editor
1391 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1392 }
1393 project::Event::SnippetEdit(id, snippet_edits) => {
1394 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1395 let focus_handle = editor.focus_handle(cx);
1396 if focus_handle.is_focused(window) {
1397 let snapshot = buffer.read(cx).snapshot();
1398 for (range, snippet) in snippet_edits {
1399 let editor_range =
1400 language::range_from_lsp(*range).to_offset(&snapshot);
1401 editor
1402 .insert_snippet(
1403 &[editor_range],
1404 snippet.clone(),
1405 window,
1406 cx,
1407 )
1408 .ok();
1409 }
1410 }
1411 }
1412 }
1413 _ => {}
1414 },
1415 ));
1416 if let Some(task_inventory) = project
1417 .read(cx)
1418 .task_store()
1419 .read(cx)
1420 .task_inventory()
1421 .cloned()
1422 {
1423 project_subscriptions.push(cx.observe_in(
1424 &task_inventory,
1425 window,
1426 |editor, _, window, cx| {
1427 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1428 },
1429 ));
1430 };
1431
1432 project_subscriptions.push(cx.subscribe_in(
1433 &project.read(cx).breakpoint_store(),
1434 window,
1435 |editor, _, event, window, cx| match event {
1436 BreakpointStoreEvent::ActiveDebugLineChanged => {
1437 if editor.go_to_active_debug_line(window, cx) {
1438 cx.stop_propagation();
1439 }
1440 }
1441 _ => {}
1442 },
1443 ));
1444 }
1445 }
1446
1447 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1448
1449 let inlay_hint_settings =
1450 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1451 let focus_handle = cx.focus_handle();
1452 cx.on_focus(&focus_handle, window, Self::handle_focus)
1453 .detach();
1454 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1455 .detach();
1456 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1457 .detach();
1458 cx.on_blur(&focus_handle, window, Self::handle_blur)
1459 .detach();
1460
1461 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1462 Some(false)
1463 } else {
1464 None
1465 };
1466
1467 let breakpoint_store = match (mode, project.as_ref()) {
1468 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1469 _ => None,
1470 };
1471
1472 let mut code_action_providers = Vec::new();
1473 let mut load_uncommitted_diff = None;
1474 if let Some(project) = project.clone() {
1475 load_uncommitted_diff = Some(
1476 get_uncommitted_diff_for_buffer(
1477 &project,
1478 buffer.read(cx).all_buffers(),
1479 buffer.clone(),
1480 cx,
1481 )
1482 .shared(),
1483 );
1484 code_action_providers.push(Rc::new(project) as Rc<_>);
1485 }
1486
1487 let mut this = Self {
1488 focus_handle,
1489 show_cursor_when_unfocused: false,
1490 last_focused_descendant: None,
1491 buffer: buffer.clone(),
1492 display_map: display_map.clone(),
1493 selections,
1494 scroll_manager: ScrollManager::new(cx),
1495 columnar_selection_tail: None,
1496 add_selections_state: None,
1497 select_next_state: None,
1498 select_prev_state: None,
1499 selection_history: Default::default(),
1500 autoclose_regions: Default::default(),
1501 snippet_stack: Default::default(),
1502 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1503 ime_transaction: Default::default(),
1504 active_diagnostics: ActiveDiagnostic::None,
1505 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1506 inline_diagnostics_update: Task::ready(()),
1507 inline_diagnostics: Vec::new(),
1508 soft_wrap_mode_override,
1509 hard_wrap: None,
1510 completion_provider: project.clone().map(|project| Box::new(project) as _),
1511 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1512 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1513 project,
1514 blink_manager: blink_manager.clone(),
1515 show_local_selections: true,
1516 show_scrollbars: true,
1517 mode,
1518 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1519 show_gutter: mode.is_full(),
1520 show_line_numbers: None,
1521 use_relative_line_numbers: None,
1522 show_git_diff_gutter: None,
1523 show_code_actions: None,
1524 show_runnables: None,
1525 show_breakpoints: None,
1526 show_wrap_guides: None,
1527 show_indent_guides,
1528 placeholder_text: None,
1529 highlight_order: 0,
1530 highlighted_rows: HashMap::default(),
1531 background_highlights: Default::default(),
1532 gutter_highlights: TreeMap::default(),
1533 scrollbar_marker_state: ScrollbarMarkerState::default(),
1534 active_indent_guides_state: ActiveIndentGuidesState::default(),
1535 nav_history: None,
1536 context_menu: RefCell::new(None),
1537 context_menu_options: None,
1538 mouse_context_menu: None,
1539 completion_tasks: Default::default(),
1540 signature_help_state: SignatureHelpState::default(),
1541 auto_signature_help: None,
1542 find_all_references_task_sources: Vec::new(),
1543 next_completion_id: 0,
1544 next_inlay_id: 0,
1545 code_action_providers,
1546 available_code_actions: Default::default(),
1547 code_actions_task: Default::default(),
1548 quick_selection_highlight_task: Default::default(),
1549 debounced_selection_highlight_task: Default::default(),
1550 document_highlights_task: Default::default(),
1551 linked_editing_range_task: Default::default(),
1552 pending_rename: Default::default(),
1553 searchable: true,
1554 cursor_shape: EditorSettings::get_global(cx)
1555 .cursor_shape
1556 .unwrap_or_default(),
1557 current_line_highlight: None,
1558 autoindent_mode: Some(AutoindentMode::EachLine),
1559 collapse_matches: false,
1560 workspace: None,
1561 input_enabled: true,
1562 use_modal_editing: mode.is_full(),
1563 read_only: false,
1564 use_autoclose: true,
1565 use_auto_surround: true,
1566 auto_replace_emoji_shortcode: false,
1567 jsx_tag_auto_close_enabled_in_any_buffer: false,
1568 leader_peer_id: None,
1569 remote_id: None,
1570 hover_state: Default::default(),
1571 pending_mouse_down: None,
1572 hovered_link_state: Default::default(),
1573 edit_prediction_provider: None,
1574 active_inline_completion: None,
1575 stale_inline_completion_in_menu: None,
1576 edit_prediction_preview: EditPredictionPreview::Inactive {
1577 released_too_fast: false,
1578 },
1579 inline_diagnostics_enabled: mode.is_full(),
1580 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1581
1582 gutter_hovered: false,
1583 pixel_position_of_newest_cursor: None,
1584 last_bounds: None,
1585 last_position_map: None,
1586 expect_bounds_change: None,
1587 gutter_dimensions: GutterDimensions::default(),
1588 style: None,
1589 show_cursor_names: false,
1590 hovered_cursors: Default::default(),
1591 next_editor_action_id: EditorActionId::default(),
1592 editor_actions: Rc::default(),
1593 inline_completions_hidden_for_vim_mode: false,
1594 show_inline_completions_override: None,
1595 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1596 edit_prediction_settings: EditPredictionSettings::Disabled,
1597 edit_prediction_indent_conflict: false,
1598 edit_prediction_requires_modifier_in_indent_conflict: true,
1599 custom_context_menu: None,
1600 show_git_blame_gutter: false,
1601 show_git_blame_inline: false,
1602 show_selection_menu: None,
1603 show_git_blame_inline_delay_task: None,
1604 git_blame_inline_tooltip: None,
1605 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1606 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1607 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1608 .session
1609 .restore_unsaved_buffers,
1610 blame: None,
1611 blame_subscription: None,
1612 tasks: Default::default(),
1613
1614 breakpoint_store,
1615 gutter_breakpoint_indicator: (None, None),
1616 _subscriptions: vec![
1617 cx.observe(&buffer, Self::on_buffer_changed),
1618 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1619 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1620 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1621 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1622 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1623 cx.observe_window_activation(window, |editor, window, cx| {
1624 let active = window.is_window_active();
1625 editor.blink_manager.update(cx, |blink_manager, cx| {
1626 if active {
1627 blink_manager.enable(cx);
1628 } else {
1629 blink_manager.disable(cx);
1630 }
1631 });
1632 }),
1633 ],
1634 tasks_update_task: None,
1635 linked_edit_ranges: Default::default(),
1636 in_project_search: false,
1637 previous_search_ranges: None,
1638 breadcrumb_header: None,
1639 focused_block: None,
1640 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1641 addons: HashMap::default(),
1642 registered_buffers: HashMap::default(),
1643 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1644 selection_mark_mode: false,
1645 toggle_fold_multiple_buffers: Task::ready(()),
1646 serialize_selections: Task::ready(()),
1647 serialize_folds: Task::ready(()),
1648 text_style_refinement: None,
1649 load_diff_task: load_uncommitted_diff,
1650 mouse_cursor_hidden: false,
1651 hide_mouse_mode: EditorSettings::get_global(cx)
1652 .hide_mouse
1653 .unwrap_or_default(),
1654 };
1655 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1656 this._subscriptions
1657 .push(cx.observe(breakpoints, |_, _, cx| {
1658 cx.notify();
1659 }));
1660 }
1661 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1662 this._subscriptions.extend(project_subscriptions);
1663
1664 this._subscriptions.push(cx.subscribe_in(
1665 &cx.entity(),
1666 window,
1667 |editor, _, e: &EditorEvent, window, cx| {
1668 if let EditorEvent::SelectionsChanged { local } = e {
1669 if *local {
1670 let new_anchor = editor.scroll_manager.anchor();
1671 let snapshot = editor.snapshot(window, cx);
1672 editor.update_restoration_data(cx, move |data| {
1673 data.scroll_position = (
1674 new_anchor.top_row(&snapshot.buffer_snapshot),
1675 new_anchor.offset,
1676 );
1677 });
1678 }
1679 }
1680 },
1681 ));
1682
1683 this.end_selection(window, cx);
1684 this.scroll_manager.show_scrollbars(window, cx);
1685 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1686
1687 if mode.is_full() {
1688 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1689 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1690
1691 if this.git_blame_inline_enabled {
1692 this.git_blame_inline_enabled = true;
1693 this.start_git_blame_inline(false, window, cx);
1694 }
1695
1696 this.go_to_active_debug_line(window, cx);
1697
1698 if let Some(buffer) = buffer.read(cx).as_singleton() {
1699 if let Some(project) = this.project.as_ref() {
1700 let handle = project.update(cx, |project, cx| {
1701 project.register_buffer_with_language_servers(&buffer, cx)
1702 });
1703 this.registered_buffers
1704 .insert(buffer.read(cx).remote_id(), handle);
1705 }
1706 }
1707 }
1708
1709 this.report_editor_event("Editor Opened", None, cx);
1710 this
1711 }
1712
1713 pub fn deploy_mouse_context_menu(
1714 &mut self,
1715 position: gpui::Point<Pixels>,
1716 context_menu: Entity<ContextMenu>,
1717 window: &mut Window,
1718 cx: &mut Context<Self>,
1719 ) {
1720 self.mouse_context_menu = Some(MouseContextMenu::new(
1721 self,
1722 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1723 context_menu,
1724 window,
1725 cx,
1726 ));
1727 }
1728
1729 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1730 self.mouse_context_menu
1731 .as_ref()
1732 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1733 }
1734
1735 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1736 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1737 }
1738
1739 fn key_context_internal(
1740 &self,
1741 has_active_edit_prediction: bool,
1742 window: &Window,
1743 cx: &App,
1744 ) -> KeyContext {
1745 let mut key_context = KeyContext::new_with_defaults();
1746 key_context.add("Editor");
1747 let mode = match self.mode {
1748 EditorMode::SingleLine { .. } => "single_line",
1749 EditorMode::AutoHeight { .. } => "auto_height",
1750 EditorMode::Full { .. } => "full",
1751 };
1752
1753 if EditorSettings::jupyter_enabled(cx) {
1754 key_context.add("jupyter");
1755 }
1756
1757 key_context.set("mode", mode);
1758 if self.pending_rename.is_some() {
1759 key_context.add("renaming");
1760 }
1761
1762 match self.context_menu.borrow().as_ref() {
1763 Some(CodeContextMenu::Completions(_)) => {
1764 key_context.add("menu");
1765 key_context.add("showing_completions");
1766 }
1767 Some(CodeContextMenu::CodeActions(_)) => {
1768 key_context.add("menu");
1769 key_context.add("showing_code_actions")
1770 }
1771 None => {}
1772 }
1773
1774 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1775 if !self.focus_handle(cx).contains_focused(window, cx)
1776 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1777 {
1778 for addon in self.addons.values() {
1779 addon.extend_key_context(&mut key_context, cx)
1780 }
1781 }
1782
1783 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1784 if let Some(extension) = singleton_buffer
1785 .read(cx)
1786 .file()
1787 .and_then(|file| file.path().extension()?.to_str())
1788 {
1789 key_context.set("extension", extension.to_string());
1790 }
1791 } else {
1792 key_context.add("multibuffer");
1793 }
1794
1795 if has_active_edit_prediction {
1796 if self.edit_prediction_in_conflict() {
1797 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1798 } else {
1799 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1800 key_context.add("copilot_suggestion");
1801 }
1802 }
1803
1804 if self.selection_mark_mode {
1805 key_context.add("selection_mode");
1806 }
1807
1808 key_context
1809 }
1810
1811 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1812 self.mouse_cursor_hidden = match origin {
1813 HideMouseCursorOrigin::TypingAction => {
1814 matches!(
1815 self.hide_mouse_mode,
1816 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1817 )
1818 }
1819 HideMouseCursorOrigin::MovementAction => {
1820 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1821 }
1822 };
1823 }
1824
1825 pub fn edit_prediction_in_conflict(&self) -> bool {
1826 if !self.show_edit_predictions_in_menu() {
1827 return false;
1828 }
1829
1830 let showing_completions = self
1831 .context_menu
1832 .borrow()
1833 .as_ref()
1834 .map_or(false, |context| {
1835 matches!(context, CodeContextMenu::Completions(_))
1836 });
1837
1838 showing_completions
1839 || self.edit_prediction_requires_modifier()
1840 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1841 // bindings to insert tab characters.
1842 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1843 }
1844
1845 pub fn accept_edit_prediction_keybind(
1846 &self,
1847 window: &Window,
1848 cx: &App,
1849 ) -> AcceptEditPredictionBinding {
1850 let key_context = self.key_context_internal(true, window, cx);
1851 let in_conflict = self.edit_prediction_in_conflict();
1852
1853 AcceptEditPredictionBinding(
1854 window
1855 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1856 .into_iter()
1857 .filter(|binding| {
1858 !in_conflict
1859 || binding
1860 .keystrokes()
1861 .first()
1862 .map_or(false, |keystroke| keystroke.modifiers.modified())
1863 })
1864 .rev()
1865 .min_by_key(|binding| {
1866 binding
1867 .keystrokes()
1868 .first()
1869 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1870 }),
1871 )
1872 }
1873
1874 pub fn new_file(
1875 workspace: &mut Workspace,
1876 _: &workspace::NewFile,
1877 window: &mut Window,
1878 cx: &mut Context<Workspace>,
1879 ) {
1880 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1881 "Failed to create buffer",
1882 window,
1883 cx,
1884 |e, _, _| match e.error_code() {
1885 ErrorCode::RemoteUpgradeRequired => Some(format!(
1886 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1887 e.error_tag("required").unwrap_or("the latest version")
1888 )),
1889 _ => None,
1890 },
1891 );
1892 }
1893
1894 pub fn new_in_workspace(
1895 workspace: &mut Workspace,
1896 window: &mut Window,
1897 cx: &mut Context<Workspace>,
1898 ) -> Task<Result<Entity<Editor>>> {
1899 let project = workspace.project().clone();
1900 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1901
1902 cx.spawn_in(window, async move |workspace, cx| {
1903 let buffer = create.await?;
1904 workspace.update_in(cx, |workspace, window, cx| {
1905 let editor =
1906 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1907 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1908 editor
1909 })
1910 })
1911 }
1912
1913 fn new_file_vertical(
1914 workspace: &mut Workspace,
1915 _: &workspace::NewFileSplitVertical,
1916 window: &mut Window,
1917 cx: &mut Context<Workspace>,
1918 ) {
1919 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1920 }
1921
1922 fn new_file_horizontal(
1923 workspace: &mut Workspace,
1924 _: &workspace::NewFileSplitHorizontal,
1925 window: &mut Window,
1926 cx: &mut Context<Workspace>,
1927 ) {
1928 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1929 }
1930
1931 fn new_file_in_direction(
1932 workspace: &mut Workspace,
1933 direction: SplitDirection,
1934 window: &mut Window,
1935 cx: &mut Context<Workspace>,
1936 ) {
1937 let project = workspace.project().clone();
1938 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1939
1940 cx.spawn_in(window, async move |workspace, cx| {
1941 let buffer = create.await?;
1942 workspace.update_in(cx, move |workspace, window, cx| {
1943 workspace.split_item(
1944 direction,
1945 Box::new(
1946 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1947 ),
1948 window,
1949 cx,
1950 )
1951 })?;
1952 anyhow::Ok(())
1953 })
1954 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1955 match e.error_code() {
1956 ErrorCode::RemoteUpgradeRequired => Some(format!(
1957 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1958 e.error_tag("required").unwrap_or("the latest version")
1959 )),
1960 _ => None,
1961 }
1962 });
1963 }
1964
1965 pub fn leader_peer_id(&self) -> Option<PeerId> {
1966 self.leader_peer_id
1967 }
1968
1969 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1970 &self.buffer
1971 }
1972
1973 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1974 self.workspace.as_ref()?.0.upgrade()
1975 }
1976
1977 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1978 self.buffer().read(cx).title(cx)
1979 }
1980
1981 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1982 let git_blame_gutter_max_author_length = self
1983 .render_git_blame_gutter(cx)
1984 .then(|| {
1985 if let Some(blame) = self.blame.as_ref() {
1986 let max_author_length =
1987 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1988 Some(max_author_length)
1989 } else {
1990 None
1991 }
1992 })
1993 .flatten();
1994
1995 EditorSnapshot {
1996 mode: self.mode,
1997 show_gutter: self.show_gutter,
1998 show_line_numbers: self.show_line_numbers,
1999 show_git_diff_gutter: self.show_git_diff_gutter,
2000 show_code_actions: self.show_code_actions,
2001 show_runnables: self.show_runnables,
2002 show_breakpoints: self.show_breakpoints,
2003 git_blame_gutter_max_author_length,
2004 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2005 scroll_anchor: self.scroll_manager.anchor(),
2006 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2007 placeholder_text: self.placeholder_text.clone(),
2008 is_focused: self.focus_handle.is_focused(window),
2009 current_line_highlight: self
2010 .current_line_highlight
2011 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2012 gutter_hovered: self.gutter_hovered,
2013 }
2014 }
2015
2016 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2017 self.buffer.read(cx).language_at(point, cx)
2018 }
2019
2020 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2021 self.buffer.read(cx).read(cx).file_at(point).cloned()
2022 }
2023
2024 pub fn active_excerpt(
2025 &self,
2026 cx: &App,
2027 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2028 self.buffer
2029 .read(cx)
2030 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2031 }
2032
2033 pub fn mode(&self) -> EditorMode {
2034 self.mode
2035 }
2036
2037 pub fn set_mode(&mut self, mode: EditorMode) {
2038 self.mode = mode;
2039 }
2040
2041 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2042 self.collaboration_hub.as_deref()
2043 }
2044
2045 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2046 self.collaboration_hub = Some(hub);
2047 }
2048
2049 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2050 self.in_project_search = in_project_search;
2051 }
2052
2053 pub fn set_custom_context_menu(
2054 &mut self,
2055 f: impl 'static
2056 + Fn(
2057 &mut Self,
2058 DisplayPoint,
2059 &mut Window,
2060 &mut Context<Self>,
2061 ) -> Option<Entity<ui::ContextMenu>>,
2062 ) {
2063 self.custom_context_menu = Some(Box::new(f))
2064 }
2065
2066 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2067 self.completion_provider = provider;
2068 }
2069
2070 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2071 self.semantics_provider.clone()
2072 }
2073
2074 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2075 self.semantics_provider = provider;
2076 }
2077
2078 pub fn set_edit_prediction_provider<T>(
2079 &mut self,
2080 provider: Option<Entity<T>>,
2081 window: &mut Window,
2082 cx: &mut Context<Self>,
2083 ) where
2084 T: EditPredictionProvider,
2085 {
2086 self.edit_prediction_provider =
2087 provider.map(|provider| RegisteredInlineCompletionProvider {
2088 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2089 if this.focus_handle.is_focused(window) {
2090 this.update_visible_inline_completion(window, cx);
2091 }
2092 }),
2093 provider: Arc::new(provider),
2094 });
2095 self.update_edit_prediction_settings(cx);
2096 self.refresh_inline_completion(false, false, window, cx);
2097 }
2098
2099 pub fn placeholder_text(&self) -> Option<&str> {
2100 self.placeholder_text.as_deref()
2101 }
2102
2103 pub fn set_placeholder_text(
2104 &mut self,
2105 placeholder_text: impl Into<Arc<str>>,
2106 cx: &mut Context<Self>,
2107 ) {
2108 let placeholder_text = Some(placeholder_text.into());
2109 if self.placeholder_text != placeholder_text {
2110 self.placeholder_text = placeholder_text;
2111 cx.notify();
2112 }
2113 }
2114
2115 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2116 self.cursor_shape = cursor_shape;
2117
2118 // Disrupt blink for immediate user feedback that the cursor shape has changed
2119 self.blink_manager.update(cx, BlinkManager::show_cursor);
2120
2121 cx.notify();
2122 }
2123
2124 pub fn set_current_line_highlight(
2125 &mut self,
2126 current_line_highlight: Option<CurrentLineHighlight>,
2127 ) {
2128 self.current_line_highlight = current_line_highlight;
2129 }
2130
2131 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2132 self.collapse_matches = collapse_matches;
2133 }
2134
2135 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2136 let buffers = self.buffer.read(cx).all_buffers();
2137 let Some(project) = self.project.as_ref() else {
2138 return;
2139 };
2140 project.update(cx, |project, cx| {
2141 for buffer in buffers {
2142 self.registered_buffers
2143 .entry(buffer.read(cx).remote_id())
2144 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2145 }
2146 })
2147 }
2148
2149 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2150 if self.collapse_matches {
2151 return range.start..range.start;
2152 }
2153 range.clone()
2154 }
2155
2156 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2157 if self.display_map.read(cx).clip_at_line_ends != clip {
2158 self.display_map
2159 .update(cx, |map, _| map.clip_at_line_ends = clip);
2160 }
2161 }
2162
2163 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2164 self.input_enabled = input_enabled;
2165 }
2166
2167 pub fn set_inline_completions_hidden_for_vim_mode(
2168 &mut self,
2169 hidden: bool,
2170 window: &mut Window,
2171 cx: &mut Context<Self>,
2172 ) {
2173 if hidden != self.inline_completions_hidden_for_vim_mode {
2174 self.inline_completions_hidden_for_vim_mode = hidden;
2175 if hidden {
2176 self.update_visible_inline_completion(window, cx);
2177 } else {
2178 self.refresh_inline_completion(true, false, window, cx);
2179 }
2180 }
2181 }
2182
2183 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2184 self.menu_inline_completions_policy = value;
2185 }
2186
2187 pub fn set_autoindent(&mut self, autoindent: bool) {
2188 if autoindent {
2189 self.autoindent_mode = Some(AutoindentMode::EachLine);
2190 } else {
2191 self.autoindent_mode = None;
2192 }
2193 }
2194
2195 pub fn read_only(&self, cx: &App) -> bool {
2196 self.read_only || self.buffer.read(cx).read_only()
2197 }
2198
2199 pub fn set_read_only(&mut self, read_only: bool) {
2200 self.read_only = read_only;
2201 }
2202
2203 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2204 self.use_autoclose = autoclose;
2205 }
2206
2207 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2208 self.use_auto_surround = auto_surround;
2209 }
2210
2211 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2212 self.auto_replace_emoji_shortcode = auto_replace;
2213 }
2214
2215 pub fn toggle_edit_predictions(
2216 &mut self,
2217 _: &ToggleEditPrediction,
2218 window: &mut Window,
2219 cx: &mut Context<Self>,
2220 ) {
2221 if self.show_inline_completions_override.is_some() {
2222 self.set_show_edit_predictions(None, window, cx);
2223 } else {
2224 let show_edit_predictions = !self.edit_predictions_enabled();
2225 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2226 }
2227 }
2228
2229 pub fn set_show_edit_predictions(
2230 &mut self,
2231 show_edit_predictions: Option<bool>,
2232 window: &mut Window,
2233 cx: &mut Context<Self>,
2234 ) {
2235 self.show_inline_completions_override = show_edit_predictions;
2236 self.update_edit_prediction_settings(cx);
2237
2238 if let Some(false) = show_edit_predictions {
2239 self.discard_inline_completion(false, cx);
2240 } else {
2241 self.refresh_inline_completion(false, true, window, cx);
2242 }
2243 }
2244
2245 fn inline_completions_disabled_in_scope(
2246 &self,
2247 buffer: &Entity<Buffer>,
2248 buffer_position: language::Anchor,
2249 cx: &App,
2250 ) -> bool {
2251 let snapshot = buffer.read(cx).snapshot();
2252 let settings = snapshot.settings_at(buffer_position, cx);
2253
2254 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2255 return false;
2256 };
2257
2258 scope.override_name().map_or(false, |scope_name| {
2259 settings
2260 .edit_predictions_disabled_in
2261 .iter()
2262 .any(|s| s == scope_name)
2263 })
2264 }
2265
2266 pub fn set_use_modal_editing(&mut self, to: bool) {
2267 self.use_modal_editing = to;
2268 }
2269
2270 pub fn use_modal_editing(&self) -> bool {
2271 self.use_modal_editing
2272 }
2273
2274 fn selections_did_change(
2275 &mut self,
2276 local: bool,
2277 old_cursor_position: &Anchor,
2278 show_completions: bool,
2279 window: &mut Window,
2280 cx: &mut Context<Self>,
2281 ) {
2282 window.invalidate_character_coordinates();
2283
2284 // Copy selections to primary selection buffer
2285 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2286 if local {
2287 let selections = self.selections.all::<usize>(cx);
2288 let buffer_handle = self.buffer.read(cx).read(cx);
2289
2290 let mut text = String::new();
2291 for (index, selection) in selections.iter().enumerate() {
2292 let text_for_selection = buffer_handle
2293 .text_for_range(selection.start..selection.end)
2294 .collect::<String>();
2295
2296 text.push_str(&text_for_selection);
2297 if index != selections.len() - 1 {
2298 text.push('\n');
2299 }
2300 }
2301
2302 if !text.is_empty() {
2303 cx.write_to_primary(ClipboardItem::new_string(text));
2304 }
2305 }
2306
2307 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2308 self.buffer.update(cx, |buffer, cx| {
2309 buffer.set_active_selections(
2310 &self.selections.disjoint_anchors(),
2311 self.selections.line_mode,
2312 self.cursor_shape,
2313 cx,
2314 )
2315 });
2316 }
2317 let display_map = self
2318 .display_map
2319 .update(cx, |display_map, cx| display_map.snapshot(cx));
2320 let buffer = &display_map.buffer_snapshot;
2321 self.add_selections_state = None;
2322 self.select_next_state = None;
2323 self.select_prev_state = None;
2324 self.select_syntax_node_history.try_clear();
2325 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2326 self.snippet_stack
2327 .invalidate(&self.selections.disjoint_anchors(), buffer);
2328 self.take_rename(false, window, cx);
2329
2330 let new_cursor_position = self.selections.newest_anchor().head();
2331
2332 self.push_to_nav_history(
2333 *old_cursor_position,
2334 Some(new_cursor_position.to_point(buffer)),
2335 false,
2336 cx,
2337 );
2338
2339 if local {
2340 let new_cursor_position = self.selections.newest_anchor().head();
2341 let mut context_menu = self.context_menu.borrow_mut();
2342 let completion_menu = match context_menu.as_ref() {
2343 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2344 _ => {
2345 *context_menu = None;
2346 None
2347 }
2348 };
2349 if let Some(buffer_id) = new_cursor_position.buffer_id {
2350 if !self.registered_buffers.contains_key(&buffer_id) {
2351 if let Some(project) = self.project.as_ref() {
2352 project.update(cx, |project, cx| {
2353 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2354 return;
2355 };
2356 self.registered_buffers.insert(
2357 buffer_id,
2358 project.register_buffer_with_language_servers(&buffer, cx),
2359 );
2360 })
2361 }
2362 }
2363 }
2364
2365 if let Some(completion_menu) = completion_menu {
2366 let cursor_position = new_cursor_position.to_offset(buffer);
2367 let (word_range, kind) =
2368 buffer.surrounding_word(completion_menu.initial_position, true);
2369 if kind == Some(CharKind::Word)
2370 && word_range.to_inclusive().contains(&cursor_position)
2371 {
2372 let mut completion_menu = completion_menu.clone();
2373 drop(context_menu);
2374
2375 let query = Self::completion_query(buffer, cursor_position);
2376 cx.spawn(async move |this, cx| {
2377 completion_menu
2378 .filter(query.as_deref(), cx.background_executor().clone())
2379 .await;
2380
2381 this.update(cx, |this, cx| {
2382 let mut context_menu = this.context_menu.borrow_mut();
2383 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2384 else {
2385 return;
2386 };
2387
2388 if menu.id > completion_menu.id {
2389 return;
2390 }
2391
2392 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2393 drop(context_menu);
2394 cx.notify();
2395 })
2396 })
2397 .detach();
2398
2399 if show_completions {
2400 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2401 }
2402 } else {
2403 drop(context_menu);
2404 self.hide_context_menu(window, cx);
2405 }
2406 } else {
2407 drop(context_menu);
2408 }
2409
2410 hide_hover(self, cx);
2411
2412 if old_cursor_position.to_display_point(&display_map).row()
2413 != new_cursor_position.to_display_point(&display_map).row()
2414 {
2415 self.available_code_actions.take();
2416 }
2417 self.refresh_code_actions(window, cx);
2418 self.refresh_document_highlights(cx);
2419 self.refresh_selected_text_highlights(window, cx);
2420 refresh_matching_bracket_highlights(self, window, cx);
2421 self.update_visible_inline_completion(window, cx);
2422 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2423 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2424 if self.git_blame_inline_enabled {
2425 self.start_inline_blame_timer(window, cx);
2426 }
2427 }
2428
2429 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2430 cx.emit(EditorEvent::SelectionsChanged { local });
2431
2432 let selections = &self.selections.disjoint;
2433 if selections.len() == 1 {
2434 cx.emit(SearchEvent::ActiveMatchChanged)
2435 }
2436 if local {
2437 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2438 let inmemory_selections = selections
2439 .iter()
2440 .map(|s| {
2441 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2442 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2443 })
2444 .collect();
2445 self.update_restoration_data(cx, |data| {
2446 data.selections = inmemory_selections;
2447 });
2448
2449 if WorkspaceSettings::get(None, cx).restore_on_startup
2450 != RestoreOnStartupBehavior::None
2451 {
2452 if let Some(workspace_id) =
2453 self.workspace.as_ref().and_then(|workspace| workspace.1)
2454 {
2455 let snapshot = self.buffer().read(cx).snapshot(cx);
2456 let selections = selections.clone();
2457 let background_executor = cx.background_executor().clone();
2458 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2459 self.serialize_selections = cx.background_spawn(async move {
2460 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2461 let db_selections = selections
2462 .iter()
2463 .map(|selection| {
2464 (
2465 selection.start.to_offset(&snapshot),
2466 selection.end.to_offset(&snapshot),
2467 )
2468 })
2469 .collect();
2470
2471 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2472 .await
2473 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2474 .log_err();
2475 });
2476 }
2477 }
2478 }
2479 }
2480
2481 cx.notify();
2482 }
2483
2484 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2485 use text::ToOffset as _;
2486 use text::ToPoint as _;
2487
2488 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2489 return;
2490 }
2491
2492 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2493 return;
2494 };
2495
2496 let snapshot = singleton.read(cx).snapshot();
2497 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2498 let display_snapshot = display_map.snapshot(cx);
2499
2500 display_snapshot
2501 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2502 .map(|fold| {
2503 fold.range.start.text_anchor.to_point(&snapshot)
2504 ..fold.range.end.text_anchor.to_point(&snapshot)
2505 })
2506 .collect()
2507 });
2508 self.update_restoration_data(cx, |data| {
2509 data.folds = inmemory_folds;
2510 });
2511
2512 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2513 return;
2514 };
2515 let background_executor = cx.background_executor().clone();
2516 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2517 let db_folds = self.display_map.update(cx, |display_map, cx| {
2518 display_map
2519 .snapshot(cx)
2520 .folds_in_range(0..snapshot.len())
2521 .map(|fold| {
2522 (
2523 fold.range.start.text_anchor.to_offset(&snapshot),
2524 fold.range.end.text_anchor.to_offset(&snapshot),
2525 )
2526 })
2527 .collect()
2528 });
2529 self.serialize_folds = cx.background_spawn(async move {
2530 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2531 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2532 .await
2533 .with_context(|| {
2534 format!(
2535 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2536 )
2537 })
2538 .log_err();
2539 });
2540 }
2541
2542 pub fn sync_selections(
2543 &mut self,
2544 other: Entity<Editor>,
2545 cx: &mut Context<Self>,
2546 ) -> gpui::Subscription {
2547 let other_selections = other.read(cx).selections.disjoint.to_vec();
2548 self.selections.change_with(cx, |selections| {
2549 selections.select_anchors(other_selections);
2550 });
2551
2552 let other_subscription =
2553 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2554 EditorEvent::SelectionsChanged { local: true } => {
2555 let other_selections = other.read(cx).selections.disjoint.to_vec();
2556 if other_selections.is_empty() {
2557 return;
2558 }
2559 this.selections.change_with(cx, |selections| {
2560 selections.select_anchors(other_selections);
2561 });
2562 }
2563 _ => {}
2564 });
2565
2566 let this_subscription =
2567 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2568 EditorEvent::SelectionsChanged { local: true } => {
2569 let these_selections = this.selections.disjoint.to_vec();
2570 if these_selections.is_empty() {
2571 return;
2572 }
2573 other.update(cx, |other_editor, cx| {
2574 other_editor.selections.change_with(cx, |selections| {
2575 selections.select_anchors(these_selections);
2576 })
2577 });
2578 }
2579 _ => {}
2580 });
2581
2582 Subscription::join(other_subscription, this_subscription)
2583 }
2584
2585 pub fn change_selections<R>(
2586 &mut self,
2587 autoscroll: Option<Autoscroll>,
2588 window: &mut Window,
2589 cx: &mut Context<Self>,
2590 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2591 ) -> R {
2592 self.change_selections_inner(autoscroll, true, window, cx, change)
2593 }
2594
2595 fn change_selections_inner<R>(
2596 &mut self,
2597 autoscroll: Option<Autoscroll>,
2598 request_completions: bool,
2599 window: &mut Window,
2600 cx: &mut Context<Self>,
2601 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2602 ) -> R {
2603 let old_cursor_position = self.selections.newest_anchor().head();
2604 self.push_to_selection_history();
2605
2606 let (changed, result) = self.selections.change_with(cx, change);
2607
2608 if changed {
2609 if let Some(autoscroll) = autoscroll {
2610 self.request_autoscroll(autoscroll, cx);
2611 }
2612 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2613
2614 if self.should_open_signature_help_automatically(
2615 &old_cursor_position,
2616 self.signature_help_state.backspace_pressed(),
2617 cx,
2618 ) {
2619 self.show_signature_help(&ShowSignatureHelp, window, cx);
2620 }
2621 self.signature_help_state.set_backspace_pressed(false);
2622 }
2623
2624 result
2625 }
2626
2627 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2628 where
2629 I: IntoIterator<Item = (Range<S>, T)>,
2630 S: ToOffset,
2631 T: Into<Arc<str>>,
2632 {
2633 if self.read_only(cx) {
2634 return;
2635 }
2636
2637 self.buffer
2638 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2639 }
2640
2641 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2642 where
2643 I: IntoIterator<Item = (Range<S>, T)>,
2644 S: ToOffset,
2645 T: Into<Arc<str>>,
2646 {
2647 if self.read_only(cx) {
2648 return;
2649 }
2650
2651 self.buffer.update(cx, |buffer, cx| {
2652 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2653 });
2654 }
2655
2656 pub fn edit_with_block_indent<I, S, T>(
2657 &mut self,
2658 edits: I,
2659 original_indent_columns: Vec<Option<u32>>,
2660 cx: &mut Context<Self>,
2661 ) where
2662 I: IntoIterator<Item = (Range<S>, T)>,
2663 S: ToOffset,
2664 T: Into<Arc<str>>,
2665 {
2666 if self.read_only(cx) {
2667 return;
2668 }
2669
2670 self.buffer.update(cx, |buffer, cx| {
2671 buffer.edit(
2672 edits,
2673 Some(AutoindentMode::Block {
2674 original_indent_columns,
2675 }),
2676 cx,
2677 )
2678 });
2679 }
2680
2681 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2682 self.hide_context_menu(window, cx);
2683
2684 match phase {
2685 SelectPhase::Begin {
2686 position,
2687 add,
2688 click_count,
2689 } => self.begin_selection(position, add, click_count, window, cx),
2690 SelectPhase::BeginColumnar {
2691 position,
2692 goal_column,
2693 reset,
2694 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2695 SelectPhase::Extend {
2696 position,
2697 click_count,
2698 } => self.extend_selection(position, click_count, window, cx),
2699 SelectPhase::Update {
2700 position,
2701 goal_column,
2702 scroll_delta,
2703 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2704 SelectPhase::End => self.end_selection(window, cx),
2705 }
2706 }
2707
2708 fn extend_selection(
2709 &mut self,
2710 position: DisplayPoint,
2711 click_count: usize,
2712 window: &mut Window,
2713 cx: &mut Context<Self>,
2714 ) {
2715 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2716 let tail = self.selections.newest::<usize>(cx).tail();
2717 self.begin_selection(position, false, click_count, window, cx);
2718
2719 let position = position.to_offset(&display_map, Bias::Left);
2720 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2721
2722 let mut pending_selection = self
2723 .selections
2724 .pending_anchor()
2725 .expect("extend_selection not called with pending selection");
2726 if position >= tail {
2727 pending_selection.start = tail_anchor;
2728 } else {
2729 pending_selection.end = tail_anchor;
2730 pending_selection.reversed = true;
2731 }
2732
2733 let mut pending_mode = self.selections.pending_mode().unwrap();
2734 match &mut pending_mode {
2735 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2736 _ => {}
2737 }
2738
2739 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2740 s.set_pending(pending_selection, pending_mode)
2741 });
2742 }
2743
2744 fn begin_selection(
2745 &mut self,
2746 position: DisplayPoint,
2747 add: bool,
2748 click_count: usize,
2749 window: &mut Window,
2750 cx: &mut Context<Self>,
2751 ) {
2752 if !self.focus_handle.is_focused(window) {
2753 self.last_focused_descendant = None;
2754 window.focus(&self.focus_handle);
2755 }
2756
2757 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2758 let buffer = &display_map.buffer_snapshot;
2759 let newest_selection = self.selections.newest_anchor().clone();
2760 let position = display_map.clip_point(position, Bias::Left);
2761
2762 let start;
2763 let end;
2764 let mode;
2765 let mut auto_scroll;
2766 match click_count {
2767 1 => {
2768 start = buffer.anchor_before(position.to_point(&display_map));
2769 end = start;
2770 mode = SelectMode::Character;
2771 auto_scroll = true;
2772 }
2773 2 => {
2774 let range = movement::surrounding_word(&display_map, position);
2775 start = buffer.anchor_before(range.start.to_point(&display_map));
2776 end = buffer.anchor_before(range.end.to_point(&display_map));
2777 mode = SelectMode::Word(start..end);
2778 auto_scroll = true;
2779 }
2780 3 => {
2781 let position = display_map
2782 .clip_point(position, Bias::Left)
2783 .to_point(&display_map);
2784 let line_start = display_map.prev_line_boundary(position).0;
2785 let next_line_start = buffer.clip_point(
2786 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2787 Bias::Left,
2788 );
2789 start = buffer.anchor_before(line_start);
2790 end = buffer.anchor_before(next_line_start);
2791 mode = SelectMode::Line(start..end);
2792 auto_scroll = true;
2793 }
2794 _ => {
2795 start = buffer.anchor_before(0);
2796 end = buffer.anchor_before(buffer.len());
2797 mode = SelectMode::All;
2798 auto_scroll = false;
2799 }
2800 }
2801 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2802
2803 let point_to_delete: Option<usize> = {
2804 let selected_points: Vec<Selection<Point>> =
2805 self.selections.disjoint_in_range(start..end, cx);
2806
2807 if !add || click_count > 1 {
2808 None
2809 } else if !selected_points.is_empty() {
2810 Some(selected_points[0].id)
2811 } else {
2812 let clicked_point_already_selected =
2813 self.selections.disjoint.iter().find(|selection| {
2814 selection.start.to_point(buffer) == start.to_point(buffer)
2815 || selection.end.to_point(buffer) == end.to_point(buffer)
2816 });
2817
2818 clicked_point_already_selected.map(|selection| selection.id)
2819 }
2820 };
2821
2822 let selections_count = self.selections.count();
2823
2824 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2825 if let Some(point_to_delete) = point_to_delete {
2826 s.delete(point_to_delete);
2827
2828 if selections_count == 1 {
2829 s.set_pending_anchor_range(start..end, mode);
2830 }
2831 } else {
2832 if !add {
2833 s.clear_disjoint();
2834 } else if click_count > 1 {
2835 s.delete(newest_selection.id)
2836 }
2837
2838 s.set_pending_anchor_range(start..end, mode);
2839 }
2840 });
2841 }
2842
2843 fn begin_columnar_selection(
2844 &mut self,
2845 position: DisplayPoint,
2846 goal_column: u32,
2847 reset: bool,
2848 window: &mut Window,
2849 cx: &mut Context<Self>,
2850 ) {
2851 if !self.focus_handle.is_focused(window) {
2852 self.last_focused_descendant = None;
2853 window.focus(&self.focus_handle);
2854 }
2855
2856 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2857
2858 if reset {
2859 let pointer_position = display_map
2860 .buffer_snapshot
2861 .anchor_before(position.to_point(&display_map));
2862
2863 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2864 s.clear_disjoint();
2865 s.set_pending_anchor_range(
2866 pointer_position..pointer_position,
2867 SelectMode::Character,
2868 );
2869 });
2870 }
2871
2872 let tail = self.selections.newest::<Point>(cx).tail();
2873 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2874
2875 if !reset {
2876 self.select_columns(
2877 tail.to_display_point(&display_map),
2878 position,
2879 goal_column,
2880 &display_map,
2881 window,
2882 cx,
2883 );
2884 }
2885 }
2886
2887 fn update_selection(
2888 &mut self,
2889 position: DisplayPoint,
2890 goal_column: u32,
2891 scroll_delta: gpui::Point<f32>,
2892 window: &mut Window,
2893 cx: &mut Context<Self>,
2894 ) {
2895 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2896
2897 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2898 let tail = tail.to_display_point(&display_map);
2899 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2900 } else if let Some(mut pending) = self.selections.pending_anchor() {
2901 let buffer = self.buffer.read(cx).snapshot(cx);
2902 let head;
2903 let tail;
2904 let mode = self.selections.pending_mode().unwrap();
2905 match &mode {
2906 SelectMode::Character => {
2907 head = position.to_point(&display_map);
2908 tail = pending.tail().to_point(&buffer);
2909 }
2910 SelectMode::Word(original_range) => {
2911 let original_display_range = original_range.start.to_display_point(&display_map)
2912 ..original_range.end.to_display_point(&display_map);
2913 let original_buffer_range = original_display_range.start.to_point(&display_map)
2914 ..original_display_range.end.to_point(&display_map);
2915 if movement::is_inside_word(&display_map, position)
2916 || original_display_range.contains(&position)
2917 {
2918 let word_range = movement::surrounding_word(&display_map, position);
2919 if word_range.start < original_display_range.start {
2920 head = word_range.start.to_point(&display_map);
2921 } else {
2922 head = word_range.end.to_point(&display_map);
2923 }
2924 } else {
2925 head = position.to_point(&display_map);
2926 }
2927
2928 if head <= original_buffer_range.start {
2929 tail = original_buffer_range.end;
2930 } else {
2931 tail = original_buffer_range.start;
2932 }
2933 }
2934 SelectMode::Line(original_range) => {
2935 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2936
2937 let position = display_map
2938 .clip_point(position, Bias::Left)
2939 .to_point(&display_map);
2940 let line_start = display_map.prev_line_boundary(position).0;
2941 let next_line_start = buffer.clip_point(
2942 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2943 Bias::Left,
2944 );
2945
2946 if line_start < original_range.start {
2947 head = line_start
2948 } else {
2949 head = next_line_start
2950 }
2951
2952 if head <= original_range.start {
2953 tail = original_range.end;
2954 } else {
2955 tail = original_range.start;
2956 }
2957 }
2958 SelectMode::All => {
2959 return;
2960 }
2961 };
2962
2963 if head < tail {
2964 pending.start = buffer.anchor_before(head);
2965 pending.end = buffer.anchor_before(tail);
2966 pending.reversed = true;
2967 } else {
2968 pending.start = buffer.anchor_before(tail);
2969 pending.end = buffer.anchor_before(head);
2970 pending.reversed = false;
2971 }
2972
2973 self.change_selections(None, window, cx, |s| {
2974 s.set_pending(pending, mode);
2975 });
2976 } else {
2977 log::error!("update_selection dispatched with no pending selection");
2978 return;
2979 }
2980
2981 self.apply_scroll_delta(scroll_delta, window, cx);
2982 cx.notify();
2983 }
2984
2985 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2986 self.columnar_selection_tail.take();
2987 if self.selections.pending_anchor().is_some() {
2988 let selections = self.selections.all::<usize>(cx);
2989 self.change_selections(None, window, cx, |s| {
2990 s.select(selections);
2991 s.clear_pending();
2992 });
2993 }
2994 }
2995
2996 fn select_columns(
2997 &mut self,
2998 tail: DisplayPoint,
2999 head: DisplayPoint,
3000 goal_column: u32,
3001 display_map: &DisplaySnapshot,
3002 window: &mut Window,
3003 cx: &mut Context<Self>,
3004 ) {
3005 let start_row = cmp::min(tail.row(), head.row());
3006 let end_row = cmp::max(tail.row(), head.row());
3007 let start_column = cmp::min(tail.column(), goal_column);
3008 let end_column = cmp::max(tail.column(), goal_column);
3009 let reversed = start_column < tail.column();
3010
3011 let selection_ranges = (start_row.0..=end_row.0)
3012 .map(DisplayRow)
3013 .filter_map(|row| {
3014 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3015 let start = display_map
3016 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3017 .to_point(display_map);
3018 let end = display_map
3019 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3020 .to_point(display_map);
3021 if reversed {
3022 Some(end..start)
3023 } else {
3024 Some(start..end)
3025 }
3026 } else {
3027 None
3028 }
3029 })
3030 .collect::<Vec<_>>();
3031
3032 self.change_selections(None, window, cx, |s| {
3033 s.select_ranges(selection_ranges);
3034 });
3035 cx.notify();
3036 }
3037
3038 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3039 self.selections
3040 .all_adjusted(cx)
3041 .iter()
3042 .any(|selection| !selection.is_empty())
3043 }
3044
3045 pub fn has_pending_nonempty_selection(&self) -> bool {
3046 let pending_nonempty_selection = match self.selections.pending_anchor() {
3047 Some(Selection { start, end, .. }) => start != end,
3048 None => false,
3049 };
3050
3051 pending_nonempty_selection
3052 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3053 }
3054
3055 pub fn has_pending_selection(&self) -> bool {
3056 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3057 }
3058
3059 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3060 self.selection_mark_mode = false;
3061
3062 if self.clear_expanded_diff_hunks(cx) {
3063 cx.notify();
3064 return;
3065 }
3066 if self.dismiss_menus_and_popups(true, window, cx) {
3067 return;
3068 }
3069
3070 if self.mode.is_full()
3071 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3072 {
3073 return;
3074 }
3075
3076 cx.propagate();
3077 }
3078
3079 pub fn dismiss_menus_and_popups(
3080 &mut self,
3081 is_user_requested: bool,
3082 window: &mut Window,
3083 cx: &mut Context<Self>,
3084 ) -> bool {
3085 if self.take_rename(false, window, cx).is_some() {
3086 return true;
3087 }
3088
3089 if hide_hover(self, cx) {
3090 return true;
3091 }
3092
3093 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3094 return true;
3095 }
3096
3097 if self.hide_context_menu(window, cx).is_some() {
3098 return true;
3099 }
3100
3101 if self.mouse_context_menu.take().is_some() {
3102 return true;
3103 }
3104
3105 if is_user_requested && self.discard_inline_completion(true, cx) {
3106 return true;
3107 }
3108
3109 if self.snippet_stack.pop().is_some() {
3110 return true;
3111 }
3112
3113 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3114 self.dismiss_diagnostics(cx);
3115 return true;
3116 }
3117
3118 false
3119 }
3120
3121 fn linked_editing_ranges_for(
3122 &self,
3123 selection: Range<text::Anchor>,
3124 cx: &App,
3125 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3126 if self.linked_edit_ranges.is_empty() {
3127 return None;
3128 }
3129 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3130 selection.end.buffer_id.and_then(|end_buffer_id| {
3131 if selection.start.buffer_id != Some(end_buffer_id) {
3132 return None;
3133 }
3134 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3135 let snapshot = buffer.read(cx).snapshot();
3136 self.linked_edit_ranges
3137 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3138 .map(|ranges| (ranges, snapshot, buffer))
3139 })?;
3140 use text::ToOffset as TO;
3141 // find offset from the start of current range to current cursor position
3142 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3143
3144 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3145 let start_difference = start_offset - start_byte_offset;
3146 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3147 let end_difference = end_offset - start_byte_offset;
3148 // Current range has associated linked ranges.
3149 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3150 for range in linked_ranges.iter() {
3151 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3152 let end_offset = start_offset + end_difference;
3153 let start_offset = start_offset + start_difference;
3154 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3155 continue;
3156 }
3157 if self.selections.disjoint_anchor_ranges().any(|s| {
3158 if s.start.buffer_id != selection.start.buffer_id
3159 || s.end.buffer_id != selection.end.buffer_id
3160 {
3161 return false;
3162 }
3163 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3164 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3165 }) {
3166 continue;
3167 }
3168 let start = buffer_snapshot.anchor_after(start_offset);
3169 let end = buffer_snapshot.anchor_after(end_offset);
3170 linked_edits
3171 .entry(buffer.clone())
3172 .or_default()
3173 .push(start..end);
3174 }
3175 Some(linked_edits)
3176 }
3177
3178 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3179 let text: Arc<str> = text.into();
3180
3181 if self.read_only(cx) {
3182 return;
3183 }
3184
3185 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3186
3187 let selections = self.selections.all_adjusted(cx);
3188 let mut bracket_inserted = false;
3189 let mut edits = Vec::new();
3190 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3191 let mut new_selections = Vec::with_capacity(selections.len());
3192 let mut new_autoclose_regions = Vec::new();
3193 let snapshot = self.buffer.read(cx).read(cx);
3194 let mut clear_linked_edit_ranges = false;
3195
3196 for (selection, autoclose_region) in
3197 self.selections_with_autoclose_regions(selections, &snapshot)
3198 {
3199 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3200 // Determine if the inserted text matches the opening or closing
3201 // bracket of any of this language's bracket pairs.
3202 let mut bracket_pair = None;
3203 let mut is_bracket_pair_start = false;
3204 let mut is_bracket_pair_end = false;
3205 if !text.is_empty() {
3206 let mut bracket_pair_matching_end = None;
3207 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3208 // and they are removing the character that triggered IME popup.
3209 for (pair, enabled) in scope.brackets() {
3210 if !pair.close && !pair.surround {
3211 continue;
3212 }
3213
3214 if enabled && pair.start.ends_with(text.as_ref()) {
3215 let prefix_len = pair.start.len() - text.len();
3216 let preceding_text_matches_prefix = prefix_len == 0
3217 || (selection.start.column >= (prefix_len as u32)
3218 && snapshot.contains_str_at(
3219 Point::new(
3220 selection.start.row,
3221 selection.start.column - (prefix_len as u32),
3222 ),
3223 &pair.start[..prefix_len],
3224 ));
3225 if preceding_text_matches_prefix {
3226 bracket_pair = Some(pair.clone());
3227 is_bracket_pair_start = true;
3228 break;
3229 }
3230 }
3231 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3232 {
3233 // take first bracket pair matching end, but don't break in case a later bracket
3234 // pair matches start
3235 bracket_pair_matching_end = Some(pair.clone());
3236 }
3237 }
3238 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3239 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3240 is_bracket_pair_end = true;
3241 }
3242 }
3243
3244 if let Some(bracket_pair) = bracket_pair {
3245 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3246 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3247 let auto_surround =
3248 self.use_auto_surround && snapshot_settings.use_auto_surround;
3249 if selection.is_empty() {
3250 if is_bracket_pair_start {
3251 // If the inserted text is a suffix of an opening bracket and the
3252 // selection is preceded by the rest of the opening bracket, then
3253 // insert the closing bracket.
3254 let following_text_allows_autoclose = snapshot
3255 .chars_at(selection.start)
3256 .next()
3257 .map_or(true, |c| scope.should_autoclose_before(c));
3258
3259 let preceding_text_allows_autoclose = selection.start.column == 0
3260 || snapshot.reversed_chars_at(selection.start).next().map_or(
3261 true,
3262 |c| {
3263 bracket_pair.start != bracket_pair.end
3264 || !snapshot
3265 .char_classifier_at(selection.start)
3266 .is_word(c)
3267 },
3268 );
3269
3270 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3271 && bracket_pair.start.len() == 1
3272 {
3273 let target = bracket_pair.start.chars().next().unwrap();
3274 let current_line_count = snapshot
3275 .reversed_chars_at(selection.start)
3276 .take_while(|&c| c != '\n')
3277 .filter(|&c| c == target)
3278 .count();
3279 current_line_count % 2 == 1
3280 } else {
3281 false
3282 };
3283
3284 if autoclose
3285 && bracket_pair.close
3286 && following_text_allows_autoclose
3287 && preceding_text_allows_autoclose
3288 && !is_closing_quote
3289 {
3290 let anchor = snapshot.anchor_before(selection.end);
3291 new_selections.push((selection.map(|_| anchor), text.len()));
3292 new_autoclose_regions.push((
3293 anchor,
3294 text.len(),
3295 selection.id,
3296 bracket_pair.clone(),
3297 ));
3298 edits.push((
3299 selection.range(),
3300 format!("{}{}", text, bracket_pair.end).into(),
3301 ));
3302 bracket_inserted = true;
3303 continue;
3304 }
3305 }
3306
3307 if let Some(region) = autoclose_region {
3308 // If the selection is followed by an auto-inserted closing bracket,
3309 // then don't insert that closing bracket again; just move the selection
3310 // past the closing bracket.
3311 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3312 && text.as_ref() == region.pair.end.as_str();
3313 if should_skip {
3314 let anchor = snapshot.anchor_after(selection.end);
3315 new_selections
3316 .push((selection.map(|_| anchor), region.pair.end.len()));
3317 continue;
3318 }
3319 }
3320
3321 let always_treat_brackets_as_autoclosed = snapshot
3322 .language_settings_at(selection.start, cx)
3323 .always_treat_brackets_as_autoclosed;
3324 if always_treat_brackets_as_autoclosed
3325 && is_bracket_pair_end
3326 && snapshot.contains_str_at(selection.end, text.as_ref())
3327 {
3328 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3329 // and the inserted text is a closing bracket and the selection is followed
3330 // by the closing bracket then move the selection past the closing bracket.
3331 let anchor = snapshot.anchor_after(selection.end);
3332 new_selections.push((selection.map(|_| anchor), text.len()));
3333 continue;
3334 }
3335 }
3336 // If an opening bracket is 1 character long and is typed while
3337 // text is selected, then surround that text with the bracket pair.
3338 else if auto_surround
3339 && bracket_pair.surround
3340 && is_bracket_pair_start
3341 && bracket_pair.start.chars().count() == 1
3342 {
3343 edits.push((selection.start..selection.start, text.clone()));
3344 edits.push((
3345 selection.end..selection.end,
3346 bracket_pair.end.as_str().into(),
3347 ));
3348 bracket_inserted = true;
3349 new_selections.push((
3350 Selection {
3351 id: selection.id,
3352 start: snapshot.anchor_after(selection.start),
3353 end: snapshot.anchor_before(selection.end),
3354 reversed: selection.reversed,
3355 goal: selection.goal,
3356 },
3357 0,
3358 ));
3359 continue;
3360 }
3361 }
3362 }
3363
3364 if self.auto_replace_emoji_shortcode
3365 && selection.is_empty()
3366 && text.as_ref().ends_with(':')
3367 {
3368 if let Some(possible_emoji_short_code) =
3369 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3370 {
3371 if !possible_emoji_short_code.is_empty() {
3372 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3373 let emoji_shortcode_start = Point::new(
3374 selection.start.row,
3375 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3376 );
3377
3378 // Remove shortcode from buffer
3379 edits.push((
3380 emoji_shortcode_start..selection.start,
3381 "".to_string().into(),
3382 ));
3383 new_selections.push((
3384 Selection {
3385 id: selection.id,
3386 start: snapshot.anchor_after(emoji_shortcode_start),
3387 end: snapshot.anchor_before(selection.start),
3388 reversed: selection.reversed,
3389 goal: selection.goal,
3390 },
3391 0,
3392 ));
3393
3394 // Insert emoji
3395 let selection_start_anchor = snapshot.anchor_after(selection.start);
3396 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3397 edits.push((selection.start..selection.end, emoji.to_string().into()));
3398
3399 continue;
3400 }
3401 }
3402 }
3403 }
3404
3405 // If not handling any auto-close operation, then just replace the selected
3406 // text with the given input and move the selection to the end of the
3407 // newly inserted text.
3408 let anchor = snapshot.anchor_after(selection.end);
3409 if !self.linked_edit_ranges.is_empty() {
3410 let start_anchor = snapshot.anchor_before(selection.start);
3411
3412 let is_word_char = text.chars().next().map_or(true, |char| {
3413 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3414 classifier.is_word(char)
3415 });
3416
3417 if is_word_char {
3418 if let Some(ranges) = self
3419 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3420 {
3421 for (buffer, edits) in ranges {
3422 linked_edits
3423 .entry(buffer.clone())
3424 .or_default()
3425 .extend(edits.into_iter().map(|range| (range, text.clone())));
3426 }
3427 }
3428 } else {
3429 clear_linked_edit_ranges = true;
3430 }
3431 }
3432
3433 new_selections.push((selection.map(|_| anchor), 0));
3434 edits.push((selection.start..selection.end, text.clone()));
3435 }
3436
3437 drop(snapshot);
3438
3439 self.transact(window, cx, |this, window, cx| {
3440 if clear_linked_edit_ranges {
3441 this.linked_edit_ranges.clear();
3442 }
3443 let initial_buffer_versions =
3444 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3445
3446 this.buffer.update(cx, |buffer, cx| {
3447 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3448 });
3449 for (buffer, edits) in linked_edits {
3450 buffer.update(cx, |buffer, cx| {
3451 let snapshot = buffer.snapshot();
3452 let edits = edits
3453 .into_iter()
3454 .map(|(range, text)| {
3455 use text::ToPoint as TP;
3456 let end_point = TP::to_point(&range.end, &snapshot);
3457 let start_point = TP::to_point(&range.start, &snapshot);
3458 (start_point..end_point, text)
3459 })
3460 .sorted_by_key(|(range, _)| range.start);
3461 buffer.edit(edits, None, cx);
3462 })
3463 }
3464 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3465 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3466 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3467 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3468 .zip(new_selection_deltas)
3469 .map(|(selection, delta)| Selection {
3470 id: selection.id,
3471 start: selection.start + delta,
3472 end: selection.end + delta,
3473 reversed: selection.reversed,
3474 goal: SelectionGoal::None,
3475 })
3476 .collect::<Vec<_>>();
3477
3478 let mut i = 0;
3479 for (position, delta, selection_id, pair) in new_autoclose_regions {
3480 let position = position.to_offset(&map.buffer_snapshot) + delta;
3481 let start = map.buffer_snapshot.anchor_before(position);
3482 let end = map.buffer_snapshot.anchor_after(position);
3483 while let Some(existing_state) = this.autoclose_regions.get(i) {
3484 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3485 Ordering::Less => i += 1,
3486 Ordering::Greater => break,
3487 Ordering::Equal => {
3488 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3489 Ordering::Less => i += 1,
3490 Ordering::Equal => break,
3491 Ordering::Greater => break,
3492 }
3493 }
3494 }
3495 }
3496 this.autoclose_regions.insert(
3497 i,
3498 AutocloseRegion {
3499 selection_id,
3500 range: start..end,
3501 pair,
3502 },
3503 );
3504 }
3505
3506 let had_active_inline_completion = this.has_active_inline_completion();
3507 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3508 s.select(new_selections)
3509 });
3510
3511 if !bracket_inserted {
3512 if let Some(on_type_format_task) =
3513 this.trigger_on_type_formatting(text.to_string(), window, cx)
3514 {
3515 on_type_format_task.detach_and_log_err(cx);
3516 }
3517 }
3518
3519 let editor_settings = EditorSettings::get_global(cx);
3520 if bracket_inserted
3521 && (editor_settings.auto_signature_help
3522 || editor_settings.show_signature_help_after_edits)
3523 {
3524 this.show_signature_help(&ShowSignatureHelp, window, cx);
3525 }
3526
3527 let trigger_in_words =
3528 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3529 if this.hard_wrap.is_some() {
3530 let latest: Range<Point> = this.selections.newest(cx).range();
3531 if latest.is_empty()
3532 && this
3533 .buffer()
3534 .read(cx)
3535 .snapshot(cx)
3536 .line_len(MultiBufferRow(latest.start.row))
3537 == latest.start.column
3538 {
3539 this.rewrap_impl(
3540 RewrapOptions {
3541 override_language_settings: true,
3542 preserve_existing_whitespace: true,
3543 },
3544 cx,
3545 )
3546 }
3547 }
3548 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3549 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3550 this.refresh_inline_completion(true, false, window, cx);
3551 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3552 });
3553 }
3554
3555 fn find_possible_emoji_shortcode_at_position(
3556 snapshot: &MultiBufferSnapshot,
3557 position: Point,
3558 ) -> Option<String> {
3559 let mut chars = Vec::new();
3560 let mut found_colon = false;
3561 for char in snapshot.reversed_chars_at(position).take(100) {
3562 // Found a possible emoji shortcode in the middle of the buffer
3563 if found_colon {
3564 if char.is_whitespace() {
3565 chars.reverse();
3566 return Some(chars.iter().collect());
3567 }
3568 // If the previous character is not a whitespace, we are in the middle of a word
3569 // and we only want to complete the shortcode if the word is made up of other emojis
3570 let mut containing_word = String::new();
3571 for ch in snapshot
3572 .reversed_chars_at(position)
3573 .skip(chars.len() + 1)
3574 .take(100)
3575 {
3576 if ch.is_whitespace() {
3577 break;
3578 }
3579 containing_word.push(ch);
3580 }
3581 let containing_word = containing_word.chars().rev().collect::<String>();
3582 if util::word_consists_of_emojis(containing_word.as_str()) {
3583 chars.reverse();
3584 return Some(chars.iter().collect());
3585 }
3586 }
3587
3588 if char.is_whitespace() || !char.is_ascii() {
3589 return None;
3590 }
3591 if char == ':' {
3592 found_colon = true;
3593 } else {
3594 chars.push(char);
3595 }
3596 }
3597 // Found a possible emoji shortcode at the beginning of the buffer
3598 chars.reverse();
3599 Some(chars.iter().collect())
3600 }
3601
3602 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3603 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3604 self.transact(window, cx, |this, window, cx| {
3605 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3606 let selections = this.selections.all::<usize>(cx);
3607 let multi_buffer = this.buffer.read(cx);
3608 let buffer = multi_buffer.snapshot(cx);
3609 selections
3610 .iter()
3611 .map(|selection| {
3612 let start_point = selection.start.to_point(&buffer);
3613 let mut indent =
3614 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3615 indent.len = cmp::min(indent.len, start_point.column);
3616 let start = selection.start;
3617 let end = selection.end;
3618 let selection_is_empty = start == end;
3619 let language_scope = buffer.language_scope_at(start);
3620 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3621 &language_scope
3622 {
3623 let insert_extra_newline =
3624 insert_extra_newline_brackets(&buffer, start..end, language)
3625 || insert_extra_newline_tree_sitter(&buffer, start..end);
3626
3627 // Comment extension on newline is allowed only for cursor selections
3628 let comment_delimiter = maybe!({
3629 if !selection_is_empty {
3630 return None;
3631 }
3632
3633 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3634 return None;
3635 }
3636
3637 let delimiters = language.line_comment_prefixes();
3638 let max_len_of_delimiter =
3639 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3640 let (snapshot, range) =
3641 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3642
3643 let mut index_of_first_non_whitespace = 0;
3644 let comment_candidate = snapshot
3645 .chars_for_range(range)
3646 .skip_while(|c| {
3647 let should_skip = c.is_whitespace();
3648 if should_skip {
3649 index_of_first_non_whitespace += 1;
3650 }
3651 should_skip
3652 })
3653 .take(max_len_of_delimiter)
3654 .collect::<String>();
3655 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3656 comment_candidate.starts_with(comment_prefix.as_ref())
3657 })?;
3658 let cursor_is_placed_after_comment_marker =
3659 index_of_first_non_whitespace + comment_prefix.len()
3660 <= start_point.column as usize;
3661 if cursor_is_placed_after_comment_marker {
3662 Some(comment_prefix.clone())
3663 } else {
3664 None
3665 }
3666 });
3667 (comment_delimiter, insert_extra_newline)
3668 } else {
3669 (None, false)
3670 };
3671
3672 let capacity_for_delimiter = comment_delimiter
3673 .as_deref()
3674 .map(str::len)
3675 .unwrap_or_default();
3676 let mut new_text =
3677 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3678 new_text.push('\n');
3679 new_text.extend(indent.chars());
3680 if let Some(delimiter) = &comment_delimiter {
3681 new_text.push_str(delimiter);
3682 }
3683 if insert_extra_newline {
3684 new_text = new_text.repeat(2);
3685 }
3686
3687 let anchor = buffer.anchor_after(end);
3688 let new_selection = selection.map(|_| anchor);
3689 (
3690 (start..end, new_text),
3691 (insert_extra_newline, new_selection),
3692 )
3693 })
3694 .unzip()
3695 };
3696
3697 this.edit_with_autoindent(edits, cx);
3698 let buffer = this.buffer.read(cx).snapshot(cx);
3699 let new_selections = selection_fixup_info
3700 .into_iter()
3701 .map(|(extra_newline_inserted, new_selection)| {
3702 let mut cursor = new_selection.end.to_point(&buffer);
3703 if extra_newline_inserted {
3704 cursor.row -= 1;
3705 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3706 }
3707 new_selection.map(|_| cursor)
3708 })
3709 .collect();
3710
3711 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3712 s.select(new_selections)
3713 });
3714 this.refresh_inline_completion(true, false, window, cx);
3715 });
3716 }
3717
3718 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3719 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3720
3721 let buffer = self.buffer.read(cx);
3722 let snapshot = buffer.snapshot(cx);
3723
3724 let mut edits = Vec::new();
3725 let mut rows = Vec::new();
3726
3727 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3728 let cursor = selection.head();
3729 let row = cursor.row;
3730
3731 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3732
3733 let newline = "\n".to_string();
3734 edits.push((start_of_line..start_of_line, newline));
3735
3736 rows.push(row + rows_inserted as u32);
3737 }
3738
3739 self.transact(window, cx, |editor, window, cx| {
3740 editor.edit(edits, cx);
3741
3742 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3743 let mut index = 0;
3744 s.move_cursors_with(|map, _, _| {
3745 let row = rows[index];
3746 index += 1;
3747
3748 let point = Point::new(row, 0);
3749 let boundary = map.next_line_boundary(point).1;
3750 let clipped = map.clip_point(boundary, Bias::Left);
3751
3752 (clipped, SelectionGoal::None)
3753 });
3754 });
3755
3756 let mut indent_edits = Vec::new();
3757 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3758 for row in rows {
3759 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3760 for (row, indent) in indents {
3761 if indent.len == 0 {
3762 continue;
3763 }
3764
3765 let text = match indent.kind {
3766 IndentKind::Space => " ".repeat(indent.len as usize),
3767 IndentKind::Tab => "\t".repeat(indent.len as usize),
3768 };
3769 let point = Point::new(row.0, 0);
3770 indent_edits.push((point..point, text));
3771 }
3772 }
3773 editor.edit(indent_edits, cx);
3774 });
3775 }
3776
3777 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3778 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3779
3780 let buffer = self.buffer.read(cx);
3781 let snapshot = buffer.snapshot(cx);
3782
3783 let mut edits = Vec::new();
3784 let mut rows = Vec::new();
3785 let mut rows_inserted = 0;
3786
3787 for selection in self.selections.all_adjusted(cx) {
3788 let cursor = selection.head();
3789 let row = cursor.row;
3790
3791 let point = Point::new(row + 1, 0);
3792 let start_of_line = snapshot.clip_point(point, Bias::Left);
3793
3794 let newline = "\n".to_string();
3795 edits.push((start_of_line..start_of_line, newline));
3796
3797 rows_inserted += 1;
3798 rows.push(row + rows_inserted);
3799 }
3800
3801 self.transact(window, cx, |editor, window, cx| {
3802 editor.edit(edits, cx);
3803
3804 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3805 let mut index = 0;
3806 s.move_cursors_with(|map, _, _| {
3807 let row = rows[index];
3808 index += 1;
3809
3810 let point = Point::new(row, 0);
3811 let boundary = map.next_line_boundary(point).1;
3812 let clipped = map.clip_point(boundary, Bias::Left);
3813
3814 (clipped, SelectionGoal::None)
3815 });
3816 });
3817
3818 let mut indent_edits = Vec::new();
3819 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3820 for row in rows {
3821 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3822 for (row, indent) in indents {
3823 if indent.len == 0 {
3824 continue;
3825 }
3826
3827 let text = match indent.kind {
3828 IndentKind::Space => " ".repeat(indent.len as usize),
3829 IndentKind::Tab => "\t".repeat(indent.len as usize),
3830 };
3831 let point = Point::new(row.0, 0);
3832 indent_edits.push((point..point, text));
3833 }
3834 }
3835 editor.edit(indent_edits, cx);
3836 });
3837 }
3838
3839 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3840 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3841 original_indent_columns: Vec::new(),
3842 });
3843 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3844 }
3845
3846 fn insert_with_autoindent_mode(
3847 &mut self,
3848 text: &str,
3849 autoindent_mode: Option<AutoindentMode>,
3850 window: &mut Window,
3851 cx: &mut Context<Self>,
3852 ) {
3853 if self.read_only(cx) {
3854 return;
3855 }
3856
3857 let text: Arc<str> = text.into();
3858 self.transact(window, cx, |this, window, cx| {
3859 let old_selections = this.selections.all_adjusted(cx);
3860 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3861 let anchors = {
3862 let snapshot = buffer.read(cx);
3863 old_selections
3864 .iter()
3865 .map(|s| {
3866 let anchor = snapshot.anchor_after(s.head());
3867 s.map(|_| anchor)
3868 })
3869 .collect::<Vec<_>>()
3870 };
3871 buffer.edit(
3872 old_selections
3873 .iter()
3874 .map(|s| (s.start..s.end, text.clone())),
3875 autoindent_mode,
3876 cx,
3877 );
3878 anchors
3879 });
3880
3881 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3882 s.select_anchors(selection_anchors);
3883 });
3884
3885 cx.notify();
3886 });
3887 }
3888
3889 fn trigger_completion_on_input(
3890 &mut self,
3891 text: &str,
3892 trigger_in_words: bool,
3893 window: &mut Window,
3894 cx: &mut Context<Self>,
3895 ) {
3896 let ignore_completion_provider = self
3897 .context_menu
3898 .borrow()
3899 .as_ref()
3900 .map(|menu| match menu {
3901 CodeContextMenu::Completions(completions_menu) => {
3902 completions_menu.ignore_completion_provider
3903 }
3904 CodeContextMenu::CodeActions(_) => false,
3905 })
3906 .unwrap_or(false);
3907
3908 if ignore_completion_provider {
3909 self.show_word_completions(&ShowWordCompletions, window, cx);
3910 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3911 self.show_completions(
3912 &ShowCompletions {
3913 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3914 },
3915 window,
3916 cx,
3917 );
3918 } else {
3919 self.hide_context_menu(window, cx);
3920 }
3921 }
3922
3923 fn is_completion_trigger(
3924 &self,
3925 text: &str,
3926 trigger_in_words: bool,
3927 cx: &mut Context<Self>,
3928 ) -> bool {
3929 let position = self.selections.newest_anchor().head();
3930 let multibuffer = self.buffer.read(cx);
3931 let Some(buffer) = position
3932 .buffer_id
3933 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3934 else {
3935 return false;
3936 };
3937
3938 if let Some(completion_provider) = &self.completion_provider {
3939 completion_provider.is_completion_trigger(
3940 &buffer,
3941 position.text_anchor,
3942 text,
3943 trigger_in_words,
3944 cx,
3945 )
3946 } else {
3947 false
3948 }
3949 }
3950
3951 /// If any empty selections is touching the start of its innermost containing autoclose
3952 /// region, expand it to select the brackets.
3953 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3954 let selections = self.selections.all::<usize>(cx);
3955 let buffer = self.buffer.read(cx).read(cx);
3956 let new_selections = self
3957 .selections_with_autoclose_regions(selections, &buffer)
3958 .map(|(mut selection, region)| {
3959 if !selection.is_empty() {
3960 return selection;
3961 }
3962
3963 if let Some(region) = region {
3964 let mut range = region.range.to_offset(&buffer);
3965 if selection.start == range.start && range.start >= region.pair.start.len() {
3966 range.start -= region.pair.start.len();
3967 if buffer.contains_str_at(range.start, ®ion.pair.start)
3968 && buffer.contains_str_at(range.end, ®ion.pair.end)
3969 {
3970 range.end += region.pair.end.len();
3971 selection.start = range.start;
3972 selection.end = range.end;
3973
3974 return selection;
3975 }
3976 }
3977 }
3978
3979 let always_treat_brackets_as_autoclosed = buffer
3980 .language_settings_at(selection.start, cx)
3981 .always_treat_brackets_as_autoclosed;
3982
3983 if !always_treat_brackets_as_autoclosed {
3984 return selection;
3985 }
3986
3987 if let Some(scope) = buffer.language_scope_at(selection.start) {
3988 for (pair, enabled) in scope.brackets() {
3989 if !enabled || !pair.close {
3990 continue;
3991 }
3992
3993 if buffer.contains_str_at(selection.start, &pair.end) {
3994 let pair_start_len = pair.start.len();
3995 if buffer.contains_str_at(
3996 selection.start.saturating_sub(pair_start_len),
3997 &pair.start,
3998 ) {
3999 selection.start -= pair_start_len;
4000 selection.end += pair.end.len();
4001
4002 return selection;
4003 }
4004 }
4005 }
4006 }
4007
4008 selection
4009 })
4010 .collect();
4011
4012 drop(buffer);
4013 self.change_selections(None, window, cx, |selections| {
4014 selections.select(new_selections)
4015 });
4016 }
4017
4018 /// Iterate the given selections, and for each one, find the smallest surrounding
4019 /// autoclose region. This uses the ordering of the selections and the autoclose
4020 /// regions to avoid repeated comparisons.
4021 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4022 &'a self,
4023 selections: impl IntoIterator<Item = Selection<D>>,
4024 buffer: &'a MultiBufferSnapshot,
4025 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4026 let mut i = 0;
4027 let mut regions = self.autoclose_regions.as_slice();
4028 selections.into_iter().map(move |selection| {
4029 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4030
4031 let mut enclosing = None;
4032 while let Some(pair_state) = regions.get(i) {
4033 if pair_state.range.end.to_offset(buffer) < range.start {
4034 regions = ®ions[i + 1..];
4035 i = 0;
4036 } else if pair_state.range.start.to_offset(buffer) > range.end {
4037 break;
4038 } else {
4039 if pair_state.selection_id == selection.id {
4040 enclosing = Some(pair_state);
4041 }
4042 i += 1;
4043 }
4044 }
4045
4046 (selection, enclosing)
4047 })
4048 }
4049
4050 /// Remove any autoclose regions that no longer contain their selection.
4051 fn invalidate_autoclose_regions(
4052 &mut self,
4053 mut selections: &[Selection<Anchor>],
4054 buffer: &MultiBufferSnapshot,
4055 ) {
4056 self.autoclose_regions.retain(|state| {
4057 let mut i = 0;
4058 while let Some(selection) = selections.get(i) {
4059 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4060 selections = &selections[1..];
4061 continue;
4062 }
4063 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4064 break;
4065 }
4066 if selection.id == state.selection_id {
4067 return true;
4068 } else {
4069 i += 1;
4070 }
4071 }
4072 false
4073 });
4074 }
4075
4076 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4077 let offset = position.to_offset(buffer);
4078 let (word_range, kind) = buffer.surrounding_word(offset, true);
4079 if offset > word_range.start && kind == Some(CharKind::Word) {
4080 Some(
4081 buffer
4082 .text_for_range(word_range.start..offset)
4083 .collect::<String>(),
4084 )
4085 } else {
4086 None
4087 }
4088 }
4089
4090 pub fn toggle_inlay_hints(
4091 &mut self,
4092 _: &ToggleInlayHints,
4093 _: &mut Window,
4094 cx: &mut Context<Self>,
4095 ) {
4096 self.refresh_inlay_hints(
4097 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4098 cx,
4099 );
4100 }
4101
4102 pub fn inlay_hints_enabled(&self) -> bool {
4103 self.inlay_hint_cache.enabled
4104 }
4105
4106 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4107 if self.semantics_provider.is_none() || !self.mode.is_full() {
4108 return;
4109 }
4110
4111 let reason_description = reason.description();
4112 let ignore_debounce = matches!(
4113 reason,
4114 InlayHintRefreshReason::SettingsChange(_)
4115 | InlayHintRefreshReason::Toggle(_)
4116 | InlayHintRefreshReason::ExcerptsRemoved(_)
4117 | InlayHintRefreshReason::ModifiersChanged(_)
4118 );
4119 let (invalidate_cache, required_languages) = match reason {
4120 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4121 match self.inlay_hint_cache.modifiers_override(enabled) {
4122 Some(enabled) => {
4123 if enabled {
4124 (InvalidationStrategy::RefreshRequested, None)
4125 } else {
4126 self.splice_inlays(
4127 &self
4128 .visible_inlay_hints(cx)
4129 .iter()
4130 .map(|inlay| inlay.id)
4131 .collect::<Vec<InlayId>>(),
4132 Vec::new(),
4133 cx,
4134 );
4135 return;
4136 }
4137 }
4138 None => return,
4139 }
4140 }
4141 InlayHintRefreshReason::Toggle(enabled) => {
4142 if self.inlay_hint_cache.toggle(enabled) {
4143 if enabled {
4144 (InvalidationStrategy::RefreshRequested, None)
4145 } else {
4146 self.splice_inlays(
4147 &self
4148 .visible_inlay_hints(cx)
4149 .iter()
4150 .map(|inlay| inlay.id)
4151 .collect::<Vec<InlayId>>(),
4152 Vec::new(),
4153 cx,
4154 );
4155 return;
4156 }
4157 } else {
4158 return;
4159 }
4160 }
4161 InlayHintRefreshReason::SettingsChange(new_settings) => {
4162 match self.inlay_hint_cache.update_settings(
4163 &self.buffer,
4164 new_settings,
4165 self.visible_inlay_hints(cx),
4166 cx,
4167 ) {
4168 ControlFlow::Break(Some(InlaySplice {
4169 to_remove,
4170 to_insert,
4171 })) => {
4172 self.splice_inlays(&to_remove, to_insert, cx);
4173 return;
4174 }
4175 ControlFlow::Break(None) => return,
4176 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4177 }
4178 }
4179 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4180 if let Some(InlaySplice {
4181 to_remove,
4182 to_insert,
4183 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4184 {
4185 self.splice_inlays(&to_remove, to_insert, cx);
4186 }
4187 self.display_map.update(cx, |display_map, _| {
4188 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4189 });
4190 return;
4191 }
4192 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4193 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4194 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4195 }
4196 InlayHintRefreshReason::RefreshRequested => {
4197 (InvalidationStrategy::RefreshRequested, None)
4198 }
4199 };
4200
4201 if let Some(InlaySplice {
4202 to_remove,
4203 to_insert,
4204 }) = self.inlay_hint_cache.spawn_hint_refresh(
4205 reason_description,
4206 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4207 invalidate_cache,
4208 ignore_debounce,
4209 cx,
4210 ) {
4211 self.splice_inlays(&to_remove, to_insert, cx);
4212 }
4213 }
4214
4215 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4216 self.display_map
4217 .read(cx)
4218 .current_inlays()
4219 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4220 .cloned()
4221 .collect()
4222 }
4223
4224 pub fn excerpts_for_inlay_hints_query(
4225 &self,
4226 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4227 cx: &mut Context<Editor>,
4228 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4229 let Some(project) = self.project.as_ref() else {
4230 return HashMap::default();
4231 };
4232 let project = project.read(cx);
4233 let multi_buffer = self.buffer().read(cx);
4234 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4235 let multi_buffer_visible_start = self
4236 .scroll_manager
4237 .anchor()
4238 .anchor
4239 .to_point(&multi_buffer_snapshot);
4240 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4241 multi_buffer_visible_start
4242 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4243 Bias::Left,
4244 );
4245 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4246 multi_buffer_snapshot
4247 .range_to_buffer_ranges(multi_buffer_visible_range)
4248 .into_iter()
4249 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4250 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4251 let buffer_file = project::File::from_dyn(buffer.file())?;
4252 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4253 let worktree_entry = buffer_worktree
4254 .read(cx)
4255 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4256 if worktree_entry.is_ignored {
4257 return None;
4258 }
4259
4260 let language = buffer.language()?;
4261 if let Some(restrict_to_languages) = restrict_to_languages {
4262 if !restrict_to_languages.contains(language) {
4263 return None;
4264 }
4265 }
4266 Some((
4267 excerpt_id,
4268 (
4269 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4270 buffer.version().clone(),
4271 excerpt_visible_range,
4272 ),
4273 ))
4274 })
4275 .collect()
4276 }
4277
4278 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4279 TextLayoutDetails {
4280 text_system: window.text_system().clone(),
4281 editor_style: self.style.clone().unwrap(),
4282 rem_size: window.rem_size(),
4283 scroll_anchor: self.scroll_manager.anchor(),
4284 visible_rows: self.visible_line_count(),
4285 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4286 }
4287 }
4288
4289 pub fn splice_inlays(
4290 &self,
4291 to_remove: &[InlayId],
4292 to_insert: Vec<Inlay>,
4293 cx: &mut Context<Self>,
4294 ) {
4295 self.display_map.update(cx, |display_map, cx| {
4296 display_map.splice_inlays(to_remove, to_insert, cx)
4297 });
4298 cx.notify();
4299 }
4300
4301 fn trigger_on_type_formatting(
4302 &self,
4303 input: String,
4304 window: &mut Window,
4305 cx: &mut Context<Self>,
4306 ) -> Option<Task<Result<()>>> {
4307 if input.len() != 1 {
4308 return None;
4309 }
4310
4311 let project = self.project.as_ref()?;
4312 let position = self.selections.newest_anchor().head();
4313 let (buffer, buffer_position) = self
4314 .buffer
4315 .read(cx)
4316 .text_anchor_for_position(position, cx)?;
4317
4318 let settings = language_settings::language_settings(
4319 buffer
4320 .read(cx)
4321 .language_at(buffer_position)
4322 .map(|l| l.name()),
4323 buffer.read(cx).file(),
4324 cx,
4325 );
4326 if !settings.use_on_type_format {
4327 return None;
4328 }
4329
4330 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4331 // hence we do LSP request & edit on host side only — add formats to host's history.
4332 let push_to_lsp_host_history = true;
4333 // If this is not the host, append its history with new edits.
4334 let push_to_client_history = project.read(cx).is_via_collab();
4335
4336 let on_type_formatting = project.update(cx, |project, cx| {
4337 project.on_type_format(
4338 buffer.clone(),
4339 buffer_position,
4340 input,
4341 push_to_lsp_host_history,
4342 cx,
4343 )
4344 });
4345 Some(cx.spawn_in(window, async move |editor, cx| {
4346 if let Some(transaction) = on_type_formatting.await? {
4347 if push_to_client_history {
4348 buffer
4349 .update(cx, |buffer, _| {
4350 buffer.push_transaction(transaction, Instant::now());
4351 buffer.finalize_last_transaction();
4352 })
4353 .ok();
4354 }
4355 editor.update(cx, |editor, cx| {
4356 editor.refresh_document_highlights(cx);
4357 })?;
4358 }
4359 Ok(())
4360 }))
4361 }
4362
4363 pub fn show_word_completions(
4364 &mut self,
4365 _: &ShowWordCompletions,
4366 window: &mut Window,
4367 cx: &mut Context<Self>,
4368 ) {
4369 self.open_completions_menu(true, None, window, cx);
4370 }
4371
4372 pub fn show_completions(
4373 &mut self,
4374 options: &ShowCompletions,
4375 window: &mut Window,
4376 cx: &mut Context<Self>,
4377 ) {
4378 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4379 }
4380
4381 fn open_completions_menu(
4382 &mut self,
4383 ignore_completion_provider: bool,
4384 trigger: Option<&str>,
4385 window: &mut Window,
4386 cx: &mut Context<Self>,
4387 ) {
4388 if self.pending_rename.is_some() {
4389 return;
4390 }
4391 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4392 return;
4393 }
4394
4395 let position = self.selections.newest_anchor().head();
4396 if position.diff_base_anchor.is_some() {
4397 return;
4398 }
4399 let (buffer, buffer_position) =
4400 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4401 output
4402 } else {
4403 return;
4404 };
4405 let buffer_snapshot = buffer.read(cx).snapshot();
4406 let show_completion_documentation = buffer_snapshot
4407 .settings_at(buffer_position, cx)
4408 .show_completion_documentation;
4409
4410 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4411
4412 let trigger_kind = match trigger {
4413 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4414 CompletionTriggerKind::TRIGGER_CHARACTER
4415 }
4416 _ => CompletionTriggerKind::INVOKED,
4417 };
4418 let completion_context = CompletionContext {
4419 trigger_character: trigger.and_then(|trigger| {
4420 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4421 Some(String::from(trigger))
4422 } else {
4423 None
4424 }
4425 }),
4426 trigger_kind,
4427 };
4428
4429 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4430 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4431 let word_to_exclude = buffer_snapshot
4432 .text_for_range(old_range.clone())
4433 .collect::<String>();
4434 (
4435 buffer_snapshot.anchor_before(old_range.start)
4436 ..buffer_snapshot.anchor_after(old_range.end),
4437 Some(word_to_exclude),
4438 )
4439 } else {
4440 (buffer_position..buffer_position, None)
4441 };
4442
4443 let completion_settings = language_settings(
4444 buffer_snapshot
4445 .language_at(buffer_position)
4446 .map(|language| language.name()),
4447 buffer_snapshot.file(),
4448 cx,
4449 )
4450 .completions;
4451
4452 // The document can be large, so stay in reasonable bounds when searching for words,
4453 // otherwise completion pop-up might be slow to appear.
4454 const WORD_LOOKUP_ROWS: u32 = 5_000;
4455 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4456 let min_word_search = buffer_snapshot.clip_point(
4457 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4458 Bias::Left,
4459 );
4460 let max_word_search = buffer_snapshot.clip_point(
4461 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4462 Bias::Right,
4463 );
4464 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4465 ..buffer_snapshot.point_to_offset(max_word_search);
4466
4467 let provider = self
4468 .completion_provider
4469 .as_ref()
4470 .filter(|_| !ignore_completion_provider);
4471 let skip_digits = query
4472 .as_ref()
4473 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4474
4475 let (mut words, provided_completions) = match provider {
4476 Some(provider) => {
4477 let completions = provider.completions(
4478 position.excerpt_id,
4479 &buffer,
4480 buffer_position,
4481 completion_context,
4482 window,
4483 cx,
4484 );
4485
4486 let words = match completion_settings.words {
4487 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4488 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4489 .background_spawn(async move {
4490 buffer_snapshot.words_in_range(WordsQuery {
4491 fuzzy_contents: None,
4492 range: word_search_range,
4493 skip_digits,
4494 })
4495 }),
4496 };
4497
4498 (words, completions)
4499 }
4500 None => (
4501 cx.background_spawn(async move {
4502 buffer_snapshot.words_in_range(WordsQuery {
4503 fuzzy_contents: None,
4504 range: word_search_range,
4505 skip_digits,
4506 })
4507 }),
4508 Task::ready(Ok(None)),
4509 ),
4510 };
4511
4512 let sort_completions = provider
4513 .as_ref()
4514 .map_or(false, |provider| provider.sort_completions());
4515
4516 let filter_completions = provider
4517 .as_ref()
4518 .map_or(true, |provider| provider.filter_completions());
4519
4520 let id = post_inc(&mut self.next_completion_id);
4521 let task = cx.spawn_in(window, async move |editor, cx| {
4522 async move {
4523 editor.update(cx, |this, _| {
4524 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4525 })?;
4526
4527 let mut completions = Vec::new();
4528 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4529 completions.extend(provided_completions);
4530 if completion_settings.words == WordsCompletionMode::Fallback {
4531 words = Task::ready(BTreeMap::default());
4532 }
4533 }
4534
4535 let mut words = words.await;
4536 if let Some(word_to_exclude) = &word_to_exclude {
4537 words.remove(word_to_exclude);
4538 }
4539 for lsp_completion in &completions {
4540 words.remove(&lsp_completion.new_text);
4541 }
4542 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4543 replace_range: old_range.clone(),
4544 new_text: word.clone(),
4545 label: CodeLabel::plain(word, None),
4546 icon_path: None,
4547 documentation: None,
4548 source: CompletionSource::BufferWord {
4549 word_range,
4550 resolved: false,
4551 },
4552 insert_text_mode: Some(InsertTextMode::AS_IS),
4553 confirm: None,
4554 }));
4555
4556 let menu = if completions.is_empty() {
4557 None
4558 } else {
4559 let mut menu = CompletionsMenu::new(
4560 id,
4561 sort_completions,
4562 show_completion_documentation,
4563 ignore_completion_provider,
4564 position,
4565 buffer.clone(),
4566 completions.into(),
4567 );
4568
4569 menu.filter(
4570 if filter_completions {
4571 query.as_deref()
4572 } else {
4573 None
4574 },
4575 cx.background_executor().clone(),
4576 )
4577 .await;
4578
4579 menu.visible().then_some(menu)
4580 };
4581
4582 editor.update_in(cx, |editor, window, cx| {
4583 match editor.context_menu.borrow().as_ref() {
4584 None => {}
4585 Some(CodeContextMenu::Completions(prev_menu)) => {
4586 if prev_menu.id > id {
4587 return;
4588 }
4589 }
4590 _ => return,
4591 }
4592
4593 if editor.focus_handle.is_focused(window) && menu.is_some() {
4594 let mut menu = menu.unwrap();
4595 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4596
4597 *editor.context_menu.borrow_mut() =
4598 Some(CodeContextMenu::Completions(menu));
4599
4600 if editor.show_edit_predictions_in_menu() {
4601 editor.update_visible_inline_completion(window, cx);
4602 } else {
4603 editor.discard_inline_completion(false, cx);
4604 }
4605
4606 cx.notify();
4607 } else if editor.completion_tasks.len() <= 1 {
4608 // If there are no more completion tasks and the last menu was
4609 // empty, we should hide it.
4610 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4611 // If it was already hidden and we don't show inline
4612 // completions in the menu, we should also show the
4613 // inline-completion when available.
4614 if was_hidden && editor.show_edit_predictions_in_menu() {
4615 editor.update_visible_inline_completion(window, cx);
4616 }
4617 }
4618 })?;
4619
4620 anyhow::Ok(())
4621 }
4622 .log_err()
4623 .await
4624 });
4625
4626 self.completion_tasks.push((id, task));
4627 }
4628
4629 #[cfg(feature = "test-support")]
4630 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4631 let menu = self.context_menu.borrow();
4632 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4633 let completions = menu.completions.borrow();
4634 Some(completions.to_vec())
4635 } else {
4636 None
4637 }
4638 }
4639
4640 pub fn confirm_completion(
4641 &mut self,
4642 action: &ConfirmCompletion,
4643 window: &mut Window,
4644 cx: &mut Context<Self>,
4645 ) -> Option<Task<Result<()>>> {
4646 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4647 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4648 }
4649
4650 pub fn confirm_completion_insert(
4651 &mut self,
4652 _: &ConfirmCompletionInsert,
4653 window: &mut Window,
4654 cx: &mut Context<Self>,
4655 ) -> Option<Task<Result<()>>> {
4656 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4657 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4658 }
4659
4660 pub fn confirm_completion_replace(
4661 &mut self,
4662 _: &ConfirmCompletionReplace,
4663 window: &mut Window,
4664 cx: &mut Context<Self>,
4665 ) -> Option<Task<Result<()>>> {
4666 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4667 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4668 }
4669
4670 pub fn compose_completion(
4671 &mut self,
4672 action: &ComposeCompletion,
4673 window: &mut Window,
4674 cx: &mut Context<Self>,
4675 ) -> Option<Task<Result<()>>> {
4676 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4677 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4678 }
4679
4680 fn do_completion(
4681 &mut self,
4682 item_ix: Option<usize>,
4683 intent: CompletionIntent,
4684 window: &mut Window,
4685 cx: &mut Context<Editor>,
4686 ) -> Option<Task<Result<()>>> {
4687 use language::ToOffset as _;
4688
4689 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4690 else {
4691 return None;
4692 };
4693
4694 let candidate_id = {
4695 let entries = completions_menu.entries.borrow();
4696 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4697 if self.show_edit_predictions_in_menu() {
4698 self.discard_inline_completion(true, cx);
4699 }
4700 mat.candidate_id
4701 };
4702
4703 let buffer_handle = completions_menu.buffer;
4704 let completion = completions_menu
4705 .completions
4706 .borrow()
4707 .get(candidate_id)?
4708 .clone();
4709 cx.stop_propagation();
4710
4711 let snippet;
4712 let new_text;
4713 if completion.is_snippet() {
4714 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4715 new_text = snippet.as_ref().unwrap().text.clone();
4716 } else {
4717 snippet = None;
4718 new_text = completion.new_text.clone();
4719 };
4720
4721 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4722 let buffer = buffer_handle.read(cx);
4723 let snapshot = self.buffer.read(cx).snapshot(cx);
4724 let replace_range_multibuffer = {
4725 let excerpt = snapshot
4726 .excerpt_containing(self.selections.newest_anchor().range())
4727 .unwrap();
4728 let multibuffer_anchor = snapshot
4729 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4730 .unwrap()
4731 ..snapshot
4732 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4733 .unwrap();
4734 multibuffer_anchor.start.to_offset(&snapshot)
4735 ..multibuffer_anchor.end.to_offset(&snapshot)
4736 };
4737 let newest_anchor = self.selections.newest_anchor();
4738 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4739 return None;
4740 }
4741
4742 let old_text = buffer
4743 .text_for_range(replace_range.clone())
4744 .collect::<String>();
4745 let lookbehind = newest_anchor
4746 .start
4747 .text_anchor
4748 .to_offset(buffer)
4749 .saturating_sub(replace_range.start);
4750 let lookahead = replace_range
4751 .end
4752 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4753 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4754 let suffix = &old_text[lookbehind.min(old_text.len())..];
4755
4756 let selections = self.selections.all::<usize>(cx);
4757 let mut ranges = Vec::new();
4758 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4759
4760 for selection in &selections {
4761 let range = if selection.id == newest_anchor.id {
4762 replace_range_multibuffer.clone()
4763 } else {
4764 let mut range = selection.range();
4765
4766 // if prefix is present, don't duplicate it
4767 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4768 range.start = range.start.saturating_sub(lookbehind);
4769
4770 // if suffix is also present, mimic the newest cursor and replace it
4771 if selection.id != newest_anchor.id
4772 && snapshot.contains_str_at(range.end, suffix)
4773 {
4774 range.end += lookahead;
4775 }
4776 }
4777 range
4778 };
4779
4780 ranges.push(range);
4781
4782 if !self.linked_edit_ranges.is_empty() {
4783 let start_anchor = snapshot.anchor_before(selection.head());
4784 let end_anchor = snapshot.anchor_after(selection.tail());
4785 if let Some(ranges) = self
4786 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4787 {
4788 for (buffer, edits) in ranges {
4789 linked_edits
4790 .entry(buffer.clone())
4791 .or_default()
4792 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
4793 }
4794 }
4795 }
4796 }
4797
4798 cx.emit(EditorEvent::InputHandled {
4799 utf16_range_to_replace: None,
4800 text: new_text.clone().into(),
4801 });
4802
4803 self.transact(window, cx, |this, window, cx| {
4804 if let Some(mut snippet) = snippet {
4805 snippet.text = new_text.to_string();
4806 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4807 } else {
4808 this.buffer.update(cx, |buffer, cx| {
4809 let auto_indent = match completion.insert_text_mode {
4810 Some(InsertTextMode::AS_IS) => None,
4811 _ => this.autoindent_mode.clone(),
4812 };
4813 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
4814 buffer.edit(edits, auto_indent, cx);
4815 });
4816 }
4817 for (buffer, edits) in linked_edits {
4818 buffer.update(cx, |buffer, cx| {
4819 let snapshot = buffer.snapshot();
4820 let edits = edits
4821 .into_iter()
4822 .map(|(range, text)| {
4823 use text::ToPoint as TP;
4824 let end_point = TP::to_point(&range.end, &snapshot);
4825 let start_point = TP::to_point(&range.start, &snapshot);
4826 (start_point..end_point, text)
4827 })
4828 .sorted_by_key(|(range, _)| range.start);
4829 buffer.edit(edits, None, cx);
4830 })
4831 }
4832
4833 this.refresh_inline_completion(true, false, window, cx);
4834 });
4835
4836 let show_new_completions_on_confirm = completion
4837 .confirm
4838 .as_ref()
4839 .map_or(false, |confirm| confirm(intent, window, cx));
4840 if show_new_completions_on_confirm {
4841 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4842 }
4843
4844 let provider = self.completion_provider.as_ref()?;
4845 drop(completion);
4846 let apply_edits = provider.apply_additional_edits_for_completion(
4847 buffer_handle,
4848 completions_menu.completions.clone(),
4849 candidate_id,
4850 true,
4851 cx,
4852 );
4853
4854 let editor_settings = EditorSettings::get_global(cx);
4855 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4856 // After the code completion is finished, users often want to know what signatures are needed.
4857 // so we should automatically call signature_help
4858 self.show_signature_help(&ShowSignatureHelp, window, cx);
4859 }
4860
4861 Some(cx.foreground_executor().spawn(async move {
4862 apply_edits.await?;
4863 Ok(())
4864 }))
4865 }
4866
4867 pub fn toggle_code_actions(
4868 &mut self,
4869 action: &ToggleCodeActions,
4870 window: &mut Window,
4871 cx: &mut Context<Self>,
4872 ) {
4873 let mut context_menu = self.context_menu.borrow_mut();
4874 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4875 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4876 // Toggle if we're selecting the same one
4877 *context_menu = None;
4878 cx.notify();
4879 return;
4880 } else {
4881 // Otherwise, clear it and start a new one
4882 *context_menu = None;
4883 cx.notify();
4884 }
4885 }
4886 drop(context_menu);
4887 let snapshot = self.snapshot(window, cx);
4888 let deployed_from_indicator = action.deployed_from_indicator;
4889 let mut task = self.code_actions_task.take();
4890 let action = action.clone();
4891 cx.spawn_in(window, async move |editor, cx| {
4892 while let Some(prev_task) = task {
4893 prev_task.await.log_err();
4894 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4895 }
4896
4897 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4898 if editor.focus_handle.is_focused(window) {
4899 let multibuffer_point = action
4900 .deployed_from_indicator
4901 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4902 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4903 let (buffer, buffer_row) = snapshot
4904 .buffer_snapshot
4905 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4906 .and_then(|(buffer_snapshot, range)| {
4907 editor
4908 .buffer
4909 .read(cx)
4910 .buffer(buffer_snapshot.remote_id())
4911 .map(|buffer| (buffer, range.start.row))
4912 })?;
4913 let (_, code_actions) = editor
4914 .available_code_actions
4915 .clone()
4916 .and_then(|(location, code_actions)| {
4917 let snapshot = location.buffer.read(cx).snapshot();
4918 let point_range = location.range.to_point(&snapshot);
4919 let point_range = point_range.start.row..=point_range.end.row;
4920 if point_range.contains(&buffer_row) {
4921 Some((location, code_actions))
4922 } else {
4923 None
4924 }
4925 })
4926 .unzip();
4927 let buffer_id = buffer.read(cx).remote_id();
4928 let tasks = editor
4929 .tasks
4930 .get(&(buffer_id, buffer_row))
4931 .map(|t| Arc::new(t.to_owned()));
4932 if tasks.is_none() && code_actions.is_none() {
4933 return None;
4934 }
4935
4936 editor.completion_tasks.clear();
4937 editor.discard_inline_completion(false, cx);
4938 let task_context =
4939 tasks
4940 .as_ref()
4941 .zip(editor.project.clone())
4942 .map(|(tasks, project)| {
4943 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4944 });
4945
4946 let debugger_flag = cx.has_flag::<Debugger>();
4947
4948 Some(cx.spawn_in(window, async move |editor, cx| {
4949 let task_context = match task_context {
4950 Some(task_context) => task_context.await,
4951 None => None,
4952 };
4953 let resolved_tasks =
4954 tasks
4955 .zip(task_context)
4956 .map(|(tasks, task_context)| ResolvedTasks {
4957 templates: tasks.resolve(&task_context).collect(),
4958 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4959 multibuffer_point.row,
4960 tasks.column,
4961 )),
4962 });
4963 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
4964 tasks
4965 .templates
4966 .iter()
4967 .filter(|task| {
4968 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4969 debugger_flag
4970 } else {
4971 true
4972 }
4973 })
4974 .count()
4975 == 1
4976 }) && code_actions
4977 .as_ref()
4978 .map_or(true, |actions| actions.is_empty());
4979 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4980 *editor.context_menu.borrow_mut() =
4981 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4982 buffer,
4983 actions: CodeActionContents::new(
4984 resolved_tasks,
4985 code_actions,
4986 cx,
4987 ),
4988 selected_item: Default::default(),
4989 scroll_handle: UniformListScrollHandle::default(),
4990 deployed_from_indicator,
4991 }));
4992 if spawn_straight_away {
4993 if let Some(task) = editor.confirm_code_action(
4994 &ConfirmCodeAction { item_ix: Some(0) },
4995 window,
4996 cx,
4997 ) {
4998 cx.notify();
4999 return task;
5000 }
5001 }
5002 cx.notify();
5003 Task::ready(Ok(()))
5004 }) {
5005 task.await
5006 } else {
5007 Ok(())
5008 }
5009 }))
5010 } else {
5011 Some(Task::ready(Ok(())))
5012 }
5013 })?;
5014 if let Some(task) = spawned_test_task {
5015 task.await?;
5016 }
5017
5018 Ok::<_, anyhow::Error>(())
5019 })
5020 .detach_and_log_err(cx);
5021 }
5022
5023 pub fn confirm_code_action(
5024 &mut self,
5025 action: &ConfirmCodeAction,
5026 window: &mut Window,
5027 cx: &mut Context<Self>,
5028 ) -> Option<Task<Result<()>>> {
5029 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5030
5031 let actions_menu =
5032 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5033 menu
5034 } else {
5035 return None;
5036 };
5037
5038 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5039 let action = actions_menu.actions.get(action_ix)?;
5040 let title = action.label();
5041 let buffer = actions_menu.buffer;
5042 let workspace = self.workspace()?;
5043
5044 match action {
5045 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5046 match resolved_task.task_type() {
5047 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5048 workspace::tasks::schedule_resolved_task(
5049 workspace,
5050 task_source_kind,
5051 resolved_task,
5052 false,
5053 cx,
5054 );
5055
5056 Some(Task::ready(Ok(())))
5057 }),
5058 task::TaskType::Debug(debug_args) => {
5059 if debug_args.locator.is_some() {
5060 workspace.update(cx, |workspace, cx| {
5061 workspace::tasks::schedule_resolved_task(
5062 workspace,
5063 task_source_kind,
5064 resolved_task,
5065 false,
5066 cx,
5067 );
5068 });
5069
5070 return Some(Task::ready(Ok(())));
5071 }
5072
5073 if let Some(project) = self.project.as_ref() {
5074 project
5075 .update(cx, |project, cx| {
5076 project.start_debug_session(
5077 resolved_task.resolved_debug_adapter_config().unwrap(),
5078 cx,
5079 )
5080 })
5081 .detach_and_log_err(cx);
5082 Some(Task::ready(Ok(())))
5083 } else {
5084 Some(Task::ready(Ok(())))
5085 }
5086 }
5087 }
5088 }
5089 CodeActionsItem::CodeAction {
5090 excerpt_id,
5091 action,
5092 provider,
5093 } => {
5094 let apply_code_action =
5095 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5096 let workspace = workspace.downgrade();
5097 Some(cx.spawn_in(window, async move |editor, cx| {
5098 let project_transaction = apply_code_action.await?;
5099 Self::open_project_transaction(
5100 &editor,
5101 workspace,
5102 project_transaction,
5103 title,
5104 cx,
5105 )
5106 .await
5107 }))
5108 }
5109 }
5110 }
5111
5112 pub async fn open_project_transaction(
5113 this: &WeakEntity<Editor>,
5114 workspace: WeakEntity<Workspace>,
5115 transaction: ProjectTransaction,
5116 title: String,
5117 cx: &mut AsyncWindowContext,
5118 ) -> Result<()> {
5119 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5120 cx.update(|_, cx| {
5121 entries.sort_unstable_by_key(|(buffer, _)| {
5122 buffer.read(cx).file().map(|f| f.path().clone())
5123 });
5124 })?;
5125
5126 // If the project transaction's edits are all contained within this editor, then
5127 // avoid opening a new editor to display them.
5128
5129 if let Some((buffer, transaction)) = entries.first() {
5130 if entries.len() == 1 {
5131 let excerpt = this.update(cx, |editor, cx| {
5132 editor
5133 .buffer()
5134 .read(cx)
5135 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5136 })?;
5137 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5138 if excerpted_buffer == *buffer {
5139 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5140 let excerpt_range = excerpt_range.to_offset(buffer);
5141 buffer
5142 .edited_ranges_for_transaction::<usize>(transaction)
5143 .all(|range| {
5144 excerpt_range.start <= range.start
5145 && excerpt_range.end >= range.end
5146 })
5147 })?;
5148
5149 if all_edits_within_excerpt {
5150 return Ok(());
5151 }
5152 }
5153 }
5154 }
5155 } else {
5156 return Ok(());
5157 }
5158
5159 let mut ranges_to_highlight = Vec::new();
5160 let excerpt_buffer = cx.new(|cx| {
5161 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5162 for (buffer_handle, transaction) in &entries {
5163 let edited_ranges = buffer_handle
5164 .read(cx)
5165 .edited_ranges_for_transaction::<Point>(transaction)
5166 .collect::<Vec<_>>();
5167 let (ranges, _) = multibuffer.set_excerpts_for_path(
5168 PathKey::for_buffer(buffer_handle, cx),
5169 buffer_handle.clone(),
5170 edited_ranges,
5171 DEFAULT_MULTIBUFFER_CONTEXT,
5172 cx,
5173 );
5174
5175 ranges_to_highlight.extend(ranges);
5176 }
5177 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5178 multibuffer
5179 })?;
5180
5181 workspace.update_in(cx, |workspace, window, cx| {
5182 let project = workspace.project().clone();
5183 let editor =
5184 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5185 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5186 editor.update(cx, |editor, cx| {
5187 editor.highlight_background::<Self>(
5188 &ranges_to_highlight,
5189 |theme| theme.editor_highlighted_line_background,
5190 cx,
5191 );
5192 });
5193 })?;
5194
5195 Ok(())
5196 }
5197
5198 pub fn clear_code_action_providers(&mut self) {
5199 self.code_action_providers.clear();
5200 self.available_code_actions.take();
5201 }
5202
5203 pub fn add_code_action_provider(
5204 &mut self,
5205 provider: Rc<dyn CodeActionProvider>,
5206 window: &mut Window,
5207 cx: &mut Context<Self>,
5208 ) {
5209 if self
5210 .code_action_providers
5211 .iter()
5212 .any(|existing_provider| existing_provider.id() == provider.id())
5213 {
5214 return;
5215 }
5216
5217 self.code_action_providers.push(provider);
5218 self.refresh_code_actions(window, cx);
5219 }
5220
5221 pub fn remove_code_action_provider(
5222 &mut self,
5223 id: Arc<str>,
5224 window: &mut Window,
5225 cx: &mut Context<Self>,
5226 ) {
5227 self.code_action_providers
5228 .retain(|provider| provider.id() != id);
5229 self.refresh_code_actions(window, cx);
5230 }
5231
5232 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5233 let newest_selection = self.selections.newest_anchor().clone();
5234 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5235 let buffer = self.buffer.read(cx);
5236 if newest_selection.head().diff_base_anchor.is_some() {
5237 return None;
5238 }
5239 let (start_buffer, start) =
5240 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5241 let (end_buffer, end) =
5242 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5243 if start_buffer != end_buffer {
5244 return None;
5245 }
5246
5247 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5248 cx.background_executor()
5249 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5250 .await;
5251
5252 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5253 let providers = this.code_action_providers.clone();
5254 let tasks = this
5255 .code_action_providers
5256 .iter()
5257 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5258 .collect::<Vec<_>>();
5259 (providers, tasks)
5260 })?;
5261
5262 let mut actions = Vec::new();
5263 for (provider, provider_actions) in
5264 providers.into_iter().zip(future::join_all(tasks).await)
5265 {
5266 if let Some(provider_actions) = provider_actions.log_err() {
5267 actions.extend(provider_actions.into_iter().map(|action| {
5268 AvailableCodeAction {
5269 excerpt_id: newest_selection.start.excerpt_id,
5270 action,
5271 provider: provider.clone(),
5272 }
5273 }));
5274 }
5275 }
5276
5277 this.update(cx, |this, cx| {
5278 this.available_code_actions = if actions.is_empty() {
5279 None
5280 } else {
5281 Some((
5282 Location {
5283 buffer: start_buffer,
5284 range: start..end,
5285 },
5286 actions.into(),
5287 ))
5288 };
5289 cx.notify();
5290 })
5291 }));
5292 None
5293 }
5294
5295 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5296 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5297 self.show_git_blame_inline = false;
5298
5299 self.show_git_blame_inline_delay_task =
5300 Some(cx.spawn_in(window, async move |this, cx| {
5301 cx.background_executor().timer(delay).await;
5302
5303 this.update(cx, |this, cx| {
5304 this.show_git_blame_inline = true;
5305 cx.notify();
5306 })
5307 .log_err();
5308 }));
5309 }
5310 }
5311
5312 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5313 if self.pending_rename.is_some() {
5314 return None;
5315 }
5316
5317 let provider = self.semantics_provider.clone()?;
5318 let buffer = self.buffer.read(cx);
5319 let newest_selection = self.selections.newest_anchor().clone();
5320 let cursor_position = newest_selection.head();
5321 let (cursor_buffer, cursor_buffer_position) =
5322 buffer.text_anchor_for_position(cursor_position, cx)?;
5323 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5324 if cursor_buffer != tail_buffer {
5325 return None;
5326 }
5327 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5328 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5329 cx.background_executor()
5330 .timer(Duration::from_millis(debounce))
5331 .await;
5332
5333 let highlights = if let Some(highlights) = cx
5334 .update(|cx| {
5335 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5336 })
5337 .ok()
5338 .flatten()
5339 {
5340 highlights.await.log_err()
5341 } else {
5342 None
5343 };
5344
5345 if let Some(highlights) = highlights {
5346 this.update(cx, |this, cx| {
5347 if this.pending_rename.is_some() {
5348 return;
5349 }
5350
5351 let buffer_id = cursor_position.buffer_id;
5352 let buffer = this.buffer.read(cx);
5353 if !buffer
5354 .text_anchor_for_position(cursor_position, cx)
5355 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5356 {
5357 return;
5358 }
5359
5360 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5361 let mut write_ranges = Vec::new();
5362 let mut read_ranges = Vec::new();
5363 for highlight in highlights {
5364 for (excerpt_id, excerpt_range) in
5365 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5366 {
5367 let start = highlight
5368 .range
5369 .start
5370 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5371 let end = highlight
5372 .range
5373 .end
5374 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5375 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5376 continue;
5377 }
5378
5379 let range = Anchor {
5380 buffer_id,
5381 excerpt_id,
5382 text_anchor: start,
5383 diff_base_anchor: None,
5384 }..Anchor {
5385 buffer_id,
5386 excerpt_id,
5387 text_anchor: end,
5388 diff_base_anchor: None,
5389 };
5390 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5391 write_ranges.push(range);
5392 } else {
5393 read_ranges.push(range);
5394 }
5395 }
5396 }
5397
5398 this.highlight_background::<DocumentHighlightRead>(
5399 &read_ranges,
5400 |theme| theme.editor_document_highlight_read_background,
5401 cx,
5402 );
5403 this.highlight_background::<DocumentHighlightWrite>(
5404 &write_ranges,
5405 |theme| theme.editor_document_highlight_write_background,
5406 cx,
5407 );
5408 cx.notify();
5409 })
5410 .log_err();
5411 }
5412 }));
5413 None
5414 }
5415
5416 fn prepare_highlight_query_from_selection(
5417 &mut self,
5418 cx: &mut Context<Editor>,
5419 ) -> Option<(String, Range<Anchor>)> {
5420 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5421 return None;
5422 }
5423 if !EditorSettings::get_global(cx).selection_highlight {
5424 return None;
5425 }
5426 if self.selections.count() != 1 || self.selections.line_mode {
5427 return None;
5428 }
5429 let selection = self.selections.newest::<Point>(cx);
5430 if selection.is_empty() || selection.start.row != selection.end.row {
5431 return None;
5432 }
5433 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5434 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5435 let query = multi_buffer_snapshot
5436 .text_for_range(selection_anchor_range.clone())
5437 .collect::<String>();
5438 if query.trim().is_empty() {
5439 return None;
5440 }
5441 Some((query, selection_anchor_range))
5442 }
5443
5444 fn update_selection_occurrence_highlights(
5445 &mut self,
5446 query_text: String,
5447 query_range: Range<Anchor>,
5448 multi_buffer_range_to_query: Range<Point>,
5449 use_debounce: bool,
5450 window: &mut Window,
5451 cx: &mut Context<Editor>,
5452 ) -> Task<()> {
5453 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5454 cx.spawn_in(window, async move |editor, cx| {
5455 if use_debounce {
5456 cx.background_executor()
5457 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5458 .await;
5459 }
5460 let match_task = cx.background_spawn(async move {
5461 let buffer_ranges = multi_buffer_snapshot
5462 .range_to_buffer_ranges(multi_buffer_range_to_query)
5463 .into_iter()
5464 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5465 let mut match_ranges = Vec::new();
5466 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5467 match_ranges.extend(
5468 project::search::SearchQuery::text(
5469 query_text.clone(),
5470 false,
5471 false,
5472 false,
5473 Default::default(),
5474 Default::default(),
5475 false,
5476 None,
5477 )
5478 .unwrap()
5479 .search(&buffer_snapshot, Some(search_range.clone()))
5480 .await
5481 .into_iter()
5482 .filter_map(|match_range| {
5483 let match_start = buffer_snapshot
5484 .anchor_after(search_range.start + match_range.start);
5485 let match_end =
5486 buffer_snapshot.anchor_before(search_range.start + match_range.end);
5487 let match_anchor_range = Anchor::range_in_buffer(
5488 excerpt_id,
5489 buffer_snapshot.remote_id(),
5490 match_start..match_end,
5491 );
5492 (match_anchor_range != query_range).then_some(match_anchor_range)
5493 }),
5494 );
5495 }
5496 match_ranges
5497 });
5498 let match_ranges = match_task.await;
5499 editor
5500 .update_in(cx, |editor, _, cx| {
5501 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5502 if !match_ranges.is_empty() {
5503 editor.highlight_background::<SelectedTextHighlight>(
5504 &match_ranges,
5505 |theme| theme.editor_document_highlight_bracket_background,
5506 cx,
5507 )
5508 }
5509 })
5510 .log_err();
5511 })
5512 }
5513
5514 fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
5515 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5516 else {
5517 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5518 self.quick_selection_highlight_task.take();
5519 self.debounced_selection_highlight_task.take();
5520 return;
5521 };
5522 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5523 if self
5524 .quick_selection_highlight_task
5525 .as_ref()
5526 .map_or(true, |(prev_anchor_range, _)| {
5527 prev_anchor_range != &query_range
5528 })
5529 {
5530 let multi_buffer_visible_start = self
5531 .scroll_manager
5532 .anchor()
5533 .anchor
5534 .to_point(&multi_buffer_snapshot);
5535 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5536 multi_buffer_visible_start
5537 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5538 Bias::Left,
5539 );
5540 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5541 self.quick_selection_highlight_task = Some((
5542 query_range.clone(),
5543 self.update_selection_occurrence_highlights(
5544 query_text.clone(),
5545 query_range.clone(),
5546 multi_buffer_visible_range,
5547 false,
5548 window,
5549 cx,
5550 ),
5551 ));
5552 }
5553 if self
5554 .debounced_selection_highlight_task
5555 .as_ref()
5556 .map_or(true, |(prev_anchor_range, _)| {
5557 prev_anchor_range != &query_range
5558 })
5559 {
5560 let multi_buffer_start = multi_buffer_snapshot
5561 .anchor_before(0)
5562 .to_point(&multi_buffer_snapshot);
5563 let multi_buffer_end = multi_buffer_snapshot
5564 .anchor_after(multi_buffer_snapshot.len())
5565 .to_point(&multi_buffer_snapshot);
5566 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5567 self.debounced_selection_highlight_task = Some((
5568 query_range.clone(),
5569 self.update_selection_occurrence_highlights(
5570 query_text,
5571 query_range,
5572 multi_buffer_full_range,
5573 true,
5574 window,
5575 cx,
5576 ),
5577 ));
5578 }
5579 }
5580
5581 pub fn refresh_inline_completion(
5582 &mut self,
5583 debounce: bool,
5584 user_requested: bool,
5585 window: &mut Window,
5586 cx: &mut Context<Self>,
5587 ) -> Option<()> {
5588 let provider = self.edit_prediction_provider()?;
5589 let cursor = self.selections.newest_anchor().head();
5590 let (buffer, cursor_buffer_position) =
5591 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5592
5593 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5594 self.discard_inline_completion(false, cx);
5595 return None;
5596 }
5597
5598 if !user_requested
5599 && (!self.should_show_edit_predictions()
5600 || !self.is_focused(window)
5601 || buffer.read(cx).is_empty())
5602 {
5603 self.discard_inline_completion(false, cx);
5604 return None;
5605 }
5606
5607 self.update_visible_inline_completion(window, cx);
5608 provider.refresh(
5609 self.project.clone(),
5610 buffer,
5611 cursor_buffer_position,
5612 debounce,
5613 cx,
5614 );
5615 Some(())
5616 }
5617
5618 fn show_edit_predictions_in_menu(&self) -> bool {
5619 match self.edit_prediction_settings {
5620 EditPredictionSettings::Disabled => false,
5621 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5622 }
5623 }
5624
5625 pub fn edit_predictions_enabled(&self) -> bool {
5626 match self.edit_prediction_settings {
5627 EditPredictionSettings::Disabled => false,
5628 EditPredictionSettings::Enabled { .. } => true,
5629 }
5630 }
5631
5632 fn edit_prediction_requires_modifier(&self) -> bool {
5633 match self.edit_prediction_settings {
5634 EditPredictionSettings::Disabled => false,
5635 EditPredictionSettings::Enabled {
5636 preview_requires_modifier,
5637 ..
5638 } => preview_requires_modifier,
5639 }
5640 }
5641
5642 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5643 if self.edit_prediction_provider.is_none() {
5644 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5645 } else {
5646 let selection = self.selections.newest_anchor();
5647 let cursor = selection.head();
5648
5649 if let Some((buffer, cursor_buffer_position)) =
5650 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5651 {
5652 self.edit_prediction_settings =
5653 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5654 }
5655 }
5656 }
5657
5658 fn edit_prediction_settings_at_position(
5659 &self,
5660 buffer: &Entity<Buffer>,
5661 buffer_position: language::Anchor,
5662 cx: &App,
5663 ) -> EditPredictionSettings {
5664 if !self.mode.is_full()
5665 || !self.show_inline_completions_override.unwrap_or(true)
5666 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5667 {
5668 return EditPredictionSettings::Disabled;
5669 }
5670
5671 let buffer = buffer.read(cx);
5672
5673 let file = buffer.file();
5674
5675 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5676 return EditPredictionSettings::Disabled;
5677 };
5678
5679 let by_provider = matches!(
5680 self.menu_inline_completions_policy,
5681 MenuInlineCompletionsPolicy::ByProvider
5682 );
5683
5684 let show_in_menu = by_provider
5685 && self
5686 .edit_prediction_provider
5687 .as_ref()
5688 .map_or(false, |provider| {
5689 provider.provider.show_completions_in_menu()
5690 });
5691
5692 let preview_requires_modifier =
5693 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5694
5695 EditPredictionSettings::Enabled {
5696 show_in_menu,
5697 preview_requires_modifier,
5698 }
5699 }
5700
5701 fn should_show_edit_predictions(&self) -> bool {
5702 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5703 }
5704
5705 pub fn edit_prediction_preview_is_active(&self) -> bool {
5706 matches!(
5707 self.edit_prediction_preview,
5708 EditPredictionPreview::Active { .. }
5709 )
5710 }
5711
5712 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5713 let cursor = self.selections.newest_anchor().head();
5714 if let Some((buffer, cursor_position)) =
5715 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5716 {
5717 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5718 } else {
5719 false
5720 }
5721 }
5722
5723 fn edit_predictions_enabled_in_buffer(
5724 &self,
5725 buffer: &Entity<Buffer>,
5726 buffer_position: language::Anchor,
5727 cx: &App,
5728 ) -> bool {
5729 maybe!({
5730 if self.read_only(cx) {
5731 return Some(false);
5732 }
5733 let provider = self.edit_prediction_provider()?;
5734 if !provider.is_enabled(&buffer, buffer_position, cx) {
5735 return Some(false);
5736 }
5737 let buffer = buffer.read(cx);
5738 let Some(file) = buffer.file() else {
5739 return Some(true);
5740 };
5741 let settings = all_language_settings(Some(file), cx);
5742 Some(settings.edit_predictions_enabled_for_file(file, cx))
5743 })
5744 .unwrap_or(false)
5745 }
5746
5747 fn cycle_inline_completion(
5748 &mut self,
5749 direction: Direction,
5750 window: &mut Window,
5751 cx: &mut Context<Self>,
5752 ) -> Option<()> {
5753 let provider = self.edit_prediction_provider()?;
5754 let cursor = self.selections.newest_anchor().head();
5755 let (buffer, cursor_buffer_position) =
5756 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5757 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5758 return None;
5759 }
5760
5761 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5762 self.update_visible_inline_completion(window, cx);
5763
5764 Some(())
5765 }
5766
5767 pub fn show_inline_completion(
5768 &mut self,
5769 _: &ShowEditPrediction,
5770 window: &mut Window,
5771 cx: &mut Context<Self>,
5772 ) {
5773 if !self.has_active_inline_completion() {
5774 self.refresh_inline_completion(false, true, window, cx);
5775 return;
5776 }
5777
5778 self.update_visible_inline_completion(window, cx);
5779 }
5780
5781 pub fn display_cursor_names(
5782 &mut self,
5783 _: &DisplayCursorNames,
5784 window: &mut Window,
5785 cx: &mut Context<Self>,
5786 ) {
5787 self.show_cursor_names(window, cx);
5788 }
5789
5790 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5791 self.show_cursor_names = true;
5792 cx.notify();
5793 cx.spawn_in(window, async move |this, cx| {
5794 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5795 this.update(cx, |this, cx| {
5796 this.show_cursor_names = false;
5797 cx.notify()
5798 })
5799 .ok()
5800 })
5801 .detach();
5802 }
5803
5804 pub fn next_edit_prediction(
5805 &mut self,
5806 _: &NextEditPrediction,
5807 window: &mut Window,
5808 cx: &mut Context<Self>,
5809 ) {
5810 if self.has_active_inline_completion() {
5811 self.cycle_inline_completion(Direction::Next, window, cx);
5812 } else {
5813 let is_copilot_disabled = self
5814 .refresh_inline_completion(false, true, window, cx)
5815 .is_none();
5816 if is_copilot_disabled {
5817 cx.propagate();
5818 }
5819 }
5820 }
5821
5822 pub fn previous_edit_prediction(
5823 &mut self,
5824 _: &PreviousEditPrediction,
5825 window: &mut Window,
5826 cx: &mut Context<Self>,
5827 ) {
5828 if self.has_active_inline_completion() {
5829 self.cycle_inline_completion(Direction::Prev, window, cx);
5830 } else {
5831 let is_copilot_disabled = self
5832 .refresh_inline_completion(false, true, window, cx)
5833 .is_none();
5834 if is_copilot_disabled {
5835 cx.propagate();
5836 }
5837 }
5838 }
5839
5840 pub fn accept_edit_prediction(
5841 &mut self,
5842 _: &AcceptEditPrediction,
5843 window: &mut Window,
5844 cx: &mut Context<Self>,
5845 ) {
5846 if self.show_edit_predictions_in_menu() {
5847 self.hide_context_menu(window, cx);
5848 }
5849
5850 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5851 return;
5852 };
5853
5854 self.report_inline_completion_event(
5855 active_inline_completion.completion_id.clone(),
5856 true,
5857 cx,
5858 );
5859
5860 match &active_inline_completion.completion {
5861 InlineCompletion::Move { target, .. } => {
5862 let target = *target;
5863
5864 if let Some(position_map) = &self.last_position_map {
5865 if position_map
5866 .visible_row_range
5867 .contains(&target.to_display_point(&position_map.snapshot).row())
5868 || !self.edit_prediction_requires_modifier()
5869 {
5870 self.unfold_ranges(&[target..target], true, false, cx);
5871 // Note that this is also done in vim's handler of the Tab action.
5872 self.change_selections(
5873 Some(Autoscroll::newest()),
5874 window,
5875 cx,
5876 |selections| {
5877 selections.select_anchor_ranges([target..target]);
5878 },
5879 );
5880 self.clear_row_highlights::<EditPredictionPreview>();
5881
5882 self.edit_prediction_preview
5883 .set_previous_scroll_position(None);
5884 } else {
5885 self.edit_prediction_preview
5886 .set_previous_scroll_position(Some(
5887 position_map.snapshot.scroll_anchor,
5888 ));
5889
5890 self.highlight_rows::<EditPredictionPreview>(
5891 target..target,
5892 cx.theme().colors().editor_highlighted_line_background,
5893 true,
5894 cx,
5895 );
5896 self.request_autoscroll(Autoscroll::fit(), cx);
5897 }
5898 }
5899 }
5900 InlineCompletion::Edit { edits, .. } => {
5901 if let Some(provider) = self.edit_prediction_provider() {
5902 provider.accept(cx);
5903 }
5904
5905 let snapshot = self.buffer.read(cx).snapshot(cx);
5906 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5907
5908 self.buffer.update(cx, |buffer, cx| {
5909 buffer.edit(edits.iter().cloned(), None, cx)
5910 });
5911
5912 self.change_selections(None, window, cx, |s| {
5913 s.select_anchor_ranges([last_edit_end..last_edit_end])
5914 });
5915
5916 self.update_visible_inline_completion(window, cx);
5917 if self.active_inline_completion.is_none() {
5918 self.refresh_inline_completion(true, true, window, cx);
5919 }
5920
5921 cx.notify();
5922 }
5923 }
5924
5925 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5926 }
5927
5928 pub fn accept_partial_inline_completion(
5929 &mut self,
5930 _: &AcceptPartialEditPrediction,
5931 window: &mut Window,
5932 cx: &mut Context<Self>,
5933 ) {
5934 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5935 return;
5936 };
5937 if self.selections.count() != 1 {
5938 return;
5939 }
5940
5941 self.report_inline_completion_event(
5942 active_inline_completion.completion_id.clone(),
5943 true,
5944 cx,
5945 );
5946
5947 match &active_inline_completion.completion {
5948 InlineCompletion::Move { target, .. } => {
5949 let target = *target;
5950 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5951 selections.select_anchor_ranges([target..target]);
5952 });
5953 }
5954 InlineCompletion::Edit { edits, .. } => {
5955 // Find an insertion that starts at the cursor position.
5956 let snapshot = self.buffer.read(cx).snapshot(cx);
5957 let cursor_offset = self.selections.newest::<usize>(cx).head();
5958 let insertion = edits.iter().find_map(|(range, text)| {
5959 let range = range.to_offset(&snapshot);
5960 if range.is_empty() && range.start == cursor_offset {
5961 Some(text)
5962 } else {
5963 None
5964 }
5965 });
5966
5967 if let Some(text) = insertion {
5968 let mut partial_completion = text
5969 .chars()
5970 .by_ref()
5971 .take_while(|c| c.is_alphabetic())
5972 .collect::<String>();
5973 if partial_completion.is_empty() {
5974 partial_completion = text
5975 .chars()
5976 .by_ref()
5977 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5978 .collect::<String>();
5979 }
5980
5981 cx.emit(EditorEvent::InputHandled {
5982 utf16_range_to_replace: None,
5983 text: partial_completion.clone().into(),
5984 });
5985
5986 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5987
5988 self.refresh_inline_completion(true, true, window, cx);
5989 cx.notify();
5990 } else {
5991 self.accept_edit_prediction(&Default::default(), window, cx);
5992 }
5993 }
5994 }
5995 }
5996
5997 fn discard_inline_completion(
5998 &mut self,
5999 should_report_inline_completion_event: bool,
6000 cx: &mut Context<Self>,
6001 ) -> bool {
6002 if should_report_inline_completion_event {
6003 let completion_id = self
6004 .active_inline_completion
6005 .as_ref()
6006 .and_then(|active_completion| active_completion.completion_id.clone());
6007
6008 self.report_inline_completion_event(completion_id, false, cx);
6009 }
6010
6011 if let Some(provider) = self.edit_prediction_provider() {
6012 provider.discard(cx);
6013 }
6014
6015 self.take_active_inline_completion(cx)
6016 }
6017
6018 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6019 let Some(provider) = self.edit_prediction_provider() else {
6020 return;
6021 };
6022
6023 let Some((_, buffer, _)) = self
6024 .buffer
6025 .read(cx)
6026 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6027 else {
6028 return;
6029 };
6030
6031 let extension = buffer
6032 .read(cx)
6033 .file()
6034 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6035
6036 let event_type = match accepted {
6037 true => "Edit Prediction Accepted",
6038 false => "Edit Prediction Discarded",
6039 };
6040 telemetry::event!(
6041 event_type,
6042 provider = provider.name(),
6043 prediction_id = id,
6044 suggestion_accepted = accepted,
6045 file_extension = extension,
6046 );
6047 }
6048
6049 pub fn has_active_inline_completion(&self) -> bool {
6050 self.active_inline_completion.is_some()
6051 }
6052
6053 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6054 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6055 return false;
6056 };
6057
6058 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6059 self.clear_highlights::<InlineCompletionHighlight>(cx);
6060 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6061 true
6062 }
6063
6064 /// Returns true when we're displaying the edit prediction popover below the cursor
6065 /// like we are not previewing and the LSP autocomplete menu is visible
6066 /// or we are in `when_holding_modifier` mode.
6067 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6068 if self.edit_prediction_preview_is_active()
6069 || !self.show_edit_predictions_in_menu()
6070 || !self.edit_predictions_enabled()
6071 {
6072 return false;
6073 }
6074
6075 if self.has_visible_completions_menu() {
6076 return true;
6077 }
6078
6079 has_completion && self.edit_prediction_requires_modifier()
6080 }
6081
6082 fn handle_modifiers_changed(
6083 &mut self,
6084 modifiers: Modifiers,
6085 position_map: &PositionMap,
6086 window: &mut Window,
6087 cx: &mut Context<Self>,
6088 ) {
6089 if self.show_edit_predictions_in_menu() {
6090 self.update_edit_prediction_preview(&modifiers, window, cx);
6091 }
6092
6093 self.update_selection_mode(&modifiers, position_map, window, cx);
6094
6095 let mouse_position = window.mouse_position();
6096 if !position_map.text_hitbox.is_hovered(window) {
6097 return;
6098 }
6099
6100 self.update_hovered_link(
6101 position_map.point_for_position(mouse_position),
6102 &position_map.snapshot,
6103 modifiers,
6104 window,
6105 cx,
6106 )
6107 }
6108
6109 fn update_selection_mode(
6110 &mut self,
6111 modifiers: &Modifiers,
6112 position_map: &PositionMap,
6113 window: &mut Window,
6114 cx: &mut Context<Self>,
6115 ) {
6116 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6117 return;
6118 }
6119
6120 let mouse_position = window.mouse_position();
6121 let point_for_position = position_map.point_for_position(mouse_position);
6122 let position = point_for_position.previous_valid;
6123
6124 self.select(
6125 SelectPhase::BeginColumnar {
6126 position,
6127 reset: false,
6128 goal_column: point_for_position.exact_unclipped.column(),
6129 },
6130 window,
6131 cx,
6132 );
6133 }
6134
6135 fn update_edit_prediction_preview(
6136 &mut self,
6137 modifiers: &Modifiers,
6138 window: &mut Window,
6139 cx: &mut Context<Self>,
6140 ) {
6141 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6142 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6143 return;
6144 };
6145
6146 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6147 if matches!(
6148 self.edit_prediction_preview,
6149 EditPredictionPreview::Inactive { .. }
6150 ) {
6151 self.edit_prediction_preview = EditPredictionPreview::Active {
6152 previous_scroll_position: None,
6153 since: Instant::now(),
6154 };
6155
6156 self.update_visible_inline_completion(window, cx);
6157 cx.notify();
6158 }
6159 } else if let EditPredictionPreview::Active {
6160 previous_scroll_position,
6161 since,
6162 } = self.edit_prediction_preview
6163 {
6164 if let (Some(previous_scroll_position), Some(position_map)) =
6165 (previous_scroll_position, self.last_position_map.as_ref())
6166 {
6167 self.set_scroll_position(
6168 previous_scroll_position
6169 .scroll_position(&position_map.snapshot.display_snapshot),
6170 window,
6171 cx,
6172 );
6173 }
6174
6175 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6176 released_too_fast: since.elapsed() < Duration::from_millis(200),
6177 };
6178 self.clear_row_highlights::<EditPredictionPreview>();
6179 self.update_visible_inline_completion(window, cx);
6180 cx.notify();
6181 }
6182 }
6183
6184 fn update_visible_inline_completion(
6185 &mut self,
6186 _window: &mut Window,
6187 cx: &mut Context<Self>,
6188 ) -> Option<()> {
6189 let selection = self.selections.newest_anchor();
6190 let cursor = selection.head();
6191 let multibuffer = self.buffer.read(cx).snapshot(cx);
6192 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6193 let excerpt_id = cursor.excerpt_id;
6194
6195 let show_in_menu = self.show_edit_predictions_in_menu();
6196 let completions_menu_has_precedence = !show_in_menu
6197 && (self.context_menu.borrow().is_some()
6198 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6199
6200 if completions_menu_has_precedence
6201 || !offset_selection.is_empty()
6202 || self
6203 .active_inline_completion
6204 .as_ref()
6205 .map_or(false, |completion| {
6206 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6207 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6208 !invalidation_range.contains(&offset_selection.head())
6209 })
6210 {
6211 self.discard_inline_completion(false, cx);
6212 return None;
6213 }
6214
6215 self.take_active_inline_completion(cx);
6216 let Some(provider) = self.edit_prediction_provider() else {
6217 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6218 return None;
6219 };
6220
6221 let (buffer, cursor_buffer_position) =
6222 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6223
6224 self.edit_prediction_settings =
6225 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6226
6227 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6228
6229 if self.edit_prediction_indent_conflict {
6230 let cursor_point = cursor.to_point(&multibuffer);
6231
6232 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6233
6234 if let Some((_, indent)) = indents.iter().next() {
6235 if indent.len == cursor_point.column {
6236 self.edit_prediction_indent_conflict = false;
6237 }
6238 }
6239 }
6240
6241 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6242 let edits = inline_completion
6243 .edits
6244 .into_iter()
6245 .flat_map(|(range, new_text)| {
6246 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6247 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6248 Some((start..end, new_text))
6249 })
6250 .collect::<Vec<_>>();
6251 if edits.is_empty() {
6252 return None;
6253 }
6254
6255 let first_edit_start = edits.first().unwrap().0.start;
6256 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6257 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6258
6259 let last_edit_end = edits.last().unwrap().0.end;
6260 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6261 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6262
6263 let cursor_row = cursor.to_point(&multibuffer).row;
6264
6265 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6266
6267 let mut inlay_ids = Vec::new();
6268 let invalidation_row_range;
6269 let move_invalidation_row_range = if cursor_row < edit_start_row {
6270 Some(cursor_row..edit_end_row)
6271 } else if cursor_row > edit_end_row {
6272 Some(edit_start_row..cursor_row)
6273 } else {
6274 None
6275 };
6276 let is_move =
6277 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6278 let completion = if is_move {
6279 invalidation_row_range =
6280 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6281 let target = first_edit_start;
6282 InlineCompletion::Move { target, snapshot }
6283 } else {
6284 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6285 && !self.inline_completions_hidden_for_vim_mode;
6286
6287 if show_completions_in_buffer {
6288 if edits
6289 .iter()
6290 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6291 {
6292 let mut inlays = Vec::new();
6293 for (range, new_text) in &edits {
6294 let inlay = Inlay::inline_completion(
6295 post_inc(&mut self.next_inlay_id),
6296 range.start,
6297 new_text.as_str(),
6298 );
6299 inlay_ids.push(inlay.id);
6300 inlays.push(inlay);
6301 }
6302
6303 self.splice_inlays(&[], inlays, cx);
6304 } else {
6305 let background_color = cx.theme().status().deleted_background;
6306 self.highlight_text::<InlineCompletionHighlight>(
6307 edits.iter().map(|(range, _)| range.clone()).collect(),
6308 HighlightStyle {
6309 background_color: Some(background_color),
6310 ..Default::default()
6311 },
6312 cx,
6313 );
6314 }
6315 }
6316
6317 invalidation_row_range = edit_start_row..edit_end_row;
6318
6319 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6320 if provider.show_tab_accept_marker() {
6321 EditDisplayMode::TabAccept
6322 } else {
6323 EditDisplayMode::Inline
6324 }
6325 } else {
6326 EditDisplayMode::DiffPopover
6327 };
6328
6329 InlineCompletion::Edit {
6330 edits,
6331 edit_preview: inline_completion.edit_preview,
6332 display_mode,
6333 snapshot,
6334 }
6335 };
6336
6337 let invalidation_range = multibuffer
6338 .anchor_before(Point::new(invalidation_row_range.start, 0))
6339 ..multibuffer.anchor_after(Point::new(
6340 invalidation_row_range.end,
6341 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6342 ));
6343
6344 self.stale_inline_completion_in_menu = None;
6345 self.active_inline_completion = Some(InlineCompletionState {
6346 inlay_ids,
6347 completion,
6348 completion_id: inline_completion.id,
6349 invalidation_range,
6350 });
6351
6352 cx.notify();
6353
6354 Some(())
6355 }
6356
6357 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6358 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6359 }
6360
6361 fn render_code_actions_indicator(
6362 &self,
6363 _style: &EditorStyle,
6364 row: DisplayRow,
6365 is_active: bool,
6366 breakpoint: Option<&(Anchor, Breakpoint)>,
6367 cx: &mut Context<Self>,
6368 ) -> Option<IconButton> {
6369 let color = Color::Muted;
6370 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6371 let show_tooltip = !self.context_menu_visible();
6372
6373 if self.available_code_actions.is_some() {
6374 Some(
6375 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6376 .shape(ui::IconButtonShape::Square)
6377 .icon_size(IconSize::XSmall)
6378 .icon_color(color)
6379 .toggle_state(is_active)
6380 .when(show_tooltip, |this| {
6381 this.tooltip({
6382 let focus_handle = self.focus_handle.clone();
6383 move |window, cx| {
6384 Tooltip::for_action_in(
6385 "Toggle Code Actions",
6386 &ToggleCodeActions {
6387 deployed_from_indicator: None,
6388 },
6389 &focus_handle,
6390 window,
6391 cx,
6392 )
6393 }
6394 })
6395 })
6396 .on_click(cx.listener(move |editor, _e, window, cx| {
6397 window.focus(&editor.focus_handle(cx));
6398 editor.toggle_code_actions(
6399 &ToggleCodeActions {
6400 deployed_from_indicator: Some(row),
6401 },
6402 window,
6403 cx,
6404 );
6405 }))
6406 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6407 editor.set_breakpoint_context_menu(
6408 row,
6409 position,
6410 event.down.position,
6411 window,
6412 cx,
6413 );
6414 })),
6415 )
6416 } else {
6417 None
6418 }
6419 }
6420
6421 fn clear_tasks(&mut self) {
6422 self.tasks.clear()
6423 }
6424
6425 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6426 if self.tasks.insert(key, value).is_some() {
6427 // This case should hopefully be rare, but just in case...
6428 log::error!(
6429 "multiple different run targets found on a single line, only the last target will be rendered"
6430 )
6431 }
6432 }
6433
6434 /// Get all display points of breakpoints that will be rendered within editor
6435 ///
6436 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6437 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6438 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6439 fn active_breakpoints(
6440 &self,
6441 range: Range<DisplayRow>,
6442 window: &mut Window,
6443 cx: &mut Context<Self>,
6444 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6445 let mut breakpoint_display_points = HashMap::default();
6446
6447 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6448 return breakpoint_display_points;
6449 };
6450
6451 let snapshot = self.snapshot(window, cx);
6452
6453 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6454 let Some(project) = self.project.as_ref() else {
6455 return breakpoint_display_points;
6456 };
6457
6458 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6459 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6460
6461 for (buffer_snapshot, range, excerpt_id) in
6462 multi_buffer_snapshot.range_to_buffer_ranges(range)
6463 {
6464 let Some(buffer) = project.read_with(cx, |this, cx| {
6465 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6466 }) else {
6467 continue;
6468 };
6469 let breakpoints = breakpoint_store.read(cx).breakpoints(
6470 &buffer,
6471 Some(
6472 buffer_snapshot.anchor_before(range.start)
6473 ..buffer_snapshot.anchor_after(range.end),
6474 ),
6475 buffer_snapshot,
6476 cx,
6477 );
6478 for (anchor, breakpoint) in breakpoints {
6479 let multi_buffer_anchor =
6480 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6481 let position = multi_buffer_anchor
6482 .to_point(&multi_buffer_snapshot)
6483 .to_display_point(&snapshot);
6484
6485 breakpoint_display_points
6486 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6487 }
6488 }
6489
6490 breakpoint_display_points
6491 }
6492
6493 fn breakpoint_context_menu(
6494 &self,
6495 anchor: Anchor,
6496 window: &mut Window,
6497 cx: &mut Context<Self>,
6498 ) -> Entity<ui::ContextMenu> {
6499 let weak_editor = cx.weak_entity();
6500 let focus_handle = self.focus_handle(cx);
6501
6502 let row = self
6503 .buffer
6504 .read(cx)
6505 .snapshot(cx)
6506 .summary_for_anchor::<Point>(&anchor)
6507 .row;
6508
6509 let breakpoint = self
6510 .breakpoint_at_row(row, window, cx)
6511 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6512
6513 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6514 "Edit Log Breakpoint"
6515 } else {
6516 "Set Log Breakpoint"
6517 };
6518
6519 let condition_breakpoint_msg = if breakpoint
6520 .as_ref()
6521 .is_some_and(|bp| bp.1.condition.is_some())
6522 {
6523 "Edit Condition Breakpoint"
6524 } else {
6525 "Set Condition Breakpoint"
6526 };
6527
6528 let hit_condition_breakpoint_msg = if breakpoint
6529 .as_ref()
6530 .is_some_and(|bp| bp.1.hit_condition.is_some())
6531 {
6532 "Edit Hit Condition Breakpoint"
6533 } else {
6534 "Set Hit Condition Breakpoint"
6535 };
6536
6537 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6538 "Unset Breakpoint"
6539 } else {
6540 "Set Breakpoint"
6541 };
6542
6543 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6544 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6545
6546 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6547 BreakpointState::Enabled => Some("Disable"),
6548 BreakpointState::Disabled => Some("Enable"),
6549 });
6550
6551 let (anchor, breakpoint) =
6552 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6553
6554 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6555 menu.on_blur_subscription(Subscription::new(|| {}))
6556 .context(focus_handle)
6557 .when(run_to_cursor, |this| {
6558 let weak_editor = weak_editor.clone();
6559 this.entry("Run to cursor", None, move |window, cx| {
6560 weak_editor
6561 .update(cx, |editor, cx| {
6562 editor.change_selections(None, window, cx, |s| {
6563 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6564 });
6565 })
6566 .ok();
6567
6568 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6569 })
6570 .separator()
6571 })
6572 .when_some(toggle_state_msg, |this, msg| {
6573 this.entry(msg, None, {
6574 let weak_editor = weak_editor.clone();
6575 let breakpoint = breakpoint.clone();
6576 move |_window, cx| {
6577 weak_editor
6578 .update(cx, |this, cx| {
6579 this.edit_breakpoint_at_anchor(
6580 anchor,
6581 breakpoint.as_ref().clone(),
6582 BreakpointEditAction::InvertState,
6583 cx,
6584 );
6585 })
6586 .log_err();
6587 }
6588 })
6589 })
6590 .entry(set_breakpoint_msg, None, {
6591 let weak_editor = weak_editor.clone();
6592 let breakpoint = breakpoint.clone();
6593 move |_window, cx| {
6594 weak_editor
6595 .update(cx, |this, cx| {
6596 this.edit_breakpoint_at_anchor(
6597 anchor,
6598 breakpoint.as_ref().clone(),
6599 BreakpointEditAction::Toggle,
6600 cx,
6601 );
6602 })
6603 .log_err();
6604 }
6605 })
6606 .entry(log_breakpoint_msg, None, {
6607 let breakpoint = breakpoint.clone();
6608 let weak_editor = weak_editor.clone();
6609 move |window, cx| {
6610 weak_editor
6611 .update(cx, |this, cx| {
6612 this.add_edit_breakpoint_block(
6613 anchor,
6614 breakpoint.as_ref(),
6615 BreakpointPromptEditAction::Log,
6616 window,
6617 cx,
6618 );
6619 })
6620 .log_err();
6621 }
6622 })
6623 .entry(condition_breakpoint_msg, None, {
6624 let breakpoint = breakpoint.clone();
6625 let weak_editor = weak_editor.clone();
6626 move |window, cx| {
6627 weak_editor
6628 .update(cx, |this, cx| {
6629 this.add_edit_breakpoint_block(
6630 anchor,
6631 breakpoint.as_ref(),
6632 BreakpointPromptEditAction::Condition,
6633 window,
6634 cx,
6635 );
6636 })
6637 .log_err();
6638 }
6639 })
6640 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6641 weak_editor
6642 .update(cx, |this, cx| {
6643 this.add_edit_breakpoint_block(
6644 anchor,
6645 breakpoint.as_ref(),
6646 BreakpointPromptEditAction::HitCondition,
6647 window,
6648 cx,
6649 );
6650 })
6651 .log_err();
6652 })
6653 })
6654 }
6655
6656 fn render_breakpoint(
6657 &self,
6658 position: Anchor,
6659 row: DisplayRow,
6660 breakpoint: &Breakpoint,
6661 cx: &mut Context<Self>,
6662 ) -> IconButton {
6663 let (color, icon) = {
6664 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6665 (false, false) => ui::IconName::DebugBreakpoint,
6666 (true, false) => ui::IconName::DebugLogBreakpoint,
6667 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6668 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6669 };
6670
6671 let color = if self
6672 .gutter_breakpoint_indicator
6673 .0
6674 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6675 {
6676 Color::Hint
6677 } else {
6678 Color::Debugger
6679 };
6680
6681 (color, icon)
6682 };
6683
6684 let breakpoint = Arc::from(breakpoint.clone());
6685
6686 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6687 .icon_size(IconSize::XSmall)
6688 .size(ui::ButtonSize::None)
6689 .icon_color(color)
6690 .style(ButtonStyle::Transparent)
6691 .on_click(cx.listener({
6692 let breakpoint = breakpoint.clone();
6693
6694 move |editor, event: &ClickEvent, window, cx| {
6695 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6696 BreakpointEditAction::InvertState
6697 } else {
6698 BreakpointEditAction::Toggle
6699 };
6700
6701 window.focus(&editor.focus_handle(cx));
6702 editor.edit_breakpoint_at_anchor(
6703 position,
6704 breakpoint.as_ref().clone(),
6705 edit_action,
6706 cx,
6707 );
6708 }
6709 }))
6710 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6711 editor.set_breakpoint_context_menu(
6712 row,
6713 Some(position),
6714 event.down.position,
6715 window,
6716 cx,
6717 );
6718 }))
6719 }
6720
6721 fn build_tasks_context(
6722 project: &Entity<Project>,
6723 buffer: &Entity<Buffer>,
6724 buffer_row: u32,
6725 tasks: &Arc<RunnableTasks>,
6726 cx: &mut Context<Self>,
6727 ) -> Task<Option<task::TaskContext>> {
6728 let position = Point::new(buffer_row, tasks.column);
6729 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6730 let location = Location {
6731 buffer: buffer.clone(),
6732 range: range_start..range_start,
6733 };
6734 // Fill in the environmental variables from the tree-sitter captures
6735 let mut captured_task_variables = TaskVariables::default();
6736 for (capture_name, value) in tasks.extra_variables.clone() {
6737 captured_task_variables.insert(
6738 task::VariableName::Custom(capture_name.into()),
6739 value.clone(),
6740 );
6741 }
6742 project.update(cx, |project, cx| {
6743 project.task_store().update(cx, |task_store, cx| {
6744 task_store.task_context_for_location(captured_task_variables, location, cx)
6745 })
6746 })
6747 }
6748
6749 pub fn spawn_nearest_task(
6750 &mut self,
6751 action: &SpawnNearestTask,
6752 window: &mut Window,
6753 cx: &mut Context<Self>,
6754 ) {
6755 let Some((workspace, _)) = self.workspace.clone() else {
6756 return;
6757 };
6758 let Some(project) = self.project.clone() else {
6759 return;
6760 };
6761
6762 // Try to find a closest, enclosing node using tree-sitter that has a
6763 // task
6764 let Some((buffer, buffer_row, tasks)) = self
6765 .find_enclosing_node_task(cx)
6766 // Or find the task that's closest in row-distance.
6767 .or_else(|| self.find_closest_task(cx))
6768 else {
6769 return;
6770 };
6771
6772 let reveal_strategy = action.reveal;
6773 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6774 cx.spawn_in(window, async move |_, cx| {
6775 let context = task_context.await?;
6776 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6777
6778 let resolved = resolved_task.resolved.as_mut()?;
6779 resolved.reveal = reveal_strategy;
6780
6781 workspace
6782 .update(cx, |workspace, cx| {
6783 workspace::tasks::schedule_resolved_task(
6784 workspace,
6785 task_source_kind,
6786 resolved_task,
6787 false,
6788 cx,
6789 );
6790 })
6791 .ok()
6792 })
6793 .detach();
6794 }
6795
6796 fn find_closest_task(
6797 &mut self,
6798 cx: &mut Context<Self>,
6799 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6800 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6801
6802 let ((buffer_id, row), tasks) = self
6803 .tasks
6804 .iter()
6805 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6806
6807 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6808 let tasks = Arc::new(tasks.to_owned());
6809 Some((buffer, *row, tasks))
6810 }
6811
6812 fn find_enclosing_node_task(
6813 &mut self,
6814 cx: &mut Context<Self>,
6815 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6816 let snapshot = self.buffer.read(cx).snapshot(cx);
6817 let offset = self.selections.newest::<usize>(cx).head();
6818 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6819 let buffer_id = excerpt.buffer().remote_id();
6820
6821 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6822 let mut cursor = layer.node().walk();
6823
6824 while cursor.goto_first_child_for_byte(offset).is_some() {
6825 if cursor.node().end_byte() == offset {
6826 cursor.goto_next_sibling();
6827 }
6828 }
6829
6830 // Ascend to the smallest ancestor that contains the range and has a task.
6831 loop {
6832 let node = cursor.node();
6833 let node_range = node.byte_range();
6834 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6835
6836 // Check if this node contains our offset
6837 if node_range.start <= offset && node_range.end >= offset {
6838 // If it contains offset, check for task
6839 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6840 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6841 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6842 }
6843 }
6844
6845 if !cursor.goto_parent() {
6846 break;
6847 }
6848 }
6849 None
6850 }
6851
6852 fn render_run_indicator(
6853 &self,
6854 _style: &EditorStyle,
6855 is_active: bool,
6856 row: DisplayRow,
6857 breakpoint: Option<(Anchor, Breakpoint)>,
6858 cx: &mut Context<Self>,
6859 ) -> IconButton {
6860 let color = Color::Muted;
6861 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6862
6863 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6864 .shape(ui::IconButtonShape::Square)
6865 .icon_size(IconSize::XSmall)
6866 .icon_color(color)
6867 .toggle_state(is_active)
6868 .on_click(cx.listener(move |editor, _e, window, cx| {
6869 window.focus(&editor.focus_handle(cx));
6870 editor.toggle_code_actions(
6871 &ToggleCodeActions {
6872 deployed_from_indicator: Some(row),
6873 },
6874 window,
6875 cx,
6876 );
6877 }))
6878 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6879 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6880 }))
6881 }
6882
6883 pub fn context_menu_visible(&self) -> bool {
6884 !self.edit_prediction_preview_is_active()
6885 && self
6886 .context_menu
6887 .borrow()
6888 .as_ref()
6889 .map_or(false, |menu| menu.visible())
6890 }
6891
6892 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6893 self.context_menu
6894 .borrow()
6895 .as_ref()
6896 .map(|menu| menu.origin())
6897 }
6898
6899 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6900 self.context_menu_options = Some(options);
6901 }
6902
6903 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6904 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6905
6906 fn render_edit_prediction_popover(
6907 &mut self,
6908 text_bounds: &Bounds<Pixels>,
6909 content_origin: gpui::Point<Pixels>,
6910 editor_snapshot: &EditorSnapshot,
6911 visible_row_range: Range<DisplayRow>,
6912 scroll_top: f32,
6913 scroll_bottom: f32,
6914 line_layouts: &[LineWithInvisibles],
6915 line_height: Pixels,
6916 scroll_pixel_position: gpui::Point<Pixels>,
6917 newest_selection_head: Option<DisplayPoint>,
6918 editor_width: Pixels,
6919 style: &EditorStyle,
6920 window: &mut Window,
6921 cx: &mut App,
6922 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6923 let active_inline_completion = self.active_inline_completion.as_ref()?;
6924
6925 if self.edit_prediction_visible_in_cursor_popover(true) {
6926 return None;
6927 }
6928
6929 match &active_inline_completion.completion {
6930 InlineCompletion::Move { target, .. } => {
6931 let target_display_point = target.to_display_point(editor_snapshot);
6932
6933 if self.edit_prediction_requires_modifier() {
6934 if !self.edit_prediction_preview_is_active() {
6935 return None;
6936 }
6937
6938 self.render_edit_prediction_modifier_jump_popover(
6939 text_bounds,
6940 content_origin,
6941 visible_row_range,
6942 line_layouts,
6943 line_height,
6944 scroll_pixel_position,
6945 newest_selection_head,
6946 target_display_point,
6947 window,
6948 cx,
6949 )
6950 } else {
6951 self.render_edit_prediction_eager_jump_popover(
6952 text_bounds,
6953 content_origin,
6954 editor_snapshot,
6955 visible_row_range,
6956 scroll_top,
6957 scroll_bottom,
6958 line_height,
6959 scroll_pixel_position,
6960 target_display_point,
6961 editor_width,
6962 window,
6963 cx,
6964 )
6965 }
6966 }
6967 InlineCompletion::Edit {
6968 display_mode: EditDisplayMode::Inline,
6969 ..
6970 } => None,
6971 InlineCompletion::Edit {
6972 display_mode: EditDisplayMode::TabAccept,
6973 edits,
6974 ..
6975 } => {
6976 let range = &edits.first()?.0;
6977 let target_display_point = range.end.to_display_point(editor_snapshot);
6978
6979 self.render_edit_prediction_end_of_line_popover(
6980 "Accept",
6981 editor_snapshot,
6982 visible_row_range,
6983 target_display_point,
6984 line_height,
6985 scroll_pixel_position,
6986 content_origin,
6987 editor_width,
6988 window,
6989 cx,
6990 )
6991 }
6992 InlineCompletion::Edit {
6993 edits,
6994 edit_preview,
6995 display_mode: EditDisplayMode::DiffPopover,
6996 snapshot,
6997 } => self.render_edit_prediction_diff_popover(
6998 text_bounds,
6999 content_origin,
7000 editor_snapshot,
7001 visible_row_range,
7002 line_layouts,
7003 line_height,
7004 scroll_pixel_position,
7005 newest_selection_head,
7006 editor_width,
7007 style,
7008 edits,
7009 edit_preview,
7010 snapshot,
7011 window,
7012 cx,
7013 ),
7014 }
7015 }
7016
7017 fn render_edit_prediction_modifier_jump_popover(
7018 &mut self,
7019 text_bounds: &Bounds<Pixels>,
7020 content_origin: gpui::Point<Pixels>,
7021 visible_row_range: Range<DisplayRow>,
7022 line_layouts: &[LineWithInvisibles],
7023 line_height: Pixels,
7024 scroll_pixel_position: gpui::Point<Pixels>,
7025 newest_selection_head: Option<DisplayPoint>,
7026 target_display_point: DisplayPoint,
7027 window: &mut Window,
7028 cx: &mut App,
7029 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7030 let scrolled_content_origin =
7031 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7032
7033 const SCROLL_PADDING_Y: Pixels = px(12.);
7034
7035 if target_display_point.row() < visible_row_range.start {
7036 return self.render_edit_prediction_scroll_popover(
7037 |_| SCROLL_PADDING_Y,
7038 IconName::ArrowUp,
7039 visible_row_range,
7040 line_layouts,
7041 newest_selection_head,
7042 scrolled_content_origin,
7043 window,
7044 cx,
7045 );
7046 } else if target_display_point.row() >= visible_row_range.end {
7047 return self.render_edit_prediction_scroll_popover(
7048 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7049 IconName::ArrowDown,
7050 visible_row_range,
7051 line_layouts,
7052 newest_selection_head,
7053 scrolled_content_origin,
7054 window,
7055 cx,
7056 );
7057 }
7058
7059 const POLE_WIDTH: Pixels = px(2.);
7060
7061 let line_layout =
7062 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7063 let target_column = target_display_point.column() as usize;
7064
7065 let target_x = line_layout.x_for_index(target_column);
7066 let target_y =
7067 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7068
7069 let flag_on_right = target_x < text_bounds.size.width / 2.;
7070
7071 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7072 border_color.l += 0.001;
7073
7074 let mut element = v_flex()
7075 .items_end()
7076 .when(flag_on_right, |el| el.items_start())
7077 .child(if flag_on_right {
7078 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7079 .rounded_bl(px(0.))
7080 .rounded_tl(px(0.))
7081 .border_l_2()
7082 .border_color(border_color)
7083 } else {
7084 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7085 .rounded_br(px(0.))
7086 .rounded_tr(px(0.))
7087 .border_r_2()
7088 .border_color(border_color)
7089 })
7090 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7091 .into_any();
7092
7093 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7094
7095 let mut origin = scrolled_content_origin + point(target_x, target_y)
7096 - point(
7097 if flag_on_right {
7098 POLE_WIDTH
7099 } else {
7100 size.width - POLE_WIDTH
7101 },
7102 size.height - line_height,
7103 );
7104
7105 origin.x = origin.x.max(content_origin.x);
7106
7107 element.prepaint_at(origin, window, cx);
7108
7109 Some((element, origin))
7110 }
7111
7112 fn render_edit_prediction_scroll_popover(
7113 &mut self,
7114 to_y: impl Fn(Size<Pixels>) -> Pixels,
7115 scroll_icon: IconName,
7116 visible_row_range: Range<DisplayRow>,
7117 line_layouts: &[LineWithInvisibles],
7118 newest_selection_head: Option<DisplayPoint>,
7119 scrolled_content_origin: gpui::Point<Pixels>,
7120 window: &mut Window,
7121 cx: &mut App,
7122 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7123 let mut element = self
7124 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7125 .into_any();
7126
7127 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7128
7129 let cursor = newest_selection_head?;
7130 let cursor_row_layout =
7131 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7132 let cursor_column = cursor.column() as usize;
7133
7134 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7135
7136 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7137
7138 element.prepaint_at(origin, window, cx);
7139 Some((element, origin))
7140 }
7141
7142 fn render_edit_prediction_eager_jump_popover(
7143 &mut self,
7144 text_bounds: &Bounds<Pixels>,
7145 content_origin: gpui::Point<Pixels>,
7146 editor_snapshot: &EditorSnapshot,
7147 visible_row_range: Range<DisplayRow>,
7148 scroll_top: f32,
7149 scroll_bottom: f32,
7150 line_height: Pixels,
7151 scroll_pixel_position: gpui::Point<Pixels>,
7152 target_display_point: DisplayPoint,
7153 editor_width: Pixels,
7154 window: &mut Window,
7155 cx: &mut App,
7156 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7157 if target_display_point.row().as_f32() < scroll_top {
7158 let mut element = self
7159 .render_edit_prediction_line_popover(
7160 "Jump to Edit",
7161 Some(IconName::ArrowUp),
7162 window,
7163 cx,
7164 )?
7165 .into_any();
7166
7167 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7168 let offset = point(
7169 (text_bounds.size.width - size.width) / 2.,
7170 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7171 );
7172
7173 let origin = text_bounds.origin + offset;
7174 element.prepaint_at(origin, window, cx);
7175 Some((element, origin))
7176 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7177 let mut element = self
7178 .render_edit_prediction_line_popover(
7179 "Jump to Edit",
7180 Some(IconName::ArrowDown),
7181 window,
7182 cx,
7183 )?
7184 .into_any();
7185
7186 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7187 let offset = point(
7188 (text_bounds.size.width - size.width) / 2.,
7189 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7190 );
7191
7192 let origin = text_bounds.origin + offset;
7193 element.prepaint_at(origin, window, cx);
7194 Some((element, origin))
7195 } else {
7196 self.render_edit_prediction_end_of_line_popover(
7197 "Jump to Edit",
7198 editor_snapshot,
7199 visible_row_range,
7200 target_display_point,
7201 line_height,
7202 scroll_pixel_position,
7203 content_origin,
7204 editor_width,
7205 window,
7206 cx,
7207 )
7208 }
7209 }
7210
7211 fn render_edit_prediction_end_of_line_popover(
7212 self: &mut Editor,
7213 label: &'static str,
7214 editor_snapshot: &EditorSnapshot,
7215 visible_row_range: Range<DisplayRow>,
7216 target_display_point: DisplayPoint,
7217 line_height: Pixels,
7218 scroll_pixel_position: gpui::Point<Pixels>,
7219 content_origin: gpui::Point<Pixels>,
7220 editor_width: Pixels,
7221 window: &mut Window,
7222 cx: &mut App,
7223 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7224 let target_line_end = DisplayPoint::new(
7225 target_display_point.row(),
7226 editor_snapshot.line_len(target_display_point.row()),
7227 );
7228
7229 let mut element = self
7230 .render_edit_prediction_line_popover(label, None, window, cx)?
7231 .into_any();
7232
7233 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7234
7235 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7236
7237 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7238 let mut origin = start_point
7239 + line_origin
7240 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7241 origin.x = origin.x.max(content_origin.x);
7242
7243 let max_x = content_origin.x + editor_width - size.width;
7244
7245 if origin.x > max_x {
7246 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7247
7248 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7249 origin.y += offset;
7250 IconName::ArrowUp
7251 } else {
7252 origin.y -= offset;
7253 IconName::ArrowDown
7254 };
7255
7256 element = self
7257 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7258 .into_any();
7259
7260 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7261
7262 origin.x = content_origin.x + editor_width - size.width - px(2.);
7263 }
7264
7265 element.prepaint_at(origin, window, cx);
7266 Some((element, origin))
7267 }
7268
7269 fn render_edit_prediction_diff_popover(
7270 self: &Editor,
7271 text_bounds: &Bounds<Pixels>,
7272 content_origin: gpui::Point<Pixels>,
7273 editor_snapshot: &EditorSnapshot,
7274 visible_row_range: Range<DisplayRow>,
7275 line_layouts: &[LineWithInvisibles],
7276 line_height: Pixels,
7277 scroll_pixel_position: gpui::Point<Pixels>,
7278 newest_selection_head: Option<DisplayPoint>,
7279 editor_width: Pixels,
7280 style: &EditorStyle,
7281 edits: &Vec<(Range<Anchor>, String)>,
7282 edit_preview: &Option<language::EditPreview>,
7283 snapshot: &language::BufferSnapshot,
7284 window: &mut Window,
7285 cx: &mut App,
7286 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7287 let edit_start = edits
7288 .first()
7289 .unwrap()
7290 .0
7291 .start
7292 .to_display_point(editor_snapshot);
7293 let edit_end = edits
7294 .last()
7295 .unwrap()
7296 .0
7297 .end
7298 .to_display_point(editor_snapshot);
7299
7300 let is_visible = visible_row_range.contains(&edit_start.row())
7301 || visible_row_range.contains(&edit_end.row());
7302 if !is_visible {
7303 return None;
7304 }
7305
7306 let highlighted_edits =
7307 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7308
7309 let styled_text = highlighted_edits.to_styled_text(&style.text);
7310 let line_count = highlighted_edits.text.lines().count();
7311
7312 const BORDER_WIDTH: Pixels = px(1.);
7313
7314 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7315 let has_keybind = keybind.is_some();
7316
7317 let mut element = h_flex()
7318 .items_start()
7319 .child(
7320 h_flex()
7321 .bg(cx.theme().colors().editor_background)
7322 .border(BORDER_WIDTH)
7323 .shadow_sm()
7324 .border_color(cx.theme().colors().border)
7325 .rounded_l_lg()
7326 .when(line_count > 1, |el| el.rounded_br_lg())
7327 .pr_1()
7328 .child(styled_text),
7329 )
7330 .child(
7331 h_flex()
7332 .h(line_height + BORDER_WIDTH * 2.)
7333 .px_1p5()
7334 .gap_1()
7335 // Workaround: For some reason, there's a gap if we don't do this
7336 .ml(-BORDER_WIDTH)
7337 .shadow(smallvec![gpui::BoxShadow {
7338 color: gpui::black().opacity(0.05),
7339 offset: point(px(1.), px(1.)),
7340 blur_radius: px(2.),
7341 spread_radius: px(0.),
7342 }])
7343 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7344 .border(BORDER_WIDTH)
7345 .border_color(cx.theme().colors().border)
7346 .rounded_r_lg()
7347 .id("edit_prediction_diff_popover_keybind")
7348 .when(!has_keybind, |el| {
7349 let status_colors = cx.theme().status();
7350
7351 el.bg(status_colors.error_background)
7352 .border_color(status_colors.error.opacity(0.6))
7353 .child(Icon::new(IconName::Info).color(Color::Error))
7354 .cursor_default()
7355 .hoverable_tooltip(move |_window, cx| {
7356 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7357 })
7358 })
7359 .children(keybind),
7360 )
7361 .into_any();
7362
7363 let longest_row =
7364 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7365 let longest_line_width = if visible_row_range.contains(&longest_row) {
7366 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7367 } else {
7368 layout_line(
7369 longest_row,
7370 editor_snapshot,
7371 style,
7372 editor_width,
7373 |_| false,
7374 window,
7375 cx,
7376 )
7377 .width
7378 };
7379
7380 let viewport_bounds =
7381 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7382 right: -EditorElement::SCROLLBAR_WIDTH,
7383 ..Default::default()
7384 });
7385
7386 let x_after_longest =
7387 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7388 - scroll_pixel_position.x;
7389
7390 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7391
7392 // Fully visible if it can be displayed within the window (allow overlapping other
7393 // panes). However, this is only allowed if the popover starts within text_bounds.
7394 let can_position_to_the_right = x_after_longest < text_bounds.right()
7395 && x_after_longest + element_bounds.width < viewport_bounds.right();
7396
7397 let mut origin = if can_position_to_the_right {
7398 point(
7399 x_after_longest,
7400 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7401 - scroll_pixel_position.y,
7402 )
7403 } else {
7404 let cursor_row = newest_selection_head.map(|head| head.row());
7405 let above_edit = edit_start
7406 .row()
7407 .0
7408 .checked_sub(line_count as u32)
7409 .map(DisplayRow);
7410 let below_edit = Some(edit_end.row() + 1);
7411 let above_cursor =
7412 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7413 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7414
7415 // Place the edit popover adjacent to the edit if there is a location
7416 // available that is onscreen and does not obscure the cursor. Otherwise,
7417 // place it adjacent to the cursor.
7418 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7419 .into_iter()
7420 .flatten()
7421 .find(|&start_row| {
7422 let end_row = start_row + line_count as u32;
7423 visible_row_range.contains(&start_row)
7424 && visible_row_range.contains(&end_row)
7425 && cursor_row.map_or(true, |cursor_row| {
7426 !((start_row..end_row).contains(&cursor_row))
7427 })
7428 })?;
7429
7430 content_origin
7431 + point(
7432 -scroll_pixel_position.x,
7433 row_target.as_f32() * line_height - scroll_pixel_position.y,
7434 )
7435 };
7436
7437 origin.x -= BORDER_WIDTH;
7438
7439 window.defer_draw(element, origin, 1);
7440
7441 // Do not return an element, since it will already be drawn due to defer_draw.
7442 None
7443 }
7444
7445 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7446 px(30.)
7447 }
7448
7449 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7450 if self.read_only(cx) {
7451 cx.theme().players().read_only()
7452 } else {
7453 self.style.as_ref().unwrap().local_player
7454 }
7455 }
7456
7457 fn render_edit_prediction_accept_keybind(
7458 &self,
7459 window: &mut Window,
7460 cx: &App,
7461 ) -> Option<AnyElement> {
7462 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7463 let accept_keystroke = accept_binding.keystroke()?;
7464
7465 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7466
7467 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7468 Color::Accent
7469 } else {
7470 Color::Muted
7471 };
7472
7473 h_flex()
7474 .px_0p5()
7475 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7476 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7477 .text_size(TextSize::XSmall.rems(cx))
7478 .child(h_flex().children(ui::render_modifiers(
7479 &accept_keystroke.modifiers,
7480 PlatformStyle::platform(),
7481 Some(modifiers_color),
7482 Some(IconSize::XSmall.rems().into()),
7483 true,
7484 )))
7485 .when(is_platform_style_mac, |parent| {
7486 parent.child(accept_keystroke.key.clone())
7487 })
7488 .when(!is_platform_style_mac, |parent| {
7489 parent.child(
7490 Key::new(
7491 util::capitalize(&accept_keystroke.key),
7492 Some(Color::Default),
7493 )
7494 .size(Some(IconSize::XSmall.rems().into())),
7495 )
7496 })
7497 .into_any()
7498 .into()
7499 }
7500
7501 fn render_edit_prediction_line_popover(
7502 &self,
7503 label: impl Into<SharedString>,
7504 icon: Option<IconName>,
7505 window: &mut Window,
7506 cx: &App,
7507 ) -> Option<Stateful<Div>> {
7508 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7509
7510 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7511 let has_keybind = keybind.is_some();
7512
7513 let result = h_flex()
7514 .id("ep-line-popover")
7515 .py_0p5()
7516 .pl_1()
7517 .pr(padding_right)
7518 .gap_1()
7519 .rounded_md()
7520 .border_1()
7521 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7522 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7523 .shadow_sm()
7524 .when(!has_keybind, |el| {
7525 let status_colors = cx.theme().status();
7526
7527 el.bg(status_colors.error_background)
7528 .border_color(status_colors.error.opacity(0.6))
7529 .pl_2()
7530 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7531 .cursor_default()
7532 .hoverable_tooltip(move |_window, cx| {
7533 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7534 })
7535 })
7536 .children(keybind)
7537 .child(
7538 Label::new(label)
7539 .size(LabelSize::Small)
7540 .when(!has_keybind, |el| {
7541 el.color(cx.theme().status().error.into()).strikethrough()
7542 }),
7543 )
7544 .when(!has_keybind, |el| {
7545 el.child(
7546 h_flex().ml_1().child(
7547 Icon::new(IconName::Info)
7548 .size(IconSize::Small)
7549 .color(cx.theme().status().error.into()),
7550 ),
7551 )
7552 })
7553 .when_some(icon, |element, icon| {
7554 element.child(
7555 div()
7556 .mt(px(1.5))
7557 .child(Icon::new(icon).size(IconSize::Small)),
7558 )
7559 });
7560
7561 Some(result)
7562 }
7563
7564 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7565 let accent_color = cx.theme().colors().text_accent;
7566 let editor_bg_color = cx.theme().colors().editor_background;
7567 editor_bg_color.blend(accent_color.opacity(0.1))
7568 }
7569
7570 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7571 let accent_color = cx.theme().colors().text_accent;
7572 let editor_bg_color = cx.theme().colors().editor_background;
7573 editor_bg_color.blend(accent_color.opacity(0.6))
7574 }
7575
7576 fn render_edit_prediction_cursor_popover(
7577 &self,
7578 min_width: Pixels,
7579 max_width: Pixels,
7580 cursor_point: Point,
7581 style: &EditorStyle,
7582 accept_keystroke: Option<&gpui::Keystroke>,
7583 _window: &Window,
7584 cx: &mut Context<Editor>,
7585 ) -> Option<AnyElement> {
7586 let provider = self.edit_prediction_provider.as_ref()?;
7587
7588 if provider.provider.needs_terms_acceptance(cx) {
7589 return Some(
7590 h_flex()
7591 .min_w(min_width)
7592 .flex_1()
7593 .px_2()
7594 .py_1()
7595 .gap_3()
7596 .elevation_2(cx)
7597 .hover(|style| style.bg(cx.theme().colors().element_hover))
7598 .id("accept-terms")
7599 .cursor_pointer()
7600 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7601 .on_click(cx.listener(|this, _event, window, cx| {
7602 cx.stop_propagation();
7603 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7604 window.dispatch_action(
7605 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7606 cx,
7607 );
7608 }))
7609 .child(
7610 h_flex()
7611 .flex_1()
7612 .gap_2()
7613 .child(Icon::new(IconName::ZedPredict))
7614 .child(Label::new("Accept Terms of Service"))
7615 .child(div().w_full())
7616 .child(
7617 Icon::new(IconName::ArrowUpRight)
7618 .color(Color::Muted)
7619 .size(IconSize::Small),
7620 )
7621 .into_any_element(),
7622 )
7623 .into_any(),
7624 );
7625 }
7626
7627 let is_refreshing = provider.provider.is_refreshing(cx);
7628
7629 fn pending_completion_container() -> Div {
7630 h_flex()
7631 .h_full()
7632 .flex_1()
7633 .gap_2()
7634 .child(Icon::new(IconName::ZedPredict))
7635 }
7636
7637 let completion = match &self.active_inline_completion {
7638 Some(prediction) => {
7639 if !self.has_visible_completions_menu() {
7640 const RADIUS: Pixels = px(6.);
7641 const BORDER_WIDTH: Pixels = px(1.);
7642
7643 return Some(
7644 h_flex()
7645 .elevation_2(cx)
7646 .border(BORDER_WIDTH)
7647 .border_color(cx.theme().colors().border)
7648 .when(accept_keystroke.is_none(), |el| {
7649 el.border_color(cx.theme().status().error)
7650 })
7651 .rounded(RADIUS)
7652 .rounded_tl(px(0.))
7653 .overflow_hidden()
7654 .child(div().px_1p5().child(match &prediction.completion {
7655 InlineCompletion::Move { target, snapshot } => {
7656 use text::ToPoint as _;
7657 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7658 {
7659 Icon::new(IconName::ZedPredictDown)
7660 } else {
7661 Icon::new(IconName::ZedPredictUp)
7662 }
7663 }
7664 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7665 }))
7666 .child(
7667 h_flex()
7668 .gap_1()
7669 .py_1()
7670 .px_2()
7671 .rounded_r(RADIUS - BORDER_WIDTH)
7672 .border_l_1()
7673 .border_color(cx.theme().colors().border)
7674 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7675 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7676 el.child(
7677 Label::new("Hold")
7678 .size(LabelSize::Small)
7679 .when(accept_keystroke.is_none(), |el| {
7680 el.strikethrough()
7681 })
7682 .line_height_style(LineHeightStyle::UiLabel),
7683 )
7684 })
7685 .id("edit_prediction_cursor_popover_keybind")
7686 .when(accept_keystroke.is_none(), |el| {
7687 let status_colors = cx.theme().status();
7688
7689 el.bg(status_colors.error_background)
7690 .border_color(status_colors.error.opacity(0.6))
7691 .child(Icon::new(IconName::Info).color(Color::Error))
7692 .cursor_default()
7693 .hoverable_tooltip(move |_window, cx| {
7694 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7695 .into()
7696 })
7697 })
7698 .when_some(
7699 accept_keystroke.as_ref(),
7700 |el, accept_keystroke| {
7701 el.child(h_flex().children(ui::render_modifiers(
7702 &accept_keystroke.modifiers,
7703 PlatformStyle::platform(),
7704 Some(Color::Default),
7705 Some(IconSize::XSmall.rems().into()),
7706 false,
7707 )))
7708 },
7709 ),
7710 )
7711 .into_any(),
7712 );
7713 }
7714
7715 self.render_edit_prediction_cursor_popover_preview(
7716 prediction,
7717 cursor_point,
7718 style,
7719 cx,
7720 )?
7721 }
7722
7723 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7724 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7725 stale_completion,
7726 cursor_point,
7727 style,
7728 cx,
7729 )?,
7730
7731 None => {
7732 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7733 }
7734 },
7735
7736 None => pending_completion_container().child(Label::new("No Prediction")),
7737 };
7738
7739 let completion = if is_refreshing {
7740 completion
7741 .with_animation(
7742 "loading-completion",
7743 Animation::new(Duration::from_secs(2))
7744 .repeat()
7745 .with_easing(pulsating_between(0.4, 0.8)),
7746 |label, delta| label.opacity(delta),
7747 )
7748 .into_any_element()
7749 } else {
7750 completion.into_any_element()
7751 };
7752
7753 let has_completion = self.active_inline_completion.is_some();
7754
7755 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7756 Some(
7757 h_flex()
7758 .min_w(min_width)
7759 .max_w(max_width)
7760 .flex_1()
7761 .elevation_2(cx)
7762 .border_color(cx.theme().colors().border)
7763 .child(
7764 div()
7765 .flex_1()
7766 .py_1()
7767 .px_2()
7768 .overflow_hidden()
7769 .child(completion),
7770 )
7771 .when_some(accept_keystroke, |el, accept_keystroke| {
7772 if !accept_keystroke.modifiers.modified() {
7773 return el;
7774 }
7775
7776 el.child(
7777 h_flex()
7778 .h_full()
7779 .border_l_1()
7780 .rounded_r_lg()
7781 .border_color(cx.theme().colors().border)
7782 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7783 .gap_1()
7784 .py_1()
7785 .px_2()
7786 .child(
7787 h_flex()
7788 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7789 .when(is_platform_style_mac, |parent| parent.gap_1())
7790 .child(h_flex().children(ui::render_modifiers(
7791 &accept_keystroke.modifiers,
7792 PlatformStyle::platform(),
7793 Some(if !has_completion {
7794 Color::Muted
7795 } else {
7796 Color::Default
7797 }),
7798 None,
7799 false,
7800 ))),
7801 )
7802 .child(Label::new("Preview").into_any_element())
7803 .opacity(if has_completion { 1.0 } else { 0.4 }),
7804 )
7805 })
7806 .into_any(),
7807 )
7808 }
7809
7810 fn render_edit_prediction_cursor_popover_preview(
7811 &self,
7812 completion: &InlineCompletionState,
7813 cursor_point: Point,
7814 style: &EditorStyle,
7815 cx: &mut Context<Editor>,
7816 ) -> Option<Div> {
7817 use text::ToPoint as _;
7818
7819 fn render_relative_row_jump(
7820 prefix: impl Into<String>,
7821 current_row: u32,
7822 target_row: u32,
7823 ) -> Div {
7824 let (row_diff, arrow) = if target_row < current_row {
7825 (current_row - target_row, IconName::ArrowUp)
7826 } else {
7827 (target_row - current_row, IconName::ArrowDown)
7828 };
7829
7830 h_flex()
7831 .child(
7832 Label::new(format!("{}{}", prefix.into(), row_diff))
7833 .color(Color::Muted)
7834 .size(LabelSize::Small),
7835 )
7836 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7837 }
7838
7839 match &completion.completion {
7840 InlineCompletion::Move {
7841 target, snapshot, ..
7842 } => Some(
7843 h_flex()
7844 .px_2()
7845 .gap_2()
7846 .flex_1()
7847 .child(
7848 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7849 Icon::new(IconName::ZedPredictDown)
7850 } else {
7851 Icon::new(IconName::ZedPredictUp)
7852 },
7853 )
7854 .child(Label::new("Jump to Edit")),
7855 ),
7856
7857 InlineCompletion::Edit {
7858 edits,
7859 edit_preview,
7860 snapshot,
7861 display_mode: _,
7862 } => {
7863 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7864
7865 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7866 &snapshot,
7867 &edits,
7868 edit_preview.as_ref()?,
7869 true,
7870 cx,
7871 )
7872 .first_line_preview();
7873
7874 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7875 .with_default_highlights(&style.text, highlighted_edits.highlights);
7876
7877 let preview = h_flex()
7878 .gap_1()
7879 .min_w_16()
7880 .child(styled_text)
7881 .when(has_more_lines, |parent| parent.child("…"));
7882
7883 let left = if first_edit_row != cursor_point.row {
7884 render_relative_row_jump("", cursor_point.row, first_edit_row)
7885 .into_any_element()
7886 } else {
7887 Icon::new(IconName::ZedPredict).into_any_element()
7888 };
7889
7890 Some(
7891 h_flex()
7892 .h_full()
7893 .flex_1()
7894 .gap_2()
7895 .pr_1()
7896 .overflow_x_hidden()
7897 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7898 .child(left)
7899 .child(preview),
7900 )
7901 }
7902 }
7903 }
7904
7905 fn render_context_menu(
7906 &self,
7907 style: &EditorStyle,
7908 max_height_in_lines: u32,
7909 window: &mut Window,
7910 cx: &mut Context<Editor>,
7911 ) -> Option<AnyElement> {
7912 let menu = self.context_menu.borrow();
7913 let menu = menu.as_ref()?;
7914 if !menu.visible() {
7915 return None;
7916 };
7917 Some(menu.render(style, max_height_in_lines, window, cx))
7918 }
7919
7920 fn render_context_menu_aside(
7921 &mut self,
7922 max_size: Size<Pixels>,
7923 window: &mut Window,
7924 cx: &mut Context<Editor>,
7925 ) -> Option<AnyElement> {
7926 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7927 if menu.visible() {
7928 menu.render_aside(self, max_size, window, cx)
7929 } else {
7930 None
7931 }
7932 })
7933 }
7934
7935 fn hide_context_menu(
7936 &mut self,
7937 window: &mut Window,
7938 cx: &mut Context<Self>,
7939 ) -> Option<CodeContextMenu> {
7940 cx.notify();
7941 self.completion_tasks.clear();
7942 let context_menu = self.context_menu.borrow_mut().take();
7943 self.stale_inline_completion_in_menu.take();
7944 self.update_visible_inline_completion(window, cx);
7945 context_menu
7946 }
7947
7948 fn show_snippet_choices(
7949 &mut self,
7950 choices: &Vec<String>,
7951 selection: Range<Anchor>,
7952 cx: &mut Context<Self>,
7953 ) {
7954 if selection.start.buffer_id.is_none() {
7955 return;
7956 }
7957 let buffer_id = selection.start.buffer_id.unwrap();
7958 let buffer = self.buffer().read(cx).buffer(buffer_id);
7959 let id = post_inc(&mut self.next_completion_id);
7960
7961 if let Some(buffer) = buffer {
7962 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7963 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7964 ));
7965 }
7966 }
7967
7968 pub fn insert_snippet(
7969 &mut self,
7970 insertion_ranges: &[Range<usize>],
7971 snippet: Snippet,
7972 window: &mut Window,
7973 cx: &mut Context<Self>,
7974 ) -> Result<()> {
7975 struct Tabstop<T> {
7976 is_end_tabstop: bool,
7977 ranges: Vec<Range<T>>,
7978 choices: Option<Vec<String>>,
7979 }
7980
7981 let tabstops = self.buffer.update(cx, |buffer, cx| {
7982 let snippet_text: Arc<str> = snippet.text.clone().into();
7983 let edits = insertion_ranges
7984 .iter()
7985 .cloned()
7986 .map(|range| (range, snippet_text.clone()));
7987 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7988
7989 let snapshot = &*buffer.read(cx);
7990 let snippet = &snippet;
7991 snippet
7992 .tabstops
7993 .iter()
7994 .map(|tabstop| {
7995 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7996 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7997 });
7998 let mut tabstop_ranges = tabstop
7999 .ranges
8000 .iter()
8001 .flat_map(|tabstop_range| {
8002 let mut delta = 0_isize;
8003 insertion_ranges.iter().map(move |insertion_range| {
8004 let insertion_start = insertion_range.start as isize + delta;
8005 delta +=
8006 snippet.text.len() as isize - insertion_range.len() as isize;
8007
8008 let start = ((insertion_start + tabstop_range.start) as usize)
8009 .min(snapshot.len());
8010 let end = ((insertion_start + tabstop_range.end) as usize)
8011 .min(snapshot.len());
8012 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8013 })
8014 })
8015 .collect::<Vec<_>>();
8016 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8017
8018 Tabstop {
8019 is_end_tabstop,
8020 ranges: tabstop_ranges,
8021 choices: tabstop.choices.clone(),
8022 }
8023 })
8024 .collect::<Vec<_>>()
8025 });
8026 if let Some(tabstop) = tabstops.first() {
8027 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8028 s.select_ranges(tabstop.ranges.iter().cloned());
8029 });
8030
8031 if let Some(choices) = &tabstop.choices {
8032 if let Some(selection) = tabstop.ranges.first() {
8033 self.show_snippet_choices(choices, selection.clone(), cx)
8034 }
8035 }
8036
8037 // If we're already at the last tabstop and it's at the end of the snippet,
8038 // we're done, we don't need to keep the state around.
8039 if !tabstop.is_end_tabstop {
8040 let choices = tabstops
8041 .iter()
8042 .map(|tabstop| tabstop.choices.clone())
8043 .collect();
8044
8045 let ranges = tabstops
8046 .into_iter()
8047 .map(|tabstop| tabstop.ranges)
8048 .collect::<Vec<_>>();
8049
8050 self.snippet_stack.push(SnippetState {
8051 active_index: 0,
8052 ranges,
8053 choices,
8054 });
8055 }
8056
8057 // Check whether the just-entered snippet ends with an auto-closable bracket.
8058 if self.autoclose_regions.is_empty() {
8059 let snapshot = self.buffer.read(cx).snapshot(cx);
8060 for selection in &mut self.selections.all::<Point>(cx) {
8061 let selection_head = selection.head();
8062 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8063 continue;
8064 };
8065
8066 let mut bracket_pair = None;
8067 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8068 let prev_chars = snapshot
8069 .reversed_chars_at(selection_head)
8070 .collect::<String>();
8071 for (pair, enabled) in scope.brackets() {
8072 if enabled
8073 && pair.close
8074 && prev_chars.starts_with(pair.start.as_str())
8075 && next_chars.starts_with(pair.end.as_str())
8076 {
8077 bracket_pair = Some(pair.clone());
8078 break;
8079 }
8080 }
8081 if let Some(pair) = bracket_pair {
8082 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8083 let autoclose_enabled =
8084 self.use_autoclose && snapshot_settings.use_autoclose;
8085 if autoclose_enabled {
8086 let start = snapshot.anchor_after(selection_head);
8087 let end = snapshot.anchor_after(selection_head);
8088 self.autoclose_regions.push(AutocloseRegion {
8089 selection_id: selection.id,
8090 range: start..end,
8091 pair,
8092 });
8093 }
8094 }
8095 }
8096 }
8097 }
8098 Ok(())
8099 }
8100
8101 pub fn move_to_next_snippet_tabstop(
8102 &mut self,
8103 window: &mut Window,
8104 cx: &mut Context<Self>,
8105 ) -> bool {
8106 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8107 }
8108
8109 pub fn move_to_prev_snippet_tabstop(
8110 &mut self,
8111 window: &mut Window,
8112 cx: &mut Context<Self>,
8113 ) -> bool {
8114 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8115 }
8116
8117 pub fn move_to_snippet_tabstop(
8118 &mut self,
8119 bias: Bias,
8120 window: &mut Window,
8121 cx: &mut Context<Self>,
8122 ) -> bool {
8123 if let Some(mut snippet) = self.snippet_stack.pop() {
8124 match bias {
8125 Bias::Left => {
8126 if snippet.active_index > 0 {
8127 snippet.active_index -= 1;
8128 } else {
8129 self.snippet_stack.push(snippet);
8130 return false;
8131 }
8132 }
8133 Bias::Right => {
8134 if snippet.active_index + 1 < snippet.ranges.len() {
8135 snippet.active_index += 1;
8136 } else {
8137 self.snippet_stack.push(snippet);
8138 return false;
8139 }
8140 }
8141 }
8142 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8143 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8144 s.select_anchor_ranges(current_ranges.iter().cloned())
8145 });
8146
8147 if let Some(choices) = &snippet.choices[snippet.active_index] {
8148 if let Some(selection) = current_ranges.first() {
8149 self.show_snippet_choices(&choices, selection.clone(), cx);
8150 }
8151 }
8152
8153 // If snippet state is not at the last tabstop, push it back on the stack
8154 if snippet.active_index + 1 < snippet.ranges.len() {
8155 self.snippet_stack.push(snippet);
8156 }
8157 return true;
8158 }
8159 }
8160
8161 false
8162 }
8163
8164 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8165 self.transact(window, cx, |this, window, cx| {
8166 this.select_all(&SelectAll, window, cx);
8167 this.insert("", window, cx);
8168 });
8169 }
8170
8171 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8172 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8173 self.transact(window, cx, |this, window, cx| {
8174 this.select_autoclose_pair(window, cx);
8175 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8176 if !this.linked_edit_ranges.is_empty() {
8177 let selections = this.selections.all::<MultiBufferPoint>(cx);
8178 let snapshot = this.buffer.read(cx).snapshot(cx);
8179
8180 for selection in selections.iter() {
8181 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8182 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8183 if selection_start.buffer_id != selection_end.buffer_id {
8184 continue;
8185 }
8186 if let Some(ranges) =
8187 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8188 {
8189 for (buffer, entries) in ranges {
8190 linked_ranges.entry(buffer).or_default().extend(entries);
8191 }
8192 }
8193 }
8194 }
8195
8196 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8197 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8198 for selection in &mut selections {
8199 if selection.is_empty() {
8200 let old_head = selection.head();
8201 let mut new_head =
8202 movement::left(&display_map, old_head.to_display_point(&display_map))
8203 .to_point(&display_map);
8204 if let Some((buffer, line_buffer_range)) = display_map
8205 .buffer_snapshot
8206 .buffer_line_for_row(MultiBufferRow(old_head.row))
8207 {
8208 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8209 let indent_len = match indent_size.kind {
8210 IndentKind::Space => {
8211 buffer.settings_at(line_buffer_range.start, cx).tab_size
8212 }
8213 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8214 };
8215 if old_head.column <= indent_size.len && old_head.column > 0 {
8216 let indent_len = indent_len.get();
8217 new_head = cmp::min(
8218 new_head,
8219 MultiBufferPoint::new(
8220 old_head.row,
8221 ((old_head.column - 1) / indent_len) * indent_len,
8222 ),
8223 );
8224 }
8225 }
8226
8227 selection.set_head(new_head, SelectionGoal::None);
8228 }
8229 }
8230
8231 this.signature_help_state.set_backspace_pressed(true);
8232 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8233 s.select(selections)
8234 });
8235 this.insert("", window, cx);
8236 let empty_str: Arc<str> = Arc::from("");
8237 for (buffer, edits) in linked_ranges {
8238 let snapshot = buffer.read(cx).snapshot();
8239 use text::ToPoint as TP;
8240
8241 let edits = edits
8242 .into_iter()
8243 .map(|range| {
8244 let end_point = TP::to_point(&range.end, &snapshot);
8245 let mut start_point = TP::to_point(&range.start, &snapshot);
8246
8247 if end_point == start_point {
8248 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8249 .saturating_sub(1);
8250 start_point =
8251 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8252 };
8253
8254 (start_point..end_point, empty_str.clone())
8255 })
8256 .sorted_by_key(|(range, _)| range.start)
8257 .collect::<Vec<_>>();
8258 buffer.update(cx, |this, cx| {
8259 this.edit(edits, None, cx);
8260 })
8261 }
8262 this.refresh_inline_completion(true, false, window, cx);
8263 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8264 });
8265 }
8266
8267 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8268 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8269 self.transact(window, cx, |this, window, cx| {
8270 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8271 s.move_with(|map, selection| {
8272 if selection.is_empty() {
8273 let cursor = movement::right(map, selection.head());
8274 selection.end = cursor;
8275 selection.reversed = true;
8276 selection.goal = SelectionGoal::None;
8277 }
8278 })
8279 });
8280 this.insert("", window, cx);
8281 this.refresh_inline_completion(true, false, window, cx);
8282 });
8283 }
8284
8285 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8286 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8287 if self.move_to_prev_snippet_tabstop(window, cx) {
8288 return;
8289 }
8290 self.outdent(&Outdent, window, cx);
8291 }
8292
8293 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8294 if self.move_to_next_snippet_tabstop(window, cx) {
8295 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8296 return;
8297 }
8298 if self.read_only(cx) {
8299 return;
8300 }
8301 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8302 let mut selections = self.selections.all_adjusted(cx);
8303 let buffer = self.buffer.read(cx);
8304 let snapshot = buffer.snapshot(cx);
8305 let rows_iter = selections.iter().map(|s| s.head().row);
8306 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8307
8308 let mut edits = Vec::new();
8309 let mut prev_edited_row = 0;
8310 let mut row_delta = 0;
8311 for selection in &mut selections {
8312 if selection.start.row != prev_edited_row {
8313 row_delta = 0;
8314 }
8315 prev_edited_row = selection.end.row;
8316
8317 // If the selection is non-empty, then increase the indentation of the selected lines.
8318 if !selection.is_empty() {
8319 row_delta =
8320 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8321 continue;
8322 }
8323
8324 // If the selection is empty and the cursor is in the leading whitespace before the
8325 // suggested indentation, then auto-indent the line.
8326 let cursor = selection.head();
8327 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8328 if let Some(suggested_indent) =
8329 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8330 {
8331 if cursor.column < suggested_indent.len
8332 && cursor.column <= current_indent.len
8333 && current_indent.len <= suggested_indent.len
8334 {
8335 selection.start = Point::new(cursor.row, suggested_indent.len);
8336 selection.end = selection.start;
8337 if row_delta == 0 {
8338 edits.extend(Buffer::edit_for_indent_size_adjustment(
8339 cursor.row,
8340 current_indent,
8341 suggested_indent,
8342 ));
8343 row_delta = suggested_indent.len - current_indent.len;
8344 }
8345 continue;
8346 }
8347 }
8348
8349 // Otherwise, insert a hard or soft tab.
8350 let settings = buffer.language_settings_at(cursor, cx);
8351 let tab_size = if settings.hard_tabs {
8352 IndentSize::tab()
8353 } else {
8354 let tab_size = settings.tab_size.get();
8355 let indent_remainder = snapshot
8356 .text_for_range(Point::new(cursor.row, 0)..cursor)
8357 .flat_map(str::chars)
8358 .fold(row_delta % tab_size, |counter: u32, c| {
8359 if c == '\t' {
8360 0
8361 } else {
8362 (counter + 1) % tab_size
8363 }
8364 });
8365
8366 let chars_to_next_tab_stop = tab_size - indent_remainder;
8367 IndentSize::spaces(chars_to_next_tab_stop)
8368 };
8369 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8370 selection.end = selection.start;
8371 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8372 row_delta += tab_size.len;
8373 }
8374
8375 self.transact(window, cx, |this, window, cx| {
8376 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8377 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8378 s.select(selections)
8379 });
8380 this.refresh_inline_completion(true, false, window, cx);
8381 });
8382 }
8383
8384 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8385 if self.read_only(cx) {
8386 return;
8387 }
8388 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8389 let mut selections = self.selections.all::<Point>(cx);
8390 let mut prev_edited_row = 0;
8391 let mut row_delta = 0;
8392 let mut edits = Vec::new();
8393 let buffer = self.buffer.read(cx);
8394 let snapshot = buffer.snapshot(cx);
8395 for selection in &mut selections {
8396 if selection.start.row != prev_edited_row {
8397 row_delta = 0;
8398 }
8399 prev_edited_row = selection.end.row;
8400
8401 row_delta =
8402 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8403 }
8404
8405 self.transact(window, cx, |this, window, cx| {
8406 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8407 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8408 s.select(selections)
8409 });
8410 });
8411 }
8412
8413 fn indent_selection(
8414 buffer: &MultiBuffer,
8415 snapshot: &MultiBufferSnapshot,
8416 selection: &mut Selection<Point>,
8417 edits: &mut Vec<(Range<Point>, String)>,
8418 delta_for_start_row: u32,
8419 cx: &App,
8420 ) -> u32 {
8421 let settings = buffer.language_settings_at(selection.start, cx);
8422 let tab_size = settings.tab_size.get();
8423 let indent_kind = if settings.hard_tabs {
8424 IndentKind::Tab
8425 } else {
8426 IndentKind::Space
8427 };
8428 let mut start_row = selection.start.row;
8429 let mut end_row = selection.end.row + 1;
8430
8431 // If a selection ends at the beginning of a line, don't indent
8432 // that last line.
8433 if selection.end.column == 0 && selection.end.row > selection.start.row {
8434 end_row -= 1;
8435 }
8436
8437 // Avoid re-indenting a row that has already been indented by a
8438 // previous selection, but still update this selection's column
8439 // to reflect that indentation.
8440 if delta_for_start_row > 0 {
8441 start_row += 1;
8442 selection.start.column += delta_for_start_row;
8443 if selection.end.row == selection.start.row {
8444 selection.end.column += delta_for_start_row;
8445 }
8446 }
8447
8448 let mut delta_for_end_row = 0;
8449 let has_multiple_rows = start_row + 1 != end_row;
8450 for row in start_row..end_row {
8451 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8452 let indent_delta = match (current_indent.kind, indent_kind) {
8453 (IndentKind::Space, IndentKind::Space) => {
8454 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8455 IndentSize::spaces(columns_to_next_tab_stop)
8456 }
8457 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8458 (_, IndentKind::Tab) => IndentSize::tab(),
8459 };
8460
8461 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8462 0
8463 } else {
8464 selection.start.column
8465 };
8466 let row_start = Point::new(row, start);
8467 edits.push((
8468 row_start..row_start,
8469 indent_delta.chars().collect::<String>(),
8470 ));
8471
8472 // Update this selection's endpoints to reflect the indentation.
8473 if row == selection.start.row {
8474 selection.start.column += indent_delta.len;
8475 }
8476 if row == selection.end.row {
8477 selection.end.column += indent_delta.len;
8478 delta_for_end_row = indent_delta.len;
8479 }
8480 }
8481
8482 if selection.start.row == selection.end.row {
8483 delta_for_start_row + delta_for_end_row
8484 } else {
8485 delta_for_end_row
8486 }
8487 }
8488
8489 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8490 if self.read_only(cx) {
8491 return;
8492 }
8493 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8494 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8495 let selections = self.selections.all::<Point>(cx);
8496 let mut deletion_ranges = Vec::new();
8497 let mut last_outdent = None;
8498 {
8499 let buffer = self.buffer.read(cx);
8500 let snapshot = buffer.snapshot(cx);
8501 for selection in &selections {
8502 let settings = buffer.language_settings_at(selection.start, cx);
8503 let tab_size = settings.tab_size.get();
8504 let mut rows = selection.spanned_rows(false, &display_map);
8505
8506 // Avoid re-outdenting a row that has already been outdented by a
8507 // previous selection.
8508 if let Some(last_row) = last_outdent {
8509 if last_row == rows.start {
8510 rows.start = rows.start.next_row();
8511 }
8512 }
8513 let has_multiple_rows = rows.len() > 1;
8514 for row in rows.iter_rows() {
8515 let indent_size = snapshot.indent_size_for_line(row);
8516 if indent_size.len > 0 {
8517 let deletion_len = match indent_size.kind {
8518 IndentKind::Space => {
8519 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8520 if columns_to_prev_tab_stop == 0 {
8521 tab_size
8522 } else {
8523 columns_to_prev_tab_stop
8524 }
8525 }
8526 IndentKind::Tab => 1,
8527 };
8528 let start = if has_multiple_rows
8529 || deletion_len > selection.start.column
8530 || indent_size.len < selection.start.column
8531 {
8532 0
8533 } else {
8534 selection.start.column - deletion_len
8535 };
8536 deletion_ranges.push(
8537 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8538 );
8539 last_outdent = Some(row);
8540 }
8541 }
8542 }
8543 }
8544
8545 self.transact(window, cx, |this, window, cx| {
8546 this.buffer.update(cx, |buffer, cx| {
8547 let empty_str: Arc<str> = Arc::default();
8548 buffer.edit(
8549 deletion_ranges
8550 .into_iter()
8551 .map(|range| (range, empty_str.clone())),
8552 None,
8553 cx,
8554 );
8555 });
8556 let selections = this.selections.all::<usize>(cx);
8557 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8558 s.select(selections)
8559 });
8560 });
8561 }
8562
8563 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8564 if self.read_only(cx) {
8565 return;
8566 }
8567 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8568 let selections = self
8569 .selections
8570 .all::<usize>(cx)
8571 .into_iter()
8572 .map(|s| s.range());
8573
8574 self.transact(window, cx, |this, window, cx| {
8575 this.buffer.update(cx, |buffer, cx| {
8576 buffer.autoindent_ranges(selections, cx);
8577 });
8578 let selections = this.selections.all::<usize>(cx);
8579 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8580 s.select(selections)
8581 });
8582 });
8583 }
8584
8585 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8586 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8587 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8588 let selections = self.selections.all::<Point>(cx);
8589
8590 let mut new_cursors = Vec::new();
8591 let mut edit_ranges = Vec::new();
8592 let mut selections = selections.iter().peekable();
8593 while let Some(selection) = selections.next() {
8594 let mut rows = selection.spanned_rows(false, &display_map);
8595 let goal_display_column = selection.head().to_display_point(&display_map).column();
8596
8597 // Accumulate contiguous regions of rows that we want to delete.
8598 while let Some(next_selection) = selections.peek() {
8599 let next_rows = next_selection.spanned_rows(false, &display_map);
8600 if next_rows.start <= rows.end {
8601 rows.end = next_rows.end;
8602 selections.next().unwrap();
8603 } else {
8604 break;
8605 }
8606 }
8607
8608 let buffer = &display_map.buffer_snapshot;
8609 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8610 let edit_end;
8611 let cursor_buffer_row;
8612 if buffer.max_point().row >= rows.end.0 {
8613 // If there's a line after the range, delete the \n from the end of the row range
8614 // and position the cursor on the next line.
8615 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8616 cursor_buffer_row = rows.end;
8617 } else {
8618 // If there isn't a line after the range, delete the \n from the line before the
8619 // start of the row range and position the cursor there.
8620 edit_start = edit_start.saturating_sub(1);
8621 edit_end = buffer.len();
8622 cursor_buffer_row = rows.start.previous_row();
8623 }
8624
8625 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8626 *cursor.column_mut() =
8627 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8628
8629 new_cursors.push((
8630 selection.id,
8631 buffer.anchor_after(cursor.to_point(&display_map)),
8632 ));
8633 edit_ranges.push(edit_start..edit_end);
8634 }
8635
8636 self.transact(window, cx, |this, window, cx| {
8637 let buffer = this.buffer.update(cx, |buffer, cx| {
8638 let empty_str: Arc<str> = Arc::default();
8639 buffer.edit(
8640 edit_ranges
8641 .into_iter()
8642 .map(|range| (range, empty_str.clone())),
8643 None,
8644 cx,
8645 );
8646 buffer.snapshot(cx)
8647 });
8648 let new_selections = new_cursors
8649 .into_iter()
8650 .map(|(id, cursor)| {
8651 let cursor = cursor.to_point(&buffer);
8652 Selection {
8653 id,
8654 start: cursor,
8655 end: cursor,
8656 reversed: false,
8657 goal: SelectionGoal::None,
8658 }
8659 })
8660 .collect();
8661
8662 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8663 s.select(new_selections);
8664 });
8665 });
8666 }
8667
8668 pub fn join_lines_impl(
8669 &mut self,
8670 insert_whitespace: bool,
8671 window: &mut Window,
8672 cx: &mut Context<Self>,
8673 ) {
8674 if self.read_only(cx) {
8675 return;
8676 }
8677 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8678 for selection in self.selections.all::<Point>(cx) {
8679 let start = MultiBufferRow(selection.start.row);
8680 // Treat single line selections as if they include the next line. Otherwise this action
8681 // would do nothing for single line selections individual cursors.
8682 let end = if selection.start.row == selection.end.row {
8683 MultiBufferRow(selection.start.row + 1)
8684 } else {
8685 MultiBufferRow(selection.end.row)
8686 };
8687
8688 if let Some(last_row_range) = row_ranges.last_mut() {
8689 if start <= last_row_range.end {
8690 last_row_range.end = end;
8691 continue;
8692 }
8693 }
8694 row_ranges.push(start..end);
8695 }
8696
8697 let snapshot = self.buffer.read(cx).snapshot(cx);
8698 let mut cursor_positions = Vec::new();
8699 for row_range in &row_ranges {
8700 let anchor = snapshot.anchor_before(Point::new(
8701 row_range.end.previous_row().0,
8702 snapshot.line_len(row_range.end.previous_row()),
8703 ));
8704 cursor_positions.push(anchor..anchor);
8705 }
8706
8707 self.transact(window, cx, |this, window, cx| {
8708 for row_range in row_ranges.into_iter().rev() {
8709 for row in row_range.iter_rows().rev() {
8710 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8711 let next_line_row = row.next_row();
8712 let indent = snapshot.indent_size_for_line(next_line_row);
8713 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8714
8715 let replace =
8716 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8717 " "
8718 } else {
8719 ""
8720 };
8721
8722 this.buffer.update(cx, |buffer, cx| {
8723 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8724 });
8725 }
8726 }
8727
8728 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8729 s.select_anchor_ranges(cursor_positions)
8730 });
8731 });
8732 }
8733
8734 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8735 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8736 self.join_lines_impl(true, window, cx);
8737 }
8738
8739 pub fn sort_lines_case_sensitive(
8740 &mut self,
8741 _: &SortLinesCaseSensitive,
8742 window: &mut Window,
8743 cx: &mut Context<Self>,
8744 ) {
8745 self.manipulate_lines(window, cx, |lines| lines.sort())
8746 }
8747
8748 pub fn sort_lines_case_insensitive(
8749 &mut self,
8750 _: &SortLinesCaseInsensitive,
8751 window: &mut Window,
8752 cx: &mut Context<Self>,
8753 ) {
8754 self.manipulate_lines(window, cx, |lines| {
8755 lines.sort_by_key(|line| line.to_lowercase())
8756 })
8757 }
8758
8759 pub fn unique_lines_case_insensitive(
8760 &mut self,
8761 _: &UniqueLinesCaseInsensitive,
8762 window: &mut Window,
8763 cx: &mut Context<Self>,
8764 ) {
8765 self.manipulate_lines(window, cx, |lines| {
8766 let mut seen = HashSet::default();
8767 lines.retain(|line| seen.insert(line.to_lowercase()));
8768 })
8769 }
8770
8771 pub fn unique_lines_case_sensitive(
8772 &mut self,
8773 _: &UniqueLinesCaseSensitive,
8774 window: &mut Window,
8775 cx: &mut Context<Self>,
8776 ) {
8777 self.manipulate_lines(window, cx, |lines| {
8778 let mut seen = HashSet::default();
8779 lines.retain(|line| seen.insert(*line));
8780 })
8781 }
8782
8783 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8784 let Some(project) = self.project.clone() else {
8785 return;
8786 };
8787 self.reload(project, window, cx)
8788 .detach_and_notify_err(window, cx);
8789 }
8790
8791 pub fn restore_file(
8792 &mut self,
8793 _: &::git::RestoreFile,
8794 window: &mut Window,
8795 cx: &mut Context<Self>,
8796 ) {
8797 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8798 let mut buffer_ids = HashSet::default();
8799 let snapshot = self.buffer().read(cx).snapshot(cx);
8800 for selection in self.selections.all::<usize>(cx) {
8801 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8802 }
8803
8804 let buffer = self.buffer().read(cx);
8805 let ranges = buffer_ids
8806 .into_iter()
8807 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8808 .collect::<Vec<_>>();
8809
8810 self.restore_hunks_in_ranges(ranges, window, cx);
8811 }
8812
8813 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8814 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8815 let selections = self
8816 .selections
8817 .all(cx)
8818 .into_iter()
8819 .map(|s| s.range())
8820 .collect();
8821 self.restore_hunks_in_ranges(selections, window, cx);
8822 }
8823
8824 pub fn restore_hunks_in_ranges(
8825 &mut self,
8826 ranges: Vec<Range<Point>>,
8827 window: &mut Window,
8828 cx: &mut Context<Editor>,
8829 ) {
8830 let mut revert_changes = HashMap::default();
8831 let chunk_by = self
8832 .snapshot(window, cx)
8833 .hunks_for_ranges(ranges)
8834 .into_iter()
8835 .chunk_by(|hunk| hunk.buffer_id);
8836 for (buffer_id, hunks) in &chunk_by {
8837 let hunks = hunks.collect::<Vec<_>>();
8838 for hunk in &hunks {
8839 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8840 }
8841 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8842 }
8843 drop(chunk_by);
8844 if !revert_changes.is_empty() {
8845 self.transact(window, cx, |editor, window, cx| {
8846 editor.restore(revert_changes, window, cx);
8847 });
8848 }
8849 }
8850
8851 pub fn open_active_item_in_terminal(
8852 &mut self,
8853 _: &OpenInTerminal,
8854 window: &mut Window,
8855 cx: &mut Context<Self>,
8856 ) {
8857 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8858 let project_path = buffer.read(cx).project_path(cx)?;
8859 let project = self.project.as_ref()?.read(cx);
8860 let entry = project.entry_for_path(&project_path, cx)?;
8861 let parent = match &entry.canonical_path {
8862 Some(canonical_path) => canonical_path.to_path_buf(),
8863 None => project.absolute_path(&project_path, cx)?,
8864 }
8865 .parent()?
8866 .to_path_buf();
8867 Some(parent)
8868 }) {
8869 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8870 }
8871 }
8872
8873 fn set_breakpoint_context_menu(
8874 &mut self,
8875 display_row: DisplayRow,
8876 position: Option<Anchor>,
8877 clicked_point: gpui::Point<Pixels>,
8878 window: &mut Window,
8879 cx: &mut Context<Self>,
8880 ) {
8881 if !cx.has_flag::<Debugger>() {
8882 return;
8883 }
8884 let source = self
8885 .buffer
8886 .read(cx)
8887 .snapshot(cx)
8888 .anchor_before(Point::new(display_row.0, 0u32));
8889
8890 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8891
8892 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8893 self,
8894 source,
8895 clicked_point,
8896 context_menu,
8897 window,
8898 cx,
8899 );
8900 }
8901
8902 fn add_edit_breakpoint_block(
8903 &mut self,
8904 anchor: Anchor,
8905 breakpoint: &Breakpoint,
8906 edit_action: BreakpointPromptEditAction,
8907 window: &mut Window,
8908 cx: &mut Context<Self>,
8909 ) {
8910 let weak_editor = cx.weak_entity();
8911 let bp_prompt = cx.new(|cx| {
8912 BreakpointPromptEditor::new(
8913 weak_editor,
8914 anchor,
8915 breakpoint.clone(),
8916 edit_action,
8917 window,
8918 cx,
8919 )
8920 });
8921
8922 let height = bp_prompt.update(cx, |this, cx| {
8923 this.prompt
8924 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8925 });
8926 let cloned_prompt = bp_prompt.clone();
8927 let blocks = vec![BlockProperties {
8928 style: BlockStyle::Sticky,
8929 placement: BlockPlacement::Above(anchor),
8930 height: Some(height),
8931 render: Arc::new(move |cx| {
8932 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8933 cloned_prompt.clone().into_any_element()
8934 }),
8935 priority: 0,
8936 }];
8937
8938 let focus_handle = bp_prompt.focus_handle(cx);
8939 window.focus(&focus_handle);
8940
8941 let block_ids = self.insert_blocks(blocks, None, cx);
8942 bp_prompt.update(cx, |prompt, _| {
8943 prompt.add_block_ids(block_ids);
8944 });
8945 }
8946
8947 pub(crate) fn breakpoint_at_row(
8948 &self,
8949 row: u32,
8950 window: &mut Window,
8951 cx: &mut Context<Self>,
8952 ) -> Option<(Anchor, Breakpoint)> {
8953 let snapshot = self.snapshot(window, cx);
8954 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8955
8956 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
8957 }
8958
8959 pub(crate) fn breakpoint_at_anchor(
8960 &self,
8961 breakpoint_position: Anchor,
8962 snapshot: &EditorSnapshot,
8963 cx: &mut Context<Self>,
8964 ) -> Option<(Anchor, Breakpoint)> {
8965 let project = self.project.clone()?;
8966
8967 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8968 snapshot
8969 .buffer_snapshot
8970 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8971 })?;
8972
8973 let enclosing_excerpt = breakpoint_position.excerpt_id;
8974 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8975 let buffer_snapshot = buffer.read(cx).snapshot();
8976
8977 let row = buffer_snapshot
8978 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8979 .row;
8980
8981 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8982 let anchor_end = snapshot
8983 .buffer_snapshot
8984 .anchor_after(Point::new(row, line_len));
8985
8986 let bp = self
8987 .breakpoint_store
8988 .as_ref()?
8989 .read_with(cx, |breakpoint_store, cx| {
8990 breakpoint_store
8991 .breakpoints(
8992 &buffer,
8993 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8994 &buffer_snapshot,
8995 cx,
8996 )
8997 .next()
8998 .and_then(|(anchor, bp)| {
8999 let breakpoint_row = buffer_snapshot
9000 .summary_for_anchor::<text::PointUtf16>(anchor)
9001 .row;
9002
9003 if breakpoint_row == row {
9004 snapshot
9005 .buffer_snapshot
9006 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9007 .map(|anchor| (anchor, bp.clone()))
9008 } else {
9009 None
9010 }
9011 })
9012 });
9013 bp
9014 }
9015
9016 pub fn edit_log_breakpoint(
9017 &mut self,
9018 _: &EditLogBreakpoint,
9019 window: &mut Window,
9020 cx: &mut Context<Self>,
9021 ) {
9022 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9023 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9024 message: None,
9025 state: BreakpointState::Enabled,
9026 condition: None,
9027 hit_condition: None,
9028 });
9029
9030 self.add_edit_breakpoint_block(
9031 anchor,
9032 &breakpoint,
9033 BreakpointPromptEditAction::Log,
9034 window,
9035 cx,
9036 );
9037 }
9038 }
9039
9040 fn breakpoints_at_cursors(
9041 &self,
9042 window: &mut Window,
9043 cx: &mut Context<Self>,
9044 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9045 let snapshot = self.snapshot(window, cx);
9046 let cursors = self
9047 .selections
9048 .disjoint_anchors()
9049 .into_iter()
9050 .map(|selection| {
9051 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9052
9053 let breakpoint_position = self
9054 .breakpoint_at_row(cursor_position.row, window, cx)
9055 .map(|bp| bp.0)
9056 .unwrap_or_else(|| {
9057 snapshot
9058 .display_snapshot
9059 .buffer_snapshot
9060 .anchor_after(Point::new(cursor_position.row, 0))
9061 });
9062
9063 let breakpoint = self
9064 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9065 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9066
9067 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9068 })
9069 // 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.
9070 .collect::<HashMap<Anchor, _>>();
9071
9072 cursors.into_iter().collect()
9073 }
9074
9075 pub fn enable_breakpoint(
9076 &mut self,
9077 _: &crate::actions::EnableBreakpoint,
9078 window: &mut Window,
9079 cx: &mut Context<Self>,
9080 ) {
9081 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9082 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9083 continue;
9084 };
9085 self.edit_breakpoint_at_anchor(
9086 anchor,
9087 breakpoint,
9088 BreakpointEditAction::InvertState,
9089 cx,
9090 );
9091 }
9092 }
9093
9094 pub fn disable_breakpoint(
9095 &mut self,
9096 _: &crate::actions::DisableBreakpoint,
9097 window: &mut Window,
9098 cx: &mut Context<Self>,
9099 ) {
9100 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9101 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9102 continue;
9103 };
9104 self.edit_breakpoint_at_anchor(
9105 anchor,
9106 breakpoint,
9107 BreakpointEditAction::InvertState,
9108 cx,
9109 );
9110 }
9111 }
9112
9113 pub fn toggle_breakpoint(
9114 &mut self,
9115 _: &crate::actions::ToggleBreakpoint,
9116 window: &mut Window,
9117 cx: &mut Context<Self>,
9118 ) {
9119 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9120 if let Some(breakpoint) = breakpoint {
9121 self.edit_breakpoint_at_anchor(
9122 anchor,
9123 breakpoint,
9124 BreakpointEditAction::Toggle,
9125 cx,
9126 );
9127 } else {
9128 self.edit_breakpoint_at_anchor(
9129 anchor,
9130 Breakpoint::new_standard(),
9131 BreakpointEditAction::Toggle,
9132 cx,
9133 );
9134 }
9135 }
9136 }
9137
9138 pub fn edit_breakpoint_at_anchor(
9139 &mut self,
9140 breakpoint_position: Anchor,
9141 breakpoint: Breakpoint,
9142 edit_action: BreakpointEditAction,
9143 cx: &mut Context<Self>,
9144 ) {
9145 let Some(breakpoint_store) = &self.breakpoint_store else {
9146 return;
9147 };
9148
9149 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9150 if breakpoint_position == Anchor::min() {
9151 self.buffer()
9152 .read(cx)
9153 .excerpt_buffer_ids()
9154 .into_iter()
9155 .next()
9156 } else {
9157 None
9158 }
9159 }) else {
9160 return;
9161 };
9162
9163 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9164 return;
9165 };
9166
9167 breakpoint_store.update(cx, |breakpoint_store, cx| {
9168 breakpoint_store.toggle_breakpoint(
9169 buffer,
9170 (breakpoint_position.text_anchor, breakpoint),
9171 edit_action,
9172 cx,
9173 );
9174 });
9175
9176 cx.notify();
9177 }
9178
9179 #[cfg(any(test, feature = "test-support"))]
9180 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9181 self.breakpoint_store.clone()
9182 }
9183
9184 pub fn prepare_restore_change(
9185 &self,
9186 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9187 hunk: &MultiBufferDiffHunk,
9188 cx: &mut App,
9189 ) -> Option<()> {
9190 if hunk.is_created_file() {
9191 return None;
9192 }
9193 let buffer = self.buffer.read(cx);
9194 let diff = buffer.diff_for(hunk.buffer_id)?;
9195 let buffer = buffer.buffer(hunk.buffer_id)?;
9196 let buffer = buffer.read(cx);
9197 let original_text = diff
9198 .read(cx)
9199 .base_text()
9200 .as_rope()
9201 .slice(hunk.diff_base_byte_range.clone());
9202 let buffer_snapshot = buffer.snapshot();
9203 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9204 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9205 probe
9206 .0
9207 .start
9208 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9209 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9210 }) {
9211 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9212 Some(())
9213 } else {
9214 None
9215 }
9216 }
9217
9218 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9219 self.manipulate_lines(window, cx, |lines| lines.reverse())
9220 }
9221
9222 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9223 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9224 }
9225
9226 fn manipulate_lines<Fn>(
9227 &mut self,
9228 window: &mut Window,
9229 cx: &mut Context<Self>,
9230 mut callback: Fn,
9231 ) where
9232 Fn: FnMut(&mut Vec<&str>),
9233 {
9234 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9235
9236 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9237 let buffer = self.buffer.read(cx).snapshot(cx);
9238
9239 let mut edits = Vec::new();
9240
9241 let selections = self.selections.all::<Point>(cx);
9242 let mut selections = selections.iter().peekable();
9243 let mut contiguous_row_selections = Vec::new();
9244 let mut new_selections = Vec::new();
9245 let mut added_lines = 0;
9246 let mut removed_lines = 0;
9247
9248 while let Some(selection) = selections.next() {
9249 let (start_row, end_row) = consume_contiguous_rows(
9250 &mut contiguous_row_selections,
9251 selection,
9252 &display_map,
9253 &mut selections,
9254 );
9255
9256 let start_point = Point::new(start_row.0, 0);
9257 let end_point = Point::new(
9258 end_row.previous_row().0,
9259 buffer.line_len(end_row.previous_row()),
9260 );
9261 let text = buffer
9262 .text_for_range(start_point..end_point)
9263 .collect::<String>();
9264
9265 let mut lines = text.split('\n').collect_vec();
9266
9267 let lines_before = lines.len();
9268 callback(&mut lines);
9269 let lines_after = lines.len();
9270
9271 edits.push((start_point..end_point, lines.join("\n")));
9272
9273 // Selections must change based on added and removed line count
9274 let start_row =
9275 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9276 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9277 new_selections.push(Selection {
9278 id: selection.id,
9279 start: start_row,
9280 end: end_row,
9281 goal: SelectionGoal::None,
9282 reversed: selection.reversed,
9283 });
9284
9285 if lines_after > lines_before {
9286 added_lines += lines_after - lines_before;
9287 } else if lines_before > lines_after {
9288 removed_lines += lines_before - lines_after;
9289 }
9290 }
9291
9292 self.transact(window, cx, |this, window, cx| {
9293 let buffer = this.buffer.update(cx, |buffer, cx| {
9294 buffer.edit(edits, None, cx);
9295 buffer.snapshot(cx)
9296 });
9297
9298 // Recalculate offsets on newly edited buffer
9299 let new_selections = new_selections
9300 .iter()
9301 .map(|s| {
9302 let start_point = Point::new(s.start.0, 0);
9303 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9304 Selection {
9305 id: s.id,
9306 start: buffer.point_to_offset(start_point),
9307 end: buffer.point_to_offset(end_point),
9308 goal: s.goal,
9309 reversed: s.reversed,
9310 }
9311 })
9312 .collect();
9313
9314 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9315 s.select(new_selections);
9316 });
9317
9318 this.request_autoscroll(Autoscroll::fit(), cx);
9319 });
9320 }
9321
9322 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9323 self.manipulate_text(window, cx, |text| {
9324 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9325 if has_upper_case_characters {
9326 text.to_lowercase()
9327 } else {
9328 text.to_uppercase()
9329 }
9330 })
9331 }
9332
9333 pub fn convert_to_upper_case(
9334 &mut self,
9335 _: &ConvertToUpperCase,
9336 window: &mut Window,
9337 cx: &mut Context<Self>,
9338 ) {
9339 self.manipulate_text(window, cx, |text| text.to_uppercase())
9340 }
9341
9342 pub fn convert_to_lower_case(
9343 &mut self,
9344 _: &ConvertToLowerCase,
9345 window: &mut Window,
9346 cx: &mut Context<Self>,
9347 ) {
9348 self.manipulate_text(window, cx, |text| text.to_lowercase())
9349 }
9350
9351 pub fn convert_to_title_case(
9352 &mut self,
9353 _: &ConvertToTitleCase,
9354 window: &mut Window,
9355 cx: &mut Context<Self>,
9356 ) {
9357 self.manipulate_text(window, cx, |text| {
9358 text.split('\n')
9359 .map(|line| line.to_case(Case::Title))
9360 .join("\n")
9361 })
9362 }
9363
9364 pub fn convert_to_snake_case(
9365 &mut self,
9366 _: &ConvertToSnakeCase,
9367 window: &mut Window,
9368 cx: &mut Context<Self>,
9369 ) {
9370 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9371 }
9372
9373 pub fn convert_to_kebab_case(
9374 &mut self,
9375 _: &ConvertToKebabCase,
9376 window: &mut Window,
9377 cx: &mut Context<Self>,
9378 ) {
9379 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9380 }
9381
9382 pub fn convert_to_upper_camel_case(
9383 &mut self,
9384 _: &ConvertToUpperCamelCase,
9385 window: &mut Window,
9386 cx: &mut Context<Self>,
9387 ) {
9388 self.manipulate_text(window, cx, |text| {
9389 text.split('\n')
9390 .map(|line| line.to_case(Case::UpperCamel))
9391 .join("\n")
9392 })
9393 }
9394
9395 pub fn convert_to_lower_camel_case(
9396 &mut self,
9397 _: &ConvertToLowerCamelCase,
9398 window: &mut Window,
9399 cx: &mut Context<Self>,
9400 ) {
9401 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9402 }
9403
9404 pub fn convert_to_opposite_case(
9405 &mut self,
9406 _: &ConvertToOppositeCase,
9407 window: &mut Window,
9408 cx: &mut Context<Self>,
9409 ) {
9410 self.manipulate_text(window, cx, |text| {
9411 text.chars()
9412 .fold(String::with_capacity(text.len()), |mut t, c| {
9413 if c.is_uppercase() {
9414 t.extend(c.to_lowercase());
9415 } else {
9416 t.extend(c.to_uppercase());
9417 }
9418 t
9419 })
9420 })
9421 }
9422
9423 pub fn convert_to_rot13(
9424 &mut self,
9425 _: &ConvertToRot13,
9426 window: &mut Window,
9427 cx: &mut Context<Self>,
9428 ) {
9429 self.manipulate_text(window, cx, |text| {
9430 text.chars()
9431 .map(|c| match c {
9432 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9433 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9434 _ => c,
9435 })
9436 .collect()
9437 })
9438 }
9439
9440 pub fn convert_to_rot47(
9441 &mut self,
9442 _: &ConvertToRot47,
9443 window: &mut Window,
9444 cx: &mut Context<Self>,
9445 ) {
9446 self.manipulate_text(window, cx, |text| {
9447 text.chars()
9448 .map(|c| {
9449 let code_point = c as u32;
9450 if code_point >= 33 && code_point <= 126 {
9451 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9452 }
9453 c
9454 })
9455 .collect()
9456 })
9457 }
9458
9459 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9460 where
9461 Fn: FnMut(&str) -> String,
9462 {
9463 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9464 let buffer = self.buffer.read(cx).snapshot(cx);
9465
9466 let mut new_selections = Vec::new();
9467 let mut edits = Vec::new();
9468 let mut selection_adjustment = 0i32;
9469
9470 for selection in self.selections.all::<usize>(cx) {
9471 let selection_is_empty = selection.is_empty();
9472
9473 let (start, end) = if selection_is_empty {
9474 let word_range = movement::surrounding_word(
9475 &display_map,
9476 selection.start.to_display_point(&display_map),
9477 );
9478 let start = word_range.start.to_offset(&display_map, Bias::Left);
9479 let end = word_range.end.to_offset(&display_map, Bias::Left);
9480 (start, end)
9481 } else {
9482 (selection.start, selection.end)
9483 };
9484
9485 let text = buffer.text_for_range(start..end).collect::<String>();
9486 let old_length = text.len() as i32;
9487 let text = callback(&text);
9488
9489 new_selections.push(Selection {
9490 start: (start as i32 - selection_adjustment) as usize,
9491 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9492 goal: SelectionGoal::None,
9493 ..selection
9494 });
9495
9496 selection_adjustment += old_length - text.len() as i32;
9497
9498 edits.push((start..end, text));
9499 }
9500
9501 self.transact(window, cx, |this, window, cx| {
9502 this.buffer.update(cx, |buffer, cx| {
9503 buffer.edit(edits, None, cx);
9504 });
9505
9506 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9507 s.select(new_selections);
9508 });
9509
9510 this.request_autoscroll(Autoscroll::fit(), cx);
9511 });
9512 }
9513
9514 pub fn duplicate(
9515 &mut self,
9516 upwards: bool,
9517 whole_lines: bool,
9518 window: &mut Window,
9519 cx: &mut Context<Self>,
9520 ) {
9521 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9522
9523 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9524 let buffer = &display_map.buffer_snapshot;
9525 let selections = self.selections.all::<Point>(cx);
9526
9527 let mut edits = Vec::new();
9528 let mut selections_iter = selections.iter().peekable();
9529 while let Some(selection) = selections_iter.next() {
9530 let mut rows = selection.spanned_rows(false, &display_map);
9531 // duplicate line-wise
9532 if whole_lines || selection.start == selection.end {
9533 // Avoid duplicating the same lines twice.
9534 while let Some(next_selection) = selections_iter.peek() {
9535 let next_rows = next_selection.spanned_rows(false, &display_map);
9536 if next_rows.start < rows.end {
9537 rows.end = next_rows.end;
9538 selections_iter.next().unwrap();
9539 } else {
9540 break;
9541 }
9542 }
9543
9544 // Copy the text from the selected row region and splice it either at the start
9545 // or end of the region.
9546 let start = Point::new(rows.start.0, 0);
9547 let end = Point::new(
9548 rows.end.previous_row().0,
9549 buffer.line_len(rows.end.previous_row()),
9550 );
9551 let text = buffer
9552 .text_for_range(start..end)
9553 .chain(Some("\n"))
9554 .collect::<String>();
9555 let insert_location = if upwards {
9556 Point::new(rows.end.0, 0)
9557 } else {
9558 start
9559 };
9560 edits.push((insert_location..insert_location, text));
9561 } else {
9562 // duplicate character-wise
9563 let start = selection.start;
9564 let end = selection.end;
9565 let text = buffer.text_for_range(start..end).collect::<String>();
9566 edits.push((selection.end..selection.end, text));
9567 }
9568 }
9569
9570 self.transact(window, cx, |this, _, cx| {
9571 this.buffer.update(cx, |buffer, cx| {
9572 buffer.edit(edits, None, cx);
9573 });
9574
9575 this.request_autoscroll(Autoscroll::fit(), cx);
9576 });
9577 }
9578
9579 pub fn duplicate_line_up(
9580 &mut self,
9581 _: &DuplicateLineUp,
9582 window: &mut Window,
9583 cx: &mut Context<Self>,
9584 ) {
9585 self.duplicate(true, true, window, cx);
9586 }
9587
9588 pub fn duplicate_line_down(
9589 &mut self,
9590 _: &DuplicateLineDown,
9591 window: &mut Window,
9592 cx: &mut Context<Self>,
9593 ) {
9594 self.duplicate(false, true, window, cx);
9595 }
9596
9597 pub fn duplicate_selection(
9598 &mut self,
9599 _: &DuplicateSelection,
9600 window: &mut Window,
9601 cx: &mut Context<Self>,
9602 ) {
9603 self.duplicate(false, false, window, cx);
9604 }
9605
9606 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9607 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9608
9609 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9610 let buffer = self.buffer.read(cx).snapshot(cx);
9611
9612 let mut edits = Vec::new();
9613 let mut unfold_ranges = Vec::new();
9614 let mut refold_creases = Vec::new();
9615
9616 let selections = self.selections.all::<Point>(cx);
9617 let mut selections = selections.iter().peekable();
9618 let mut contiguous_row_selections = Vec::new();
9619 let mut new_selections = Vec::new();
9620
9621 while let Some(selection) = selections.next() {
9622 // Find all the selections that span a contiguous row range
9623 let (start_row, end_row) = consume_contiguous_rows(
9624 &mut contiguous_row_selections,
9625 selection,
9626 &display_map,
9627 &mut selections,
9628 );
9629
9630 // Move the text spanned by the row range to be before the line preceding the row range
9631 if start_row.0 > 0 {
9632 let range_to_move = Point::new(
9633 start_row.previous_row().0,
9634 buffer.line_len(start_row.previous_row()),
9635 )
9636 ..Point::new(
9637 end_row.previous_row().0,
9638 buffer.line_len(end_row.previous_row()),
9639 );
9640 let insertion_point = display_map
9641 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9642 .0;
9643
9644 // Don't move lines across excerpts
9645 if buffer
9646 .excerpt_containing(insertion_point..range_to_move.end)
9647 .is_some()
9648 {
9649 let text = buffer
9650 .text_for_range(range_to_move.clone())
9651 .flat_map(|s| s.chars())
9652 .skip(1)
9653 .chain(['\n'])
9654 .collect::<String>();
9655
9656 edits.push((
9657 buffer.anchor_after(range_to_move.start)
9658 ..buffer.anchor_before(range_to_move.end),
9659 String::new(),
9660 ));
9661 let insertion_anchor = buffer.anchor_after(insertion_point);
9662 edits.push((insertion_anchor..insertion_anchor, text));
9663
9664 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9665
9666 // Move selections up
9667 new_selections.extend(contiguous_row_selections.drain(..).map(
9668 |mut selection| {
9669 selection.start.row -= row_delta;
9670 selection.end.row -= row_delta;
9671 selection
9672 },
9673 ));
9674
9675 // Move folds up
9676 unfold_ranges.push(range_to_move.clone());
9677 for fold in display_map.folds_in_range(
9678 buffer.anchor_before(range_to_move.start)
9679 ..buffer.anchor_after(range_to_move.end),
9680 ) {
9681 let mut start = fold.range.start.to_point(&buffer);
9682 let mut end = fold.range.end.to_point(&buffer);
9683 start.row -= row_delta;
9684 end.row -= row_delta;
9685 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9686 }
9687 }
9688 }
9689
9690 // If we didn't move line(s), preserve the existing selections
9691 new_selections.append(&mut contiguous_row_selections);
9692 }
9693
9694 self.transact(window, cx, |this, window, cx| {
9695 this.unfold_ranges(&unfold_ranges, true, true, cx);
9696 this.buffer.update(cx, |buffer, cx| {
9697 for (range, text) in edits {
9698 buffer.edit([(range, text)], None, cx);
9699 }
9700 });
9701 this.fold_creases(refold_creases, true, window, cx);
9702 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9703 s.select(new_selections);
9704 })
9705 });
9706 }
9707
9708 pub fn move_line_down(
9709 &mut self,
9710 _: &MoveLineDown,
9711 window: &mut Window,
9712 cx: &mut Context<Self>,
9713 ) {
9714 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9715
9716 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9717 let buffer = self.buffer.read(cx).snapshot(cx);
9718
9719 let mut edits = Vec::new();
9720 let mut unfold_ranges = Vec::new();
9721 let mut refold_creases = Vec::new();
9722
9723 let selections = self.selections.all::<Point>(cx);
9724 let mut selections = selections.iter().peekable();
9725 let mut contiguous_row_selections = Vec::new();
9726 let mut new_selections = Vec::new();
9727
9728 while let Some(selection) = selections.next() {
9729 // Find all the selections that span a contiguous row range
9730 let (start_row, end_row) = consume_contiguous_rows(
9731 &mut contiguous_row_selections,
9732 selection,
9733 &display_map,
9734 &mut selections,
9735 );
9736
9737 // Move the text spanned by the row range to be after the last line of the row range
9738 if end_row.0 <= buffer.max_point().row {
9739 let range_to_move =
9740 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9741 let insertion_point = display_map
9742 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9743 .0;
9744
9745 // Don't move lines across excerpt boundaries
9746 if buffer
9747 .excerpt_containing(range_to_move.start..insertion_point)
9748 .is_some()
9749 {
9750 let mut text = String::from("\n");
9751 text.extend(buffer.text_for_range(range_to_move.clone()));
9752 text.pop(); // Drop trailing newline
9753 edits.push((
9754 buffer.anchor_after(range_to_move.start)
9755 ..buffer.anchor_before(range_to_move.end),
9756 String::new(),
9757 ));
9758 let insertion_anchor = buffer.anchor_after(insertion_point);
9759 edits.push((insertion_anchor..insertion_anchor, text));
9760
9761 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9762
9763 // Move selections down
9764 new_selections.extend(contiguous_row_selections.drain(..).map(
9765 |mut selection| {
9766 selection.start.row += row_delta;
9767 selection.end.row += row_delta;
9768 selection
9769 },
9770 ));
9771
9772 // Move folds down
9773 unfold_ranges.push(range_to_move.clone());
9774 for fold in display_map.folds_in_range(
9775 buffer.anchor_before(range_to_move.start)
9776 ..buffer.anchor_after(range_to_move.end),
9777 ) {
9778 let mut start = fold.range.start.to_point(&buffer);
9779 let mut end = fold.range.end.to_point(&buffer);
9780 start.row += row_delta;
9781 end.row += row_delta;
9782 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9783 }
9784 }
9785 }
9786
9787 // If we didn't move line(s), preserve the existing selections
9788 new_selections.append(&mut contiguous_row_selections);
9789 }
9790
9791 self.transact(window, cx, |this, window, cx| {
9792 this.unfold_ranges(&unfold_ranges, true, true, cx);
9793 this.buffer.update(cx, |buffer, cx| {
9794 for (range, text) in edits {
9795 buffer.edit([(range, text)], None, cx);
9796 }
9797 });
9798 this.fold_creases(refold_creases, true, window, cx);
9799 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9800 s.select(new_selections)
9801 });
9802 });
9803 }
9804
9805 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9806 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9807 let text_layout_details = &self.text_layout_details(window);
9808 self.transact(window, cx, |this, window, cx| {
9809 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9810 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9811 s.move_with(|display_map, selection| {
9812 if !selection.is_empty() {
9813 return;
9814 }
9815
9816 let mut head = selection.head();
9817 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9818 if head.column() == display_map.line_len(head.row()) {
9819 transpose_offset = display_map
9820 .buffer_snapshot
9821 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9822 }
9823
9824 if transpose_offset == 0 {
9825 return;
9826 }
9827
9828 *head.column_mut() += 1;
9829 head = display_map.clip_point(head, Bias::Right);
9830 let goal = SelectionGoal::HorizontalPosition(
9831 display_map
9832 .x_for_display_point(head, text_layout_details)
9833 .into(),
9834 );
9835 selection.collapse_to(head, goal);
9836
9837 let transpose_start = display_map
9838 .buffer_snapshot
9839 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9840 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9841 let transpose_end = display_map
9842 .buffer_snapshot
9843 .clip_offset(transpose_offset + 1, Bias::Right);
9844 if let Some(ch) =
9845 display_map.buffer_snapshot.chars_at(transpose_start).next()
9846 {
9847 edits.push((transpose_start..transpose_offset, String::new()));
9848 edits.push((transpose_end..transpose_end, ch.to_string()));
9849 }
9850 }
9851 });
9852 edits
9853 });
9854 this.buffer
9855 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9856 let selections = this.selections.all::<usize>(cx);
9857 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9858 s.select(selections);
9859 });
9860 });
9861 }
9862
9863 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9864 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9865 self.rewrap_impl(RewrapOptions::default(), cx)
9866 }
9867
9868 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9869 let buffer = self.buffer.read(cx).snapshot(cx);
9870 let selections = self.selections.all::<Point>(cx);
9871 let mut selections = selections.iter().peekable();
9872
9873 let mut edits = Vec::new();
9874 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9875
9876 while let Some(selection) = selections.next() {
9877 let mut start_row = selection.start.row;
9878 let mut end_row = selection.end.row;
9879
9880 // Skip selections that overlap with a range that has already been rewrapped.
9881 let selection_range = start_row..end_row;
9882 if rewrapped_row_ranges
9883 .iter()
9884 .any(|range| range.overlaps(&selection_range))
9885 {
9886 continue;
9887 }
9888
9889 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9890
9891 // Since not all lines in the selection may be at the same indent
9892 // level, choose the indent size that is the most common between all
9893 // of the lines.
9894 //
9895 // If there is a tie, we use the deepest indent.
9896 let (indent_size, indent_end) = {
9897 let mut indent_size_occurrences = HashMap::default();
9898 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9899
9900 for row in start_row..=end_row {
9901 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9902 rows_by_indent_size.entry(indent).or_default().push(row);
9903 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9904 }
9905
9906 let indent_size = indent_size_occurrences
9907 .into_iter()
9908 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9909 .map(|(indent, _)| indent)
9910 .unwrap_or_default();
9911 let row = rows_by_indent_size[&indent_size][0];
9912 let indent_end = Point::new(row, indent_size.len);
9913
9914 (indent_size, indent_end)
9915 };
9916
9917 let mut line_prefix = indent_size.chars().collect::<String>();
9918
9919 let mut inside_comment = false;
9920 if let Some(comment_prefix) =
9921 buffer
9922 .language_scope_at(selection.head())
9923 .and_then(|language| {
9924 language
9925 .line_comment_prefixes()
9926 .iter()
9927 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9928 .cloned()
9929 })
9930 {
9931 line_prefix.push_str(&comment_prefix);
9932 inside_comment = true;
9933 }
9934
9935 let language_settings = buffer.language_settings_at(selection.head(), cx);
9936 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9937 RewrapBehavior::InComments => inside_comment,
9938 RewrapBehavior::InSelections => !selection.is_empty(),
9939 RewrapBehavior::Anywhere => true,
9940 };
9941
9942 let should_rewrap = options.override_language_settings
9943 || allow_rewrap_based_on_language
9944 || self.hard_wrap.is_some();
9945 if !should_rewrap {
9946 continue;
9947 }
9948
9949 if selection.is_empty() {
9950 'expand_upwards: while start_row > 0 {
9951 let prev_row = start_row - 1;
9952 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9953 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9954 {
9955 start_row = prev_row;
9956 } else {
9957 break 'expand_upwards;
9958 }
9959 }
9960
9961 'expand_downwards: while end_row < buffer.max_point().row {
9962 let next_row = end_row + 1;
9963 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9964 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9965 {
9966 end_row = next_row;
9967 } else {
9968 break 'expand_downwards;
9969 }
9970 }
9971 }
9972
9973 let start = Point::new(start_row, 0);
9974 let start_offset = start.to_offset(&buffer);
9975 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9976 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9977 let Some(lines_without_prefixes) = selection_text
9978 .lines()
9979 .map(|line| {
9980 line.strip_prefix(&line_prefix)
9981 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9982 .ok_or_else(|| {
9983 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9984 })
9985 })
9986 .collect::<Result<Vec<_>, _>>()
9987 .log_err()
9988 else {
9989 continue;
9990 };
9991
9992 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9993 buffer
9994 .language_settings_at(Point::new(start_row, 0), cx)
9995 .preferred_line_length as usize
9996 });
9997 let wrapped_text = wrap_with_prefix(
9998 line_prefix,
9999 lines_without_prefixes.join("\n"),
10000 wrap_column,
10001 tab_size,
10002 options.preserve_existing_whitespace,
10003 );
10004
10005 // TODO: should always use char-based diff while still supporting cursor behavior that
10006 // matches vim.
10007 let mut diff_options = DiffOptions::default();
10008 if options.override_language_settings {
10009 diff_options.max_word_diff_len = 0;
10010 diff_options.max_word_diff_line_count = 0;
10011 } else {
10012 diff_options.max_word_diff_len = usize::MAX;
10013 diff_options.max_word_diff_line_count = usize::MAX;
10014 }
10015
10016 for (old_range, new_text) in
10017 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10018 {
10019 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10020 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10021 edits.push((edit_start..edit_end, new_text));
10022 }
10023
10024 rewrapped_row_ranges.push(start_row..=end_row);
10025 }
10026
10027 self.buffer
10028 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10029 }
10030
10031 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10032 let mut text = String::new();
10033 let buffer = self.buffer.read(cx).snapshot(cx);
10034 let mut selections = self.selections.all::<Point>(cx);
10035 let mut clipboard_selections = Vec::with_capacity(selections.len());
10036 {
10037 let max_point = buffer.max_point();
10038 let mut is_first = true;
10039 for selection in &mut selections {
10040 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10041 if is_entire_line {
10042 selection.start = Point::new(selection.start.row, 0);
10043 if !selection.is_empty() && selection.end.column == 0 {
10044 selection.end = cmp::min(max_point, selection.end);
10045 } else {
10046 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10047 }
10048 selection.goal = SelectionGoal::None;
10049 }
10050 if is_first {
10051 is_first = false;
10052 } else {
10053 text += "\n";
10054 }
10055 let mut len = 0;
10056 for chunk in buffer.text_for_range(selection.start..selection.end) {
10057 text.push_str(chunk);
10058 len += chunk.len();
10059 }
10060 clipboard_selections.push(ClipboardSelection {
10061 len,
10062 is_entire_line,
10063 first_line_indent: buffer
10064 .indent_size_for_line(MultiBufferRow(selection.start.row))
10065 .len,
10066 });
10067 }
10068 }
10069
10070 self.transact(window, cx, |this, window, cx| {
10071 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10072 s.select(selections);
10073 });
10074 this.insert("", window, cx);
10075 });
10076 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10077 }
10078
10079 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10080 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10081 let item = self.cut_common(window, cx);
10082 cx.write_to_clipboard(item);
10083 }
10084
10085 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10086 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10087 self.change_selections(None, window, cx, |s| {
10088 s.move_with(|snapshot, sel| {
10089 if sel.is_empty() {
10090 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10091 }
10092 });
10093 });
10094 let item = self.cut_common(window, cx);
10095 cx.set_global(KillRing(item))
10096 }
10097
10098 pub fn kill_ring_yank(
10099 &mut self,
10100 _: &KillRingYank,
10101 window: &mut Window,
10102 cx: &mut Context<Self>,
10103 ) {
10104 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10105 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10106 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10107 (kill_ring.text().to_string(), kill_ring.metadata_json())
10108 } else {
10109 return;
10110 }
10111 } else {
10112 return;
10113 };
10114 self.do_paste(&text, metadata, false, window, cx);
10115 }
10116
10117 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10118 self.do_copy(true, cx);
10119 }
10120
10121 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10122 self.do_copy(false, cx);
10123 }
10124
10125 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10126 let selections = self.selections.all::<Point>(cx);
10127 let buffer = self.buffer.read(cx).read(cx);
10128 let mut text = String::new();
10129
10130 let mut clipboard_selections = Vec::with_capacity(selections.len());
10131 {
10132 let max_point = buffer.max_point();
10133 let mut is_first = true;
10134 for selection in &selections {
10135 let mut start = selection.start;
10136 let mut end = selection.end;
10137 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10138 if is_entire_line {
10139 start = Point::new(start.row, 0);
10140 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10141 }
10142
10143 let mut trimmed_selections = Vec::new();
10144 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10145 let row = MultiBufferRow(start.row);
10146 let first_indent = buffer.indent_size_for_line(row);
10147 if first_indent.len == 0 || start.column > first_indent.len {
10148 trimmed_selections.push(start..end);
10149 } else {
10150 trimmed_selections.push(
10151 Point::new(row.0, first_indent.len)
10152 ..Point::new(row.0, buffer.line_len(row)),
10153 );
10154 for row in start.row + 1..=end.row {
10155 let mut line_len = buffer.line_len(MultiBufferRow(row));
10156 if row == end.row {
10157 line_len = end.column;
10158 }
10159 if line_len == 0 {
10160 trimmed_selections
10161 .push(Point::new(row, 0)..Point::new(row, line_len));
10162 continue;
10163 }
10164 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10165 if row_indent_size.len >= first_indent.len {
10166 trimmed_selections.push(
10167 Point::new(row, first_indent.len)..Point::new(row, line_len),
10168 );
10169 } else {
10170 trimmed_selections.clear();
10171 trimmed_selections.push(start..end);
10172 break;
10173 }
10174 }
10175 }
10176 } else {
10177 trimmed_selections.push(start..end);
10178 }
10179
10180 for trimmed_range in trimmed_selections {
10181 if is_first {
10182 is_first = false;
10183 } else {
10184 text += "\n";
10185 }
10186 let mut len = 0;
10187 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10188 text.push_str(chunk);
10189 len += chunk.len();
10190 }
10191 clipboard_selections.push(ClipboardSelection {
10192 len,
10193 is_entire_line,
10194 first_line_indent: buffer
10195 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10196 .len,
10197 });
10198 }
10199 }
10200 }
10201
10202 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10203 text,
10204 clipboard_selections,
10205 ));
10206 }
10207
10208 pub fn do_paste(
10209 &mut self,
10210 text: &String,
10211 clipboard_selections: Option<Vec<ClipboardSelection>>,
10212 handle_entire_lines: bool,
10213 window: &mut Window,
10214 cx: &mut Context<Self>,
10215 ) {
10216 if self.read_only(cx) {
10217 return;
10218 }
10219
10220 let clipboard_text = Cow::Borrowed(text);
10221
10222 self.transact(window, cx, |this, window, cx| {
10223 if let Some(mut clipboard_selections) = clipboard_selections {
10224 let old_selections = this.selections.all::<usize>(cx);
10225 let all_selections_were_entire_line =
10226 clipboard_selections.iter().all(|s| s.is_entire_line);
10227 let first_selection_indent_column =
10228 clipboard_selections.first().map(|s| s.first_line_indent);
10229 if clipboard_selections.len() != old_selections.len() {
10230 clipboard_selections.drain(..);
10231 }
10232 let cursor_offset = this.selections.last::<usize>(cx).head();
10233 let mut auto_indent_on_paste = true;
10234
10235 this.buffer.update(cx, |buffer, cx| {
10236 let snapshot = buffer.read(cx);
10237 auto_indent_on_paste = snapshot
10238 .language_settings_at(cursor_offset, cx)
10239 .auto_indent_on_paste;
10240
10241 let mut start_offset = 0;
10242 let mut edits = Vec::new();
10243 let mut original_indent_columns = Vec::new();
10244 for (ix, selection) in old_selections.iter().enumerate() {
10245 let to_insert;
10246 let entire_line;
10247 let original_indent_column;
10248 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10249 let end_offset = start_offset + clipboard_selection.len;
10250 to_insert = &clipboard_text[start_offset..end_offset];
10251 entire_line = clipboard_selection.is_entire_line;
10252 start_offset = end_offset + 1;
10253 original_indent_column = Some(clipboard_selection.first_line_indent);
10254 } else {
10255 to_insert = clipboard_text.as_str();
10256 entire_line = all_selections_were_entire_line;
10257 original_indent_column = first_selection_indent_column
10258 }
10259
10260 // If the corresponding selection was empty when this slice of the
10261 // clipboard text was written, then the entire line containing the
10262 // selection was copied. If this selection is also currently empty,
10263 // then paste the line before the current line of the buffer.
10264 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10265 let column = selection.start.to_point(&snapshot).column as usize;
10266 let line_start = selection.start - column;
10267 line_start..line_start
10268 } else {
10269 selection.range()
10270 };
10271
10272 edits.push((range, to_insert));
10273 original_indent_columns.push(original_indent_column);
10274 }
10275 drop(snapshot);
10276
10277 buffer.edit(
10278 edits,
10279 if auto_indent_on_paste {
10280 Some(AutoindentMode::Block {
10281 original_indent_columns,
10282 })
10283 } else {
10284 None
10285 },
10286 cx,
10287 );
10288 });
10289
10290 let selections = this.selections.all::<usize>(cx);
10291 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10292 s.select(selections)
10293 });
10294 } else {
10295 this.insert(&clipboard_text, window, cx);
10296 }
10297 });
10298 }
10299
10300 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10301 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10302 if let Some(item) = cx.read_from_clipboard() {
10303 let entries = item.entries();
10304
10305 match entries.first() {
10306 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10307 // of all the pasted entries.
10308 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10309 .do_paste(
10310 clipboard_string.text(),
10311 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10312 true,
10313 window,
10314 cx,
10315 ),
10316 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10317 }
10318 }
10319 }
10320
10321 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10322 if self.read_only(cx) {
10323 return;
10324 }
10325
10326 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10327
10328 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10329 if let Some((selections, _)) =
10330 self.selection_history.transaction(transaction_id).cloned()
10331 {
10332 self.change_selections(None, window, cx, |s| {
10333 s.select_anchors(selections.to_vec());
10334 });
10335 } else {
10336 log::error!(
10337 "No entry in selection_history found for undo. \
10338 This may correspond to a bug where undo does not update the selection. \
10339 If this is occurring, please add details to \
10340 https://github.com/zed-industries/zed/issues/22692"
10341 );
10342 }
10343 self.request_autoscroll(Autoscroll::fit(), cx);
10344 self.unmark_text(window, cx);
10345 self.refresh_inline_completion(true, false, window, cx);
10346 cx.emit(EditorEvent::Edited { transaction_id });
10347 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10348 }
10349 }
10350
10351 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10352 if self.read_only(cx) {
10353 return;
10354 }
10355
10356 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10357
10358 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10359 if let Some((_, Some(selections))) =
10360 self.selection_history.transaction(transaction_id).cloned()
10361 {
10362 self.change_selections(None, window, cx, |s| {
10363 s.select_anchors(selections.to_vec());
10364 });
10365 } else {
10366 log::error!(
10367 "No entry in selection_history found for redo. \
10368 This may correspond to a bug where undo does not update the selection. \
10369 If this is occurring, please add details to \
10370 https://github.com/zed-industries/zed/issues/22692"
10371 );
10372 }
10373 self.request_autoscroll(Autoscroll::fit(), cx);
10374 self.unmark_text(window, cx);
10375 self.refresh_inline_completion(true, false, window, cx);
10376 cx.emit(EditorEvent::Edited { transaction_id });
10377 }
10378 }
10379
10380 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10381 self.buffer
10382 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10383 }
10384
10385 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10386 self.buffer
10387 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10388 }
10389
10390 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10391 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10392 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10393 s.move_with(|map, selection| {
10394 let cursor = if selection.is_empty() {
10395 movement::left(map, selection.start)
10396 } else {
10397 selection.start
10398 };
10399 selection.collapse_to(cursor, SelectionGoal::None);
10400 });
10401 })
10402 }
10403
10404 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10405 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10406 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10407 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10408 })
10409 }
10410
10411 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10412 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10413 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10414 s.move_with(|map, selection| {
10415 let cursor = if selection.is_empty() {
10416 movement::right(map, selection.end)
10417 } else {
10418 selection.end
10419 };
10420 selection.collapse_to(cursor, SelectionGoal::None)
10421 });
10422 })
10423 }
10424
10425 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10426 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10427 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10428 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10429 })
10430 }
10431
10432 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10433 if self.take_rename(true, window, cx).is_some() {
10434 return;
10435 }
10436
10437 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10438 cx.propagate();
10439 return;
10440 }
10441
10442 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10443
10444 let text_layout_details = &self.text_layout_details(window);
10445 let selection_count = self.selections.count();
10446 let first_selection = self.selections.first_anchor();
10447
10448 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10449 s.move_with(|map, selection| {
10450 if !selection.is_empty() {
10451 selection.goal = SelectionGoal::None;
10452 }
10453 let (cursor, goal) = movement::up(
10454 map,
10455 selection.start,
10456 selection.goal,
10457 false,
10458 text_layout_details,
10459 );
10460 selection.collapse_to(cursor, goal);
10461 });
10462 });
10463
10464 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10465 {
10466 cx.propagate();
10467 }
10468 }
10469
10470 pub fn move_up_by_lines(
10471 &mut self,
10472 action: &MoveUpByLines,
10473 window: &mut Window,
10474 cx: &mut Context<Self>,
10475 ) {
10476 if self.take_rename(true, window, cx).is_some() {
10477 return;
10478 }
10479
10480 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10481 cx.propagate();
10482 return;
10483 }
10484
10485 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10486
10487 let text_layout_details = &self.text_layout_details(window);
10488
10489 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10490 s.move_with(|map, selection| {
10491 if !selection.is_empty() {
10492 selection.goal = SelectionGoal::None;
10493 }
10494 let (cursor, goal) = movement::up_by_rows(
10495 map,
10496 selection.start,
10497 action.lines,
10498 selection.goal,
10499 false,
10500 text_layout_details,
10501 );
10502 selection.collapse_to(cursor, goal);
10503 });
10504 })
10505 }
10506
10507 pub fn move_down_by_lines(
10508 &mut self,
10509 action: &MoveDownByLines,
10510 window: &mut Window,
10511 cx: &mut Context<Self>,
10512 ) {
10513 if self.take_rename(true, window, cx).is_some() {
10514 return;
10515 }
10516
10517 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10518 cx.propagate();
10519 return;
10520 }
10521
10522 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10523
10524 let text_layout_details = &self.text_layout_details(window);
10525
10526 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10527 s.move_with(|map, selection| {
10528 if !selection.is_empty() {
10529 selection.goal = SelectionGoal::None;
10530 }
10531 let (cursor, goal) = movement::down_by_rows(
10532 map,
10533 selection.start,
10534 action.lines,
10535 selection.goal,
10536 false,
10537 text_layout_details,
10538 );
10539 selection.collapse_to(cursor, goal);
10540 });
10541 })
10542 }
10543
10544 pub fn select_down_by_lines(
10545 &mut self,
10546 action: &SelectDownByLines,
10547 window: &mut Window,
10548 cx: &mut Context<Self>,
10549 ) {
10550 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10551 let text_layout_details = &self.text_layout_details(window);
10552 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10553 s.move_heads_with(|map, head, goal| {
10554 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10555 })
10556 })
10557 }
10558
10559 pub fn select_up_by_lines(
10560 &mut self,
10561 action: &SelectUpByLines,
10562 window: &mut Window,
10563 cx: &mut Context<Self>,
10564 ) {
10565 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10566 let text_layout_details = &self.text_layout_details(window);
10567 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10568 s.move_heads_with(|map, head, goal| {
10569 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10570 })
10571 })
10572 }
10573
10574 pub fn select_page_up(
10575 &mut self,
10576 _: &SelectPageUp,
10577 window: &mut Window,
10578 cx: &mut Context<Self>,
10579 ) {
10580 let Some(row_count) = self.visible_row_count() else {
10581 return;
10582 };
10583
10584 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10585
10586 let text_layout_details = &self.text_layout_details(window);
10587
10588 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10589 s.move_heads_with(|map, head, goal| {
10590 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10591 })
10592 })
10593 }
10594
10595 pub fn move_page_up(
10596 &mut self,
10597 action: &MovePageUp,
10598 window: &mut Window,
10599 cx: &mut Context<Self>,
10600 ) {
10601 if self.take_rename(true, window, cx).is_some() {
10602 return;
10603 }
10604
10605 if self
10606 .context_menu
10607 .borrow_mut()
10608 .as_mut()
10609 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10610 .unwrap_or(false)
10611 {
10612 return;
10613 }
10614
10615 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10616 cx.propagate();
10617 return;
10618 }
10619
10620 let Some(row_count) = self.visible_row_count() else {
10621 return;
10622 };
10623
10624 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10625
10626 let autoscroll = if action.center_cursor {
10627 Autoscroll::center()
10628 } else {
10629 Autoscroll::fit()
10630 };
10631
10632 let text_layout_details = &self.text_layout_details(window);
10633
10634 self.change_selections(Some(autoscroll), window, cx, |s| {
10635 s.move_with(|map, selection| {
10636 if !selection.is_empty() {
10637 selection.goal = SelectionGoal::None;
10638 }
10639 let (cursor, goal) = movement::up_by_rows(
10640 map,
10641 selection.end,
10642 row_count,
10643 selection.goal,
10644 false,
10645 text_layout_details,
10646 );
10647 selection.collapse_to(cursor, goal);
10648 });
10649 });
10650 }
10651
10652 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10653 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10654 let text_layout_details = &self.text_layout_details(window);
10655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10656 s.move_heads_with(|map, head, goal| {
10657 movement::up(map, head, goal, false, text_layout_details)
10658 })
10659 })
10660 }
10661
10662 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10663 self.take_rename(true, window, cx);
10664
10665 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10666 cx.propagate();
10667 return;
10668 }
10669
10670 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10671
10672 let text_layout_details = &self.text_layout_details(window);
10673 let selection_count = self.selections.count();
10674 let first_selection = self.selections.first_anchor();
10675
10676 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10677 s.move_with(|map, selection| {
10678 if !selection.is_empty() {
10679 selection.goal = SelectionGoal::None;
10680 }
10681 let (cursor, goal) = movement::down(
10682 map,
10683 selection.end,
10684 selection.goal,
10685 false,
10686 text_layout_details,
10687 );
10688 selection.collapse_to(cursor, goal);
10689 });
10690 });
10691
10692 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10693 {
10694 cx.propagate();
10695 }
10696 }
10697
10698 pub fn select_page_down(
10699 &mut self,
10700 _: &SelectPageDown,
10701 window: &mut Window,
10702 cx: &mut Context<Self>,
10703 ) {
10704 let Some(row_count) = self.visible_row_count() else {
10705 return;
10706 };
10707
10708 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10709
10710 let text_layout_details = &self.text_layout_details(window);
10711
10712 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10713 s.move_heads_with(|map, head, goal| {
10714 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10715 })
10716 })
10717 }
10718
10719 pub fn move_page_down(
10720 &mut self,
10721 action: &MovePageDown,
10722 window: &mut Window,
10723 cx: &mut Context<Self>,
10724 ) {
10725 if self.take_rename(true, window, cx).is_some() {
10726 return;
10727 }
10728
10729 if self
10730 .context_menu
10731 .borrow_mut()
10732 .as_mut()
10733 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10734 .unwrap_or(false)
10735 {
10736 return;
10737 }
10738
10739 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10740 cx.propagate();
10741 return;
10742 }
10743
10744 let Some(row_count) = self.visible_row_count() else {
10745 return;
10746 };
10747
10748 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10749
10750 let autoscroll = if action.center_cursor {
10751 Autoscroll::center()
10752 } else {
10753 Autoscroll::fit()
10754 };
10755
10756 let text_layout_details = &self.text_layout_details(window);
10757 self.change_selections(Some(autoscroll), window, cx, |s| {
10758 s.move_with(|map, selection| {
10759 if !selection.is_empty() {
10760 selection.goal = SelectionGoal::None;
10761 }
10762 let (cursor, goal) = movement::down_by_rows(
10763 map,
10764 selection.end,
10765 row_count,
10766 selection.goal,
10767 false,
10768 text_layout_details,
10769 );
10770 selection.collapse_to(cursor, goal);
10771 });
10772 });
10773 }
10774
10775 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10776 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10777 let text_layout_details = &self.text_layout_details(window);
10778 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10779 s.move_heads_with(|map, head, goal| {
10780 movement::down(map, head, goal, false, text_layout_details)
10781 })
10782 });
10783 }
10784
10785 pub fn context_menu_first(
10786 &mut self,
10787 _: &ContextMenuFirst,
10788 _window: &mut Window,
10789 cx: &mut Context<Self>,
10790 ) {
10791 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10792 context_menu.select_first(self.completion_provider.as_deref(), cx);
10793 }
10794 }
10795
10796 pub fn context_menu_prev(
10797 &mut self,
10798 _: &ContextMenuPrevious,
10799 _window: &mut Window,
10800 cx: &mut Context<Self>,
10801 ) {
10802 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10803 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10804 }
10805 }
10806
10807 pub fn context_menu_next(
10808 &mut self,
10809 _: &ContextMenuNext,
10810 _window: &mut Window,
10811 cx: &mut Context<Self>,
10812 ) {
10813 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10814 context_menu.select_next(self.completion_provider.as_deref(), cx);
10815 }
10816 }
10817
10818 pub fn context_menu_last(
10819 &mut self,
10820 _: &ContextMenuLast,
10821 _window: &mut Window,
10822 cx: &mut Context<Self>,
10823 ) {
10824 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10825 context_menu.select_last(self.completion_provider.as_deref(), cx);
10826 }
10827 }
10828
10829 pub fn move_to_previous_word_start(
10830 &mut self,
10831 _: &MoveToPreviousWordStart,
10832 window: &mut Window,
10833 cx: &mut Context<Self>,
10834 ) {
10835 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10836 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10837 s.move_cursors_with(|map, head, _| {
10838 (
10839 movement::previous_word_start(map, head),
10840 SelectionGoal::None,
10841 )
10842 });
10843 })
10844 }
10845
10846 pub fn move_to_previous_subword_start(
10847 &mut self,
10848 _: &MoveToPreviousSubwordStart,
10849 window: &mut Window,
10850 cx: &mut Context<Self>,
10851 ) {
10852 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10853 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10854 s.move_cursors_with(|map, head, _| {
10855 (
10856 movement::previous_subword_start(map, head),
10857 SelectionGoal::None,
10858 )
10859 });
10860 })
10861 }
10862
10863 pub fn select_to_previous_word_start(
10864 &mut self,
10865 _: &SelectToPreviousWordStart,
10866 window: &mut Window,
10867 cx: &mut Context<Self>,
10868 ) {
10869 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10870 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10871 s.move_heads_with(|map, head, _| {
10872 (
10873 movement::previous_word_start(map, head),
10874 SelectionGoal::None,
10875 )
10876 });
10877 })
10878 }
10879
10880 pub fn select_to_previous_subword_start(
10881 &mut self,
10882 _: &SelectToPreviousSubwordStart,
10883 window: &mut Window,
10884 cx: &mut Context<Self>,
10885 ) {
10886 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10887 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10888 s.move_heads_with(|map, head, _| {
10889 (
10890 movement::previous_subword_start(map, head),
10891 SelectionGoal::None,
10892 )
10893 });
10894 })
10895 }
10896
10897 pub fn delete_to_previous_word_start(
10898 &mut self,
10899 action: &DeleteToPreviousWordStart,
10900 window: &mut Window,
10901 cx: &mut Context<Self>,
10902 ) {
10903 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10904 self.transact(window, cx, |this, window, cx| {
10905 this.select_autoclose_pair(window, cx);
10906 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10907 s.move_with(|map, selection| {
10908 if selection.is_empty() {
10909 let cursor = if action.ignore_newlines {
10910 movement::previous_word_start(map, selection.head())
10911 } else {
10912 movement::previous_word_start_or_newline(map, selection.head())
10913 };
10914 selection.set_head(cursor, SelectionGoal::None);
10915 }
10916 });
10917 });
10918 this.insert("", window, cx);
10919 });
10920 }
10921
10922 pub fn delete_to_previous_subword_start(
10923 &mut self,
10924 _: &DeleteToPreviousSubwordStart,
10925 window: &mut Window,
10926 cx: &mut Context<Self>,
10927 ) {
10928 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10929 self.transact(window, cx, |this, window, cx| {
10930 this.select_autoclose_pair(window, cx);
10931 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10932 s.move_with(|map, selection| {
10933 if selection.is_empty() {
10934 let cursor = movement::previous_subword_start(map, selection.head());
10935 selection.set_head(cursor, SelectionGoal::None);
10936 }
10937 });
10938 });
10939 this.insert("", window, cx);
10940 });
10941 }
10942
10943 pub fn move_to_next_word_end(
10944 &mut self,
10945 _: &MoveToNextWordEnd,
10946 window: &mut Window,
10947 cx: &mut Context<Self>,
10948 ) {
10949 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10950 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10951 s.move_cursors_with(|map, head, _| {
10952 (movement::next_word_end(map, head), SelectionGoal::None)
10953 });
10954 })
10955 }
10956
10957 pub fn move_to_next_subword_end(
10958 &mut self,
10959 _: &MoveToNextSubwordEnd,
10960 window: &mut Window,
10961 cx: &mut Context<Self>,
10962 ) {
10963 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10964 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10965 s.move_cursors_with(|map, head, _| {
10966 (movement::next_subword_end(map, head), SelectionGoal::None)
10967 });
10968 })
10969 }
10970
10971 pub fn select_to_next_word_end(
10972 &mut self,
10973 _: &SelectToNextWordEnd,
10974 window: &mut Window,
10975 cx: &mut Context<Self>,
10976 ) {
10977 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10978 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10979 s.move_heads_with(|map, head, _| {
10980 (movement::next_word_end(map, head), SelectionGoal::None)
10981 });
10982 })
10983 }
10984
10985 pub fn select_to_next_subword_end(
10986 &mut self,
10987 _: &SelectToNextSubwordEnd,
10988 window: &mut Window,
10989 cx: &mut Context<Self>,
10990 ) {
10991 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10992 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10993 s.move_heads_with(|map, head, _| {
10994 (movement::next_subword_end(map, head), SelectionGoal::None)
10995 });
10996 })
10997 }
10998
10999 pub fn delete_to_next_word_end(
11000 &mut self,
11001 action: &DeleteToNextWordEnd,
11002 window: &mut Window,
11003 cx: &mut Context<Self>,
11004 ) {
11005 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11006 self.transact(window, cx, |this, window, cx| {
11007 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11008 s.move_with(|map, selection| {
11009 if selection.is_empty() {
11010 let cursor = if action.ignore_newlines {
11011 movement::next_word_end(map, selection.head())
11012 } else {
11013 movement::next_word_end_or_newline(map, selection.head())
11014 };
11015 selection.set_head(cursor, SelectionGoal::None);
11016 }
11017 });
11018 });
11019 this.insert("", window, cx);
11020 });
11021 }
11022
11023 pub fn delete_to_next_subword_end(
11024 &mut self,
11025 _: &DeleteToNextSubwordEnd,
11026 window: &mut Window,
11027 cx: &mut Context<Self>,
11028 ) {
11029 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11030 self.transact(window, cx, |this, window, cx| {
11031 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11032 s.move_with(|map, selection| {
11033 if selection.is_empty() {
11034 let cursor = movement::next_subword_end(map, selection.head());
11035 selection.set_head(cursor, SelectionGoal::None);
11036 }
11037 });
11038 });
11039 this.insert("", window, cx);
11040 });
11041 }
11042
11043 pub fn move_to_beginning_of_line(
11044 &mut self,
11045 action: &MoveToBeginningOfLine,
11046 window: &mut Window,
11047 cx: &mut Context<Self>,
11048 ) {
11049 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11050 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11051 s.move_cursors_with(|map, head, _| {
11052 (
11053 movement::indented_line_beginning(
11054 map,
11055 head,
11056 action.stop_at_soft_wraps,
11057 action.stop_at_indent,
11058 ),
11059 SelectionGoal::None,
11060 )
11061 });
11062 })
11063 }
11064
11065 pub fn select_to_beginning_of_line(
11066 &mut self,
11067 action: &SelectToBeginningOfLine,
11068 window: &mut Window,
11069 cx: &mut Context<Self>,
11070 ) {
11071 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11072 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11073 s.move_heads_with(|map, head, _| {
11074 (
11075 movement::indented_line_beginning(
11076 map,
11077 head,
11078 action.stop_at_soft_wraps,
11079 action.stop_at_indent,
11080 ),
11081 SelectionGoal::None,
11082 )
11083 });
11084 });
11085 }
11086
11087 pub fn delete_to_beginning_of_line(
11088 &mut self,
11089 action: &DeleteToBeginningOfLine,
11090 window: &mut Window,
11091 cx: &mut Context<Self>,
11092 ) {
11093 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11094 self.transact(window, cx, |this, window, cx| {
11095 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11096 s.move_with(|_, selection| {
11097 selection.reversed = true;
11098 });
11099 });
11100
11101 this.select_to_beginning_of_line(
11102 &SelectToBeginningOfLine {
11103 stop_at_soft_wraps: false,
11104 stop_at_indent: action.stop_at_indent,
11105 },
11106 window,
11107 cx,
11108 );
11109 this.backspace(&Backspace, window, cx);
11110 });
11111 }
11112
11113 pub fn move_to_end_of_line(
11114 &mut self,
11115 action: &MoveToEndOfLine,
11116 window: &mut Window,
11117 cx: &mut Context<Self>,
11118 ) {
11119 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11120 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11121 s.move_cursors_with(|map, head, _| {
11122 (
11123 movement::line_end(map, head, action.stop_at_soft_wraps),
11124 SelectionGoal::None,
11125 )
11126 });
11127 })
11128 }
11129
11130 pub fn select_to_end_of_line(
11131 &mut self,
11132 action: &SelectToEndOfLine,
11133 window: &mut Window,
11134 cx: &mut Context<Self>,
11135 ) {
11136 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11137 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11138 s.move_heads_with(|map, head, _| {
11139 (
11140 movement::line_end(map, head, action.stop_at_soft_wraps),
11141 SelectionGoal::None,
11142 )
11143 });
11144 })
11145 }
11146
11147 pub fn delete_to_end_of_line(
11148 &mut self,
11149 _: &DeleteToEndOfLine,
11150 window: &mut Window,
11151 cx: &mut Context<Self>,
11152 ) {
11153 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11154 self.transact(window, cx, |this, window, cx| {
11155 this.select_to_end_of_line(
11156 &SelectToEndOfLine {
11157 stop_at_soft_wraps: false,
11158 },
11159 window,
11160 cx,
11161 );
11162 this.delete(&Delete, window, cx);
11163 });
11164 }
11165
11166 pub fn cut_to_end_of_line(
11167 &mut self,
11168 _: &CutToEndOfLine,
11169 window: &mut Window,
11170 cx: &mut Context<Self>,
11171 ) {
11172 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11173 self.transact(window, cx, |this, window, cx| {
11174 this.select_to_end_of_line(
11175 &SelectToEndOfLine {
11176 stop_at_soft_wraps: false,
11177 },
11178 window,
11179 cx,
11180 );
11181 this.cut(&Cut, window, cx);
11182 });
11183 }
11184
11185 pub fn move_to_start_of_paragraph(
11186 &mut self,
11187 _: &MoveToStartOfParagraph,
11188 window: &mut Window,
11189 cx: &mut Context<Self>,
11190 ) {
11191 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11192 cx.propagate();
11193 return;
11194 }
11195 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11196 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11197 s.move_with(|map, selection| {
11198 selection.collapse_to(
11199 movement::start_of_paragraph(map, selection.head(), 1),
11200 SelectionGoal::None,
11201 )
11202 });
11203 })
11204 }
11205
11206 pub fn move_to_end_of_paragraph(
11207 &mut self,
11208 _: &MoveToEndOfParagraph,
11209 window: &mut Window,
11210 cx: &mut Context<Self>,
11211 ) {
11212 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11213 cx.propagate();
11214 return;
11215 }
11216 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11217 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11218 s.move_with(|map, selection| {
11219 selection.collapse_to(
11220 movement::end_of_paragraph(map, selection.head(), 1),
11221 SelectionGoal::None,
11222 )
11223 });
11224 })
11225 }
11226
11227 pub fn select_to_start_of_paragraph(
11228 &mut self,
11229 _: &SelectToStartOfParagraph,
11230 window: &mut Window,
11231 cx: &mut Context<Self>,
11232 ) {
11233 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11234 cx.propagate();
11235 return;
11236 }
11237 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11238 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11239 s.move_heads_with(|map, head, _| {
11240 (
11241 movement::start_of_paragraph(map, head, 1),
11242 SelectionGoal::None,
11243 )
11244 });
11245 })
11246 }
11247
11248 pub fn select_to_end_of_paragraph(
11249 &mut self,
11250 _: &SelectToEndOfParagraph,
11251 window: &mut Window,
11252 cx: &mut Context<Self>,
11253 ) {
11254 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11255 cx.propagate();
11256 return;
11257 }
11258 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11259 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11260 s.move_heads_with(|map, head, _| {
11261 (
11262 movement::end_of_paragraph(map, head, 1),
11263 SelectionGoal::None,
11264 )
11265 });
11266 })
11267 }
11268
11269 pub fn move_to_start_of_excerpt(
11270 &mut self,
11271 _: &MoveToStartOfExcerpt,
11272 window: &mut Window,
11273 cx: &mut Context<Self>,
11274 ) {
11275 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11276 cx.propagate();
11277 return;
11278 }
11279 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11280 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11281 s.move_with(|map, selection| {
11282 selection.collapse_to(
11283 movement::start_of_excerpt(
11284 map,
11285 selection.head(),
11286 workspace::searchable::Direction::Prev,
11287 ),
11288 SelectionGoal::None,
11289 )
11290 });
11291 })
11292 }
11293
11294 pub fn move_to_start_of_next_excerpt(
11295 &mut self,
11296 _: &MoveToStartOfNextExcerpt,
11297 window: &mut Window,
11298 cx: &mut Context<Self>,
11299 ) {
11300 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11301 cx.propagate();
11302 return;
11303 }
11304
11305 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11306 s.move_with(|map, selection| {
11307 selection.collapse_to(
11308 movement::start_of_excerpt(
11309 map,
11310 selection.head(),
11311 workspace::searchable::Direction::Next,
11312 ),
11313 SelectionGoal::None,
11314 )
11315 });
11316 })
11317 }
11318
11319 pub fn move_to_end_of_excerpt(
11320 &mut self,
11321 _: &MoveToEndOfExcerpt,
11322 window: &mut Window,
11323 cx: &mut Context<Self>,
11324 ) {
11325 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11326 cx.propagate();
11327 return;
11328 }
11329 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11330 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11331 s.move_with(|map, selection| {
11332 selection.collapse_to(
11333 movement::end_of_excerpt(
11334 map,
11335 selection.head(),
11336 workspace::searchable::Direction::Next,
11337 ),
11338 SelectionGoal::None,
11339 )
11340 });
11341 })
11342 }
11343
11344 pub fn move_to_end_of_previous_excerpt(
11345 &mut self,
11346 _: &MoveToEndOfPreviousExcerpt,
11347 window: &mut Window,
11348 cx: &mut Context<Self>,
11349 ) {
11350 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11351 cx.propagate();
11352 return;
11353 }
11354 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11355 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11356 s.move_with(|map, selection| {
11357 selection.collapse_to(
11358 movement::end_of_excerpt(
11359 map,
11360 selection.head(),
11361 workspace::searchable::Direction::Prev,
11362 ),
11363 SelectionGoal::None,
11364 )
11365 });
11366 })
11367 }
11368
11369 pub fn select_to_start_of_excerpt(
11370 &mut self,
11371 _: &SelectToStartOfExcerpt,
11372 window: &mut Window,
11373 cx: &mut Context<Self>,
11374 ) {
11375 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11376 cx.propagate();
11377 return;
11378 }
11379 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11380 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11381 s.move_heads_with(|map, head, _| {
11382 (
11383 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11384 SelectionGoal::None,
11385 )
11386 });
11387 })
11388 }
11389
11390 pub fn select_to_start_of_next_excerpt(
11391 &mut self,
11392 _: &SelectToStartOfNextExcerpt,
11393 window: &mut Window,
11394 cx: &mut Context<Self>,
11395 ) {
11396 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11397 cx.propagate();
11398 return;
11399 }
11400 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11401 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11402 s.move_heads_with(|map, head, _| {
11403 (
11404 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11405 SelectionGoal::None,
11406 )
11407 });
11408 })
11409 }
11410
11411 pub fn select_to_end_of_excerpt(
11412 &mut self,
11413 _: &SelectToEndOfExcerpt,
11414 window: &mut Window,
11415 cx: &mut Context<Self>,
11416 ) {
11417 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11418 cx.propagate();
11419 return;
11420 }
11421 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11422 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11423 s.move_heads_with(|map, head, _| {
11424 (
11425 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11426 SelectionGoal::None,
11427 )
11428 });
11429 })
11430 }
11431
11432 pub fn select_to_end_of_previous_excerpt(
11433 &mut self,
11434 _: &SelectToEndOfPreviousExcerpt,
11435 window: &mut Window,
11436 cx: &mut Context<Self>,
11437 ) {
11438 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11439 cx.propagate();
11440 return;
11441 }
11442 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11443 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11444 s.move_heads_with(|map, head, _| {
11445 (
11446 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11447 SelectionGoal::None,
11448 )
11449 });
11450 })
11451 }
11452
11453 pub fn move_to_beginning(
11454 &mut self,
11455 _: &MoveToBeginning,
11456 window: &mut Window,
11457 cx: &mut Context<Self>,
11458 ) {
11459 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11460 cx.propagate();
11461 return;
11462 }
11463 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11464 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11465 s.select_ranges(vec![0..0]);
11466 });
11467 }
11468
11469 pub fn select_to_beginning(
11470 &mut self,
11471 _: &SelectToBeginning,
11472 window: &mut Window,
11473 cx: &mut Context<Self>,
11474 ) {
11475 let mut selection = self.selections.last::<Point>(cx);
11476 selection.set_head(Point::zero(), SelectionGoal::None);
11477 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11478 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11479 s.select(vec![selection]);
11480 });
11481 }
11482
11483 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11484 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11485 cx.propagate();
11486 return;
11487 }
11488 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11489 let cursor = self.buffer.read(cx).read(cx).len();
11490 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11491 s.select_ranges(vec![cursor..cursor])
11492 });
11493 }
11494
11495 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11496 self.nav_history = nav_history;
11497 }
11498
11499 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11500 self.nav_history.as_ref()
11501 }
11502
11503 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11504 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11505 }
11506
11507 fn push_to_nav_history(
11508 &mut self,
11509 cursor_anchor: Anchor,
11510 new_position: Option<Point>,
11511 is_deactivate: bool,
11512 cx: &mut Context<Self>,
11513 ) {
11514 if let Some(nav_history) = self.nav_history.as_mut() {
11515 let buffer = self.buffer.read(cx).read(cx);
11516 let cursor_position = cursor_anchor.to_point(&buffer);
11517 let scroll_state = self.scroll_manager.anchor();
11518 let scroll_top_row = scroll_state.top_row(&buffer);
11519 drop(buffer);
11520
11521 if let Some(new_position) = new_position {
11522 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11523 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11524 return;
11525 }
11526 }
11527
11528 nav_history.push(
11529 Some(NavigationData {
11530 cursor_anchor,
11531 cursor_position,
11532 scroll_anchor: scroll_state,
11533 scroll_top_row,
11534 }),
11535 cx,
11536 );
11537 cx.emit(EditorEvent::PushedToNavHistory {
11538 anchor: cursor_anchor,
11539 is_deactivate,
11540 })
11541 }
11542 }
11543
11544 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11545 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11546 let buffer = self.buffer.read(cx).snapshot(cx);
11547 let mut selection = self.selections.first::<usize>(cx);
11548 selection.set_head(buffer.len(), SelectionGoal::None);
11549 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11550 s.select(vec![selection]);
11551 });
11552 }
11553
11554 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11555 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11556 let end = self.buffer.read(cx).read(cx).len();
11557 self.change_selections(None, window, cx, |s| {
11558 s.select_ranges(vec![0..end]);
11559 });
11560 }
11561
11562 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11563 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11564 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11565 let mut selections = self.selections.all::<Point>(cx);
11566 let max_point = display_map.buffer_snapshot.max_point();
11567 for selection in &mut selections {
11568 let rows = selection.spanned_rows(true, &display_map);
11569 selection.start = Point::new(rows.start.0, 0);
11570 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11571 selection.reversed = false;
11572 }
11573 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11574 s.select(selections);
11575 });
11576 }
11577
11578 pub fn split_selection_into_lines(
11579 &mut self,
11580 _: &SplitSelectionIntoLines,
11581 window: &mut Window,
11582 cx: &mut Context<Self>,
11583 ) {
11584 let selections = self
11585 .selections
11586 .all::<Point>(cx)
11587 .into_iter()
11588 .map(|selection| selection.start..selection.end)
11589 .collect::<Vec<_>>();
11590 self.unfold_ranges(&selections, true, true, cx);
11591
11592 let mut new_selection_ranges = Vec::new();
11593 {
11594 let buffer = self.buffer.read(cx).read(cx);
11595 for selection in selections {
11596 for row in selection.start.row..selection.end.row {
11597 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11598 new_selection_ranges.push(cursor..cursor);
11599 }
11600
11601 let is_multiline_selection = selection.start.row != selection.end.row;
11602 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11603 // so this action feels more ergonomic when paired with other selection operations
11604 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11605 if !should_skip_last {
11606 new_selection_ranges.push(selection.end..selection.end);
11607 }
11608 }
11609 }
11610 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11611 s.select_ranges(new_selection_ranges);
11612 });
11613 }
11614
11615 pub fn add_selection_above(
11616 &mut self,
11617 _: &AddSelectionAbove,
11618 window: &mut Window,
11619 cx: &mut Context<Self>,
11620 ) {
11621 self.add_selection(true, window, cx);
11622 }
11623
11624 pub fn add_selection_below(
11625 &mut self,
11626 _: &AddSelectionBelow,
11627 window: &mut Window,
11628 cx: &mut Context<Self>,
11629 ) {
11630 self.add_selection(false, window, cx);
11631 }
11632
11633 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11634 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11635
11636 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11637 let mut selections = self.selections.all::<Point>(cx);
11638 let text_layout_details = self.text_layout_details(window);
11639 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11640 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11641 let range = oldest_selection.display_range(&display_map).sorted();
11642
11643 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11644 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11645 let positions = start_x.min(end_x)..start_x.max(end_x);
11646
11647 selections.clear();
11648 let mut stack = Vec::new();
11649 for row in range.start.row().0..=range.end.row().0 {
11650 if let Some(selection) = self.selections.build_columnar_selection(
11651 &display_map,
11652 DisplayRow(row),
11653 &positions,
11654 oldest_selection.reversed,
11655 &text_layout_details,
11656 ) {
11657 stack.push(selection.id);
11658 selections.push(selection);
11659 }
11660 }
11661
11662 if above {
11663 stack.reverse();
11664 }
11665
11666 AddSelectionsState { above, stack }
11667 });
11668
11669 let last_added_selection = *state.stack.last().unwrap();
11670 let mut new_selections = Vec::new();
11671 if above == state.above {
11672 let end_row = if above {
11673 DisplayRow(0)
11674 } else {
11675 display_map.max_point().row()
11676 };
11677
11678 'outer: for selection in selections {
11679 if selection.id == last_added_selection {
11680 let range = selection.display_range(&display_map).sorted();
11681 debug_assert_eq!(range.start.row(), range.end.row());
11682 let mut row = range.start.row();
11683 let positions =
11684 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11685 px(start)..px(end)
11686 } else {
11687 let start_x =
11688 display_map.x_for_display_point(range.start, &text_layout_details);
11689 let end_x =
11690 display_map.x_for_display_point(range.end, &text_layout_details);
11691 start_x.min(end_x)..start_x.max(end_x)
11692 };
11693
11694 while row != end_row {
11695 if above {
11696 row.0 -= 1;
11697 } else {
11698 row.0 += 1;
11699 }
11700
11701 if let Some(new_selection) = self.selections.build_columnar_selection(
11702 &display_map,
11703 row,
11704 &positions,
11705 selection.reversed,
11706 &text_layout_details,
11707 ) {
11708 state.stack.push(new_selection.id);
11709 if above {
11710 new_selections.push(new_selection);
11711 new_selections.push(selection);
11712 } else {
11713 new_selections.push(selection);
11714 new_selections.push(new_selection);
11715 }
11716
11717 continue 'outer;
11718 }
11719 }
11720 }
11721
11722 new_selections.push(selection);
11723 }
11724 } else {
11725 new_selections = selections;
11726 new_selections.retain(|s| s.id != last_added_selection);
11727 state.stack.pop();
11728 }
11729
11730 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11731 s.select(new_selections);
11732 });
11733 if state.stack.len() > 1 {
11734 self.add_selections_state = Some(state);
11735 }
11736 }
11737
11738 pub fn select_next_match_internal(
11739 &mut self,
11740 display_map: &DisplaySnapshot,
11741 replace_newest: bool,
11742 autoscroll: Option<Autoscroll>,
11743 window: &mut Window,
11744 cx: &mut Context<Self>,
11745 ) -> Result<()> {
11746 fn select_next_match_ranges(
11747 this: &mut Editor,
11748 range: Range<usize>,
11749 replace_newest: bool,
11750 auto_scroll: Option<Autoscroll>,
11751 window: &mut Window,
11752 cx: &mut Context<Editor>,
11753 ) {
11754 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11755 this.change_selections(auto_scroll, window, cx, |s| {
11756 if replace_newest {
11757 s.delete(s.newest_anchor().id);
11758 }
11759 s.insert_range(range.clone());
11760 });
11761 }
11762
11763 let buffer = &display_map.buffer_snapshot;
11764 let mut selections = self.selections.all::<usize>(cx);
11765 if let Some(mut select_next_state) = self.select_next_state.take() {
11766 let query = &select_next_state.query;
11767 if !select_next_state.done {
11768 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11769 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11770 let mut next_selected_range = None;
11771
11772 let bytes_after_last_selection =
11773 buffer.bytes_in_range(last_selection.end..buffer.len());
11774 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11775 let query_matches = query
11776 .stream_find_iter(bytes_after_last_selection)
11777 .map(|result| (last_selection.end, result))
11778 .chain(
11779 query
11780 .stream_find_iter(bytes_before_first_selection)
11781 .map(|result| (0, result)),
11782 );
11783
11784 for (start_offset, query_match) in query_matches {
11785 let query_match = query_match.unwrap(); // can only fail due to I/O
11786 let offset_range =
11787 start_offset + query_match.start()..start_offset + query_match.end();
11788 let display_range = offset_range.start.to_display_point(display_map)
11789 ..offset_range.end.to_display_point(display_map);
11790
11791 if !select_next_state.wordwise
11792 || (!movement::is_inside_word(display_map, display_range.start)
11793 && !movement::is_inside_word(display_map, display_range.end))
11794 {
11795 // TODO: This is n^2, because we might check all the selections
11796 if !selections
11797 .iter()
11798 .any(|selection| selection.range().overlaps(&offset_range))
11799 {
11800 next_selected_range = Some(offset_range);
11801 break;
11802 }
11803 }
11804 }
11805
11806 if let Some(next_selected_range) = next_selected_range {
11807 select_next_match_ranges(
11808 self,
11809 next_selected_range,
11810 replace_newest,
11811 autoscroll,
11812 window,
11813 cx,
11814 );
11815 } else {
11816 select_next_state.done = true;
11817 }
11818 }
11819
11820 self.select_next_state = Some(select_next_state);
11821 } else {
11822 let mut only_carets = true;
11823 let mut same_text_selected = true;
11824 let mut selected_text = None;
11825
11826 let mut selections_iter = selections.iter().peekable();
11827 while let Some(selection) = selections_iter.next() {
11828 if selection.start != selection.end {
11829 only_carets = false;
11830 }
11831
11832 if same_text_selected {
11833 if selected_text.is_none() {
11834 selected_text =
11835 Some(buffer.text_for_range(selection.range()).collect::<String>());
11836 }
11837
11838 if let Some(next_selection) = selections_iter.peek() {
11839 if next_selection.range().len() == selection.range().len() {
11840 let next_selected_text = buffer
11841 .text_for_range(next_selection.range())
11842 .collect::<String>();
11843 if Some(next_selected_text) != selected_text {
11844 same_text_selected = false;
11845 selected_text = None;
11846 }
11847 } else {
11848 same_text_selected = false;
11849 selected_text = None;
11850 }
11851 }
11852 }
11853 }
11854
11855 if only_carets {
11856 for selection in &mut selections {
11857 let word_range = movement::surrounding_word(
11858 display_map,
11859 selection.start.to_display_point(display_map),
11860 );
11861 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11862 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11863 selection.goal = SelectionGoal::None;
11864 selection.reversed = false;
11865 select_next_match_ranges(
11866 self,
11867 selection.start..selection.end,
11868 replace_newest,
11869 autoscroll,
11870 window,
11871 cx,
11872 );
11873 }
11874
11875 if selections.len() == 1 {
11876 let selection = selections
11877 .last()
11878 .expect("ensured that there's only one selection");
11879 let query = buffer
11880 .text_for_range(selection.start..selection.end)
11881 .collect::<String>();
11882 let is_empty = query.is_empty();
11883 let select_state = SelectNextState {
11884 query: AhoCorasick::new(&[query])?,
11885 wordwise: true,
11886 done: is_empty,
11887 };
11888 self.select_next_state = Some(select_state);
11889 } else {
11890 self.select_next_state = None;
11891 }
11892 } else if let Some(selected_text) = selected_text {
11893 self.select_next_state = Some(SelectNextState {
11894 query: AhoCorasick::new(&[selected_text])?,
11895 wordwise: false,
11896 done: false,
11897 });
11898 self.select_next_match_internal(
11899 display_map,
11900 replace_newest,
11901 autoscroll,
11902 window,
11903 cx,
11904 )?;
11905 }
11906 }
11907 Ok(())
11908 }
11909
11910 pub fn select_all_matches(
11911 &mut self,
11912 _action: &SelectAllMatches,
11913 window: &mut Window,
11914 cx: &mut Context<Self>,
11915 ) -> Result<()> {
11916 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11917
11918 self.push_to_selection_history();
11919 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11920
11921 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11922 let Some(select_next_state) = self.select_next_state.as_mut() else {
11923 return Ok(());
11924 };
11925 if select_next_state.done {
11926 return Ok(());
11927 }
11928
11929 let mut new_selections = Vec::new();
11930
11931 let reversed = self.selections.oldest::<usize>(cx).reversed;
11932 let buffer = &display_map.buffer_snapshot;
11933 let query_matches = select_next_state
11934 .query
11935 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11936
11937 for query_match in query_matches.into_iter() {
11938 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11939 let offset_range = if reversed {
11940 query_match.end()..query_match.start()
11941 } else {
11942 query_match.start()..query_match.end()
11943 };
11944 let display_range = offset_range.start.to_display_point(&display_map)
11945 ..offset_range.end.to_display_point(&display_map);
11946
11947 if !select_next_state.wordwise
11948 || (!movement::is_inside_word(&display_map, display_range.start)
11949 && !movement::is_inside_word(&display_map, display_range.end))
11950 {
11951 new_selections.push(offset_range.start..offset_range.end);
11952 }
11953 }
11954
11955 select_next_state.done = true;
11956 self.unfold_ranges(&new_selections.clone(), false, false, cx);
11957 self.change_selections(None, window, cx, |selections| {
11958 selections.select_ranges(new_selections)
11959 });
11960
11961 Ok(())
11962 }
11963
11964 pub fn select_next(
11965 &mut self,
11966 action: &SelectNext,
11967 window: &mut Window,
11968 cx: &mut Context<Self>,
11969 ) -> Result<()> {
11970 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11971 self.push_to_selection_history();
11972 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11973 self.select_next_match_internal(
11974 &display_map,
11975 action.replace_newest,
11976 Some(Autoscroll::newest()),
11977 window,
11978 cx,
11979 )?;
11980 Ok(())
11981 }
11982
11983 pub fn select_previous(
11984 &mut self,
11985 action: &SelectPrevious,
11986 window: &mut Window,
11987 cx: &mut Context<Self>,
11988 ) -> Result<()> {
11989 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11990 self.push_to_selection_history();
11991 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11992 let buffer = &display_map.buffer_snapshot;
11993 let mut selections = self.selections.all::<usize>(cx);
11994 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11995 let query = &select_prev_state.query;
11996 if !select_prev_state.done {
11997 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11998 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11999 let mut next_selected_range = None;
12000 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12001 let bytes_before_last_selection =
12002 buffer.reversed_bytes_in_range(0..last_selection.start);
12003 let bytes_after_first_selection =
12004 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12005 let query_matches = query
12006 .stream_find_iter(bytes_before_last_selection)
12007 .map(|result| (last_selection.start, result))
12008 .chain(
12009 query
12010 .stream_find_iter(bytes_after_first_selection)
12011 .map(|result| (buffer.len(), result)),
12012 );
12013 for (end_offset, query_match) in query_matches {
12014 let query_match = query_match.unwrap(); // can only fail due to I/O
12015 let offset_range =
12016 end_offset - query_match.end()..end_offset - query_match.start();
12017 let display_range = offset_range.start.to_display_point(&display_map)
12018 ..offset_range.end.to_display_point(&display_map);
12019
12020 if !select_prev_state.wordwise
12021 || (!movement::is_inside_word(&display_map, display_range.start)
12022 && !movement::is_inside_word(&display_map, display_range.end))
12023 {
12024 next_selected_range = Some(offset_range);
12025 break;
12026 }
12027 }
12028
12029 if let Some(next_selected_range) = next_selected_range {
12030 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12031 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12032 if action.replace_newest {
12033 s.delete(s.newest_anchor().id);
12034 }
12035 s.insert_range(next_selected_range);
12036 });
12037 } else {
12038 select_prev_state.done = true;
12039 }
12040 }
12041
12042 self.select_prev_state = Some(select_prev_state);
12043 } else {
12044 let mut only_carets = true;
12045 let mut same_text_selected = true;
12046 let mut selected_text = None;
12047
12048 let mut selections_iter = selections.iter().peekable();
12049 while let Some(selection) = selections_iter.next() {
12050 if selection.start != selection.end {
12051 only_carets = false;
12052 }
12053
12054 if same_text_selected {
12055 if selected_text.is_none() {
12056 selected_text =
12057 Some(buffer.text_for_range(selection.range()).collect::<String>());
12058 }
12059
12060 if let Some(next_selection) = selections_iter.peek() {
12061 if next_selection.range().len() == selection.range().len() {
12062 let next_selected_text = buffer
12063 .text_for_range(next_selection.range())
12064 .collect::<String>();
12065 if Some(next_selected_text) != selected_text {
12066 same_text_selected = false;
12067 selected_text = None;
12068 }
12069 } else {
12070 same_text_selected = false;
12071 selected_text = None;
12072 }
12073 }
12074 }
12075 }
12076
12077 if only_carets {
12078 for selection in &mut selections {
12079 let word_range = movement::surrounding_word(
12080 &display_map,
12081 selection.start.to_display_point(&display_map),
12082 );
12083 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12084 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12085 selection.goal = SelectionGoal::None;
12086 selection.reversed = false;
12087 }
12088 if selections.len() == 1 {
12089 let selection = selections
12090 .last()
12091 .expect("ensured that there's only one selection");
12092 let query = buffer
12093 .text_for_range(selection.start..selection.end)
12094 .collect::<String>();
12095 let is_empty = query.is_empty();
12096 let select_state = SelectNextState {
12097 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12098 wordwise: true,
12099 done: is_empty,
12100 };
12101 self.select_prev_state = Some(select_state);
12102 } else {
12103 self.select_prev_state = None;
12104 }
12105
12106 self.unfold_ranges(
12107 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12108 false,
12109 true,
12110 cx,
12111 );
12112 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12113 s.select(selections);
12114 });
12115 } else if let Some(selected_text) = selected_text {
12116 self.select_prev_state = Some(SelectNextState {
12117 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12118 wordwise: false,
12119 done: false,
12120 });
12121 self.select_previous(action, window, cx)?;
12122 }
12123 }
12124 Ok(())
12125 }
12126
12127 pub fn find_next_match(
12128 &mut self,
12129 _: &FindNextMatch,
12130 window: &mut Window,
12131 cx: &mut Context<Self>,
12132 ) -> Result<()> {
12133 let selections = self.selections.disjoint_anchors();
12134 match selections.first() {
12135 Some(first) if selections.len() >= 2 => {
12136 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12137 s.select_ranges([first.range()]);
12138 });
12139 }
12140 _ => self.select_next(
12141 &SelectNext {
12142 replace_newest: true,
12143 },
12144 window,
12145 cx,
12146 )?,
12147 }
12148 Ok(())
12149 }
12150
12151 pub fn find_previous_match(
12152 &mut self,
12153 _: &FindPreviousMatch,
12154 window: &mut Window,
12155 cx: &mut Context<Self>,
12156 ) -> Result<()> {
12157 let selections = self.selections.disjoint_anchors();
12158 match selections.last() {
12159 Some(last) if selections.len() >= 2 => {
12160 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12161 s.select_ranges([last.range()]);
12162 });
12163 }
12164 _ => self.select_previous(
12165 &SelectPrevious {
12166 replace_newest: true,
12167 },
12168 window,
12169 cx,
12170 )?,
12171 }
12172 Ok(())
12173 }
12174
12175 pub fn toggle_comments(
12176 &mut self,
12177 action: &ToggleComments,
12178 window: &mut Window,
12179 cx: &mut Context<Self>,
12180 ) {
12181 if self.read_only(cx) {
12182 return;
12183 }
12184 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12185 let text_layout_details = &self.text_layout_details(window);
12186 self.transact(window, cx, |this, window, cx| {
12187 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12188 let mut edits = Vec::new();
12189 let mut selection_edit_ranges = Vec::new();
12190 let mut last_toggled_row = None;
12191 let snapshot = this.buffer.read(cx).read(cx);
12192 let empty_str: Arc<str> = Arc::default();
12193 let mut suffixes_inserted = Vec::new();
12194 let ignore_indent = action.ignore_indent;
12195
12196 fn comment_prefix_range(
12197 snapshot: &MultiBufferSnapshot,
12198 row: MultiBufferRow,
12199 comment_prefix: &str,
12200 comment_prefix_whitespace: &str,
12201 ignore_indent: bool,
12202 ) -> Range<Point> {
12203 let indent_size = if ignore_indent {
12204 0
12205 } else {
12206 snapshot.indent_size_for_line(row).len
12207 };
12208
12209 let start = Point::new(row.0, indent_size);
12210
12211 let mut line_bytes = snapshot
12212 .bytes_in_range(start..snapshot.max_point())
12213 .flatten()
12214 .copied();
12215
12216 // If this line currently begins with the line comment prefix, then record
12217 // the range containing the prefix.
12218 if line_bytes
12219 .by_ref()
12220 .take(comment_prefix.len())
12221 .eq(comment_prefix.bytes())
12222 {
12223 // Include any whitespace that matches the comment prefix.
12224 let matching_whitespace_len = line_bytes
12225 .zip(comment_prefix_whitespace.bytes())
12226 .take_while(|(a, b)| a == b)
12227 .count() as u32;
12228 let end = Point::new(
12229 start.row,
12230 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12231 );
12232 start..end
12233 } else {
12234 start..start
12235 }
12236 }
12237
12238 fn comment_suffix_range(
12239 snapshot: &MultiBufferSnapshot,
12240 row: MultiBufferRow,
12241 comment_suffix: &str,
12242 comment_suffix_has_leading_space: bool,
12243 ) -> Range<Point> {
12244 let end = Point::new(row.0, snapshot.line_len(row));
12245 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12246
12247 let mut line_end_bytes = snapshot
12248 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12249 .flatten()
12250 .copied();
12251
12252 let leading_space_len = if suffix_start_column > 0
12253 && line_end_bytes.next() == Some(b' ')
12254 && comment_suffix_has_leading_space
12255 {
12256 1
12257 } else {
12258 0
12259 };
12260
12261 // If this line currently begins with the line comment prefix, then record
12262 // the range containing the prefix.
12263 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12264 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12265 start..end
12266 } else {
12267 end..end
12268 }
12269 }
12270
12271 // TODO: Handle selections that cross excerpts
12272 for selection in &mut selections {
12273 let start_column = snapshot
12274 .indent_size_for_line(MultiBufferRow(selection.start.row))
12275 .len;
12276 let language = if let Some(language) =
12277 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12278 {
12279 language
12280 } else {
12281 continue;
12282 };
12283
12284 selection_edit_ranges.clear();
12285
12286 // If multiple selections contain a given row, avoid processing that
12287 // row more than once.
12288 let mut start_row = MultiBufferRow(selection.start.row);
12289 if last_toggled_row == Some(start_row) {
12290 start_row = start_row.next_row();
12291 }
12292 let end_row =
12293 if selection.end.row > selection.start.row && selection.end.column == 0 {
12294 MultiBufferRow(selection.end.row - 1)
12295 } else {
12296 MultiBufferRow(selection.end.row)
12297 };
12298 last_toggled_row = Some(end_row);
12299
12300 if start_row > end_row {
12301 continue;
12302 }
12303
12304 // If the language has line comments, toggle those.
12305 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12306
12307 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12308 if ignore_indent {
12309 full_comment_prefixes = full_comment_prefixes
12310 .into_iter()
12311 .map(|s| Arc::from(s.trim_end()))
12312 .collect();
12313 }
12314
12315 if !full_comment_prefixes.is_empty() {
12316 let first_prefix = full_comment_prefixes
12317 .first()
12318 .expect("prefixes is non-empty");
12319 let prefix_trimmed_lengths = full_comment_prefixes
12320 .iter()
12321 .map(|p| p.trim_end_matches(' ').len())
12322 .collect::<SmallVec<[usize; 4]>>();
12323
12324 let mut all_selection_lines_are_comments = true;
12325
12326 for row in start_row.0..=end_row.0 {
12327 let row = MultiBufferRow(row);
12328 if start_row < end_row && snapshot.is_line_blank(row) {
12329 continue;
12330 }
12331
12332 let prefix_range = full_comment_prefixes
12333 .iter()
12334 .zip(prefix_trimmed_lengths.iter().copied())
12335 .map(|(prefix, trimmed_prefix_len)| {
12336 comment_prefix_range(
12337 snapshot.deref(),
12338 row,
12339 &prefix[..trimmed_prefix_len],
12340 &prefix[trimmed_prefix_len..],
12341 ignore_indent,
12342 )
12343 })
12344 .max_by_key(|range| range.end.column - range.start.column)
12345 .expect("prefixes is non-empty");
12346
12347 if prefix_range.is_empty() {
12348 all_selection_lines_are_comments = false;
12349 }
12350
12351 selection_edit_ranges.push(prefix_range);
12352 }
12353
12354 if all_selection_lines_are_comments {
12355 edits.extend(
12356 selection_edit_ranges
12357 .iter()
12358 .cloned()
12359 .map(|range| (range, empty_str.clone())),
12360 );
12361 } else {
12362 let min_column = selection_edit_ranges
12363 .iter()
12364 .map(|range| range.start.column)
12365 .min()
12366 .unwrap_or(0);
12367 edits.extend(selection_edit_ranges.iter().map(|range| {
12368 let position = Point::new(range.start.row, min_column);
12369 (position..position, first_prefix.clone())
12370 }));
12371 }
12372 } else if let Some((full_comment_prefix, comment_suffix)) =
12373 language.block_comment_delimiters()
12374 {
12375 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12376 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12377 let prefix_range = comment_prefix_range(
12378 snapshot.deref(),
12379 start_row,
12380 comment_prefix,
12381 comment_prefix_whitespace,
12382 ignore_indent,
12383 );
12384 let suffix_range = comment_suffix_range(
12385 snapshot.deref(),
12386 end_row,
12387 comment_suffix.trim_start_matches(' '),
12388 comment_suffix.starts_with(' '),
12389 );
12390
12391 if prefix_range.is_empty() || suffix_range.is_empty() {
12392 edits.push((
12393 prefix_range.start..prefix_range.start,
12394 full_comment_prefix.clone(),
12395 ));
12396 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12397 suffixes_inserted.push((end_row, comment_suffix.len()));
12398 } else {
12399 edits.push((prefix_range, empty_str.clone()));
12400 edits.push((suffix_range, empty_str.clone()));
12401 }
12402 } else {
12403 continue;
12404 }
12405 }
12406
12407 drop(snapshot);
12408 this.buffer.update(cx, |buffer, cx| {
12409 buffer.edit(edits, None, cx);
12410 });
12411
12412 // Adjust selections so that they end before any comment suffixes that
12413 // were inserted.
12414 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12415 let mut selections = this.selections.all::<Point>(cx);
12416 let snapshot = this.buffer.read(cx).read(cx);
12417 for selection in &mut selections {
12418 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12419 match row.cmp(&MultiBufferRow(selection.end.row)) {
12420 Ordering::Less => {
12421 suffixes_inserted.next();
12422 continue;
12423 }
12424 Ordering::Greater => break,
12425 Ordering::Equal => {
12426 if selection.end.column == snapshot.line_len(row) {
12427 if selection.is_empty() {
12428 selection.start.column -= suffix_len as u32;
12429 }
12430 selection.end.column -= suffix_len as u32;
12431 }
12432 break;
12433 }
12434 }
12435 }
12436 }
12437
12438 drop(snapshot);
12439 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12440 s.select(selections)
12441 });
12442
12443 let selections = this.selections.all::<Point>(cx);
12444 let selections_on_single_row = selections.windows(2).all(|selections| {
12445 selections[0].start.row == selections[1].start.row
12446 && selections[0].end.row == selections[1].end.row
12447 && selections[0].start.row == selections[0].end.row
12448 });
12449 let selections_selecting = selections
12450 .iter()
12451 .any(|selection| selection.start != selection.end);
12452 let advance_downwards = action.advance_downwards
12453 && selections_on_single_row
12454 && !selections_selecting
12455 && !matches!(this.mode, EditorMode::SingleLine { .. });
12456
12457 if advance_downwards {
12458 let snapshot = this.buffer.read(cx).snapshot(cx);
12459
12460 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12461 s.move_cursors_with(|display_snapshot, display_point, _| {
12462 let mut point = display_point.to_point(display_snapshot);
12463 point.row += 1;
12464 point = snapshot.clip_point(point, Bias::Left);
12465 let display_point = point.to_display_point(display_snapshot);
12466 let goal = SelectionGoal::HorizontalPosition(
12467 display_snapshot
12468 .x_for_display_point(display_point, text_layout_details)
12469 .into(),
12470 );
12471 (display_point, goal)
12472 })
12473 });
12474 }
12475 });
12476 }
12477
12478 pub fn select_enclosing_symbol(
12479 &mut self,
12480 _: &SelectEnclosingSymbol,
12481 window: &mut Window,
12482 cx: &mut Context<Self>,
12483 ) {
12484 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12485
12486 let buffer = self.buffer.read(cx).snapshot(cx);
12487 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12488
12489 fn update_selection(
12490 selection: &Selection<usize>,
12491 buffer_snap: &MultiBufferSnapshot,
12492 ) -> Option<Selection<usize>> {
12493 let cursor = selection.head();
12494 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12495 for symbol in symbols.iter().rev() {
12496 let start = symbol.range.start.to_offset(buffer_snap);
12497 let end = symbol.range.end.to_offset(buffer_snap);
12498 let new_range = start..end;
12499 if start < selection.start || end > selection.end {
12500 return Some(Selection {
12501 id: selection.id,
12502 start: new_range.start,
12503 end: new_range.end,
12504 goal: SelectionGoal::None,
12505 reversed: selection.reversed,
12506 });
12507 }
12508 }
12509 None
12510 }
12511
12512 let mut selected_larger_symbol = false;
12513 let new_selections = old_selections
12514 .iter()
12515 .map(|selection| match update_selection(selection, &buffer) {
12516 Some(new_selection) => {
12517 if new_selection.range() != selection.range() {
12518 selected_larger_symbol = true;
12519 }
12520 new_selection
12521 }
12522 None => selection.clone(),
12523 })
12524 .collect::<Vec<_>>();
12525
12526 if selected_larger_symbol {
12527 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12528 s.select(new_selections);
12529 });
12530 }
12531 }
12532
12533 pub fn select_larger_syntax_node(
12534 &mut self,
12535 _: &SelectLargerSyntaxNode,
12536 window: &mut Window,
12537 cx: &mut Context<Self>,
12538 ) {
12539 let Some(visible_row_count) = self.visible_row_count() else {
12540 return;
12541 };
12542 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12543 if old_selections.is_empty() {
12544 return;
12545 }
12546
12547 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12548
12549 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12550 let buffer = self.buffer.read(cx).snapshot(cx);
12551
12552 let mut selected_larger_node = false;
12553 let mut new_selections = old_selections
12554 .iter()
12555 .map(|selection| {
12556 let old_range = selection.start..selection.end;
12557
12558 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12559 // manually select word at selection
12560 if ["string_content", "inline"].contains(&node.kind()) {
12561 let word_range = {
12562 let display_point = buffer
12563 .offset_to_point(old_range.start)
12564 .to_display_point(&display_map);
12565 let Range { start, end } =
12566 movement::surrounding_word(&display_map, display_point);
12567 start.to_point(&display_map).to_offset(&buffer)
12568 ..end.to_point(&display_map).to_offset(&buffer)
12569 };
12570 // ignore if word is already selected
12571 if !word_range.is_empty() && old_range != word_range {
12572 let last_word_range = {
12573 let display_point = buffer
12574 .offset_to_point(old_range.end)
12575 .to_display_point(&display_map);
12576 let Range { start, end } =
12577 movement::surrounding_word(&display_map, display_point);
12578 start.to_point(&display_map).to_offset(&buffer)
12579 ..end.to_point(&display_map).to_offset(&buffer)
12580 };
12581 // only select word if start and end point belongs to same word
12582 if word_range == last_word_range {
12583 selected_larger_node = true;
12584 return Selection {
12585 id: selection.id,
12586 start: word_range.start,
12587 end: word_range.end,
12588 goal: SelectionGoal::None,
12589 reversed: selection.reversed,
12590 };
12591 }
12592 }
12593 }
12594 }
12595
12596 let mut new_range = old_range.clone();
12597 let mut new_node = None;
12598 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12599 {
12600 new_node = Some(node);
12601 new_range = match containing_range {
12602 MultiOrSingleBufferOffsetRange::Single(_) => break,
12603 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12604 };
12605 if !display_map.intersects_fold(new_range.start)
12606 && !display_map.intersects_fold(new_range.end)
12607 {
12608 break;
12609 }
12610 }
12611
12612 if let Some(node) = new_node {
12613 // Log the ancestor, to support using this action as a way to explore TreeSitter
12614 // nodes. Parent and grandparent are also logged because this operation will not
12615 // visit nodes that have the same range as their parent.
12616 log::info!("Node: {node:?}");
12617 let parent = node.parent();
12618 log::info!("Parent: {parent:?}");
12619 let grandparent = parent.and_then(|x| x.parent());
12620 log::info!("Grandparent: {grandparent:?}");
12621 }
12622
12623 selected_larger_node |= new_range != old_range;
12624 Selection {
12625 id: selection.id,
12626 start: new_range.start,
12627 end: new_range.end,
12628 goal: SelectionGoal::None,
12629 reversed: selection.reversed,
12630 }
12631 })
12632 .collect::<Vec<_>>();
12633
12634 if !selected_larger_node {
12635 return; // don't put this call in the history
12636 }
12637
12638 // scroll based on transformation done to the last selection created by the user
12639 let (last_old, last_new) = old_selections
12640 .last()
12641 .zip(new_selections.last().cloned())
12642 .expect("old_selections isn't empty");
12643
12644 // revert selection
12645 let is_selection_reversed = {
12646 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12647 new_selections.last_mut().expect("checked above").reversed =
12648 should_newest_selection_be_reversed;
12649 should_newest_selection_be_reversed
12650 };
12651
12652 if selected_larger_node {
12653 self.select_syntax_node_history.disable_clearing = true;
12654 self.change_selections(None, window, cx, |s| {
12655 s.select(new_selections.clone());
12656 });
12657 self.select_syntax_node_history.disable_clearing = false;
12658 }
12659
12660 let start_row = last_new.start.to_display_point(&display_map).row().0;
12661 let end_row = last_new.end.to_display_point(&display_map).row().0;
12662 let selection_height = end_row - start_row + 1;
12663 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12664
12665 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12666 let scroll_behavior = if fits_on_the_screen {
12667 self.request_autoscroll(Autoscroll::fit(), cx);
12668 SelectSyntaxNodeScrollBehavior::FitSelection
12669 } else if is_selection_reversed {
12670 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12671 SelectSyntaxNodeScrollBehavior::CursorTop
12672 } else {
12673 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12674 SelectSyntaxNodeScrollBehavior::CursorBottom
12675 };
12676
12677 self.select_syntax_node_history.push((
12678 old_selections,
12679 scroll_behavior,
12680 is_selection_reversed,
12681 ));
12682 }
12683
12684 pub fn select_smaller_syntax_node(
12685 &mut self,
12686 _: &SelectSmallerSyntaxNode,
12687 window: &mut Window,
12688 cx: &mut Context<Self>,
12689 ) {
12690 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12691
12692 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12693 self.select_syntax_node_history.pop()
12694 {
12695 if let Some(selection) = selections.last_mut() {
12696 selection.reversed = is_selection_reversed;
12697 }
12698
12699 self.select_syntax_node_history.disable_clearing = true;
12700 self.change_selections(None, window, cx, |s| {
12701 s.select(selections.to_vec());
12702 });
12703 self.select_syntax_node_history.disable_clearing = false;
12704
12705 match scroll_behavior {
12706 SelectSyntaxNodeScrollBehavior::CursorTop => {
12707 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12708 }
12709 SelectSyntaxNodeScrollBehavior::FitSelection => {
12710 self.request_autoscroll(Autoscroll::fit(), cx);
12711 }
12712 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12713 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12714 }
12715 }
12716 }
12717 }
12718
12719 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12720 if !EditorSettings::get_global(cx).gutter.runnables {
12721 self.clear_tasks();
12722 return Task::ready(());
12723 }
12724 let project = self.project.as_ref().map(Entity::downgrade);
12725 let task_sources = self.lsp_task_sources(cx);
12726 cx.spawn_in(window, async move |editor, cx| {
12727 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12728 let Some(project) = project.and_then(|p| p.upgrade()) else {
12729 return;
12730 };
12731 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12732 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12733 }) else {
12734 return;
12735 };
12736
12737 let hide_runnables = project
12738 .update(cx, |project, cx| {
12739 // Do not display any test indicators in non-dev server remote projects.
12740 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12741 })
12742 .unwrap_or(true);
12743 if hide_runnables {
12744 return;
12745 }
12746 let new_rows =
12747 cx.background_spawn({
12748 let snapshot = display_snapshot.clone();
12749 async move {
12750 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12751 }
12752 })
12753 .await;
12754 let Ok(lsp_tasks) =
12755 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12756 else {
12757 return;
12758 };
12759 let lsp_tasks = lsp_tasks.await;
12760
12761 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12762 lsp_tasks
12763 .into_iter()
12764 .flat_map(|(kind, tasks)| {
12765 tasks.into_iter().filter_map(move |(location, task)| {
12766 Some((kind.clone(), location?, task))
12767 })
12768 })
12769 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12770 let buffer = location.target.buffer;
12771 let buffer_snapshot = buffer.read(cx).snapshot();
12772 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12773 |(excerpt_id, snapshot, _)| {
12774 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12775 display_snapshot
12776 .buffer_snapshot
12777 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12778 } else {
12779 None
12780 }
12781 },
12782 );
12783 if let Some(offset) = offset {
12784 let task_buffer_range =
12785 location.target.range.to_point(&buffer_snapshot);
12786 let context_buffer_range =
12787 task_buffer_range.to_offset(&buffer_snapshot);
12788 let context_range = BufferOffset(context_buffer_range.start)
12789 ..BufferOffset(context_buffer_range.end);
12790
12791 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12792 .or_insert_with(|| RunnableTasks {
12793 templates: Vec::new(),
12794 offset,
12795 column: task_buffer_range.start.column,
12796 extra_variables: HashMap::default(),
12797 context_range,
12798 })
12799 .templates
12800 .push((kind, task.original_task().clone()));
12801 }
12802
12803 acc
12804 })
12805 }) else {
12806 return;
12807 };
12808
12809 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12810 editor
12811 .update(cx, |editor, _| {
12812 editor.clear_tasks();
12813 for (key, mut value) in rows {
12814 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12815 value.templates.extend(lsp_tasks.templates);
12816 }
12817
12818 editor.insert_tasks(key, value);
12819 }
12820 for (key, value) in lsp_tasks_by_rows {
12821 editor.insert_tasks(key, value);
12822 }
12823 })
12824 .ok();
12825 })
12826 }
12827 fn fetch_runnable_ranges(
12828 snapshot: &DisplaySnapshot,
12829 range: Range<Anchor>,
12830 ) -> Vec<language::RunnableRange> {
12831 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12832 }
12833
12834 fn runnable_rows(
12835 project: Entity<Project>,
12836 snapshot: DisplaySnapshot,
12837 runnable_ranges: Vec<RunnableRange>,
12838 mut cx: AsyncWindowContext,
12839 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12840 runnable_ranges
12841 .into_iter()
12842 .filter_map(|mut runnable| {
12843 let tasks = cx
12844 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12845 .ok()?;
12846 if tasks.is_empty() {
12847 return None;
12848 }
12849
12850 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12851
12852 let row = snapshot
12853 .buffer_snapshot
12854 .buffer_line_for_row(MultiBufferRow(point.row))?
12855 .1
12856 .start
12857 .row;
12858
12859 let context_range =
12860 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12861 Some((
12862 (runnable.buffer_id, row),
12863 RunnableTasks {
12864 templates: tasks,
12865 offset: snapshot
12866 .buffer_snapshot
12867 .anchor_before(runnable.run_range.start),
12868 context_range,
12869 column: point.column,
12870 extra_variables: runnable.extra_captures,
12871 },
12872 ))
12873 })
12874 .collect()
12875 }
12876
12877 fn templates_with_tags(
12878 project: &Entity<Project>,
12879 runnable: &mut Runnable,
12880 cx: &mut App,
12881 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12882 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12883 let (worktree_id, file) = project
12884 .buffer_for_id(runnable.buffer, cx)
12885 .and_then(|buffer| buffer.read(cx).file())
12886 .map(|file| (file.worktree_id(cx), file.clone()))
12887 .unzip();
12888
12889 (
12890 project.task_store().read(cx).task_inventory().cloned(),
12891 worktree_id,
12892 file,
12893 )
12894 });
12895
12896 let mut templates_with_tags = mem::take(&mut runnable.tags)
12897 .into_iter()
12898 .flat_map(|RunnableTag(tag)| {
12899 inventory
12900 .as_ref()
12901 .into_iter()
12902 .flat_map(|inventory| {
12903 inventory.read(cx).list_tasks(
12904 file.clone(),
12905 Some(runnable.language.clone()),
12906 worktree_id,
12907 cx,
12908 )
12909 })
12910 .filter(move |(_, template)| {
12911 template.tags.iter().any(|source_tag| source_tag == &tag)
12912 })
12913 })
12914 .sorted_by_key(|(kind, _)| kind.to_owned())
12915 .collect::<Vec<_>>();
12916 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12917 // Strongest source wins; if we have worktree tag binding, prefer that to
12918 // global and language bindings;
12919 // if we have a global binding, prefer that to language binding.
12920 let first_mismatch = templates_with_tags
12921 .iter()
12922 .position(|(tag_source, _)| tag_source != leading_tag_source);
12923 if let Some(index) = first_mismatch {
12924 templates_with_tags.truncate(index);
12925 }
12926 }
12927
12928 templates_with_tags
12929 }
12930
12931 pub fn move_to_enclosing_bracket(
12932 &mut self,
12933 _: &MoveToEnclosingBracket,
12934 window: &mut Window,
12935 cx: &mut Context<Self>,
12936 ) {
12937 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12938 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12939 s.move_offsets_with(|snapshot, selection| {
12940 let Some(enclosing_bracket_ranges) =
12941 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12942 else {
12943 return;
12944 };
12945
12946 let mut best_length = usize::MAX;
12947 let mut best_inside = false;
12948 let mut best_in_bracket_range = false;
12949 let mut best_destination = None;
12950 for (open, close) in enclosing_bracket_ranges {
12951 let close = close.to_inclusive();
12952 let length = close.end() - open.start;
12953 let inside = selection.start >= open.end && selection.end <= *close.start();
12954 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12955 || close.contains(&selection.head());
12956
12957 // If best is next to a bracket and current isn't, skip
12958 if !in_bracket_range && best_in_bracket_range {
12959 continue;
12960 }
12961
12962 // Prefer smaller lengths unless best is inside and current isn't
12963 if length > best_length && (best_inside || !inside) {
12964 continue;
12965 }
12966
12967 best_length = length;
12968 best_inside = inside;
12969 best_in_bracket_range = in_bracket_range;
12970 best_destination = Some(
12971 if close.contains(&selection.start) && close.contains(&selection.end) {
12972 if inside { open.end } else { open.start }
12973 } else if inside {
12974 *close.start()
12975 } else {
12976 *close.end()
12977 },
12978 );
12979 }
12980
12981 if let Some(destination) = best_destination {
12982 selection.collapse_to(destination, SelectionGoal::None);
12983 }
12984 })
12985 });
12986 }
12987
12988 pub fn undo_selection(
12989 &mut self,
12990 _: &UndoSelection,
12991 window: &mut Window,
12992 cx: &mut Context<Self>,
12993 ) {
12994 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12995 self.end_selection(window, cx);
12996 self.selection_history.mode = SelectionHistoryMode::Undoing;
12997 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12998 self.change_selections(None, window, cx, |s| {
12999 s.select_anchors(entry.selections.to_vec())
13000 });
13001 self.select_next_state = entry.select_next_state;
13002 self.select_prev_state = entry.select_prev_state;
13003 self.add_selections_state = entry.add_selections_state;
13004 self.request_autoscroll(Autoscroll::newest(), cx);
13005 }
13006 self.selection_history.mode = SelectionHistoryMode::Normal;
13007 }
13008
13009 pub fn redo_selection(
13010 &mut self,
13011 _: &RedoSelection,
13012 window: &mut Window,
13013 cx: &mut Context<Self>,
13014 ) {
13015 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13016 self.end_selection(window, cx);
13017 self.selection_history.mode = SelectionHistoryMode::Redoing;
13018 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13019 self.change_selections(None, window, cx, |s| {
13020 s.select_anchors(entry.selections.to_vec())
13021 });
13022 self.select_next_state = entry.select_next_state;
13023 self.select_prev_state = entry.select_prev_state;
13024 self.add_selections_state = entry.add_selections_state;
13025 self.request_autoscroll(Autoscroll::newest(), cx);
13026 }
13027 self.selection_history.mode = SelectionHistoryMode::Normal;
13028 }
13029
13030 pub fn expand_excerpts(
13031 &mut self,
13032 action: &ExpandExcerpts,
13033 _: &mut Window,
13034 cx: &mut Context<Self>,
13035 ) {
13036 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13037 }
13038
13039 pub fn expand_excerpts_down(
13040 &mut self,
13041 action: &ExpandExcerptsDown,
13042 _: &mut Window,
13043 cx: &mut Context<Self>,
13044 ) {
13045 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13046 }
13047
13048 pub fn expand_excerpts_up(
13049 &mut self,
13050 action: &ExpandExcerptsUp,
13051 _: &mut Window,
13052 cx: &mut Context<Self>,
13053 ) {
13054 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13055 }
13056
13057 pub fn expand_excerpts_for_direction(
13058 &mut self,
13059 lines: u32,
13060 direction: ExpandExcerptDirection,
13061
13062 cx: &mut Context<Self>,
13063 ) {
13064 let selections = self.selections.disjoint_anchors();
13065
13066 let lines = if lines == 0 {
13067 EditorSettings::get_global(cx).expand_excerpt_lines
13068 } else {
13069 lines
13070 };
13071
13072 self.buffer.update(cx, |buffer, cx| {
13073 let snapshot = buffer.snapshot(cx);
13074 let mut excerpt_ids = selections
13075 .iter()
13076 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13077 .collect::<Vec<_>>();
13078 excerpt_ids.sort();
13079 excerpt_ids.dedup();
13080 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13081 })
13082 }
13083
13084 pub fn expand_excerpt(
13085 &mut self,
13086 excerpt: ExcerptId,
13087 direction: ExpandExcerptDirection,
13088 window: &mut Window,
13089 cx: &mut Context<Self>,
13090 ) {
13091 let current_scroll_position = self.scroll_position(cx);
13092 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13093 let mut should_scroll_up = false;
13094
13095 if direction == ExpandExcerptDirection::Down {
13096 let multi_buffer = self.buffer.read(cx);
13097 let snapshot = multi_buffer.snapshot(cx);
13098 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13099 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13100 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13101 let buffer_snapshot = buffer.read(cx).snapshot();
13102 let excerpt_end_row =
13103 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13104 let last_row = buffer_snapshot.max_point().row;
13105 let lines_below = last_row.saturating_sub(excerpt_end_row);
13106 should_scroll_up = lines_below >= lines_to_expand;
13107 }
13108 }
13109 }
13110 }
13111
13112 self.buffer.update(cx, |buffer, cx| {
13113 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13114 });
13115
13116 if should_scroll_up {
13117 let new_scroll_position =
13118 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13119 self.set_scroll_position(new_scroll_position, window, cx);
13120 }
13121 }
13122
13123 pub fn go_to_singleton_buffer_point(
13124 &mut self,
13125 point: Point,
13126 window: &mut Window,
13127 cx: &mut Context<Self>,
13128 ) {
13129 self.go_to_singleton_buffer_range(point..point, window, cx);
13130 }
13131
13132 pub fn go_to_singleton_buffer_range(
13133 &mut self,
13134 range: Range<Point>,
13135 window: &mut Window,
13136 cx: &mut Context<Self>,
13137 ) {
13138 let multibuffer = self.buffer().read(cx);
13139 let Some(buffer) = multibuffer.as_singleton() else {
13140 return;
13141 };
13142 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13143 return;
13144 };
13145 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13146 return;
13147 };
13148 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13149 s.select_anchor_ranges([start..end])
13150 });
13151 }
13152
13153 pub fn go_to_diagnostic(
13154 &mut self,
13155 _: &GoToDiagnostic,
13156 window: &mut Window,
13157 cx: &mut Context<Self>,
13158 ) {
13159 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13160 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13161 }
13162
13163 pub fn go_to_prev_diagnostic(
13164 &mut self,
13165 _: &GoToPreviousDiagnostic,
13166 window: &mut Window,
13167 cx: &mut Context<Self>,
13168 ) {
13169 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13170 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13171 }
13172
13173 pub fn go_to_diagnostic_impl(
13174 &mut self,
13175 direction: Direction,
13176 window: &mut Window,
13177 cx: &mut Context<Self>,
13178 ) {
13179 let buffer = self.buffer.read(cx).snapshot(cx);
13180 let selection = self.selections.newest::<usize>(cx);
13181
13182 let mut active_group_id = None;
13183 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13184 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13185 active_group_id = Some(active_group.group_id);
13186 }
13187 }
13188
13189 fn filtered(
13190 snapshot: EditorSnapshot,
13191 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13192 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13193 diagnostics
13194 .filter(|entry| entry.range.start != entry.range.end)
13195 .filter(|entry| !entry.diagnostic.is_unnecessary)
13196 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13197 }
13198
13199 let snapshot = self.snapshot(window, cx);
13200 let before = filtered(
13201 snapshot.clone(),
13202 buffer
13203 .diagnostics_in_range(0..selection.start)
13204 .filter(|entry| entry.range.start <= selection.start),
13205 );
13206 let after = filtered(
13207 snapshot,
13208 buffer
13209 .diagnostics_in_range(selection.start..buffer.len())
13210 .filter(|entry| entry.range.start >= selection.start),
13211 );
13212
13213 let mut found: Option<DiagnosticEntry<usize>> = None;
13214 if direction == Direction::Prev {
13215 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13216 {
13217 for diagnostic in prev_diagnostics.into_iter().rev() {
13218 if diagnostic.range.start != selection.start
13219 || active_group_id
13220 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13221 {
13222 found = Some(diagnostic);
13223 break 'outer;
13224 }
13225 }
13226 }
13227 } else {
13228 for diagnostic in after.chain(before) {
13229 if diagnostic.range.start != selection.start
13230 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13231 {
13232 found = Some(diagnostic);
13233 break;
13234 }
13235 }
13236 }
13237 let Some(next_diagnostic) = found else {
13238 return;
13239 };
13240
13241 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13242 return;
13243 };
13244 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13245 s.select_ranges(vec![
13246 next_diagnostic.range.start..next_diagnostic.range.start,
13247 ])
13248 });
13249 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13250 self.refresh_inline_completion(false, true, window, cx);
13251 }
13252
13253 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13254 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13255 let snapshot = self.snapshot(window, cx);
13256 let selection = self.selections.newest::<Point>(cx);
13257 self.go_to_hunk_before_or_after_position(
13258 &snapshot,
13259 selection.head(),
13260 Direction::Next,
13261 window,
13262 cx,
13263 );
13264 }
13265
13266 pub fn go_to_hunk_before_or_after_position(
13267 &mut self,
13268 snapshot: &EditorSnapshot,
13269 position: Point,
13270 direction: Direction,
13271 window: &mut Window,
13272 cx: &mut Context<Editor>,
13273 ) {
13274 let row = if direction == Direction::Next {
13275 self.hunk_after_position(snapshot, position)
13276 .map(|hunk| hunk.row_range.start)
13277 } else {
13278 self.hunk_before_position(snapshot, position)
13279 };
13280
13281 if let Some(row) = row {
13282 let destination = Point::new(row.0, 0);
13283 let autoscroll = Autoscroll::center();
13284
13285 self.unfold_ranges(&[destination..destination], false, false, cx);
13286 self.change_selections(Some(autoscroll), window, cx, |s| {
13287 s.select_ranges([destination..destination]);
13288 });
13289 }
13290 }
13291
13292 fn hunk_after_position(
13293 &mut self,
13294 snapshot: &EditorSnapshot,
13295 position: Point,
13296 ) -> Option<MultiBufferDiffHunk> {
13297 snapshot
13298 .buffer_snapshot
13299 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13300 .find(|hunk| hunk.row_range.start.0 > position.row)
13301 .or_else(|| {
13302 snapshot
13303 .buffer_snapshot
13304 .diff_hunks_in_range(Point::zero()..position)
13305 .find(|hunk| hunk.row_range.end.0 < position.row)
13306 })
13307 }
13308
13309 fn go_to_prev_hunk(
13310 &mut self,
13311 _: &GoToPreviousHunk,
13312 window: &mut Window,
13313 cx: &mut Context<Self>,
13314 ) {
13315 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13316 let snapshot = self.snapshot(window, cx);
13317 let selection = self.selections.newest::<Point>(cx);
13318 self.go_to_hunk_before_or_after_position(
13319 &snapshot,
13320 selection.head(),
13321 Direction::Prev,
13322 window,
13323 cx,
13324 );
13325 }
13326
13327 fn hunk_before_position(
13328 &mut self,
13329 snapshot: &EditorSnapshot,
13330 position: Point,
13331 ) -> Option<MultiBufferRow> {
13332 snapshot
13333 .buffer_snapshot
13334 .diff_hunk_before(position)
13335 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13336 }
13337
13338 fn go_to_line<T: 'static>(
13339 &mut self,
13340 position: Anchor,
13341 highlight_color: Option<Hsla>,
13342 window: &mut Window,
13343 cx: &mut Context<Self>,
13344 ) {
13345 let snapshot = self.snapshot(window, cx).display_snapshot;
13346 let position = position.to_point(&snapshot.buffer_snapshot);
13347 let start = snapshot
13348 .buffer_snapshot
13349 .clip_point(Point::new(position.row, 0), Bias::Left);
13350 let end = start + Point::new(1, 0);
13351 let start = snapshot.buffer_snapshot.anchor_before(start);
13352 let end = snapshot.buffer_snapshot.anchor_before(end);
13353
13354 self.highlight_rows::<T>(
13355 start..end,
13356 highlight_color
13357 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13358 false,
13359 cx,
13360 );
13361 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13362 }
13363
13364 pub fn go_to_definition(
13365 &mut self,
13366 _: &GoToDefinition,
13367 window: &mut Window,
13368 cx: &mut Context<Self>,
13369 ) -> Task<Result<Navigated>> {
13370 let definition =
13371 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13372 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13373 cx.spawn_in(window, async move |editor, cx| {
13374 if definition.await? == Navigated::Yes {
13375 return Ok(Navigated::Yes);
13376 }
13377 match fallback_strategy {
13378 GoToDefinitionFallback::None => Ok(Navigated::No),
13379 GoToDefinitionFallback::FindAllReferences => {
13380 match editor.update_in(cx, |editor, window, cx| {
13381 editor.find_all_references(&FindAllReferences, window, cx)
13382 })? {
13383 Some(references) => references.await,
13384 None => Ok(Navigated::No),
13385 }
13386 }
13387 }
13388 })
13389 }
13390
13391 pub fn go_to_declaration(
13392 &mut self,
13393 _: &GoToDeclaration,
13394 window: &mut Window,
13395 cx: &mut Context<Self>,
13396 ) -> Task<Result<Navigated>> {
13397 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13398 }
13399
13400 pub fn go_to_declaration_split(
13401 &mut self,
13402 _: &GoToDeclaration,
13403 window: &mut Window,
13404 cx: &mut Context<Self>,
13405 ) -> Task<Result<Navigated>> {
13406 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13407 }
13408
13409 pub fn go_to_implementation(
13410 &mut self,
13411 _: &GoToImplementation,
13412 window: &mut Window,
13413 cx: &mut Context<Self>,
13414 ) -> Task<Result<Navigated>> {
13415 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13416 }
13417
13418 pub fn go_to_implementation_split(
13419 &mut self,
13420 _: &GoToImplementationSplit,
13421 window: &mut Window,
13422 cx: &mut Context<Self>,
13423 ) -> Task<Result<Navigated>> {
13424 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13425 }
13426
13427 pub fn go_to_type_definition(
13428 &mut self,
13429 _: &GoToTypeDefinition,
13430 window: &mut Window,
13431 cx: &mut Context<Self>,
13432 ) -> Task<Result<Navigated>> {
13433 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13434 }
13435
13436 pub fn go_to_definition_split(
13437 &mut self,
13438 _: &GoToDefinitionSplit,
13439 window: &mut Window,
13440 cx: &mut Context<Self>,
13441 ) -> Task<Result<Navigated>> {
13442 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13443 }
13444
13445 pub fn go_to_type_definition_split(
13446 &mut self,
13447 _: &GoToTypeDefinitionSplit,
13448 window: &mut Window,
13449 cx: &mut Context<Self>,
13450 ) -> Task<Result<Navigated>> {
13451 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13452 }
13453
13454 fn go_to_definition_of_kind(
13455 &mut self,
13456 kind: GotoDefinitionKind,
13457 split: bool,
13458 window: &mut Window,
13459 cx: &mut Context<Self>,
13460 ) -> Task<Result<Navigated>> {
13461 let Some(provider) = self.semantics_provider.clone() else {
13462 return Task::ready(Ok(Navigated::No));
13463 };
13464 let head = self.selections.newest::<usize>(cx).head();
13465 let buffer = self.buffer.read(cx);
13466 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13467 text_anchor
13468 } else {
13469 return Task::ready(Ok(Navigated::No));
13470 };
13471
13472 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13473 return Task::ready(Ok(Navigated::No));
13474 };
13475
13476 cx.spawn_in(window, async move |editor, cx| {
13477 let definitions = definitions.await?;
13478 let navigated = editor
13479 .update_in(cx, |editor, window, cx| {
13480 editor.navigate_to_hover_links(
13481 Some(kind),
13482 definitions
13483 .into_iter()
13484 .filter(|location| {
13485 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13486 })
13487 .map(HoverLink::Text)
13488 .collect::<Vec<_>>(),
13489 split,
13490 window,
13491 cx,
13492 )
13493 })?
13494 .await?;
13495 anyhow::Ok(navigated)
13496 })
13497 }
13498
13499 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13500 let selection = self.selections.newest_anchor();
13501 let head = selection.head();
13502 let tail = selection.tail();
13503
13504 let Some((buffer, start_position)) =
13505 self.buffer.read(cx).text_anchor_for_position(head, cx)
13506 else {
13507 return;
13508 };
13509
13510 let end_position = if head != tail {
13511 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13512 return;
13513 };
13514 Some(pos)
13515 } else {
13516 None
13517 };
13518
13519 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13520 let url = if let Some(end_pos) = end_position {
13521 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13522 } else {
13523 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13524 };
13525
13526 if let Some(url) = url {
13527 editor.update(cx, |_, cx| {
13528 cx.open_url(&url);
13529 })
13530 } else {
13531 Ok(())
13532 }
13533 });
13534
13535 url_finder.detach();
13536 }
13537
13538 pub fn open_selected_filename(
13539 &mut self,
13540 _: &OpenSelectedFilename,
13541 window: &mut Window,
13542 cx: &mut Context<Self>,
13543 ) {
13544 let Some(workspace) = self.workspace() else {
13545 return;
13546 };
13547
13548 let position = self.selections.newest_anchor().head();
13549
13550 let Some((buffer, buffer_position)) =
13551 self.buffer.read(cx).text_anchor_for_position(position, cx)
13552 else {
13553 return;
13554 };
13555
13556 let project = self.project.clone();
13557
13558 cx.spawn_in(window, async move |_, cx| {
13559 let result = find_file(&buffer, project, buffer_position, cx).await;
13560
13561 if let Some((_, path)) = result {
13562 workspace
13563 .update_in(cx, |workspace, window, cx| {
13564 workspace.open_resolved_path(path, window, cx)
13565 })?
13566 .await?;
13567 }
13568 anyhow::Ok(())
13569 })
13570 .detach();
13571 }
13572
13573 pub(crate) fn navigate_to_hover_links(
13574 &mut self,
13575 kind: Option<GotoDefinitionKind>,
13576 mut definitions: Vec<HoverLink>,
13577 split: bool,
13578 window: &mut Window,
13579 cx: &mut Context<Editor>,
13580 ) -> Task<Result<Navigated>> {
13581 // If there is one definition, just open it directly
13582 if definitions.len() == 1 {
13583 let definition = definitions.pop().unwrap();
13584
13585 enum TargetTaskResult {
13586 Location(Option<Location>),
13587 AlreadyNavigated,
13588 }
13589
13590 let target_task = match definition {
13591 HoverLink::Text(link) => {
13592 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13593 }
13594 HoverLink::InlayHint(lsp_location, server_id) => {
13595 let computation =
13596 self.compute_target_location(lsp_location, server_id, window, cx);
13597 cx.background_spawn(async move {
13598 let location = computation.await?;
13599 Ok(TargetTaskResult::Location(location))
13600 })
13601 }
13602 HoverLink::Url(url) => {
13603 cx.open_url(&url);
13604 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13605 }
13606 HoverLink::File(path) => {
13607 if let Some(workspace) = self.workspace() {
13608 cx.spawn_in(window, async move |_, cx| {
13609 workspace
13610 .update_in(cx, |workspace, window, cx| {
13611 workspace.open_resolved_path(path, window, cx)
13612 })?
13613 .await
13614 .map(|_| TargetTaskResult::AlreadyNavigated)
13615 })
13616 } else {
13617 Task::ready(Ok(TargetTaskResult::Location(None)))
13618 }
13619 }
13620 };
13621 cx.spawn_in(window, async move |editor, cx| {
13622 let target = match target_task.await.context("target resolution task")? {
13623 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13624 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13625 TargetTaskResult::Location(Some(target)) => target,
13626 };
13627
13628 editor.update_in(cx, |editor, window, cx| {
13629 let Some(workspace) = editor.workspace() else {
13630 return Navigated::No;
13631 };
13632 let pane = workspace.read(cx).active_pane().clone();
13633
13634 let range = target.range.to_point(target.buffer.read(cx));
13635 let range = editor.range_for_match(&range);
13636 let range = collapse_multiline_range(range);
13637
13638 if !split
13639 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13640 {
13641 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13642 } else {
13643 window.defer(cx, move |window, cx| {
13644 let target_editor: Entity<Self> =
13645 workspace.update(cx, |workspace, cx| {
13646 let pane = if split {
13647 workspace.adjacent_pane(window, cx)
13648 } else {
13649 workspace.active_pane().clone()
13650 };
13651
13652 workspace.open_project_item(
13653 pane,
13654 target.buffer.clone(),
13655 true,
13656 true,
13657 window,
13658 cx,
13659 )
13660 });
13661 target_editor.update(cx, |target_editor, cx| {
13662 // When selecting a definition in a different buffer, disable the nav history
13663 // to avoid creating a history entry at the previous cursor location.
13664 pane.update(cx, |pane, _| pane.disable_history());
13665 target_editor.go_to_singleton_buffer_range(range, window, cx);
13666 pane.update(cx, |pane, _| pane.enable_history());
13667 });
13668 });
13669 }
13670 Navigated::Yes
13671 })
13672 })
13673 } else if !definitions.is_empty() {
13674 cx.spawn_in(window, async move |editor, cx| {
13675 let (title, location_tasks, workspace) = editor
13676 .update_in(cx, |editor, window, cx| {
13677 let tab_kind = match kind {
13678 Some(GotoDefinitionKind::Implementation) => "Implementations",
13679 _ => "Definitions",
13680 };
13681 let title = definitions
13682 .iter()
13683 .find_map(|definition| match definition {
13684 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13685 let buffer = origin.buffer.read(cx);
13686 format!(
13687 "{} for {}",
13688 tab_kind,
13689 buffer
13690 .text_for_range(origin.range.clone())
13691 .collect::<String>()
13692 )
13693 }),
13694 HoverLink::InlayHint(_, _) => None,
13695 HoverLink::Url(_) => None,
13696 HoverLink::File(_) => None,
13697 })
13698 .unwrap_or(tab_kind.to_string());
13699 let location_tasks = definitions
13700 .into_iter()
13701 .map(|definition| match definition {
13702 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13703 HoverLink::InlayHint(lsp_location, server_id) => editor
13704 .compute_target_location(lsp_location, server_id, window, cx),
13705 HoverLink::Url(_) => Task::ready(Ok(None)),
13706 HoverLink::File(_) => Task::ready(Ok(None)),
13707 })
13708 .collect::<Vec<_>>();
13709 (title, location_tasks, editor.workspace().clone())
13710 })
13711 .context("location tasks preparation")?;
13712
13713 let locations = future::join_all(location_tasks)
13714 .await
13715 .into_iter()
13716 .filter_map(|location| location.transpose())
13717 .collect::<Result<_>>()
13718 .context("location tasks")?;
13719
13720 let Some(workspace) = workspace else {
13721 return Ok(Navigated::No);
13722 };
13723 let opened = workspace
13724 .update_in(cx, |workspace, window, cx| {
13725 Self::open_locations_in_multibuffer(
13726 workspace,
13727 locations,
13728 title,
13729 split,
13730 MultibufferSelectionMode::First,
13731 window,
13732 cx,
13733 )
13734 })
13735 .ok();
13736
13737 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13738 })
13739 } else {
13740 Task::ready(Ok(Navigated::No))
13741 }
13742 }
13743
13744 fn compute_target_location(
13745 &self,
13746 lsp_location: lsp::Location,
13747 server_id: LanguageServerId,
13748 window: &mut Window,
13749 cx: &mut Context<Self>,
13750 ) -> Task<anyhow::Result<Option<Location>>> {
13751 let Some(project) = self.project.clone() else {
13752 return Task::ready(Ok(None));
13753 };
13754
13755 cx.spawn_in(window, async move |editor, cx| {
13756 let location_task = editor.update(cx, |_, cx| {
13757 project.update(cx, |project, cx| {
13758 let language_server_name = project
13759 .language_server_statuses(cx)
13760 .find(|(id, _)| server_id == *id)
13761 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13762 language_server_name.map(|language_server_name| {
13763 project.open_local_buffer_via_lsp(
13764 lsp_location.uri.clone(),
13765 server_id,
13766 language_server_name,
13767 cx,
13768 )
13769 })
13770 })
13771 })?;
13772 let location = match location_task {
13773 Some(task) => Some({
13774 let target_buffer_handle = task.await.context("open local buffer")?;
13775 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13776 let target_start = target_buffer
13777 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13778 let target_end = target_buffer
13779 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13780 target_buffer.anchor_after(target_start)
13781 ..target_buffer.anchor_before(target_end)
13782 })?;
13783 Location {
13784 buffer: target_buffer_handle,
13785 range,
13786 }
13787 }),
13788 None => None,
13789 };
13790 Ok(location)
13791 })
13792 }
13793
13794 pub fn find_all_references(
13795 &mut self,
13796 _: &FindAllReferences,
13797 window: &mut Window,
13798 cx: &mut Context<Self>,
13799 ) -> Option<Task<Result<Navigated>>> {
13800 let selection = self.selections.newest::<usize>(cx);
13801 let multi_buffer = self.buffer.read(cx);
13802 let head = selection.head();
13803
13804 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13805 let head_anchor = multi_buffer_snapshot.anchor_at(
13806 head,
13807 if head < selection.tail() {
13808 Bias::Right
13809 } else {
13810 Bias::Left
13811 },
13812 );
13813
13814 match self
13815 .find_all_references_task_sources
13816 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13817 {
13818 Ok(_) => {
13819 log::info!(
13820 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13821 );
13822 return None;
13823 }
13824 Err(i) => {
13825 self.find_all_references_task_sources.insert(i, head_anchor);
13826 }
13827 }
13828
13829 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13830 let workspace = self.workspace()?;
13831 let project = workspace.read(cx).project().clone();
13832 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13833 Some(cx.spawn_in(window, async move |editor, cx| {
13834 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13835 if let Ok(i) = editor
13836 .find_all_references_task_sources
13837 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13838 {
13839 editor.find_all_references_task_sources.remove(i);
13840 }
13841 });
13842
13843 let locations = references.await?;
13844 if locations.is_empty() {
13845 return anyhow::Ok(Navigated::No);
13846 }
13847
13848 workspace.update_in(cx, |workspace, window, cx| {
13849 let title = locations
13850 .first()
13851 .as_ref()
13852 .map(|location| {
13853 let buffer = location.buffer.read(cx);
13854 format!(
13855 "References to `{}`",
13856 buffer
13857 .text_for_range(location.range.clone())
13858 .collect::<String>()
13859 )
13860 })
13861 .unwrap();
13862 Self::open_locations_in_multibuffer(
13863 workspace,
13864 locations,
13865 title,
13866 false,
13867 MultibufferSelectionMode::First,
13868 window,
13869 cx,
13870 );
13871 Navigated::Yes
13872 })
13873 }))
13874 }
13875
13876 /// Opens a multibuffer with the given project locations in it
13877 pub fn open_locations_in_multibuffer(
13878 workspace: &mut Workspace,
13879 mut locations: Vec<Location>,
13880 title: String,
13881 split: bool,
13882 multibuffer_selection_mode: MultibufferSelectionMode,
13883 window: &mut Window,
13884 cx: &mut Context<Workspace>,
13885 ) {
13886 // If there are multiple definitions, open them in a multibuffer
13887 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13888 let mut locations = locations.into_iter().peekable();
13889 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13890 let capability = workspace.project().read(cx).capability();
13891
13892 let excerpt_buffer = cx.new(|cx| {
13893 let mut multibuffer = MultiBuffer::new(capability);
13894 while let Some(location) = locations.next() {
13895 let buffer = location.buffer.read(cx);
13896 let mut ranges_for_buffer = Vec::new();
13897 let range = location.range.to_point(buffer);
13898 ranges_for_buffer.push(range.clone());
13899
13900 while let Some(next_location) = locations.peek() {
13901 if next_location.buffer == location.buffer {
13902 ranges_for_buffer.push(next_location.range.to_point(buffer));
13903 locations.next();
13904 } else {
13905 break;
13906 }
13907 }
13908
13909 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13910 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13911 PathKey::for_buffer(&location.buffer, cx),
13912 location.buffer.clone(),
13913 ranges_for_buffer,
13914 DEFAULT_MULTIBUFFER_CONTEXT,
13915 cx,
13916 );
13917 ranges.extend(new_ranges)
13918 }
13919
13920 multibuffer.with_title(title)
13921 });
13922
13923 let editor = cx.new(|cx| {
13924 Editor::for_multibuffer(
13925 excerpt_buffer,
13926 Some(workspace.project().clone()),
13927 window,
13928 cx,
13929 )
13930 });
13931 editor.update(cx, |editor, cx| {
13932 match multibuffer_selection_mode {
13933 MultibufferSelectionMode::First => {
13934 if let Some(first_range) = ranges.first() {
13935 editor.change_selections(None, window, cx, |selections| {
13936 selections.clear_disjoint();
13937 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13938 });
13939 }
13940 editor.highlight_background::<Self>(
13941 &ranges,
13942 |theme| theme.editor_highlighted_line_background,
13943 cx,
13944 );
13945 }
13946 MultibufferSelectionMode::All => {
13947 editor.change_selections(None, window, cx, |selections| {
13948 selections.clear_disjoint();
13949 selections.select_anchor_ranges(ranges);
13950 });
13951 }
13952 }
13953 editor.register_buffers_with_language_servers(cx);
13954 });
13955
13956 let item = Box::new(editor);
13957 let item_id = item.item_id();
13958
13959 if split {
13960 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13961 } else {
13962 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13963 let (preview_item_id, preview_item_idx) =
13964 workspace.active_pane().update(cx, |pane, _| {
13965 (pane.preview_item_id(), pane.preview_item_idx())
13966 });
13967
13968 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13969
13970 if let Some(preview_item_id) = preview_item_id {
13971 workspace.active_pane().update(cx, |pane, cx| {
13972 pane.remove_item(preview_item_id, false, false, window, cx);
13973 });
13974 }
13975 } else {
13976 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13977 }
13978 }
13979 workspace.active_pane().update(cx, |pane, cx| {
13980 pane.set_preview_item_id(Some(item_id), cx);
13981 });
13982 }
13983
13984 pub fn rename(
13985 &mut self,
13986 _: &Rename,
13987 window: &mut Window,
13988 cx: &mut Context<Self>,
13989 ) -> Option<Task<Result<()>>> {
13990 use language::ToOffset as _;
13991
13992 let provider = self.semantics_provider.clone()?;
13993 let selection = self.selections.newest_anchor().clone();
13994 let (cursor_buffer, cursor_buffer_position) = self
13995 .buffer
13996 .read(cx)
13997 .text_anchor_for_position(selection.head(), cx)?;
13998 let (tail_buffer, cursor_buffer_position_end) = self
13999 .buffer
14000 .read(cx)
14001 .text_anchor_for_position(selection.tail(), cx)?;
14002 if tail_buffer != cursor_buffer {
14003 return None;
14004 }
14005
14006 let snapshot = cursor_buffer.read(cx).snapshot();
14007 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14008 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14009 let prepare_rename = provider
14010 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14011 .unwrap_or_else(|| Task::ready(Ok(None)));
14012 drop(snapshot);
14013
14014 Some(cx.spawn_in(window, async move |this, cx| {
14015 let rename_range = if let Some(range) = prepare_rename.await? {
14016 Some(range)
14017 } else {
14018 this.update(cx, |this, cx| {
14019 let buffer = this.buffer.read(cx).snapshot(cx);
14020 let mut buffer_highlights = this
14021 .document_highlights_for_position(selection.head(), &buffer)
14022 .filter(|highlight| {
14023 highlight.start.excerpt_id == selection.head().excerpt_id
14024 && highlight.end.excerpt_id == selection.head().excerpt_id
14025 });
14026 buffer_highlights
14027 .next()
14028 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14029 })?
14030 };
14031 if let Some(rename_range) = rename_range {
14032 this.update_in(cx, |this, window, cx| {
14033 let snapshot = cursor_buffer.read(cx).snapshot();
14034 let rename_buffer_range = rename_range.to_offset(&snapshot);
14035 let cursor_offset_in_rename_range =
14036 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14037 let cursor_offset_in_rename_range_end =
14038 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14039
14040 this.take_rename(false, window, cx);
14041 let buffer = this.buffer.read(cx).read(cx);
14042 let cursor_offset = selection.head().to_offset(&buffer);
14043 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14044 let rename_end = rename_start + rename_buffer_range.len();
14045 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14046 let mut old_highlight_id = None;
14047 let old_name: Arc<str> = buffer
14048 .chunks(rename_start..rename_end, true)
14049 .map(|chunk| {
14050 if old_highlight_id.is_none() {
14051 old_highlight_id = chunk.syntax_highlight_id;
14052 }
14053 chunk.text
14054 })
14055 .collect::<String>()
14056 .into();
14057
14058 drop(buffer);
14059
14060 // Position the selection in the rename editor so that it matches the current selection.
14061 this.show_local_selections = false;
14062 let rename_editor = cx.new(|cx| {
14063 let mut editor = Editor::single_line(window, cx);
14064 editor.buffer.update(cx, |buffer, cx| {
14065 buffer.edit([(0..0, old_name.clone())], None, cx)
14066 });
14067 let rename_selection_range = match cursor_offset_in_rename_range
14068 .cmp(&cursor_offset_in_rename_range_end)
14069 {
14070 Ordering::Equal => {
14071 editor.select_all(&SelectAll, window, cx);
14072 return editor;
14073 }
14074 Ordering::Less => {
14075 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14076 }
14077 Ordering::Greater => {
14078 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14079 }
14080 };
14081 if rename_selection_range.end > old_name.len() {
14082 editor.select_all(&SelectAll, window, cx);
14083 } else {
14084 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14085 s.select_ranges([rename_selection_range]);
14086 });
14087 }
14088 editor
14089 });
14090 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14091 if e == &EditorEvent::Focused {
14092 cx.emit(EditorEvent::FocusedIn)
14093 }
14094 })
14095 .detach();
14096
14097 let write_highlights =
14098 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14099 let read_highlights =
14100 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14101 let ranges = write_highlights
14102 .iter()
14103 .flat_map(|(_, ranges)| ranges.iter())
14104 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14105 .cloned()
14106 .collect();
14107
14108 this.highlight_text::<Rename>(
14109 ranges,
14110 HighlightStyle {
14111 fade_out: Some(0.6),
14112 ..Default::default()
14113 },
14114 cx,
14115 );
14116 let rename_focus_handle = rename_editor.focus_handle(cx);
14117 window.focus(&rename_focus_handle);
14118 let block_id = this.insert_blocks(
14119 [BlockProperties {
14120 style: BlockStyle::Flex,
14121 placement: BlockPlacement::Below(range.start),
14122 height: Some(1),
14123 render: Arc::new({
14124 let rename_editor = rename_editor.clone();
14125 move |cx: &mut BlockContext| {
14126 let mut text_style = cx.editor_style.text.clone();
14127 if let Some(highlight_style) = old_highlight_id
14128 .and_then(|h| h.style(&cx.editor_style.syntax))
14129 {
14130 text_style = text_style.highlight(highlight_style);
14131 }
14132 div()
14133 .block_mouse_down()
14134 .pl(cx.anchor_x)
14135 .child(EditorElement::new(
14136 &rename_editor,
14137 EditorStyle {
14138 background: cx.theme().system().transparent,
14139 local_player: cx.editor_style.local_player,
14140 text: text_style,
14141 scrollbar_width: cx.editor_style.scrollbar_width,
14142 syntax: cx.editor_style.syntax.clone(),
14143 status: cx.editor_style.status.clone(),
14144 inlay_hints_style: HighlightStyle {
14145 font_weight: Some(FontWeight::BOLD),
14146 ..make_inlay_hints_style(cx.app)
14147 },
14148 inline_completion_styles: make_suggestion_styles(
14149 cx.app,
14150 ),
14151 ..EditorStyle::default()
14152 },
14153 ))
14154 .into_any_element()
14155 }
14156 }),
14157 priority: 0,
14158 }],
14159 Some(Autoscroll::fit()),
14160 cx,
14161 )[0];
14162 this.pending_rename = Some(RenameState {
14163 range,
14164 old_name,
14165 editor: rename_editor,
14166 block_id,
14167 });
14168 })?;
14169 }
14170
14171 Ok(())
14172 }))
14173 }
14174
14175 pub fn confirm_rename(
14176 &mut self,
14177 _: &ConfirmRename,
14178 window: &mut Window,
14179 cx: &mut Context<Self>,
14180 ) -> Option<Task<Result<()>>> {
14181 let rename = self.take_rename(false, window, cx)?;
14182 let workspace = self.workspace()?.downgrade();
14183 let (buffer, start) = self
14184 .buffer
14185 .read(cx)
14186 .text_anchor_for_position(rename.range.start, cx)?;
14187 let (end_buffer, _) = self
14188 .buffer
14189 .read(cx)
14190 .text_anchor_for_position(rename.range.end, cx)?;
14191 if buffer != end_buffer {
14192 return None;
14193 }
14194
14195 let old_name = rename.old_name;
14196 let new_name = rename.editor.read(cx).text(cx);
14197
14198 let rename = self.semantics_provider.as_ref()?.perform_rename(
14199 &buffer,
14200 start,
14201 new_name.clone(),
14202 cx,
14203 )?;
14204
14205 Some(cx.spawn_in(window, async move |editor, cx| {
14206 let project_transaction = rename.await?;
14207 Self::open_project_transaction(
14208 &editor,
14209 workspace,
14210 project_transaction,
14211 format!("Rename: {} → {}", old_name, new_name),
14212 cx,
14213 )
14214 .await?;
14215
14216 editor.update(cx, |editor, cx| {
14217 editor.refresh_document_highlights(cx);
14218 })?;
14219 Ok(())
14220 }))
14221 }
14222
14223 fn take_rename(
14224 &mut self,
14225 moving_cursor: bool,
14226 window: &mut Window,
14227 cx: &mut Context<Self>,
14228 ) -> Option<RenameState> {
14229 let rename = self.pending_rename.take()?;
14230 if rename.editor.focus_handle(cx).is_focused(window) {
14231 window.focus(&self.focus_handle);
14232 }
14233
14234 self.remove_blocks(
14235 [rename.block_id].into_iter().collect(),
14236 Some(Autoscroll::fit()),
14237 cx,
14238 );
14239 self.clear_highlights::<Rename>(cx);
14240 self.show_local_selections = true;
14241
14242 if moving_cursor {
14243 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14244 editor.selections.newest::<usize>(cx).head()
14245 });
14246
14247 // Update the selection to match the position of the selection inside
14248 // the rename editor.
14249 let snapshot = self.buffer.read(cx).read(cx);
14250 let rename_range = rename.range.to_offset(&snapshot);
14251 let cursor_in_editor = snapshot
14252 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14253 .min(rename_range.end);
14254 drop(snapshot);
14255
14256 self.change_selections(None, window, cx, |s| {
14257 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14258 });
14259 } else {
14260 self.refresh_document_highlights(cx);
14261 }
14262
14263 Some(rename)
14264 }
14265
14266 pub fn pending_rename(&self) -> Option<&RenameState> {
14267 self.pending_rename.as_ref()
14268 }
14269
14270 fn format(
14271 &mut self,
14272 _: &Format,
14273 window: &mut Window,
14274 cx: &mut Context<Self>,
14275 ) -> Option<Task<Result<()>>> {
14276 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14277
14278 let project = match &self.project {
14279 Some(project) => project.clone(),
14280 None => return None,
14281 };
14282
14283 Some(self.perform_format(
14284 project,
14285 FormatTrigger::Manual,
14286 FormatTarget::Buffers,
14287 window,
14288 cx,
14289 ))
14290 }
14291
14292 fn format_selections(
14293 &mut self,
14294 _: &FormatSelections,
14295 window: &mut Window,
14296 cx: &mut Context<Self>,
14297 ) -> Option<Task<Result<()>>> {
14298 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14299
14300 let project = match &self.project {
14301 Some(project) => project.clone(),
14302 None => return None,
14303 };
14304
14305 let ranges = self
14306 .selections
14307 .all_adjusted(cx)
14308 .into_iter()
14309 .map(|selection| selection.range())
14310 .collect_vec();
14311
14312 Some(self.perform_format(
14313 project,
14314 FormatTrigger::Manual,
14315 FormatTarget::Ranges(ranges),
14316 window,
14317 cx,
14318 ))
14319 }
14320
14321 fn perform_format(
14322 &mut self,
14323 project: Entity<Project>,
14324 trigger: FormatTrigger,
14325 target: FormatTarget,
14326 window: &mut Window,
14327 cx: &mut Context<Self>,
14328 ) -> Task<Result<()>> {
14329 let buffer = self.buffer.clone();
14330 let (buffers, target) = match target {
14331 FormatTarget::Buffers => {
14332 let mut buffers = buffer.read(cx).all_buffers();
14333 if trigger == FormatTrigger::Save {
14334 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14335 }
14336 (buffers, LspFormatTarget::Buffers)
14337 }
14338 FormatTarget::Ranges(selection_ranges) => {
14339 let multi_buffer = buffer.read(cx);
14340 let snapshot = multi_buffer.read(cx);
14341 let mut buffers = HashSet::default();
14342 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14343 BTreeMap::new();
14344 for selection_range in selection_ranges {
14345 for (buffer, buffer_range, _) in
14346 snapshot.range_to_buffer_ranges(selection_range)
14347 {
14348 let buffer_id = buffer.remote_id();
14349 let start = buffer.anchor_before(buffer_range.start);
14350 let end = buffer.anchor_after(buffer_range.end);
14351 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14352 buffer_id_to_ranges
14353 .entry(buffer_id)
14354 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14355 .or_insert_with(|| vec![start..end]);
14356 }
14357 }
14358 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14359 }
14360 };
14361
14362 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14363 let selections_prev = transaction_id_prev
14364 .and_then(|transaction_id_prev| {
14365 // default to selections as they were after the last edit, if we have them,
14366 // instead of how they are now.
14367 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14368 // will take you back to where you made the last edit, instead of staying where you scrolled
14369 self.selection_history
14370 .transaction(transaction_id_prev)
14371 .map(|t| t.0.clone())
14372 })
14373 .unwrap_or_else(|| {
14374 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14375 self.selections.disjoint_anchors()
14376 });
14377
14378 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14379 let format = project.update(cx, |project, cx| {
14380 project.format(buffers, target, true, trigger, cx)
14381 });
14382
14383 cx.spawn_in(window, async move |editor, cx| {
14384 let transaction = futures::select_biased! {
14385 transaction = format.log_err().fuse() => transaction,
14386 () = timeout => {
14387 log::warn!("timed out waiting for formatting");
14388 None
14389 }
14390 };
14391
14392 buffer
14393 .update(cx, |buffer, cx| {
14394 if let Some(transaction) = transaction {
14395 if !buffer.is_singleton() {
14396 buffer.push_transaction(&transaction.0, cx);
14397 }
14398 }
14399 cx.notify();
14400 })
14401 .ok();
14402
14403 if let Some(transaction_id_now) =
14404 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14405 {
14406 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14407 if has_new_transaction {
14408 _ = editor.update(cx, |editor, _| {
14409 editor
14410 .selection_history
14411 .insert_transaction(transaction_id_now, selections_prev);
14412 });
14413 }
14414 }
14415
14416 Ok(())
14417 })
14418 }
14419
14420 fn organize_imports(
14421 &mut self,
14422 _: &OrganizeImports,
14423 window: &mut Window,
14424 cx: &mut Context<Self>,
14425 ) -> Option<Task<Result<()>>> {
14426 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14427 let project = match &self.project {
14428 Some(project) => project.clone(),
14429 None => return None,
14430 };
14431 Some(self.perform_code_action_kind(
14432 project,
14433 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14434 window,
14435 cx,
14436 ))
14437 }
14438
14439 fn perform_code_action_kind(
14440 &mut self,
14441 project: Entity<Project>,
14442 kind: CodeActionKind,
14443 window: &mut Window,
14444 cx: &mut Context<Self>,
14445 ) -> Task<Result<()>> {
14446 let buffer = self.buffer.clone();
14447 let buffers = buffer.read(cx).all_buffers();
14448 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14449 let apply_action = project.update(cx, |project, cx| {
14450 project.apply_code_action_kind(buffers, kind, true, cx)
14451 });
14452 cx.spawn_in(window, async move |_, cx| {
14453 let transaction = futures::select_biased! {
14454 () = timeout => {
14455 log::warn!("timed out waiting for executing code action");
14456 None
14457 }
14458 transaction = apply_action.log_err().fuse() => transaction,
14459 };
14460 buffer
14461 .update(cx, |buffer, cx| {
14462 // check if we need this
14463 if let Some(transaction) = transaction {
14464 if !buffer.is_singleton() {
14465 buffer.push_transaction(&transaction.0, cx);
14466 }
14467 }
14468 cx.notify();
14469 })
14470 .ok();
14471 Ok(())
14472 })
14473 }
14474
14475 fn restart_language_server(
14476 &mut self,
14477 _: &RestartLanguageServer,
14478 _: &mut Window,
14479 cx: &mut Context<Self>,
14480 ) {
14481 if let Some(project) = self.project.clone() {
14482 self.buffer.update(cx, |multi_buffer, cx| {
14483 project.update(cx, |project, cx| {
14484 project.restart_language_servers_for_buffers(
14485 multi_buffer.all_buffers().into_iter().collect(),
14486 cx,
14487 );
14488 });
14489 })
14490 }
14491 }
14492
14493 fn stop_language_server(
14494 &mut self,
14495 _: &StopLanguageServer,
14496 _: &mut Window,
14497 cx: &mut Context<Self>,
14498 ) {
14499 if let Some(project) = self.project.clone() {
14500 self.buffer.update(cx, |multi_buffer, cx| {
14501 project.update(cx, |project, cx| {
14502 project.stop_language_servers_for_buffers(
14503 multi_buffer.all_buffers().into_iter().collect(),
14504 cx,
14505 );
14506 cx.emit(project::Event::RefreshInlayHints);
14507 });
14508 });
14509 }
14510 }
14511
14512 fn cancel_language_server_work(
14513 workspace: &mut Workspace,
14514 _: &actions::CancelLanguageServerWork,
14515 _: &mut Window,
14516 cx: &mut Context<Workspace>,
14517 ) {
14518 let project = workspace.project();
14519 let buffers = workspace
14520 .active_item(cx)
14521 .and_then(|item| item.act_as::<Editor>(cx))
14522 .map_or(HashSet::default(), |editor| {
14523 editor.read(cx).buffer.read(cx).all_buffers()
14524 });
14525 project.update(cx, |project, cx| {
14526 project.cancel_language_server_work_for_buffers(buffers, cx);
14527 });
14528 }
14529
14530 fn show_character_palette(
14531 &mut self,
14532 _: &ShowCharacterPalette,
14533 window: &mut Window,
14534 _: &mut Context<Self>,
14535 ) {
14536 window.show_character_palette();
14537 }
14538
14539 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14540 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14541 let buffer = self.buffer.read(cx).snapshot(cx);
14542 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14543 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14544 let is_valid = buffer
14545 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14546 .any(|entry| {
14547 entry.diagnostic.is_primary
14548 && !entry.range.is_empty()
14549 && entry.range.start == primary_range_start
14550 && entry.diagnostic.message == active_diagnostics.active_message
14551 });
14552
14553 if !is_valid {
14554 self.dismiss_diagnostics(cx);
14555 }
14556 }
14557 }
14558
14559 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14560 match &self.active_diagnostics {
14561 ActiveDiagnostic::Group(group) => Some(group),
14562 _ => None,
14563 }
14564 }
14565
14566 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14567 self.dismiss_diagnostics(cx);
14568 self.active_diagnostics = ActiveDiagnostic::All;
14569 }
14570
14571 fn activate_diagnostics(
14572 &mut self,
14573 buffer_id: BufferId,
14574 diagnostic: DiagnosticEntry<usize>,
14575 window: &mut Window,
14576 cx: &mut Context<Self>,
14577 ) {
14578 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14579 return;
14580 }
14581 self.dismiss_diagnostics(cx);
14582 let snapshot = self.snapshot(window, cx);
14583 let Some(diagnostic_renderer) = cx
14584 .try_global::<GlobalDiagnosticRenderer>()
14585 .map(|g| g.0.clone())
14586 else {
14587 return;
14588 };
14589 let buffer = self.buffer.read(cx).snapshot(cx);
14590
14591 let diagnostic_group = buffer
14592 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14593 .collect::<Vec<_>>();
14594
14595 let blocks = diagnostic_renderer.render_group(
14596 diagnostic_group,
14597 buffer_id,
14598 snapshot,
14599 cx.weak_entity(),
14600 cx,
14601 );
14602
14603 let blocks = self.display_map.update(cx, |display_map, cx| {
14604 display_map.insert_blocks(blocks, cx).into_iter().collect()
14605 });
14606 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14607 active_range: buffer.anchor_before(diagnostic.range.start)
14608 ..buffer.anchor_after(diagnostic.range.end),
14609 active_message: diagnostic.diagnostic.message.clone(),
14610 group_id: diagnostic.diagnostic.group_id,
14611 blocks,
14612 });
14613 cx.notify();
14614 }
14615
14616 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14617 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14618 return;
14619 };
14620
14621 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14622 if let ActiveDiagnostic::Group(group) = prev {
14623 self.display_map.update(cx, |display_map, cx| {
14624 display_map.remove_blocks(group.blocks, cx);
14625 });
14626 cx.notify();
14627 }
14628 }
14629
14630 /// Disable inline diagnostics rendering for this editor.
14631 pub fn disable_inline_diagnostics(&mut self) {
14632 self.inline_diagnostics_enabled = false;
14633 self.inline_diagnostics_update = Task::ready(());
14634 self.inline_diagnostics.clear();
14635 }
14636
14637 pub fn inline_diagnostics_enabled(&self) -> bool {
14638 self.inline_diagnostics_enabled
14639 }
14640
14641 pub fn show_inline_diagnostics(&self) -> bool {
14642 self.show_inline_diagnostics
14643 }
14644
14645 pub fn toggle_inline_diagnostics(
14646 &mut self,
14647 _: &ToggleInlineDiagnostics,
14648 window: &mut Window,
14649 cx: &mut Context<Editor>,
14650 ) {
14651 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14652 self.refresh_inline_diagnostics(false, window, cx);
14653 }
14654
14655 fn refresh_inline_diagnostics(
14656 &mut self,
14657 debounce: bool,
14658 window: &mut Window,
14659 cx: &mut Context<Self>,
14660 ) {
14661 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14662 self.inline_diagnostics_update = Task::ready(());
14663 self.inline_diagnostics.clear();
14664 return;
14665 }
14666
14667 let debounce_ms = ProjectSettings::get_global(cx)
14668 .diagnostics
14669 .inline
14670 .update_debounce_ms;
14671 let debounce = if debounce && debounce_ms > 0 {
14672 Some(Duration::from_millis(debounce_ms))
14673 } else {
14674 None
14675 };
14676 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14677 let editor = editor.upgrade().unwrap();
14678
14679 if let Some(debounce) = debounce {
14680 cx.background_executor().timer(debounce).await;
14681 }
14682 let Some(snapshot) = editor
14683 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14684 .ok()
14685 else {
14686 return;
14687 };
14688
14689 let new_inline_diagnostics = cx
14690 .background_spawn(async move {
14691 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14692 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14693 let message = diagnostic_entry
14694 .diagnostic
14695 .message
14696 .split_once('\n')
14697 .map(|(line, _)| line)
14698 .map(SharedString::new)
14699 .unwrap_or_else(|| {
14700 SharedString::from(diagnostic_entry.diagnostic.message)
14701 });
14702 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14703 let (Ok(i) | Err(i)) = inline_diagnostics
14704 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14705 inline_diagnostics.insert(
14706 i,
14707 (
14708 start_anchor,
14709 InlineDiagnostic {
14710 message,
14711 group_id: diagnostic_entry.diagnostic.group_id,
14712 start: diagnostic_entry.range.start.to_point(&snapshot),
14713 is_primary: diagnostic_entry.diagnostic.is_primary,
14714 severity: diagnostic_entry.diagnostic.severity,
14715 },
14716 ),
14717 );
14718 }
14719 inline_diagnostics
14720 })
14721 .await;
14722
14723 editor
14724 .update(cx, |editor, cx| {
14725 editor.inline_diagnostics = new_inline_diagnostics;
14726 cx.notify();
14727 })
14728 .ok();
14729 });
14730 }
14731
14732 pub fn set_selections_from_remote(
14733 &mut self,
14734 selections: Vec<Selection<Anchor>>,
14735 pending_selection: Option<Selection<Anchor>>,
14736 window: &mut Window,
14737 cx: &mut Context<Self>,
14738 ) {
14739 let old_cursor_position = self.selections.newest_anchor().head();
14740 self.selections.change_with(cx, |s| {
14741 s.select_anchors(selections);
14742 if let Some(pending_selection) = pending_selection {
14743 s.set_pending(pending_selection, SelectMode::Character);
14744 } else {
14745 s.clear_pending();
14746 }
14747 });
14748 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14749 }
14750
14751 fn push_to_selection_history(&mut self) {
14752 self.selection_history.push(SelectionHistoryEntry {
14753 selections: self.selections.disjoint_anchors(),
14754 select_next_state: self.select_next_state.clone(),
14755 select_prev_state: self.select_prev_state.clone(),
14756 add_selections_state: self.add_selections_state.clone(),
14757 });
14758 }
14759
14760 pub fn transact(
14761 &mut self,
14762 window: &mut Window,
14763 cx: &mut Context<Self>,
14764 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14765 ) -> Option<TransactionId> {
14766 self.start_transaction_at(Instant::now(), window, cx);
14767 update(self, window, cx);
14768 self.end_transaction_at(Instant::now(), cx)
14769 }
14770
14771 pub fn start_transaction_at(
14772 &mut self,
14773 now: Instant,
14774 window: &mut Window,
14775 cx: &mut Context<Self>,
14776 ) {
14777 self.end_selection(window, cx);
14778 if let Some(tx_id) = self
14779 .buffer
14780 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14781 {
14782 self.selection_history
14783 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14784 cx.emit(EditorEvent::TransactionBegun {
14785 transaction_id: tx_id,
14786 })
14787 }
14788 }
14789
14790 pub fn end_transaction_at(
14791 &mut self,
14792 now: Instant,
14793 cx: &mut Context<Self>,
14794 ) -> Option<TransactionId> {
14795 if let Some(transaction_id) = self
14796 .buffer
14797 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14798 {
14799 if let Some((_, end_selections)) =
14800 self.selection_history.transaction_mut(transaction_id)
14801 {
14802 *end_selections = Some(self.selections.disjoint_anchors());
14803 } else {
14804 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14805 }
14806
14807 cx.emit(EditorEvent::Edited { transaction_id });
14808 Some(transaction_id)
14809 } else {
14810 None
14811 }
14812 }
14813
14814 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14815 if self.selection_mark_mode {
14816 self.change_selections(None, window, cx, |s| {
14817 s.move_with(|_, sel| {
14818 sel.collapse_to(sel.head(), SelectionGoal::None);
14819 });
14820 })
14821 }
14822 self.selection_mark_mode = true;
14823 cx.notify();
14824 }
14825
14826 pub fn swap_selection_ends(
14827 &mut self,
14828 _: &actions::SwapSelectionEnds,
14829 window: &mut Window,
14830 cx: &mut Context<Self>,
14831 ) {
14832 self.change_selections(None, window, cx, |s| {
14833 s.move_with(|_, sel| {
14834 if sel.start != sel.end {
14835 sel.reversed = !sel.reversed
14836 }
14837 });
14838 });
14839 self.request_autoscroll(Autoscroll::newest(), cx);
14840 cx.notify();
14841 }
14842
14843 pub fn toggle_fold(
14844 &mut self,
14845 _: &actions::ToggleFold,
14846 window: &mut Window,
14847 cx: &mut Context<Self>,
14848 ) {
14849 if self.is_singleton(cx) {
14850 let selection = self.selections.newest::<Point>(cx);
14851
14852 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14853 let range = if selection.is_empty() {
14854 let point = selection.head().to_display_point(&display_map);
14855 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14856 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14857 .to_point(&display_map);
14858 start..end
14859 } else {
14860 selection.range()
14861 };
14862 if display_map.folds_in_range(range).next().is_some() {
14863 self.unfold_lines(&Default::default(), window, cx)
14864 } else {
14865 self.fold(&Default::default(), window, cx)
14866 }
14867 } else {
14868 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14869 let buffer_ids: HashSet<_> = self
14870 .selections
14871 .disjoint_anchor_ranges()
14872 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14873 .collect();
14874
14875 let should_unfold = buffer_ids
14876 .iter()
14877 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14878
14879 for buffer_id in buffer_ids {
14880 if should_unfold {
14881 self.unfold_buffer(buffer_id, cx);
14882 } else {
14883 self.fold_buffer(buffer_id, cx);
14884 }
14885 }
14886 }
14887 }
14888
14889 pub fn toggle_fold_recursive(
14890 &mut self,
14891 _: &actions::ToggleFoldRecursive,
14892 window: &mut Window,
14893 cx: &mut Context<Self>,
14894 ) {
14895 let selection = self.selections.newest::<Point>(cx);
14896
14897 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14898 let range = if selection.is_empty() {
14899 let point = selection.head().to_display_point(&display_map);
14900 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14901 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14902 .to_point(&display_map);
14903 start..end
14904 } else {
14905 selection.range()
14906 };
14907 if display_map.folds_in_range(range).next().is_some() {
14908 self.unfold_recursive(&Default::default(), window, cx)
14909 } else {
14910 self.fold_recursive(&Default::default(), window, cx)
14911 }
14912 }
14913
14914 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14915 if self.is_singleton(cx) {
14916 let mut to_fold = Vec::new();
14917 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14918 let selections = self.selections.all_adjusted(cx);
14919
14920 for selection in selections {
14921 let range = selection.range().sorted();
14922 let buffer_start_row = range.start.row;
14923
14924 if range.start.row != range.end.row {
14925 let mut found = false;
14926 let mut row = range.start.row;
14927 while row <= range.end.row {
14928 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14929 {
14930 found = true;
14931 row = crease.range().end.row + 1;
14932 to_fold.push(crease);
14933 } else {
14934 row += 1
14935 }
14936 }
14937 if found {
14938 continue;
14939 }
14940 }
14941
14942 for row in (0..=range.start.row).rev() {
14943 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14944 if crease.range().end.row >= buffer_start_row {
14945 to_fold.push(crease);
14946 if row <= range.start.row {
14947 break;
14948 }
14949 }
14950 }
14951 }
14952 }
14953
14954 self.fold_creases(to_fold, true, window, cx);
14955 } else {
14956 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14957 let buffer_ids = self
14958 .selections
14959 .disjoint_anchor_ranges()
14960 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14961 .collect::<HashSet<_>>();
14962 for buffer_id in buffer_ids {
14963 self.fold_buffer(buffer_id, cx);
14964 }
14965 }
14966 }
14967
14968 fn fold_at_level(
14969 &mut self,
14970 fold_at: &FoldAtLevel,
14971 window: &mut Window,
14972 cx: &mut Context<Self>,
14973 ) {
14974 if !self.buffer.read(cx).is_singleton() {
14975 return;
14976 }
14977
14978 let fold_at_level = fold_at.0;
14979 let snapshot = self.buffer.read(cx).snapshot(cx);
14980 let mut to_fold = Vec::new();
14981 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14982
14983 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14984 while start_row < end_row {
14985 match self
14986 .snapshot(window, cx)
14987 .crease_for_buffer_row(MultiBufferRow(start_row))
14988 {
14989 Some(crease) => {
14990 let nested_start_row = crease.range().start.row + 1;
14991 let nested_end_row = crease.range().end.row;
14992
14993 if current_level < fold_at_level {
14994 stack.push((nested_start_row, nested_end_row, current_level + 1));
14995 } else if current_level == fold_at_level {
14996 to_fold.push(crease);
14997 }
14998
14999 start_row = nested_end_row + 1;
15000 }
15001 None => start_row += 1,
15002 }
15003 }
15004 }
15005
15006 self.fold_creases(to_fold, true, window, cx);
15007 }
15008
15009 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15010 if self.buffer.read(cx).is_singleton() {
15011 let mut fold_ranges = Vec::new();
15012 let snapshot = self.buffer.read(cx).snapshot(cx);
15013
15014 for row in 0..snapshot.max_row().0 {
15015 if let Some(foldable_range) = self
15016 .snapshot(window, cx)
15017 .crease_for_buffer_row(MultiBufferRow(row))
15018 {
15019 fold_ranges.push(foldable_range);
15020 }
15021 }
15022
15023 self.fold_creases(fold_ranges, true, window, cx);
15024 } else {
15025 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15026 editor
15027 .update_in(cx, |editor, _, cx| {
15028 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15029 editor.fold_buffer(buffer_id, cx);
15030 }
15031 })
15032 .ok();
15033 });
15034 }
15035 }
15036
15037 pub fn fold_function_bodies(
15038 &mut self,
15039 _: &actions::FoldFunctionBodies,
15040 window: &mut Window,
15041 cx: &mut Context<Self>,
15042 ) {
15043 let snapshot = self.buffer.read(cx).snapshot(cx);
15044
15045 let ranges = snapshot
15046 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15047 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15048 .collect::<Vec<_>>();
15049
15050 let creases = ranges
15051 .into_iter()
15052 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15053 .collect();
15054
15055 self.fold_creases(creases, true, window, cx);
15056 }
15057
15058 pub fn fold_recursive(
15059 &mut self,
15060 _: &actions::FoldRecursive,
15061 window: &mut Window,
15062 cx: &mut Context<Self>,
15063 ) {
15064 let mut to_fold = Vec::new();
15065 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15066 let selections = self.selections.all_adjusted(cx);
15067
15068 for selection in selections {
15069 let range = selection.range().sorted();
15070 let buffer_start_row = range.start.row;
15071
15072 if range.start.row != range.end.row {
15073 let mut found = false;
15074 for row in range.start.row..=range.end.row {
15075 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15076 found = true;
15077 to_fold.push(crease);
15078 }
15079 }
15080 if found {
15081 continue;
15082 }
15083 }
15084
15085 for row in (0..=range.start.row).rev() {
15086 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15087 if crease.range().end.row >= buffer_start_row {
15088 to_fold.push(crease);
15089 } else {
15090 break;
15091 }
15092 }
15093 }
15094 }
15095
15096 self.fold_creases(to_fold, true, window, cx);
15097 }
15098
15099 pub fn fold_at(
15100 &mut self,
15101 buffer_row: MultiBufferRow,
15102 window: &mut Window,
15103 cx: &mut Context<Self>,
15104 ) {
15105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15106
15107 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15108 let autoscroll = self
15109 .selections
15110 .all::<Point>(cx)
15111 .iter()
15112 .any(|selection| crease.range().overlaps(&selection.range()));
15113
15114 self.fold_creases(vec![crease], autoscroll, window, cx);
15115 }
15116 }
15117
15118 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15119 if self.is_singleton(cx) {
15120 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15121 let buffer = &display_map.buffer_snapshot;
15122 let selections = self.selections.all::<Point>(cx);
15123 let ranges = selections
15124 .iter()
15125 .map(|s| {
15126 let range = s.display_range(&display_map).sorted();
15127 let mut start = range.start.to_point(&display_map);
15128 let mut end = range.end.to_point(&display_map);
15129 start.column = 0;
15130 end.column = buffer.line_len(MultiBufferRow(end.row));
15131 start..end
15132 })
15133 .collect::<Vec<_>>();
15134
15135 self.unfold_ranges(&ranges, true, true, cx);
15136 } else {
15137 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15138 let buffer_ids = self
15139 .selections
15140 .disjoint_anchor_ranges()
15141 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15142 .collect::<HashSet<_>>();
15143 for buffer_id in buffer_ids {
15144 self.unfold_buffer(buffer_id, cx);
15145 }
15146 }
15147 }
15148
15149 pub fn unfold_recursive(
15150 &mut self,
15151 _: &UnfoldRecursive,
15152 _window: &mut Window,
15153 cx: &mut Context<Self>,
15154 ) {
15155 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15156 let selections = self.selections.all::<Point>(cx);
15157 let ranges = selections
15158 .iter()
15159 .map(|s| {
15160 let mut range = s.display_range(&display_map).sorted();
15161 *range.start.column_mut() = 0;
15162 *range.end.column_mut() = display_map.line_len(range.end.row());
15163 let start = range.start.to_point(&display_map);
15164 let end = range.end.to_point(&display_map);
15165 start..end
15166 })
15167 .collect::<Vec<_>>();
15168
15169 self.unfold_ranges(&ranges, true, true, cx);
15170 }
15171
15172 pub fn unfold_at(
15173 &mut self,
15174 buffer_row: MultiBufferRow,
15175 _window: &mut Window,
15176 cx: &mut Context<Self>,
15177 ) {
15178 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15179
15180 let intersection_range = Point::new(buffer_row.0, 0)
15181 ..Point::new(
15182 buffer_row.0,
15183 display_map.buffer_snapshot.line_len(buffer_row),
15184 );
15185
15186 let autoscroll = self
15187 .selections
15188 .all::<Point>(cx)
15189 .iter()
15190 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15191
15192 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15193 }
15194
15195 pub fn unfold_all(
15196 &mut self,
15197 _: &actions::UnfoldAll,
15198 _window: &mut Window,
15199 cx: &mut Context<Self>,
15200 ) {
15201 if self.buffer.read(cx).is_singleton() {
15202 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15203 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15204 } else {
15205 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15206 editor
15207 .update(cx, |editor, cx| {
15208 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15209 editor.unfold_buffer(buffer_id, cx);
15210 }
15211 })
15212 .ok();
15213 });
15214 }
15215 }
15216
15217 pub fn fold_selected_ranges(
15218 &mut self,
15219 _: &FoldSelectedRanges,
15220 window: &mut Window,
15221 cx: &mut Context<Self>,
15222 ) {
15223 let selections = self.selections.all_adjusted(cx);
15224 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15225 let ranges = selections
15226 .into_iter()
15227 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15228 .collect::<Vec<_>>();
15229 self.fold_creases(ranges, true, window, cx);
15230 }
15231
15232 pub fn fold_ranges<T: ToOffset + Clone>(
15233 &mut self,
15234 ranges: Vec<Range<T>>,
15235 auto_scroll: bool,
15236 window: &mut Window,
15237 cx: &mut Context<Self>,
15238 ) {
15239 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15240 let ranges = ranges
15241 .into_iter()
15242 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15243 .collect::<Vec<_>>();
15244 self.fold_creases(ranges, auto_scroll, window, cx);
15245 }
15246
15247 pub fn fold_creases<T: ToOffset + Clone>(
15248 &mut self,
15249 creases: Vec<Crease<T>>,
15250 auto_scroll: bool,
15251 _window: &mut Window,
15252 cx: &mut Context<Self>,
15253 ) {
15254 if creases.is_empty() {
15255 return;
15256 }
15257
15258 let mut buffers_affected = HashSet::default();
15259 let multi_buffer = self.buffer().read(cx);
15260 for crease in &creases {
15261 if let Some((_, buffer, _)) =
15262 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15263 {
15264 buffers_affected.insert(buffer.read(cx).remote_id());
15265 };
15266 }
15267
15268 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15269
15270 if auto_scroll {
15271 self.request_autoscroll(Autoscroll::fit(), cx);
15272 }
15273
15274 cx.notify();
15275
15276 self.scrollbar_marker_state.dirty = true;
15277 self.folds_did_change(cx);
15278 }
15279
15280 /// Removes any folds whose ranges intersect any of the given ranges.
15281 pub fn unfold_ranges<T: ToOffset + Clone>(
15282 &mut self,
15283 ranges: &[Range<T>],
15284 inclusive: bool,
15285 auto_scroll: bool,
15286 cx: &mut Context<Self>,
15287 ) {
15288 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15289 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15290 });
15291 self.folds_did_change(cx);
15292 }
15293
15294 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15295 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15296 return;
15297 }
15298 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15299 self.display_map.update(cx, |display_map, cx| {
15300 display_map.fold_buffers([buffer_id], cx)
15301 });
15302 cx.emit(EditorEvent::BufferFoldToggled {
15303 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15304 folded: true,
15305 });
15306 cx.notify();
15307 }
15308
15309 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15310 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15311 return;
15312 }
15313 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15314 self.display_map.update(cx, |display_map, cx| {
15315 display_map.unfold_buffers([buffer_id], cx);
15316 });
15317 cx.emit(EditorEvent::BufferFoldToggled {
15318 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15319 folded: false,
15320 });
15321 cx.notify();
15322 }
15323
15324 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15325 self.display_map.read(cx).is_buffer_folded(buffer)
15326 }
15327
15328 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15329 self.display_map.read(cx).folded_buffers()
15330 }
15331
15332 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15333 self.display_map.update(cx, |display_map, cx| {
15334 display_map.disable_header_for_buffer(buffer_id, cx);
15335 });
15336 cx.notify();
15337 }
15338
15339 /// Removes any folds with the given ranges.
15340 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15341 &mut self,
15342 ranges: &[Range<T>],
15343 type_id: TypeId,
15344 auto_scroll: bool,
15345 cx: &mut Context<Self>,
15346 ) {
15347 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15348 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15349 });
15350 self.folds_did_change(cx);
15351 }
15352
15353 fn remove_folds_with<T: ToOffset + Clone>(
15354 &mut self,
15355 ranges: &[Range<T>],
15356 auto_scroll: bool,
15357 cx: &mut Context<Self>,
15358 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15359 ) {
15360 if ranges.is_empty() {
15361 return;
15362 }
15363
15364 let mut buffers_affected = HashSet::default();
15365 let multi_buffer = self.buffer().read(cx);
15366 for range in ranges {
15367 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15368 buffers_affected.insert(buffer.read(cx).remote_id());
15369 };
15370 }
15371
15372 self.display_map.update(cx, update);
15373
15374 if auto_scroll {
15375 self.request_autoscroll(Autoscroll::fit(), cx);
15376 }
15377
15378 cx.notify();
15379 self.scrollbar_marker_state.dirty = true;
15380 self.active_indent_guides_state.dirty = true;
15381 }
15382
15383 pub fn update_fold_widths(
15384 &mut self,
15385 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15386 cx: &mut Context<Self>,
15387 ) -> bool {
15388 self.display_map
15389 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15390 }
15391
15392 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15393 self.display_map.read(cx).fold_placeholder.clone()
15394 }
15395
15396 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15397 self.buffer.update(cx, |buffer, cx| {
15398 buffer.set_all_diff_hunks_expanded(cx);
15399 });
15400 }
15401
15402 pub fn expand_all_diff_hunks(
15403 &mut self,
15404 _: &ExpandAllDiffHunks,
15405 _window: &mut Window,
15406 cx: &mut Context<Self>,
15407 ) {
15408 self.buffer.update(cx, |buffer, cx| {
15409 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15410 });
15411 }
15412
15413 pub fn toggle_selected_diff_hunks(
15414 &mut self,
15415 _: &ToggleSelectedDiffHunks,
15416 _window: &mut Window,
15417 cx: &mut Context<Self>,
15418 ) {
15419 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15420 self.toggle_diff_hunks_in_ranges(ranges, cx);
15421 }
15422
15423 pub fn diff_hunks_in_ranges<'a>(
15424 &'a self,
15425 ranges: &'a [Range<Anchor>],
15426 buffer: &'a MultiBufferSnapshot,
15427 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15428 ranges.iter().flat_map(move |range| {
15429 let end_excerpt_id = range.end.excerpt_id;
15430 let range = range.to_point(buffer);
15431 let mut peek_end = range.end;
15432 if range.end.row < buffer.max_row().0 {
15433 peek_end = Point::new(range.end.row + 1, 0);
15434 }
15435 buffer
15436 .diff_hunks_in_range(range.start..peek_end)
15437 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15438 })
15439 }
15440
15441 pub fn has_stageable_diff_hunks_in_ranges(
15442 &self,
15443 ranges: &[Range<Anchor>],
15444 snapshot: &MultiBufferSnapshot,
15445 ) -> bool {
15446 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15447 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15448 }
15449
15450 pub fn toggle_staged_selected_diff_hunks(
15451 &mut self,
15452 _: &::git::ToggleStaged,
15453 _: &mut Window,
15454 cx: &mut Context<Self>,
15455 ) {
15456 let snapshot = self.buffer.read(cx).snapshot(cx);
15457 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15458 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15459 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15460 }
15461
15462 pub fn set_render_diff_hunk_controls(
15463 &mut self,
15464 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15465 cx: &mut Context<Self>,
15466 ) {
15467 self.render_diff_hunk_controls = render_diff_hunk_controls;
15468 cx.notify();
15469 }
15470
15471 pub fn stage_and_next(
15472 &mut self,
15473 _: &::git::StageAndNext,
15474 window: &mut Window,
15475 cx: &mut Context<Self>,
15476 ) {
15477 self.do_stage_or_unstage_and_next(true, window, cx);
15478 }
15479
15480 pub fn unstage_and_next(
15481 &mut self,
15482 _: &::git::UnstageAndNext,
15483 window: &mut Window,
15484 cx: &mut Context<Self>,
15485 ) {
15486 self.do_stage_or_unstage_and_next(false, window, cx);
15487 }
15488
15489 pub fn stage_or_unstage_diff_hunks(
15490 &mut self,
15491 stage: bool,
15492 ranges: Vec<Range<Anchor>>,
15493 cx: &mut Context<Self>,
15494 ) {
15495 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15496 cx.spawn(async move |this, cx| {
15497 task.await?;
15498 this.update(cx, |this, cx| {
15499 let snapshot = this.buffer.read(cx).snapshot(cx);
15500 let chunk_by = this
15501 .diff_hunks_in_ranges(&ranges, &snapshot)
15502 .chunk_by(|hunk| hunk.buffer_id);
15503 for (buffer_id, hunks) in &chunk_by {
15504 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15505 }
15506 })
15507 })
15508 .detach_and_log_err(cx);
15509 }
15510
15511 fn save_buffers_for_ranges_if_needed(
15512 &mut self,
15513 ranges: &[Range<Anchor>],
15514 cx: &mut Context<Editor>,
15515 ) -> Task<Result<()>> {
15516 let multibuffer = self.buffer.read(cx);
15517 let snapshot = multibuffer.read(cx);
15518 let buffer_ids: HashSet<_> = ranges
15519 .iter()
15520 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15521 .collect();
15522 drop(snapshot);
15523
15524 let mut buffers = HashSet::default();
15525 for buffer_id in buffer_ids {
15526 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15527 let buffer = buffer_entity.read(cx);
15528 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15529 {
15530 buffers.insert(buffer_entity);
15531 }
15532 }
15533 }
15534
15535 if let Some(project) = &self.project {
15536 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15537 } else {
15538 Task::ready(Ok(()))
15539 }
15540 }
15541
15542 fn do_stage_or_unstage_and_next(
15543 &mut self,
15544 stage: bool,
15545 window: &mut Window,
15546 cx: &mut Context<Self>,
15547 ) {
15548 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15549
15550 if ranges.iter().any(|range| range.start != range.end) {
15551 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15552 return;
15553 }
15554
15555 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15556 let snapshot = self.snapshot(window, cx);
15557 let position = self.selections.newest::<Point>(cx).head();
15558 let mut row = snapshot
15559 .buffer_snapshot
15560 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15561 .find(|hunk| hunk.row_range.start.0 > position.row)
15562 .map(|hunk| hunk.row_range.start);
15563
15564 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15565 // Outside of the project diff editor, wrap around to the beginning.
15566 if !all_diff_hunks_expanded {
15567 row = row.or_else(|| {
15568 snapshot
15569 .buffer_snapshot
15570 .diff_hunks_in_range(Point::zero()..position)
15571 .find(|hunk| hunk.row_range.end.0 < position.row)
15572 .map(|hunk| hunk.row_range.start)
15573 });
15574 }
15575
15576 if let Some(row) = row {
15577 let destination = Point::new(row.0, 0);
15578 let autoscroll = Autoscroll::center();
15579
15580 self.unfold_ranges(&[destination..destination], false, false, cx);
15581 self.change_selections(Some(autoscroll), window, cx, |s| {
15582 s.select_ranges([destination..destination]);
15583 });
15584 }
15585 }
15586
15587 fn do_stage_or_unstage(
15588 &self,
15589 stage: bool,
15590 buffer_id: BufferId,
15591 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15592 cx: &mut App,
15593 ) -> Option<()> {
15594 let project = self.project.as_ref()?;
15595 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15596 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15597 let buffer_snapshot = buffer.read(cx).snapshot();
15598 let file_exists = buffer_snapshot
15599 .file()
15600 .is_some_and(|file| file.disk_state().exists());
15601 diff.update(cx, |diff, cx| {
15602 diff.stage_or_unstage_hunks(
15603 stage,
15604 &hunks
15605 .map(|hunk| buffer_diff::DiffHunk {
15606 buffer_range: hunk.buffer_range,
15607 diff_base_byte_range: hunk.diff_base_byte_range,
15608 secondary_status: hunk.secondary_status,
15609 range: Point::zero()..Point::zero(), // unused
15610 })
15611 .collect::<Vec<_>>(),
15612 &buffer_snapshot,
15613 file_exists,
15614 cx,
15615 )
15616 });
15617 None
15618 }
15619
15620 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15621 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15622 self.buffer
15623 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15624 }
15625
15626 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15627 self.buffer.update(cx, |buffer, cx| {
15628 let ranges = vec![Anchor::min()..Anchor::max()];
15629 if !buffer.all_diff_hunks_expanded()
15630 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15631 {
15632 buffer.collapse_diff_hunks(ranges, cx);
15633 true
15634 } else {
15635 false
15636 }
15637 })
15638 }
15639
15640 fn toggle_diff_hunks_in_ranges(
15641 &mut self,
15642 ranges: Vec<Range<Anchor>>,
15643 cx: &mut Context<Editor>,
15644 ) {
15645 self.buffer.update(cx, |buffer, cx| {
15646 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15647 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15648 })
15649 }
15650
15651 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15652 self.buffer.update(cx, |buffer, cx| {
15653 let snapshot = buffer.snapshot(cx);
15654 let excerpt_id = range.end.excerpt_id;
15655 let point_range = range.to_point(&snapshot);
15656 let expand = !buffer.single_hunk_is_expanded(range, cx);
15657 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15658 })
15659 }
15660
15661 pub(crate) fn apply_all_diff_hunks(
15662 &mut self,
15663 _: &ApplyAllDiffHunks,
15664 window: &mut Window,
15665 cx: &mut Context<Self>,
15666 ) {
15667 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15668
15669 let buffers = self.buffer.read(cx).all_buffers();
15670 for branch_buffer in buffers {
15671 branch_buffer.update(cx, |branch_buffer, cx| {
15672 branch_buffer.merge_into_base(Vec::new(), cx);
15673 });
15674 }
15675
15676 if let Some(project) = self.project.clone() {
15677 self.save(true, project, window, cx).detach_and_log_err(cx);
15678 }
15679 }
15680
15681 pub(crate) fn apply_selected_diff_hunks(
15682 &mut self,
15683 _: &ApplyDiffHunk,
15684 window: &mut Window,
15685 cx: &mut Context<Self>,
15686 ) {
15687 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15688 let snapshot = self.snapshot(window, cx);
15689 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15690 let mut ranges_by_buffer = HashMap::default();
15691 self.transact(window, cx, |editor, _window, cx| {
15692 for hunk in hunks {
15693 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15694 ranges_by_buffer
15695 .entry(buffer.clone())
15696 .or_insert_with(Vec::new)
15697 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15698 }
15699 }
15700
15701 for (buffer, ranges) in ranges_by_buffer {
15702 buffer.update(cx, |buffer, cx| {
15703 buffer.merge_into_base(ranges, cx);
15704 });
15705 }
15706 });
15707
15708 if let Some(project) = self.project.clone() {
15709 self.save(true, project, window, cx).detach_and_log_err(cx);
15710 }
15711 }
15712
15713 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15714 if hovered != self.gutter_hovered {
15715 self.gutter_hovered = hovered;
15716 cx.notify();
15717 }
15718 }
15719
15720 pub fn insert_blocks(
15721 &mut self,
15722 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15723 autoscroll: Option<Autoscroll>,
15724 cx: &mut Context<Self>,
15725 ) -> Vec<CustomBlockId> {
15726 let blocks = self
15727 .display_map
15728 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15729 if let Some(autoscroll) = autoscroll {
15730 self.request_autoscroll(autoscroll, cx);
15731 }
15732 cx.notify();
15733 blocks
15734 }
15735
15736 pub fn resize_blocks(
15737 &mut self,
15738 heights: HashMap<CustomBlockId, u32>,
15739 autoscroll: Option<Autoscroll>,
15740 cx: &mut Context<Self>,
15741 ) {
15742 self.display_map
15743 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15744 if let Some(autoscroll) = autoscroll {
15745 self.request_autoscroll(autoscroll, cx);
15746 }
15747 cx.notify();
15748 }
15749
15750 pub fn replace_blocks(
15751 &mut self,
15752 renderers: HashMap<CustomBlockId, RenderBlock>,
15753 autoscroll: Option<Autoscroll>,
15754 cx: &mut Context<Self>,
15755 ) {
15756 self.display_map
15757 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15758 if let Some(autoscroll) = autoscroll {
15759 self.request_autoscroll(autoscroll, cx);
15760 }
15761 cx.notify();
15762 }
15763
15764 pub fn remove_blocks(
15765 &mut self,
15766 block_ids: HashSet<CustomBlockId>,
15767 autoscroll: Option<Autoscroll>,
15768 cx: &mut Context<Self>,
15769 ) {
15770 self.display_map.update(cx, |display_map, cx| {
15771 display_map.remove_blocks(block_ids, cx)
15772 });
15773 if let Some(autoscroll) = autoscroll {
15774 self.request_autoscroll(autoscroll, cx);
15775 }
15776 cx.notify();
15777 }
15778
15779 pub fn row_for_block(
15780 &self,
15781 block_id: CustomBlockId,
15782 cx: &mut Context<Self>,
15783 ) -> Option<DisplayRow> {
15784 self.display_map
15785 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15786 }
15787
15788 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15789 self.focused_block = Some(focused_block);
15790 }
15791
15792 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15793 self.focused_block.take()
15794 }
15795
15796 pub fn insert_creases(
15797 &mut self,
15798 creases: impl IntoIterator<Item = Crease<Anchor>>,
15799 cx: &mut Context<Self>,
15800 ) -> Vec<CreaseId> {
15801 self.display_map
15802 .update(cx, |map, cx| map.insert_creases(creases, cx))
15803 }
15804
15805 pub fn remove_creases(
15806 &mut self,
15807 ids: impl IntoIterator<Item = CreaseId>,
15808 cx: &mut Context<Self>,
15809 ) {
15810 self.display_map
15811 .update(cx, |map, cx| map.remove_creases(ids, cx));
15812 }
15813
15814 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15815 self.display_map
15816 .update(cx, |map, cx| map.snapshot(cx))
15817 .longest_row()
15818 }
15819
15820 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15821 self.display_map
15822 .update(cx, |map, cx| map.snapshot(cx))
15823 .max_point()
15824 }
15825
15826 pub fn text(&self, cx: &App) -> String {
15827 self.buffer.read(cx).read(cx).text()
15828 }
15829
15830 pub fn is_empty(&self, cx: &App) -> bool {
15831 self.buffer.read(cx).read(cx).is_empty()
15832 }
15833
15834 pub fn text_option(&self, cx: &App) -> Option<String> {
15835 let text = self.text(cx);
15836 let text = text.trim();
15837
15838 if text.is_empty() {
15839 return None;
15840 }
15841
15842 Some(text.to_string())
15843 }
15844
15845 pub fn set_text(
15846 &mut self,
15847 text: impl Into<Arc<str>>,
15848 window: &mut Window,
15849 cx: &mut Context<Self>,
15850 ) {
15851 self.transact(window, cx, |this, _, cx| {
15852 this.buffer
15853 .read(cx)
15854 .as_singleton()
15855 .expect("you can only call set_text on editors for singleton buffers")
15856 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15857 });
15858 }
15859
15860 pub fn display_text(&self, cx: &mut App) -> String {
15861 self.display_map
15862 .update(cx, |map, cx| map.snapshot(cx))
15863 .text()
15864 }
15865
15866 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15867 let mut wrap_guides = smallvec::smallvec![];
15868
15869 if self.show_wrap_guides == Some(false) {
15870 return wrap_guides;
15871 }
15872
15873 let settings = self.buffer.read(cx).language_settings(cx);
15874 if settings.show_wrap_guides {
15875 match self.soft_wrap_mode(cx) {
15876 SoftWrap::Column(soft_wrap) => {
15877 wrap_guides.push((soft_wrap as usize, true));
15878 }
15879 SoftWrap::Bounded(soft_wrap) => {
15880 wrap_guides.push((soft_wrap as usize, true));
15881 }
15882 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15883 }
15884 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15885 }
15886
15887 wrap_guides
15888 }
15889
15890 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15891 let settings = self.buffer.read(cx).language_settings(cx);
15892 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15893 match mode {
15894 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15895 SoftWrap::None
15896 }
15897 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15898 language_settings::SoftWrap::PreferredLineLength => {
15899 SoftWrap::Column(settings.preferred_line_length)
15900 }
15901 language_settings::SoftWrap::Bounded => {
15902 SoftWrap::Bounded(settings.preferred_line_length)
15903 }
15904 }
15905 }
15906
15907 pub fn set_soft_wrap_mode(
15908 &mut self,
15909 mode: language_settings::SoftWrap,
15910
15911 cx: &mut Context<Self>,
15912 ) {
15913 self.soft_wrap_mode_override = Some(mode);
15914 cx.notify();
15915 }
15916
15917 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15918 self.hard_wrap = hard_wrap;
15919 cx.notify();
15920 }
15921
15922 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15923 self.text_style_refinement = Some(style);
15924 }
15925
15926 /// called by the Element so we know what style we were most recently rendered with.
15927 pub(crate) fn set_style(
15928 &mut self,
15929 style: EditorStyle,
15930 window: &mut Window,
15931 cx: &mut Context<Self>,
15932 ) {
15933 let rem_size = window.rem_size();
15934 self.display_map.update(cx, |map, cx| {
15935 map.set_font(
15936 style.text.font(),
15937 style.text.font_size.to_pixels(rem_size),
15938 cx,
15939 )
15940 });
15941 self.style = Some(style);
15942 }
15943
15944 pub fn style(&self) -> Option<&EditorStyle> {
15945 self.style.as_ref()
15946 }
15947
15948 // Called by the element. This method is not designed to be called outside of the editor
15949 // element's layout code because it does not notify when rewrapping is computed synchronously.
15950 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15951 self.display_map
15952 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15953 }
15954
15955 pub fn set_soft_wrap(&mut self) {
15956 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15957 }
15958
15959 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15960 if self.soft_wrap_mode_override.is_some() {
15961 self.soft_wrap_mode_override.take();
15962 } else {
15963 let soft_wrap = match self.soft_wrap_mode(cx) {
15964 SoftWrap::GitDiff => return,
15965 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15966 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15967 language_settings::SoftWrap::None
15968 }
15969 };
15970 self.soft_wrap_mode_override = Some(soft_wrap);
15971 }
15972 cx.notify();
15973 }
15974
15975 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15976 let Some(workspace) = self.workspace() else {
15977 return;
15978 };
15979 let fs = workspace.read(cx).app_state().fs.clone();
15980 let current_show = TabBarSettings::get_global(cx).show;
15981 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15982 setting.show = Some(!current_show);
15983 });
15984 }
15985
15986 pub fn toggle_indent_guides(
15987 &mut self,
15988 _: &ToggleIndentGuides,
15989 _: &mut Window,
15990 cx: &mut Context<Self>,
15991 ) {
15992 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15993 self.buffer
15994 .read(cx)
15995 .language_settings(cx)
15996 .indent_guides
15997 .enabled
15998 });
15999 self.show_indent_guides = Some(!currently_enabled);
16000 cx.notify();
16001 }
16002
16003 fn should_show_indent_guides(&self) -> Option<bool> {
16004 self.show_indent_guides
16005 }
16006
16007 pub fn toggle_line_numbers(
16008 &mut self,
16009 _: &ToggleLineNumbers,
16010 _: &mut Window,
16011 cx: &mut Context<Self>,
16012 ) {
16013 let mut editor_settings = EditorSettings::get_global(cx).clone();
16014 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16015 EditorSettings::override_global(editor_settings, cx);
16016 }
16017
16018 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16019 if let Some(show_line_numbers) = self.show_line_numbers {
16020 return show_line_numbers;
16021 }
16022 EditorSettings::get_global(cx).gutter.line_numbers
16023 }
16024
16025 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16026 self.use_relative_line_numbers
16027 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16028 }
16029
16030 pub fn toggle_relative_line_numbers(
16031 &mut self,
16032 _: &ToggleRelativeLineNumbers,
16033 _: &mut Window,
16034 cx: &mut Context<Self>,
16035 ) {
16036 let is_relative = self.should_use_relative_line_numbers(cx);
16037 self.set_relative_line_number(Some(!is_relative), cx)
16038 }
16039
16040 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16041 self.use_relative_line_numbers = is_relative;
16042 cx.notify();
16043 }
16044
16045 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16046 self.show_gutter = show_gutter;
16047 cx.notify();
16048 }
16049
16050 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16051 self.show_scrollbars = show_scrollbars;
16052 cx.notify();
16053 }
16054
16055 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16056 self.show_line_numbers = Some(show_line_numbers);
16057 cx.notify();
16058 }
16059
16060 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16061 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16062 cx.notify();
16063 }
16064
16065 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16066 self.show_code_actions = Some(show_code_actions);
16067 cx.notify();
16068 }
16069
16070 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16071 self.show_runnables = Some(show_runnables);
16072 cx.notify();
16073 }
16074
16075 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16076 self.show_breakpoints = Some(show_breakpoints);
16077 cx.notify();
16078 }
16079
16080 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16081 if self.display_map.read(cx).masked != masked {
16082 self.display_map.update(cx, |map, _| map.masked = masked);
16083 }
16084 cx.notify()
16085 }
16086
16087 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16088 self.show_wrap_guides = Some(show_wrap_guides);
16089 cx.notify();
16090 }
16091
16092 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16093 self.show_indent_guides = Some(show_indent_guides);
16094 cx.notify();
16095 }
16096
16097 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16098 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16099 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16100 if let Some(dir) = file.abs_path(cx).parent() {
16101 return Some(dir.to_owned());
16102 }
16103 }
16104
16105 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16106 return Some(project_path.path.to_path_buf());
16107 }
16108 }
16109
16110 None
16111 }
16112
16113 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16114 self.active_excerpt(cx)?
16115 .1
16116 .read(cx)
16117 .file()
16118 .and_then(|f| f.as_local())
16119 }
16120
16121 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16122 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16123 let buffer = buffer.read(cx);
16124 if let Some(project_path) = buffer.project_path(cx) {
16125 let project = self.project.as_ref()?.read(cx);
16126 project.absolute_path(&project_path, cx)
16127 } else {
16128 buffer
16129 .file()
16130 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16131 }
16132 })
16133 }
16134
16135 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16136 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16137 let project_path = buffer.read(cx).project_path(cx)?;
16138 let project = self.project.as_ref()?.read(cx);
16139 let entry = project.entry_for_path(&project_path, cx)?;
16140 let path = entry.path.to_path_buf();
16141 Some(path)
16142 })
16143 }
16144
16145 pub fn reveal_in_finder(
16146 &mut self,
16147 _: &RevealInFileManager,
16148 _window: &mut Window,
16149 cx: &mut Context<Self>,
16150 ) {
16151 if let Some(target) = self.target_file(cx) {
16152 cx.reveal_path(&target.abs_path(cx));
16153 }
16154 }
16155
16156 pub fn copy_path(
16157 &mut self,
16158 _: &zed_actions::workspace::CopyPath,
16159 _window: &mut Window,
16160 cx: &mut Context<Self>,
16161 ) {
16162 if let Some(path) = self.target_file_abs_path(cx) {
16163 if let Some(path) = path.to_str() {
16164 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16165 }
16166 }
16167 }
16168
16169 pub fn copy_relative_path(
16170 &mut self,
16171 _: &zed_actions::workspace::CopyRelativePath,
16172 _window: &mut Window,
16173 cx: &mut Context<Self>,
16174 ) {
16175 if let Some(path) = self.target_file_path(cx) {
16176 if let Some(path) = path.to_str() {
16177 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16178 }
16179 }
16180 }
16181
16182 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16183 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16184 buffer.read(cx).project_path(cx)
16185 } else {
16186 None
16187 }
16188 }
16189
16190 // Returns true if the editor handled a go-to-line request
16191 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16192 maybe!({
16193 let breakpoint_store = self.breakpoint_store.as_ref()?;
16194
16195 let Some((_, _, active_position)) =
16196 breakpoint_store.read(cx).active_position().cloned()
16197 else {
16198 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16199 return None;
16200 };
16201
16202 let snapshot = self
16203 .project
16204 .as_ref()?
16205 .read(cx)
16206 .buffer_for_id(active_position.buffer_id?, cx)?
16207 .read(cx)
16208 .snapshot();
16209
16210 let mut handled = false;
16211 for (id, ExcerptRange { context, .. }) in self
16212 .buffer
16213 .read(cx)
16214 .excerpts_for_buffer(active_position.buffer_id?, cx)
16215 {
16216 if context.start.cmp(&active_position, &snapshot).is_ge()
16217 || context.end.cmp(&active_position, &snapshot).is_lt()
16218 {
16219 continue;
16220 }
16221 let snapshot = self.buffer.read(cx).snapshot(cx);
16222 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16223
16224 handled = true;
16225 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16226 self.go_to_line::<DebugCurrentRowHighlight>(
16227 multibuffer_anchor,
16228 Some(cx.theme().colors().editor_debugger_active_line_background),
16229 window,
16230 cx,
16231 );
16232
16233 cx.notify();
16234 }
16235 handled.then_some(())
16236 })
16237 .is_some()
16238 }
16239
16240 pub fn copy_file_name_without_extension(
16241 &mut self,
16242 _: &CopyFileNameWithoutExtension,
16243 _: &mut Window,
16244 cx: &mut Context<Self>,
16245 ) {
16246 if let Some(file) = self.target_file(cx) {
16247 if let Some(file_stem) = file.path().file_stem() {
16248 if let Some(name) = file_stem.to_str() {
16249 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16250 }
16251 }
16252 }
16253 }
16254
16255 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16256 if let Some(file) = self.target_file(cx) {
16257 if let Some(file_name) = file.path().file_name() {
16258 if let Some(name) = file_name.to_str() {
16259 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16260 }
16261 }
16262 }
16263 }
16264
16265 pub fn toggle_git_blame(
16266 &mut self,
16267 _: &::git::Blame,
16268 window: &mut Window,
16269 cx: &mut Context<Self>,
16270 ) {
16271 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16272
16273 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16274 self.start_git_blame(true, window, cx);
16275 }
16276
16277 cx.notify();
16278 }
16279
16280 pub fn toggle_git_blame_inline(
16281 &mut self,
16282 _: &ToggleGitBlameInline,
16283 window: &mut Window,
16284 cx: &mut Context<Self>,
16285 ) {
16286 self.toggle_git_blame_inline_internal(true, window, cx);
16287 cx.notify();
16288 }
16289
16290 pub fn open_git_blame_commit(
16291 &mut self,
16292 _: &OpenGitBlameCommit,
16293 window: &mut Window,
16294 cx: &mut Context<Self>,
16295 ) {
16296 self.open_git_blame_commit_internal(window, cx);
16297 }
16298
16299 fn open_git_blame_commit_internal(
16300 &mut self,
16301 window: &mut Window,
16302 cx: &mut Context<Self>,
16303 ) -> Option<()> {
16304 let blame = self.blame.as_ref()?;
16305 let snapshot = self.snapshot(window, cx);
16306 let cursor = self.selections.newest::<Point>(cx).head();
16307 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16308 let blame_entry = blame
16309 .update(cx, |blame, cx| {
16310 blame
16311 .blame_for_rows(
16312 &[RowInfo {
16313 buffer_id: Some(buffer.remote_id()),
16314 buffer_row: Some(point.row),
16315 ..Default::default()
16316 }],
16317 cx,
16318 )
16319 .next()
16320 })
16321 .flatten()?;
16322 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16323 let repo = blame.read(cx).repository(cx)?;
16324 let workspace = self.workspace()?.downgrade();
16325 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16326 None
16327 }
16328
16329 pub fn git_blame_inline_enabled(&self) -> bool {
16330 self.git_blame_inline_enabled
16331 }
16332
16333 pub fn toggle_selection_menu(
16334 &mut self,
16335 _: &ToggleSelectionMenu,
16336 _: &mut Window,
16337 cx: &mut Context<Self>,
16338 ) {
16339 self.show_selection_menu = self
16340 .show_selection_menu
16341 .map(|show_selections_menu| !show_selections_menu)
16342 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16343
16344 cx.notify();
16345 }
16346
16347 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16348 self.show_selection_menu
16349 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16350 }
16351
16352 fn start_git_blame(
16353 &mut self,
16354 user_triggered: bool,
16355 window: &mut Window,
16356 cx: &mut Context<Self>,
16357 ) {
16358 if let Some(project) = self.project.as_ref() {
16359 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16360 return;
16361 };
16362
16363 if buffer.read(cx).file().is_none() {
16364 return;
16365 }
16366
16367 let focused = self.focus_handle(cx).contains_focused(window, cx);
16368
16369 let project = project.clone();
16370 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16371 self.blame_subscription =
16372 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16373 self.blame = Some(blame);
16374 }
16375 }
16376
16377 fn toggle_git_blame_inline_internal(
16378 &mut self,
16379 user_triggered: bool,
16380 window: &mut Window,
16381 cx: &mut Context<Self>,
16382 ) {
16383 if self.git_blame_inline_enabled {
16384 self.git_blame_inline_enabled = false;
16385 self.show_git_blame_inline = false;
16386 self.show_git_blame_inline_delay_task.take();
16387 } else {
16388 self.git_blame_inline_enabled = true;
16389 self.start_git_blame_inline(user_triggered, window, cx);
16390 }
16391
16392 cx.notify();
16393 }
16394
16395 fn start_git_blame_inline(
16396 &mut self,
16397 user_triggered: bool,
16398 window: &mut Window,
16399 cx: &mut Context<Self>,
16400 ) {
16401 self.start_git_blame(user_triggered, window, cx);
16402
16403 if ProjectSettings::get_global(cx)
16404 .git
16405 .inline_blame_delay()
16406 .is_some()
16407 {
16408 self.start_inline_blame_timer(window, cx);
16409 } else {
16410 self.show_git_blame_inline = true
16411 }
16412 }
16413
16414 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16415 self.blame.as_ref()
16416 }
16417
16418 pub fn show_git_blame_gutter(&self) -> bool {
16419 self.show_git_blame_gutter
16420 }
16421
16422 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16423 self.show_git_blame_gutter && self.has_blame_entries(cx)
16424 }
16425
16426 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16427 self.show_git_blame_inline
16428 && (self.focus_handle.is_focused(window)
16429 || self
16430 .git_blame_inline_tooltip
16431 .as_ref()
16432 .and_then(|t| t.upgrade())
16433 .is_some())
16434 && !self.newest_selection_head_on_empty_line(cx)
16435 && self.has_blame_entries(cx)
16436 }
16437
16438 fn has_blame_entries(&self, cx: &App) -> bool {
16439 self.blame()
16440 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16441 }
16442
16443 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16444 let cursor_anchor = self.selections.newest_anchor().head();
16445
16446 let snapshot = self.buffer.read(cx).snapshot(cx);
16447 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16448
16449 snapshot.line_len(buffer_row) == 0
16450 }
16451
16452 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16453 let buffer_and_selection = maybe!({
16454 let selection = self.selections.newest::<Point>(cx);
16455 let selection_range = selection.range();
16456
16457 let multi_buffer = self.buffer().read(cx);
16458 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16459 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16460
16461 let (buffer, range, _) = if selection.reversed {
16462 buffer_ranges.first()
16463 } else {
16464 buffer_ranges.last()
16465 }?;
16466
16467 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16468 ..text::ToPoint::to_point(&range.end, &buffer).row;
16469 Some((
16470 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16471 selection,
16472 ))
16473 });
16474
16475 let Some((buffer, selection)) = buffer_and_selection else {
16476 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16477 };
16478
16479 let Some(project) = self.project.as_ref() else {
16480 return Task::ready(Err(anyhow!("editor does not have project")));
16481 };
16482
16483 project.update(cx, |project, cx| {
16484 project.get_permalink_to_line(&buffer, selection, cx)
16485 })
16486 }
16487
16488 pub fn copy_permalink_to_line(
16489 &mut self,
16490 _: &CopyPermalinkToLine,
16491 window: &mut Window,
16492 cx: &mut Context<Self>,
16493 ) {
16494 let permalink_task = self.get_permalink_to_line(cx);
16495 let workspace = self.workspace();
16496
16497 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16498 Ok(permalink) => {
16499 cx.update(|_, cx| {
16500 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16501 })
16502 .ok();
16503 }
16504 Err(err) => {
16505 let message = format!("Failed to copy permalink: {err}");
16506
16507 Err::<(), anyhow::Error>(err).log_err();
16508
16509 if let Some(workspace) = workspace {
16510 workspace
16511 .update_in(cx, |workspace, _, cx| {
16512 struct CopyPermalinkToLine;
16513
16514 workspace.show_toast(
16515 Toast::new(
16516 NotificationId::unique::<CopyPermalinkToLine>(),
16517 message,
16518 ),
16519 cx,
16520 )
16521 })
16522 .ok();
16523 }
16524 }
16525 })
16526 .detach();
16527 }
16528
16529 pub fn copy_file_location(
16530 &mut self,
16531 _: &CopyFileLocation,
16532 _: &mut Window,
16533 cx: &mut Context<Self>,
16534 ) {
16535 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16536 if let Some(file) = self.target_file(cx) {
16537 if let Some(path) = file.path().to_str() {
16538 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16539 }
16540 }
16541 }
16542
16543 pub fn open_permalink_to_line(
16544 &mut self,
16545 _: &OpenPermalinkToLine,
16546 window: &mut Window,
16547 cx: &mut Context<Self>,
16548 ) {
16549 let permalink_task = self.get_permalink_to_line(cx);
16550 let workspace = self.workspace();
16551
16552 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16553 Ok(permalink) => {
16554 cx.update(|_, cx| {
16555 cx.open_url(permalink.as_ref());
16556 })
16557 .ok();
16558 }
16559 Err(err) => {
16560 let message = format!("Failed to open permalink: {err}");
16561
16562 Err::<(), anyhow::Error>(err).log_err();
16563
16564 if let Some(workspace) = workspace {
16565 workspace
16566 .update(cx, |workspace, cx| {
16567 struct OpenPermalinkToLine;
16568
16569 workspace.show_toast(
16570 Toast::new(
16571 NotificationId::unique::<OpenPermalinkToLine>(),
16572 message,
16573 ),
16574 cx,
16575 )
16576 })
16577 .ok();
16578 }
16579 }
16580 })
16581 .detach();
16582 }
16583
16584 pub fn insert_uuid_v4(
16585 &mut self,
16586 _: &InsertUuidV4,
16587 window: &mut Window,
16588 cx: &mut Context<Self>,
16589 ) {
16590 self.insert_uuid(UuidVersion::V4, window, cx);
16591 }
16592
16593 pub fn insert_uuid_v7(
16594 &mut self,
16595 _: &InsertUuidV7,
16596 window: &mut Window,
16597 cx: &mut Context<Self>,
16598 ) {
16599 self.insert_uuid(UuidVersion::V7, window, cx);
16600 }
16601
16602 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16603 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16604 self.transact(window, cx, |this, window, cx| {
16605 let edits = this
16606 .selections
16607 .all::<Point>(cx)
16608 .into_iter()
16609 .map(|selection| {
16610 let uuid = match version {
16611 UuidVersion::V4 => uuid::Uuid::new_v4(),
16612 UuidVersion::V7 => uuid::Uuid::now_v7(),
16613 };
16614
16615 (selection.range(), uuid.to_string())
16616 });
16617 this.edit(edits, cx);
16618 this.refresh_inline_completion(true, false, window, cx);
16619 });
16620 }
16621
16622 pub fn open_selections_in_multibuffer(
16623 &mut self,
16624 _: &OpenSelectionsInMultibuffer,
16625 window: &mut Window,
16626 cx: &mut Context<Self>,
16627 ) {
16628 let multibuffer = self.buffer.read(cx);
16629
16630 let Some(buffer) = multibuffer.as_singleton() else {
16631 return;
16632 };
16633
16634 let Some(workspace) = self.workspace() else {
16635 return;
16636 };
16637
16638 let locations = self
16639 .selections
16640 .disjoint_anchors()
16641 .iter()
16642 .map(|range| Location {
16643 buffer: buffer.clone(),
16644 range: range.start.text_anchor..range.end.text_anchor,
16645 })
16646 .collect::<Vec<_>>();
16647
16648 let title = multibuffer.title(cx).to_string();
16649
16650 cx.spawn_in(window, async move |_, cx| {
16651 workspace.update_in(cx, |workspace, window, cx| {
16652 Self::open_locations_in_multibuffer(
16653 workspace,
16654 locations,
16655 format!("Selections for '{title}'"),
16656 false,
16657 MultibufferSelectionMode::All,
16658 window,
16659 cx,
16660 );
16661 })
16662 })
16663 .detach();
16664 }
16665
16666 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16667 /// last highlight added will be used.
16668 ///
16669 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16670 pub fn highlight_rows<T: 'static>(
16671 &mut self,
16672 range: Range<Anchor>,
16673 color: Hsla,
16674 should_autoscroll: bool,
16675 cx: &mut Context<Self>,
16676 ) {
16677 let snapshot = self.buffer().read(cx).snapshot(cx);
16678 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16679 let ix = row_highlights.binary_search_by(|highlight| {
16680 Ordering::Equal
16681 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16682 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16683 });
16684
16685 if let Err(mut ix) = ix {
16686 let index = post_inc(&mut self.highlight_order);
16687
16688 // If this range intersects with the preceding highlight, then merge it with
16689 // the preceding highlight. Otherwise insert a new highlight.
16690 let mut merged = false;
16691 if ix > 0 {
16692 let prev_highlight = &mut row_highlights[ix - 1];
16693 if prev_highlight
16694 .range
16695 .end
16696 .cmp(&range.start, &snapshot)
16697 .is_ge()
16698 {
16699 ix -= 1;
16700 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16701 prev_highlight.range.end = range.end;
16702 }
16703 merged = true;
16704 prev_highlight.index = index;
16705 prev_highlight.color = color;
16706 prev_highlight.should_autoscroll = should_autoscroll;
16707 }
16708 }
16709
16710 if !merged {
16711 row_highlights.insert(
16712 ix,
16713 RowHighlight {
16714 range: range.clone(),
16715 index,
16716 color,
16717 should_autoscroll,
16718 },
16719 );
16720 }
16721
16722 // If any of the following highlights intersect with this one, merge them.
16723 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16724 let highlight = &row_highlights[ix];
16725 if next_highlight
16726 .range
16727 .start
16728 .cmp(&highlight.range.end, &snapshot)
16729 .is_le()
16730 {
16731 if next_highlight
16732 .range
16733 .end
16734 .cmp(&highlight.range.end, &snapshot)
16735 .is_gt()
16736 {
16737 row_highlights[ix].range.end = next_highlight.range.end;
16738 }
16739 row_highlights.remove(ix + 1);
16740 } else {
16741 break;
16742 }
16743 }
16744 }
16745 }
16746
16747 /// Remove any highlighted row ranges of the given type that intersect the
16748 /// given ranges.
16749 pub fn remove_highlighted_rows<T: 'static>(
16750 &mut self,
16751 ranges_to_remove: Vec<Range<Anchor>>,
16752 cx: &mut Context<Self>,
16753 ) {
16754 let snapshot = self.buffer().read(cx).snapshot(cx);
16755 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16756 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16757 row_highlights.retain(|highlight| {
16758 while let Some(range_to_remove) = ranges_to_remove.peek() {
16759 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16760 Ordering::Less | Ordering::Equal => {
16761 ranges_to_remove.next();
16762 }
16763 Ordering::Greater => {
16764 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16765 Ordering::Less | Ordering::Equal => {
16766 return false;
16767 }
16768 Ordering::Greater => break,
16769 }
16770 }
16771 }
16772 }
16773
16774 true
16775 })
16776 }
16777
16778 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16779 pub fn clear_row_highlights<T: 'static>(&mut self) {
16780 self.highlighted_rows.remove(&TypeId::of::<T>());
16781 }
16782
16783 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16784 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16785 self.highlighted_rows
16786 .get(&TypeId::of::<T>())
16787 .map_or(&[] as &[_], |vec| vec.as_slice())
16788 .iter()
16789 .map(|highlight| (highlight.range.clone(), highlight.color))
16790 }
16791
16792 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16793 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16794 /// Allows to ignore certain kinds of highlights.
16795 pub fn highlighted_display_rows(
16796 &self,
16797 window: &mut Window,
16798 cx: &mut App,
16799 ) -> BTreeMap<DisplayRow, LineHighlight> {
16800 let snapshot = self.snapshot(window, cx);
16801 let mut used_highlight_orders = HashMap::default();
16802 self.highlighted_rows
16803 .iter()
16804 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16805 .fold(
16806 BTreeMap::<DisplayRow, LineHighlight>::new(),
16807 |mut unique_rows, highlight| {
16808 let start = highlight.range.start.to_display_point(&snapshot);
16809 let end = highlight.range.end.to_display_point(&snapshot);
16810 let start_row = start.row().0;
16811 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16812 && end.column() == 0
16813 {
16814 end.row().0.saturating_sub(1)
16815 } else {
16816 end.row().0
16817 };
16818 for row in start_row..=end_row {
16819 let used_index =
16820 used_highlight_orders.entry(row).or_insert(highlight.index);
16821 if highlight.index >= *used_index {
16822 *used_index = highlight.index;
16823 unique_rows.insert(DisplayRow(row), highlight.color.into());
16824 }
16825 }
16826 unique_rows
16827 },
16828 )
16829 }
16830
16831 pub fn highlighted_display_row_for_autoscroll(
16832 &self,
16833 snapshot: &DisplaySnapshot,
16834 ) -> Option<DisplayRow> {
16835 self.highlighted_rows
16836 .values()
16837 .flat_map(|highlighted_rows| highlighted_rows.iter())
16838 .filter_map(|highlight| {
16839 if highlight.should_autoscroll {
16840 Some(highlight.range.start.to_display_point(snapshot).row())
16841 } else {
16842 None
16843 }
16844 })
16845 .min()
16846 }
16847
16848 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16849 self.highlight_background::<SearchWithinRange>(
16850 ranges,
16851 |colors| colors.editor_document_highlight_read_background,
16852 cx,
16853 )
16854 }
16855
16856 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16857 self.breadcrumb_header = Some(new_header);
16858 }
16859
16860 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16861 self.clear_background_highlights::<SearchWithinRange>(cx);
16862 }
16863
16864 pub fn highlight_background<T: 'static>(
16865 &mut self,
16866 ranges: &[Range<Anchor>],
16867 color_fetcher: fn(&ThemeColors) -> Hsla,
16868 cx: &mut Context<Self>,
16869 ) {
16870 self.background_highlights
16871 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16872 self.scrollbar_marker_state.dirty = true;
16873 cx.notify();
16874 }
16875
16876 pub fn clear_background_highlights<T: 'static>(
16877 &mut self,
16878 cx: &mut Context<Self>,
16879 ) -> Option<BackgroundHighlight> {
16880 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16881 if !text_highlights.1.is_empty() {
16882 self.scrollbar_marker_state.dirty = true;
16883 cx.notify();
16884 }
16885 Some(text_highlights)
16886 }
16887
16888 pub fn highlight_gutter<T: 'static>(
16889 &mut self,
16890 ranges: &[Range<Anchor>],
16891 color_fetcher: fn(&App) -> Hsla,
16892 cx: &mut Context<Self>,
16893 ) {
16894 self.gutter_highlights
16895 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16896 cx.notify();
16897 }
16898
16899 pub fn clear_gutter_highlights<T: 'static>(
16900 &mut self,
16901 cx: &mut Context<Self>,
16902 ) -> Option<GutterHighlight> {
16903 cx.notify();
16904 self.gutter_highlights.remove(&TypeId::of::<T>())
16905 }
16906
16907 #[cfg(feature = "test-support")]
16908 pub fn all_text_background_highlights(
16909 &self,
16910 window: &mut Window,
16911 cx: &mut Context<Self>,
16912 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16913 let snapshot = self.snapshot(window, cx);
16914 let buffer = &snapshot.buffer_snapshot;
16915 let start = buffer.anchor_before(0);
16916 let end = buffer.anchor_after(buffer.len());
16917 let theme = cx.theme().colors();
16918 self.background_highlights_in_range(start..end, &snapshot, theme)
16919 }
16920
16921 #[cfg(feature = "test-support")]
16922 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16923 let snapshot = self.buffer().read(cx).snapshot(cx);
16924
16925 let highlights = self
16926 .background_highlights
16927 .get(&TypeId::of::<items::BufferSearchHighlights>());
16928
16929 if let Some((_color, ranges)) = highlights {
16930 ranges
16931 .iter()
16932 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16933 .collect_vec()
16934 } else {
16935 vec![]
16936 }
16937 }
16938
16939 fn document_highlights_for_position<'a>(
16940 &'a self,
16941 position: Anchor,
16942 buffer: &'a MultiBufferSnapshot,
16943 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16944 let read_highlights = self
16945 .background_highlights
16946 .get(&TypeId::of::<DocumentHighlightRead>())
16947 .map(|h| &h.1);
16948 let write_highlights = self
16949 .background_highlights
16950 .get(&TypeId::of::<DocumentHighlightWrite>())
16951 .map(|h| &h.1);
16952 let left_position = position.bias_left(buffer);
16953 let right_position = position.bias_right(buffer);
16954 read_highlights
16955 .into_iter()
16956 .chain(write_highlights)
16957 .flat_map(move |ranges| {
16958 let start_ix = match ranges.binary_search_by(|probe| {
16959 let cmp = probe.end.cmp(&left_position, buffer);
16960 if cmp.is_ge() {
16961 Ordering::Greater
16962 } else {
16963 Ordering::Less
16964 }
16965 }) {
16966 Ok(i) | Err(i) => i,
16967 };
16968
16969 ranges[start_ix..]
16970 .iter()
16971 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16972 })
16973 }
16974
16975 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16976 self.background_highlights
16977 .get(&TypeId::of::<T>())
16978 .map_or(false, |(_, highlights)| !highlights.is_empty())
16979 }
16980
16981 pub fn background_highlights_in_range(
16982 &self,
16983 search_range: Range<Anchor>,
16984 display_snapshot: &DisplaySnapshot,
16985 theme: &ThemeColors,
16986 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16987 let mut results = Vec::new();
16988 for (color_fetcher, ranges) in self.background_highlights.values() {
16989 let color = color_fetcher(theme);
16990 let start_ix = match ranges.binary_search_by(|probe| {
16991 let cmp = probe
16992 .end
16993 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16994 if cmp.is_gt() {
16995 Ordering::Greater
16996 } else {
16997 Ordering::Less
16998 }
16999 }) {
17000 Ok(i) | Err(i) => i,
17001 };
17002 for range in &ranges[start_ix..] {
17003 if range
17004 .start
17005 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17006 .is_ge()
17007 {
17008 break;
17009 }
17010
17011 let start = range.start.to_display_point(display_snapshot);
17012 let end = range.end.to_display_point(display_snapshot);
17013 results.push((start..end, color))
17014 }
17015 }
17016 results
17017 }
17018
17019 pub fn background_highlight_row_ranges<T: 'static>(
17020 &self,
17021 search_range: Range<Anchor>,
17022 display_snapshot: &DisplaySnapshot,
17023 count: usize,
17024 ) -> Vec<RangeInclusive<DisplayPoint>> {
17025 let mut results = Vec::new();
17026 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17027 return vec![];
17028 };
17029
17030 let start_ix = match ranges.binary_search_by(|probe| {
17031 let cmp = probe
17032 .end
17033 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17034 if cmp.is_gt() {
17035 Ordering::Greater
17036 } else {
17037 Ordering::Less
17038 }
17039 }) {
17040 Ok(i) | Err(i) => i,
17041 };
17042 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17043 if let (Some(start_display), Some(end_display)) = (start, end) {
17044 results.push(
17045 start_display.to_display_point(display_snapshot)
17046 ..=end_display.to_display_point(display_snapshot),
17047 );
17048 }
17049 };
17050 let mut start_row: Option<Point> = None;
17051 let mut end_row: Option<Point> = None;
17052 if ranges.len() > count {
17053 return Vec::new();
17054 }
17055 for range in &ranges[start_ix..] {
17056 if range
17057 .start
17058 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17059 .is_ge()
17060 {
17061 break;
17062 }
17063 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17064 if let Some(current_row) = &end_row {
17065 if end.row == current_row.row {
17066 continue;
17067 }
17068 }
17069 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17070 if start_row.is_none() {
17071 assert_eq!(end_row, None);
17072 start_row = Some(start);
17073 end_row = Some(end);
17074 continue;
17075 }
17076 if let Some(current_end) = end_row.as_mut() {
17077 if start.row > current_end.row + 1 {
17078 push_region(start_row, end_row);
17079 start_row = Some(start);
17080 end_row = Some(end);
17081 } else {
17082 // Merge two hunks.
17083 *current_end = end;
17084 }
17085 } else {
17086 unreachable!();
17087 }
17088 }
17089 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17090 push_region(start_row, end_row);
17091 results
17092 }
17093
17094 pub fn gutter_highlights_in_range(
17095 &self,
17096 search_range: Range<Anchor>,
17097 display_snapshot: &DisplaySnapshot,
17098 cx: &App,
17099 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17100 let mut results = Vec::new();
17101 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17102 let color = color_fetcher(cx);
17103 let start_ix = match ranges.binary_search_by(|probe| {
17104 let cmp = probe
17105 .end
17106 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17107 if cmp.is_gt() {
17108 Ordering::Greater
17109 } else {
17110 Ordering::Less
17111 }
17112 }) {
17113 Ok(i) | Err(i) => i,
17114 };
17115 for range in &ranges[start_ix..] {
17116 if range
17117 .start
17118 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17119 .is_ge()
17120 {
17121 break;
17122 }
17123
17124 let start = range.start.to_display_point(display_snapshot);
17125 let end = range.end.to_display_point(display_snapshot);
17126 results.push((start..end, color))
17127 }
17128 }
17129 results
17130 }
17131
17132 /// Get the text ranges corresponding to the redaction query
17133 pub fn redacted_ranges(
17134 &self,
17135 search_range: Range<Anchor>,
17136 display_snapshot: &DisplaySnapshot,
17137 cx: &App,
17138 ) -> Vec<Range<DisplayPoint>> {
17139 display_snapshot
17140 .buffer_snapshot
17141 .redacted_ranges(search_range, |file| {
17142 if let Some(file) = file {
17143 file.is_private()
17144 && EditorSettings::get(
17145 Some(SettingsLocation {
17146 worktree_id: file.worktree_id(cx),
17147 path: file.path().as_ref(),
17148 }),
17149 cx,
17150 )
17151 .redact_private_values
17152 } else {
17153 false
17154 }
17155 })
17156 .map(|range| {
17157 range.start.to_display_point(display_snapshot)
17158 ..range.end.to_display_point(display_snapshot)
17159 })
17160 .collect()
17161 }
17162
17163 pub fn highlight_text<T: 'static>(
17164 &mut self,
17165 ranges: Vec<Range<Anchor>>,
17166 style: HighlightStyle,
17167 cx: &mut Context<Self>,
17168 ) {
17169 self.display_map.update(cx, |map, _| {
17170 map.highlight_text(TypeId::of::<T>(), ranges, style)
17171 });
17172 cx.notify();
17173 }
17174
17175 pub(crate) fn highlight_inlays<T: 'static>(
17176 &mut self,
17177 highlights: Vec<InlayHighlight>,
17178 style: HighlightStyle,
17179 cx: &mut Context<Self>,
17180 ) {
17181 self.display_map.update(cx, |map, _| {
17182 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17183 });
17184 cx.notify();
17185 }
17186
17187 pub fn text_highlights<'a, T: 'static>(
17188 &'a self,
17189 cx: &'a App,
17190 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17191 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17192 }
17193
17194 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17195 let cleared = self
17196 .display_map
17197 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17198 if cleared {
17199 cx.notify();
17200 }
17201 }
17202
17203 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17204 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17205 && self.focus_handle.is_focused(window)
17206 }
17207
17208 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17209 self.show_cursor_when_unfocused = is_enabled;
17210 cx.notify();
17211 }
17212
17213 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17214 cx.notify();
17215 }
17216
17217 fn on_buffer_event(
17218 &mut self,
17219 multibuffer: &Entity<MultiBuffer>,
17220 event: &multi_buffer::Event,
17221 window: &mut Window,
17222 cx: &mut Context<Self>,
17223 ) {
17224 match event {
17225 multi_buffer::Event::Edited {
17226 singleton_buffer_edited,
17227 edited_buffer: buffer_edited,
17228 } => {
17229 self.scrollbar_marker_state.dirty = true;
17230 self.active_indent_guides_state.dirty = true;
17231 self.refresh_active_diagnostics(cx);
17232 self.refresh_code_actions(window, cx);
17233 if self.has_active_inline_completion() {
17234 self.update_visible_inline_completion(window, cx);
17235 }
17236 if let Some(buffer) = buffer_edited {
17237 let buffer_id = buffer.read(cx).remote_id();
17238 if !self.registered_buffers.contains_key(&buffer_id) {
17239 if let Some(project) = self.project.as_ref() {
17240 project.update(cx, |project, cx| {
17241 self.registered_buffers.insert(
17242 buffer_id,
17243 project.register_buffer_with_language_servers(&buffer, cx),
17244 );
17245 })
17246 }
17247 }
17248 }
17249 cx.emit(EditorEvent::BufferEdited);
17250 cx.emit(SearchEvent::MatchesInvalidated);
17251 if *singleton_buffer_edited {
17252 if let Some(project) = &self.project {
17253 #[allow(clippy::mutable_key_type)]
17254 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17255 multibuffer
17256 .all_buffers()
17257 .into_iter()
17258 .filter_map(|buffer| {
17259 buffer.update(cx, |buffer, cx| {
17260 let language = buffer.language()?;
17261 let should_discard = project.update(cx, |project, cx| {
17262 project.is_local()
17263 && !project.has_language_servers_for(buffer, cx)
17264 });
17265 should_discard.not().then_some(language.clone())
17266 })
17267 })
17268 .collect::<HashSet<_>>()
17269 });
17270 if !languages_affected.is_empty() {
17271 self.refresh_inlay_hints(
17272 InlayHintRefreshReason::BufferEdited(languages_affected),
17273 cx,
17274 );
17275 }
17276 }
17277 }
17278
17279 let Some(project) = &self.project else { return };
17280 let (telemetry, is_via_ssh) = {
17281 let project = project.read(cx);
17282 let telemetry = project.client().telemetry().clone();
17283 let is_via_ssh = project.is_via_ssh();
17284 (telemetry, is_via_ssh)
17285 };
17286 refresh_linked_ranges(self, window, cx);
17287 telemetry.log_edit_event("editor", is_via_ssh);
17288 }
17289 multi_buffer::Event::ExcerptsAdded {
17290 buffer,
17291 predecessor,
17292 excerpts,
17293 } => {
17294 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17295 let buffer_id = buffer.read(cx).remote_id();
17296 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17297 if let Some(project) = &self.project {
17298 get_uncommitted_diff_for_buffer(
17299 project,
17300 [buffer.clone()],
17301 self.buffer.clone(),
17302 cx,
17303 )
17304 .detach();
17305 }
17306 }
17307 cx.emit(EditorEvent::ExcerptsAdded {
17308 buffer: buffer.clone(),
17309 predecessor: *predecessor,
17310 excerpts: excerpts.clone(),
17311 });
17312 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17313 }
17314 multi_buffer::Event::ExcerptsRemoved { ids } => {
17315 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17316 let buffer = self.buffer.read(cx);
17317 self.registered_buffers
17318 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17319 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17320 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17321 }
17322 multi_buffer::Event::ExcerptsEdited {
17323 excerpt_ids,
17324 buffer_ids,
17325 } => {
17326 self.display_map.update(cx, |map, cx| {
17327 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17328 });
17329 cx.emit(EditorEvent::ExcerptsEdited {
17330 ids: excerpt_ids.clone(),
17331 })
17332 }
17333 multi_buffer::Event::ExcerptsExpanded { ids } => {
17334 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17335 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17336 }
17337 multi_buffer::Event::Reparsed(buffer_id) => {
17338 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17339 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17340
17341 cx.emit(EditorEvent::Reparsed(*buffer_id));
17342 }
17343 multi_buffer::Event::DiffHunksToggled => {
17344 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17345 }
17346 multi_buffer::Event::LanguageChanged(buffer_id) => {
17347 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17348 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17349 cx.emit(EditorEvent::Reparsed(*buffer_id));
17350 cx.notify();
17351 }
17352 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17353 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17354 multi_buffer::Event::FileHandleChanged
17355 | multi_buffer::Event::Reloaded
17356 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17357 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17358 multi_buffer::Event::DiagnosticsUpdated => {
17359 self.refresh_active_diagnostics(cx);
17360 self.refresh_inline_diagnostics(true, window, cx);
17361 self.scrollbar_marker_state.dirty = true;
17362 cx.notify();
17363 }
17364 _ => {}
17365 };
17366 }
17367
17368 fn on_display_map_changed(
17369 &mut self,
17370 _: Entity<DisplayMap>,
17371 _: &mut Window,
17372 cx: &mut Context<Self>,
17373 ) {
17374 cx.notify();
17375 }
17376
17377 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17378 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17379 self.update_edit_prediction_settings(cx);
17380 self.refresh_inline_completion(true, false, window, cx);
17381 self.refresh_inlay_hints(
17382 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17383 self.selections.newest_anchor().head(),
17384 &self.buffer.read(cx).snapshot(cx),
17385 cx,
17386 )),
17387 cx,
17388 );
17389
17390 let old_cursor_shape = self.cursor_shape;
17391
17392 {
17393 let editor_settings = EditorSettings::get_global(cx);
17394 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17395 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17396 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17397 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17398 }
17399
17400 if old_cursor_shape != self.cursor_shape {
17401 cx.emit(EditorEvent::CursorShapeChanged);
17402 }
17403
17404 let project_settings = ProjectSettings::get_global(cx);
17405 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17406
17407 if self.mode.is_full() {
17408 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17409 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17410 if self.show_inline_diagnostics != show_inline_diagnostics {
17411 self.show_inline_diagnostics = show_inline_diagnostics;
17412 self.refresh_inline_diagnostics(false, window, cx);
17413 }
17414
17415 if self.git_blame_inline_enabled != inline_blame_enabled {
17416 self.toggle_git_blame_inline_internal(false, window, cx);
17417 }
17418 }
17419
17420 cx.notify();
17421 }
17422
17423 pub fn set_searchable(&mut self, searchable: bool) {
17424 self.searchable = searchable;
17425 }
17426
17427 pub fn searchable(&self) -> bool {
17428 self.searchable
17429 }
17430
17431 fn open_proposed_changes_editor(
17432 &mut self,
17433 _: &OpenProposedChangesEditor,
17434 window: &mut Window,
17435 cx: &mut Context<Self>,
17436 ) {
17437 let Some(workspace) = self.workspace() else {
17438 cx.propagate();
17439 return;
17440 };
17441
17442 let selections = self.selections.all::<usize>(cx);
17443 let multi_buffer = self.buffer.read(cx);
17444 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17445 let mut new_selections_by_buffer = HashMap::default();
17446 for selection in selections {
17447 for (buffer, range, _) in
17448 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17449 {
17450 let mut range = range.to_point(buffer);
17451 range.start.column = 0;
17452 range.end.column = buffer.line_len(range.end.row);
17453 new_selections_by_buffer
17454 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17455 .or_insert(Vec::new())
17456 .push(range)
17457 }
17458 }
17459
17460 let proposed_changes_buffers = new_selections_by_buffer
17461 .into_iter()
17462 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17463 .collect::<Vec<_>>();
17464 let proposed_changes_editor = cx.new(|cx| {
17465 ProposedChangesEditor::new(
17466 "Proposed changes",
17467 proposed_changes_buffers,
17468 self.project.clone(),
17469 window,
17470 cx,
17471 )
17472 });
17473
17474 window.defer(cx, move |window, cx| {
17475 workspace.update(cx, |workspace, cx| {
17476 workspace.active_pane().update(cx, |pane, cx| {
17477 pane.add_item(
17478 Box::new(proposed_changes_editor),
17479 true,
17480 true,
17481 None,
17482 window,
17483 cx,
17484 );
17485 });
17486 });
17487 });
17488 }
17489
17490 pub fn open_excerpts_in_split(
17491 &mut self,
17492 _: &OpenExcerptsSplit,
17493 window: &mut Window,
17494 cx: &mut Context<Self>,
17495 ) {
17496 self.open_excerpts_common(None, true, window, cx)
17497 }
17498
17499 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17500 self.open_excerpts_common(None, false, window, cx)
17501 }
17502
17503 fn open_excerpts_common(
17504 &mut self,
17505 jump_data: Option<JumpData>,
17506 split: bool,
17507 window: &mut Window,
17508 cx: &mut Context<Self>,
17509 ) {
17510 let Some(workspace) = self.workspace() else {
17511 cx.propagate();
17512 return;
17513 };
17514
17515 if self.buffer.read(cx).is_singleton() {
17516 cx.propagate();
17517 return;
17518 }
17519
17520 let mut new_selections_by_buffer = HashMap::default();
17521 match &jump_data {
17522 Some(JumpData::MultiBufferPoint {
17523 excerpt_id,
17524 position,
17525 anchor,
17526 line_offset_from_top,
17527 }) => {
17528 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17529 if let Some(buffer) = multi_buffer_snapshot
17530 .buffer_id_for_excerpt(*excerpt_id)
17531 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17532 {
17533 let buffer_snapshot = buffer.read(cx).snapshot();
17534 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17535 language::ToPoint::to_point(anchor, &buffer_snapshot)
17536 } else {
17537 buffer_snapshot.clip_point(*position, Bias::Left)
17538 };
17539 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17540 new_selections_by_buffer.insert(
17541 buffer,
17542 (
17543 vec![jump_to_offset..jump_to_offset],
17544 Some(*line_offset_from_top),
17545 ),
17546 );
17547 }
17548 }
17549 Some(JumpData::MultiBufferRow {
17550 row,
17551 line_offset_from_top,
17552 }) => {
17553 let point = MultiBufferPoint::new(row.0, 0);
17554 if let Some((buffer, buffer_point, _)) =
17555 self.buffer.read(cx).point_to_buffer_point(point, cx)
17556 {
17557 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17558 new_selections_by_buffer
17559 .entry(buffer)
17560 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17561 .0
17562 .push(buffer_offset..buffer_offset)
17563 }
17564 }
17565 None => {
17566 let selections = self.selections.all::<usize>(cx);
17567 let multi_buffer = self.buffer.read(cx);
17568 for selection in selections {
17569 for (snapshot, range, _, anchor) in multi_buffer
17570 .snapshot(cx)
17571 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17572 {
17573 if let Some(anchor) = anchor {
17574 // selection is in a deleted hunk
17575 let Some(buffer_id) = anchor.buffer_id else {
17576 continue;
17577 };
17578 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17579 continue;
17580 };
17581 let offset = text::ToOffset::to_offset(
17582 &anchor.text_anchor,
17583 &buffer_handle.read(cx).snapshot(),
17584 );
17585 let range = offset..offset;
17586 new_selections_by_buffer
17587 .entry(buffer_handle)
17588 .or_insert((Vec::new(), None))
17589 .0
17590 .push(range)
17591 } else {
17592 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17593 else {
17594 continue;
17595 };
17596 new_selections_by_buffer
17597 .entry(buffer_handle)
17598 .or_insert((Vec::new(), None))
17599 .0
17600 .push(range)
17601 }
17602 }
17603 }
17604 }
17605 }
17606
17607 new_selections_by_buffer
17608 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17609
17610 if new_selections_by_buffer.is_empty() {
17611 return;
17612 }
17613
17614 // We defer the pane interaction because we ourselves are a workspace item
17615 // and activating a new item causes the pane to call a method on us reentrantly,
17616 // which panics if we're on the stack.
17617 window.defer(cx, move |window, cx| {
17618 workspace.update(cx, |workspace, cx| {
17619 let pane = if split {
17620 workspace.adjacent_pane(window, cx)
17621 } else {
17622 workspace.active_pane().clone()
17623 };
17624
17625 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17626 let editor = buffer
17627 .read(cx)
17628 .file()
17629 .is_none()
17630 .then(|| {
17631 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17632 // so `workspace.open_project_item` will never find them, always opening a new editor.
17633 // Instead, we try to activate the existing editor in the pane first.
17634 let (editor, pane_item_index) =
17635 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17636 let editor = item.downcast::<Editor>()?;
17637 let singleton_buffer =
17638 editor.read(cx).buffer().read(cx).as_singleton()?;
17639 if singleton_buffer == buffer {
17640 Some((editor, i))
17641 } else {
17642 None
17643 }
17644 })?;
17645 pane.update(cx, |pane, cx| {
17646 pane.activate_item(pane_item_index, true, true, window, cx)
17647 });
17648 Some(editor)
17649 })
17650 .flatten()
17651 .unwrap_or_else(|| {
17652 workspace.open_project_item::<Self>(
17653 pane.clone(),
17654 buffer,
17655 true,
17656 true,
17657 window,
17658 cx,
17659 )
17660 });
17661
17662 editor.update(cx, |editor, cx| {
17663 let autoscroll = match scroll_offset {
17664 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17665 None => Autoscroll::newest(),
17666 };
17667 let nav_history = editor.nav_history.take();
17668 editor.change_selections(Some(autoscroll), window, cx, |s| {
17669 s.select_ranges(ranges);
17670 });
17671 editor.nav_history = nav_history;
17672 });
17673 }
17674 })
17675 });
17676 }
17677
17678 // For now, don't allow opening excerpts in buffers that aren't backed by
17679 // regular project files.
17680 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17681 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17682 }
17683
17684 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17685 let snapshot = self.buffer.read(cx).read(cx);
17686 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17687 Some(
17688 ranges
17689 .iter()
17690 .map(move |range| {
17691 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17692 })
17693 .collect(),
17694 )
17695 }
17696
17697 fn selection_replacement_ranges(
17698 &self,
17699 range: Range<OffsetUtf16>,
17700 cx: &mut App,
17701 ) -> Vec<Range<OffsetUtf16>> {
17702 let selections = self.selections.all::<OffsetUtf16>(cx);
17703 let newest_selection = selections
17704 .iter()
17705 .max_by_key(|selection| selection.id)
17706 .unwrap();
17707 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17708 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17709 let snapshot = self.buffer.read(cx).read(cx);
17710 selections
17711 .into_iter()
17712 .map(|mut selection| {
17713 selection.start.0 =
17714 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17715 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17716 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17717 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17718 })
17719 .collect()
17720 }
17721
17722 fn report_editor_event(
17723 &self,
17724 event_type: &'static str,
17725 file_extension: Option<String>,
17726 cx: &App,
17727 ) {
17728 if cfg!(any(test, feature = "test-support")) {
17729 return;
17730 }
17731
17732 let Some(project) = &self.project else { return };
17733
17734 // If None, we are in a file without an extension
17735 let file = self
17736 .buffer
17737 .read(cx)
17738 .as_singleton()
17739 .and_then(|b| b.read(cx).file());
17740 let file_extension = file_extension.or(file
17741 .as_ref()
17742 .and_then(|file| Path::new(file.file_name(cx)).extension())
17743 .and_then(|e| e.to_str())
17744 .map(|a| a.to_string()));
17745
17746 let vim_mode = cx
17747 .global::<SettingsStore>()
17748 .raw_user_settings()
17749 .get("vim_mode")
17750 == Some(&serde_json::Value::Bool(true));
17751
17752 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17753 let copilot_enabled = edit_predictions_provider
17754 == language::language_settings::EditPredictionProvider::Copilot;
17755 let copilot_enabled_for_language = self
17756 .buffer
17757 .read(cx)
17758 .language_settings(cx)
17759 .show_edit_predictions;
17760
17761 let project = project.read(cx);
17762 telemetry::event!(
17763 event_type,
17764 file_extension,
17765 vim_mode,
17766 copilot_enabled,
17767 copilot_enabled_for_language,
17768 edit_predictions_provider,
17769 is_via_ssh = project.is_via_ssh(),
17770 );
17771 }
17772
17773 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17774 /// with each line being an array of {text, highlight} objects.
17775 fn copy_highlight_json(
17776 &mut self,
17777 _: &CopyHighlightJson,
17778 window: &mut Window,
17779 cx: &mut Context<Self>,
17780 ) {
17781 #[derive(Serialize)]
17782 struct Chunk<'a> {
17783 text: String,
17784 highlight: Option<&'a str>,
17785 }
17786
17787 let snapshot = self.buffer.read(cx).snapshot(cx);
17788 let range = self
17789 .selected_text_range(false, window, cx)
17790 .and_then(|selection| {
17791 if selection.range.is_empty() {
17792 None
17793 } else {
17794 Some(selection.range)
17795 }
17796 })
17797 .unwrap_or_else(|| 0..snapshot.len());
17798
17799 let chunks = snapshot.chunks(range, true);
17800 let mut lines = Vec::new();
17801 let mut line: VecDeque<Chunk> = VecDeque::new();
17802
17803 let Some(style) = self.style.as_ref() else {
17804 return;
17805 };
17806
17807 for chunk in chunks {
17808 let highlight = chunk
17809 .syntax_highlight_id
17810 .and_then(|id| id.name(&style.syntax));
17811 let mut chunk_lines = chunk.text.split('\n').peekable();
17812 while let Some(text) = chunk_lines.next() {
17813 let mut merged_with_last_token = false;
17814 if let Some(last_token) = line.back_mut() {
17815 if last_token.highlight == highlight {
17816 last_token.text.push_str(text);
17817 merged_with_last_token = true;
17818 }
17819 }
17820
17821 if !merged_with_last_token {
17822 line.push_back(Chunk {
17823 text: text.into(),
17824 highlight,
17825 });
17826 }
17827
17828 if chunk_lines.peek().is_some() {
17829 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17830 line.pop_front();
17831 }
17832 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17833 line.pop_back();
17834 }
17835
17836 lines.push(mem::take(&mut line));
17837 }
17838 }
17839 }
17840
17841 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17842 return;
17843 };
17844 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17845 }
17846
17847 pub fn open_context_menu(
17848 &mut self,
17849 _: &OpenContextMenu,
17850 window: &mut Window,
17851 cx: &mut Context<Self>,
17852 ) {
17853 self.request_autoscroll(Autoscroll::newest(), cx);
17854 let position = self.selections.newest_display(cx).start;
17855 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17856 }
17857
17858 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17859 &self.inlay_hint_cache
17860 }
17861
17862 pub fn replay_insert_event(
17863 &mut self,
17864 text: &str,
17865 relative_utf16_range: Option<Range<isize>>,
17866 window: &mut Window,
17867 cx: &mut Context<Self>,
17868 ) {
17869 if !self.input_enabled {
17870 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17871 return;
17872 }
17873 if let Some(relative_utf16_range) = relative_utf16_range {
17874 let selections = self.selections.all::<OffsetUtf16>(cx);
17875 self.change_selections(None, window, cx, |s| {
17876 let new_ranges = selections.into_iter().map(|range| {
17877 let start = OffsetUtf16(
17878 range
17879 .head()
17880 .0
17881 .saturating_add_signed(relative_utf16_range.start),
17882 );
17883 let end = OffsetUtf16(
17884 range
17885 .head()
17886 .0
17887 .saturating_add_signed(relative_utf16_range.end),
17888 );
17889 start..end
17890 });
17891 s.select_ranges(new_ranges);
17892 });
17893 }
17894
17895 self.handle_input(text, window, cx);
17896 }
17897
17898 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17899 let Some(provider) = self.semantics_provider.as_ref() else {
17900 return false;
17901 };
17902
17903 let mut supports = false;
17904 self.buffer().update(cx, |this, cx| {
17905 this.for_each_buffer(|buffer| {
17906 supports |= provider.supports_inlay_hints(buffer, cx);
17907 });
17908 });
17909
17910 supports
17911 }
17912
17913 pub fn is_focused(&self, window: &Window) -> bool {
17914 self.focus_handle.is_focused(window)
17915 }
17916
17917 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17918 cx.emit(EditorEvent::Focused);
17919
17920 if let Some(descendant) = self
17921 .last_focused_descendant
17922 .take()
17923 .and_then(|descendant| descendant.upgrade())
17924 {
17925 window.focus(&descendant);
17926 } else {
17927 if let Some(blame) = self.blame.as_ref() {
17928 blame.update(cx, GitBlame::focus)
17929 }
17930
17931 self.blink_manager.update(cx, BlinkManager::enable);
17932 self.show_cursor_names(window, cx);
17933 self.buffer.update(cx, |buffer, cx| {
17934 buffer.finalize_last_transaction(cx);
17935 if self.leader_peer_id.is_none() {
17936 buffer.set_active_selections(
17937 &self.selections.disjoint_anchors(),
17938 self.selections.line_mode,
17939 self.cursor_shape,
17940 cx,
17941 );
17942 }
17943 });
17944 }
17945 }
17946
17947 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17948 cx.emit(EditorEvent::FocusedIn)
17949 }
17950
17951 fn handle_focus_out(
17952 &mut self,
17953 event: FocusOutEvent,
17954 _window: &mut Window,
17955 cx: &mut Context<Self>,
17956 ) {
17957 if event.blurred != self.focus_handle {
17958 self.last_focused_descendant = Some(event.blurred);
17959 }
17960 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17961 }
17962
17963 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17964 self.blink_manager.update(cx, BlinkManager::disable);
17965 self.buffer
17966 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17967
17968 if let Some(blame) = self.blame.as_ref() {
17969 blame.update(cx, GitBlame::blur)
17970 }
17971 if !self.hover_state.focused(window, cx) {
17972 hide_hover(self, cx);
17973 }
17974 if !self
17975 .context_menu
17976 .borrow()
17977 .as_ref()
17978 .is_some_and(|context_menu| context_menu.focused(window, cx))
17979 {
17980 self.hide_context_menu(window, cx);
17981 }
17982 self.discard_inline_completion(false, cx);
17983 cx.emit(EditorEvent::Blurred);
17984 cx.notify();
17985 }
17986
17987 pub fn register_action<A: Action>(
17988 &mut self,
17989 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17990 ) -> Subscription {
17991 let id = self.next_editor_action_id.post_inc();
17992 let listener = Arc::new(listener);
17993 self.editor_actions.borrow_mut().insert(
17994 id,
17995 Box::new(move |window, _| {
17996 let listener = listener.clone();
17997 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17998 let action = action.downcast_ref().unwrap();
17999 if phase == DispatchPhase::Bubble {
18000 listener(action, window, cx)
18001 }
18002 })
18003 }),
18004 );
18005
18006 let editor_actions = self.editor_actions.clone();
18007 Subscription::new(move || {
18008 editor_actions.borrow_mut().remove(&id);
18009 })
18010 }
18011
18012 pub fn file_header_size(&self) -> u32 {
18013 FILE_HEADER_HEIGHT
18014 }
18015
18016 pub fn restore(
18017 &mut self,
18018 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18019 window: &mut Window,
18020 cx: &mut Context<Self>,
18021 ) {
18022 let workspace = self.workspace();
18023 let project = self.project.as_ref();
18024 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18025 let mut tasks = Vec::new();
18026 for (buffer_id, changes) in revert_changes {
18027 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18028 buffer.update(cx, |buffer, cx| {
18029 buffer.edit(
18030 changes
18031 .into_iter()
18032 .map(|(range, text)| (range, text.to_string())),
18033 None,
18034 cx,
18035 );
18036 });
18037
18038 if let Some(project) =
18039 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18040 {
18041 project.update(cx, |project, cx| {
18042 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18043 })
18044 }
18045 }
18046 }
18047 tasks
18048 });
18049 cx.spawn_in(window, async move |_, cx| {
18050 for (buffer, task) in save_tasks {
18051 let result = task.await;
18052 if result.is_err() {
18053 let Some(path) = buffer
18054 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18055 .ok()
18056 else {
18057 continue;
18058 };
18059 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18060 let Some(task) = cx
18061 .update_window_entity(&workspace, |workspace, window, cx| {
18062 workspace
18063 .open_path_preview(path, None, false, false, false, window, cx)
18064 })
18065 .ok()
18066 else {
18067 continue;
18068 };
18069 task.await.log_err();
18070 }
18071 }
18072 }
18073 })
18074 .detach();
18075 self.change_selections(None, window, cx, |selections| selections.refresh());
18076 }
18077
18078 pub fn to_pixel_point(
18079 &self,
18080 source: multi_buffer::Anchor,
18081 editor_snapshot: &EditorSnapshot,
18082 window: &mut Window,
18083 ) -> Option<gpui::Point<Pixels>> {
18084 let source_point = source.to_display_point(editor_snapshot);
18085 self.display_to_pixel_point(source_point, editor_snapshot, window)
18086 }
18087
18088 pub fn display_to_pixel_point(
18089 &self,
18090 source: DisplayPoint,
18091 editor_snapshot: &EditorSnapshot,
18092 window: &mut Window,
18093 ) -> Option<gpui::Point<Pixels>> {
18094 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18095 let text_layout_details = self.text_layout_details(window);
18096 let scroll_top = text_layout_details
18097 .scroll_anchor
18098 .scroll_position(editor_snapshot)
18099 .y;
18100
18101 if source.row().as_f32() < scroll_top.floor() {
18102 return None;
18103 }
18104 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18105 let source_y = line_height * (source.row().as_f32() - scroll_top);
18106 Some(gpui::Point::new(source_x, source_y))
18107 }
18108
18109 pub fn has_visible_completions_menu(&self) -> bool {
18110 !self.edit_prediction_preview_is_active()
18111 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18112 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18113 })
18114 }
18115
18116 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18117 self.addons
18118 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18119 }
18120
18121 pub fn unregister_addon<T: Addon>(&mut self) {
18122 self.addons.remove(&std::any::TypeId::of::<T>());
18123 }
18124
18125 pub fn addon<T: Addon>(&self) -> Option<&T> {
18126 let type_id = std::any::TypeId::of::<T>();
18127 self.addons
18128 .get(&type_id)
18129 .and_then(|item| item.to_any().downcast_ref::<T>())
18130 }
18131
18132 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18133 let text_layout_details = self.text_layout_details(window);
18134 let style = &text_layout_details.editor_style;
18135 let font_id = window.text_system().resolve_font(&style.text.font());
18136 let font_size = style.text.font_size.to_pixels(window.rem_size());
18137 let line_height = style.text.line_height_in_pixels(window.rem_size());
18138 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18139
18140 gpui::Size::new(em_width, line_height)
18141 }
18142
18143 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18144 self.load_diff_task.clone()
18145 }
18146
18147 fn read_metadata_from_db(
18148 &mut self,
18149 item_id: u64,
18150 workspace_id: WorkspaceId,
18151 window: &mut Window,
18152 cx: &mut Context<Editor>,
18153 ) {
18154 if self.is_singleton(cx)
18155 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18156 {
18157 let buffer_snapshot = OnceCell::new();
18158
18159 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18160 if !folds.is_empty() {
18161 let snapshot =
18162 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18163 self.fold_ranges(
18164 folds
18165 .into_iter()
18166 .map(|(start, end)| {
18167 snapshot.clip_offset(start, Bias::Left)
18168 ..snapshot.clip_offset(end, Bias::Right)
18169 })
18170 .collect(),
18171 false,
18172 window,
18173 cx,
18174 );
18175 }
18176 }
18177
18178 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18179 if !selections.is_empty() {
18180 let snapshot =
18181 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18182 self.change_selections(None, window, cx, |s| {
18183 s.select_ranges(selections.into_iter().map(|(start, end)| {
18184 snapshot.clip_offset(start, Bias::Left)
18185 ..snapshot.clip_offset(end, Bias::Right)
18186 }));
18187 });
18188 }
18189 };
18190 }
18191
18192 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18193 }
18194}
18195
18196// Consider user intent and default settings
18197fn choose_completion_range(
18198 completion: &Completion,
18199 intent: CompletionIntent,
18200 buffer: &Entity<Buffer>,
18201 cx: &mut Context<Editor>,
18202) -> Range<usize> {
18203 fn should_replace(
18204 completion: &Completion,
18205 insert_range: &Range<text::Anchor>,
18206 intent: CompletionIntent,
18207 completion_mode_setting: LspInsertMode,
18208 buffer: &Buffer,
18209 ) -> bool {
18210 // specific actions take precedence over settings
18211 match intent {
18212 CompletionIntent::CompleteWithInsert => return false,
18213 CompletionIntent::CompleteWithReplace => return true,
18214 CompletionIntent::Complete | CompletionIntent::Compose => {}
18215 }
18216
18217 match completion_mode_setting {
18218 LspInsertMode::Insert => false,
18219 LspInsertMode::Replace => true,
18220 LspInsertMode::ReplaceSubsequence => {
18221 let mut text_to_replace = buffer.chars_for_range(
18222 buffer.anchor_before(completion.replace_range.start)
18223 ..buffer.anchor_after(completion.replace_range.end),
18224 );
18225 let mut completion_text = completion.new_text.chars();
18226
18227 // is `text_to_replace` a subsequence of `completion_text`
18228 text_to_replace
18229 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18230 }
18231 LspInsertMode::ReplaceSuffix => {
18232 let range_after_cursor = insert_range.end..completion.replace_range.end;
18233
18234 let text_after_cursor = buffer
18235 .text_for_range(
18236 buffer.anchor_before(range_after_cursor.start)
18237 ..buffer.anchor_after(range_after_cursor.end),
18238 )
18239 .collect::<String>();
18240 completion.new_text.ends_with(&text_after_cursor)
18241 }
18242 }
18243 }
18244
18245 let buffer = buffer.read(cx);
18246
18247 if let CompletionSource::Lsp {
18248 insert_range: Some(insert_range),
18249 ..
18250 } = &completion.source
18251 {
18252 let completion_mode_setting =
18253 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18254 .completions
18255 .lsp_insert_mode;
18256
18257 if !should_replace(
18258 completion,
18259 &insert_range,
18260 intent,
18261 completion_mode_setting,
18262 buffer,
18263 ) {
18264 return insert_range.to_offset(buffer);
18265 }
18266 }
18267
18268 completion.replace_range.to_offset(buffer)
18269}
18270
18271fn insert_extra_newline_brackets(
18272 buffer: &MultiBufferSnapshot,
18273 range: Range<usize>,
18274 language: &language::LanguageScope,
18275) -> bool {
18276 let leading_whitespace_len = buffer
18277 .reversed_chars_at(range.start)
18278 .take_while(|c| c.is_whitespace() && *c != '\n')
18279 .map(|c| c.len_utf8())
18280 .sum::<usize>();
18281 let trailing_whitespace_len = buffer
18282 .chars_at(range.end)
18283 .take_while(|c| c.is_whitespace() && *c != '\n')
18284 .map(|c| c.len_utf8())
18285 .sum::<usize>();
18286 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18287
18288 language.brackets().any(|(pair, enabled)| {
18289 let pair_start = pair.start.trim_end();
18290 let pair_end = pair.end.trim_start();
18291
18292 enabled
18293 && pair.newline
18294 && buffer.contains_str_at(range.end, pair_end)
18295 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18296 })
18297}
18298
18299fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18300 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18301 [(buffer, range, _)] => (*buffer, range.clone()),
18302 _ => return false,
18303 };
18304 let pair = {
18305 let mut result: Option<BracketMatch> = None;
18306
18307 for pair in buffer
18308 .all_bracket_ranges(range.clone())
18309 .filter(move |pair| {
18310 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18311 })
18312 {
18313 let len = pair.close_range.end - pair.open_range.start;
18314
18315 if let Some(existing) = &result {
18316 let existing_len = existing.close_range.end - existing.open_range.start;
18317 if len > existing_len {
18318 continue;
18319 }
18320 }
18321
18322 result = Some(pair);
18323 }
18324
18325 result
18326 };
18327 let Some(pair) = pair else {
18328 return false;
18329 };
18330 pair.newline_only
18331 && buffer
18332 .chars_for_range(pair.open_range.end..range.start)
18333 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18334 .all(|c| c.is_whitespace() && c != '\n')
18335}
18336
18337fn get_uncommitted_diff_for_buffer(
18338 project: &Entity<Project>,
18339 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18340 buffer: Entity<MultiBuffer>,
18341 cx: &mut App,
18342) -> Task<()> {
18343 let mut tasks = Vec::new();
18344 project.update(cx, |project, cx| {
18345 for buffer in buffers {
18346 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18347 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18348 }
18349 }
18350 });
18351 cx.spawn(async move |cx| {
18352 let diffs = future::join_all(tasks).await;
18353 buffer
18354 .update(cx, |buffer, cx| {
18355 for diff in diffs.into_iter().flatten() {
18356 buffer.add_diff(diff, cx);
18357 }
18358 })
18359 .ok();
18360 })
18361}
18362
18363fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18364 let tab_size = tab_size.get() as usize;
18365 let mut width = offset;
18366
18367 for ch in text.chars() {
18368 width += if ch == '\t' {
18369 tab_size - (width % tab_size)
18370 } else {
18371 1
18372 };
18373 }
18374
18375 width - offset
18376}
18377
18378#[cfg(test)]
18379mod tests {
18380 use super::*;
18381
18382 #[test]
18383 fn test_string_size_with_expanded_tabs() {
18384 let nz = |val| NonZeroU32::new(val).unwrap();
18385 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18386 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18387 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18388 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18389 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18390 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18391 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18392 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18393 }
18394}
18395
18396/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18397struct WordBreakingTokenizer<'a> {
18398 input: &'a str,
18399}
18400
18401impl<'a> WordBreakingTokenizer<'a> {
18402 fn new(input: &'a str) -> Self {
18403 Self { input }
18404 }
18405}
18406
18407fn is_char_ideographic(ch: char) -> bool {
18408 use unicode_script::Script::*;
18409 use unicode_script::UnicodeScript;
18410 matches!(ch.script(), Han | Tangut | Yi)
18411}
18412
18413fn is_grapheme_ideographic(text: &str) -> bool {
18414 text.chars().any(is_char_ideographic)
18415}
18416
18417fn is_grapheme_whitespace(text: &str) -> bool {
18418 text.chars().any(|x| x.is_whitespace())
18419}
18420
18421fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18422 text.chars().next().map_or(false, |ch| {
18423 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18424 })
18425}
18426
18427#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18428enum WordBreakToken<'a> {
18429 Word { token: &'a str, grapheme_len: usize },
18430 InlineWhitespace { token: &'a str, grapheme_len: usize },
18431 Newline,
18432}
18433
18434impl<'a> Iterator for WordBreakingTokenizer<'a> {
18435 /// Yields a span, the count of graphemes in the token, and whether it was
18436 /// whitespace. Note that it also breaks at word boundaries.
18437 type Item = WordBreakToken<'a>;
18438
18439 fn next(&mut self) -> Option<Self::Item> {
18440 use unicode_segmentation::UnicodeSegmentation;
18441 if self.input.is_empty() {
18442 return None;
18443 }
18444
18445 let mut iter = self.input.graphemes(true).peekable();
18446 let mut offset = 0;
18447 let mut grapheme_len = 0;
18448 if let Some(first_grapheme) = iter.next() {
18449 let is_newline = first_grapheme == "\n";
18450 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18451 offset += first_grapheme.len();
18452 grapheme_len += 1;
18453 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18454 if let Some(grapheme) = iter.peek().copied() {
18455 if should_stay_with_preceding_ideograph(grapheme) {
18456 offset += grapheme.len();
18457 grapheme_len += 1;
18458 }
18459 }
18460 } else {
18461 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18462 let mut next_word_bound = words.peek().copied();
18463 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18464 next_word_bound = words.next();
18465 }
18466 while let Some(grapheme) = iter.peek().copied() {
18467 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18468 break;
18469 };
18470 if is_grapheme_whitespace(grapheme) != is_whitespace
18471 || (grapheme == "\n") != is_newline
18472 {
18473 break;
18474 };
18475 offset += grapheme.len();
18476 grapheme_len += 1;
18477 iter.next();
18478 }
18479 }
18480 let token = &self.input[..offset];
18481 self.input = &self.input[offset..];
18482 if token == "\n" {
18483 Some(WordBreakToken::Newline)
18484 } else if is_whitespace {
18485 Some(WordBreakToken::InlineWhitespace {
18486 token,
18487 grapheme_len,
18488 })
18489 } else {
18490 Some(WordBreakToken::Word {
18491 token,
18492 grapheme_len,
18493 })
18494 }
18495 } else {
18496 None
18497 }
18498 }
18499}
18500
18501#[test]
18502fn test_word_breaking_tokenizer() {
18503 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18504 ("", &[]),
18505 (" ", &[whitespace(" ", 2)]),
18506 ("Ʒ", &[word("Ʒ", 1)]),
18507 ("Ǽ", &[word("Ǽ", 1)]),
18508 ("⋑", &[word("⋑", 1)]),
18509 ("⋑⋑", &[word("⋑⋑", 2)]),
18510 (
18511 "原理,进而",
18512 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18513 ),
18514 (
18515 "hello world",
18516 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18517 ),
18518 (
18519 "hello, world",
18520 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18521 ),
18522 (
18523 " hello world",
18524 &[
18525 whitespace(" ", 2),
18526 word("hello", 5),
18527 whitespace(" ", 1),
18528 word("world", 5),
18529 ],
18530 ),
18531 (
18532 "这是什么 \n 钢笔",
18533 &[
18534 word("这", 1),
18535 word("是", 1),
18536 word("什", 1),
18537 word("么", 1),
18538 whitespace(" ", 1),
18539 newline(),
18540 whitespace(" ", 1),
18541 word("钢", 1),
18542 word("笔", 1),
18543 ],
18544 ),
18545 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18546 ];
18547
18548 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18549 WordBreakToken::Word {
18550 token,
18551 grapheme_len,
18552 }
18553 }
18554
18555 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18556 WordBreakToken::InlineWhitespace {
18557 token,
18558 grapheme_len,
18559 }
18560 }
18561
18562 fn newline() -> WordBreakToken<'static> {
18563 WordBreakToken::Newline
18564 }
18565
18566 for (input, result) in tests {
18567 assert_eq!(
18568 WordBreakingTokenizer::new(input)
18569 .collect::<Vec<_>>()
18570 .as_slice(),
18571 *result,
18572 );
18573 }
18574}
18575
18576fn wrap_with_prefix(
18577 line_prefix: String,
18578 unwrapped_text: String,
18579 wrap_column: usize,
18580 tab_size: NonZeroU32,
18581 preserve_existing_whitespace: bool,
18582) -> String {
18583 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18584 let mut wrapped_text = String::new();
18585 let mut current_line = line_prefix.clone();
18586
18587 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18588 let mut current_line_len = line_prefix_len;
18589 let mut in_whitespace = false;
18590 for token in tokenizer {
18591 let have_preceding_whitespace = in_whitespace;
18592 match token {
18593 WordBreakToken::Word {
18594 token,
18595 grapheme_len,
18596 } => {
18597 in_whitespace = false;
18598 if current_line_len + grapheme_len > wrap_column
18599 && current_line_len != line_prefix_len
18600 {
18601 wrapped_text.push_str(current_line.trim_end());
18602 wrapped_text.push('\n');
18603 current_line.truncate(line_prefix.len());
18604 current_line_len = line_prefix_len;
18605 }
18606 current_line.push_str(token);
18607 current_line_len += grapheme_len;
18608 }
18609 WordBreakToken::InlineWhitespace {
18610 mut token,
18611 mut grapheme_len,
18612 } => {
18613 in_whitespace = true;
18614 if have_preceding_whitespace && !preserve_existing_whitespace {
18615 continue;
18616 }
18617 if !preserve_existing_whitespace {
18618 token = " ";
18619 grapheme_len = 1;
18620 }
18621 if current_line_len + grapheme_len > wrap_column {
18622 wrapped_text.push_str(current_line.trim_end());
18623 wrapped_text.push('\n');
18624 current_line.truncate(line_prefix.len());
18625 current_line_len = line_prefix_len;
18626 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18627 current_line.push_str(token);
18628 current_line_len += grapheme_len;
18629 }
18630 }
18631 WordBreakToken::Newline => {
18632 in_whitespace = true;
18633 if preserve_existing_whitespace {
18634 wrapped_text.push_str(current_line.trim_end());
18635 wrapped_text.push('\n');
18636 current_line.truncate(line_prefix.len());
18637 current_line_len = line_prefix_len;
18638 } else if have_preceding_whitespace {
18639 continue;
18640 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18641 {
18642 wrapped_text.push_str(current_line.trim_end());
18643 wrapped_text.push('\n');
18644 current_line.truncate(line_prefix.len());
18645 current_line_len = line_prefix_len;
18646 } else if current_line_len != line_prefix_len {
18647 current_line.push(' ');
18648 current_line_len += 1;
18649 }
18650 }
18651 }
18652 }
18653
18654 if !current_line.is_empty() {
18655 wrapped_text.push_str(¤t_line);
18656 }
18657 wrapped_text
18658}
18659
18660#[test]
18661fn test_wrap_with_prefix() {
18662 assert_eq!(
18663 wrap_with_prefix(
18664 "# ".to_string(),
18665 "abcdefg".to_string(),
18666 4,
18667 NonZeroU32::new(4).unwrap(),
18668 false,
18669 ),
18670 "# abcdefg"
18671 );
18672 assert_eq!(
18673 wrap_with_prefix(
18674 "".to_string(),
18675 "\thello world".to_string(),
18676 8,
18677 NonZeroU32::new(4).unwrap(),
18678 false,
18679 ),
18680 "hello\nworld"
18681 );
18682 assert_eq!(
18683 wrap_with_prefix(
18684 "// ".to_string(),
18685 "xx \nyy zz aa bb cc".to_string(),
18686 12,
18687 NonZeroU32::new(4).unwrap(),
18688 false,
18689 ),
18690 "// xx yy zz\n// aa bb cc"
18691 );
18692 assert_eq!(
18693 wrap_with_prefix(
18694 String::new(),
18695 "这是什么 \n 钢笔".to_string(),
18696 3,
18697 NonZeroU32::new(4).unwrap(),
18698 false,
18699 ),
18700 "这是什\n么 钢\n笔"
18701 );
18702}
18703
18704pub trait CollaborationHub {
18705 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18706 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18707 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18708}
18709
18710impl CollaborationHub for Entity<Project> {
18711 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18712 self.read(cx).collaborators()
18713 }
18714
18715 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18716 self.read(cx).user_store().read(cx).participant_indices()
18717 }
18718
18719 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18720 let this = self.read(cx);
18721 let user_ids = this.collaborators().values().map(|c| c.user_id);
18722 this.user_store().read_with(cx, |user_store, cx| {
18723 user_store.participant_names(user_ids, cx)
18724 })
18725 }
18726}
18727
18728pub trait SemanticsProvider {
18729 fn hover(
18730 &self,
18731 buffer: &Entity<Buffer>,
18732 position: text::Anchor,
18733 cx: &mut App,
18734 ) -> Option<Task<Vec<project::Hover>>>;
18735
18736 fn inlay_hints(
18737 &self,
18738 buffer_handle: Entity<Buffer>,
18739 range: Range<text::Anchor>,
18740 cx: &mut App,
18741 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18742
18743 fn resolve_inlay_hint(
18744 &self,
18745 hint: InlayHint,
18746 buffer_handle: Entity<Buffer>,
18747 server_id: LanguageServerId,
18748 cx: &mut App,
18749 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18750
18751 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18752
18753 fn document_highlights(
18754 &self,
18755 buffer: &Entity<Buffer>,
18756 position: text::Anchor,
18757 cx: &mut App,
18758 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18759
18760 fn definitions(
18761 &self,
18762 buffer: &Entity<Buffer>,
18763 position: text::Anchor,
18764 kind: GotoDefinitionKind,
18765 cx: &mut App,
18766 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18767
18768 fn range_for_rename(
18769 &self,
18770 buffer: &Entity<Buffer>,
18771 position: text::Anchor,
18772 cx: &mut App,
18773 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18774
18775 fn perform_rename(
18776 &self,
18777 buffer: &Entity<Buffer>,
18778 position: text::Anchor,
18779 new_name: String,
18780 cx: &mut App,
18781 ) -> Option<Task<Result<ProjectTransaction>>>;
18782}
18783
18784pub trait CompletionProvider {
18785 fn completions(
18786 &self,
18787 excerpt_id: ExcerptId,
18788 buffer: &Entity<Buffer>,
18789 buffer_position: text::Anchor,
18790 trigger: CompletionContext,
18791 window: &mut Window,
18792 cx: &mut Context<Editor>,
18793 ) -> Task<Result<Option<Vec<Completion>>>>;
18794
18795 fn resolve_completions(
18796 &self,
18797 buffer: Entity<Buffer>,
18798 completion_indices: Vec<usize>,
18799 completions: Rc<RefCell<Box<[Completion]>>>,
18800 cx: &mut Context<Editor>,
18801 ) -> Task<Result<bool>>;
18802
18803 fn apply_additional_edits_for_completion(
18804 &self,
18805 _buffer: Entity<Buffer>,
18806 _completions: Rc<RefCell<Box<[Completion]>>>,
18807 _completion_index: usize,
18808 _push_to_history: bool,
18809 _cx: &mut Context<Editor>,
18810 ) -> Task<Result<Option<language::Transaction>>> {
18811 Task::ready(Ok(None))
18812 }
18813
18814 fn is_completion_trigger(
18815 &self,
18816 buffer: &Entity<Buffer>,
18817 position: language::Anchor,
18818 text: &str,
18819 trigger_in_words: bool,
18820 cx: &mut Context<Editor>,
18821 ) -> bool;
18822
18823 fn sort_completions(&self) -> bool {
18824 true
18825 }
18826
18827 fn filter_completions(&self) -> bool {
18828 true
18829 }
18830}
18831
18832pub trait CodeActionProvider {
18833 fn id(&self) -> Arc<str>;
18834
18835 fn code_actions(
18836 &self,
18837 buffer: &Entity<Buffer>,
18838 range: Range<text::Anchor>,
18839 window: &mut Window,
18840 cx: &mut App,
18841 ) -> Task<Result<Vec<CodeAction>>>;
18842
18843 fn apply_code_action(
18844 &self,
18845 buffer_handle: Entity<Buffer>,
18846 action: CodeAction,
18847 excerpt_id: ExcerptId,
18848 push_to_history: bool,
18849 window: &mut Window,
18850 cx: &mut App,
18851 ) -> Task<Result<ProjectTransaction>>;
18852}
18853
18854impl CodeActionProvider for Entity<Project> {
18855 fn id(&self) -> Arc<str> {
18856 "project".into()
18857 }
18858
18859 fn code_actions(
18860 &self,
18861 buffer: &Entity<Buffer>,
18862 range: Range<text::Anchor>,
18863 _window: &mut Window,
18864 cx: &mut App,
18865 ) -> Task<Result<Vec<CodeAction>>> {
18866 self.update(cx, |project, cx| {
18867 let code_lens = project.code_lens(buffer, range.clone(), cx);
18868 let code_actions = project.code_actions(buffer, range, None, cx);
18869 cx.background_spawn(async move {
18870 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18871 Ok(code_lens
18872 .context("code lens fetch")?
18873 .into_iter()
18874 .chain(code_actions.context("code action fetch")?)
18875 .collect())
18876 })
18877 })
18878 }
18879
18880 fn apply_code_action(
18881 &self,
18882 buffer_handle: Entity<Buffer>,
18883 action: CodeAction,
18884 _excerpt_id: ExcerptId,
18885 push_to_history: bool,
18886 _window: &mut Window,
18887 cx: &mut App,
18888 ) -> Task<Result<ProjectTransaction>> {
18889 self.update(cx, |project, cx| {
18890 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18891 })
18892 }
18893}
18894
18895fn snippet_completions(
18896 project: &Project,
18897 buffer: &Entity<Buffer>,
18898 buffer_position: text::Anchor,
18899 cx: &mut App,
18900) -> Task<Result<Vec<Completion>>> {
18901 let languages = buffer.read(cx).languages_at(buffer_position);
18902 let snippet_store = project.snippets().read(cx);
18903
18904 let scopes: Vec<_> = languages
18905 .iter()
18906 .filter_map(|language| {
18907 let language_name = language.lsp_id();
18908 let snippets = snippet_store.snippets_for(Some(language_name), cx);
18909
18910 if snippets.is_empty() {
18911 None
18912 } else {
18913 Some((language.default_scope(), snippets))
18914 }
18915 })
18916 .collect();
18917
18918 if scopes.is_empty() {
18919 return Task::ready(Ok(vec![]));
18920 }
18921
18922 let snapshot = buffer.read(cx).text_snapshot();
18923 let chars: String = snapshot
18924 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18925 .collect();
18926 let executor = cx.background_executor().clone();
18927
18928 cx.background_spawn(async move {
18929 let mut all_results: Vec<Completion> = Vec::new();
18930 for (scope, snippets) in scopes.into_iter() {
18931 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18932 let mut last_word = chars
18933 .chars()
18934 .take_while(|c| classifier.is_word(*c))
18935 .collect::<String>();
18936 last_word = last_word.chars().rev().collect();
18937
18938 if last_word.is_empty() {
18939 return Ok(vec![]);
18940 }
18941
18942 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18943 let to_lsp = |point: &text::Anchor| {
18944 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18945 point_to_lsp(end)
18946 };
18947 let lsp_end = to_lsp(&buffer_position);
18948
18949 let candidates = snippets
18950 .iter()
18951 .enumerate()
18952 .flat_map(|(ix, snippet)| {
18953 snippet
18954 .prefix
18955 .iter()
18956 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18957 })
18958 .collect::<Vec<StringMatchCandidate>>();
18959
18960 let mut matches = fuzzy::match_strings(
18961 &candidates,
18962 &last_word,
18963 last_word.chars().any(|c| c.is_uppercase()),
18964 100,
18965 &Default::default(),
18966 executor.clone(),
18967 )
18968 .await;
18969
18970 // Remove all candidates where the query's start does not match the start of any word in the candidate
18971 if let Some(query_start) = last_word.chars().next() {
18972 matches.retain(|string_match| {
18973 split_words(&string_match.string).any(|word| {
18974 // Check that the first codepoint of the word as lowercase matches the first
18975 // codepoint of the query as lowercase
18976 word.chars()
18977 .flat_map(|codepoint| codepoint.to_lowercase())
18978 .zip(query_start.to_lowercase())
18979 .all(|(word_cp, query_cp)| word_cp == query_cp)
18980 })
18981 });
18982 }
18983
18984 let matched_strings = matches
18985 .into_iter()
18986 .map(|m| m.string)
18987 .collect::<HashSet<_>>();
18988
18989 let mut result: Vec<Completion> = snippets
18990 .iter()
18991 .filter_map(|snippet| {
18992 let matching_prefix = snippet
18993 .prefix
18994 .iter()
18995 .find(|prefix| matched_strings.contains(*prefix))?;
18996 let start = as_offset - last_word.len();
18997 let start = snapshot.anchor_before(start);
18998 let range = start..buffer_position;
18999 let lsp_start = to_lsp(&start);
19000 let lsp_range = lsp::Range {
19001 start: lsp_start,
19002 end: lsp_end,
19003 };
19004 Some(Completion {
19005 replace_range: range,
19006 new_text: snippet.body.clone(),
19007 source: CompletionSource::Lsp {
19008 insert_range: None,
19009 server_id: LanguageServerId(usize::MAX),
19010 resolved: true,
19011 lsp_completion: Box::new(lsp::CompletionItem {
19012 label: snippet.prefix.first().unwrap().clone(),
19013 kind: Some(CompletionItemKind::SNIPPET),
19014 label_details: snippet.description.as_ref().map(|description| {
19015 lsp::CompletionItemLabelDetails {
19016 detail: Some(description.clone()),
19017 description: None,
19018 }
19019 }),
19020 insert_text_format: Some(InsertTextFormat::SNIPPET),
19021 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19022 lsp::InsertReplaceEdit {
19023 new_text: snippet.body.clone(),
19024 insert: lsp_range,
19025 replace: lsp_range,
19026 },
19027 )),
19028 filter_text: Some(snippet.body.clone()),
19029 sort_text: Some(char::MAX.to_string()),
19030 ..lsp::CompletionItem::default()
19031 }),
19032 lsp_defaults: None,
19033 },
19034 label: CodeLabel {
19035 text: matching_prefix.clone(),
19036 runs: Vec::new(),
19037 filter_range: 0..matching_prefix.len(),
19038 },
19039 icon_path: None,
19040 documentation: snippet.description.clone().map(|description| {
19041 CompletionDocumentation::SingleLine(description.into())
19042 }),
19043 insert_text_mode: None,
19044 confirm: None,
19045 })
19046 })
19047 .collect();
19048
19049 all_results.append(&mut result);
19050 }
19051
19052 Ok(all_results)
19053 })
19054}
19055
19056impl CompletionProvider for Entity<Project> {
19057 fn completions(
19058 &self,
19059 _excerpt_id: ExcerptId,
19060 buffer: &Entity<Buffer>,
19061 buffer_position: text::Anchor,
19062 options: CompletionContext,
19063 _window: &mut Window,
19064 cx: &mut Context<Editor>,
19065 ) -> Task<Result<Option<Vec<Completion>>>> {
19066 self.update(cx, |project, cx| {
19067 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19068 let project_completions = project.completions(buffer, buffer_position, options, cx);
19069 cx.background_spawn(async move {
19070 let snippets_completions = snippets.await?;
19071 match project_completions.await? {
19072 Some(mut completions) => {
19073 completions.extend(snippets_completions);
19074 Ok(Some(completions))
19075 }
19076 None => {
19077 if snippets_completions.is_empty() {
19078 Ok(None)
19079 } else {
19080 Ok(Some(snippets_completions))
19081 }
19082 }
19083 }
19084 })
19085 })
19086 }
19087
19088 fn resolve_completions(
19089 &self,
19090 buffer: Entity<Buffer>,
19091 completion_indices: Vec<usize>,
19092 completions: Rc<RefCell<Box<[Completion]>>>,
19093 cx: &mut Context<Editor>,
19094 ) -> Task<Result<bool>> {
19095 self.update(cx, |project, cx| {
19096 project.lsp_store().update(cx, |lsp_store, cx| {
19097 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19098 })
19099 })
19100 }
19101
19102 fn apply_additional_edits_for_completion(
19103 &self,
19104 buffer: Entity<Buffer>,
19105 completions: Rc<RefCell<Box<[Completion]>>>,
19106 completion_index: usize,
19107 push_to_history: bool,
19108 cx: &mut Context<Editor>,
19109 ) -> Task<Result<Option<language::Transaction>>> {
19110 self.update(cx, |project, cx| {
19111 project.lsp_store().update(cx, |lsp_store, cx| {
19112 lsp_store.apply_additional_edits_for_completion(
19113 buffer,
19114 completions,
19115 completion_index,
19116 push_to_history,
19117 cx,
19118 )
19119 })
19120 })
19121 }
19122
19123 fn is_completion_trigger(
19124 &self,
19125 buffer: &Entity<Buffer>,
19126 position: language::Anchor,
19127 text: &str,
19128 trigger_in_words: bool,
19129 cx: &mut Context<Editor>,
19130 ) -> bool {
19131 let mut chars = text.chars();
19132 let char = if let Some(char) = chars.next() {
19133 char
19134 } else {
19135 return false;
19136 };
19137 if chars.next().is_some() {
19138 return false;
19139 }
19140
19141 let buffer = buffer.read(cx);
19142 let snapshot = buffer.snapshot();
19143 if !snapshot.settings_at(position, cx).show_completions_on_input {
19144 return false;
19145 }
19146 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19147 if trigger_in_words && classifier.is_word(char) {
19148 return true;
19149 }
19150
19151 buffer.completion_triggers().contains(text)
19152 }
19153}
19154
19155impl SemanticsProvider for Entity<Project> {
19156 fn hover(
19157 &self,
19158 buffer: &Entity<Buffer>,
19159 position: text::Anchor,
19160 cx: &mut App,
19161 ) -> Option<Task<Vec<project::Hover>>> {
19162 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19163 }
19164
19165 fn document_highlights(
19166 &self,
19167 buffer: &Entity<Buffer>,
19168 position: text::Anchor,
19169 cx: &mut App,
19170 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19171 Some(self.update(cx, |project, cx| {
19172 project.document_highlights(buffer, position, cx)
19173 }))
19174 }
19175
19176 fn definitions(
19177 &self,
19178 buffer: &Entity<Buffer>,
19179 position: text::Anchor,
19180 kind: GotoDefinitionKind,
19181 cx: &mut App,
19182 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19183 Some(self.update(cx, |project, cx| match kind {
19184 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19185 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19186 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19187 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19188 }))
19189 }
19190
19191 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19192 // TODO: make this work for remote projects
19193 self.update(cx, |this, cx| {
19194 buffer.update(cx, |buffer, cx| {
19195 this.any_language_server_supports_inlay_hints(buffer, cx)
19196 })
19197 })
19198 }
19199
19200 fn inlay_hints(
19201 &self,
19202 buffer_handle: Entity<Buffer>,
19203 range: Range<text::Anchor>,
19204 cx: &mut App,
19205 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19206 Some(self.update(cx, |project, cx| {
19207 project.inlay_hints(buffer_handle, range, cx)
19208 }))
19209 }
19210
19211 fn resolve_inlay_hint(
19212 &self,
19213 hint: InlayHint,
19214 buffer_handle: Entity<Buffer>,
19215 server_id: LanguageServerId,
19216 cx: &mut App,
19217 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19218 Some(self.update(cx, |project, cx| {
19219 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19220 }))
19221 }
19222
19223 fn range_for_rename(
19224 &self,
19225 buffer: &Entity<Buffer>,
19226 position: text::Anchor,
19227 cx: &mut App,
19228 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19229 Some(self.update(cx, |project, cx| {
19230 let buffer = buffer.clone();
19231 let task = project.prepare_rename(buffer.clone(), position, cx);
19232 cx.spawn(async move |_, cx| {
19233 Ok(match task.await? {
19234 PrepareRenameResponse::Success(range) => Some(range),
19235 PrepareRenameResponse::InvalidPosition => None,
19236 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19237 // Fallback on using TreeSitter info to determine identifier range
19238 buffer.update(cx, |buffer, _| {
19239 let snapshot = buffer.snapshot();
19240 let (range, kind) = snapshot.surrounding_word(position);
19241 if kind != Some(CharKind::Word) {
19242 return None;
19243 }
19244 Some(
19245 snapshot.anchor_before(range.start)
19246 ..snapshot.anchor_after(range.end),
19247 )
19248 })?
19249 }
19250 })
19251 })
19252 }))
19253 }
19254
19255 fn perform_rename(
19256 &self,
19257 buffer: &Entity<Buffer>,
19258 position: text::Anchor,
19259 new_name: String,
19260 cx: &mut App,
19261 ) -> Option<Task<Result<ProjectTransaction>>> {
19262 Some(self.update(cx, |project, cx| {
19263 project.perform_rename(buffer.clone(), position, new_name, cx)
19264 }))
19265 }
19266}
19267
19268fn inlay_hint_settings(
19269 location: Anchor,
19270 snapshot: &MultiBufferSnapshot,
19271 cx: &mut Context<Editor>,
19272) -> InlayHintSettings {
19273 let file = snapshot.file_at(location);
19274 let language = snapshot.language_at(location).map(|l| l.name());
19275 language_settings(language, file, cx).inlay_hints
19276}
19277
19278fn consume_contiguous_rows(
19279 contiguous_row_selections: &mut Vec<Selection<Point>>,
19280 selection: &Selection<Point>,
19281 display_map: &DisplaySnapshot,
19282 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19283) -> (MultiBufferRow, MultiBufferRow) {
19284 contiguous_row_selections.push(selection.clone());
19285 let start_row = MultiBufferRow(selection.start.row);
19286 let mut end_row = ending_row(selection, display_map);
19287
19288 while let Some(next_selection) = selections.peek() {
19289 if next_selection.start.row <= end_row.0 {
19290 end_row = ending_row(next_selection, display_map);
19291 contiguous_row_selections.push(selections.next().unwrap().clone());
19292 } else {
19293 break;
19294 }
19295 }
19296 (start_row, end_row)
19297}
19298
19299fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19300 if next_selection.end.column > 0 || next_selection.is_empty() {
19301 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19302 } else {
19303 MultiBufferRow(next_selection.end.row)
19304 }
19305}
19306
19307impl EditorSnapshot {
19308 pub fn remote_selections_in_range<'a>(
19309 &'a self,
19310 range: &'a Range<Anchor>,
19311 collaboration_hub: &dyn CollaborationHub,
19312 cx: &'a App,
19313 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19314 let participant_names = collaboration_hub.user_names(cx);
19315 let participant_indices = collaboration_hub.user_participant_indices(cx);
19316 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19317 let collaborators_by_replica_id = collaborators_by_peer_id
19318 .iter()
19319 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19320 .collect::<HashMap<_, _>>();
19321 self.buffer_snapshot
19322 .selections_in_range(range, false)
19323 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19324 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19325 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19326 let user_name = participant_names.get(&collaborator.user_id).cloned();
19327 Some(RemoteSelection {
19328 replica_id,
19329 selection,
19330 cursor_shape,
19331 line_mode,
19332 participant_index,
19333 peer_id: collaborator.peer_id,
19334 user_name,
19335 })
19336 })
19337 }
19338
19339 pub fn hunks_for_ranges(
19340 &self,
19341 ranges: impl IntoIterator<Item = Range<Point>>,
19342 ) -> Vec<MultiBufferDiffHunk> {
19343 let mut hunks = Vec::new();
19344 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19345 HashMap::default();
19346 for query_range in ranges {
19347 let query_rows =
19348 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19349 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19350 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19351 ) {
19352 // Include deleted hunks that are adjacent to the query range, because
19353 // otherwise they would be missed.
19354 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19355 if hunk.status().is_deleted() {
19356 intersects_range |= hunk.row_range.start == query_rows.end;
19357 intersects_range |= hunk.row_range.end == query_rows.start;
19358 }
19359 if intersects_range {
19360 if !processed_buffer_rows
19361 .entry(hunk.buffer_id)
19362 .or_default()
19363 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19364 {
19365 continue;
19366 }
19367 hunks.push(hunk);
19368 }
19369 }
19370 }
19371
19372 hunks
19373 }
19374
19375 fn display_diff_hunks_for_rows<'a>(
19376 &'a self,
19377 display_rows: Range<DisplayRow>,
19378 folded_buffers: &'a HashSet<BufferId>,
19379 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19380 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19381 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19382
19383 self.buffer_snapshot
19384 .diff_hunks_in_range(buffer_start..buffer_end)
19385 .filter_map(|hunk| {
19386 if folded_buffers.contains(&hunk.buffer_id) {
19387 return None;
19388 }
19389
19390 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19391 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19392
19393 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19394 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19395
19396 let display_hunk = if hunk_display_start.column() != 0 {
19397 DisplayDiffHunk::Folded {
19398 display_row: hunk_display_start.row(),
19399 }
19400 } else {
19401 let mut end_row = hunk_display_end.row();
19402 if hunk_display_end.column() > 0 {
19403 end_row.0 += 1;
19404 }
19405 let is_created_file = hunk.is_created_file();
19406 DisplayDiffHunk::Unfolded {
19407 status: hunk.status(),
19408 diff_base_byte_range: hunk.diff_base_byte_range,
19409 display_row_range: hunk_display_start.row()..end_row,
19410 multi_buffer_range: Anchor::range_in_buffer(
19411 hunk.excerpt_id,
19412 hunk.buffer_id,
19413 hunk.buffer_range,
19414 ),
19415 is_created_file,
19416 }
19417 };
19418
19419 Some(display_hunk)
19420 })
19421 }
19422
19423 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19424 self.display_snapshot.buffer_snapshot.language_at(position)
19425 }
19426
19427 pub fn is_focused(&self) -> bool {
19428 self.is_focused
19429 }
19430
19431 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19432 self.placeholder_text.as_ref()
19433 }
19434
19435 pub fn scroll_position(&self) -> gpui::Point<f32> {
19436 self.scroll_anchor.scroll_position(&self.display_snapshot)
19437 }
19438
19439 fn gutter_dimensions(
19440 &self,
19441 font_id: FontId,
19442 font_size: Pixels,
19443 max_line_number_width: Pixels,
19444 cx: &App,
19445 ) -> Option<GutterDimensions> {
19446 if !self.show_gutter {
19447 return None;
19448 }
19449
19450 let descent = cx.text_system().descent(font_id, font_size);
19451 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19452 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19453
19454 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19455 matches!(
19456 ProjectSettings::get_global(cx).git.git_gutter,
19457 Some(GitGutterSetting::TrackedFiles)
19458 )
19459 });
19460 let gutter_settings = EditorSettings::get_global(cx).gutter;
19461 let show_line_numbers = self
19462 .show_line_numbers
19463 .unwrap_or(gutter_settings.line_numbers);
19464 let line_gutter_width = if show_line_numbers {
19465 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19466 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19467 max_line_number_width.max(min_width_for_number_on_gutter)
19468 } else {
19469 0.0.into()
19470 };
19471
19472 let show_code_actions = self
19473 .show_code_actions
19474 .unwrap_or(gutter_settings.code_actions);
19475
19476 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19477 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19478
19479 let git_blame_entries_width =
19480 self.git_blame_gutter_max_author_length
19481 .map(|max_author_length| {
19482 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19483 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19484
19485 /// The number of characters to dedicate to gaps and margins.
19486 const SPACING_WIDTH: usize = 4;
19487
19488 let max_char_count = max_author_length.min(renderer.max_author_length())
19489 + ::git::SHORT_SHA_LENGTH
19490 + MAX_RELATIVE_TIMESTAMP.len()
19491 + SPACING_WIDTH;
19492
19493 em_advance * max_char_count
19494 });
19495
19496 let is_singleton = self.buffer_snapshot.is_singleton();
19497
19498 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19499 left_padding += if !is_singleton {
19500 em_width * 4.0
19501 } else if show_code_actions || show_runnables || show_breakpoints {
19502 em_width * 3.0
19503 } else if show_git_gutter && show_line_numbers {
19504 em_width * 2.0
19505 } else if show_git_gutter || show_line_numbers {
19506 em_width
19507 } else {
19508 px(0.)
19509 };
19510
19511 let shows_folds = is_singleton && gutter_settings.folds;
19512
19513 let right_padding = if shows_folds && show_line_numbers {
19514 em_width * 4.0
19515 } else if shows_folds || (!is_singleton && show_line_numbers) {
19516 em_width * 3.0
19517 } else if show_line_numbers {
19518 em_width
19519 } else {
19520 px(0.)
19521 };
19522
19523 Some(GutterDimensions {
19524 left_padding,
19525 right_padding,
19526 width: line_gutter_width + left_padding + right_padding,
19527 margin: -descent,
19528 git_blame_entries_width,
19529 })
19530 }
19531
19532 pub fn render_crease_toggle(
19533 &self,
19534 buffer_row: MultiBufferRow,
19535 row_contains_cursor: bool,
19536 editor: Entity<Editor>,
19537 window: &mut Window,
19538 cx: &mut App,
19539 ) -> Option<AnyElement> {
19540 let folded = self.is_line_folded(buffer_row);
19541 let mut is_foldable = false;
19542
19543 if let Some(crease) = self
19544 .crease_snapshot
19545 .query_row(buffer_row, &self.buffer_snapshot)
19546 {
19547 is_foldable = true;
19548 match crease {
19549 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19550 if let Some(render_toggle) = render_toggle {
19551 let toggle_callback =
19552 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19553 if folded {
19554 editor.update(cx, |editor, cx| {
19555 editor.fold_at(buffer_row, window, cx)
19556 });
19557 } else {
19558 editor.update(cx, |editor, cx| {
19559 editor.unfold_at(buffer_row, window, cx)
19560 });
19561 }
19562 });
19563 return Some((render_toggle)(
19564 buffer_row,
19565 folded,
19566 toggle_callback,
19567 window,
19568 cx,
19569 ));
19570 }
19571 }
19572 }
19573 }
19574
19575 is_foldable |= self.starts_indent(buffer_row);
19576
19577 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19578 Some(
19579 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19580 .toggle_state(folded)
19581 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19582 if folded {
19583 this.unfold_at(buffer_row, window, cx);
19584 } else {
19585 this.fold_at(buffer_row, window, cx);
19586 }
19587 }))
19588 .into_any_element(),
19589 )
19590 } else {
19591 None
19592 }
19593 }
19594
19595 pub fn render_crease_trailer(
19596 &self,
19597 buffer_row: MultiBufferRow,
19598 window: &mut Window,
19599 cx: &mut App,
19600 ) -> Option<AnyElement> {
19601 let folded = self.is_line_folded(buffer_row);
19602 if let Crease::Inline { render_trailer, .. } = self
19603 .crease_snapshot
19604 .query_row(buffer_row, &self.buffer_snapshot)?
19605 {
19606 let render_trailer = render_trailer.as_ref()?;
19607 Some(render_trailer(buffer_row, folded, window, cx))
19608 } else {
19609 None
19610 }
19611 }
19612}
19613
19614impl Deref for EditorSnapshot {
19615 type Target = DisplaySnapshot;
19616
19617 fn deref(&self) -> &Self::Target {
19618 &self.display_snapshot
19619 }
19620}
19621
19622#[derive(Clone, Debug, PartialEq, Eq)]
19623pub enum EditorEvent {
19624 InputIgnored {
19625 text: Arc<str>,
19626 },
19627 InputHandled {
19628 utf16_range_to_replace: Option<Range<isize>>,
19629 text: Arc<str>,
19630 },
19631 ExcerptsAdded {
19632 buffer: Entity<Buffer>,
19633 predecessor: ExcerptId,
19634 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19635 },
19636 ExcerptsRemoved {
19637 ids: Vec<ExcerptId>,
19638 },
19639 BufferFoldToggled {
19640 ids: Vec<ExcerptId>,
19641 folded: bool,
19642 },
19643 ExcerptsEdited {
19644 ids: Vec<ExcerptId>,
19645 },
19646 ExcerptsExpanded {
19647 ids: Vec<ExcerptId>,
19648 },
19649 BufferEdited,
19650 Edited {
19651 transaction_id: clock::Lamport,
19652 },
19653 Reparsed(BufferId),
19654 Focused,
19655 FocusedIn,
19656 Blurred,
19657 DirtyChanged,
19658 Saved,
19659 TitleChanged,
19660 DiffBaseChanged,
19661 SelectionsChanged {
19662 local: bool,
19663 },
19664 ScrollPositionChanged {
19665 local: bool,
19666 autoscroll: bool,
19667 },
19668 Closed,
19669 TransactionUndone {
19670 transaction_id: clock::Lamport,
19671 },
19672 TransactionBegun {
19673 transaction_id: clock::Lamport,
19674 },
19675 Reloaded,
19676 CursorShapeChanged,
19677 PushedToNavHistory {
19678 anchor: Anchor,
19679 is_deactivate: bool,
19680 },
19681}
19682
19683impl EventEmitter<EditorEvent> for Editor {}
19684
19685impl Focusable for Editor {
19686 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19687 self.focus_handle.clone()
19688 }
19689}
19690
19691impl Render for Editor {
19692 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19693 let settings = ThemeSettings::get_global(cx);
19694
19695 let mut text_style = match self.mode {
19696 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19697 color: cx.theme().colors().editor_foreground,
19698 font_family: settings.ui_font.family.clone(),
19699 font_features: settings.ui_font.features.clone(),
19700 font_fallbacks: settings.ui_font.fallbacks.clone(),
19701 font_size: rems(0.875).into(),
19702 font_weight: settings.ui_font.weight,
19703 line_height: relative(settings.buffer_line_height.value()),
19704 ..Default::default()
19705 },
19706 EditorMode::Full { .. } => TextStyle {
19707 color: cx.theme().colors().editor_foreground,
19708 font_family: settings.buffer_font.family.clone(),
19709 font_features: settings.buffer_font.features.clone(),
19710 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19711 font_size: settings.buffer_font_size(cx).into(),
19712 font_weight: settings.buffer_font.weight,
19713 line_height: relative(settings.buffer_line_height.value()),
19714 ..Default::default()
19715 },
19716 };
19717 if let Some(text_style_refinement) = &self.text_style_refinement {
19718 text_style.refine(text_style_refinement)
19719 }
19720
19721 let background = match self.mode {
19722 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19723 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19724 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19725 };
19726
19727 EditorElement::new(
19728 &cx.entity(),
19729 EditorStyle {
19730 background,
19731 local_player: cx.theme().players().local(),
19732 text: text_style,
19733 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19734 syntax: cx.theme().syntax().clone(),
19735 status: cx.theme().status().clone(),
19736 inlay_hints_style: make_inlay_hints_style(cx),
19737 inline_completion_styles: make_suggestion_styles(cx),
19738 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19739 },
19740 )
19741 }
19742}
19743
19744impl EntityInputHandler for Editor {
19745 fn text_for_range(
19746 &mut self,
19747 range_utf16: Range<usize>,
19748 adjusted_range: &mut Option<Range<usize>>,
19749 _: &mut Window,
19750 cx: &mut Context<Self>,
19751 ) -> Option<String> {
19752 let snapshot = self.buffer.read(cx).read(cx);
19753 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19754 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19755 if (start.0..end.0) != range_utf16 {
19756 adjusted_range.replace(start.0..end.0);
19757 }
19758 Some(snapshot.text_for_range(start..end).collect())
19759 }
19760
19761 fn selected_text_range(
19762 &mut self,
19763 ignore_disabled_input: bool,
19764 _: &mut Window,
19765 cx: &mut Context<Self>,
19766 ) -> Option<UTF16Selection> {
19767 // Prevent the IME menu from appearing when holding down an alphabetic key
19768 // while input is disabled.
19769 if !ignore_disabled_input && !self.input_enabled {
19770 return None;
19771 }
19772
19773 let selection = self.selections.newest::<OffsetUtf16>(cx);
19774 let range = selection.range();
19775
19776 Some(UTF16Selection {
19777 range: range.start.0..range.end.0,
19778 reversed: selection.reversed,
19779 })
19780 }
19781
19782 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19783 let snapshot = self.buffer.read(cx).read(cx);
19784 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19785 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19786 }
19787
19788 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19789 self.clear_highlights::<InputComposition>(cx);
19790 self.ime_transaction.take();
19791 }
19792
19793 fn replace_text_in_range(
19794 &mut self,
19795 range_utf16: Option<Range<usize>>,
19796 text: &str,
19797 window: &mut Window,
19798 cx: &mut Context<Self>,
19799 ) {
19800 if !self.input_enabled {
19801 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19802 return;
19803 }
19804
19805 self.transact(window, cx, |this, window, cx| {
19806 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19807 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19808 Some(this.selection_replacement_ranges(range_utf16, cx))
19809 } else {
19810 this.marked_text_ranges(cx)
19811 };
19812
19813 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19814 let newest_selection_id = this.selections.newest_anchor().id;
19815 this.selections
19816 .all::<OffsetUtf16>(cx)
19817 .iter()
19818 .zip(ranges_to_replace.iter())
19819 .find_map(|(selection, range)| {
19820 if selection.id == newest_selection_id {
19821 Some(
19822 (range.start.0 as isize - selection.head().0 as isize)
19823 ..(range.end.0 as isize - selection.head().0 as isize),
19824 )
19825 } else {
19826 None
19827 }
19828 })
19829 });
19830
19831 cx.emit(EditorEvent::InputHandled {
19832 utf16_range_to_replace: range_to_replace,
19833 text: text.into(),
19834 });
19835
19836 if let Some(new_selected_ranges) = new_selected_ranges {
19837 this.change_selections(None, window, cx, |selections| {
19838 selections.select_ranges(new_selected_ranges)
19839 });
19840 this.backspace(&Default::default(), window, cx);
19841 }
19842
19843 this.handle_input(text, window, cx);
19844 });
19845
19846 if let Some(transaction) = self.ime_transaction {
19847 self.buffer.update(cx, |buffer, cx| {
19848 buffer.group_until_transaction(transaction, cx);
19849 });
19850 }
19851
19852 self.unmark_text(window, cx);
19853 }
19854
19855 fn replace_and_mark_text_in_range(
19856 &mut self,
19857 range_utf16: Option<Range<usize>>,
19858 text: &str,
19859 new_selected_range_utf16: Option<Range<usize>>,
19860 window: &mut Window,
19861 cx: &mut Context<Self>,
19862 ) {
19863 if !self.input_enabled {
19864 return;
19865 }
19866
19867 let transaction = self.transact(window, cx, |this, window, cx| {
19868 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19869 let snapshot = this.buffer.read(cx).read(cx);
19870 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19871 for marked_range in &mut marked_ranges {
19872 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19873 marked_range.start.0 += relative_range_utf16.start;
19874 marked_range.start =
19875 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19876 marked_range.end =
19877 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19878 }
19879 }
19880 Some(marked_ranges)
19881 } else if let Some(range_utf16) = range_utf16 {
19882 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19883 Some(this.selection_replacement_ranges(range_utf16, cx))
19884 } else {
19885 None
19886 };
19887
19888 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19889 let newest_selection_id = this.selections.newest_anchor().id;
19890 this.selections
19891 .all::<OffsetUtf16>(cx)
19892 .iter()
19893 .zip(ranges_to_replace.iter())
19894 .find_map(|(selection, range)| {
19895 if selection.id == newest_selection_id {
19896 Some(
19897 (range.start.0 as isize - selection.head().0 as isize)
19898 ..(range.end.0 as isize - selection.head().0 as isize),
19899 )
19900 } else {
19901 None
19902 }
19903 })
19904 });
19905
19906 cx.emit(EditorEvent::InputHandled {
19907 utf16_range_to_replace: range_to_replace,
19908 text: text.into(),
19909 });
19910
19911 if let Some(ranges) = ranges_to_replace {
19912 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19913 }
19914
19915 let marked_ranges = {
19916 let snapshot = this.buffer.read(cx).read(cx);
19917 this.selections
19918 .disjoint_anchors()
19919 .iter()
19920 .map(|selection| {
19921 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19922 })
19923 .collect::<Vec<_>>()
19924 };
19925
19926 if text.is_empty() {
19927 this.unmark_text(window, cx);
19928 } else {
19929 this.highlight_text::<InputComposition>(
19930 marked_ranges.clone(),
19931 HighlightStyle {
19932 underline: Some(UnderlineStyle {
19933 thickness: px(1.),
19934 color: None,
19935 wavy: false,
19936 }),
19937 ..Default::default()
19938 },
19939 cx,
19940 );
19941 }
19942
19943 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19944 let use_autoclose = this.use_autoclose;
19945 let use_auto_surround = this.use_auto_surround;
19946 this.set_use_autoclose(false);
19947 this.set_use_auto_surround(false);
19948 this.handle_input(text, window, cx);
19949 this.set_use_autoclose(use_autoclose);
19950 this.set_use_auto_surround(use_auto_surround);
19951
19952 if let Some(new_selected_range) = new_selected_range_utf16 {
19953 let snapshot = this.buffer.read(cx).read(cx);
19954 let new_selected_ranges = marked_ranges
19955 .into_iter()
19956 .map(|marked_range| {
19957 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19958 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19959 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19960 snapshot.clip_offset_utf16(new_start, Bias::Left)
19961 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19962 })
19963 .collect::<Vec<_>>();
19964
19965 drop(snapshot);
19966 this.change_selections(None, window, cx, |selections| {
19967 selections.select_ranges(new_selected_ranges)
19968 });
19969 }
19970 });
19971
19972 self.ime_transaction = self.ime_transaction.or(transaction);
19973 if let Some(transaction) = self.ime_transaction {
19974 self.buffer.update(cx, |buffer, cx| {
19975 buffer.group_until_transaction(transaction, cx);
19976 });
19977 }
19978
19979 if self.text_highlights::<InputComposition>(cx).is_none() {
19980 self.ime_transaction.take();
19981 }
19982 }
19983
19984 fn bounds_for_range(
19985 &mut self,
19986 range_utf16: Range<usize>,
19987 element_bounds: gpui::Bounds<Pixels>,
19988 window: &mut Window,
19989 cx: &mut Context<Self>,
19990 ) -> Option<gpui::Bounds<Pixels>> {
19991 let text_layout_details = self.text_layout_details(window);
19992 let gpui::Size {
19993 width: em_width,
19994 height: line_height,
19995 } = self.character_size(window);
19996
19997 let snapshot = self.snapshot(window, cx);
19998 let scroll_position = snapshot.scroll_position();
19999 let scroll_left = scroll_position.x * em_width;
20000
20001 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20002 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20003 + self.gutter_dimensions.width
20004 + self.gutter_dimensions.margin;
20005 let y = line_height * (start.row().as_f32() - scroll_position.y);
20006
20007 Some(Bounds {
20008 origin: element_bounds.origin + point(x, y),
20009 size: size(em_width, line_height),
20010 })
20011 }
20012
20013 fn character_index_for_point(
20014 &mut self,
20015 point: gpui::Point<Pixels>,
20016 _window: &mut Window,
20017 _cx: &mut Context<Self>,
20018 ) -> Option<usize> {
20019 let position_map = self.last_position_map.as_ref()?;
20020 if !position_map.text_hitbox.contains(&point) {
20021 return None;
20022 }
20023 let display_point = position_map.point_for_position(point).previous_valid;
20024 let anchor = position_map
20025 .snapshot
20026 .display_point_to_anchor(display_point, Bias::Left);
20027 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20028 Some(utf16_offset.0)
20029 }
20030}
20031
20032trait SelectionExt {
20033 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20034 fn spanned_rows(
20035 &self,
20036 include_end_if_at_line_start: bool,
20037 map: &DisplaySnapshot,
20038 ) -> Range<MultiBufferRow>;
20039}
20040
20041impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20042 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20043 let start = self
20044 .start
20045 .to_point(&map.buffer_snapshot)
20046 .to_display_point(map);
20047 let end = self
20048 .end
20049 .to_point(&map.buffer_snapshot)
20050 .to_display_point(map);
20051 if self.reversed {
20052 end..start
20053 } else {
20054 start..end
20055 }
20056 }
20057
20058 fn spanned_rows(
20059 &self,
20060 include_end_if_at_line_start: bool,
20061 map: &DisplaySnapshot,
20062 ) -> Range<MultiBufferRow> {
20063 let start = self.start.to_point(&map.buffer_snapshot);
20064 let mut end = self.end.to_point(&map.buffer_snapshot);
20065 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20066 end.row -= 1;
20067 }
20068
20069 let buffer_start = map.prev_line_boundary(start).0;
20070 let buffer_end = map.next_line_boundary(end).0;
20071 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20072 }
20073}
20074
20075impl<T: InvalidationRegion> InvalidationStack<T> {
20076 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20077 where
20078 S: Clone + ToOffset,
20079 {
20080 while let Some(region) = self.last() {
20081 let all_selections_inside_invalidation_ranges =
20082 if selections.len() == region.ranges().len() {
20083 selections
20084 .iter()
20085 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20086 .all(|(selection, invalidation_range)| {
20087 let head = selection.head().to_offset(buffer);
20088 invalidation_range.start <= head && invalidation_range.end >= head
20089 })
20090 } else {
20091 false
20092 };
20093
20094 if all_selections_inside_invalidation_ranges {
20095 break;
20096 } else {
20097 self.pop();
20098 }
20099 }
20100 }
20101}
20102
20103impl<T> Default for InvalidationStack<T> {
20104 fn default() -> Self {
20105 Self(Default::default())
20106 }
20107}
20108
20109impl<T> Deref for InvalidationStack<T> {
20110 type Target = Vec<T>;
20111
20112 fn deref(&self) -> &Self::Target {
20113 &self.0
20114 }
20115}
20116
20117impl<T> DerefMut for InvalidationStack<T> {
20118 fn deref_mut(&mut self) -> &mut Self::Target {
20119 &mut self.0
20120 }
20121}
20122
20123impl InvalidationRegion for SnippetState {
20124 fn ranges(&self) -> &[Range<Anchor>] {
20125 &self.ranges[self.active_index]
20126 }
20127}
20128
20129fn inline_completion_edit_text(
20130 current_snapshot: &BufferSnapshot,
20131 edits: &[(Range<Anchor>, String)],
20132 edit_preview: &EditPreview,
20133 include_deletions: bool,
20134 cx: &App,
20135) -> HighlightedText {
20136 let edits = edits
20137 .iter()
20138 .map(|(anchor, text)| {
20139 (
20140 anchor.start.text_anchor..anchor.end.text_anchor,
20141 text.clone(),
20142 )
20143 })
20144 .collect::<Vec<_>>();
20145
20146 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20147}
20148
20149pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20150 match severity {
20151 DiagnosticSeverity::ERROR => colors.error,
20152 DiagnosticSeverity::WARNING => colors.warning,
20153 DiagnosticSeverity::INFORMATION => colors.info,
20154 DiagnosticSeverity::HINT => colors.info,
20155 _ => colors.ignored,
20156 }
20157}
20158
20159pub fn styled_runs_for_code_label<'a>(
20160 label: &'a CodeLabel,
20161 syntax_theme: &'a theme::SyntaxTheme,
20162) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20163 let fade_out = HighlightStyle {
20164 fade_out: Some(0.35),
20165 ..Default::default()
20166 };
20167
20168 let mut prev_end = label.filter_range.end;
20169 label
20170 .runs
20171 .iter()
20172 .enumerate()
20173 .flat_map(move |(ix, (range, highlight_id))| {
20174 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20175 style
20176 } else {
20177 return Default::default();
20178 };
20179 let mut muted_style = style;
20180 muted_style.highlight(fade_out);
20181
20182 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20183 if range.start >= label.filter_range.end {
20184 if range.start > prev_end {
20185 runs.push((prev_end..range.start, fade_out));
20186 }
20187 runs.push((range.clone(), muted_style));
20188 } else if range.end <= label.filter_range.end {
20189 runs.push((range.clone(), style));
20190 } else {
20191 runs.push((range.start..label.filter_range.end, style));
20192 runs.push((label.filter_range.end..range.end, muted_style));
20193 }
20194 prev_end = cmp::max(prev_end, range.end);
20195
20196 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20197 runs.push((prev_end..label.text.len(), fade_out));
20198 }
20199
20200 runs
20201 })
20202}
20203
20204pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20205 let mut prev_index = 0;
20206 let mut prev_codepoint: Option<char> = None;
20207 text.char_indices()
20208 .chain([(text.len(), '\0')])
20209 .filter_map(move |(index, codepoint)| {
20210 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20211 let is_boundary = index == text.len()
20212 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20213 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20214 if is_boundary {
20215 let chunk = &text[prev_index..index];
20216 prev_index = index;
20217 Some(chunk)
20218 } else {
20219 None
20220 }
20221 })
20222}
20223
20224pub trait RangeToAnchorExt: Sized {
20225 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20226
20227 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20228 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20229 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20230 }
20231}
20232
20233impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20234 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20235 let start_offset = self.start.to_offset(snapshot);
20236 let end_offset = self.end.to_offset(snapshot);
20237 if start_offset == end_offset {
20238 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20239 } else {
20240 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20241 }
20242 }
20243}
20244
20245pub trait RowExt {
20246 fn as_f32(&self) -> f32;
20247
20248 fn next_row(&self) -> Self;
20249
20250 fn previous_row(&self) -> Self;
20251
20252 fn minus(&self, other: Self) -> u32;
20253}
20254
20255impl RowExt for DisplayRow {
20256 fn as_f32(&self) -> f32 {
20257 self.0 as f32
20258 }
20259
20260 fn next_row(&self) -> Self {
20261 Self(self.0 + 1)
20262 }
20263
20264 fn previous_row(&self) -> Self {
20265 Self(self.0.saturating_sub(1))
20266 }
20267
20268 fn minus(&self, other: Self) -> u32 {
20269 self.0 - other.0
20270 }
20271}
20272
20273impl RowExt for MultiBufferRow {
20274 fn as_f32(&self) -> f32 {
20275 self.0 as f32
20276 }
20277
20278 fn next_row(&self) -> Self {
20279 Self(self.0 + 1)
20280 }
20281
20282 fn previous_row(&self) -> Self {
20283 Self(self.0.saturating_sub(1))
20284 }
20285
20286 fn minus(&self, other: Self) -> u32 {
20287 self.0 - other.0
20288 }
20289}
20290
20291trait RowRangeExt {
20292 type Row;
20293
20294 fn len(&self) -> usize;
20295
20296 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20297}
20298
20299impl RowRangeExt for Range<MultiBufferRow> {
20300 type Row = MultiBufferRow;
20301
20302 fn len(&self) -> usize {
20303 (self.end.0 - self.start.0) as usize
20304 }
20305
20306 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20307 (self.start.0..self.end.0).map(MultiBufferRow)
20308 }
20309}
20310
20311impl RowRangeExt for Range<DisplayRow> {
20312 type Row = DisplayRow;
20313
20314 fn len(&self) -> usize {
20315 (self.end.0 - self.start.0) as usize
20316 }
20317
20318 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20319 (self.start.0..self.end.0).map(DisplayRow)
20320 }
20321}
20322
20323/// If select range has more than one line, we
20324/// just point the cursor to range.start.
20325fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20326 if range.start.row == range.end.row {
20327 range
20328 } else {
20329 range.start..range.start
20330 }
20331}
20332pub struct KillRing(ClipboardItem);
20333impl Global for KillRing {}
20334
20335const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20336
20337enum BreakpointPromptEditAction {
20338 Log,
20339 Condition,
20340 HitCondition,
20341}
20342
20343struct BreakpointPromptEditor {
20344 pub(crate) prompt: Entity<Editor>,
20345 editor: WeakEntity<Editor>,
20346 breakpoint_anchor: Anchor,
20347 breakpoint: Breakpoint,
20348 edit_action: BreakpointPromptEditAction,
20349 block_ids: HashSet<CustomBlockId>,
20350 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20351 _subscriptions: Vec<Subscription>,
20352}
20353
20354impl BreakpointPromptEditor {
20355 const MAX_LINES: u8 = 4;
20356
20357 fn new(
20358 editor: WeakEntity<Editor>,
20359 breakpoint_anchor: Anchor,
20360 breakpoint: Breakpoint,
20361 edit_action: BreakpointPromptEditAction,
20362 window: &mut Window,
20363 cx: &mut Context<Self>,
20364 ) -> Self {
20365 let base_text = match edit_action {
20366 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20367 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20368 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20369 }
20370 .map(|msg| msg.to_string())
20371 .unwrap_or_default();
20372
20373 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20374 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20375
20376 let prompt = cx.new(|cx| {
20377 let mut prompt = Editor::new(
20378 EditorMode::AutoHeight {
20379 max_lines: Self::MAX_LINES as usize,
20380 },
20381 buffer,
20382 None,
20383 window,
20384 cx,
20385 );
20386 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20387 prompt.set_show_cursor_when_unfocused(false, cx);
20388 prompt.set_placeholder_text(
20389 match edit_action {
20390 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20391 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20392 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20393 },
20394 cx,
20395 );
20396
20397 prompt
20398 });
20399
20400 Self {
20401 prompt,
20402 editor,
20403 breakpoint_anchor,
20404 breakpoint,
20405 edit_action,
20406 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20407 block_ids: Default::default(),
20408 _subscriptions: vec![],
20409 }
20410 }
20411
20412 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20413 self.block_ids.extend(block_ids)
20414 }
20415
20416 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20417 if let Some(editor) = self.editor.upgrade() {
20418 let message = self
20419 .prompt
20420 .read(cx)
20421 .buffer
20422 .read(cx)
20423 .as_singleton()
20424 .expect("A multi buffer in breakpoint prompt isn't possible")
20425 .read(cx)
20426 .as_rope()
20427 .to_string();
20428
20429 editor.update(cx, |editor, cx| {
20430 editor.edit_breakpoint_at_anchor(
20431 self.breakpoint_anchor,
20432 self.breakpoint.clone(),
20433 match self.edit_action {
20434 BreakpointPromptEditAction::Log => {
20435 BreakpointEditAction::EditLogMessage(message.into())
20436 }
20437 BreakpointPromptEditAction::Condition => {
20438 BreakpointEditAction::EditCondition(message.into())
20439 }
20440 BreakpointPromptEditAction::HitCondition => {
20441 BreakpointEditAction::EditHitCondition(message.into())
20442 }
20443 },
20444 cx,
20445 );
20446
20447 editor.remove_blocks(self.block_ids.clone(), None, cx);
20448 cx.focus_self(window);
20449 });
20450 }
20451 }
20452
20453 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20454 self.editor
20455 .update(cx, |editor, cx| {
20456 editor.remove_blocks(self.block_ids.clone(), None, cx);
20457 window.focus(&editor.focus_handle);
20458 })
20459 .log_err();
20460 }
20461
20462 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20463 let settings = ThemeSettings::get_global(cx);
20464 let text_style = TextStyle {
20465 color: if self.prompt.read(cx).read_only(cx) {
20466 cx.theme().colors().text_disabled
20467 } else {
20468 cx.theme().colors().text
20469 },
20470 font_family: settings.buffer_font.family.clone(),
20471 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20472 font_size: settings.buffer_font_size(cx).into(),
20473 font_weight: settings.buffer_font.weight,
20474 line_height: relative(settings.buffer_line_height.value()),
20475 ..Default::default()
20476 };
20477 EditorElement::new(
20478 &self.prompt,
20479 EditorStyle {
20480 background: cx.theme().colors().editor_background,
20481 local_player: cx.theme().players().local(),
20482 text: text_style,
20483 ..Default::default()
20484 },
20485 )
20486 }
20487}
20488
20489impl Render for BreakpointPromptEditor {
20490 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20491 let gutter_dimensions = *self.gutter_dimensions.lock();
20492 h_flex()
20493 .key_context("Editor")
20494 .bg(cx.theme().colors().editor_background)
20495 .border_y_1()
20496 .border_color(cx.theme().status().info_border)
20497 .size_full()
20498 .py(window.line_height() / 2.5)
20499 .on_action(cx.listener(Self::confirm))
20500 .on_action(cx.listener(Self::cancel))
20501 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20502 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20503 }
20504}
20505
20506impl Focusable for BreakpointPromptEditor {
20507 fn focus_handle(&self, cx: &App) -> FocusHandle {
20508 self.prompt.focus_handle(cx)
20509 }
20510}
20511
20512fn all_edits_insertions_or_deletions(
20513 edits: &Vec<(Range<Anchor>, String)>,
20514 snapshot: &MultiBufferSnapshot,
20515) -> bool {
20516 let mut all_insertions = true;
20517 let mut all_deletions = true;
20518
20519 for (range, new_text) in edits.iter() {
20520 let range_is_empty = range.to_offset(&snapshot).is_empty();
20521 let text_is_empty = new_text.is_empty();
20522
20523 if range_is_empty != text_is_empty {
20524 if range_is_empty {
20525 all_deletions = false;
20526 } else {
20527 all_insertions = false;
20528 }
20529 } else {
20530 return false;
20531 }
20532
20533 if !all_insertions && !all_deletions {
20534 return false;
20535 }
20536 }
20537 all_insertions || all_deletions
20538}
20539
20540struct MissingEditPredictionKeybindingTooltip;
20541
20542impl Render for MissingEditPredictionKeybindingTooltip {
20543 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20544 ui::tooltip_container(window, cx, |container, _, cx| {
20545 container
20546 .flex_shrink_0()
20547 .max_w_80()
20548 .min_h(rems_from_px(124.))
20549 .justify_between()
20550 .child(
20551 v_flex()
20552 .flex_1()
20553 .text_ui_sm(cx)
20554 .child(Label::new("Conflict with Accept Keybinding"))
20555 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20556 )
20557 .child(
20558 h_flex()
20559 .pb_1()
20560 .gap_1()
20561 .items_end()
20562 .w_full()
20563 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20564 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20565 }))
20566 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20567 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20568 })),
20569 )
20570 })
20571 }
20572}
20573
20574#[derive(Debug, Clone, Copy, PartialEq)]
20575pub struct LineHighlight {
20576 pub background: Background,
20577 pub border: Option<gpui::Hsla>,
20578}
20579
20580impl From<Hsla> for LineHighlight {
20581 fn from(hsla: Hsla) -> Self {
20582 Self {
20583 background: hsla.into(),
20584 border: None,
20585 }
20586 }
20587}
20588
20589impl From<Background> for LineHighlight {
20590 fn from(background: Background) -> Self {
20591 Self {
20592 background,
20593 border: None,
20594 }
20595 }
20596}
20597
20598fn render_diff_hunk_controls(
20599 row: u32,
20600 status: &DiffHunkStatus,
20601 hunk_range: Range<Anchor>,
20602 is_created_file: bool,
20603 line_height: Pixels,
20604 editor: &Entity<Editor>,
20605 _window: &mut Window,
20606 cx: &mut App,
20607) -> AnyElement {
20608 h_flex()
20609 .h(line_height)
20610 .mr_1()
20611 .gap_1()
20612 .px_0p5()
20613 .pb_1()
20614 .border_x_1()
20615 .border_b_1()
20616 .border_color(cx.theme().colors().border_variant)
20617 .rounded_b_lg()
20618 .bg(cx.theme().colors().editor_background)
20619 .gap_1()
20620 .occlude()
20621 .shadow_md()
20622 .child(if status.has_secondary_hunk() {
20623 Button::new(("stage", row as u64), "Stage")
20624 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20625 .tooltip({
20626 let focus_handle = editor.focus_handle(cx);
20627 move |window, cx| {
20628 Tooltip::for_action_in(
20629 "Stage Hunk",
20630 &::git::ToggleStaged,
20631 &focus_handle,
20632 window,
20633 cx,
20634 )
20635 }
20636 })
20637 .on_click({
20638 let editor = editor.clone();
20639 move |_event, _window, cx| {
20640 editor.update(cx, |editor, cx| {
20641 editor.stage_or_unstage_diff_hunks(
20642 true,
20643 vec![hunk_range.start..hunk_range.start],
20644 cx,
20645 );
20646 });
20647 }
20648 })
20649 } else {
20650 Button::new(("unstage", row as u64), "Unstage")
20651 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20652 .tooltip({
20653 let focus_handle = editor.focus_handle(cx);
20654 move |window, cx| {
20655 Tooltip::for_action_in(
20656 "Unstage Hunk",
20657 &::git::ToggleStaged,
20658 &focus_handle,
20659 window,
20660 cx,
20661 )
20662 }
20663 })
20664 .on_click({
20665 let editor = editor.clone();
20666 move |_event, _window, cx| {
20667 editor.update(cx, |editor, cx| {
20668 editor.stage_or_unstage_diff_hunks(
20669 false,
20670 vec![hunk_range.start..hunk_range.start],
20671 cx,
20672 );
20673 });
20674 }
20675 })
20676 })
20677 .child(
20678 Button::new(("restore", row as u64), "Restore")
20679 .tooltip({
20680 let focus_handle = editor.focus_handle(cx);
20681 move |window, cx| {
20682 Tooltip::for_action_in(
20683 "Restore Hunk",
20684 &::git::Restore,
20685 &focus_handle,
20686 window,
20687 cx,
20688 )
20689 }
20690 })
20691 .on_click({
20692 let editor = editor.clone();
20693 move |_event, window, cx| {
20694 editor.update(cx, |editor, cx| {
20695 let snapshot = editor.snapshot(window, cx);
20696 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20697 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20698 });
20699 }
20700 })
20701 .disabled(is_created_file),
20702 )
20703 .when(
20704 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20705 |el| {
20706 el.child(
20707 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20708 .shape(IconButtonShape::Square)
20709 .icon_size(IconSize::Small)
20710 // .disabled(!has_multiple_hunks)
20711 .tooltip({
20712 let focus_handle = editor.focus_handle(cx);
20713 move |window, cx| {
20714 Tooltip::for_action_in(
20715 "Next Hunk",
20716 &GoToHunk,
20717 &focus_handle,
20718 window,
20719 cx,
20720 )
20721 }
20722 })
20723 .on_click({
20724 let editor = editor.clone();
20725 move |_event, window, cx| {
20726 editor.update(cx, |editor, cx| {
20727 let snapshot = editor.snapshot(window, cx);
20728 let position =
20729 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20730 editor.go_to_hunk_before_or_after_position(
20731 &snapshot,
20732 position,
20733 Direction::Next,
20734 window,
20735 cx,
20736 );
20737 editor.expand_selected_diff_hunks(cx);
20738 });
20739 }
20740 }),
20741 )
20742 .child(
20743 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20744 .shape(IconButtonShape::Square)
20745 .icon_size(IconSize::Small)
20746 // .disabled(!has_multiple_hunks)
20747 .tooltip({
20748 let focus_handle = editor.focus_handle(cx);
20749 move |window, cx| {
20750 Tooltip::for_action_in(
20751 "Previous Hunk",
20752 &GoToPreviousHunk,
20753 &focus_handle,
20754 window,
20755 cx,
20756 )
20757 }
20758 })
20759 .on_click({
20760 let editor = editor.clone();
20761 move |_event, window, cx| {
20762 editor.update(cx, |editor, cx| {
20763 let snapshot = editor.snapshot(window, cx);
20764 let point =
20765 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20766 editor.go_to_hunk_before_or_after_position(
20767 &snapshot,
20768 point,
20769 Direction::Prev,
20770 window,
20771 cx,
20772 );
20773 editor.expand_selected_diff_hunks(cx);
20774 });
20775 }
20776 }),
20777 )
20778 },
20779 )
20780 .into_any_element()
20781}