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 code_completion_tests;
44#[cfg(test)]
45mod editor_tests;
46#[cfg(test)]
47mod inline_completion_tests;
48mod signature_help;
49#[cfg(any(test, feature = "test-support"))]
50pub mod test;
51
52pub(crate) use actions::*;
53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{Context as _, Result, anyhow};
56use blink_manager::BlinkManager;
57use buffer_diff::DiffHunkStatus;
58use client::{Collaborator, ParticipantIndex};
59use clock::ReplicaId;
60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
61use convert_case::{Case, Casing};
62use display_map::*;
63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
64use editor_settings::GoToDefinitionFallback;
65pub use editor_settings::{
66 CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
67 ShowScrollbar,
68};
69pub use editor_settings_controls::*;
70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
71pub use element::{
72 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
73};
74use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt};
75use futures::{
76 FutureExt,
77 future::{self, Shared, join},
78};
79use fuzzy::StringMatchCandidate;
80
81use ::git::blame::BlameEntry;
82use ::git::{Restore, blame::ParsedCommitMessage};
83use code_context_menus::{
84 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
85 CompletionsMenu, ContextMenuOrigin,
86};
87use git::blame::{GitBlame, GlobalBlameRenderer};
88use gpui::{
89 Action, Animation, AnimationExt, AnyElement, App, AppContext, AsyncWindowContext,
90 AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
91 DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
92 Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
93 MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, ScrollHandle,
94 SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
95 UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
96 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
97};
98use highlight_matching_bracket::refresh_matching_bracket_highlights;
99use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
100pub use hover_popover::hover_markdown_style;
101use hover_popover::{HoverState, hide_hover};
102use indent_guides::ActiveIndentGuidesState;
103use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
104pub use inline_completion::Direction;
105use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
106pub use items::MAX_TAB_TITLE_LEN;
107use itertools::Itertools;
108use language::{
109 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
110 CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
111 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
112 TransactionId, TreeSitterOptions, WordsQuery,
113 language_settings::{
114 self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
115 all_language_settings, language_settings,
116 },
117 point_from_lsp, text_diff_with_options,
118};
119use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
120use linked_editing_ranges::refresh_linked_ranges;
121use markdown::Markdown;
122use mouse_context_menu::MouseContextMenu;
123use persistence::DB;
124use project::{
125 ProjectPath,
126 debugger::{
127 breakpoint_store::{
128 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
129 },
130 session::{Session, SessionEvent},
131 },
132};
133
134pub use git::blame::BlameRenderer;
135pub use proposed_changes_editor::{
136 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
137};
138use smallvec::smallvec;
139use std::{cell::OnceCell, iter::Peekable};
140use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
141
142pub use lsp::CompletionContext;
143use lsp::{
144 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
145 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
146};
147
148use language::BufferSnapshot;
149pub use lsp_ext::lsp_tasks;
150use movement::TextLayoutDetails;
151pub use multi_buffer::{
152 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
153 RowInfo, ToOffset, ToPoint,
154};
155use multi_buffer::{
156 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
157 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
158};
159use parking_lot::Mutex;
160use project::{
161 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
162 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
163 TaskSourceKind,
164 debugger::breakpoint_store::Breakpoint,
165 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
166 project_settings::{GitGutterSetting, ProjectSettings},
167};
168use rand::prelude::*;
169use rpc::{ErrorExt, proto::*};
170use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
171use selections_collection::{
172 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
173};
174use serde::{Deserialize, Serialize};
175use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
176use smallvec::SmallVec;
177use snippet::Snippet;
178use std::sync::Arc;
179use std::{
180 any::TypeId,
181 borrow::Cow,
182 cell::RefCell,
183 cmp::{self, Ordering, Reverse},
184 mem,
185 num::NonZeroU32,
186 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
187 path::{Path, PathBuf},
188 rc::Rc,
189 time::{Duration, Instant},
190};
191pub use sum_tree::Bias;
192use sum_tree::TreeMap;
193use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
194use theme::{
195 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
196 observe_buffer_font_size_adjustment,
197};
198use ui::{
199 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
200 IconSize, Key, Tooltip, h_flex, prelude::*,
201};
202use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
203use workspace::{
204 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
205 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
206 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
207 item::{ItemHandle, PreviewTabsSettings},
208 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
209 searchable::SearchEvent,
210};
211
212use crate::hover_links::{find_url, find_url_from_range};
213use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
214
215pub const FILE_HEADER_HEIGHT: u32 = 2;
216pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
217pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
218const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
219const MAX_LINE_LEN: usize = 1024;
220const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
221const MAX_SELECTION_HISTORY_LEN: usize = 1024;
222pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
223#[doc(hidden)]
224pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
225const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
226
227pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
228pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
229pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
230
231pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
232pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
233pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
234
235pub type RenderDiffHunkControlsFn = Arc<
236 dyn Fn(
237 u32,
238 &DiffHunkStatus,
239 Range<Anchor>,
240 bool,
241 Pixels,
242 &Entity<Editor>,
243 &mut Window,
244 &mut App,
245 ) -> AnyElement,
246>;
247
248const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
249 alt: true,
250 shift: true,
251 control: false,
252 platform: false,
253 function: false,
254};
255
256struct InlineValueCache {
257 enabled: bool,
258 inlays: Vec<InlayId>,
259 refresh_task: Task<Option<()>>,
260}
261
262impl InlineValueCache {
263 fn new(enabled: bool) -> Self {
264 Self {
265 enabled,
266 inlays: Vec::new(),
267 refresh_task: Task::ready(None),
268 }
269 }
270}
271
272#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
273pub enum InlayId {
274 InlineCompletion(usize),
275 Hint(usize),
276 DebuggerValue(usize),
277}
278
279impl InlayId {
280 fn id(&self) -> usize {
281 match self {
282 Self::InlineCompletion(id) => *id,
283 Self::Hint(id) => *id,
284 Self::DebuggerValue(id) => *id,
285 }
286 }
287}
288
289pub enum DebugCurrentRowHighlight {}
290enum DocumentHighlightRead {}
291enum DocumentHighlightWrite {}
292enum InputComposition {}
293enum SelectedTextHighlight {}
294
295pub enum ConflictsOuter {}
296pub enum ConflictsOurs {}
297pub enum ConflictsTheirs {}
298pub enum ConflictsOursMarker {}
299pub enum ConflictsTheirsMarker {}
300
301#[derive(Debug, Copy, Clone, PartialEq, Eq)]
302pub enum Navigated {
303 Yes,
304 No,
305}
306
307impl Navigated {
308 pub fn from_bool(yes: bool) -> Navigated {
309 if yes { Navigated::Yes } else { Navigated::No }
310 }
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
314enum DisplayDiffHunk {
315 Folded {
316 display_row: DisplayRow,
317 },
318 Unfolded {
319 is_created_file: bool,
320 diff_base_byte_range: Range<usize>,
321 display_row_range: Range<DisplayRow>,
322 multi_buffer_range: Range<Anchor>,
323 status: DiffHunkStatus,
324 },
325}
326
327pub enum HideMouseCursorOrigin {
328 TypingAction,
329 MovementAction,
330}
331
332pub fn init_settings(cx: &mut App) {
333 EditorSettings::register(cx);
334}
335
336pub fn init(cx: &mut App) {
337 init_settings(cx);
338
339 cx.set_global(GlobalBlameRenderer(Arc::new(())));
340
341 workspace::register_project_item::<Editor>(cx);
342 workspace::FollowableViewRegistry::register::<Editor>(cx);
343 workspace::register_serializable_item::<Editor>(cx);
344
345 cx.observe_new(
346 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
347 workspace.register_action(Editor::new_file);
348 workspace.register_action(Editor::new_file_vertical);
349 workspace.register_action(Editor::new_file_horizontal);
350 workspace.register_action(Editor::cancel_language_server_work);
351 },
352 )
353 .detach();
354
355 cx.on_action(move |_: &workspace::NewFile, cx| {
356 let app_state = workspace::AppState::global(cx);
357 if let Some(app_state) = app_state.upgrade() {
358 workspace::open_new(
359 Default::default(),
360 app_state,
361 cx,
362 |workspace, window, cx| {
363 Editor::new_file(workspace, &Default::default(), window, cx)
364 },
365 )
366 .detach();
367 }
368 });
369 cx.on_action(move |_: &workspace::NewWindow, cx| {
370 let app_state = workspace::AppState::global(cx);
371 if let Some(app_state) = app_state.upgrade() {
372 workspace::open_new(
373 Default::default(),
374 app_state,
375 cx,
376 |workspace, window, cx| {
377 cx.activate(true);
378 Editor::new_file(workspace, &Default::default(), window, cx)
379 },
380 )
381 .detach();
382 }
383 });
384}
385
386pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
387 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
388}
389
390pub trait DiagnosticRenderer {
391 fn render_group(
392 &self,
393 diagnostic_group: Vec<DiagnosticEntry<Point>>,
394 buffer_id: BufferId,
395 snapshot: EditorSnapshot,
396 editor: WeakEntity<Editor>,
397 cx: &mut App,
398 ) -> Vec<BlockProperties<Anchor>>;
399
400 fn render_hover(
401 &self,
402 diagnostic_group: Vec<DiagnosticEntry<Point>>,
403 range: Range<Point>,
404 buffer_id: BufferId,
405 cx: &mut App,
406 ) -> Option<Entity<markdown::Markdown>>;
407
408 fn open_link(
409 &self,
410 editor: &mut Editor,
411 link: SharedString,
412 window: &mut Window,
413 cx: &mut Context<Editor>,
414 );
415}
416
417pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
418
419impl GlobalDiagnosticRenderer {
420 fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
421 cx.try_global::<Self>().map(|g| g.0.clone())
422 }
423}
424
425impl gpui::Global for GlobalDiagnosticRenderer {}
426pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
427 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
428}
429
430pub struct SearchWithinRange;
431
432trait InvalidationRegion {
433 fn ranges(&self) -> &[Range<Anchor>];
434}
435
436#[derive(Clone, Debug, PartialEq)]
437pub enum SelectPhase {
438 Begin {
439 position: DisplayPoint,
440 add: bool,
441 click_count: usize,
442 },
443 BeginColumnar {
444 position: DisplayPoint,
445 reset: bool,
446 goal_column: u32,
447 },
448 Extend {
449 position: DisplayPoint,
450 click_count: usize,
451 },
452 Update {
453 position: DisplayPoint,
454 goal_column: u32,
455 scroll_delta: gpui::Point<f32>,
456 },
457 End,
458}
459
460#[derive(Clone, Debug)]
461pub enum SelectMode {
462 Character,
463 Word(Range<Anchor>),
464 Line(Range<Anchor>),
465 All,
466}
467
468#[derive(Copy, Clone, PartialEq, Eq, Debug)]
469pub enum EditorMode {
470 SingleLine {
471 auto_width: bool,
472 },
473 AutoHeight {
474 max_lines: usize,
475 },
476 Full {
477 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
478 scale_ui_elements_with_buffer_font_size: bool,
479 /// When set to `true`, the editor will render a background for the active line.
480 show_active_line_background: bool,
481 /// When set to `true`, the editor's height will be determined by its content.
482 sized_by_content: bool,
483 },
484}
485
486impl EditorMode {
487 pub fn full() -> Self {
488 Self::Full {
489 scale_ui_elements_with_buffer_font_size: true,
490 show_active_line_background: true,
491 sized_by_content: false,
492 }
493 }
494
495 pub fn is_full(&self) -> bool {
496 matches!(self, Self::Full { .. })
497 }
498}
499
500#[derive(Copy, Clone, Debug)]
501pub enum SoftWrap {
502 /// Prefer not to wrap at all.
503 ///
504 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
505 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
506 GitDiff,
507 /// Prefer a single line generally, unless an overly long line is encountered.
508 None,
509 /// Soft wrap lines that exceed the editor width.
510 EditorWidth,
511 /// Soft wrap lines at the preferred line length.
512 Column(u32),
513 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
514 Bounded(u32),
515}
516
517#[derive(Clone)]
518pub struct EditorStyle {
519 pub background: Hsla,
520 pub local_player: PlayerColor,
521 pub text: TextStyle,
522 pub scrollbar_width: Pixels,
523 pub syntax: Arc<SyntaxTheme>,
524 pub status: StatusColors,
525 pub inlay_hints_style: HighlightStyle,
526 pub inline_completion_styles: InlineCompletionStyles,
527 pub unnecessary_code_fade: f32,
528}
529
530impl Default for EditorStyle {
531 fn default() -> Self {
532 Self {
533 background: Hsla::default(),
534 local_player: PlayerColor::default(),
535 text: TextStyle::default(),
536 scrollbar_width: Pixels::default(),
537 syntax: Default::default(),
538 // HACK: Status colors don't have a real default.
539 // We should look into removing the status colors from the editor
540 // style and retrieve them directly from the theme.
541 status: StatusColors::dark(),
542 inlay_hints_style: HighlightStyle::default(),
543 inline_completion_styles: InlineCompletionStyles {
544 insertion: HighlightStyle::default(),
545 whitespace: HighlightStyle::default(),
546 },
547 unnecessary_code_fade: Default::default(),
548 }
549 }
550}
551
552pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
553 let show_background = language_settings::language_settings(None, None, cx)
554 .inlay_hints
555 .show_background;
556
557 HighlightStyle {
558 color: Some(cx.theme().status().hint),
559 background_color: show_background.then(|| cx.theme().status().hint_background),
560 ..HighlightStyle::default()
561 }
562}
563
564pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
565 InlineCompletionStyles {
566 insertion: HighlightStyle {
567 color: Some(cx.theme().status().predictive),
568 ..HighlightStyle::default()
569 },
570 whitespace: HighlightStyle {
571 background_color: Some(cx.theme().status().created_background),
572 ..HighlightStyle::default()
573 },
574 }
575}
576
577type CompletionId = usize;
578
579pub(crate) enum EditDisplayMode {
580 TabAccept,
581 DiffPopover,
582 Inline,
583}
584
585enum InlineCompletion {
586 Edit {
587 edits: Vec<(Range<Anchor>, String)>,
588 edit_preview: Option<EditPreview>,
589 display_mode: EditDisplayMode,
590 snapshot: BufferSnapshot,
591 },
592 Move {
593 target: Anchor,
594 snapshot: BufferSnapshot,
595 },
596}
597
598struct InlineCompletionState {
599 inlay_ids: Vec<InlayId>,
600 completion: InlineCompletion,
601 completion_id: Option<SharedString>,
602 invalidation_range: Range<Anchor>,
603}
604
605enum EditPredictionSettings {
606 Disabled,
607 Enabled {
608 show_in_menu: bool,
609 preview_requires_modifier: bool,
610 },
611}
612
613enum InlineCompletionHighlight {}
614
615#[derive(Debug, Clone)]
616struct InlineDiagnostic {
617 message: SharedString,
618 group_id: usize,
619 is_primary: bool,
620 start: Point,
621 severity: DiagnosticSeverity,
622}
623
624pub enum MenuInlineCompletionsPolicy {
625 Never,
626 ByProvider,
627}
628
629pub enum EditPredictionPreview {
630 /// Modifier is not pressed
631 Inactive { released_too_fast: bool },
632 /// Modifier pressed
633 Active {
634 since: Instant,
635 previous_scroll_position: Option<ScrollAnchor>,
636 },
637}
638
639impl EditPredictionPreview {
640 pub fn released_too_fast(&self) -> bool {
641 match self {
642 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
643 EditPredictionPreview::Active { .. } => false,
644 }
645 }
646
647 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
648 if let EditPredictionPreview::Active {
649 previous_scroll_position,
650 ..
651 } = self
652 {
653 *previous_scroll_position = scroll_position;
654 }
655 }
656}
657
658pub struct ContextMenuOptions {
659 pub min_entries_visible: usize,
660 pub max_entries_visible: usize,
661 pub placement: Option<ContextMenuPlacement>,
662}
663
664#[derive(Debug, Clone, PartialEq, Eq)]
665pub enum ContextMenuPlacement {
666 Above,
667 Below,
668}
669
670#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
671struct EditorActionId(usize);
672
673impl EditorActionId {
674 pub fn post_inc(&mut self) -> Self {
675 let answer = self.0;
676
677 *self = Self(answer + 1);
678
679 Self(answer)
680 }
681}
682
683// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
684// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
685
686type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
687type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
688
689#[derive(Default)]
690struct ScrollbarMarkerState {
691 scrollbar_size: Size<Pixels>,
692 dirty: bool,
693 markers: Arc<[PaintQuad]>,
694 pending_refresh: Option<Task<Result<()>>>,
695}
696
697impl ScrollbarMarkerState {
698 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
699 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
700 }
701}
702
703#[derive(Clone, Debug)]
704struct RunnableTasks {
705 templates: Vec<(TaskSourceKind, TaskTemplate)>,
706 offset: multi_buffer::Anchor,
707 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
708 column: u32,
709 // Values of all named captures, including those starting with '_'
710 extra_variables: HashMap<String, String>,
711 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
712 context_range: Range<BufferOffset>,
713}
714
715impl RunnableTasks {
716 fn resolve<'a>(
717 &'a self,
718 cx: &'a task::TaskContext,
719 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
720 self.templates.iter().filter_map(|(kind, template)| {
721 template
722 .resolve_task(&kind.to_id_base(), cx)
723 .map(|task| (kind.clone(), task))
724 })
725 }
726}
727
728#[derive(Clone)]
729struct ResolvedTasks {
730 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
731 position: Anchor,
732}
733
734#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
735struct BufferOffset(usize);
736
737// Addons allow storing per-editor state in other crates (e.g. Vim)
738pub trait Addon: 'static {
739 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
740
741 fn render_buffer_header_controls(
742 &self,
743 _: &ExcerptInfo,
744 _: &Window,
745 _: &App,
746 ) -> Option<AnyElement> {
747 None
748 }
749
750 fn to_any(&self) -> &dyn std::any::Any;
751
752 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
753 None
754 }
755}
756
757/// A set of caret positions, registered when the editor was edited.
758pub struct ChangeList {
759 changes: Vec<Vec<Anchor>>,
760 /// Currently "selected" change.
761 position: Option<usize>,
762}
763
764impl ChangeList {
765 pub fn new() -> Self {
766 Self {
767 changes: Vec::new(),
768 position: None,
769 }
770 }
771
772 /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
773 /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
774 pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
775 if self.changes.is_empty() {
776 return None;
777 }
778
779 let prev = self.position.unwrap_or(self.changes.len());
780 let next = if direction == Direction::Prev {
781 prev.saturating_sub(count)
782 } else {
783 (prev + count).min(self.changes.len() - 1)
784 };
785 self.position = Some(next);
786 self.changes.get(next).map(|anchors| anchors.as_slice())
787 }
788
789 /// Adds a new change to the list, resetting the change list position.
790 pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
791 self.position.take();
792 if pop_state {
793 self.changes.pop();
794 }
795 self.changes.push(new_positions.clone());
796 }
797
798 pub fn last(&self) -> Option<&[Anchor]> {
799 self.changes.last().map(|anchors| anchors.as_slice())
800 }
801}
802
803#[derive(Clone)]
804struct InlineBlamePopoverState {
805 scroll_handle: ScrollHandle,
806 commit_message: Option<ParsedCommitMessage>,
807 markdown: Entity<Markdown>,
808}
809
810struct InlineBlamePopover {
811 position: gpui::Point<Pixels>,
812 show_task: Option<Task<()>>,
813 hide_task: Option<Task<()>>,
814 popover_bounds: Option<Bounds<Pixels>>,
815 popover_state: InlineBlamePopoverState,
816}
817
818/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
819///
820/// See the [module level documentation](self) for more information.
821pub struct Editor {
822 focus_handle: FocusHandle,
823 last_focused_descendant: Option<WeakFocusHandle>,
824 /// The text buffer being edited
825 buffer: Entity<MultiBuffer>,
826 /// Map of how text in the buffer should be displayed.
827 /// Handles soft wraps, folds, fake inlay text insertions, etc.
828 pub display_map: Entity<DisplayMap>,
829 pub selections: SelectionsCollection,
830 pub scroll_manager: ScrollManager,
831 /// When inline assist editors are linked, they all render cursors because
832 /// typing enters text into each of them, even the ones that aren't focused.
833 pub(crate) show_cursor_when_unfocused: bool,
834 columnar_selection_tail: Option<Anchor>,
835 add_selections_state: Option<AddSelectionsState>,
836 select_next_state: Option<SelectNextState>,
837 select_prev_state: Option<SelectNextState>,
838 selection_history: SelectionHistory,
839 autoclose_regions: Vec<AutocloseRegion>,
840 snippet_stack: InvalidationStack<SnippetState>,
841 select_syntax_node_history: SelectSyntaxNodeHistory,
842 ime_transaction: Option<TransactionId>,
843 active_diagnostics: ActiveDiagnostic,
844 show_inline_diagnostics: bool,
845 inline_diagnostics_update: Task<()>,
846 inline_diagnostics_enabled: bool,
847 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
848 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
849 hard_wrap: Option<usize>,
850
851 // TODO: make this a access method
852 pub project: Option<Entity<Project>>,
853 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
854 completion_provider: Option<Box<dyn CompletionProvider>>,
855 collaboration_hub: Option<Box<dyn CollaborationHub>>,
856 blink_manager: Entity<BlinkManager>,
857 show_cursor_names: bool,
858 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
859 pub show_local_selections: bool,
860 mode: EditorMode,
861 show_breadcrumbs: bool,
862 show_gutter: bool,
863 show_scrollbars: bool,
864 disable_scrolling: bool,
865 disable_expand_excerpt_buttons: bool,
866 show_line_numbers: Option<bool>,
867 use_relative_line_numbers: Option<bool>,
868 show_git_diff_gutter: Option<bool>,
869 show_code_actions: Option<bool>,
870 show_runnables: Option<bool>,
871 show_breakpoints: Option<bool>,
872 show_wrap_guides: Option<bool>,
873 show_indent_guides: Option<bool>,
874 placeholder_text: Option<Arc<str>>,
875 highlight_order: usize,
876 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
877 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
878 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
879 scrollbar_marker_state: ScrollbarMarkerState,
880 active_indent_guides_state: ActiveIndentGuidesState,
881 nav_history: Option<ItemNavHistory>,
882 context_menu: RefCell<Option<CodeContextMenu>>,
883 context_menu_options: Option<ContextMenuOptions>,
884 mouse_context_menu: Option<MouseContextMenu>,
885 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
886 inline_blame_popover: Option<InlineBlamePopover>,
887 signature_help_state: SignatureHelpState,
888 auto_signature_help: Option<bool>,
889 find_all_references_task_sources: Vec<Anchor>,
890 next_completion_id: CompletionId,
891 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
892 code_actions_task: Option<Task<Result<()>>>,
893 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
894 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
895 document_highlights_task: Option<Task<()>>,
896 linked_editing_range_task: Option<Task<Option<()>>>,
897 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
898 pending_rename: Option<RenameState>,
899 searchable: bool,
900 cursor_shape: CursorShape,
901 current_line_highlight: Option<CurrentLineHighlight>,
902 collapse_matches: bool,
903 autoindent_mode: Option<AutoindentMode>,
904 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
905 input_enabled: bool,
906 use_modal_editing: bool,
907 read_only: bool,
908 leader_peer_id: Option<PeerId>,
909 remote_id: Option<ViewId>,
910 pub hover_state: HoverState,
911 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
912 gutter_hovered: bool,
913 hovered_link_state: Option<HoveredLinkState>,
914 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
915 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
916 active_inline_completion: Option<InlineCompletionState>,
917 /// Used to prevent flickering as the user types while the menu is open
918 stale_inline_completion_in_menu: Option<InlineCompletionState>,
919 edit_prediction_settings: EditPredictionSettings,
920 inline_completions_hidden_for_vim_mode: bool,
921 show_inline_completions_override: Option<bool>,
922 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
923 edit_prediction_preview: EditPredictionPreview,
924 edit_prediction_indent_conflict: bool,
925 edit_prediction_requires_modifier_in_indent_conflict: bool,
926 inlay_hint_cache: InlayHintCache,
927 next_inlay_id: usize,
928 _subscriptions: Vec<Subscription>,
929 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
930 gutter_dimensions: GutterDimensions,
931 style: Option<EditorStyle>,
932 text_style_refinement: Option<TextStyleRefinement>,
933 next_editor_action_id: EditorActionId,
934 editor_actions:
935 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
936 use_autoclose: bool,
937 use_auto_surround: bool,
938 auto_replace_emoji_shortcode: bool,
939 jsx_tag_auto_close_enabled_in_any_buffer: bool,
940 show_git_blame_gutter: bool,
941 show_git_blame_inline: bool,
942 show_git_blame_inline_delay_task: Option<Task<()>>,
943 git_blame_inline_enabled: bool,
944 render_diff_hunk_controls: RenderDiffHunkControlsFn,
945 serialize_dirty_buffers: bool,
946 show_selection_menu: Option<bool>,
947 blame: Option<Entity<GitBlame>>,
948 blame_subscription: Option<Subscription>,
949 custom_context_menu: Option<
950 Box<
951 dyn 'static
952 + Fn(
953 &mut Self,
954 DisplayPoint,
955 &mut Window,
956 &mut Context<Self>,
957 ) -> Option<Entity<ui::ContextMenu>>,
958 >,
959 >,
960 last_bounds: Option<Bounds<Pixels>>,
961 last_position_map: Option<Rc<PositionMap>>,
962 expect_bounds_change: Option<Bounds<Pixels>>,
963 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
964 tasks_update_task: Option<Task<()>>,
965 breakpoint_store: Option<Entity<BreakpointStore>>,
966 /// Allow's a user to create a breakpoint by selecting this indicator
967 /// It should be None while a user is not hovering over the gutter
968 /// Otherwise it represents the point that the breakpoint will be shown
969 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
970 in_project_search: bool,
971 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
972 breadcrumb_header: Option<String>,
973 focused_block: Option<FocusedBlock>,
974 next_scroll_position: NextScrollCursorCenterTopBottom,
975 addons: HashMap<TypeId, Box<dyn Addon>>,
976 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
977 load_diff_task: Option<Shared<Task<()>>>,
978 selection_mark_mode: bool,
979 toggle_fold_multiple_buffers: Task<()>,
980 _scroll_cursor_center_top_bottom_task: Task<()>,
981 serialize_selections: Task<()>,
982 serialize_folds: Task<()>,
983 mouse_cursor_hidden: bool,
984 hide_mouse_mode: HideMouseMode,
985 pub change_list: ChangeList,
986 inline_value_cache: InlineValueCache,
987}
988
989#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
990enum NextScrollCursorCenterTopBottom {
991 #[default]
992 Center,
993 Top,
994 Bottom,
995}
996
997impl NextScrollCursorCenterTopBottom {
998 fn next(&self) -> Self {
999 match self {
1000 Self::Center => Self::Top,
1001 Self::Top => Self::Bottom,
1002 Self::Bottom => Self::Center,
1003 }
1004 }
1005}
1006
1007#[derive(Clone)]
1008pub struct EditorSnapshot {
1009 pub mode: EditorMode,
1010 show_gutter: bool,
1011 show_line_numbers: Option<bool>,
1012 show_git_diff_gutter: Option<bool>,
1013 show_code_actions: Option<bool>,
1014 show_runnables: Option<bool>,
1015 show_breakpoints: Option<bool>,
1016 git_blame_gutter_max_author_length: Option<usize>,
1017 pub display_snapshot: DisplaySnapshot,
1018 pub placeholder_text: Option<Arc<str>>,
1019 is_focused: bool,
1020 scroll_anchor: ScrollAnchor,
1021 ongoing_scroll: OngoingScroll,
1022 current_line_highlight: CurrentLineHighlight,
1023 gutter_hovered: bool,
1024}
1025
1026#[derive(Default, Debug, Clone, Copy)]
1027pub struct GutterDimensions {
1028 pub left_padding: Pixels,
1029 pub right_padding: Pixels,
1030 pub width: Pixels,
1031 pub margin: Pixels,
1032 pub git_blame_entries_width: Option<Pixels>,
1033}
1034
1035impl GutterDimensions {
1036 /// The full width of the space taken up by the gutter.
1037 pub fn full_width(&self) -> Pixels {
1038 self.margin + self.width
1039 }
1040
1041 /// The width of the space reserved for the fold indicators,
1042 /// use alongside 'justify_end' and `gutter_width` to
1043 /// right align content with the line numbers
1044 pub fn fold_area_width(&self) -> Pixels {
1045 self.margin + self.right_padding
1046 }
1047}
1048
1049#[derive(Debug)]
1050pub struct RemoteSelection {
1051 pub replica_id: ReplicaId,
1052 pub selection: Selection<Anchor>,
1053 pub cursor_shape: CursorShape,
1054 pub peer_id: PeerId,
1055 pub line_mode: bool,
1056 pub participant_index: Option<ParticipantIndex>,
1057 pub user_name: Option<SharedString>,
1058}
1059
1060#[derive(Clone, Debug)]
1061struct SelectionHistoryEntry {
1062 selections: Arc<[Selection<Anchor>]>,
1063 select_next_state: Option<SelectNextState>,
1064 select_prev_state: Option<SelectNextState>,
1065 add_selections_state: Option<AddSelectionsState>,
1066}
1067
1068enum SelectionHistoryMode {
1069 Normal,
1070 Undoing,
1071 Redoing,
1072}
1073
1074#[derive(Clone, PartialEq, Eq, Hash)]
1075struct HoveredCursor {
1076 replica_id: u16,
1077 selection_id: usize,
1078}
1079
1080impl Default for SelectionHistoryMode {
1081 fn default() -> Self {
1082 Self::Normal
1083 }
1084}
1085
1086#[derive(Default)]
1087struct SelectionHistory {
1088 #[allow(clippy::type_complexity)]
1089 selections_by_transaction:
1090 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1091 mode: SelectionHistoryMode,
1092 undo_stack: VecDeque<SelectionHistoryEntry>,
1093 redo_stack: VecDeque<SelectionHistoryEntry>,
1094}
1095
1096impl SelectionHistory {
1097 fn insert_transaction(
1098 &mut self,
1099 transaction_id: TransactionId,
1100 selections: Arc<[Selection<Anchor>]>,
1101 ) {
1102 self.selections_by_transaction
1103 .insert(transaction_id, (selections, None));
1104 }
1105
1106 #[allow(clippy::type_complexity)]
1107 fn transaction(
1108 &self,
1109 transaction_id: TransactionId,
1110 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1111 self.selections_by_transaction.get(&transaction_id)
1112 }
1113
1114 #[allow(clippy::type_complexity)]
1115 fn transaction_mut(
1116 &mut self,
1117 transaction_id: TransactionId,
1118 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1119 self.selections_by_transaction.get_mut(&transaction_id)
1120 }
1121
1122 fn push(&mut self, entry: SelectionHistoryEntry) {
1123 if !entry.selections.is_empty() {
1124 match self.mode {
1125 SelectionHistoryMode::Normal => {
1126 self.push_undo(entry);
1127 self.redo_stack.clear();
1128 }
1129 SelectionHistoryMode::Undoing => self.push_redo(entry),
1130 SelectionHistoryMode::Redoing => self.push_undo(entry),
1131 }
1132 }
1133 }
1134
1135 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1136 if self
1137 .undo_stack
1138 .back()
1139 .map_or(true, |e| e.selections != entry.selections)
1140 {
1141 self.undo_stack.push_back(entry);
1142 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1143 self.undo_stack.pop_front();
1144 }
1145 }
1146 }
1147
1148 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1149 if self
1150 .redo_stack
1151 .back()
1152 .map_or(true, |e| e.selections != entry.selections)
1153 {
1154 self.redo_stack.push_back(entry);
1155 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1156 self.redo_stack.pop_front();
1157 }
1158 }
1159 }
1160}
1161
1162#[derive(Clone, Copy)]
1163pub struct RowHighlightOptions {
1164 pub autoscroll: bool,
1165 pub include_gutter: bool,
1166}
1167
1168impl Default for RowHighlightOptions {
1169 fn default() -> Self {
1170 Self {
1171 autoscroll: Default::default(),
1172 include_gutter: true,
1173 }
1174 }
1175}
1176
1177struct RowHighlight {
1178 index: usize,
1179 range: Range<Anchor>,
1180 color: Hsla,
1181 options: RowHighlightOptions,
1182 type_id: TypeId,
1183}
1184
1185#[derive(Clone, Debug)]
1186struct AddSelectionsState {
1187 above: bool,
1188 stack: Vec<usize>,
1189}
1190
1191#[derive(Clone)]
1192struct SelectNextState {
1193 query: AhoCorasick,
1194 wordwise: bool,
1195 done: bool,
1196}
1197
1198impl std::fmt::Debug for SelectNextState {
1199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1200 f.debug_struct(std::any::type_name::<Self>())
1201 .field("wordwise", &self.wordwise)
1202 .field("done", &self.done)
1203 .finish()
1204 }
1205}
1206
1207#[derive(Debug)]
1208struct AutocloseRegion {
1209 selection_id: usize,
1210 range: Range<Anchor>,
1211 pair: BracketPair,
1212}
1213
1214#[derive(Debug)]
1215struct SnippetState {
1216 ranges: Vec<Vec<Range<Anchor>>>,
1217 active_index: usize,
1218 choices: Vec<Option<Vec<String>>>,
1219}
1220
1221#[doc(hidden)]
1222pub struct RenameState {
1223 pub range: Range<Anchor>,
1224 pub old_name: Arc<str>,
1225 pub editor: Entity<Editor>,
1226 block_id: CustomBlockId,
1227}
1228
1229struct InvalidationStack<T>(Vec<T>);
1230
1231struct RegisteredInlineCompletionProvider {
1232 provider: Arc<dyn InlineCompletionProviderHandle>,
1233 _subscription: Subscription,
1234}
1235
1236#[derive(Debug, PartialEq, Eq)]
1237pub struct ActiveDiagnosticGroup {
1238 pub active_range: Range<Anchor>,
1239 pub active_message: String,
1240 pub group_id: usize,
1241 pub blocks: HashSet<CustomBlockId>,
1242}
1243
1244#[derive(Debug, PartialEq, Eq)]
1245#[allow(clippy::large_enum_variant)]
1246pub(crate) enum ActiveDiagnostic {
1247 None,
1248 All,
1249 Group(ActiveDiagnosticGroup),
1250}
1251
1252#[derive(Serialize, Deserialize, Clone, Debug)]
1253pub struct ClipboardSelection {
1254 /// The number of bytes in this selection.
1255 pub len: usize,
1256 /// Whether this was a full-line selection.
1257 pub is_entire_line: bool,
1258 /// The indentation of the first line when this content was originally copied.
1259 pub first_line_indent: u32,
1260}
1261
1262// selections, scroll behavior, was newest selection reversed
1263type SelectSyntaxNodeHistoryState = (
1264 Box<[Selection<usize>]>,
1265 SelectSyntaxNodeScrollBehavior,
1266 bool,
1267);
1268
1269#[derive(Default)]
1270struct SelectSyntaxNodeHistory {
1271 stack: Vec<SelectSyntaxNodeHistoryState>,
1272 // disable temporarily to allow changing selections without losing the stack
1273 pub disable_clearing: bool,
1274}
1275
1276impl SelectSyntaxNodeHistory {
1277 pub fn try_clear(&mut self) {
1278 if !self.disable_clearing {
1279 self.stack.clear();
1280 }
1281 }
1282
1283 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1284 self.stack.push(selection);
1285 }
1286
1287 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1288 self.stack.pop()
1289 }
1290}
1291
1292enum SelectSyntaxNodeScrollBehavior {
1293 CursorTop,
1294 FitSelection,
1295 CursorBottom,
1296}
1297
1298#[derive(Debug)]
1299pub(crate) struct NavigationData {
1300 cursor_anchor: Anchor,
1301 cursor_position: Point,
1302 scroll_anchor: ScrollAnchor,
1303 scroll_top_row: u32,
1304}
1305
1306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1307pub enum GotoDefinitionKind {
1308 Symbol,
1309 Declaration,
1310 Type,
1311 Implementation,
1312}
1313
1314#[derive(Debug, Clone)]
1315enum InlayHintRefreshReason {
1316 ModifiersChanged(bool),
1317 Toggle(bool),
1318 SettingsChange(InlayHintSettings),
1319 NewLinesShown,
1320 BufferEdited(HashSet<Arc<Language>>),
1321 RefreshRequested,
1322 ExcerptsRemoved(Vec<ExcerptId>),
1323}
1324
1325impl InlayHintRefreshReason {
1326 fn description(&self) -> &'static str {
1327 match self {
1328 Self::ModifiersChanged(_) => "modifiers changed",
1329 Self::Toggle(_) => "toggle",
1330 Self::SettingsChange(_) => "settings change",
1331 Self::NewLinesShown => "new lines shown",
1332 Self::BufferEdited(_) => "buffer edited",
1333 Self::RefreshRequested => "refresh requested",
1334 Self::ExcerptsRemoved(_) => "excerpts removed",
1335 }
1336 }
1337}
1338
1339pub enum FormatTarget {
1340 Buffers,
1341 Ranges(Vec<Range<MultiBufferPoint>>),
1342}
1343
1344pub(crate) struct FocusedBlock {
1345 id: BlockId,
1346 focus_handle: WeakFocusHandle,
1347}
1348
1349#[derive(Clone)]
1350enum JumpData {
1351 MultiBufferRow {
1352 row: MultiBufferRow,
1353 line_offset_from_top: u32,
1354 },
1355 MultiBufferPoint {
1356 excerpt_id: ExcerptId,
1357 position: Point,
1358 anchor: text::Anchor,
1359 line_offset_from_top: u32,
1360 },
1361}
1362
1363pub enum MultibufferSelectionMode {
1364 First,
1365 All,
1366}
1367
1368#[derive(Clone, Copy, Debug, Default)]
1369pub struct RewrapOptions {
1370 pub override_language_settings: bool,
1371 pub preserve_existing_whitespace: bool,
1372}
1373
1374impl Editor {
1375 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1376 let buffer = cx.new(|cx| Buffer::local("", cx));
1377 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1378 Self::new(
1379 EditorMode::SingleLine { auto_width: false },
1380 buffer,
1381 None,
1382 window,
1383 cx,
1384 )
1385 }
1386
1387 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1388 let buffer = cx.new(|cx| Buffer::local("", cx));
1389 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1390 Self::new(EditorMode::full(), buffer, None, window, cx)
1391 }
1392
1393 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1394 let buffer = cx.new(|cx| Buffer::local("", cx));
1395 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1396 Self::new(
1397 EditorMode::SingleLine { auto_width: true },
1398 buffer,
1399 None,
1400 window,
1401 cx,
1402 )
1403 }
1404
1405 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1406 let buffer = cx.new(|cx| Buffer::local("", cx));
1407 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1408 Self::new(
1409 EditorMode::AutoHeight { max_lines },
1410 buffer,
1411 None,
1412 window,
1413 cx,
1414 )
1415 }
1416
1417 pub fn for_buffer(
1418 buffer: Entity<Buffer>,
1419 project: Option<Entity<Project>>,
1420 window: &mut Window,
1421 cx: &mut Context<Self>,
1422 ) -> Self {
1423 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1424 Self::new(EditorMode::full(), buffer, project, window, cx)
1425 }
1426
1427 pub fn for_multibuffer(
1428 buffer: Entity<MultiBuffer>,
1429 project: Option<Entity<Project>>,
1430 window: &mut Window,
1431 cx: &mut Context<Self>,
1432 ) -> Self {
1433 Self::new(EditorMode::full(), buffer, project, window, cx)
1434 }
1435
1436 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1437 let mut clone = Self::new(
1438 self.mode,
1439 self.buffer.clone(),
1440 self.project.clone(),
1441 window,
1442 cx,
1443 );
1444 self.display_map.update(cx, |display_map, cx| {
1445 let snapshot = display_map.snapshot(cx);
1446 clone.display_map.update(cx, |display_map, cx| {
1447 display_map.set_state(&snapshot, cx);
1448 });
1449 });
1450 clone.folds_did_change(cx);
1451 clone.selections.clone_state(&self.selections);
1452 clone.scroll_manager.clone_state(&self.scroll_manager);
1453 clone.searchable = self.searchable;
1454 clone.read_only = self.read_only;
1455 clone
1456 }
1457
1458 pub fn new(
1459 mode: EditorMode,
1460 buffer: Entity<MultiBuffer>,
1461 project: Option<Entity<Project>>,
1462 window: &mut Window,
1463 cx: &mut Context<Self>,
1464 ) -> Self {
1465 let style = window.text_style();
1466 let font_size = style.font_size.to_pixels(window.rem_size());
1467 let editor = cx.entity().downgrade();
1468 let fold_placeholder = FoldPlaceholder {
1469 constrain_width: true,
1470 render: Arc::new(move |fold_id, fold_range, cx| {
1471 let editor = editor.clone();
1472 div()
1473 .id(fold_id)
1474 .bg(cx.theme().colors().ghost_element_background)
1475 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1476 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1477 .rounded_xs()
1478 .size_full()
1479 .cursor_pointer()
1480 .child("⋯")
1481 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1482 .on_click(move |_, _window, cx| {
1483 editor
1484 .update(cx, |editor, cx| {
1485 editor.unfold_ranges(
1486 &[fold_range.start..fold_range.end],
1487 true,
1488 false,
1489 cx,
1490 );
1491 cx.stop_propagation();
1492 })
1493 .ok();
1494 })
1495 .into_any()
1496 }),
1497 merge_adjacent: true,
1498 ..Default::default()
1499 };
1500 let display_map = cx.new(|cx| {
1501 DisplayMap::new(
1502 buffer.clone(),
1503 style.font(),
1504 font_size,
1505 None,
1506 FILE_HEADER_HEIGHT,
1507 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1508 fold_placeholder,
1509 cx,
1510 )
1511 });
1512
1513 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1514
1515 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1516
1517 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1518 .then(|| language_settings::SoftWrap::None);
1519
1520 let mut project_subscriptions = Vec::new();
1521 if mode.is_full() {
1522 if let Some(project) = project.as_ref() {
1523 project_subscriptions.push(cx.subscribe_in(
1524 project,
1525 window,
1526 |editor, _, event, window, cx| match event {
1527 project::Event::RefreshCodeLens => {
1528 // we always query lens with actions, without storing them, always refreshing them
1529 }
1530 project::Event::RefreshInlayHints => {
1531 editor
1532 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1533 }
1534 project::Event::SnippetEdit(id, snippet_edits) => {
1535 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1536 let focus_handle = editor.focus_handle(cx);
1537 if focus_handle.is_focused(window) {
1538 let snapshot = buffer.read(cx).snapshot();
1539 for (range, snippet) in snippet_edits {
1540 let editor_range =
1541 language::range_from_lsp(*range).to_offset(&snapshot);
1542 editor
1543 .insert_snippet(
1544 &[editor_range],
1545 snippet.clone(),
1546 window,
1547 cx,
1548 )
1549 .ok();
1550 }
1551 }
1552 }
1553 }
1554 _ => {}
1555 },
1556 ));
1557 if let Some(task_inventory) = project
1558 .read(cx)
1559 .task_store()
1560 .read(cx)
1561 .task_inventory()
1562 .cloned()
1563 {
1564 project_subscriptions.push(cx.observe_in(
1565 &task_inventory,
1566 window,
1567 |editor, _, window, cx| {
1568 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1569 },
1570 ));
1571 };
1572
1573 project_subscriptions.push(cx.subscribe_in(
1574 &project.read(cx).breakpoint_store(),
1575 window,
1576 |editor, _, event, window, cx| match event {
1577 BreakpointStoreEvent::ActiveDebugLineChanged => {
1578 if editor.go_to_active_debug_line(window, cx) {
1579 cx.stop_propagation();
1580 }
1581
1582 editor.refresh_inline_values(cx);
1583 }
1584 _ => {}
1585 },
1586 ));
1587 }
1588 }
1589
1590 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1591
1592 let inlay_hint_settings =
1593 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1594 let focus_handle = cx.focus_handle();
1595 cx.on_focus(&focus_handle, window, Self::handle_focus)
1596 .detach();
1597 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1598 .detach();
1599 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1600 .detach();
1601 cx.on_blur(&focus_handle, window, Self::handle_blur)
1602 .detach();
1603
1604 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1605 Some(false)
1606 } else {
1607 None
1608 };
1609
1610 let breakpoint_store = match (mode, project.as_ref()) {
1611 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1612 _ => None,
1613 };
1614
1615 let mut code_action_providers = Vec::new();
1616 let mut load_uncommitted_diff = None;
1617 if let Some(project) = project.clone() {
1618 load_uncommitted_diff = Some(
1619 get_uncommitted_diff_for_buffer(
1620 &project,
1621 buffer.read(cx).all_buffers(),
1622 buffer.clone(),
1623 cx,
1624 )
1625 .shared(),
1626 );
1627 code_action_providers.push(Rc::new(project) as Rc<_>);
1628 }
1629
1630 let mut this = Self {
1631 focus_handle,
1632 show_cursor_when_unfocused: false,
1633 last_focused_descendant: None,
1634 buffer: buffer.clone(),
1635 display_map: display_map.clone(),
1636 selections,
1637 scroll_manager: ScrollManager::new(cx),
1638 columnar_selection_tail: None,
1639 add_selections_state: None,
1640 select_next_state: None,
1641 select_prev_state: None,
1642 selection_history: Default::default(),
1643 autoclose_regions: Default::default(),
1644 snippet_stack: Default::default(),
1645 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1646 ime_transaction: Default::default(),
1647 active_diagnostics: ActiveDiagnostic::None,
1648 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1649 inline_diagnostics_update: Task::ready(()),
1650 inline_diagnostics: Vec::new(),
1651 soft_wrap_mode_override,
1652 hard_wrap: None,
1653 completion_provider: project.clone().map(|project| Box::new(project) as _),
1654 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1655 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1656 project,
1657 blink_manager: blink_manager.clone(),
1658 show_local_selections: true,
1659 show_scrollbars: true,
1660 disable_scrolling: false,
1661 mode,
1662 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1663 show_gutter: mode.is_full(),
1664 show_line_numbers: None,
1665 use_relative_line_numbers: None,
1666 disable_expand_excerpt_buttons: false,
1667 show_git_diff_gutter: None,
1668 show_code_actions: None,
1669 show_runnables: None,
1670 show_breakpoints: None,
1671 show_wrap_guides: None,
1672 show_indent_guides,
1673 placeholder_text: None,
1674 highlight_order: 0,
1675 highlighted_rows: HashMap::default(),
1676 background_highlights: Default::default(),
1677 gutter_highlights: TreeMap::default(),
1678 scrollbar_marker_state: ScrollbarMarkerState::default(),
1679 active_indent_guides_state: ActiveIndentGuidesState::default(),
1680 nav_history: None,
1681 context_menu: RefCell::new(None),
1682 context_menu_options: None,
1683 mouse_context_menu: None,
1684 completion_tasks: Default::default(),
1685 inline_blame_popover: Default::default(),
1686 signature_help_state: SignatureHelpState::default(),
1687 auto_signature_help: None,
1688 find_all_references_task_sources: Vec::new(),
1689 next_completion_id: 0,
1690 next_inlay_id: 0,
1691 code_action_providers,
1692 available_code_actions: Default::default(),
1693 code_actions_task: Default::default(),
1694 quick_selection_highlight_task: Default::default(),
1695 debounced_selection_highlight_task: Default::default(),
1696 document_highlights_task: Default::default(),
1697 linked_editing_range_task: Default::default(),
1698 pending_rename: Default::default(),
1699 searchable: true,
1700 cursor_shape: EditorSettings::get_global(cx)
1701 .cursor_shape
1702 .unwrap_or_default(),
1703 current_line_highlight: None,
1704 autoindent_mode: Some(AutoindentMode::EachLine),
1705 collapse_matches: false,
1706 workspace: None,
1707 input_enabled: true,
1708 use_modal_editing: mode.is_full(),
1709 read_only: false,
1710 use_autoclose: true,
1711 use_auto_surround: true,
1712 auto_replace_emoji_shortcode: false,
1713 jsx_tag_auto_close_enabled_in_any_buffer: false,
1714 leader_peer_id: None,
1715 remote_id: None,
1716 hover_state: Default::default(),
1717 pending_mouse_down: None,
1718 hovered_link_state: Default::default(),
1719 edit_prediction_provider: None,
1720 active_inline_completion: None,
1721 stale_inline_completion_in_menu: None,
1722 edit_prediction_preview: EditPredictionPreview::Inactive {
1723 released_too_fast: false,
1724 },
1725 inline_diagnostics_enabled: mode.is_full(),
1726 inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
1727 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1728
1729 gutter_hovered: false,
1730 pixel_position_of_newest_cursor: None,
1731 last_bounds: None,
1732 last_position_map: None,
1733 expect_bounds_change: None,
1734 gutter_dimensions: GutterDimensions::default(),
1735 style: None,
1736 show_cursor_names: false,
1737 hovered_cursors: Default::default(),
1738 next_editor_action_id: EditorActionId::default(),
1739 editor_actions: Rc::default(),
1740 inline_completions_hidden_for_vim_mode: false,
1741 show_inline_completions_override: None,
1742 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1743 edit_prediction_settings: EditPredictionSettings::Disabled,
1744 edit_prediction_indent_conflict: false,
1745 edit_prediction_requires_modifier_in_indent_conflict: true,
1746 custom_context_menu: None,
1747 show_git_blame_gutter: false,
1748 show_git_blame_inline: false,
1749 show_selection_menu: None,
1750 show_git_blame_inline_delay_task: None,
1751 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1752 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1753 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1754 .session
1755 .restore_unsaved_buffers,
1756 blame: None,
1757 blame_subscription: None,
1758 tasks: Default::default(),
1759
1760 breakpoint_store,
1761 gutter_breakpoint_indicator: (None, None),
1762 _subscriptions: vec![
1763 cx.observe(&buffer, Self::on_buffer_changed),
1764 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1765 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1766 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1767 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1768 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1769 cx.observe_window_activation(window, |editor, window, cx| {
1770 let active = window.is_window_active();
1771 editor.blink_manager.update(cx, |blink_manager, cx| {
1772 if active {
1773 blink_manager.enable(cx);
1774 } else {
1775 blink_manager.disable(cx);
1776 }
1777 });
1778 }),
1779 ],
1780 tasks_update_task: None,
1781 linked_edit_ranges: Default::default(),
1782 in_project_search: false,
1783 previous_search_ranges: None,
1784 breadcrumb_header: None,
1785 focused_block: None,
1786 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1787 addons: HashMap::default(),
1788 registered_buffers: HashMap::default(),
1789 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1790 selection_mark_mode: false,
1791 toggle_fold_multiple_buffers: Task::ready(()),
1792 serialize_selections: Task::ready(()),
1793 serialize_folds: Task::ready(()),
1794 text_style_refinement: None,
1795 load_diff_task: load_uncommitted_diff,
1796 mouse_cursor_hidden: false,
1797 hide_mouse_mode: EditorSettings::get_global(cx)
1798 .hide_mouse
1799 .unwrap_or_default(),
1800 change_list: ChangeList::new(),
1801 };
1802 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1803 this._subscriptions
1804 .push(cx.observe(breakpoints, |_, _, cx| {
1805 cx.notify();
1806 }));
1807 }
1808 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1809 this._subscriptions.extend(project_subscriptions);
1810
1811 this._subscriptions.push(cx.subscribe_in(
1812 &cx.entity(),
1813 window,
1814 |editor, _, e: &EditorEvent, window, cx| match e {
1815 EditorEvent::ScrollPositionChanged { local, .. } => {
1816 if *local {
1817 let new_anchor = editor.scroll_manager.anchor();
1818 let snapshot = editor.snapshot(window, cx);
1819 editor.update_restoration_data(cx, move |data| {
1820 data.scroll_position = (
1821 new_anchor.top_row(&snapshot.buffer_snapshot),
1822 new_anchor.offset,
1823 );
1824 });
1825 editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
1826 editor.inline_blame_popover.take();
1827 }
1828 }
1829 EditorEvent::Edited { .. } => {
1830 if !vim_enabled(cx) {
1831 let (map, selections) = editor.selections.all_adjusted_display(cx);
1832 let pop_state = editor
1833 .change_list
1834 .last()
1835 .map(|previous| {
1836 previous.len() == selections.len()
1837 && previous.iter().enumerate().all(|(ix, p)| {
1838 p.to_display_point(&map).row()
1839 == selections[ix].head().row()
1840 })
1841 })
1842 .unwrap_or(false);
1843 let new_positions = selections
1844 .into_iter()
1845 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1846 .collect();
1847 editor
1848 .change_list
1849 .push_to_change_list(pop_state, new_positions);
1850 }
1851 }
1852 _ => (),
1853 },
1854 ));
1855
1856 if let Some(dap_store) = this
1857 .project
1858 .as_ref()
1859 .map(|project| project.read(cx).dap_store())
1860 {
1861 let weak_editor = cx.weak_entity();
1862
1863 this._subscriptions
1864 .push(
1865 cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
1866 let session_entity = cx.entity();
1867 weak_editor
1868 .update(cx, |editor, cx| {
1869 editor._subscriptions.push(
1870 cx.subscribe(&session_entity, Self::on_debug_session_event),
1871 );
1872 })
1873 .ok();
1874 }),
1875 );
1876
1877 for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
1878 this._subscriptions
1879 .push(cx.subscribe(&session, Self::on_debug_session_event));
1880 }
1881 }
1882
1883 this.end_selection(window, cx);
1884 this.scroll_manager.show_scrollbars(window, cx);
1885 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1886
1887 if mode.is_full() {
1888 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1889 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1890
1891 if this.git_blame_inline_enabled {
1892 this.git_blame_inline_enabled = true;
1893 this.start_git_blame_inline(false, window, cx);
1894 }
1895
1896 this.go_to_active_debug_line(window, cx);
1897
1898 if let Some(buffer) = buffer.read(cx).as_singleton() {
1899 if let Some(project) = this.project.as_ref() {
1900 let handle = project.update(cx, |project, cx| {
1901 project.register_buffer_with_language_servers(&buffer, cx)
1902 });
1903 this.registered_buffers
1904 .insert(buffer.read(cx).remote_id(), handle);
1905 }
1906 }
1907 }
1908
1909 this.report_editor_event("Editor Opened", None, cx);
1910 this
1911 }
1912
1913 pub fn deploy_mouse_context_menu(
1914 &mut self,
1915 position: gpui::Point<Pixels>,
1916 context_menu: Entity<ContextMenu>,
1917 window: &mut Window,
1918 cx: &mut Context<Self>,
1919 ) {
1920 self.mouse_context_menu = Some(MouseContextMenu::new(
1921 self,
1922 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1923 context_menu,
1924 window,
1925 cx,
1926 ));
1927 }
1928
1929 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1930 self.mouse_context_menu
1931 .as_ref()
1932 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1933 }
1934
1935 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1936 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1937 }
1938
1939 fn key_context_internal(
1940 &self,
1941 has_active_edit_prediction: bool,
1942 window: &Window,
1943 cx: &App,
1944 ) -> KeyContext {
1945 let mut key_context = KeyContext::new_with_defaults();
1946 key_context.add("Editor");
1947 let mode = match self.mode {
1948 EditorMode::SingleLine { .. } => "single_line",
1949 EditorMode::AutoHeight { .. } => "auto_height",
1950 EditorMode::Full { .. } => "full",
1951 };
1952
1953 if EditorSettings::jupyter_enabled(cx) {
1954 key_context.add("jupyter");
1955 }
1956
1957 key_context.set("mode", mode);
1958 if self.pending_rename.is_some() {
1959 key_context.add("renaming");
1960 }
1961
1962 match self.context_menu.borrow().as_ref() {
1963 Some(CodeContextMenu::Completions(_)) => {
1964 key_context.add("menu");
1965 key_context.add("showing_completions");
1966 }
1967 Some(CodeContextMenu::CodeActions(_)) => {
1968 key_context.add("menu");
1969 key_context.add("showing_code_actions")
1970 }
1971 None => {}
1972 }
1973
1974 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1975 if !self.focus_handle(cx).contains_focused(window, cx)
1976 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1977 {
1978 for addon in self.addons.values() {
1979 addon.extend_key_context(&mut key_context, cx)
1980 }
1981 }
1982
1983 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1984 if let Some(extension) = singleton_buffer
1985 .read(cx)
1986 .file()
1987 .and_then(|file| file.path().extension()?.to_str())
1988 {
1989 key_context.set("extension", extension.to_string());
1990 }
1991 } else {
1992 key_context.add("multibuffer");
1993 }
1994
1995 if has_active_edit_prediction {
1996 if self.edit_prediction_in_conflict() {
1997 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1998 } else {
1999 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
2000 key_context.add("copilot_suggestion");
2001 }
2002 }
2003
2004 if self.selection_mark_mode {
2005 key_context.add("selection_mode");
2006 }
2007
2008 key_context
2009 }
2010
2011 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
2012 self.mouse_cursor_hidden = match origin {
2013 HideMouseCursorOrigin::TypingAction => {
2014 matches!(
2015 self.hide_mouse_mode,
2016 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
2017 )
2018 }
2019 HideMouseCursorOrigin::MovementAction => {
2020 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
2021 }
2022 };
2023 }
2024
2025 pub fn edit_prediction_in_conflict(&self) -> bool {
2026 if !self.show_edit_predictions_in_menu() {
2027 return false;
2028 }
2029
2030 let showing_completions = self
2031 .context_menu
2032 .borrow()
2033 .as_ref()
2034 .map_or(false, |context| {
2035 matches!(context, CodeContextMenu::Completions(_))
2036 });
2037
2038 showing_completions
2039 || self.edit_prediction_requires_modifier()
2040 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
2041 // bindings to insert tab characters.
2042 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
2043 }
2044
2045 pub fn accept_edit_prediction_keybind(
2046 &self,
2047 window: &Window,
2048 cx: &App,
2049 ) -> AcceptEditPredictionBinding {
2050 let key_context = self.key_context_internal(true, window, cx);
2051 let in_conflict = self.edit_prediction_in_conflict();
2052
2053 AcceptEditPredictionBinding(
2054 window
2055 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
2056 .into_iter()
2057 .filter(|binding| {
2058 !in_conflict
2059 || binding
2060 .keystrokes()
2061 .first()
2062 .map_or(false, |keystroke| keystroke.modifiers.modified())
2063 })
2064 .rev()
2065 .min_by_key(|binding| {
2066 binding
2067 .keystrokes()
2068 .first()
2069 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
2070 }),
2071 )
2072 }
2073
2074 pub fn new_file(
2075 workspace: &mut Workspace,
2076 _: &workspace::NewFile,
2077 window: &mut Window,
2078 cx: &mut Context<Workspace>,
2079 ) {
2080 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
2081 "Failed to create buffer",
2082 window,
2083 cx,
2084 |e, _, _| match e.error_code() {
2085 ErrorCode::RemoteUpgradeRequired => Some(format!(
2086 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2087 e.error_tag("required").unwrap_or("the latest version")
2088 )),
2089 _ => None,
2090 },
2091 );
2092 }
2093
2094 pub fn new_in_workspace(
2095 workspace: &mut Workspace,
2096 window: &mut Window,
2097 cx: &mut Context<Workspace>,
2098 ) -> Task<Result<Entity<Editor>>> {
2099 let project = workspace.project().clone();
2100 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2101
2102 cx.spawn_in(window, async move |workspace, cx| {
2103 let buffer = create.await?;
2104 workspace.update_in(cx, |workspace, window, cx| {
2105 let editor =
2106 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
2107 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2108 editor
2109 })
2110 })
2111 }
2112
2113 fn new_file_vertical(
2114 workspace: &mut Workspace,
2115 _: &workspace::NewFileSplitVertical,
2116 window: &mut Window,
2117 cx: &mut Context<Workspace>,
2118 ) {
2119 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
2120 }
2121
2122 fn new_file_horizontal(
2123 workspace: &mut Workspace,
2124 _: &workspace::NewFileSplitHorizontal,
2125 window: &mut Window,
2126 cx: &mut Context<Workspace>,
2127 ) {
2128 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2129 }
2130
2131 fn new_file_in_direction(
2132 workspace: &mut Workspace,
2133 direction: SplitDirection,
2134 window: &mut Window,
2135 cx: &mut Context<Workspace>,
2136 ) {
2137 let project = workspace.project().clone();
2138 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2139
2140 cx.spawn_in(window, async move |workspace, cx| {
2141 let buffer = create.await?;
2142 workspace.update_in(cx, move |workspace, window, cx| {
2143 workspace.split_item(
2144 direction,
2145 Box::new(
2146 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2147 ),
2148 window,
2149 cx,
2150 )
2151 })?;
2152 anyhow::Ok(())
2153 })
2154 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2155 match e.error_code() {
2156 ErrorCode::RemoteUpgradeRequired => Some(format!(
2157 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2158 e.error_tag("required").unwrap_or("the latest version")
2159 )),
2160 _ => None,
2161 }
2162 });
2163 }
2164
2165 pub fn leader_peer_id(&self) -> Option<PeerId> {
2166 self.leader_peer_id
2167 }
2168
2169 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2170 &self.buffer
2171 }
2172
2173 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2174 self.workspace.as_ref()?.0.upgrade()
2175 }
2176
2177 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2178 self.buffer().read(cx).title(cx)
2179 }
2180
2181 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2182 let git_blame_gutter_max_author_length = self
2183 .render_git_blame_gutter(cx)
2184 .then(|| {
2185 if let Some(blame) = self.blame.as_ref() {
2186 let max_author_length =
2187 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2188 Some(max_author_length)
2189 } else {
2190 None
2191 }
2192 })
2193 .flatten();
2194
2195 EditorSnapshot {
2196 mode: self.mode,
2197 show_gutter: self.show_gutter,
2198 show_line_numbers: self.show_line_numbers,
2199 show_git_diff_gutter: self.show_git_diff_gutter,
2200 show_code_actions: self.show_code_actions,
2201 show_runnables: self.show_runnables,
2202 show_breakpoints: self.show_breakpoints,
2203 git_blame_gutter_max_author_length,
2204 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2205 scroll_anchor: self.scroll_manager.anchor(),
2206 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2207 placeholder_text: self.placeholder_text.clone(),
2208 is_focused: self.focus_handle.is_focused(window),
2209 current_line_highlight: self
2210 .current_line_highlight
2211 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2212 gutter_hovered: self.gutter_hovered,
2213 }
2214 }
2215
2216 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2217 self.buffer.read(cx).language_at(point, cx)
2218 }
2219
2220 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2221 self.buffer.read(cx).read(cx).file_at(point).cloned()
2222 }
2223
2224 pub fn active_excerpt(
2225 &self,
2226 cx: &App,
2227 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2228 self.buffer
2229 .read(cx)
2230 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2231 }
2232
2233 pub fn mode(&self) -> EditorMode {
2234 self.mode
2235 }
2236
2237 pub fn set_mode(&mut self, mode: EditorMode) {
2238 self.mode = mode;
2239 }
2240
2241 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2242 self.collaboration_hub.as_deref()
2243 }
2244
2245 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2246 self.collaboration_hub = Some(hub);
2247 }
2248
2249 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2250 self.in_project_search = in_project_search;
2251 }
2252
2253 pub fn set_custom_context_menu(
2254 &mut self,
2255 f: impl 'static
2256 + Fn(
2257 &mut Self,
2258 DisplayPoint,
2259 &mut Window,
2260 &mut Context<Self>,
2261 ) -> Option<Entity<ui::ContextMenu>>,
2262 ) {
2263 self.custom_context_menu = Some(Box::new(f))
2264 }
2265
2266 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2267 self.completion_provider = provider;
2268 }
2269
2270 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2271 self.semantics_provider.clone()
2272 }
2273
2274 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2275 self.semantics_provider = provider;
2276 }
2277
2278 pub fn set_edit_prediction_provider<T>(
2279 &mut self,
2280 provider: Option<Entity<T>>,
2281 window: &mut Window,
2282 cx: &mut Context<Self>,
2283 ) where
2284 T: EditPredictionProvider,
2285 {
2286 self.edit_prediction_provider =
2287 provider.map(|provider| RegisteredInlineCompletionProvider {
2288 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2289 if this.focus_handle.is_focused(window) {
2290 this.update_visible_inline_completion(window, cx);
2291 }
2292 }),
2293 provider: Arc::new(provider),
2294 });
2295 self.update_edit_prediction_settings(cx);
2296 self.refresh_inline_completion(false, false, window, cx);
2297 }
2298
2299 pub fn placeholder_text(&self) -> Option<&str> {
2300 self.placeholder_text.as_deref()
2301 }
2302
2303 pub fn set_placeholder_text(
2304 &mut self,
2305 placeholder_text: impl Into<Arc<str>>,
2306 cx: &mut Context<Self>,
2307 ) {
2308 let placeholder_text = Some(placeholder_text.into());
2309 if self.placeholder_text != placeholder_text {
2310 self.placeholder_text = placeholder_text;
2311 cx.notify();
2312 }
2313 }
2314
2315 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2316 self.cursor_shape = cursor_shape;
2317
2318 // Disrupt blink for immediate user feedback that the cursor shape has changed
2319 self.blink_manager.update(cx, BlinkManager::show_cursor);
2320
2321 cx.notify();
2322 }
2323
2324 pub fn set_current_line_highlight(
2325 &mut self,
2326 current_line_highlight: Option<CurrentLineHighlight>,
2327 ) {
2328 self.current_line_highlight = current_line_highlight;
2329 }
2330
2331 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2332 self.collapse_matches = collapse_matches;
2333 }
2334
2335 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2336 let buffers = self.buffer.read(cx).all_buffers();
2337 let Some(project) = self.project.as_ref() else {
2338 return;
2339 };
2340 project.update(cx, |project, cx| {
2341 for buffer in buffers {
2342 self.registered_buffers
2343 .entry(buffer.read(cx).remote_id())
2344 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2345 }
2346 })
2347 }
2348
2349 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2350 if self.collapse_matches {
2351 return range.start..range.start;
2352 }
2353 range.clone()
2354 }
2355
2356 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2357 if self.display_map.read(cx).clip_at_line_ends != clip {
2358 self.display_map
2359 .update(cx, |map, _| map.clip_at_line_ends = clip);
2360 }
2361 }
2362
2363 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2364 self.input_enabled = input_enabled;
2365 }
2366
2367 pub fn set_inline_completions_hidden_for_vim_mode(
2368 &mut self,
2369 hidden: bool,
2370 window: &mut Window,
2371 cx: &mut Context<Self>,
2372 ) {
2373 if hidden != self.inline_completions_hidden_for_vim_mode {
2374 self.inline_completions_hidden_for_vim_mode = hidden;
2375 if hidden {
2376 self.update_visible_inline_completion(window, cx);
2377 } else {
2378 self.refresh_inline_completion(true, false, window, cx);
2379 }
2380 }
2381 }
2382
2383 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2384 self.menu_inline_completions_policy = value;
2385 }
2386
2387 pub fn set_autoindent(&mut self, autoindent: bool) {
2388 if autoindent {
2389 self.autoindent_mode = Some(AutoindentMode::EachLine);
2390 } else {
2391 self.autoindent_mode = None;
2392 }
2393 }
2394
2395 pub fn read_only(&self, cx: &App) -> bool {
2396 self.read_only || self.buffer.read(cx).read_only()
2397 }
2398
2399 pub fn set_read_only(&mut self, read_only: bool) {
2400 self.read_only = read_only;
2401 }
2402
2403 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2404 self.use_autoclose = autoclose;
2405 }
2406
2407 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2408 self.use_auto_surround = auto_surround;
2409 }
2410
2411 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2412 self.auto_replace_emoji_shortcode = auto_replace;
2413 }
2414
2415 pub fn toggle_edit_predictions(
2416 &mut self,
2417 _: &ToggleEditPrediction,
2418 window: &mut Window,
2419 cx: &mut Context<Self>,
2420 ) {
2421 if self.show_inline_completions_override.is_some() {
2422 self.set_show_edit_predictions(None, window, cx);
2423 } else {
2424 let show_edit_predictions = !self.edit_predictions_enabled();
2425 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2426 }
2427 }
2428
2429 pub fn set_show_edit_predictions(
2430 &mut self,
2431 show_edit_predictions: Option<bool>,
2432 window: &mut Window,
2433 cx: &mut Context<Self>,
2434 ) {
2435 self.show_inline_completions_override = show_edit_predictions;
2436 self.update_edit_prediction_settings(cx);
2437
2438 if let Some(false) = show_edit_predictions {
2439 self.discard_inline_completion(false, cx);
2440 } else {
2441 self.refresh_inline_completion(false, true, window, cx);
2442 }
2443 }
2444
2445 fn inline_completions_disabled_in_scope(
2446 &self,
2447 buffer: &Entity<Buffer>,
2448 buffer_position: language::Anchor,
2449 cx: &App,
2450 ) -> bool {
2451 let snapshot = buffer.read(cx).snapshot();
2452 let settings = snapshot.settings_at(buffer_position, cx);
2453
2454 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2455 return false;
2456 };
2457
2458 scope.override_name().map_or(false, |scope_name| {
2459 settings
2460 .edit_predictions_disabled_in
2461 .iter()
2462 .any(|s| s == scope_name)
2463 })
2464 }
2465
2466 pub fn set_use_modal_editing(&mut self, to: bool) {
2467 self.use_modal_editing = to;
2468 }
2469
2470 pub fn use_modal_editing(&self) -> bool {
2471 self.use_modal_editing
2472 }
2473
2474 fn selections_did_change(
2475 &mut self,
2476 local: bool,
2477 old_cursor_position: &Anchor,
2478 show_completions: bool,
2479 window: &mut Window,
2480 cx: &mut Context<Self>,
2481 ) {
2482 window.invalidate_character_coordinates();
2483
2484 // Copy selections to primary selection buffer
2485 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2486 if local {
2487 let selections = self.selections.all::<usize>(cx);
2488 let buffer_handle = self.buffer.read(cx).read(cx);
2489
2490 let mut text = String::new();
2491 for (index, selection) in selections.iter().enumerate() {
2492 let text_for_selection = buffer_handle
2493 .text_for_range(selection.start..selection.end)
2494 .collect::<String>();
2495
2496 text.push_str(&text_for_selection);
2497 if index != selections.len() - 1 {
2498 text.push('\n');
2499 }
2500 }
2501
2502 if !text.is_empty() {
2503 cx.write_to_primary(ClipboardItem::new_string(text));
2504 }
2505 }
2506
2507 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2508 self.buffer.update(cx, |buffer, cx| {
2509 buffer.set_active_selections(
2510 &self.selections.disjoint_anchors(),
2511 self.selections.line_mode,
2512 self.cursor_shape,
2513 cx,
2514 )
2515 });
2516 }
2517 let display_map = self
2518 .display_map
2519 .update(cx, |display_map, cx| display_map.snapshot(cx));
2520 let buffer = &display_map.buffer_snapshot;
2521 self.add_selections_state = None;
2522 self.select_next_state = None;
2523 self.select_prev_state = None;
2524 self.select_syntax_node_history.try_clear();
2525 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2526 self.snippet_stack
2527 .invalidate(&self.selections.disjoint_anchors(), buffer);
2528 self.take_rename(false, window, cx);
2529
2530 let new_cursor_position = self.selections.newest_anchor().head();
2531
2532 self.push_to_nav_history(
2533 *old_cursor_position,
2534 Some(new_cursor_position.to_point(buffer)),
2535 false,
2536 cx,
2537 );
2538
2539 if local {
2540 let new_cursor_position = self.selections.newest_anchor().head();
2541 let mut context_menu = self.context_menu.borrow_mut();
2542 let completion_menu = match context_menu.as_ref() {
2543 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2544 _ => {
2545 *context_menu = None;
2546 None
2547 }
2548 };
2549 if let Some(buffer_id) = new_cursor_position.buffer_id {
2550 if !self.registered_buffers.contains_key(&buffer_id) {
2551 if let Some(project) = self.project.as_ref() {
2552 project.update(cx, |project, cx| {
2553 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2554 return;
2555 };
2556 self.registered_buffers.insert(
2557 buffer_id,
2558 project.register_buffer_with_language_servers(&buffer, cx),
2559 );
2560 })
2561 }
2562 }
2563 }
2564
2565 if let Some(completion_menu) = completion_menu {
2566 let cursor_position = new_cursor_position.to_offset(buffer);
2567 let (word_range, kind) =
2568 buffer.surrounding_word(completion_menu.initial_position, true);
2569 if kind == Some(CharKind::Word)
2570 && word_range.to_inclusive().contains(&cursor_position)
2571 {
2572 let mut completion_menu = completion_menu.clone();
2573 drop(context_menu);
2574
2575 let query = Self::completion_query(buffer, cursor_position);
2576 cx.spawn(async move |this, cx| {
2577 completion_menu
2578 .filter(query.as_deref(), cx.background_executor().clone())
2579 .await;
2580
2581 this.update(cx, |this, cx| {
2582 let mut context_menu = this.context_menu.borrow_mut();
2583 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2584 else {
2585 return;
2586 };
2587
2588 if menu.id > completion_menu.id {
2589 return;
2590 }
2591
2592 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2593 drop(context_menu);
2594 cx.notify();
2595 })
2596 })
2597 .detach();
2598
2599 if show_completions {
2600 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2601 }
2602 } else {
2603 drop(context_menu);
2604 self.hide_context_menu(window, cx);
2605 }
2606 } else {
2607 drop(context_menu);
2608 }
2609
2610 hide_hover(self, cx);
2611
2612 if old_cursor_position.to_display_point(&display_map).row()
2613 != new_cursor_position.to_display_point(&display_map).row()
2614 {
2615 self.available_code_actions.take();
2616 }
2617 self.refresh_code_actions(window, cx);
2618 self.refresh_document_highlights(cx);
2619 self.refresh_selected_text_highlights(window, cx);
2620 refresh_matching_bracket_highlights(self, window, cx);
2621 self.update_visible_inline_completion(window, cx);
2622 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2623 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2624 self.inline_blame_popover.take();
2625 if self.git_blame_inline_enabled {
2626 self.start_inline_blame_timer(window, cx);
2627 }
2628 }
2629
2630 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2631 cx.emit(EditorEvent::SelectionsChanged { local });
2632
2633 let selections = &self.selections.disjoint;
2634 if selections.len() == 1 {
2635 cx.emit(SearchEvent::ActiveMatchChanged)
2636 }
2637 if local {
2638 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2639 let inmemory_selections = selections
2640 .iter()
2641 .map(|s| {
2642 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2643 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2644 })
2645 .collect();
2646 self.update_restoration_data(cx, |data| {
2647 data.selections = inmemory_selections;
2648 });
2649
2650 if WorkspaceSettings::get(None, cx).restore_on_startup
2651 != RestoreOnStartupBehavior::None
2652 {
2653 if let Some(workspace_id) =
2654 self.workspace.as_ref().and_then(|workspace| workspace.1)
2655 {
2656 let snapshot = self.buffer().read(cx).snapshot(cx);
2657 let selections = selections.clone();
2658 let background_executor = cx.background_executor().clone();
2659 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2660 self.serialize_selections = cx.background_spawn(async move {
2661 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2662 let db_selections = selections
2663 .iter()
2664 .map(|selection| {
2665 (
2666 selection.start.to_offset(&snapshot),
2667 selection.end.to_offset(&snapshot),
2668 )
2669 })
2670 .collect();
2671
2672 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2673 .await
2674 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2675 .log_err();
2676 });
2677 }
2678 }
2679 }
2680 }
2681
2682 cx.notify();
2683 }
2684
2685 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2686 use text::ToOffset as _;
2687 use text::ToPoint as _;
2688
2689 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2690 return;
2691 }
2692
2693 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2694 return;
2695 };
2696
2697 let snapshot = singleton.read(cx).snapshot();
2698 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2699 let display_snapshot = display_map.snapshot(cx);
2700
2701 display_snapshot
2702 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2703 .map(|fold| {
2704 fold.range.start.text_anchor.to_point(&snapshot)
2705 ..fold.range.end.text_anchor.to_point(&snapshot)
2706 })
2707 .collect()
2708 });
2709 self.update_restoration_data(cx, |data| {
2710 data.folds = inmemory_folds;
2711 });
2712
2713 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2714 return;
2715 };
2716 let background_executor = cx.background_executor().clone();
2717 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2718 let db_folds = self.display_map.update(cx, |display_map, cx| {
2719 display_map
2720 .snapshot(cx)
2721 .folds_in_range(0..snapshot.len())
2722 .map(|fold| {
2723 (
2724 fold.range.start.text_anchor.to_offset(&snapshot),
2725 fold.range.end.text_anchor.to_offset(&snapshot),
2726 )
2727 })
2728 .collect()
2729 });
2730 self.serialize_folds = cx.background_spawn(async move {
2731 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2732 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2733 .await
2734 .with_context(|| {
2735 format!(
2736 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2737 )
2738 })
2739 .log_err();
2740 });
2741 }
2742
2743 pub fn sync_selections(
2744 &mut self,
2745 other: Entity<Editor>,
2746 cx: &mut Context<Self>,
2747 ) -> gpui::Subscription {
2748 let other_selections = other.read(cx).selections.disjoint.to_vec();
2749 self.selections.change_with(cx, |selections| {
2750 selections.select_anchors(other_selections);
2751 });
2752
2753 let other_subscription =
2754 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2755 EditorEvent::SelectionsChanged { local: true } => {
2756 let other_selections = other.read(cx).selections.disjoint.to_vec();
2757 if other_selections.is_empty() {
2758 return;
2759 }
2760 this.selections.change_with(cx, |selections| {
2761 selections.select_anchors(other_selections);
2762 });
2763 }
2764 _ => {}
2765 });
2766
2767 let this_subscription =
2768 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2769 EditorEvent::SelectionsChanged { local: true } => {
2770 let these_selections = this.selections.disjoint.to_vec();
2771 if these_selections.is_empty() {
2772 return;
2773 }
2774 other.update(cx, |other_editor, cx| {
2775 other_editor.selections.change_with(cx, |selections| {
2776 selections.select_anchors(these_selections);
2777 })
2778 });
2779 }
2780 _ => {}
2781 });
2782
2783 Subscription::join(other_subscription, this_subscription)
2784 }
2785
2786 pub fn change_selections<R>(
2787 &mut self,
2788 autoscroll: Option<Autoscroll>,
2789 window: &mut Window,
2790 cx: &mut Context<Self>,
2791 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2792 ) -> R {
2793 self.change_selections_inner(autoscroll, true, window, cx, change)
2794 }
2795
2796 fn change_selections_inner<R>(
2797 &mut self,
2798 autoscroll: Option<Autoscroll>,
2799 request_completions: bool,
2800 window: &mut Window,
2801 cx: &mut Context<Self>,
2802 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2803 ) -> R {
2804 let old_cursor_position = self.selections.newest_anchor().head();
2805 self.push_to_selection_history();
2806
2807 let (changed, result) = self.selections.change_with(cx, change);
2808
2809 if changed {
2810 if let Some(autoscroll) = autoscroll {
2811 self.request_autoscroll(autoscroll, cx);
2812 }
2813 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2814
2815 if self.should_open_signature_help_automatically(
2816 &old_cursor_position,
2817 self.signature_help_state.backspace_pressed(),
2818 cx,
2819 ) {
2820 self.show_signature_help(&ShowSignatureHelp, window, cx);
2821 }
2822 self.signature_help_state.set_backspace_pressed(false);
2823 }
2824
2825 result
2826 }
2827
2828 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2829 where
2830 I: IntoIterator<Item = (Range<S>, T)>,
2831 S: ToOffset,
2832 T: Into<Arc<str>>,
2833 {
2834 if self.read_only(cx) {
2835 return;
2836 }
2837
2838 self.buffer
2839 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2840 }
2841
2842 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2843 where
2844 I: IntoIterator<Item = (Range<S>, T)>,
2845 S: ToOffset,
2846 T: Into<Arc<str>>,
2847 {
2848 if self.read_only(cx) {
2849 return;
2850 }
2851
2852 self.buffer.update(cx, |buffer, cx| {
2853 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2854 });
2855 }
2856
2857 pub fn edit_with_block_indent<I, S, T>(
2858 &mut self,
2859 edits: I,
2860 original_indent_columns: Vec<Option<u32>>,
2861 cx: &mut Context<Self>,
2862 ) where
2863 I: IntoIterator<Item = (Range<S>, T)>,
2864 S: ToOffset,
2865 T: Into<Arc<str>>,
2866 {
2867 if self.read_only(cx) {
2868 return;
2869 }
2870
2871 self.buffer.update(cx, |buffer, cx| {
2872 buffer.edit(
2873 edits,
2874 Some(AutoindentMode::Block {
2875 original_indent_columns,
2876 }),
2877 cx,
2878 )
2879 });
2880 }
2881
2882 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2883 self.hide_context_menu(window, cx);
2884
2885 match phase {
2886 SelectPhase::Begin {
2887 position,
2888 add,
2889 click_count,
2890 } => self.begin_selection(position, add, click_count, window, cx),
2891 SelectPhase::BeginColumnar {
2892 position,
2893 goal_column,
2894 reset,
2895 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2896 SelectPhase::Extend {
2897 position,
2898 click_count,
2899 } => self.extend_selection(position, click_count, window, cx),
2900 SelectPhase::Update {
2901 position,
2902 goal_column,
2903 scroll_delta,
2904 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2905 SelectPhase::End => self.end_selection(window, cx),
2906 }
2907 }
2908
2909 fn extend_selection(
2910 &mut self,
2911 position: DisplayPoint,
2912 click_count: usize,
2913 window: &mut Window,
2914 cx: &mut Context<Self>,
2915 ) {
2916 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2917 let tail = self.selections.newest::<usize>(cx).tail();
2918 self.begin_selection(position, false, click_count, window, cx);
2919
2920 let position = position.to_offset(&display_map, Bias::Left);
2921 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2922
2923 let mut pending_selection = self
2924 .selections
2925 .pending_anchor()
2926 .expect("extend_selection not called with pending selection");
2927 if position >= tail {
2928 pending_selection.start = tail_anchor;
2929 } else {
2930 pending_selection.end = tail_anchor;
2931 pending_selection.reversed = true;
2932 }
2933
2934 let mut pending_mode = self.selections.pending_mode().unwrap();
2935 match &mut pending_mode {
2936 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2937 _ => {}
2938 }
2939
2940 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2941 s.set_pending(pending_selection, pending_mode)
2942 });
2943 }
2944
2945 fn begin_selection(
2946 &mut self,
2947 position: DisplayPoint,
2948 add: bool,
2949 click_count: usize,
2950 window: &mut Window,
2951 cx: &mut Context<Self>,
2952 ) {
2953 if !self.focus_handle.is_focused(window) {
2954 self.last_focused_descendant = None;
2955 window.focus(&self.focus_handle);
2956 }
2957
2958 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2959 let buffer = &display_map.buffer_snapshot;
2960 let newest_selection = self.selections.newest_anchor().clone();
2961 let position = display_map.clip_point(position, Bias::Left);
2962
2963 let start;
2964 let end;
2965 let mode;
2966 let mut auto_scroll;
2967 match click_count {
2968 1 => {
2969 start = buffer.anchor_before(position.to_point(&display_map));
2970 end = start;
2971 mode = SelectMode::Character;
2972 auto_scroll = true;
2973 }
2974 2 => {
2975 let range = movement::surrounding_word(&display_map, position);
2976 start = buffer.anchor_before(range.start.to_point(&display_map));
2977 end = buffer.anchor_before(range.end.to_point(&display_map));
2978 mode = SelectMode::Word(start..end);
2979 auto_scroll = true;
2980 }
2981 3 => {
2982 let position = display_map
2983 .clip_point(position, Bias::Left)
2984 .to_point(&display_map);
2985 let line_start = display_map.prev_line_boundary(position).0;
2986 let next_line_start = buffer.clip_point(
2987 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2988 Bias::Left,
2989 );
2990 start = buffer.anchor_before(line_start);
2991 end = buffer.anchor_before(next_line_start);
2992 mode = SelectMode::Line(start..end);
2993 auto_scroll = true;
2994 }
2995 _ => {
2996 start = buffer.anchor_before(0);
2997 end = buffer.anchor_before(buffer.len());
2998 mode = SelectMode::All;
2999 auto_scroll = false;
3000 }
3001 }
3002 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
3003
3004 let point_to_delete: Option<usize> = {
3005 let selected_points: Vec<Selection<Point>> =
3006 self.selections.disjoint_in_range(start..end, cx);
3007
3008 if !add || click_count > 1 {
3009 None
3010 } else if !selected_points.is_empty() {
3011 Some(selected_points[0].id)
3012 } else {
3013 let clicked_point_already_selected =
3014 self.selections.disjoint.iter().find(|selection| {
3015 selection.start.to_point(buffer) == start.to_point(buffer)
3016 || selection.end.to_point(buffer) == end.to_point(buffer)
3017 });
3018
3019 clicked_point_already_selected.map(|selection| selection.id)
3020 }
3021 };
3022
3023 let selections_count = self.selections.count();
3024
3025 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
3026 if let Some(point_to_delete) = point_to_delete {
3027 s.delete(point_to_delete);
3028
3029 if selections_count == 1 {
3030 s.set_pending_anchor_range(start..end, mode);
3031 }
3032 } else {
3033 if !add {
3034 s.clear_disjoint();
3035 } else if click_count > 1 {
3036 s.delete(newest_selection.id)
3037 }
3038
3039 s.set_pending_anchor_range(start..end, mode);
3040 }
3041 });
3042 }
3043
3044 fn begin_columnar_selection(
3045 &mut self,
3046 position: DisplayPoint,
3047 goal_column: u32,
3048 reset: bool,
3049 window: &mut Window,
3050 cx: &mut Context<Self>,
3051 ) {
3052 if !self.focus_handle.is_focused(window) {
3053 self.last_focused_descendant = None;
3054 window.focus(&self.focus_handle);
3055 }
3056
3057 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3058
3059 if reset {
3060 let pointer_position = display_map
3061 .buffer_snapshot
3062 .anchor_before(position.to_point(&display_map));
3063
3064 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
3065 s.clear_disjoint();
3066 s.set_pending_anchor_range(
3067 pointer_position..pointer_position,
3068 SelectMode::Character,
3069 );
3070 });
3071 }
3072
3073 let tail = self.selections.newest::<Point>(cx).tail();
3074 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3075
3076 if !reset {
3077 self.select_columns(
3078 tail.to_display_point(&display_map),
3079 position,
3080 goal_column,
3081 &display_map,
3082 window,
3083 cx,
3084 );
3085 }
3086 }
3087
3088 fn update_selection(
3089 &mut self,
3090 position: DisplayPoint,
3091 goal_column: u32,
3092 scroll_delta: gpui::Point<f32>,
3093 window: &mut Window,
3094 cx: &mut Context<Self>,
3095 ) {
3096 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3097
3098 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3099 let tail = tail.to_display_point(&display_map);
3100 self.select_columns(tail, position, goal_column, &display_map, window, cx);
3101 } else if let Some(mut pending) = self.selections.pending_anchor() {
3102 let buffer = self.buffer.read(cx).snapshot(cx);
3103 let head;
3104 let tail;
3105 let mode = self.selections.pending_mode().unwrap();
3106 match &mode {
3107 SelectMode::Character => {
3108 head = position.to_point(&display_map);
3109 tail = pending.tail().to_point(&buffer);
3110 }
3111 SelectMode::Word(original_range) => {
3112 let original_display_range = original_range.start.to_display_point(&display_map)
3113 ..original_range.end.to_display_point(&display_map);
3114 let original_buffer_range = original_display_range.start.to_point(&display_map)
3115 ..original_display_range.end.to_point(&display_map);
3116 if movement::is_inside_word(&display_map, position)
3117 || original_display_range.contains(&position)
3118 {
3119 let word_range = movement::surrounding_word(&display_map, position);
3120 if word_range.start < original_display_range.start {
3121 head = word_range.start.to_point(&display_map);
3122 } else {
3123 head = word_range.end.to_point(&display_map);
3124 }
3125 } else {
3126 head = position.to_point(&display_map);
3127 }
3128
3129 if head <= original_buffer_range.start {
3130 tail = original_buffer_range.end;
3131 } else {
3132 tail = original_buffer_range.start;
3133 }
3134 }
3135 SelectMode::Line(original_range) => {
3136 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3137
3138 let position = display_map
3139 .clip_point(position, Bias::Left)
3140 .to_point(&display_map);
3141 let line_start = display_map.prev_line_boundary(position).0;
3142 let next_line_start = buffer.clip_point(
3143 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3144 Bias::Left,
3145 );
3146
3147 if line_start < original_range.start {
3148 head = line_start
3149 } else {
3150 head = next_line_start
3151 }
3152
3153 if head <= original_range.start {
3154 tail = original_range.end;
3155 } else {
3156 tail = original_range.start;
3157 }
3158 }
3159 SelectMode::All => {
3160 return;
3161 }
3162 };
3163
3164 if head < tail {
3165 pending.start = buffer.anchor_before(head);
3166 pending.end = buffer.anchor_before(tail);
3167 pending.reversed = true;
3168 } else {
3169 pending.start = buffer.anchor_before(tail);
3170 pending.end = buffer.anchor_before(head);
3171 pending.reversed = false;
3172 }
3173
3174 self.change_selections(None, window, cx, |s| {
3175 s.set_pending(pending, mode);
3176 });
3177 } else {
3178 log::error!("update_selection dispatched with no pending selection");
3179 return;
3180 }
3181
3182 self.apply_scroll_delta(scroll_delta, window, cx);
3183 cx.notify();
3184 }
3185
3186 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3187 self.columnar_selection_tail.take();
3188 if self.selections.pending_anchor().is_some() {
3189 let selections = self.selections.all::<usize>(cx);
3190 self.change_selections(None, window, cx, |s| {
3191 s.select(selections);
3192 s.clear_pending();
3193 });
3194 }
3195 }
3196
3197 fn select_columns(
3198 &mut self,
3199 tail: DisplayPoint,
3200 head: DisplayPoint,
3201 goal_column: u32,
3202 display_map: &DisplaySnapshot,
3203 window: &mut Window,
3204 cx: &mut Context<Self>,
3205 ) {
3206 let start_row = cmp::min(tail.row(), head.row());
3207 let end_row = cmp::max(tail.row(), head.row());
3208 let start_column = cmp::min(tail.column(), goal_column);
3209 let end_column = cmp::max(tail.column(), goal_column);
3210 let reversed = start_column < tail.column();
3211
3212 let selection_ranges = (start_row.0..=end_row.0)
3213 .map(DisplayRow)
3214 .filter_map(|row| {
3215 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3216 let start = display_map
3217 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3218 .to_point(display_map);
3219 let end = display_map
3220 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3221 .to_point(display_map);
3222 if reversed {
3223 Some(end..start)
3224 } else {
3225 Some(start..end)
3226 }
3227 } else {
3228 None
3229 }
3230 })
3231 .collect::<Vec<_>>();
3232
3233 self.change_selections(None, window, cx, |s| {
3234 s.select_ranges(selection_ranges);
3235 });
3236 cx.notify();
3237 }
3238
3239 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3240 self.selections
3241 .all_adjusted(cx)
3242 .iter()
3243 .any(|selection| !selection.is_empty())
3244 }
3245
3246 pub fn has_pending_nonempty_selection(&self) -> bool {
3247 let pending_nonempty_selection = match self.selections.pending_anchor() {
3248 Some(Selection { start, end, .. }) => start != end,
3249 None => false,
3250 };
3251
3252 pending_nonempty_selection
3253 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3254 }
3255
3256 pub fn has_pending_selection(&self) -> bool {
3257 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3258 }
3259
3260 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3261 self.selection_mark_mode = false;
3262
3263 if self.clear_expanded_diff_hunks(cx) {
3264 cx.notify();
3265 return;
3266 }
3267 if self.dismiss_menus_and_popups(true, window, cx) {
3268 return;
3269 }
3270
3271 if self.mode.is_full()
3272 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3273 {
3274 return;
3275 }
3276
3277 cx.propagate();
3278 }
3279
3280 pub fn dismiss_menus_and_popups(
3281 &mut self,
3282 is_user_requested: bool,
3283 window: &mut Window,
3284 cx: &mut Context<Self>,
3285 ) -> bool {
3286 if self.take_rename(false, window, cx).is_some() {
3287 return true;
3288 }
3289
3290 if hide_hover(self, cx) {
3291 return true;
3292 }
3293
3294 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3295 return true;
3296 }
3297
3298 if self.hide_context_menu(window, cx).is_some() {
3299 return true;
3300 }
3301
3302 if self.mouse_context_menu.take().is_some() {
3303 return true;
3304 }
3305
3306 if is_user_requested && self.discard_inline_completion(true, cx) {
3307 return true;
3308 }
3309
3310 if self.snippet_stack.pop().is_some() {
3311 return true;
3312 }
3313
3314 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3315 self.dismiss_diagnostics(cx);
3316 return true;
3317 }
3318
3319 false
3320 }
3321
3322 fn linked_editing_ranges_for(
3323 &self,
3324 selection: Range<text::Anchor>,
3325 cx: &App,
3326 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3327 if self.linked_edit_ranges.is_empty() {
3328 return None;
3329 }
3330 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3331 selection.end.buffer_id.and_then(|end_buffer_id| {
3332 if selection.start.buffer_id != Some(end_buffer_id) {
3333 return None;
3334 }
3335 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3336 let snapshot = buffer.read(cx).snapshot();
3337 self.linked_edit_ranges
3338 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3339 .map(|ranges| (ranges, snapshot, buffer))
3340 })?;
3341 use text::ToOffset as TO;
3342 // find offset from the start of current range to current cursor position
3343 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3344
3345 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3346 let start_difference = start_offset - start_byte_offset;
3347 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3348 let end_difference = end_offset - start_byte_offset;
3349 // Current range has associated linked ranges.
3350 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3351 for range in linked_ranges.iter() {
3352 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3353 let end_offset = start_offset + end_difference;
3354 let start_offset = start_offset + start_difference;
3355 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3356 continue;
3357 }
3358 if self.selections.disjoint_anchor_ranges().any(|s| {
3359 if s.start.buffer_id != selection.start.buffer_id
3360 || s.end.buffer_id != selection.end.buffer_id
3361 {
3362 return false;
3363 }
3364 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3365 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3366 }) {
3367 continue;
3368 }
3369 let start = buffer_snapshot.anchor_after(start_offset);
3370 let end = buffer_snapshot.anchor_after(end_offset);
3371 linked_edits
3372 .entry(buffer.clone())
3373 .or_default()
3374 .push(start..end);
3375 }
3376 Some(linked_edits)
3377 }
3378
3379 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3380 let text: Arc<str> = text.into();
3381
3382 if self.read_only(cx) {
3383 return;
3384 }
3385
3386 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3387
3388 let selections = self.selections.all_adjusted(cx);
3389 let mut bracket_inserted = false;
3390 let mut edits = Vec::new();
3391 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3392 let mut new_selections = Vec::with_capacity(selections.len());
3393 let mut new_autoclose_regions = Vec::new();
3394 let snapshot = self.buffer.read(cx).read(cx);
3395 let mut clear_linked_edit_ranges = false;
3396
3397 for (selection, autoclose_region) in
3398 self.selections_with_autoclose_regions(selections, &snapshot)
3399 {
3400 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3401 // Determine if the inserted text matches the opening or closing
3402 // bracket of any of this language's bracket pairs.
3403 let mut bracket_pair = None;
3404 let mut is_bracket_pair_start = false;
3405 let mut is_bracket_pair_end = false;
3406 if !text.is_empty() {
3407 let mut bracket_pair_matching_end = None;
3408 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3409 // and they are removing the character that triggered IME popup.
3410 for (pair, enabled) in scope.brackets() {
3411 if !pair.close && !pair.surround {
3412 continue;
3413 }
3414
3415 if enabled && pair.start.ends_with(text.as_ref()) {
3416 let prefix_len = pair.start.len() - text.len();
3417 let preceding_text_matches_prefix = prefix_len == 0
3418 || (selection.start.column >= (prefix_len as u32)
3419 && snapshot.contains_str_at(
3420 Point::new(
3421 selection.start.row,
3422 selection.start.column - (prefix_len as u32),
3423 ),
3424 &pair.start[..prefix_len],
3425 ));
3426 if preceding_text_matches_prefix {
3427 bracket_pair = Some(pair.clone());
3428 is_bracket_pair_start = true;
3429 break;
3430 }
3431 }
3432 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3433 {
3434 // take first bracket pair matching end, but don't break in case a later bracket
3435 // pair matches start
3436 bracket_pair_matching_end = Some(pair.clone());
3437 }
3438 }
3439 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3440 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3441 is_bracket_pair_end = true;
3442 }
3443 }
3444
3445 if let Some(bracket_pair) = bracket_pair {
3446 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3447 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3448 let auto_surround =
3449 self.use_auto_surround && snapshot_settings.use_auto_surround;
3450 if selection.is_empty() {
3451 if is_bracket_pair_start {
3452 // If the inserted text is a suffix of an opening bracket and the
3453 // selection is preceded by the rest of the opening bracket, then
3454 // insert the closing bracket.
3455 let following_text_allows_autoclose = snapshot
3456 .chars_at(selection.start)
3457 .next()
3458 .map_or(true, |c| scope.should_autoclose_before(c));
3459
3460 let preceding_text_allows_autoclose = selection.start.column == 0
3461 || snapshot.reversed_chars_at(selection.start).next().map_or(
3462 true,
3463 |c| {
3464 bracket_pair.start != bracket_pair.end
3465 || !snapshot
3466 .char_classifier_at(selection.start)
3467 .is_word(c)
3468 },
3469 );
3470
3471 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3472 && bracket_pair.start.len() == 1
3473 {
3474 let target = bracket_pair.start.chars().next().unwrap();
3475 let current_line_count = snapshot
3476 .reversed_chars_at(selection.start)
3477 .take_while(|&c| c != '\n')
3478 .filter(|&c| c == target)
3479 .count();
3480 current_line_count % 2 == 1
3481 } else {
3482 false
3483 };
3484
3485 if autoclose
3486 && bracket_pair.close
3487 && following_text_allows_autoclose
3488 && preceding_text_allows_autoclose
3489 && !is_closing_quote
3490 {
3491 let anchor = snapshot.anchor_before(selection.end);
3492 new_selections.push((selection.map(|_| anchor), text.len()));
3493 new_autoclose_regions.push((
3494 anchor,
3495 text.len(),
3496 selection.id,
3497 bracket_pair.clone(),
3498 ));
3499 edits.push((
3500 selection.range(),
3501 format!("{}{}", text, bracket_pair.end).into(),
3502 ));
3503 bracket_inserted = true;
3504 continue;
3505 }
3506 }
3507
3508 if let Some(region) = autoclose_region {
3509 // If the selection is followed by an auto-inserted closing bracket,
3510 // then don't insert that closing bracket again; just move the selection
3511 // past the closing bracket.
3512 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3513 && text.as_ref() == region.pair.end.as_str();
3514 if should_skip {
3515 let anchor = snapshot.anchor_after(selection.end);
3516 new_selections
3517 .push((selection.map(|_| anchor), region.pair.end.len()));
3518 continue;
3519 }
3520 }
3521
3522 let always_treat_brackets_as_autoclosed = snapshot
3523 .language_settings_at(selection.start, cx)
3524 .always_treat_brackets_as_autoclosed;
3525 if always_treat_brackets_as_autoclosed
3526 && is_bracket_pair_end
3527 && snapshot.contains_str_at(selection.end, text.as_ref())
3528 {
3529 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3530 // and the inserted text is a closing bracket and the selection is followed
3531 // by the closing bracket then move the selection past the closing bracket.
3532 let anchor = snapshot.anchor_after(selection.end);
3533 new_selections.push((selection.map(|_| anchor), text.len()));
3534 continue;
3535 }
3536 }
3537 // If an opening bracket is 1 character long and is typed while
3538 // text is selected, then surround that text with the bracket pair.
3539 else if auto_surround
3540 && bracket_pair.surround
3541 && is_bracket_pair_start
3542 && bracket_pair.start.chars().count() == 1
3543 {
3544 edits.push((selection.start..selection.start, text.clone()));
3545 edits.push((
3546 selection.end..selection.end,
3547 bracket_pair.end.as_str().into(),
3548 ));
3549 bracket_inserted = true;
3550 new_selections.push((
3551 Selection {
3552 id: selection.id,
3553 start: snapshot.anchor_after(selection.start),
3554 end: snapshot.anchor_before(selection.end),
3555 reversed: selection.reversed,
3556 goal: selection.goal,
3557 },
3558 0,
3559 ));
3560 continue;
3561 }
3562 }
3563 }
3564
3565 if self.auto_replace_emoji_shortcode
3566 && selection.is_empty()
3567 && text.as_ref().ends_with(':')
3568 {
3569 if let Some(possible_emoji_short_code) =
3570 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3571 {
3572 if !possible_emoji_short_code.is_empty() {
3573 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3574 let emoji_shortcode_start = Point::new(
3575 selection.start.row,
3576 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3577 );
3578
3579 // Remove shortcode from buffer
3580 edits.push((
3581 emoji_shortcode_start..selection.start,
3582 "".to_string().into(),
3583 ));
3584 new_selections.push((
3585 Selection {
3586 id: selection.id,
3587 start: snapshot.anchor_after(emoji_shortcode_start),
3588 end: snapshot.anchor_before(selection.start),
3589 reversed: selection.reversed,
3590 goal: selection.goal,
3591 },
3592 0,
3593 ));
3594
3595 // Insert emoji
3596 let selection_start_anchor = snapshot.anchor_after(selection.start);
3597 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3598 edits.push((selection.start..selection.end, emoji.to_string().into()));
3599
3600 continue;
3601 }
3602 }
3603 }
3604 }
3605
3606 // If not handling any auto-close operation, then just replace the selected
3607 // text with the given input and move the selection to the end of the
3608 // newly inserted text.
3609 let anchor = snapshot.anchor_after(selection.end);
3610 if !self.linked_edit_ranges.is_empty() {
3611 let start_anchor = snapshot.anchor_before(selection.start);
3612
3613 let is_word_char = text.chars().next().map_or(true, |char| {
3614 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3615 classifier.is_word(char)
3616 });
3617
3618 if is_word_char {
3619 if let Some(ranges) = self
3620 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3621 {
3622 for (buffer, edits) in ranges {
3623 linked_edits
3624 .entry(buffer.clone())
3625 .or_default()
3626 .extend(edits.into_iter().map(|range| (range, text.clone())));
3627 }
3628 }
3629 } else {
3630 clear_linked_edit_ranges = true;
3631 }
3632 }
3633
3634 new_selections.push((selection.map(|_| anchor), 0));
3635 edits.push((selection.start..selection.end, text.clone()));
3636 }
3637
3638 drop(snapshot);
3639
3640 self.transact(window, cx, |this, window, cx| {
3641 if clear_linked_edit_ranges {
3642 this.linked_edit_ranges.clear();
3643 }
3644 let initial_buffer_versions =
3645 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3646
3647 this.buffer.update(cx, |buffer, cx| {
3648 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3649 });
3650 for (buffer, edits) in linked_edits {
3651 buffer.update(cx, |buffer, cx| {
3652 let snapshot = buffer.snapshot();
3653 let edits = edits
3654 .into_iter()
3655 .map(|(range, text)| {
3656 use text::ToPoint as TP;
3657 let end_point = TP::to_point(&range.end, &snapshot);
3658 let start_point = TP::to_point(&range.start, &snapshot);
3659 (start_point..end_point, text)
3660 })
3661 .sorted_by_key(|(range, _)| range.start);
3662 buffer.edit(edits, None, cx);
3663 })
3664 }
3665 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3666 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3667 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3668 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3669 .zip(new_selection_deltas)
3670 .map(|(selection, delta)| Selection {
3671 id: selection.id,
3672 start: selection.start + delta,
3673 end: selection.end + delta,
3674 reversed: selection.reversed,
3675 goal: SelectionGoal::None,
3676 })
3677 .collect::<Vec<_>>();
3678
3679 let mut i = 0;
3680 for (position, delta, selection_id, pair) in new_autoclose_regions {
3681 let position = position.to_offset(&map.buffer_snapshot) + delta;
3682 let start = map.buffer_snapshot.anchor_before(position);
3683 let end = map.buffer_snapshot.anchor_after(position);
3684 while let Some(existing_state) = this.autoclose_regions.get(i) {
3685 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3686 Ordering::Less => i += 1,
3687 Ordering::Greater => break,
3688 Ordering::Equal => {
3689 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3690 Ordering::Less => i += 1,
3691 Ordering::Equal => break,
3692 Ordering::Greater => break,
3693 }
3694 }
3695 }
3696 }
3697 this.autoclose_regions.insert(
3698 i,
3699 AutocloseRegion {
3700 selection_id,
3701 range: start..end,
3702 pair,
3703 },
3704 );
3705 }
3706
3707 let had_active_inline_completion = this.has_active_inline_completion();
3708 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3709 s.select(new_selections)
3710 });
3711
3712 if !bracket_inserted {
3713 if let Some(on_type_format_task) =
3714 this.trigger_on_type_formatting(text.to_string(), window, cx)
3715 {
3716 on_type_format_task.detach_and_log_err(cx);
3717 }
3718 }
3719
3720 let editor_settings = EditorSettings::get_global(cx);
3721 if bracket_inserted
3722 && (editor_settings.auto_signature_help
3723 || editor_settings.show_signature_help_after_edits)
3724 {
3725 this.show_signature_help(&ShowSignatureHelp, window, cx);
3726 }
3727
3728 let trigger_in_words =
3729 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3730 if this.hard_wrap.is_some() {
3731 let latest: Range<Point> = this.selections.newest(cx).range();
3732 if latest.is_empty()
3733 && this
3734 .buffer()
3735 .read(cx)
3736 .snapshot(cx)
3737 .line_len(MultiBufferRow(latest.start.row))
3738 == latest.start.column
3739 {
3740 this.rewrap_impl(
3741 RewrapOptions {
3742 override_language_settings: true,
3743 preserve_existing_whitespace: true,
3744 },
3745 cx,
3746 )
3747 }
3748 }
3749 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3750 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3751 this.refresh_inline_completion(true, false, window, cx);
3752 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3753 });
3754 }
3755
3756 fn find_possible_emoji_shortcode_at_position(
3757 snapshot: &MultiBufferSnapshot,
3758 position: Point,
3759 ) -> Option<String> {
3760 let mut chars = Vec::new();
3761 let mut found_colon = false;
3762 for char in snapshot.reversed_chars_at(position).take(100) {
3763 // Found a possible emoji shortcode in the middle of the buffer
3764 if found_colon {
3765 if char.is_whitespace() {
3766 chars.reverse();
3767 return Some(chars.iter().collect());
3768 }
3769 // If the previous character is not a whitespace, we are in the middle of a word
3770 // and we only want to complete the shortcode if the word is made up of other emojis
3771 let mut containing_word = String::new();
3772 for ch in snapshot
3773 .reversed_chars_at(position)
3774 .skip(chars.len() + 1)
3775 .take(100)
3776 {
3777 if ch.is_whitespace() {
3778 break;
3779 }
3780 containing_word.push(ch);
3781 }
3782 let containing_word = containing_word.chars().rev().collect::<String>();
3783 if util::word_consists_of_emojis(containing_word.as_str()) {
3784 chars.reverse();
3785 return Some(chars.iter().collect());
3786 }
3787 }
3788
3789 if char.is_whitespace() || !char.is_ascii() {
3790 return None;
3791 }
3792 if char == ':' {
3793 found_colon = true;
3794 } else {
3795 chars.push(char);
3796 }
3797 }
3798 // Found a possible emoji shortcode at the beginning of the buffer
3799 chars.reverse();
3800 Some(chars.iter().collect())
3801 }
3802
3803 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3804 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3805 self.transact(window, cx, |this, window, cx| {
3806 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3807 let selections = this.selections.all::<usize>(cx);
3808 let multi_buffer = this.buffer.read(cx);
3809 let buffer = multi_buffer.snapshot(cx);
3810 selections
3811 .iter()
3812 .map(|selection| {
3813 let start_point = selection.start.to_point(&buffer);
3814 let mut indent =
3815 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3816 indent.len = cmp::min(indent.len, start_point.column);
3817 let start = selection.start;
3818 let end = selection.end;
3819 let selection_is_empty = start == end;
3820 let language_scope = buffer.language_scope_at(start);
3821 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3822 &language_scope
3823 {
3824 let insert_extra_newline =
3825 insert_extra_newline_brackets(&buffer, start..end, language)
3826 || insert_extra_newline_tree_sitter(&buffer, start..end);
3827
3828 // Comment extension on newline is allowed only for cursor selections
3829 let comment_delimiter = maybe!({
3830 if !selection_is_empty {
3831 return None;
3832 }
3833
3834 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3835 return None;
3836 }
3837
3838 let delimiters = language.line_comment_prefixes();
3839 let max_len_of_delimiter =
3840 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3841 let (snapshot, range) =
3842 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3843
3844 let mut index_of_first_non_whitespace = 0;
3845 let comment_candidate = snapshot
3846 .chars_for_range(range)
3847 .skip_while(|c| {
3848 let should_skip = c.is_whitespace();
3849 if should_skip {
3850 index_of_first_non_whitespace += 1;
3851 }
3852 should_skip
3853 })
3854 .take(max_len_of_delimiter)
3855 .collect::<String>();
3856 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3857 comment_candidate.starts_with(comment_prefix.as_ref())
3858 })?;
3859 let cursor_is_placed_after_comment_marker =
3860 index_of_first_non_whitespace + comment_prefix.len()
3861 <= start_point.column as usize;
3862 if cursor_is_placed_after_comment_marker {
3863 Some(comment_prefix.clone())
3864 } else {
3865 None
3866 }
3867 });
3868 (comment_delimiter, insert_extra_newline)
3869 } else {
3870 (None, false)
3871 };
3872
3873 let capacity_for_delimiter = comment_delimiter
3874 .as_deref()
3875 .map(str::len)
3876 .unwrap_or_default();
3877 let mut new_text =
3878 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3879 new_text.push('\n');
3880 new_text.extend(indent.chars());
3881 if let Some(delimiter) = &comment_delimiter {
3882 new_text.push_str(delimiter);
3883 }
3884 if insert_extra_newline {
3885 new_text = new_text.repeat(2);
3886 }
3887
3888 let anchor = buffer.anchor_after(end);
3889 let new_selection = selection.map(|_| anchor);
3890 (
3891 (start..end, new_text),
3892 (insert_extra_newline, new_selection),
3893 )
3894 })
3895 .unzip()
3896 };
3897
3898 this.edit_with_autoindent(edits, cx);
3899 let buffer = this.buffer.read(cx).snapshot(cx);
3900 let new_selections = selection_fixup_info
3901 .into_iter()
3902 .map(|(extra_newline_inserted, new_selection)| {
3903 let mut cursor = new_selection.end.to_point(&buffer);
3904 if extra_newline_inserted {
3905 cursor.row -= 1;
3906 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3907 }
3908 new_selection.map(|_| cursor)
3909 })
3910 .collect();
3911
3912 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3913 s.select(new_selections)
3914 });
3915 this.refresh_inline_completion(true, false, window, cx);
3916 });
3917 }
3918
3919 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3920 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3921
3922 let buffer = self.buffer.read(cx);
3923 let snapshot = buffer.snapshot(cx);
3924
3925 let mut edits = Vec::new();
3926 let mut rows = Vec::new();
3927
3928 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3929 let cursor = selection.head();
3930 let row = cursor.row;
3931
3932 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3933
3934 let newline = "\n".to_string();
3935 edits.push((start_of_line..start_of_line, newline));
3936
3937 rows.push(row + rows_inserted as u32);
3938 }
3939
3940 self.transact(window, cx, |editor, window, cx| {
3941 editor.edit(edits, cx);
3942
3943 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3944 let mut index = 0;
3945 s.move_cursors_with(|map, _, _| {
3946 let row = rows[index];
3947 index += 1;
3948
3949 let point = Point::new(row, 0);
3950 let boundary = map.next_line_boundary(point).1;
3951 let clipped = map.clip_point(boundary, Bias::Left);
3952
3953 (clipped, SelectionGoal::None)
3954 });
3955 });
3956
3957 let mut indent_edits = Vec::new();
3958 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3959 for row in rows {
3960 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3961 for (row, indent) in indents {
3962 if indent.len == 0 {
3963 continue;
3964 }
3965
3966 let text = match indent.kind {
3967 IndentKind::Space => " ".repeat(indent.len as usize),
3968 IndentKind::Tab => "\t".repeat(indent.len as usize),
3969 };
3970 let point = Point::new(row.0, 0);
3971 indent_edits.push((point..point, text));
3972 }
3973 }
3974 editor.edit(indent_edits, cx);
3975 });
3976 }
3977
3978 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3979 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3980
3981 let buffer = self.buffer.read(cx);
3982 let snapshot = buffer.snapshot(cx);
3983
3984 let mut edits = Vec::new();
3985 let mut rows = Vec::new();
3986 let mut rows_inserted = 0;
3987
3988 for selection in self.selections.all_adjusted(cx) {
3989 let cursor = selection.head();
3990 let row = cursor.row;
3991
3992 let point = Point::new(row + 1, 0);
3993 let start_of_line = snapshot.clip_point(point, Bias::Left);
3994
3995 let newline = "\n".to_string();
3996 edits.push((start_of_line..start_of_line, newline));
3997
3998 rows_inserted += 1;
3999 rows.push(row + rows_inserted);
4000 }
4001
4002 self.transact(window, cx, |editor, window, cx| {
4003 editor.edit(edits, cx);
4004
4005 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4006 let mut index = 0;
4007 s.move_cursors_with(|map, _, _| {
4008 let row = rows[index];
4009 index += 1;
4010
4011 let point = Point::new(row, 0);
4012 let boundary = map.next_line_boundary(point).1;
4013 let clipped = map.clip_point(boundary, Bias::Left);
4014
4015 (clipped, SelectionGoal::None)
4016 });
4017 });
4018
4019 let mut indent_edits = Vec::new();
4020 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4021 for row in rows {
4022 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4023 for (row, indent) in indents {
4024 if indent.len == 0 {
4025 continue;
4026 }
4027
4028 let text = match indent.kind {
4029 IndentKind::Space => " ".repeat(indent.len as usize),
4030 IndentKind::Tab => "\t".repeat(indent.len as usize),
4031 };
4032 let point = Point::new(row.0, 0);
4033 indent_edits.push((point..point, text));
4034 }
4035 }
4036 editor.edit(indent_edits, cx);
4037 });
4038 }
4039
4040 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
4041 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4042 original_indent_columns: Vec::new(),
4043 });
4044 self.insert_with_autoindent_mode(text, autoindent, window, cx);
4045 }
4046
4047 fn insert_with_autoindent_mode(
4048 &mut self,
4049 text: &str,
4050 autoindent_mode: Option<AutoindentMode>,
4051 window: &mut Window,
4052 cx: &mut Context<Self>,
4053 ) {
4054 if self.read_only(cx) {
4055 return;
4056 }
4057
4058 let text: Arc<str> = text.into();
4059 self.transact(window, cx, |this, window, cx| {
4060 let old_selections = this.selections.all_adjusted(cx);
4061 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4062 let anchors = {
4063 let snapshot = buffer.read(cx);
4064 old_selections
4065 .iter()
4066 .map(|s| {
4067 let anchor = snapshot.anchor_after(s.head());
4068 s.map(|_| anchor)
4069 })
4070 .collect::<Vec<_>>()
4071 };
4072 buffer.edit(
4073 old_selections
4074 .iter()
4075 .map(|s| (s.start..s.end, text.clone())),
4076 autoindent_mode,
4077 cx,
4078 );
4079 anchors
4080 });
4081
4082 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4083 s.select_anchors(selection_anchors);
4084 });
4085
4086 cx.notify();
4087 });
4088 }
4089
4090 fn trigger_completion_on_input(
4091 &mut self,
4092 text: &str,
4093 trigger_in_words: bool,
4094 window: &mut Window,
4095 cx: &mut Context<Self>,
4096 ) {
4097 let ignore_completion_provider = self
4098 .context_menu
4099 .borrow()
4100 .as_ref()
4101 .map(|menu| match menu {
4102 CodeContextMenu::Completions(completions_menu) => {
4103 completions_menu.ignore_completion_provider
4104 }
4105 CodeContextMenu::CodeActions(_) => false,
4106 })
4107 .unwrap_or(false);
4108
4109 if ignore_completion_provider {
4110 self.show_word_completions(&ShowWordCompletions, window, cx);
4111 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
4112 self.show_completions(
4113 &ShowCompletions {
4114 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4115 },
4116 window,
4117 cx,
4118 );
4119 } else {
4120 self.hide_context_menu(window, cx);
4121 }
4122 }
4123
4124 fn is_completion_trigger(
4125 &self,
4126 text: &str,
4127 trigger_in_words: bool,
4128 cx: &mut Context<Self>,
4129 ) -> bool {
4130 let position = self.selections.newest_anchor().head();
4131 let multibuffer = self.buffer.read(cx);
4132 let Some(buffer) = position
4133 .buffer_id
4134 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4135 else {
4136 return false;
4137 };
4138
4139 if let Some(completion_provider) = &self.completion_provider {
4140 completion_provider.is_completion_trigger(
4141 &buffer,
4142 position.text_anchor,
4143 text,
4144 trigger_in_words,
4145 cx,
4146 )
4147 } else {
4148 false
4149 }
4150 }
4151
4152 /// If any empty selections is touching the start of its innermost containing autoclose
4153 /// region, expand it to select the brackets.
4154 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4155 let selections = self.selections.all::<usize>(cx);
4156 let buffer = self.buffer.read(cx).read(cx);
4157 let new_selections = self
4158 .selections_with_autoclose_regions(selections, &buffer)
4159 .map(|(mut selection, region)| {
4160 if !selection.is_empty() {
4161 return selection;
4162 }
4163
4164 if let Some(region) = region {
4165 let mut range = region.range.to_offset(&buffer);
4166 if selection.start == range.start && range.start >= region.pair.start.len() {
4167 range.start -= region.pair.start.len();
4168 if buffer.contains_str_at(range.start, ®ion.pair.start)
4169 && buffer.contains_str_at(range.end, ®ion.pair.end)
4170 {
4171 range.end += region.pair.end.len();
4172 selection.start = range.start;
4173 selection.end = range.end;
4174
4175 return selection;
4176 }
4177 }
4178 }
4179
4180 let always_treat_brackets_as_autoclosed = buffer
4181 .language_settings_at(selection.start, cx)
4182 .always_treat_brackets_as_autoclosed;
4183
4184 if !always_treat_brackets_as_autoclosed {
4185 return selection;
4186 }
4187
4188 if let Some(scope) = buffer.language_scope_at(selection.start) {
4189 for (pair, enabled) in scope.brackets() {
4190 if !enabled || !pair.close {
4191 continue;
4192 }
4193
4194 if buffer.contains_str_at(selection.start, &pair.end) {
4195 let pair_start_len = pair.start.len();
4196 if buffer.contains_str_at(
4197 selection.start.saturating_sub(pair_start_len),
4198 &pair.start,
4199 ) {
4200 selection.start -= pair_start_len;
4201 selection.end += pair.end.len();
4202
4203 return selection;
4204 }
4205 }
4206 }
4207 }
4208
4209 selection
4210 })
4211 .collect();
4212
4213 drop(buffer);
4214 self.change_selections(None, window, cx, |selections| {
4215 selections.select(new_selections)
4216 });
4217 }
4218
4219 /// Iterate the given selections, and for each one, find the smallest surrounding
4220 /// autoclose region. This uses the ordering of the selections and the autoclose
4221 /// regions to avoid repeated comparisons.
4222 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4223 &'a self,
4224 selections: impl IntoIterator<Item = Selection<D>>,
4225 buffer: &'a MultiBufferSnapshot,
4226 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4227 let mut i = 0;
4228 let mut regions = self.autoclose_regions.as_slice();
4229 selections.into_iter().map(move |selection| {
4230 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4231
4232 let mut enclosing = None;
4233 while let Some(pair_state) = regions.get(i) {
4234 if pair_state.range.end.to_offset(buffer) < range.start {
4235 regions = ®ions[i + 1..];
4236 i = 0;
4237 } else if pair_state.range.start.to_offset(buffer) > range.end {
4238 break;
4239 } else {
4240 if pair_state.selection_id == selection.id {
4241 enclosing = Some(pair_state);
4242 }
4243 i += 1;
4244 }
4245 }
4246
4247 (selection, enclosing)
4248 })
4249 }
4250
4251 /// Remove any autoclose regions that no longer contain their selection.
4252 fn invalidate_autoclose_regions(
4253 &mut self,
4254 mut selections: &[Selection<Anchor>],
4255 buffer: &MultiBufferSnapshot,
4256 ) {
4257 self.autoclose_regions.retain(|state| {
4258 let mut i = 0;
4259 while let Some(selection) = selections.get(i) {
4260 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4261 selections = &selections[1..];
4262 continue;
4263 }
4264 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4265 break;
4266 }
4267 if selection.id == state.selection_id {
4268 return true;
4269 } else {
4270 i += 1;
4271 }
4272 }
4273 false
4274 });
4275 }
4276
4277 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4278 let offset = position.to_offset(buffer);
4279 let (word_range, kind) = buffer.surrounding_word(offset, true);
4280 if offset > word_range.start && kind == Some(CharKind::Word) {
4281 Some(
4282 buffer
4283 .text_for_range(word_range.start..offset)
4284 .collect::<String>(),
4285 )
4286 } else {
4287 None
4288 }
4289 }
4290
4291 pub fn toggle_inline_values(
4292 &mut self,
4293 _: &ToggleInlineValues,
4294 _: &mut Window,
4295 cx: &mut Context<Self>,
4296 ) {
4297 self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
4298
4299 self.refresh_inline_values(cx);
4300 }
4301
4302 pub fn toggle_inlay_hints(
4303 &mut self,
4304 _: &ToggleInlayHints,
4305 _: &mut Window,
4306 cx: &mut Context<Self>,
4307 ) {
4308 self.refresh_inlay_hints(
4309 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4310 cx,
4311 );
4312 }
4313
4314 pub fn inlay_hints_enabled(&self) -> bool {
4315 self.inlay_hint_cache.enabled
4316 }
4317
4318 pub fn inline_values_enabled(&self) -> bool {
4319 self.inline_value_cache.enabled
4320 }
4321
4322 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4323 if self.semantics_provider.is_none() || !self.mode.is_full() {
4324 return;
4325 }
4326
4327 let reason_description = reason.description();
4328 let ignore_debounce = matches!(
4329 reason,
4330 InlayHintRefreshReason::SettingsChange(_)
4331 | InlayHintRefreshReason::Toggle(_)
4332 | InlayHintRefreshReason::ExcerptsRemoved(_)
4333 | InlayHintRefreshReason::ModifiersChanged(_)
4334 );
4335 let (invalidate_cache, required_languages) = match reason {
4336 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4337 match self.inlay_hint_cache.modifiers_override(enabled) {
4338 Some(enabled) => {
4339 if enabled {
4340 (InvalidationStrategy::RefreshRequested, None)
4341 } else {
4342 self.splice_inlays(
4343 &self
4344 .visible_inlay_hints(cx)
4345 .iter()
4346 .map(|inlay| inlay.id)
4347 .collect::<Vec<InlayId>>(),
4348 Vec::new(),
4349 cx,
4350 );
4351 return;
4352 }
4353 }
4354 None => return,
4355 }
4356 }
4357 InlayHintRefreshReason::Toggle(enabled) => {
4358 if self.inlay_hint_cache.toggle(enabled) {
4359 if enabled {
4360 (InvalidationStrategy::RefreshRequested, None)
4361 } else {
4362 self.splice_inlays(
4363 &self
4364 .visible_inlay_hints(cx)
4365 .iter()
4366 .map(|inlay| inlay.id)
4367 .collect::<Vec<InlayId>>(),
4368 Vec::new(),
4369 cx,
4370 );
4371 return;
4372 }
4373 } else {
4374 return;
4375 }
4376 }
4377 InlayHintRefreshReason::SettingsChange(new_settings) => {
4378 match self.inlay_hint_cache.update_settings(
4379 &self.buffer,
4380 new_settings,
4381 self.visible_inlay_hints(cx),
4382 cx,
4383 ) {
4384 ControlFlow::Break(Some(InlaySplice {
4385 to_remove,
4386 to_insert,
4387 })) => {
4388 self.splice_inlays(&to_remove, to_insert, cx);
4389 return;
4390 }
4391 ControlFlow::Break(None) => return,
4392 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4393 }
4394 }
4395 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4396 if let Some(InlaySplice {
4397 to_remove,
4398 to_insert,
4399 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4400 {
4401 self.splice_inlays(&to_remove, to_insert, cx);
4402 }
4403 self.display_map.update(cx, |display_map, _| {
4404 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4405 });
4406 return;
4407 }
4408 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4409 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4410 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4411 }
4412 InlayHintRefreshReason::RefreshRequested => {
4413 (InvalidationStrategy::RefreshRequested, None)
4414 }
4415 };
4416
4417 if let Some(InlaySplice {
4418 to_remove,
4419 to_insert,
4420 }) = self.inlay_hint_cache.spawn_hint_refresh(
4421 reason_description,
4422 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4423 invalidate_cache,
4424 ignore_debounce,
4425 cx,
4426 ) {
4427 self.splice_inlays(&to_remove, to_insert, cx);
4428 }
4429 }
4430
4431 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4432 self.display_map
4433 .read(cx)
4434 .current_inlays()
4435 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4436 .cloned()
4437 .collect()
4438 }
4439
4440 pub fn excerpts_for_inlay_hints_query(
4441 &self,
4442 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4443 cx: &mut Context<Editor>,
4444 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4445 let Some(project) = self.project.as_ref() else {
4446 return HashMap::default();
4447 };
4448 let project = project.read(cx);
4449 let multi_buffer = self.buffer().read(cx);
4450 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4451 let multi_buffer_visible_start = self
4452 .scroll_manager
4453 .anchor()
4454 .anchor
4455 .to_point(&multi_buffer_snapshot);
4456 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4457 multi_buffer_visible_start
4458 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4459 Bias::Left,
4460 );
4461 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4462 multi_buffer_snapshot
4463 .range_to_buffer_ranges(multi_buffer_visible_range)
4464 .into_iter()
4465 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4466 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4467 let buffer_file = project::File::from_dyn(buffer.file())?;
4468 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4469 let worktree_entry = buffer_worktree
4470 .read(cx)
4471 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4472 if worktree_entry.is_ignored {
4473 return None;
4474 }
4475
4476 let language = buffer.language()?;
4477 if let Some(restrict_to_languages) = restrict_to_languages {
4478 if !restrict_to_languages.contains(language) {
4479 return None;
4480 }
4481 }
4482 Some((
4483 excerpt_id,
4484 (
4485 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4486 buffer.version().clone(),
4487 excerpt_visible_range,
4488 ),
4489 ))
4490 })
4491 .collect()
4492 }
4493
4494 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4495 TextLayoutDetails {
4496 text_system: window.text_system().clone(),
4497 editor_style: self.style.clone().unwrap(),
4498 rem_size: window.rem_size(),
4499 scroll_anchor: self.scroll_manager.anchor(),
4500 visible_rows: self.visible_line_count(),
4501 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4502 }
4503 }
4504
4505 pub fn splice_inlays(
4506 &self,
4507 to_remove: &[InlayId],
4508 to_insert: Vec<Inlay>,
4509 cx: &mut Context<Self>,
4510 ) {
4511 self.display_map.update(cx, |display_map, cx| {
4512 display_map.splice_inlays(to_remove, to_insert, cx)
4513 });
4514 cx.notify();
4515 }
4516
4517 fn trigger_on_type_formatting(
4518 &self,
4519 input: String,
4520 window: &mut Window,
4521 cx: &mut Context<Self>,
4522 ) -> Option<Task<Result<()>>> {
4523 if input.len() != 1 {
4524 return None;
4525 }
4526
4527 let project = self.project.as_ref()?;
4528 let position = self.selections.newest_anchor().head();
4529 let (buffer, buffer_position) = self
4530 .buffer
4531 .read(cx)
4532 .text_anchor_for_position(position, cx)?;
4533
4534 let settings = language_settings::language_settings(
4535 buffer
4536 .read(cx)
4537 .language_at(buffer_position)
4538 .map(|l| l.name()),
4539 buffer.read(cx).file(),
4540 cx,
4541 );
4542 if !settings.use_on_type_format {
4543 return None;
4544 }
4545
4546 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4547 // hence we do LSP request & edit on host side only — add formats to host's history.
4548 let push_to_lsp_host_history = true;
4549 // If this is not the host, append its history with new edits.
4550 let push_to_client_history = project.read(cx).is_via_collab();
4551
4552 let on_type_formatting = project.update(cx, |project, cx| {
4553 project.on_type_format(
4554 buffer.clone(),
4555 buffer_position,
4556 input,
4557 push_to_lsp_host_history,
4558 cx,
4559 )
4560 });
4561 Some(cx.spawn_in(window, async move |editor, cx| {
4562 if let Some(transaction) = on_type_formatting.await? {
4563 if push_to_client_history {
4564 buffer
4565 .update(cx, |buffer, _| {
4566 buffer.push_transaction(transaction, Instant::now());
4567 buffer.finalize_last_transaction();
4568 })
4569 .ok();
4570 }
4571 editor.update(cx, |editor, cx| {
4572 editor.refresh_document_highlights(cx);
4573 })?;
4574 }
4575 Ok(())
4576 }))
4577 }
4578
4579 pub fn show_word_completions(
4580 &mut self,
4581 _: &ShowWordCompletions,
4582 window: &mut Window,
4583 cx: &mut Context<Self>,
4584 ) {
4585 self.open_completions_menu(true, None, window, cx);
4586 }
4587
4588 pub fn show_completions(
4589 &mut self,
4590 options: &ShowCompletions,
4591 window: &mut Window,
4592 cx: &mut Context<Self>,
4593 ) {
4594 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4595 }
4596
4597 fn open_completions_menu(
4598 &mut self,
4599 ignore_completion_provider: bool,
4600 trigger: Option<&str>,
4601 window: &mut Window,
4602 cx: &mut Context<Self>,
4603 ) {
4604 if self.pending_rename.is_some() {
4605 return;
4606 }
4607 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4608 return;
4609 }
4610
4611 let position = self.selections.newest_anchor().head();
4612 if position.diff_base_anchor.is_some() {
4613 return;
4614 }
4615 let (buffer, buffer_position) =
4616 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4617 output
4618 } else {
4619 return;
4620 };
4621 let buffer_snapshot = buffer.read(cx).snapshot();
4622 let show_completion_documentation = buffer_snapshot
4623 .settings_at(buffer_position, cx)
4624 .show_completion_documentation;
4625
4626 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4627
4628 let trigger_kind = match trigger {
4629 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4630 CompletionTriggerKind::TRIGGER_CHARACTER
4631 }
4632 _ => CompletionTriggerKind::INVOKED,
4633 };
4634 let completion_context = CompletionContext {
4635 trigger_character: trigger.and_then(|trigger| {
4636 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4637 Some(String::from(trigger))
4638 } else {
4639 None
4640 }
4641 }),
4642 trigger_kind,
4643 };
4644
4645 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4646 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4647 let word_to_exclude = buffer_snapshot
4648 .text_for_range(old_range.clone())
4649 .collect::<String>();
4650 (
4651 buffer_snapshot.anchor_before(old_range.start)
4652 ..buffer_snapshot.anchor_after(old_range.end),
4653 Some(word_to_exclude),
4654 )
4655 } else {
4656 (buffer_position..buffer_position, None)
4657 };
4658
4659 let completion_settings = language_settings(
4660 buffer_snapshot
4661 .language_at(buffer_position)
4662 .map(|language| language.name()),
4663 buffer_snapshot.file(),
4664 cx,
4665 )
4666 .completions;
4667
4668 // The document can be large, so stay in reasonable bounds when searching for words,
4669 // otherwise completion pop-up might be slow to appear.
4670 const WORD_LOOKUP_ROWS: u32 = 5_000;
4671 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4672 let min_word_search = buffer_snapshot.clip_point(
4673 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4674 Bias::Left,
4675 );
4676 let max_word_search = buffer_snapshot.clip_point(
4677 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4678 Bias::Right,
4679 );
4680 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4681 ..buffer_snapshot.point_to_offset(max_word_search);
4682
4683 let provider = self
4684 .completion_provider
4685 .as_ref()
4686 .filter(|_| !ignore_completion_provider);
4687 let skip_digits = query
4688 .as_ref()
4689 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4690
4691 let (mut words, provided_completions) = match provider {
4692 Some(provider) => {
4693 let completions = provider.completions(
4694 position.excerpt_id,
4695 &buffer,
4696 buffer_position,
4697 completion_context,
4698 window,
4699 cx,
4700 );
4701
4702 let words = match completion_settings.words {
4703 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4704 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4705 .background_spawn(async move {
4706 buffer_snapshot.words_in_range(WordsQuery {
4707 fuzzy_contents: None,
4708 range: word_search_range,
4709 skip_digits,
4710 })
4711 }),
4712 };
4713
4714 (words, completions)
4715 }
4716 None => (
4717 cx.background_spawn(async move {
4718 buffer_snapshot.words_in_range(WordsQuery {
4719 fuzzy_contents: None,
4720 range: word_search_range,
4721 skip_digits,
4722 })
4723 }),
4724 Task::ready(Ok(None)),
4725 ),
4726 };
4727
4728 let sort_completions = provider
4729 .as_ref()
4730 .map_or(false, |provider| provider.sort_completions());
4731
4732 let filter_completions = provider
4733 .as_ref()
4734 .map_or(true, |provider| provider.filter_completions());
4735
4736 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
4737
4738 let id = post_inc(&mut self.next_completion_id);
4739 let task = cx.spawn_in(window, async move |editor, cx| {
4740 async move {
4741 editor.update(cx, |this, _| {
4742 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4743 })?;
4744
4745 let mut completions = Vec::new();
4746 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4747 completions.extend(provided_completions);
4748 if completion_settings.words == WordsCompletionMode::Fallback {
4749 words = Task::ready(BTreeMap::default());
4750 }
4751 }
4752
4753 let mut words = words.await;
4754 if let Some(word_to_exclude) = &word_to_exclude {
4755 words.remove(word_to_exclude);
4756 }
4757 for lsp_completion in &completions {
4758 words.remove(&lsp_completion.new_text);
4759 }
4760 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4761 replace_range: old_range.clone(),
4762 new_text: word.clone(),
4763 label: CodeLabel::plain(word, None),
4764 icon_path: None,
4765 documentation: None,
4766 source: CompletionSource::BufferWord {
4767 word_range,
4768 resolved: false,
4769 },
4770 insert_text_mode: Some(InsertTextMode::AS_IS),
4771 confirm: None,
4772 }));
4773
4774 let menu = if completions.is_empty() {
4775 None
4776 } else {
4777 let mut menu = CompletionsMenu::new(
4778 id,
4779 sort_completions,
4780 show_completion_documentation,
4781 ignore_completion_provider,
4782 position,
4783 buffer.clone(),
4784 completions.into(),
4785 snippet_sort_order,
4786 );
4787
4788 menu.filter(
4789 if filter_completions {
4790 query.as_deref()
4791 } else {
4792 None
4793 },
4794 cx.background_executor().clone(),
4795 )
4796 .await;
4797
4798 menu.visible().then_some(menu)
4799 };
4800
4801 editor.update_in(cx, |editor, window, cx| {
4802 match editor.context_menu.borrow().as_ref() {
4803 None => {}
4804 Some(CodeContextMenu::Completions(prev_menu)) => {
4805 if prev_menu.id > id {
4806 return;
4807 }
4808 }
4809 _ => return,
4810 }
4811
4812 if editor.focus_handle.is_focused(window) && menu.is_some() {
4813 let mut menu = menu.unwrap();
4814 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4815
4816 *editor.context_menu.borrow_mut() =
4817 Some(CodeContextMenu::Completions(menu));
4818
4819 if editor.show_edit_predictions_in_menu() {
4820 editor.update_visible_inline_completion(window, cx);
4821 } else {
4822 editor.discard_inline_completion(false, cx);
4823 }
4824
4825 cx.notify();
4826 } else if editor.completion_tasks.len() <= 1 {
4827 // If there are no more completion tasks and the last menu was
4828 // empty, we should hide it.
4829 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4830 // If it was already hidden and we don't show inline
4831 // completions in the menu, we should also show the
4832 // inline-completion when available.
4833 if was_hidden && editor.show_edit_predictions_in_menu() {
4834 editor.update_visible_inline_completion(window, cx);
4835 }
4836 }
4837 })?;
4838
4839 anyhow::Ok(())
4840 }
4841 .log_err()
4842 .await
4843 });
4844
4845 self.completion_tasks.push((id, task));
4846 }
4847
4848 #[cfg(feature = "test-support")]
4849 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4850 let menu = self.context_menu.borrow();
4851 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4852 let completions = menu.completions.borrow();
4853 Some(completions.to_vec())
4854 } else {
4855 None
4856 }
4857 }
4858
4859 pub fn confirm_completion(
4860 &mut self,
4861 action: &ConfirmCompletion,
4862 window: &mut Window,
4863 cx: &mut Context<Self>,
4864 ) -> Option<Task<Result<()>>> {
4865 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4866 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4867 }
4868
4869 pub fn confirm_completion_insert(
4870 &mut self,
4871 _: &ConfirmCompletionInsert,
4872 window: &mut Window,
4873 cx: &mut Context<Self>,
4874 ) -> Option<Task<Result<()>>> {
4875 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4876 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4877 }
4878
4879 pub fn confirm_completion_replace(
4880 &mut self,
4881 _: &ConfirmCompletionReplace,
4882 window: &mut Window,
4883 cx: &mut Context<Self>,
4884 ) -> Option<Task<Result<()>>> {
4885 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4886 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4887 }
4888
4889 pub fn compose_completion(
4890 &mut self,
4891 action: &ComposeCompletion,
4892 window: &mut Window,
4893 cx: &mut Context<Self>,
4894 ) -> Option<Task<Result<()>>> {
4895 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4896 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4897 }
4898
4899 fn do_completion(
4900 &mut self,
4901 item_ix: Option<usize>,
4902 intent: CompletionIntent,
4903 window: &mut Window,
4904 cx: &mut Context<Editor>,
4905 ) -> Option<Task<Result<()>>> {
4906 use language::ToOffset as _;
4907
4908 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4909 else {
4910 return None;
4911 };
4912
4913 let candidate_id = {
4914 let entries = completions_menu.entries.borrow();
4915 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4916 if self.show_edit_predictions_in_menu() {
4917 self.discard_inline_completion(true, cx);
4918 }
4919 mat.candidate_id
4920 };
4921
4922 let buffer_handle = completions_menu.buffer;
4923 let completion = completions_menu
4924 .completions
4925 .borrow()
4926 .get(candidate_id)?
4927 .clone();
4928 cx.stop_propagation();
4929
4930 let snippet;
4931 let new_text;
4932 if completion.is_snippet() {
4933 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4934 new_text = snippet.as_ref().unwrap().text.clone();
4935 } else {
4936 snippet = None;
4937 new_text = completion.new_text.clone();
4938 };
4939
4940 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4941 let buffer = buffer_handle.read(cx);
4942 let snapshot = self.buffer.read(cx).snapshot(cx);
4943 let replace_range_multibuffer = {
4944 let excerpt = snapshot
4945 .excerpt_containing(self.selections.newest_anchor().range())
4946 .unwrap();
4947 let multibuffer_anchor = snapshot
4948 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4949 .unwrap()
4950 ..snapshot
4951 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4952 .unwrap();
4953 multibuffer_anchor.start.to_offset(&snapshot)
4954 ..multibuffer_anchor.end.to_offset(&snapshot)
4955 };
4956 let newest_anchor = self.selections.newest_anchor();
4957 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4958 return None;
4959 }
4960
4961 let old_text = buffer
4962 .text_for_range(replace_range.clone())
4963 .collect::<String>();
4964 let lookbehind = newest_anchor
4965 .start
4966 .text_anchor
4967 .to_offset(buffer)
4968 .saturating_sub(replace_range.start);
4969 let lookahead = replace_range
4970 .end
4971 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4972 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4973 let suffix = &old_text[lookbehind.min(old_text.len())..];
4974
4975 let selections = self.selections.all::<usize>(cx);
4976 let mut ranges = Vec::new();
4977 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4978
4979 for selection in &selections {
4980 let range = if selection.id == newest_anchor.id {
4981 replace_range_multibuffer.clone()
4982 } else {
4983 let mut range = selection.range();
4984
4985 // if prefix is present, don't duplicate it
4986 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4987 range.start = range.start.saturating_sub(lookbehind);
4988
4989 // if suffix is also present, mimic the newest cursor and replace it
4990 if selection.id != newest_anchor.id
4991 && snapshot.contains_str_at(range.end, suffix)
4992 {
4993 range.end += lookahead;
4994 }
4995 }
4996 range
4997 };
4998
4999 ranges.push(range);
5000
5001 if !self.linked_edit_ranges.is_empty() {
5002 let start_anchor = snapshot.anchor_before(selection.head());
5003 let end_anchor = snapshot.anchor_after(selection.tail());
5004 if let Some(ranges) = self
5005 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
5006 {
5007 for (buffer, edits) in ranges {
5008 linked_edits
5009 .entry(buffer.clone())
5010 .or_default()
5011 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
5012 }
5013 }
5014 }
5015 }
5016
5017 cx.emit(EditorEvent::InputHandled {
5018 utf16_range_to_replace: None,
5019 text: new_text.clone().into(),
5020 });
5021
5022 self.transact(window, cx, |this, window, cx| {
5023 if let Some(mut snippet) = snippet {
5024 snippet.text = new_text.to_string();
5025 this.insert_snippet(&ranges, snippet, window, cx).log_err();
5026 } else {
5027 this.buffer.update(cx, |buffer, cx| {
5028 let auto_indent = match completion.insert_text_mode {
5029 Some(InsertTextMode::AS_IS) => None,
5030 _ => this.autoindent_mode.clone(),
5031 };
5032 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
5033 buffer.edit(edits, auto_indent, cx);
5034 });
5035 }
5036 for (buffer, edits) in linked_edits {
5037 buffer.update(cx, |buffer, cx| {
5038 let snapshot = buffer.snapshot();
5039 let edits = edits
5040 .into_iter()
5041 .map(|(range, text)| {
5042 use text::ToPoint as TP;
5043 let end_point = TP::to_point(&range.end, &snapshot);
5044 let start_point = TP::to_point(&range.start, &snapshot);
5045 (start_point..end_point, text)
5046 })
5047 .sorted_by_key(|(range, _)| range.start);
5048 buffer.edit(edits, None, cx);
5049 })
5050 }
5051
5052 this.refresh_inline_completion(true, false, window, cx);
5053 });
5054
5055 let show_new_completions_on_confirm = completion
5056 .confirm
5057 .as_ref()
5058 .map_or(false, |confirm| confirm(intent, window, cx));
5059 if show_new_completions_on_confirm {
5060 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
5061 }
5062
5063 let provider = self.completion_provider.as_ref()?;
5064 drop(completion);
5065 let apply_edits = provider.apply_additional_edits_for_completion(
5066 buffer_handle,
5067 completions_menu.completions.clone(),
5068 candidate_id,
5069 true,
5070 cx,
5071 );
5072
5073 let editor_settings = EditorSettings::get_global(cx);
5074 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
5075 // After the code completion is finished, users often want to know what signatures are needed.
5076 // so we should automatically call signature_help
5077 self.show_signature_help(&ShowSignatureHelp, window, cx);
5078 }
5079
5080 Some(cx.foreground_executor().spawn(async move {
5081 apply_edits.await?;
5082 Ok(())
5083 }))
5084 }
5085
5086 pub fn toggle_code_actions(
5087 &mut self,
5088 action: &ToggleCodeActions,
5089 window: &mut Window,
5090 cx: &mut Context<Self>,
5091 ) {
5092 let mut context_menu = self.context_menu.borrow_mut();
5093 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
5094 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
5095 // Toggle if we're selecting the same one
5096 *context_menu = None;
5097 cx.notify();
5098 return;
5099 } else {
5100 // Otherwise, clear it and start a new one
5101 *context_menu = None;
5102 cx.notify();
5103 }
5104 }
5105 drop(context_menu);
5106 let snapshot = self.snapshot(window, cx);
5107 let deployed_from_indicator = action.deployed_from_indicator;
5108 let mut task = self.code_actions_task.take();
5109 let action = action.clone();
5110 cx.spawn_in(window, async move |editor, cx| {
5111 while let Some(prev_task) = task {
5112 prev_task.await.log_err();
5113 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
5114 }
5115
5116 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
5117 if editor.focus_handle.is_focused(window) {
5118 let multibuffer_point = action
5119 .deployed_from_indicator
5120 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
5121 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
5122 let (buffer, buffer_row) = snapshot
5123 .buffer_snapshot
5124 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
5125 .and_then(|(buffer_snapshot, range)| {
5126 editor
5127 .buffer
5128 .read(cx)
5129 .buffer(buffer_snapshot.remote_id())
5130 .map(|buffer| (buffer, range.start.row))
5131 })?;
5132 let (_, code_actions) = editor
5133 .available_code_actions
5134 .clone()
5135 .and_then(|(location, code_actions)| {
5136 let snapshot = location.buffer.read(cx).snapshot();
5137 let point_range = location.range.to_point(&snapshot);
5138 let point_range = point_range.start.row..=point_range.end.row;
5139 if point_range.contains(&buffer_row) {
5140 Some((location, code_actions))
5141 } else {
5142 None
5143 }
5144 })
5145 .unzip();
5146 let buffer_id = buffer.read(cx).remote_id();
5147 let tasks = editor
5148 .tasks
5149 .get(&(buffer_id, buffer_row))
5150 .map(|t| Arc::new(t.to_owned()));
5151 if tasks.is_none() && code_actions.is_none() {
5152 return None;
5153 }
5154
5155 editor.completion_tasks.clear();
5156 editor.discard_inline_completion(false, cx);
5157 let task_context =
5158 tasks
5159 .as_ref()
5160 .zip(editor.project.clone())
5161 .map(|(tasks, project)| {
5162 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5163 });
5164
5165 let debugger_flag = cx.has_flag::<DebuggerFeatureFlag>();
5166
5167 Some(cx.spawn_in(window, async move |editor, cx| {
5168 let task_context = match task_context {
5169 Some(task_context) => task_context.await,
5170 None => None,
5171 };
5172 let resolved_tasks =
5173 tasks
5174 .zip(task_context)
5175 .map(|(tasks, task_context)| ResolvedTasks {
5176 templates: tasks.resolve(&task_context).collect(),
5177 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5178 multibuffer_point.row,
5179 tasks.column,
5180 )),
5181 });
5182 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
5183 tasks
5184 .templates
5185 .iter()
5186 .filter(|task| {
5187 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
5188 debugger_flag
5189 } else {
5190 true
5191 }
5192 })
5193 .count()
5194 == 1
5195 }) && code_actions
5196 .as_ref()
5197 .map_or(true, |actions| actions.is_empty());
5198 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5199 *editor.context_menu.borrow_mut() =
5200 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5201 buffer,
5202 actions: CodeActionContents::new(
5203 resolved_tasks,
5204 code_actions,
5205 cx,
5206 ),
5207 selected_item: Default::default(),
5208 scroll_handle: UniformListScrollHandle::default(),
5209 deployed_from_indicator,
5210 }));
5211 if spawn_straight_away {
5212 if let Some(task) = editor.confirm_code_action(
5213 &ConfirmCodeAction { item_ix: Some(0) },
5214 window,
5215 cx,
5216 ) {
5217 cx.notify();
5218 return task;
5219 }
5220 }
5221 cx.notify();
5222 Task::ready(Ok(()))
5223 }) {
5224 task.await
5225 } else {
5226 Ok(())
5227 }
5228 }))
5229 } else {
5230 Some(Task::ready(Ok(())))
5231 }
5232 })?;
5233 if let Some(task) = spawned_test_task {
5234 task.await?;
5235 }
5236
5237 Ok::<_, anyhow::Error>(())
5238 })
5239 .detach_and_log_err(cx);
5240 }
5241
5242 pub fn confirm_code_action(
5243 &mut self,
5244 action: &ConfirmCodeAction,
5245 window: &mut Window,
5246 cx: &mut Context<Self>,
5247 ) -> Option<Task<Result<()>>> {
5248 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5249
5250 let actions_menu =
5251 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5252 menu
5253 } else {
5254 return None;
5255 };
5256
5257 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5258 let action = actions_menu.actions.get(action_ix)?;
5259 let title = action.label();
5260 let buffer = actions_menu.buffer;
5261 let workspace = self.workspace()?;
5262
5263 match action {
5264 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5265 match resolved_task.task_type() {
5266 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5267 workspace.schedule_resolved_task(
5268 task_source_kind,
5269 resolved_task,
5270 false,
5271 window,
5272 cx,
5273 );
5274
5275 Some(Task::ready(Ok(())))
5276 }),
5277 task::TaskType::Debug(_) => {
5278 workspace.update(cx, |workspace, cx| {
5279 workspace.schedule_debug_task(resolved_task, window, cx);
5280 });
5281 Some(Task::ready(Ok(())))
5282 }
5283 }
5284 }
5285 CodeActionsItem::CodeAction {
5286 excerpt_id,
5287 action,
5288 provider,
5289 } => {
5290 let apply_code_action =
5291 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5292 let workspace = workspace.downgrade();
5293 Some(cx.spawn_in(window, async move |editor, cx| {
5294 let project_transaction = apply_code_action.await?;
5295 Self::open_project_transaction(
5296 &editor,
5297 workspace,
5298 project_transaction,
5299 title,
5300 cx,
5301 )
5302 .await
5303 }))
5304 }
5305 }
5306 }
5307
5308 pub async fn open_project_transaction(
5309 this: &WeakEntity<Editor>,
5310 workspace: WeakEntity<Workspace>,
5311 transaction: ProjectTransaction,
5312 title: String,
5313 cx: &mut AsyncWindowContext,
5314 ) -> Result<()> {
5315 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5316 cx.update(|_, cx| {
5317 entries.sort_unstable_by_key(|(buffer, _)| {
5318 buffer.read(cx).file().map(|f| f.path().clone())
5319 });
5320 })?;
5321
5322 // If the project transaction's edits are all contained within this editor, then
5323 // avoid opening a new editor to display them.
5324
5325 if let Some((buffer, transaction)) = entries.first() {
5326 if entries.len() == 1 {
5327 let excerpt = this.update(cx, |editor, cx| {
5328 editor
5329 .buffer()
5330 .read(cx)
5331 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5332 })?;
5333 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5334 if excerpted_buffer == *buffer {
5335 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5336 let excerpt_range = excerpt_range.to_offset(buffer);
5337 buffer
5338 .edited_ranges_for_transaction::<usize>(transaction)
5339 .all(|range| {
5340 excerpt_range.start <= range.start
5341 && excerpt_range.end >= range.end
5342 })
5343 })?;
5344
5345 if all_edits_within_excerpt {
5346 return Ok(());
5347 }
5348 }
5349 }
5350 }
5351 } else {
5352 return Ok(());
5353 }
5354
5355 let mut ranges_to_highlight = Vec::new();
5356 let excerpt_buffer = cx.new(|cx| {
5357 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5358 for (buffer_handle, transaction) in &entries {
5359 let edited_ranges = buffer_handle
5360 .read(cx)
5361 .edited_ranges_for_transaction::<Point>(transaction)
5362 .collect::<Vec<_>>();
5363 let (ranges, _) = multibuffer.set_excerpts_for_path(
5364 PathKey::for_buffer(buffer_handle, cx),
5365 buffer_handle.clone(),
5366 edited_ranges,
5367 DEFAULT_MULTIBUFFER_CONTEXT,
5368 cx,
5369 );
5370
5371 ranges_to_highlight.extend(ranges);
5372 }
5373 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5374 multibuffer
5375 })?;
5376
5377 workspace.update_in(cx, |workspace, window, cx| {
5378 let project = workspace.project().clone();
5379 let editor =
5380 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5381 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5382 editor.update(cx, |editor, cx| {
5383 editor.highlight_background::<Self>(
5384 &ranges_to_highlight,
5385 |theme| theme.editor_highlighted_line_background,
5386 cx,
5387 );
5388 });
5389 })?;
5390
5391 Ok(())
5392 }
5393
5394 pub fn clear_code_action_providers(&mut self) {
5395 self.code_action_providers.clear();
5396 self.available_code_actions.take();
5397 }
5398
5399 pub fn add_code_action_provider(
5400 &mut self,
5401 provider: Rc<dyn CodeActionProvider>,
5402 window: &mut Window,
5403 cx: &mut Context<Self>,
5404 ) {
5405 if self
5406 .code_action_providers
5407 .iter()
5408 .any(|existing_provider| existing_provider.id() == provider.id())
5409 {
5410 return;
5411 }
5412
5413 self.code_action_providers.push(provider);
5414 self.refresh_code_actions(window, cx);
5415 }
5416
5417 pub fn remove_code_action_provider(
5418 &mut self,
5419 id: Arc<str>,
5420 window: &mut Window,
5421 cx: &mut Context<Self>,
5422 ) {
5423 self.code_action_providers
5424 .retain(|provider| provider.id() != id);
5425 self.refresh_code_actions(window, cx);
5426 }
5427
5428 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5429 let newest_selection = self.selections.newest_anchor().clone();
5430 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5431 let buffer = self.buffer.read(cx);
5432 if newest_selection.head().diff_base_anchor.is_some() {
5433 return None;
5434 }
5435 let (start_buffer, start) =
5436 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5437 let (end_buffer, end) =
5438 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5439 if start_buffer != end_buffer {
5440 return None;
5441 }
5442
5443 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5444 cx.background_executor()
5445 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5446 .await;
5447
5448 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5449 let providers = this.code_action_providers.clone();
5450 let tasks = this
5451 .code_action_providers
5452 .iter()
5453 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5454 .collect::<Vec<_>>();
5455 (providers, tasks)
5456 })?;
5457
5458 let mut actions = Vec::new();
5459 for (provider, provider_actions) in
5460 providers.into_iter().zip(future::join_all(tasks).await)
5461 {
5462 if let Some(provider_actions) = provider_actions.log_err() {
5463 actions.extend(provider_actions.into_iter().map(|action| {
5464 AvailableCodeAction {
5465 excerpt_id: newest_selection.start.excerpt_id,
5466 action,
5467 provider: provider.clone(),
5468 }
5469 }));
5470 }
5471 }
5472
5473 this.update(cx, |this, cx| {
5474 this.available_code_actions = if actions.is_empty() {
5475 None
5476 } else {
5477 Some((
5478 Location {
5479 buffer: start_buffer,
5480 range: start..end,
5481 },
5482 actions.into(),
5483 ))
5484 };
5485 cx.notify();
5486 })
5487 }));
5488 None
5489 }
5490
5491 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5492 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5493 self.show_git_blame_inline = false;
5494
5495 self.show_git_blame_inline_delay_task =
5496 Some(cx.spawn_in(window, async move |this, cx| {
5497 cx.background_executor().timer(delay).await;
5498
5499 this.update(cx, |this, cx| {
5500 this.show_git_blame_inline = true;
5501 cx.notify();
5502 })
5503 .log_err();
5504 }));
5505 }
5506 }
5507
5508 fn show_blame_popover(
5509 &mut self,
5510 blame_entry: &BlameEntry,
5511 position: gpui::Point<Pixels>,
5512 cx: &mut Context<Self>,
5513 ) {
5514 if let Some(state) = &mut self.inline_blame_popover {
5515 state.hide_task.take();
5516 cx.notify();
5517 } else {
5518 let delay = EditorSettings::get_global(cx).hover_popover_delay;
5519 let show_task = cx.spawn(async move |editor, cx| {
5520 cx.background_executor()
5521 .timer(std::time::Duration::from_millis(delay))
5522 .await;
5523 editor
5524 .update(cx, |editor, cx| {
5525 if let Some(state) = &mut editor.inline_blame_popover {
5526 state.show_task = None;
5527 cx.notify();
5528 }
5529 })
5530 .ok();
5531 });
5532 let Some(blame) = self.blame.as_ref() else {
5533 return;
5534 };
5535 let blame = blame.read(cx);
5536 let details = blame.details_for_entry(&blame_entry);
5537 let markdown = cx.new(|cx| {
5538 Markdown::new(
5539 details
5540 .as_ref()
5541 .map(|message| message.message.clone())
5542 .unwrap_or_default(),
5543 None,
5544 None,
5545 cx,
5546 )
5547 });
5548 self.inline_blame_popover = Some(InlineBlamePopover {
5549 position,
5550 show_task: Some(show_task),
5551 hide_task: None,
5552 popover_bounds: None,
5553 popover_state: InlineBlamePopoverState {
5554 scroll_handle: ScrollHandle::new(),
5555 commit_message: details,
5556 markdown,
5557 },
5558 });
5559 }
5560 }
5561
5562 fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
5563 if let Some(state) = &mut self.inline_blame_popover {
5564 if state.show_task.is_some() {
5565 self.inline_blame_popover.take();
5566 cx.notify();
5567 } else {
5568 let hide_task = cx.spawn(async move |editor, cx| {
5569 cx.background_executor()
5570 .timer(std::time::Duration::from_millis(100))
5571 .await;
5572 editor
5573 .update(cx, |editor, cx| {
5574 editor.inline_blame_popover.take();
5575 cx.notify();
5576 })
5577 .ok();
5578 });
5579 state.hide_task = Some(hide_task);
5580 }
5581 }
5582 }
5583
5584 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5585 if self.pending_rename.is_some() {
5586 return None;
5587 }
5588
5589 let provider = self.semantics_provider.clone()?;
5590 let buffer = self.buffer.read(cx);
5591 let newest_selection = self.selections.newest_anchor().clone();
5592 let cursor_position = newest_selection.head();
5593 let (cursor_buffer, cursor_buffer_position) =
5594 buffer.text_anchor_for_position(cursor_position, cx)?;
5595 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5596 if cursor_buffer != tail_buffer {
5597 return None;
5598 }
5599 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5600 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5601 cx.background_executor()
5602 .timer(Duration::from_millis(debounce))
5603 .await;
5604
5605 let highlights = if let Some(highlights) = cx
5606 .update(|cx| {
5607 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5608 })
5609 .ok()
5610 .flatten()
5611 {
5612 highlights.await.log_err()
5613 } else {
5614 None
5615 };
5616
5617 if let Some(highlights) = highlights {
5618 this.update(cx, |this, cx| {
5619 if this.pending_rename.is_some() {
5620 return;
5621 }
5622
5623 let buffer_id = cursor_position.buffer_id;
5624 let buffer = this.buffer.read(cx);
5625 if !buffer
5626 .text_anchor_for_position(cursor_position, cx)
5627 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5628 {
5629 return;
5630 }
5631
5632 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5633 let mut write_ranges = Vec::new();
5634 let mut read_ranges = Vec::new();
5635 for highlight in highlights {
5636 for (excerpt_id, excerpt_range) in
5637 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5638 {
5639 let start = highlight
5640 .range
5641 .start
5642 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5643 let end = highlight
5644 .range
5645 .end
5646 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5647 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5648 continue;
5649 }
5650
5651 let range = Anchor {
5652 buffer_id,
5653 excerpt_id,
5654 text_anchor: start,
5655 diff_base_anchor: None,
5656 }..Anchor {
5657 buffer_id,
5658 excerpt_id,
5659 text_anchor: end,
5660 diff_base_anchor: None,
5661 };
5662 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5663 write_ranges.push(range);
5664 } else {
5665 read_ranges.push(range);
5666 }
5667 }
5668 }
5669
5670 this.highlight_background::<DocumentHighlightRead>(
5671 &read_ranges,
5672 |theme| theme.editor_document_highlight_read_background,
5673 cx,
5674 );
5675 this.highlight_background::<DocumentHighlightWrite>(
5676 &write_ranges,
5677 |theme| theme.editor_document_highlight_write_background,
5678 cx,
5679 );
5680 cx.notify();
5681 })
5682 .log_err();
5683 }
5684 }));
5685 None
5686 }
5687
5688 fn prepare_highlight_query_from_selection(
5689 &mut self,
5690 cx: &mut Context<Editor>,
5691 ) -> Option<(String, Range<Anchor>)> {
5692 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5693 return None;
5694 }
5695 if !EditorSettings::get_global(cx).selection_highlight {
5696 return None;
5697 }
5698 if self.selections.count() != 1 || self.selections.line_mode {
5699 return None;
5700 }
5701 let selection = self.selections.newest::<Point>(cx);
5702 if selection.is_empty() || selection.start.row != selection.end.row {
5703 return None;
5704 }
5705 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5706 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5707 let query = multi_buffer_snapshot
5708 .text_for_range(selection_anchor_range.clone())
5709 .collect::<String>();
5710 if query.trim().is_empty() {
5711 return None;
5712 }
5713 Some((query, selection_anchor_range))
5714 }
5715
5716 fn update_selection_occurrence_highlights(
5717 &mut self,
5718 query_text: String,
5719 query_range: Range<Anchor>,
5720 multi_buffer_range_to_query: Range<Point>,
5721 use_debounce: bool,
5722 window: &mut Window,
5723 cx: &mut Context<Editor>,
5724 ) -> Task<()> {
5725 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5726 cx.spawn_in(window, async move |editor, cx| {
5727 if use_debounce {
5728 cx.background_executor()
5729 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5730 .await;
5731 }
5732 let match_task = cx.background_spawn(async move {
5733 let buffer_ranges = multi_buffer_snapshot
5734 .range_to_buffer_ranges(multi_buffer_range_to_query)
5735 .into_iter()
5736 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5737 let mut match_ranges = Vec::new();
5738 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5739 match_ranges.extend(
5740 project::search::SearchQuery::text(
5741 query_text.clone(),
5742 false,
5743 false,
5744 false,
5745 Default::default(),
5746 Default::default(),
5747 false,
5748 None,
5749 )
5750 .unwrap()
5751 .search(&buffer_snapshot, Some(search_range.clone()))
5752 .await
5753 .into_iter()
5754 .filter_map(|match_range| {
5755 let match_start = buffer_snapshot
5756 .anchor_after(search_range.start + match_range.start);
5757 let match_end =
5758 buffer_snapshot.anchor_before(search_range.start + match_range.end);
5759 let match_anchor_range = Anchor::range_in_buffer(
5760 excerpt_id,
5761 buffer_snapshot.remote_id(),
5762 match_start..match_end,
5763 );
5764 (match_anchor_range != query_range).then_some(match_anchor_range)
5765 }),
5766 );
5767 }
5768 match_ranges
5769 });
5770 let match_ranges = match_task.await;
5771 editor
5772 .update_in(cx, |editor, _, cx| {
5773 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5774 if !match_ranges.is_empty() {
5775 editor.highlight_background::<SelectedTextHighlight>(
5776 &match_ranges,
5777 |theme| theme.editor_document_highlight_bracket_background,
5778 cx,
5779 )
5780 }
5781 })
5782 .log_err();
5783 })
5784 }
5785
5786 fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
5787 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5788 else {
5789 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5790 self.quick_selection_highlight_task.take();
5791 self.debounced_selection_highlight_task.take();
5792 return;
5793 };
5794 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5795 if self
5796 .quick_selection_highlight_task
5797 .as_ref()
5798 .map_or(true, |(prev_anchor_range, _)| {
5799 prev_anchor_range != &query_range
5800 })
5801 {
5802 let multi_buffer_visible_start = self
5803 .scroll_manager
5804 .anchor()
5805 .anchor
5806 .to_point(&multi_buffer_snapshot);
5807 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5808 multi_buffer_visible_start
5809 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5810 Bias::Left,
5811 );
5812 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5813 self.quick_selection_highlight_task = Some((
5814 query_range.clone(),
5815 self.update_selection_occurrence_highlights(
5816 query_text.clone(),
5817 query_range.clone(),
5818 multi_buffer_visible_range,
5819 false,
5820 window,
5821 cx,
5822 ),
5823 ));
5824 }
5825 if self
5826 .debounced_selection_highlight_task
5827 .as_ref()
5828 .map_or(true, |(prev_anchor_range, _)| {
5829 prev_anchor_range != &query_range
5830 })
5831 {
5832 let multi_buffer_start = multi_buffer_snapshot
5833 .anchor_before(0)
5834 .to_point(&multi_buffer_snapshot);
5835 let multi_buffer_end = multi_buffer_snapshot
5836 .anchor_after(multi_buffer_snapshot.len())
5837 .to_point(&multi_buffer_snapshot);
5838 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5839 self.debounced_selection_highlight_task = Some((
5840 query_range.clone(),
5841 self.update_selection_occurrence_highlights(
5842 query_text,
5843 query_range,
5844 multi_buffer_full_range,
5845 true,
5846 window,
5847 cx,
5848 ),
5849 ));
5850 }
5851 }
5852
5853 pub fn refresh_inline_completion(
5854 &mut self,
5855 debounce: bool,
5856 user_requested: bool,
5857 window: &mut Window,
5858 cx: &mut Context<Self>,
5859 ) -> Option<()> {
5860 let provider = self.edit_prediction_provider()?;
5861 let cursor = self.selections.newest_anchor().head();
5862 let (buffer, cursor_buffer_position) =
5863 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5864
5865 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5866 self.discard_inline_completion(false, cx);
5867 return None;
5868 }
5869
5870 if !user_requested
5871 && (!self.should_show_edit_predictions()
5872 || !self.is_focused(window)
5873 || buffer.read(cx).is_empty())
5874 {
5875 self.discard_inline_completion(false, cx);
5876 return None;
5877 }
5878
5879 self.update_visible_inline_completion(window, cx);
5880 provider.refresh(
5881 self.project.clone(),
5882 buffer,
5883 cursor_buffer_position,
5884 debounce,
5885 cx,
5886 );
5887 Some(())
5888 }
5889
5890 fn show_edit_predictions_in_menu(&self) -> bool {
5891 match self.edit_prediction_settings {
5892 EditPredictionSettings::Disabled => false,
5893 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5894 }
5895 }
5896
5897 pub fn edit_predictions_enabled(&self) -> bool {
5898 match self.edit_prediction_settings {
5899 EditPredictionSettings::Disabled => false,
5900 EditPredictionSettings::Enabled { .. } => true,
5901 }
5902 }
5903
5904 fn edit_prediction_requires_modifier(&self) -> bool {
5905 match self.edit_prediction_settings {
5906 EditPredictionSettings::Disabled => false,
5907 EditPredictionSettings::Enabled {
5908 preview_requires_modifier,
5909 ..
5910 } => preview_requires_modifier,
5911 }
5912 }
5913
5914 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5915 if self.edit_prediction_provider.is_none() {
5916 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5917 } else {
5918 let selection = self.selections.newest_anchor();
5919 let cursor = selection.head();
5920
5921 if let Some((buffer, cursor_buffer_position)) =
5922 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5923 {
5924 self.edit_prediction_settings =
5925 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5926 }
5927 }
5928 }
5929
5930 fn edit_prediction_settings_at_position(
5931 &self,
5932 buffer: &Entity<Buffer>,
5933 buffer_position: language::Anchor,
5934 cx: &App,
5935 ) -> EditPredictionSettings {
5936 if !self.mode.is_full()
5937 || !self.show_inline_completions_override.unwrap_or(true)
5938 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5939 {
5940 return EditPredictionSettings::Disabled;
5941 }
5942
5943 let buffer = buffer.read(cx);
5944
5945 let file = buffer.file();
5946
5947 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5948 return EditPredictionSettings::Disabled;
5949 };
5950
5951 let by_provider = matches!(
5952 self.menu_inline_completions_policy,
5953 MenuInlineCompletionsPolicy::ByProvider
5954 );
5955
5956 let show_in_menu = by_provider
5957 && self
5958 .edit_prediction_provider
5959 .as_ref()
5960 .map_or(false, |provider| {
5961 provider.provider.show_completions_in_menu()
5962 });
5963
5964 let preview_requires_modifier =
5965 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5966
5967 EditPredictionSettings::Enabled {
5968 show_in_menu,
5969 preview_requires_modifier,
5970 }
5971 }
5972
5973 fn should_show_edit_predictions(&self) -> bool {
5974 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5975 }
5976
5977 pub fn edit_prediction_preview_is_active(&self) -> bool {
5978 matches!(
5979 self.edit_prediction_preview,
5980 EditPredictionPreview::Active { .. }
5981 )
5982 }
5983
5984 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5985 let cursor = self.selections.newest_anchor().head();
5986 if let Some((buffer, cursor_position)) =
5987 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5988 {
5989 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5990 } else {
5991 false
5992 }
5993 }
5994
5995 fn edit_predictions_enabled_in_buffer(
5996 &self,
5997 buffer: &Entity<Buffer>,
5998 buffer_position: language::Anchor,
5999 cx: &App,
6000 ) -> bool {
6001 maybe!({
6002 if self.read_only(cx) {
6003 return Some(false);
6004 }
6005 let provider = self.edit_prediction_provider()?;
6006 if !provider.is_enabled(&buffer, buffer_position, cx) {
6007 return Some(false);
6008 }
6009 let buffer = buffer.read(cx);
6010 let Some(file) = buffer.file() else {
6011 return Some(true);
6012 };
6013 let settings = all_language_settings(Some(file), cx);
6014 Some(settings.edit_predictions_enabled_for_file(file, cx))
6015 })
6016 .unwrap_or(false)
6017 }
6018
6019 fn cycle_inline_completion(
6020 &mut self,
6021 direction: Direction,
6022 window: &mut Window,
6023 cx: &mut Context<Self>,
6024 ) -> Option<()> {
6025 let provider = self.edit_prediction_provider()?;
6026 let cursor = self.selections.newest_anchor().head();
6027 let (buffer, cursor_buffer_position) =
6028 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6029 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
6030 return None;
6031 }
6032
6033 provider.cycle(buffer, cursor_buffer_position, direction, cx);
6034 self.update_visible_inline_completion(window, cx);
6035
6036 Some(())
6037 }
6038
6039 pub fn show_inline_completion(
6040 &mut self,
6041 _: &ShowEditPrediction,
6042 window: &mut Window,
6043 cx: &mut Context<Self>,
6044 ) {
6045 if !self.has_active_inline_completion() {
6046 self.refresh_inline_completion(false, true, window, cx);
6047 return;
6048 }
6049
6050 self.update_visible_inline_completion(window, cx);
6051 }
6052
6053 pub fn display_cursor_names(
6054 &mut self,
6055 _: &DisplayCursorNames,
6056 window: &mut Window,
6057 cx: &mut Context<Self>,
6058 ) {
6059 self.show_cursor_names(window, cx);
6060 }
6061
6062 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6063 self.show_cursor_names = true;
6064 cx.notify();
6065 cx.spawn_in(window, async move |this, cx| {
6066 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
6067 this.update(cx, |this, cx| {
6068 this.show_cursor_names = false;
6069 cx.notify()
6070 })
6071 .ok()
6072 })
6073 .detach();
6074 }
6075
6076 pub fn next_edit_prediction(
6077 &mut self,
6078 _: &NextEditPrediction,
6079 window: &mut Window,
6080 cx: &mut Context<Self>,
6081 ) {
6082 if self.has_active_inline_completion() {
6083 self.cycle_inline_completion(Direction::Next, window, cx);
6084 } else {
6085 let is_copilot_disabled = self
6086 .refresh_inline_completion(false, true, window, cx)
6087 .is_none();
6088 if is_copilot_disabled {
6089 cx.propagate();
6090 }
6091 }
6092 }
6093
6094 pub fn previous_edit_prediction(
6095 &mut self,
6096 _: &PreviousEditPrediction,
6097 window: &mut Window,
6098 cx: &mut Context<Self>,
6099 ) {
6100 if self.has_active_inline_completion() {
6101 self.cycle_inline_completion(Direction::Prev, window, cx);
6102 } else {
6103 let is_copilot_disabled = self
6104 .refresh_inline_completion(false, true, window, cx)
6105 .is_none();
6106 if is_copilot_disabled {
6107 cx.propagate();
6108 }
6109 }
6110 }
6111
6112 pub fn accept_edit_prediction(
6113 &mut self,
6114 _: &AcceptEditPrediction,
6115 window: &mut Window,
6116 cx: &mut Context<Self>,
6117 ) {
6118 if self.show_edit_predictions_in_menu() {
6119 self.hide_context_menu(window, cx);
6120 }
6121
6122 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6123 return;
6124 };
6125
6126 self.report_inline_completion_event(
6127 active_inline_completion.completion_id.clone(),
6128 true,
6129 cx,
6130 );
6131
6132 match &active_inline_completion.completion {
6133 InlineCompletion::Move { target, .. } => {
6134 let target = *target;
6135
6136 if let Some(position_map) = &self.last_position_map {
6137 if position_map
6138 .visible_row_range
6139 .contains(&target.to_display_point(&position_map.snapshot).row())
6140 || !self.edit_prediction_requires_modifier()
6141 {
6142 self.unfold_ranges(&[target..target], true, false, cx);
6143 // Note that this is also done in vim's handler of the Tab action.
6144 self.change_selections(
6145 Some(Autoscroll::newest()),
6146 window,
6147 cx,
6148 |selections| {
6149 selections.select_anchor_ranges([target..target]);
6150 },
6151 );
6152 self.clear_row_highlights::<EditPredictionPreview>();
6153
6154 self.edit_prediction_preview
6155 .set_previous_scroll_position(None);
6156 } else {
6157 self.edit_prediction_preview
6158 .set_previous_scroll_position(Some(
6159 position_map.snapshot.scroll_anchor,
6160 ));
6161
6162 self.highlight_rows::<EditPredictionPreview>(
6163 target..target,
6164 cx.theme().colors().editor_highlighted_line_background,
6165 RowHighlightOptions {
6166 autoscroll: true,
6167 ..Default::default()
6168 },
6169 cx,
6170 );
6171 self.request_autoscroll(Autoscroll::fit(), cx);
6172 }
6173 }
6174 }
6175 InlineCompletion::Edit { edits, .. } => {
6176 if let Some(provider) = self.edit_prediction_provider() {
6177 provider.accept(cx);
6178 }
6179
6180 let snapshot = self.buffer.read(cx).snapshot(cx);
6181 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
6182
6183 self.buffer.update(cx, |buffer, cx| {
6184 buffer.edit(edits.iter().cloned(), None, cx)
6185 });
6186
6187 self.change_selections(None, window, cx, |s| {
6188 s.select_anchor_ranges([last_edit_end..last_edit_end])
6189 });
6190
6191 self.update_visible_inline_completion(window, cx);
6192 if self.active_inline_completion.is_none() {
6193 self.refresh_inline_completion(true, true, window, cx);
6194 }
6195
6196 cx.notify();
6197 }
6198 }
6199
6200 self.edit_prediction_requires_modifier_in_indent_conflict = false;
6201 }
6202
6203 pub fn accept_partial_inline_completion(
6204 &mut self,
6205 _: &AcceptPartialEditPrediction,
6206 window: &mut Window,
6207 cx: &mut Context<Self>,
6208 ) {
6209 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6210 return;
6211 };
6212 if self.selections.count() != 1 {
6213 return;
6214 }
6215
6216 self.report_inline_completion_event(
6217 active_inline_completion.completion_id.clone(),
6218 true,
6219 cx,
6220 );
6221
6222 match &active_inline_completion.completion {
6223 InlineCompletion::Move { target, .. } => {
6224 let target = *target;
6225 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6226 selections.select_anchor_ranges([target..target]);
6227 });
6228 }
6229 InlineCompletion::Edit { edits, .. } => {
6230 // Find an insertion that starts at the cursor position.
6231 let snapshot = self.buffer.read(cx).snapshot(cx);
6232 let cursor_offset = self.selections.newest::<usize>(cx).head();
6233 let insertion = edits.iter().find_map(|(range, text)| {
6234 let range = range.to_offset(&snapshot);
6235 if range.is_empty() && range.start == cursor_offset {
6236 Some(text)
6237 } else {
6238 None
6239 }
6240 });
6241
6242 if let Some(text) = insertion {
6243 let mut partial_completion = text
6244 .chars()
6245 .by_ref()
6246 .take_while(|c| c.is_alphabetic())
6247 .collect::<String>();
6248 if partial_completion.is_empty() {
6249 partial_completion = text
6250 .chars()
6251 .by_ref()
6252 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6253 .collect::<String>();
6254 }
6255
6256 cx.emit(EditorEvent::InputHandled {
6257 utf16_range_to_replace: None,
6258 text: partial_completion.clone().into(),
6259 });
6260
6261 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6262
6263 self.refresh_inline_completion(true, true, window, cx);
6264 cx.notify();
6265 } else {
6266 self.accept_edit_prediction(&Default::default(), window, cx);
6267 }
6268 }
6269 }
6270 }
6271
6272 fn discard_inline_completion(
6273 &mut self,
6274 should_report_inline_completion_event: bool,
6275 cx: &mut Context<Self>,
6276 ) -> bool {
6277 if should_report_inline_completion_event {
6278 let completion_id = self
6279 .active_inline_completion
6280 .as_ref()
6281 .and_then(|active_completion| active_completion.completion_id.clone());
6282
6283 self.report_inline_completion_event(completion_id, false, cx);
6284 }
6285
6286 if let Some(provider) = self.edit_prediction_provider() {
6287 provider.discard(cx);
6288 }
6289
6290 self.take_active_inline_completion(cx)
6291 }
6292
6293 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6294 let Some(provider) = self.edit_prediction_provider() else {
6295 return;
6296 };
6297
6298 let Some((_, buffer, _)) = self
6299 .buffer
6300 .read(cx)
6301 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6302 else {
6303 return;
6304 };
6305
6306 let extension = buffer
6307 .read(cx)
6308 .file()
6309 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6310
6311 let event_type = match accepted {
6312 true => "Edit Prediction Accepted",
6313 false => "Edit Prediction Discarded",
6314 };
6315 telemetry::event!(
6316 event_type,
6317 provider = provider.name(),
6318 prediction_id = id,
6319 suggestion_accepted = accepted,
6320 file_extension = extension,
6321 );
6322 }
6323
6324 pub fn has_active_inline_completion(&self) -> bool {
6325 self.active_inline_completion.is_some()
6326 }
6327
6328 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6329 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6330 return false;
6331 };
6332
6333 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6334 self.clear_highlights::<InlineCompletionHighlight>(cx);
6335 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6336 true
6337 }
6338
6339 /// Returns true when we're displaying the edit prediction popover below the cursor
6340 /// like we are not previewing and the LSP autocomplete menu is visible
6341 /// or we are in `when_holding_modifier` mode.
6342 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6343 if self.edit_prediction_preview_is_active()
6344 || !self.show_edit_predictions_in_menu()
6345 || !self.edit_predictions_enabled()
6346 {
6347 return false;
6348 }
6349
6350 if self.has_visible_completions_menu() {
6351 return true;
6352 }
6353
6354 has_completion && self.edit_prediction_requires_modifier()
6355 }
6356
6357 fn handle_modifiers_changed(
6358 &mut self,
6359 modifiers: Modifiers,
6360 position_map: &PositionMap,
6361 window: &mut Window,
6362 cx: &mut Context<Self>,
6363 ) {
6364 if self.show_edit_predictions_in_menu() {
6365 self.update_edit_prediction_preview(&modifiers, window, cx);
6366 }
6367
6368 self.update_selection_mode(&modifiers, position_map, window, cx);
6369
6370 let mouse_position = window.mouse_position();
6371 if !position_map.text_hitbox.is_hovered(window) {
6372 return;
6373 }
6374
6375 self.update_hovered_link(
6376 position_map.point_for_position(mouse_position),
6377 &position_map.snapshot,
6378 modifiers,
6379 window,
6380 cx,
6381 )
6382 }
6383
6384 fn update_selection_mode(
6385 &mut self,
6386 modifiers: &Modifiers,
6387 position_map: &PositionMap,
6388 window: &mut Window,
6389 cx: &mut Context<Self>,
6390 ) {
6391 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6392 return;
6393 }
6394
6395 let mouse_position = window.mouse_position();
6396 let point_for_position = position_map.point_for_position(mouse_position);
6397 let position = point_for_position.previous_valid;
6398
6399 self.select(
6400 SelectPhase::BeginColumnar {
6401 position,
6402 reset: false,
6403 goal_column: point_for_position.exact_unclipped.column(),
6404 },
6405 window,
6406 cx,
6407 );
6408 }
6409
6410 fn update_edit_prediction_preview(
6411 &mut self,
6412 modifiers: &Modifiers,
6413 window: &mut Window,
6414 cx: &mut Context<Self>,
6415 ) {
6416 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6417 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6418 return;
6419 };
6420
6421 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6422 if matches!(
6423 self.edit_prediction_preview,
6424 EditPredictionPreview::Inactive { .. }
6425 ) {
6426 self.edit_prediction_preview = EditPredictionPreview::Active {
6427 previous_scroll_position: None,
6428 since: Instant::now(),
6429 };
6430
6431 self.update_visible_inline_completion(window, cx);
6432 cx.notify();
6433 }
6434 } else if let EditPredictionPreview::Active {
6435 previous_scroll_position,
6436 since,
6437 } = self.edit_prediction_preview
6438 {
6439 if let (Some(previous_scroll_position), Some(position_map)) =
6440 (previous_scroll_position, self.last_position_map.as_ref())
6441 {
6442 self.set_scroll_position(
6443 previous_scroll_position
6444 .scroll_position(&position_map.snapshot.display_snapshot),
6445 window,
6446 cx,
6447 );
6448 }
6449
6450 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6451 released_too_fast: since.elapsed() < Duration::from_millis(200),
6452 };
6453 self.clear_row_highlights::<EditPredictionPreview>();
6454 self.update_visible_inline_completion(window, cx);
6455 cx.notify();
6456 }
6457 }
6458
6459 fn update_visible_inline_completion(
6460 &mut self,
6461 _window: &mut Window,
6462 cx: &mut Context<Self>,
6463 ) -> Option<()> {
6464 let selection = self.selections.newest_anchor();
6465 let cursor = selection.head();
6466 let multibuffer = self.buffer.read(cx).snapshot(cx);
6467 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6468 let excerpt_id = cursor.excerpt_id;
6469
6470 let show_in_menu = self.show_edit_predictions_in_menu();
6471 let completions_menu_has_precedence = !show_in_menu
6472 && (self.context_menu.borrow().is_some()
6473 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6474
6475 if completions_menu_has_precedence
6476 || !offset_selection.is_empty()
6477 || self
6478 .active_inline_completion
6479 .as_ref()
6480 .map_or(false, |completion| {
6481 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6482 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6483 !invalidation_range.contains(&offset_selection.head())
6484 })
6485 {
6486 self.discard_inline_completion(false, cx);
6487 return None;
6488 }
6489
6490 self.take_active_inline_completion(cx);
6491 let Some(provider) = self.edit_prediction_provider() else {
6492 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6493 return None;
6494 };
6495
6496 let (buffer, cursor_buffer_position) =
6497 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6498
6499 self.edit_prediction_settings =
6500 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6501
6502 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6503
6504 if self.edit_prediction_indent_conflict {
6505 let cursor_point = cursor.to_point(&multibuffer);
6506
6507 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6508
6509 if let Some((_, indent)) = indents.iter().next() {
6510 if indent.len == cursor_point.column {
6511 self.edit_prediction_indent_conflict = false;
6512 }
6513 }
6514 }
6515
6516 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6517 let edits = inline_completion
6518 .edits
6519 .into_iter()
6520 .flat_map(|(range, new_text)| {
6521 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6522 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6523 Some((start..end, new_text))
6524 })
6525 .collect::<Vec<_>>();
6526 if edits.is_empty() {
6527 return None;
6528 }
6529
6530 let first_edit_start = edits.first().unwrap().0.start;
6531 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6532 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6533
6534 let last_edit_end = edits.last().unwrap().0.end;
6535 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6536 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6537
6538 let cursor_row = cursor.to_point(&multibuffer).row;
6539
6540 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6541
6542 let mut inlay_ids = Vec::new();
6543 let invalidation_row_range;
6544 let move_invalidation_row_range = if cursor_row < edit_start_row {
6545 Some(cursor_row..edit_end_row)
6546 } else if cursor_row > edit_end_row {
6547 Some(edit_start_row..cursor_row)
6548 } else {
6549 None
6550 };
6551 let is_move =
6552 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6553 let completion = if is_move {
6554 invalidation_row_range =
6555 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6556 let target = first_edit_start;
6557 InlineCompletion::Move { target, snapshot }
6558 } else {
6559 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6560 && !self.inline_completions_hidden_for_vim_mode;
6561
6562 if show_completions_in_buffer {
6563 if edits
6564 .iter()
6565 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6566 {
6567 let mut inlays = Vec::new();
6568 for (range, new_text) in &edits {
6569 let inlay = Inlay::inline_completion(
6570 post_inc(&mut self.next_inlay_id),
6571 range.start,
6572 new_text.as_str(),
6573 );
6574 inlay_ids.push(inlay.id);
6575 inlays.push(inlay);
6576 }
6577
6578 self.splice_inlays(&[], inlays, cx);
6579 } else {
6580 let background_color = cx.theme().status().deleted_background;
6581 self.highlight_text::<InlineCompletionHighlight>(
6582 edits.iter().map(|(range, _)| range.clone()).collect(),
6583 HighlightStyle {
6584 background_color: Some(background_color),
6585 ..Default::default()
6586 },
6587 cx,
6588 );
6589 }
6590 }
6591
6592 invalidation_row_range = edit_start_row..edit_end_row;
6593
6594 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6595 if provider.show_tab_accept_marker() {
6596 EditDisplayMode::TabAccept
6597 } else {
6598 EditDisplayMode::Inline
6599 }
6600 } else {
6601 EditDisplayMode::DiffPopover
6602 };
6603
6604 InlineCompletion::Edit {
6605 edits,
6606 edit_preview: inline_completion.edit_preview,
6607 display_mode,
6608 snapshot,
6609 }
6610 };
6611
6612 let invalidation_range = multibuffer
6613 .anchor_before(Point::new(invalidation_row_range.start, 0))
6614 ..multibuffer.anchor_after(Point::new(
6615 invalidation_row_range.end,
6616 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6617 ));
6618
6619 self.stale_inline_completion_in_menu = None;
6620 self.active_inline_completion = Some(InlineCompletionState {
6621 inlay_ids,
6622 completion,
6623 completion_id: inline_completion.id,
6624 invalidation_range,
6625 });
6626
6627 cx.notify();
6628
6629 Some(())
6630 }
6631
6632 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6633 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6634 }
6635
6636 fn render_code_actions_indicator(
6637 &self,
6638 _style: &EditorStyle,
6639 row: DisplayRow,
6640 is_active: bool,
6641 breakpoint: Option<&(Anchor, Breakpoint)>,
6642 cx: &mut Context<Self>,
6643 ) -> Option<IconButton> {
6644 let color = Color::Muted;
6645 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6646 let show_tooltip = !self.context_menu_visible();
6647
6648 if self.available_code_actions.is_some() {
6649 Some(
6650 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6651 .shape(ui::IconButtonShape::Square)
6652 .icon_size(IconSize::XSmall)
6653 .icon_color(color)
6654 .toggle_state(is_active)
6655 .when(show_tooltip, |this| {
6656 this.tooltip({
6657 let focus_handle = self.focus_handle.clone();
6658 move |window, cx| {
6659 Tooltip::for_action_in(
6660 "Toggle Code Actions",
6661 &ToggleCodeActions {
6662 deployed_from_indicator: None,
6663 },
6664 &focus_handle,
6665 window,
6666 cx,
6667 )
6668 }
6669 })
6670 })
6671 .on_click(cx.listener(move |editor, _e, window, cx| {
6672 window.focus(&editor.focus_handle(cx));
6673 editor.toggle_code_actions(
6674 &ToggleCodeActions {
6675 deployed_from_indicator: Some(row),
6676 },
6677 window,
6678 cx,
6679 );
6680 }))
6681 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6682 editor.set_breakpoint_context_menu(
6683 row,
6684 position,
6685 event.down.position,
6686 window,
6687 cx,
6688 );
6689 })),
6690 )
6691 } else {
6692 None
6693 }
6694 }
6695
6696 fn clear_tasks(&mut self) {
6697 self.tasks.clear()
6698 }
6699
6700 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6701 if self.tasks.insert(key, value).is_some() {
6702 // This case should hopefully be rare, but just in case...
6703 log::error!(
6704 "multiple different run targets found on a single line, only the last target will be rendered"
6705 )
6706 }
6707 }
6708
6709 /// Get all display points of breakpoints that will be rendered within editor
6710 ///
6711 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6712 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6713 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6714 fn active_breakpoints(
6715 &self,
6716 range: Range<DisplayRow>,
6717 window: &mut Window,
6718 cx: &mut Context<Self>,
6719 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6720 let mut breakpoint_display_points = HashMap::default();
6721
6722 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6723 return breakpoint_display_points;
6724 };
6725
6726 let snapshot = self.snapshot(window, cx);
6727
6728 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6729 let Some(project) = self.project.as_ref() else {
6730 return breakpoint_display_points;
6731 };
6732
6733 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6734 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6735
6736 for (buffer_snapshot, range, excerpt_id) in
6737 multi_buffer_snapshot.range_to_buffer_ranges(range)
6738 {
6739 let Some(buffer) = project.read_with(cx, |this, cx| {
6740 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6741 }) else {
6742 continue;
6743 };
6744 let breakpoints = breakpoint_store.read(cx).breakpoints(
6745 &buffer,
6746 Some(
6747 buffer_snapshot.anchor_before(range.start)
6748 ..buffer_snapshot.anchor_after(range.end),
6749 ),
6750 buffer_snapshot,
6751 cx,
6752 );
6753 for (anchor, breakpoint) in breakpoints {
6754 let multi_buffer_anchor =
6755 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6756 let position = multi_buffer_anchor
6757 .to_point(&multi_buffer_snapshot)
6758 .to_display_point(&snapshot);
6759
6760 breakpoint_display_points
6761 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6762 }
6763 }
6764
6765 breakpoint_display_points
6766 }
6767
6768 fn breakpoint_context_menu(
6769 &self,
6770 anchor: Anchor,
6771 window: &mut Window,
6772 cx: &mut Context<Self>,
6773 ) -> Entity<ui::ContextMenu> {
6774 let weak_editor = cx.weak_entity();
6775 let focus_handle = self.focus_handle(cx);
6776
6777 let row = self
6778 .buffer
6779 .read(cx)
6780 .snapshot(cx)
6781 .summary_for_anchor::<Point>(&anchor)
6782 .row;
6783
6784 let breakpoint = self
6785 .breakpoint_at_row(row, window, cx)
6786 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6787
6788 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6789 "Edit Log Breakpoint"
6790 } else {
6791 "Set Log Breakpoint"
6792 };
6793
6794 let condition_breakpoint_msg = if breakpoint
6795 .as_ref()
6796 .is_some_and(|bp| bp.1.condition.is_some())
6797 {
6798 "Edit Condition Breakpoint"
6799 } else {
6800 "Set Condition Breakpoint"
6801 };
6802
6803 let hit_condition_breakpoint_msg = if breakpoint
6804 .as_ref()
6805 .is_some_and(|bp| bp.1.hit_condition.is_some())
6806 {
6807 "Edit Hit Condition Breakpoint"
6808 } else {
6809 "Set Hit Condition Breakpoint"
6810 };
6811
6812 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6813 "Unset Breakpoint"
6814 } else {
6815 "Set Breakpoint"
6816 };
6817
6818 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6819 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6820
6821 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6822 BreakpointState::Enabled => Some("Disable"),
6823 BreakpointState::Disabled => Some("Enable"),
6824 });
6825
6826 let (anchor, breakpoint) =
6827 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6828
6829 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6830 menu.on_blur_subscription(Subscription::new(|| {}))
6831 .context(focus_handle)
6832 .when(run_to_cursor, |this| {
6833 let weak_editor = weak_editor.clone();
6834 this.entry("Run to cursor", None, move |window, cx| {
6835 weak_editor
6836 .update(cx, |editor, cx| {
6837 editor.change_selections(None, window, cx, |s| {
6838 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6839 });
6840 })
6841 .ok();
6842
6843 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6844 })
6845 .separator()
6846 })
6847 .when_some(toggle_state_msg, |this, msg| {
6848 this.entry(msg, None, {
6849 let weak_editor = weak_editor.clone();
6850 let breakpoint = breakpoint.clone();
6851 move |_window, cx| {
6852 weak_editor
6853 .update(cx, |this, cx| {
6854 this.edit_breakpoint_at_anchor(
6855 anchor,
6856 breakpoint.as_ref().clone(),
6857 BreakpointEditAction::InvertState,
6858 cx,
6859 );
6860 })
6861 .log_err();
6862 }
6863 })
6864 })
6865 .entry(set_breakpoint_msg, None, {
6866 let weak_editor = weak_editor.clone();
6867 let breakpoint = breakpoint.clone();
6868 move |_window, cx| {
6869 weak_editor
6870 .update(cx, |this, cx| {
6871 this.edit_breakpoint_at_anchor(
6872 anchor,
6873 breakpoint.as_ref().clone(),
6874 BreakpointEditAction::Toggle,
6875 cx,
6876 );
6877 })
6878 .log_err();
6879 }
6880 })
6881 .entry(log_breakpoint_msg, None, {
6882 let breakpoint = breakpoint.clone();
6883 let weak_editor = weak_editor.clone();
6884 move |window, cx| {
6885 weak_editor
6886 .update(cx, |this, cx| {
6887 this.add_edit_breakpoint_block(
6888 anchor,
6889 breakpoint.as_ref(),
6890 BreakpointPromptEditAction::Log,
6891 window,
6892 cx,
6893 );
6894 })
6895 .log_err();
6896 }
6897 })
6898 .entry(condition_breakpoint_msg, None, {
6899 let breakpoint = breakpoint.clone();
6900 let weak_editor = weak_editor.clone();
6901 move |window, cx| {
6902 weak_editor
6903 .update(cx, |this, cx| {
6904 this.add_edit_breakpoint_block(
6905 anchor,
6906 breakpoint.as_ref(),
6907 BreakpointPromptEditAction::Condition,
6908 window,
6909 cx,
6910 );
6911 })
6912 .log_err();
6913 }
6914 })
6915 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6916 weak_editor
6917 .update(cx, |this, cx| {
6918 this.add_edit_breakpoint_block(
6919 anchor,
6920 breakpoint.as_ref(),
6921 BreakpointPromptEditAction::HitCondition,
6922 window,
6923 cx,
6924 );
6925 })
6926 .log_err();
6927 })
6928 })
6929 }
6930
6931 fn render_breakpoint(
6932 &self,
6933 position: Anchor,
6934 row: DisplayRow,
6935 breakpoint: &Breakpoint,
6936 cx: &mut Context<Self>,
6937 ) -> IconButton {
6938 let (color, icon) = {
6939 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6940 (false, false) => ui::IconName::DebugBreakpoint,
6941 (true, false) => ui::IconName::DebugLogBreakpoint,
6942 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6943 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6944 };
6945
6946 let color = if self
6947 .gutter_breakpoint_indicator
6948 .0
6949 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6950 {
6951 Color::Hint
6952 } else {
6953 Color::Debugger
6954 };
6955
6956 (color, icon)
6957 };
6958
6959 let breakpoint = Arc::from(breakpoint.clone());
6960
6961 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6962 .icon_size(IconSize::XSmall)
6963 .size(ui::ButtonSize::None)
6964 .icon_color(color)
6965 .style(ButtonStyle::Transparent)
6966 .on_click(cx.listener({
6967 let breakpoint = breakpoint.clone();
6968
6969 move |editor, event: &ClickEvent, window, cx| {
6970 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6971 BreakpointEditAction::InvertState
6972 } else {
6973 BreakpointEditAction::Toggle
6974 };
6975
6976 window.focus(&editor.focus_handle(cx));
6977 editor.edit_breakpoint_at_anchor(
6978 position,
6979 breakpoint.as_ref().clone(),
6980 edit_action,
6981 cx,
6982 );
6983 }
6984 }))
6985 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6986 editor.set_breakpoint_context_menu(
6987 row,
6988 Some(position),
6989 event.down.position,
6990 window,
6991 cx,
6992 );
6993 }))
6994 }
6995
6996 fn build_tasks_context(
6997 project: &Entity<Project>,
6998 buffer: &Entity<Buffer>,
6999 buffer_row: u32,
7000 tasks: &Arc<RunnableTasks>,
7001 cx: &mut Context<Self>,
7002 ) -> Task<Option<task::TaskContext>> {
7003 let position = Point::new(buffer_row, tasks.column);
7004 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
7005 let location = Location {
7006 buffer: buffer.clone(),
7007 range: range_start..range_start,
7008 };
7009 // Fill in the environmental variables from the tree-sitter captures
7010 let mut captured_task_variables = TaskVariables::default();
7011 for (capture_name, value) in tasks.extra_variables.clone() {
7012 captured_task_variables.insert(
7013 task::VariableName::Custom(capture_name.into()),
7014 value.clone(),
7015 );
7016 }
7017 project.update(cx, |project, cx| {
7018 project.task_store().update(cx, |task_store, cx| {
7019 task_store.task_context_for_location(captured_task_variables, location, cx)
7020 })
7021 })
7022 }
7023
7024 pub fn spawn_nearest_task(
7025 &mut self,
7026 action: &SpawnNearestTask,
7027 window: &mut Window,
7028 cx: &mut Context<Self>,
7029 ) {
7030 let Some((workspace, _)) = self.workspace.clone() else {
7031 return;
7032 };
7033 let Some(project) = self.project.clone() else {
7034 return;
7035 };
7036
7037 // Try to find a closest, enclosing node using tree-sitter that has a
7038 // task
7039 let Some((buffer, buffer_row, tasks)) = self
7040 .find_enclosing_node_task(cx)
7041 // Or find the task that's closest in row-distance.
7042 .or_else(|| self.find_closest_task(cx))
7043 else {
7044 return;
7045 };
7046
7047 let reveal_strategy = action.reveal;
7048 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
7049 cx.spawn_in(window, async move |_, cx| {
7050 let context = task_context.await?;
7051 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
7052
7053 let resolved = resolved_task.resolved.as_mut()?;
7054 resolved.reveal = reveal_strategy;
7055
7056 workspace
7057 .update_in(cx, |workspace, window, cx| {
7058 workspace.schedule_resolved_task(
7059 task_source_kind,
7060 resolved_task,
7061 false,
7062 window,
7063 cx,
7064 );
7065 })
7066 .ok()
7067 })
7068 .detach();
7069 }
7070
7071 fn find_closest_task(
7072 &mut self,
7073 cx: &mut Context<Self>,
7074 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7075 let cursor_row = self.selections.newest_adjusted(cx).head().row;
7076
7077 let ((buffer_id, row), tasks) = self
7078 .tasks
7079 .iter()
7080 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
7081
7082 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
7083 let tasks = Arc::new(tasks.to_owned());
7084 Some((buffer, *row, tasks))
7085 }
7086
7087 fn find_enclosing_node_task(
7088 &mut self,
7089 cx: &mut Context<Self>,
7090 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7091 let snapshot = self.buffer.read(cx).snapshot(cx);
7092 let offset = self.selections.newest::<usize>(cx).head();
7093 let excerpt = snapshot.excerpt_containing(offset..offset)?;
7094 let buffer_id = excerpt.buffer().remote_id();
7095
7096 let layer = excerpt.buffer().syntax_layer_at(offset)?;
7097 let mut cursor = layer.node().walk();
7098
7099 while cursor.goto_first_child_for_byte(offset).is_some() {
7100 if cursor.node().end_byte() == offset {
7101 cursor.goto_next_sibling();
7102 }
7103 }
7104
7105 // Ascend to the smallest ancestor that contains the range and has a task.
7106 loop {
7107 let node = cursor.node();
7108 let node_range = node.byte_range();
7109 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
7110
7111 // Check if this node contains our offset
7112 if node_range.start <= offset && node_range.end >= offset {
7113 // If it contains offset, check for task
7114 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
7115 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
7116 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
7117 }
7118 }
7119
7120 if !cursor.goto_parent() {
7121 break;
7122 }
7123 }
7124 None
7125 }
7126
7127 fn render_run_indicator(
7128 &self,
7129 _style: &EditorStyle,
7130 is_active: bool,
7131 row: DisplayRow,
7132 breakpoint: Option<(Anchor, Breakpoint)>,
7133 cx: &mut Context<Self>,
7134 ) -> IconButton {
7135 let color = Color::Muted;
7136 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
7137
7138 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
7139 .shape(ui::IconButtonShape::Square)
7140 .icon_size(IconSize::XSmall)
7141 .icon_color(color)
7142 .toggle_state(is_active)
7143 .on_click(cx.listener(move |editor, _e, window, cx| {
7144 window.focus(&editor.focus_handle(cx));
7145 editor.toggle_code_actions(
7146 &ToggleCodeActions {
7147 deployed_from_indicator: Some(row),
7148 },
7149 window,
7150 cx,
7151 );
7152 }))
7153 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7154 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
7155 }))
7156 }
7157
7158 pub fn context_menu_visible(&self) -> bool {
7159 !self.edit_prediction_preview_is_active()
7160 && self
7161 .context_menu
7162 .borrow()
7163 .as_ref()
7164 .map_or(false, |menu| menu.visible())
7165 }
7166
7167 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
7168 self.context_menu
7169 .borrow()
7170 .as_ref()
7171 .map(|menu| menu.origin())
7172 }
7173
7174 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
7175 self.context_menu_options = Some(options);
7176 }
7177
7178 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
7179 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
7180
7181 fn render_edit_prediction_popover(
7182 &mut self,
7183 text_bounds: &Bounds<Pixels>,
7184 content_origin: gpui::Point<Pixels>,
7185 editor_snapshot: &EditorSnapshot,
7186 visible_row_range: Range<DisplayRow>,
7187 scroll_top: f32,
7188 scroll_bottom: f32,
7189 line_layouts: &[LineWithInvisibles],
7190 line_height: Pixels,
7191 scroll_pixel_position: gpui::Point<Pixels>,
7192 newest_selection_head: Option<DisplayPoint>,
7193 editor_width: Pixels,
7194 style: &EditorStyle,
7195 window: &mut Window,
7196 cx: &mut App,
7197 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7198 let active_inline_completion = self.active_inline_completion.as_ref()?;
7199
7200 if self.edit_prediction_visible_in_cursor_popover(true) {
7201 return None;
7202 }
7203
7204 match &active_inline_completion.completion {
7205 InlineCompletion::Move { target, .. } => {
7206 let target_display_point = target.to_display_point(editor_snapshot);
7207
7208 if self.edit_prediction_requires_modifier() {
7209 if !self.edit_prediction_preview_is_active() {
7210 return None;
7211 }
7212
7213 self.render_edit_prediction_modifier_jump_popover(
7214 text_bounds,
7215 content_origin,
7216 visible_row_range,
7217 line_layouts,
7218 line_height,
7219 scroll_pixel_position,
7220 newest_selection_head,
7221 target_display_point,
7222 window,
7223 cx,
7224 )
7225 } else {
7226 self.render_edit_prediction_eager_jump_popover(
7227 text_bounds,
7228 content_origin,
7229 editor_snapshot,
7230 visible_row_range,
7231 scroll_top,
7232 scroll_bottom,
7233 line_height,
7234 scroll_pixel_position,
7235 target_display_point,
7236 editor_width,
7237 window,
7238 cx,
7239 )
7240 }
7241 }
7242 InlineCompletion::Edit {
7243 display_mode: EditDisplayMode::Inline,
7244 ..
7245 } => None,
7246 InlineCompletion::Edit {
7247 display_mode: EditDisplayMode::TabAccept,
7248 edits,
7249 ..
7250 } => {
7251 let range = &edits.first()?.0;
7252 let target_display_point = range.end.to_display_point(editor_snapshot);
7253
7254 self.render_edit_prediction_end_of_line_popover(
7255 "Accept",
7256 editor_snapshot,
7257 visible_row_range,
7258 target_display_point,
7259 line_height,
7260 scroll_pixel_position,
7261 content_origin,
7262 editor_width,
7263 window,
7264 cx,
7265 )
7266 }
7267 InlineCompletion::Edit {
7268 edits,
7269 edit_preview,
7270 display_mode: EditDisplayMode::DiffPopover,
7271 snapshot,
7272 } => self.render_edit_prediction_diff_popover(
7273 text_bounds,
7274 content_origin,
7275 editor_snapshot,
7276 visible_row_range,
7277 line_layouts,
7278 line_height,
7279 scroll_pixel_position,
7280 newest_selection_head,
7281 editor_width,
7282 style,
7283 edits,
7284 edit_preview,
7285 snapshot,
7286 window,
7287 cx,
7288 ),
7289 }
7290 }
7291
7292 fn render_edit_prediction_modifier_jump_popover(
7293 &mut self,
7294 text_bounds: &Bounds<Pixels>,
7295 content_origin: gpui::Point<Pixels>,
7296 visible_row_range: Range<DisplayRow>,
7297 line_layouts: &[LineWithInvisibles],
7298 line_height: Pixels,
7299 scroll_pixel_position: gpui::Point<Pixels>,
7300 newest_selection_head: Option<DisplayPoint>,
7301 target_display_point: DisplayPoint,
7302 window: &mut Window,
7303 cx: &mut App,
7304 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7305 let scrolled_content_origin =
7306 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7307
7308 const SCROLL_PADDING_Y: Pixels = px(12.);
7309
7310 if target_display_point.row() < visible_row_range.start {
7311 return self.render_edit_prediction_scroll_popover(
7312 |_| SCROLL_PADDING_Y,
7313 IconName::ArrowUp,
7314 visible_row_range,
7315 line_layouts,
7316 newest_selection_head,
7317 scrolled_content_origin,
7318 window,
7319 cx,
7320 );
7321 } else if target_display_point.row() >= visible_row_range.end {
7322 return self.render_edit_prediction_scroll_popover(
7323 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7324 IconName::ArrowDown,
7325 visible_row_range,
7326 line_layouts,
7327 newest_selection_head,
7328 scrolled_content_origin,
7329 window,
7330 cx,
7331 );
7332 }
7333
7334 const POLE_WIDTH: Pixels = px(2.);
7335
7336 let line_layout =
7337 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7338 let target_column = target_display_point.column() as usize;
7339
7340 let target_x = line_layout.x_for_index(target_column);
7341 let target_y =
7342 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7343
7344 let flag_on_right = target_x < text_bounds.size.width / 2.;
7345
7346 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7347 border_color.l += 0.001;
7348
7349 let mut element = v_flex()
7350 .items_end()
7351 .when(flag_on_right, |el| el.items_start())
7352 .child(if flag_on_right {
7353 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7354 .rounded_bl(px(0.))
7355 .rounded_tl(px(0.))
7356 .border_l_2()
7357 .border_color(border_color)
7358 } else {
7359 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7360 .rounded_br(px(0.))
7361 .rounded_tr(px(0.))
7362 .border_r_2()
7363 .border_color(border_color)
7364 })
7365 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7366 .into_any();
7367
7368 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7369
7370 let mut origin = scrolled_content_origin + point(target_x, target_y)
7371 - point(
7372 if flag_on_right {
7373 POLE_WIDTH
7374 } else {
7375 size.width - POLE_WIDTH
7376 },
7377 size.height - line_height,
7378 );
7379
7380 origin.x = origin.x.max(content_origin.x);
7381
7382 element.prepaint_at(origin, window, cx);
7383
7384 Some((element, origin))
7385 }
7386
7387 fn render_edit_prediction_scroll_popover(
7388 &mut self,
7389 to_y: impl Fn(Size<Pixels>) -> Pixels,
7390 scroll_icon: IconName,
7391 visible_row_range: Range<DisplayRow>,
7392 line_layouts: &[LineWithInvisibles],
7393 newest_selection_head: Option<DisplayPoint>,
7394 scrolled_content_origin: gpui::Point<Pixels>,
7395 window: &mut Window,
7396 cx: &mut App,
7397 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7398 let mut element = self
7399 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7400 .into_any();
7401
7402 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7403
7404 let cursor = newest_selection_head?;
7405 let cursor_row_layout =
7406 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7407 let cursor_column = cursor.column() as usize;
7408
7409 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7410
7411 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7412
7413 element.prepaint_at(origin, window, cx);
7414 Some((element, origin))
7415 }
7416
7417 fn render_edit_prediction_eager_jump_popover(
7418 &mut self,
7419 text_bounds: &Bounds<Pixels>,
7420 content_origin: gpui::Point<Pixels>,
7421 editor_snapshot: &EditorSnapshot,
7422 visible_row_range: Range<DisplayRow>,
7423 scroll_top: f32,
7424 scroll_bottom: f32,
7425 line_height: Pixels,
7426 scroll_pixel_position: gpui::Point<Pixels>,
7427 target_display_point: DisplayPoint,
7428 editor_width: Pixels,
7429 window: &mut Window,
7430 cx: &mut App,
7431 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7432 if target_display_point.row().as_f32() < scroll_top {
7433 let mut element = self
7434 .render_edit_prediction_line_popover(
7435 "Jump to Edit",
7436 Some(IconName::ArrowUp),
7437 window,
7438 cx,
7439 )?
7440 .into_any();
7441
7442 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7443 let offset = point(
7444 (text_bounds.size.width - size.width) / 2.,
7445 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7446 );
7447
7448 let origin = text_bounds.origin + offset;
7449 element.prepaint_at(origin, window, cx);
7450 Some((element, origin))
7451 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7452 let mut element = self
7453 .render_edit_prediction_line_popover(
7454 "Jump to Edit",
7455 Some(IconName::ArrowDown),
7456 window,
7457 cx,
7458 )?
7459 .into_any();
7460
7461 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7462 let offset = point(
7463 (text_bounds.size.width - size.width) / 2.,
7464 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7465 );
7466
7467 let origin = text_bounds.origin + offset;
7468 element.prepaint_at(origin, window, cx);
7469 Some((element, origin))
7470 } else {
7471 self.render_edit_prediction_end_of_line_popover(
7472 "Jump to Edit",
7473 editor_snapshot,
7474 visible_row_range,
7475 target_display_point,
7476 line_height,
7477 scroll_pixel_position,
7478 content_origin,
7479 editor_width,
7480 window,
7481 cx,
7482 )
7483 }
7484 }
7485
7486 fn render_edit_prediction_end_of_line_popover(
7487 self: &mut Editor,
7488 label: &'static str,
7489 editor_snapshot: &EditorSnapshot,
7490 visible_row_range: Range<DisplayRow>,
7491 target_display_point: DisplayPoint,
7492 line_height: Pixels,
7493 scroll_pixel_position: gpui::Point<Pixels>,
7494 content_origin: gpui::Point<Pixels>,
7495 editor_width: Pixels,
7496 window: &mut Window,
7497 cx: &mut App,
7498 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7499 let target_line_end = DisplayPoint::new(
7500 target_display_point.row(),
7501 editor_snapshot.line_len(target_display_point.row()),
7502 );
7503
7504 let mut element = self
7505 .render_edit_prediction_line_popover(label, None, window, cx)?
7506 .into_any();
7507
7508 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7509
7510 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7511
7512 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7513 let mut origin = start_point
7514 + line_origin
7515 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7516 origin.x = origin.x.max(content_origin.x);
7517
7518 let max_x = content_origin.x + editor_width - size.width;
7519
7520 if origin.x > max_x {
7521 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7522
7523 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7524 origin.y += offset;
7525 IconName::ArrowUp
7526 } else {
7527 origin.y -= offset;
7528 IconName::ArrowDown
7529 };
7530
7531 element = self
7532 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7533 .into_any();
7534
7535 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7536
7537 origin.x = content_origin.x + editor_width - size.width - px(2.);
7538 }
7539
7540 element.prepaint_at(origin, window, cx);
7541 Some((element, origin))
7542 }
7543
7544 fn render_edit_prediction_diff_popover(
7545 self: &Editor,
7546 text_bounds: &Bounds<Pixels>,
7547 content_origin: gpui::Point<Pixels>,
7548 editor_snapshot: &EditorSnapshot,
7549 visible_row_range: Range<DisplayRow>,
7550 line_layouts: &[LineWithInvisibles],
7551 line_height: Pixels,
7552 scroll_pixel_position: gpui::Point<Pixels>,
7553 newest_selection_head: Option<DisplayPoint>,
7554 editor_width: Pixels,
7555 style: &EditorStyle,
7556 edits: &Vec<(Range<Anchor>, String)>,
7557 edit_preview: &Option<language::EditPreview>,
7558 snapshot: &language::BufferSnapshot,
7559 window: &mut Window,
7560 cx: &mut App,
7561 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7562 let edit_start = edits
7563 .first()
7564 .unwrap()
7565 .0
7566 .start
7567 .to_display_point(editor_snapshot);
7568 let edit_end = edits
7569 .last()
7570 .unwrap()
7571 .0
7572 .end
7573 .to_display_point(editor_snapshot);
7574
7575 let is_visible = visible_row_range.contains(&edit_start.row())
7576 || visible_row_range.contains(&edit_end.row());
7577 if !is_visible {
7578 return None;
7579 }
7580
7581 let highlighted_edits =
7582 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7583
7584 let styled_text = highlighted_edits.to_styled_text(&style.text);
7585 let line_count = highlighted_edits.text.lines().count();
7586
7587 const BORDER_WIDTH: Pixels = px(1.);
7588
7589 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7590 let has_keybind = keybind.is_some();
7591
7592 let mut element = h_flex()
7593 .items_start()
7594 .child(
7595 h_flex()
7596 .bg(cx.theme().colors().editor_background)
7597 .border(BORDER_WIDTH)
7598 .shadow_sm()
7599 .border_color(cx.theme().colors().border)
7600 .rounded_l_lg()
7601 .when(line_count > 1, |el| el.rounded_br_lg())
7602 .pr_1()
7603 .child(styled_text),
7604 )
7605 .child(
7606 h_flex()
7607 .h(line_height + BORDER_WIDTH * 2.)
7608 .px_1p5()
7609 .gap_1()
7610 // Workaround: For some reason, there's a gap if we don't do this
7611 .ml(-BORDER_WIDTH)
7612 .shadow(smallvec![gpui::BoxShadow {
7613 color: gpui::black().opacity(0.05),
7614 offset: point(px(1.), px(1.)),
7615 blur_radius: px(2.),
7616 spread_radius: px(0.),
7617 }])
7618 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7619 .border(BORDER_WIDTH)
7620 .border_color(cx.theme().colors().border)
7621 .rounded_r_lg()
7622 .id("edit_prediction_diff_popover_keybind")
7623 .when(!has_keybind, |el| {
7624 let status_colors = cx.theme().status();
7625
7626 el.bg(status_colors.error_background)
7627 .border_color(status_colors.error.opacity(0.6))
7628 .child(Icon::new(IconName::Info).color(Color::Error))
7629 .cursor_default()
7630 .hoverable_tooltip(move |_window, cx| {
7631 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7632 })
7633 })
7634 .children(keybind),
7635 )
7636 .into_any();
7637
7638 let longest_row =
7639 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7640 let longest_line_width = if visible_row_range.contains(&longest_row) {
7641 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7642 } else {
7643 layout_line(
7644 longest_row,
7645 editor_snapshot,
7646 style,
7647 editor_width,
7648 |_| false,
7649 window,
7650 cx,
7651 )
7652 .width
7653 };
7654
7655 let viewport_bounds =
7656 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7657 right: -EditorElement::SCROLLBAR_WIDTH,
7658 ..Default::default()
7659 });
7660
7661 let x_after_longest =
7662 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7663 - scroll_pixel_position.x;
7664
7665 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7666
7667 // Fully visible if it can be displayed within the window (allow overlapping other
7668 // panes). However, this is only allowed if the popover starts within text_bounds.
7669 let can_position_to_the_right = x_after_longest < text_bounds.right()
7670 && x_after_longest + element_bounds.width < viewport_bounds.right();
7671
7672 let mut origin = if can_position_to_the_right {
7673 point(
7674 x_after_longest,
7675 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7676 - scroll_pixel_position.y,
7677 )
7678 } else {
7679 let cursor_row = newest_selection_head.map(|head| head.row());
7680 let above_edit = edit_start
7681 .row()
7682 .0
7683 .checked_sub(line_count as u32)
7684 .map(DisplayRow);
7685 let below_edit = Some(edit_end.row() + 1);
7686 let above_cursor =
7687 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7688 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7689
7690 // Place the edit popover adjacent to the edit if there is a location
7691 // available that is onscreen and does not obscure the cursor. Otherwise,
7692 // place it adjacent to the cursor.
7693 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7694 .into_iter()
7695 .flatten()
7696 .find(|&start_row| {
7697 let end_row = start_row + line_count as u32;
7698 visible_row_range.contains(&start_row)
7699 && visible_row_range.contains(&end_row)
7700 && cursor_row.map_or(true, |cursor_row| {
7701 !((start_row..end_row).contains(&cursor_row))
7702 })
7703 })?;
7704
7705 content_origin
7706 + point(
7707 -scroll_pixel_position.x,
7708 row_target.as_f32() * line_height - scroll_pixel_position.y,
7709 )
7710 };
7711
7712 origin.x -= BORDER_WIDTH;
7713
7714 window.defer_draw(element, origin, 1);
7715
7716 // Do not return an element, since it will already be drawn due to defer_draw.
7717 None
7718 }
7719
7720 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7721 px(30.)
7722 }
7723
7724 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7725 if self.read_only(cx) {
7726 cx.theme().players().read_only()
7727 } else {
7728 self.style.as_ref().unwrap().local_player
7729 }
7730 }
7731
7732 fn render_edit_prediction_accept_keybind(
7733 &self,
7734 window: &mut Window,
7735 cx: &App,
7736 ) -> Option<AnyElement> {
7737 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7738 let accept_keystroke = accept_binding.keystroke()?;
7739
7740 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7741
7742 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7743 Color::Accent
7744 } else {
7745 Color::Muted
7746 };
7747
7748 h_flex()
7749 .px_0p5()
7750 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7751 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7752 .text_size(TextSize::XSmall.rems(cx))
7753 .child(h_flex().children(ui::render_modifiers(
7754 &accept_keystroke.modifiers,
7755 PlatformStyle::platform(),
7756 Some(modifiers_color),
7757 Some(IconSize::XSmall.rems().into()),
7758 true,
7759 )))
7760 .when(is_platform_style_mac, |parent| {
7761 parent.child(accept_keystroke.key.clone())
7762 })
7763 .when(!is_platform_style_mac, |parent| {
7764 parent.child(
7765 Key::new(
7766 util::capitalize(&accept_keystroke.key),
7767 Some(Color::Default),
7768 )
7769 .size(Some(IconSize::XSmall.rems().into())),
7770 )
7771 })
7772 .into_any()
7773 .into()
7774 }
7775
7776 fn render_edit_prediction_line_popover(
7777 &self,
7778 label: impl Into<SharedString>,
7779 icon: Option<IconName>,
7780 window: &mut Window,
7781 cx: &App,
7782 ) -> Option<Stateful<Div>> {
7783 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7784
7785 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7786 let has_keybind = keybind.is_some();
7787
7788 let result = h_flex()
7789 .id("ep-line-popover")
7790 .py_0p5()
7791 .pl_1()
7792 .pr(padding_right)
7793 .gap_1()
7794 .rounded_md()
7795 .border_1()
7796 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7797 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7798 .shadow_sm()
7799 .when(!has_keybind, |el| {
7800 let status_colors = cx.theme().status();
7801
7802 el.bg(status_colors.error_background)
7803 .border_color(status_colors.error.opacity(0.6))
7804 .pl_2()
7805 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7806 .cursor_default()
7807 .hoverable_tooltip(move |_window, cx| {
7808 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7809 })
7810 })
7811 .children(keybind)
7812 .child(
7813 Label::new(label)
7814 .size(LabelSize::Small)
7815 .when(!has_keybind, |el| {
7816 el.color(cx.theme().status().error.into()).strikethrough()
7817 }),
7818 )
7819 .when(!has_keybind, |el| {
7820 el.child(
7821 h_flex().ml_1().child(
7822 Icon::new(IconName::Info)
7823 .size(IconSize::Small)
7824 .color(cx.theme().status().error.into()),
7825 ),
7826 )
7827 })
7828 .when_some(icon, |element, icon| {
7829 element.child(
7830 div()
7831 .mt(px(1.5))
7832 .child(Icon::new(icon).size(IconSize::Small)),
7833 )
7834 });
7835
7836 Some(result)
7837 }
7838
7839 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7840 let accent_color = cx.theme().colors().text_accent;
7841 let editor_bg_color = cx.theme().colors().editor_background;
7842 editor_bg_color.blend(accent_color.opacity(0.1))
7843 }
7844
7845 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7846 let accent_color = cx.theme().colors().text_accent;
7847 let editor_bg_color = cx.theme().colors().editor_background;
7848 editor_bg_color.blend(accent_color.opacity(0.6))
7849 }
7850
7851 fn render_edit_prediction_cursor_popover(
7852 &self,
7853 min_width: Pixels,
7854 max_width: Pixels,
7855 cursor_point: Point,
7856 style: &EditorStyle,
7857 accept_keystroke: Option<&gpui::Keystroke>,
7858 _window: &Window,
7859 cx: &mut Context<Editor>,
7860 ) -> Option<AnyElement> {
7861 let provider = self.edit_prediction_provider.as_ref()?;
7862
7863 if provider.provider.needs_terms_acceptance(cx) {
7864 return Some(
7865 h_flex()
7866 .min_w(min_width)
7867 .flex_1()
7868 .px_2()
7869 .py_1()
7870 .gap_3()
7871 .elevation_2(cx)
7872 .hover(|style| style.bg(cx.theme().colors().element_hover))
7873 .id("accept-terms")
7874 .cursor_pointer()
7875 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7876 .on_click(cx.listener(|this, _event, window, cx| {
7877 cx.stop_propagation();
7878 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7879 window.dispatch_action(
7880 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7881 cx,
7882 );
7883 }))
7884 .child(
7885 h_flex()
7886 .flex_1()
7887 .gap_2()
7888 .child(Icon::new(IconName::ZedPredict))
7889 .child(Label::new("Accept Terms of Service"))
7890 .child(div().w_full())
7891 .child(
7892 Icon::new(IconName::ArrowUpRight)
7893 .color(Color::Muted)
7894 .size(IconSize::Small),
7895 )
7896 .into_any_element(),
7897 )
7898 .into_any(),
7899 );
7900 }
7901
7902 let is_refreshing = provider.provider.is_refreshing(cx);
7903
7904 fn pending_completion_container() -> Div {
7905 h_flex()
7906 .h_full()
7907 .flex_1()
7908 .gap_2()
7909 .child(Icon::new(IconName::ZedPredict))
7910 }
7911
7912 let completion = match &self.active_inline_completion {
7913 Some(prediction) => {
7914 if !self.has_visible_completions_menu() {
7915 const RADIUS: Pixels = px(6.);
7916 const BORDER_WIDTH: Pixels = px(1.);
7917
7918 return Some(
7919 h_flex()
7920 .elevation_2(cx)
7921 .border(BORDER_WIDTH)
7922 .border_color(cx.theme().colors().border)
7923 .when(accept_keystroke.is_none(), |el| {
7924 el.border_color(cx.theme().status().error)
7925 })
7926 .rounded(RADIUS)
7927 .rounded_tl(px(0.))
7928 .overflow_hidden()
7929 .child(div().px_1p5().child(match &prediction.completion {
7930 InlineCompletion::Move { target, snapshot } => {
7931 use text::ToPoint as _;
7932 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7933 {
7934 Icon::new(IconName::ZedPredictDown)
7935 } else {
7936 Icon::new(IconName::ZedPredictUp)
7937 }
7938 }
7939 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7940 }))
7941 .child(
7942 h_flex()
7943 .gap_1()
7944 .py_1()
7945 .px_2()
7946 .rounded_r(RADIUS - BORDER_WIDTH)
7947 .border_l_1()
7948 .border_color(cx.theme().colors().border)
7949 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7950 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7951 el.child(
7952 Label::new("Hold")
7953 .size(LabelSize::Small)
7954 .when(accept_keystroke.is_none(), |el| {
7955 el.strikethrough()
7956 })
7957 .line_height_style(LineHeightStyle::UiLabel),
7958 )
7959 })
7960 .id("edit_prediction_cursor_popover_keybind")
7961 .when(accept_keystroke.is_none(), |el| {
7962 let status_colors = cx.theme().status();
7963
7964 el.bg(status_colors.error_background)
7965 .border_color(status_colors.error.opacity(0.6))
7966 .child(Icon::new(IconName::Info).color(Color::Error))
7967 .cursor_default()
7968 .hoverable_tooltip(move |_window, cx| {
7969 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7970 .into()
7971 })
7972 })
7973 .when_some(
7974 accept_keystroke.as_ref(),
7975 |el, accept_keystroke| {
7976 el.child(h_flex().children(ui::render_modifiers(
7977 &accept_keystroke.modifiers,
7978 PlatformStyle::platform(),
7979 Some(Color::Default),
7980 Some(IconSize::XSmall.rems().into()),
7981 false,
7982 )))
7983 },
7984 ),
7985 )
7986 .into_any(),
7987 );
7988 }
7989
7990 self.render_edit_prediction_cursor_popover_preview(
7991 prediction,
7992 cursor_point,
7993 style,
7994 cx,
7995 )?
7996 }
7997
7998 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7999 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
8000 stale_completion,
8001 cursor_point,
8002 style,
8003 cx,
8004 )?,
8005
8006 None => {
8007 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
8008 }
8009 },
8010
8011 None => pending_completion_container().child(Label::new("No Prediction")),
8012 };
8013
8014 let completion = if is_refreshing {
8015 completion
8016 .with_animation(
8017 "loading-completion",
8018 Animation::new(Duration::from_secs(2))
8019 .repeat()
8020 .with_easing(pulsating_between(0.4, 0.8)),
8021 |label, delta| label.opacity(delta),
8022 )
8023 .into_any_element()
8024 } else {
8025 completion.into_any_element()
8026 };
8027
8028 let has_completion = self.active_inline_completion.is_some();
8029
8030 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
8031 Some(
8032 h_flex()
8033 .min_w(min_width)
8034 .max_w(max_width)
8035 .flex_1()
8036 .elevation_2(cx)
8037 .border_color(cx.theme().colors().border)
8038 .child(
8039 div()
8040 .flex_1()
8041 .py_1()
8042 .px_2()
8043 .overflow_hidden()
8044 .child(completion),
8045 )
8046 .when_some(accept_keystroke, |el, accept_keystroke| {
8047 if !accept_keystroke.modifiers.modified() {
8048 return el;
8049 }
8050
8051 el.child(
8052 h_flex()
8053 .h_full()
8054 .border_l_1()
8055 .rounded_r_lg()
8056 .border_color(cx.theme().colors().border)
8057 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8058 .gap_1()
8059 .py_1()
8060 .px_2()
8061 .child(
8062 h_flex()
8063 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8064 .when(is_platform_style_mac, |parent| parent.gap_1())
8065 .child(h_flex().children(ui::render_modifiers(
8066 &accept_keystroke.modifiers,
8067 PlatformStyle::platform(),
8068 Some(if !has_completion {
8069 Color::Muted
8070 } else {
8071 Color::Default
8072 }),
8073 None,
8074 false,
8075 ))),
8076 )
8077 .child(Label::new("Preview").into_any_element())
8078 .opacity(if has_completion { 1.0 } else { 0.4 }),
8079 )
8080 })
8081 .into_any(),
8082 )
8083 }
8084
8085 fn render_edit_prediction_cursor_popover_preview(
8086 &self,
8087 completion: &InlineCompletionState,
8088 cursor_point: Point,
8089 style: &EditorStyle,
8090 cx: &mut Context<Editor>,
8091 ) -> Option<Div> {
8092 use text::ToPoint as _;
8093
8094 fn render_relative_row_jump(
8095 prefix: impl Into<String>,
8096 current_row: u32,
8097 target_row: u32,
8098 ) -> Div {
8099 let (row_diff, arrow) = if target_row < current_row {
8100 (current_row - target_row, IconName::ArrowUp)
8101 } else {
8102 (target_row - current_row, IconName::ArrowDown)
8103 };
8104
8105 h_flex()
8106 .child(
8107 Label::new(format!("{}{}", prefix.into(), row_diff))
8108 .color(Color::Muted)
8109 .size(LabelSize::Small),
8110 )
8111 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
8112 }
8113
8114 match &completion.completion {
8115 InlineCompletion::Move {
8116 target, snapshot, ..
8117 } => Some(
8118 h_flex()
8119 .px_2()
8120 .gap_2()
8121 .flex_1()
8122 .child(
8123 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
8124 Icon::new(IconName::ZedPredictDown)
8125 } else {
8126 Icon::new(IconName::ZedPredictUp)
8127 },
8128 )
8129 .child(Label::new("Jump to Edit")),
8130 ),
8131
8132 InlineCompletion::Edit {
8133 edits,
8134 edit_preview,
8135 snapshot,
8136 display_mode: _,
8137 } => {
8138 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
8139
8140 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
8141 &snapshot,
8142 &edits,
8143 edit_preview.as_ref()?,
8144 true,
8145 cx,
8146 )
8147 .first_line_preview();
8148
8149 let styled_text = gpui::StyledText::new(highlighted_edits.text)
8150 .with_default_highlights(&style.text, highlighted_edits.highlights);
8151
8152 let preview = h_flex()
8153 .gap_1()
8154 .min_w_16()
8155 .child(styled_text)
8156 .when(has_more_lines, |parent| parent.child("…"));
8157
8158 let left = if first_edit_row != cursor_point.row {
8159 render_relative_row_jump("", cursor_point.row, first_edit_row)
8160 .into_any_element()
8161 } else {
8162 Icon::new(IconName::ZedPredict).into_any_element()
8163 };
8164
8165 Some(
8166 h_flex()
8167 .h_full()
8168 .flex_1()
8169 .gap_2()
8170 .pr_1()
8171 .overflow_x_hidden()
8172 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8173 .child(left)
8174 .child(preview),
8175 )
8176 }
8177 }
8178 }
8179
8180 fn render_context_menu(
8181 &self,
8182 style: &EditorStyle,
8183 max_height_in_lines: u32,
8184 window: &mut Window,
8185 cx: &mut Context<Editor>,
8186 ) -> Option<AnyElement> {
8187 let menu = self.context_menu.borrow();
8188 let menu = menu.as_ref()?;
8189 if !menu.visible() {
8190 return None;
8191 };
8192 Some(menu.render(style, max_height_in_lines, window, cx))
8193 }
8194
8195 fn render_context_menu_aside(
8196 &mut self,
8197 max_size: Size<Pixels>,
8198 window: &mut Window,
8199 cx: &mut Context<Editor>,
8200 ) -> Option<AnyElement> {
8201 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
8202 if menu.visible() {
8203 menu.render_aside(self, max_size, window, cx)
8204 } else {
8205 None
8206 }
8207 })
8208 }
8209
8210 fn hide_context_menu(
8211 &mut self,
8212 window: &mut Window,
8213 cx: &mut Context<Self>,
8214 ) -> Option<CodeContextMenu> {
8215 cx.notify();
8216 self.completion_tasks.clear();
8217 let context_menu = self.context_menu.borrow_mut().take();
8218 self.stale_inline_completion_in_menu.take();
8219 self.update_visible_inline_completion(window, cx);
8220 context_menu
8221 }
8222
8223 fn show_snippet_choices(
8224 &mut self,
8225 choices: &Vec<String>,
8226 selection: Range<Anchor>,
8227 cx: &mut Context<Self>,
8228 ) {
8229 if selection.start.buffer_id.is_none() {
8230 return;
8231 }
8232 let buffer_id = selection.start.buffer_id.unwrap();
8233 let buffer = self.buffer().read(cx).buffer(buffer_id);
8234 let id = post_inc(&mut self.next_completion_id);
8235 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
8236
8237 if let Some(buffer) = buffer {
8238 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8239 CompletionsMenu::new_snippet_choices(
8240 id,
8241 true,
8242 choices,
8243 selection,
8244 buffer,
8245 snippet_sort_order,
8246 ),
8247 ));
8248 }
8249 }
8250
8251 pub fn insert_snippet(
8252 &mut self,
8253 insertion_ranges: &[Range<usize>],
8254 snippet: Snippet,
8255 window: &mut Window,
8256 cx: &mut Context<Self>,
8257 ) -> Result<()> {
8258 struct Tabstop<T> {
8259 is_end_tabstop: bool,
8260 ranges: Vec<Range<T>>,
8261 choices: Option<Vec<String>>,
8262 }
8263
8264 let tabstops = self.buffer.update(cx, |buffer, cx| {
8265 let snippet_text: Arc<str> = snippet.text.clone().into();
8266 let edits = insertion_ranges
8267 .iter()
8268 .cloned()
8269 .map(|range| (range, snippet_text.clone()));
8270 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8271
8272 let snapshot = &*buffer.read(cx);
8273 let snippet = &snippet;
8274 snippet
8275 .tabstops
8276 .iter()
8277 .map(|tabstop| {
8278 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8279 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8280 });
8281 let mut tabstop_ranges = tabstop
8282 .ranges
8283 .iter()
8284 .flat_map(|tabstop_range| {
8285 let mut delta = 0_isize;
8286 insertion_ranges.iter().map(move |insertion_range| {
8287 let insertion_start = insertion_range.start as isize + delta;
8288 delta +=
8289 snippet.text.len() as isize - insertion_range.len() as isize;
8290
8291 let start = ((insertion_start + tabstop_range.start) as usize)
8292 .min(snapshot.len());
8293 let end = ((insertion_start + tabstop_range.end) as usize)
8294 .min(snapshot.len());
8295 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8296 })
8297 })
8298 .collect::<Vec<_>>();
8299 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8300
8301 Tabstop {
8302 is_end_tabstop,
8303 ranges: tabstop_ranges,
8304 choices: tabstop.choices.clone(),
8305 }
8306 })
8307 .collect::<Vec<_>>()
8308 });
8309 if let Some(tabstop) = tabstops.first() {
8310 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8311 s.select_ranges(tabstop.ranges.iter().cloned());
8312 });
8313
8314 if let Some(choices) = &tabstop.choices {
8315 if let Some(selection) = tabstop.ranges.first() {
8316 self.show_snippet_choices(choices, selection.clone(), cx)
8317 }
8318 }
8319
8320 // If we're already at the last tabstop and it's at the end of the snippet,
8321 // we're done, we don't need to keep the state around.
8322 if !tabstop.is_end_tabstop {
8323 let choices = tabstops
8324 .iter()
8325 .map(|tabstop| tabstop.choices.clone())
8326 .collect();
8327
8328 let ranges = tabstops
8329 .into_iter()
8330 .map(|tabstop| tabstop.ranges)
8331 .collect::<Vec<_>>();
8332
8333 self.snippet_stack.push(SnippetState {
8334 active_index: 0,
8335 ranges,
8336 choices,
8337 });
8338 }
8339
8340 // Check whether the just-entered snippet ends with an auto-closable bracket.
8341 if self.autoclose_regions.is_empty() {
8342 let snapshot = self.buffer.read(cx).snapshot(cx);
8343 for selection in &mut self.selections.all::<Point>(cx) {
8344 let selection_head = selection.head();
8345 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8346 continue;
8347 };
8348
8349 let mut bracket_pair = None;
8350 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8351 let prev_chars = snapshot
8352 .reversed_chars_at(selection_head)
8353 .collect::<String>();
8354 for (pair, enabled) in scope.brackets() {
8355 if enabled
8356 && pair.close
8357 && prev_chars.starts_with(pair.start.as_str())
8358 && next_chars.starts_with(pair.end.as_str())
8359 {
8360 bracket_pair = Some(pair.clone());
8361 break;
8362 }
8363 }
8364 if let Some(pair) = bracket_pair {
8365 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8366 let autoclose_enabled =
8367 self.use_autoclose && snapshot_settings.use_autoclose;
8368 if autoclose_enabled {
8369 let start = snapshot.anchor_after(selection_head);
8370 let end = snapshot.anchor_after(selection_head);
8371 self.autoclose_regions.push(AutocloseRegion {
8372 selection_id: selection.id,
8373 range: start..end,
8374 pair,
8375 });
8376 }
8377 }
8378 }
8379 }
8380 }
8381 Ok(())
8382 }
8383
8384 pub fn move_to_next_snippet_tabstop(
8385 &mut self,
8386 window: &mut Window,
8387 cx: &mut Context<Self>,
8388 ) -> bool {
8389 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8390 }
8391
8392 pub fn move_to_prev_snippet_tabstop(
8393 &mut self,
8394 window: &mut Window,
8395 cx: &mut Context<Self>,
8396 ) -> bool {
8397 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8398 }
8399
8400 pub fn move_to_snippet_tabstop(
8401 &mut self,
8402 bias: Bias,
8403 window: &mut Window,
8404 cx: &mut Context<Self>,
8405 ) -> bool {
8406 if let Some(mut snippet) = self.snippet_stack.pop() {
8407 match bias {
8408 Bias::Left => {
8409 if snippet.active_index > 0 {
8410 snippet.active_index -= 1;
8411 } else {
8412 self.snippet_stack.push(snippet);
8413 return false;
8414 }
8415 }
8416 Bias::Right => {
8417 if snippet.active_index + 1 < snippet.ranges.len() {
8418 snippet.active_index += 1;
8419 } else {
8420 self.snippet_stack.push(snippet);
8421 return false;
8422 }
8423 }
8424 }
8425 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8426 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8427 s.select_anchor_ranges(current_ranges.iter().cloned())
8428 });
8429
8430 if let Some(choices) = &snippet.choices[snippet.active_index] {
8431 if let Some(selection) = current_ranges.first() {
8432 self.show_snippet_choices(&choices, selection.clone(), cx);
8433 }
8434 }
8435
8436 // If snippet state is not at the last tabstop, push it back on the stack
8437 if snippet.active_index + 1 < snippet.ranges.len() {
8438 self.snippet_stack.push(snippet);
8439 }
8440 return true;
8441 }
8442 }
8443
8444 false
8445 }
8446
8447 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8448 self.transact(window, cx, |this, window, cx| {
8449 this.select_all(&SelectAll, window, cx);
8450 this.insert("", window, cx);
8451 });
8452 }
8453
8454 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8455 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8456 self.transact(window, cx, |this, window, cx| {
8457 this.select_autoclose_pair(window, cx);
8458 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8459 if !this.linked_edit_ranges.is_empty() {
8460 let selections = this.selections.all::<MultiBufferPoint>(cx);
8461 let snapshot = this.buffer.read(cx).snapshot(cx);
8462
8463 for selection in selections.iter() {
8464 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8465 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8466 if selection_start.buffer_id != selection_end.buffer_id {
8467 continue;
8468 }
8469 if let Some(ranges) =
8470 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8471 {
8472 for (buffer, entries) in ranges {
8473 linked_ranges.entry(buffer).or_default().extend(entries);
8474 }
8475 }
8476 }
8477 }
8478
8479 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8480 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8481 for selection in &mut selections {
8482 if selection.is_empty() {
8483 let old_head = selection.head();
8484 let mut new_head =
8485 movement::left(&display_map, old_head.to_display_point(&display_map))
8486 .to_point(&display_map);
8487 if let Some((buffer, line_buffer_range)) = display_map
8488 .buffer_snapshot
8489 .buffer_line_for_row(MultiBufferRow(old_head.row))
8490 {
8491 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8492 let indent_len = match indent_size.kind {
8493 IndentKind::Space => {
8494 buffer.settings_at(line_buffer_range.start, cx).tab_size
8495 }
8496 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8497 };
8498 if old_head.column <= indent_size.len && old_head.column > 0 {
8499 let indent_len = indent_len.get();
8500 new_head = cmp::min(
8501 new_head,
8502 MultiBufferPoint::new(
8503 old_head.row,
8504 ((old_head.column - 1) / indent_len) * indent_len,
8505 ),
8506 );
8507 }
8508 }
8509
8510 selection.set_head(new_head, SelectionGoal::None);
8511 }
8512 }
8513
8514 this.signature_help_state.set_backspace_pressed(true);
8515 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8516 s.select(selections)
8517 });
8518 this.insert("", window, cx);
8519 let empty_str: Arc<str> = Arc::from("");
8520 for (buffer, edits) in linked_ranges {
8521 let snapshot = buffer.read(cx).snapshot();
8522 use text::ToPoint as TP;
8523
8524 let edits = edits
8525 .into_iter()
8526 .map(|range| {
8527 let end_point = TP::to_point(&range.end, &snapshot);
8528 let mut start_point = TP::to_point(&range.start, &snapshot);
8529
8530 if end_point == start_point {
8531 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8532 .saturating_sub(1);
8533 start_point =
8534 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8535 };
8536
8537 (start_point..end_point, empty_str.clone())
8538 })
8539 .sorted_by_key(|(range, _)| range.start)
8540 .collect::<Vec<_>>();
8541 buffer.update(cx, |this, cx| {
8542 this.edit(edits, None, cx);
8543 })
8544 }
8545 this.refresh_inline_completion(true, false, window, cx);
8546 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8547 });
8548 }
8549
8550 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8551 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8552 self.transact(window, cx, |this, window, cx| {
8553 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8554 s.move_with(|map, selection| {
8555 if selection.is_empty() {
8556 let cursor = movement::right(map, selection.head());
8557 selection.end = cursor;
8558 selection.reversed = true;
8559 selection.goal = SelectionGoal::None;
8560 }
8561 })
8562 });
8563 this.insert("", window, cx);
8564 this.refresh_inline_completion(true, false, window, cx);
8565 });
8566 }
8567
8568 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8569 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8570 if self.move_to_prev_snippet_tabstop(window, cx) {
8571 return;
8572 }
8573 self.outdent(&Outdent, window, cx);
8574 }
8575
8576 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8577 if self.move_to_next_snippet_tabstop(window, cx) {
8578 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8579 return;
8580 }
8581 if self.read_only(cx) {
8582 return;
8583 }
8584 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8585 let mut selections = self.selections.all_adjusted(cx);
8586 let buffer = self.buffer.read(cx);
8587 let snapshot = buffer.snapshot(cx);
8588 let rows_iter = selections.iter().map(|s| s.head().row);
8589 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8590
8591 let mut edits = Vec::new();
8592 let mut prev_edited_row = 0;
8593 let mut row_delta = 0;
8594 for selection in &mut selections {
8595 if selection.start.row != prev_edited_row {
8596 row_delta = 0;
8597 }
8598 prev_edited_row = selection.end.row;
8599
8600 // If the selection is non-empty, then increase the indentation of the selected lines.
8601 if !selection.is_empty() {
8602 row_delta =
8603 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8604 continue;
8605 }
8606
8607 // If the selection is empty and the cursor is in the leading whitespace before the
8608 // suggested indentation, then auto-indent the line.
8609 let cursor = selection.head();
8610 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8611 if let Some(suggested_indent) =
8612 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8613 {
8614 if cursor.column < suggested_indent.len
8615 && cursor.column <= current_indent.len
8616 && current_indent.len <= suggested_indent.len
8617 {
8618 selection.start = Point::new(cursor.row, suggested_indent.len);
8619 selection.end = selection.start;
8620 if row_delta == 0 {
8621 edits.extend(Buffer::edit_for_indent_size_adjustment(
8622 cursor.row,
8623 current_indent,
8624 suggested_indent,
8625 ));
8626 row_delta = suggested_indent.len - current_indent.len;
8627 }
8628 continue;
8629 }
8630 }
8631
8632 // Otherwise, insert a hard or soft tab.
8633 let settings = buffer.language_settings_at(cursor, cx);
8634 let tab_size = if settings.hard_tabs {
8635 IndentSize::tab()
8636 } else {
8637 let tab_size = settings.tab_size.get();
8638 let indent_remainder = snapshot
8639 .text_for_range(Point::new(cursor.row, 0)..cursor)
8640 .flat_map(str::chars)
8641 .fold(row_delta % tab_size, |counter: u32, c| {
8642 if c == '\t' {
8643 0
8644 } else {
8645 (counter + 1) % tab_size
8646 }
8647 });
8648
8649 let chars_to_next_tab_stop = tab_size - indent_remainder;
8650 IndentSize::spaces(chars_to_next_tab_stop)
8651 };
8652 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8653 selection.end = selection.start;
8654 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8655 row_delta += tab_size.len;
8656 }
8657
8658 self.transact(window, cx, |this, window, cx| {
8659 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8660 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8661 s.select(selections)
8662 });
8663 this.refresh_inline_completion(true, false, window, cx);
8664 });
8665 }
8666
8667 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8668 if self.read_only(cx) {
8669 return;
8670 }
8671 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8672 let mut selections = self.selections.all::<Point>(cx);
8673 let mut prev_edited_row = 0;
8674 let mut row_delta = 0;
8675 let mut edits = Vec::new();
8676 let buffer = self.buffer.read(cx);
8677 let snapshot = buffer.snapshot(cx);
8678 for selection in &mut selections {
8679 if selection.start.row != prev_edited_row {
8680 row_delta = 0;
8681 }
8682 prev_edited_row = selection.end.row;
8683
8684 row_delta =
8685 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8686 }
8687
8688 self.transact(window, cx, |this, window, cx| {
8689 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8690 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8691 s.select(selections)
8692 });
8693 });
8694 }
8695
8696 fn indent_selection(
8697 buffer: &MultiBuffer,
8698 snapshot: &MultiBufferSnapshot,
8699 selection: &mut Selection<Point>,
8700 edits: &mut Vec<(Range<Point>, String)>,
8701 delta_for_start_row: u32,
8702 cx: &App,
8703 ) -> u32 {
8704 let settings = buffer.language_settings_at(selection.start, cx);
8705 let tab_size = settings.tab_size.get();
8706 let indent_kind = if settings.hard_tabs {
8707 IndentKind::Tab
8708 } else {
8709 IndentKind::Space
8710 };
8711 let mut start_row = selection.start.row;
8712 let mut end_row = selection.end.row + 1;
8713
8714 // If a selection ends at the beginning of a line, don't indent
8715 // that last line.
8716 if selection.end.column == 0 && selection.end.row > selection.start.row {
8717 end_row -= 1;
8718 }
8719
8720 // Avoid re-indenting a row that has already been indented by a
8721 // previous selection, but still update this selection's column
8722 // to reflect that indentation.
8723 if delta_for_start_row > 0 {
8724 start_row += 1;
8725 selection.start.column += delta_for_start_row;
8726 if selection.end.row == selection.start.row {
8727 selection.end.column += delta_for_start_row;
8728 }
8729 }
8730
8731 let mut delta_for_end_row = 0;
8732 let has_multiple_rows = start_row + 1 != end_row;
8733 for row in start_row..end_row {
8734 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8735 let indent_delta = match (current_indent.kind, indent_kind) {
8736 (IndentKind::Space, IndentKind::Space) => {
8737 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8738 IndentSize::spaces(columns_to_next_tab_stop)
8739 }
8740 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8741 (_, IndentKind::Tab) => IndentSize::tab(),
8742 };
8743
8744 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8745 0
8746 } else {
8747 selection.start.column
8748 };
8749 let row_start = Point::new(row, start);
8750 edits.push((
8751 row_start..row_start,
8752 indent_delta.chars().collect::<String>(),
8753 ));
8754
8755 // Update this selection's endpoints to reflect the indentation.
8756 if row == selection.start.row {
8757 selection.start.column += indent_delta.len;
8758 }
8759 if row == selection.end.row {
8760 selection.end.column += indent_delta.len;
8761 delta_for_end_row = indent_delta.len;
8762 }
8763 }
8764
8765 if selection.start.row == selection.end.row {
8766 delta_for_start_row + delta_for_end_row
8767 } else {
8768 delta_for_end_row
8769 }
8770 }
8771
8772 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8773 if self.read_only(cx) {
8774 return;
8775 }
8776 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8777 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8778 let selections = self.selections.all::<Point>(cx);
8779 let mut deletion_ranges = Vec::new();
8780 let mut last_outdent = None;
8781 {
8782 let buffer = self.buffer.read(cx);
8783 let snapshot = buffer.snapshot(cx);
8784 for selection in &selections {
8785 let settings = buffer.language_settings_at(selection.start, cx);
8786 let tab_size = settings.tab_size.get();
8787 let mut rows = selection.spanned_rows(false, &display_map);
8788
8789 // Avoid re-outdenting a row that has already been outdented by a
8790 // previous selection.
8791 if let Some(last_row) = last_outdent {
8792 if last_row == rows.start {
8793 rows.start = rows.start.next_row();
8794 }
8795 }
8796 let has_multiple_rows = rows.len() > 1;
8797 for row in rows.iter_rows() {
8798 let indent_size = snapshot.indent_size_for_line(row);
8799 if indent_size.len > 0 {
8800 let deletion_len = match indent_size.kind {
8801 IndentKind::Space => {
8802 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8803 if columns_to_prev_tab_stop == 0 {
8804 tab_size
8805 } else {
8806 columns_to_prev_tab_stop
8807 }
8808 }
8809 IndentKind::Tab => 1,
8810 };
8811 let start = if has_multiple_rows
8812 || deletion_len > selection.start.column
8813 || indent_size.len < selection.start.column
8814 {
8815 0
8816 } else {
8817 selection.start.column - deletion_len
8818 };
8819 deletion_ranges.push(
8820 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8821 );
8822 last_outdent = Some(row);
8823 }
8824 }
8825 }
8826 }
8827
8828 self.transact(window, cx, |this, window, cx| {
8829 this.buffer.update(cx, |buffer, cx| {
8830 let empty_str: Arc<str> = Arc::default();
8831 buffer.edit(
8832 deletion_ranges
8833 .into_iter()
8834 .map(|range| (range, empty_str.clone())),
8835 None,
8836 cx,
8837 );
8838 });
8839 let selections = this.selections.all::<usize>(cx);
8840 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8841 s.select(selections)
8842 });
8843 });
8844 }
8845
8846 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8847 if self.read_only(cx) {
8848 return;
8849 }
8850 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8851 let selections = self
8852 .selections
8853 .all::<usize>(cx)
8854 .into_iter()
8855 .map(|s| s.range());
8856
8857 self.transact(window, cx, |this, window, cx| {
8858 this.buffer.update(cx, |buffer, cx| {
8859 buffer.autoindent_ranges(selections, cx);
8860 });
8861 let selections = this.selections.all::<usize>(cx);
8862 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8863 s.select(selections)
8864 });
8865 });
8866 }
8867
8868 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8869 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8870 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8871 let selections = self.selections.all::<Point>(cx);
8872
8873 let mut new_cursors = Vec::new();
8874 let mut edit_ranges = Vec::new();
8875 let mut selections = selections.iter().peekable();
8876 while let Some(selection) = selections.next() {
8877 let mut rows = selection.spanned_rows(false, &display_map);
8878 let goal_display_column = selection.head().to_display_point(&display_map).column();
8879
8880 // Accumulate contiguous regions of rows that we want to delete.
8881 while let Some(next_selection) = selections.peek() {
8882 let next_rows = next_selection.spanned_rows(false, &display_map);
8883 if next_rows.start <= rows.end {
8884 rows.end = next_rows.end;
8885 selections.next().unwrap();
8886 } else {
8887 break;
8888 }
8889 }
8890
8891 let buffer = &display_map.buffer_snapshot;
8892 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8893 let edit_end;
8894 let cursor_buffer_row;
8895 if buffer.max_point().row >= rows.end.0 {
8896 // If there's a line after the range, delete the \n from the end of the row range
8897 // and position the cursor on the next line.
8898 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8899 cursor_buffer_row = rows.end;
8900 } else {
8901 // If there isn't a line after the range, delete the \n from the line before the
8902 // start of the row range and position the cursor there.
8903 edit_start = edit_start.saturating_sub(1);
8904 edit_end = buffer.len();
8905 cursor_buffer_row = rows.start.previous_row();
8906 }
8907
8908 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8909 *cursor.column_mut() =
8910 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8911
8912 new_cursors.push((
8913 selection.id,
8914 buffer.anchor_after(cursor.to_point(&display_map)),
8915 ));
8916 edit_ranges.push(edit_start..edit_end);
8917 }
8918
8919 self.transact(window, cx, |this, window, cx| {
8920 let buffer = this.buffer.update(cx, |buffer, cx| {
8921 let empty_str: Arc<str> = Arc::default();
8922 buffer.edit(
8923 edit_ranges
8924 .into_iter()
8925 .map(|range| (range, empty_str.clone())),
8926 None,
8927 cx,
8928 );
8929 buffer.snapshot(cx)
8930 });
8931 let new_selections = new_cursors
8932 .into_iter()
8933 .map(|(id, cursor)| {
8934 let cursor = cursor.to_point(&buffer);
8935 Selection {
8936 id,
8937 start: cursor,
8938 end: cursor,
8939 reversed: false,
8940 goal: SelectionGoal::None,
8941 }
8942 })
8943 .collect();
8944
8945 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8946 s.select(new_selections);
8947 });
8948 });
8949 }
8950
8951 pub fn join_lines_impl(
8952 &mut self,
8953 insert_whitespace: bool,
8954 window: &mut Window,
8955 cx: &mut Context<Self>,
8956 ) {
8957 if self.read_only(cx) {
8958 return;
8959 }
8960 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8961 for selection in self.selections.all::<Point>(cx) {
8962 let start = MultiBufferRow(selection.start.row);
8963 // Treat single line selections as if they include the next line. Otherwise this action
8964 // would do nothing for single line selections individual cursors.
8965 let end = if selection.start.row == selection.end.row {
8966 MultiBufferRow(selection.start.row + 1)
8967 } else {
8968 MultiBufferRow(selection.end.row)
8969 };
8970
8971 if let Some(last_row_range) = row_ranges.last_mut() {
8972 if start <= last_row_range.end {
8973 last_row_range.end = end;
8974 continue;
8975 }
8976 }
8977 row_ranges.push(start..end);
8978 }
8979
8980 let snapshot = self.buffer.read(cx).snapshot(cx);
8981 let mut cursor_positions = Vec::new();
8982 for row_range in &row_ranges {
8983 let anchor = snapshot.anchor_before(Point::new(
8984 row_range.end.previous_row().0,
8985 snapshot.line_len(row_range.end.previous_row()),
8986 ));
8987 cursor_positions.push(anchor..anchor);
8988 }
8989
8990 self.transact(window, cx, |this, window, cx| {
8991 for row_range in row_ranges.into_iter().rev() {
8992 for row in row_range.iter_rows().rev() {
8993 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8994 let next_line_row = row.next_row();
8995 let indent = snapshot.indent_size_for_line(next_line_row);
8996 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8997
8998 let replace =
8999 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
9000 " "
9001 } else {
9002 ""
9003 };
9004
9005 this.buffer.update(cx, |buffer, cx| {
9006 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
9007 });
9008 }
9009 }
9010
9011 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9012 s.select_anchor_ranges(cursor_positions)
9013 });
9014 });
9015 }
9016
9017 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
9018 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9019 self.join_lines_impl(true, window, cx);
9020 }
9021
9022 pub fn sort_lines_case_sensitive(
9023 &mut self,
9024 _: &SortLinesCaseSensitive,
9025 window: &mut Window,
9026 cx: &mut Context<Self>,
9027 ) {
9028 self.manipulate_lines(window, cx, |lines| lines.sort())
9029 }
9030
9031 pub fn sort_lines_case_insensitive(
9032 &mut self,
9033 _: &SortLinesCaseInsensitive,
9034 window: &mut Window,
9035 cx: &mut Context<Self>,
9036 ) {
9037 self.manipulate_lines(window, cx, |lines| {
9038 lines.sort_by_key(|line| line.to_lowercase())
9039 })
9040 }
9041
9042 pub fn unique_lines_case_insensitive(
9043 &mut self,
9044 _: &UniqueLinesCaseInsensitive,
9045 window: &mut Window,
9046 cx: &mut Context<Self>,
9047 ) {
9048 self.manipulate_lines(window, cx, |lines| {
9049 let mut seen = HashSet::default();
9050 lines.retain(|line| seen.insert(line.to_lowercase()));
9051 })
9052 }
9053
9054 pub fn unique_lines_case_sensitive(
9055 &mut self,
9056 _: &UniqueLinesCaseSensitive,
9057 window: &mut Window,
9058 cx: &mut Context<Self>,
9059 ) {
9060 self.manipulate_lines(window, cx, |lines| {
9061 let mut seen = HashSet::default();
9062 lines.retain(|line| seen.insert(*line));
9063 })
9064 }
9065
9066 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
9067 let Some(project) = self.project.clone() else {
9068 return;
9069 };
9070 self.reload(project, window, cx)
9071 .detach_and_notify_err(window, cx);
9072 }
9073
9074 pub fn restore_file(
9075 &mut self,
9076 _: &::git::RestoreFile,
9077 window: &mut Window,
9078 cx: &mut Context<Self>,
9079 ) {
9080 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9081 let mut buffer_ids = HashSet::default();
9082 let snapshot = self.buffer().read(cx).snapshot(cx);
9083 for selection in self.selections.all::<usize>(cx) {
9084 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
9085 }
9086
9087 let buffer = self.buffer().read(cx);
9088 let ranges = buffer_ids
9089 .into_iter()
9090 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
9091 .collect::<Vec<_>>();
9092
9093 self.restore_hunks_in_ranges(ranges, window, cx);
9094 }
9095
9096 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
9097 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9098 let selections = self
9099 .selections
9100 .all(cx)
9101 .into_iter()
9102 .map(|s| s.range())
9103 .collect();
9104 self.restore_hunks_in_ranges(selections, window, cx);
9105 }
9106
9107 pub fn restore_hunks_in_ranges(
9108 &mut self,
9109 ranges: Vec<Range<Point>>,
9110 window: &mut Window,
9111 cx: &mut Context<Editor>,
9112 ) {
9113 let mut revert_changes = HashMap::default();
9114 let chunk_by = self
9115 .snapshot(window, cx)
9116 .hunks_for_ranges(ranges)
9117 .into_iter()
9118 .chunk_by(|hunk| hunk.buffer_id);
9119 for (buffer_id, hunks) in &chunk_by {
9120 let hunks = hunks.collect::<Vec<_>>();
9121 for hunk in &hunks {
9122 self.prepare_restore_change(&mut revert_changes, hunk, cx);
9123 }
9124 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
9125 }
9126 drop(chunk_by);
9127 if !revert_changes.is_empty() {
9128 self.transact(window, cx, |editor, window, cx| {
9129 editor.restore(revert_changes, window, cx);
9130 });
9131 }
9132 }
9133
9134 pub fn open_active_item_in_terminal(
9135 &mut self,
9136 _: &OpenInTerminal,
9137 window: &mut Window,
9138 cx: &mut Context<Self>,
9139 ) {
9140 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
9141 let project_path = buffer.read(cx).project_path(cx)?;
9142 let project = self.project.as_ref()?.read(cx);
9143 let entry = project.entry_for_path(&project_path, cx)?;
9144 let parent = match &entry.canonical_path {
9145 Some(canonical_path) => canonical_path.to_path_buf(),
9146 None => project.absolute_path(&project_path, cx)?,
9147 }
9148 .parent()?
9149 .to_path_buf();
9150 Some(parent)
9151 }) {
9152 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
9153 }
9154 }
9155
9156 fn set_breakpoint_context_menu(
9157 &mut self,
9158 display_row: DisplayRow,
9159 position: Option<Anchor>,
9160 clicked_point: gpui::Point<Pixels>,
9161 window: &mut Window,
9162 cx: &mut Context<Self>,
9163 ) {
9164 if !cx.has_flag::<DebuggerFeatureFlag>() {
9165 return;
9166 }
9167 let source = self
9168 .buffer
9169 .read(cx)
9170 .snapshot(cx)
9171 .anchor_before(Point::new(display_row.0, 0u32));
9172
9173 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
9174
9175 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
9176 self,
9177 source,
9178 clicked_point,
9179 context_menu,
9180 window,
9181 cx,
9182 );
9183 }
9184
9185 fn add_edit_breakpoint_block(
9186 &mut self,
9187 anchor: Anchor,
9188 breakpoint: &Breakpoint,
9189 edit_action: BreakpointPromptEditAction,
9190 window: &mut Window,
9191 cx: &mut Context<Self>,
9192 ) {
9193 let weak_editor = cx.weak_entity();
9194 let bp_prompt = cx.new(|cx| {
9195 BreakpointPromptEditor::new(
9196 weak_editor,
9197 anchor,
9198 breakpoint.clone(),
9199 edit_action,
9200 window,
9201 cx,
9202 )
9203 });
9204
9205 let height = bp_prompt.update(cx, |this, cx| {
9206 this.prompt
9207 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
9208 });
9209 let cloned_prompt = bp_prompt.clone();
9210 let blocks = vec![BlockProperties {
9211 style: BlockStyle::Sticky,
9212 placement: BlockPlacement::Above(anchor),
9213 height: Some(height),
9214 render: Arc::new(move |cx| {
9215 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
9216 cloned_prompt.clone().into_any_element()
9217 }),
9218 priority: 0,
9219 }];
9220
9221 let focus_handle = bp_prompt.focus_handle(cx);
9222 window.focus(&focus_handle);
9223
9224 let block_ids = self.insert_blocks(blocks, None, cx);
9225 bp_prompt.update(cx, |prompt, _| {
9226 prompt.add_block_ids(block_ids);
9227 });
9228 }
9229
9230 pub(crate) fn breakpoint_at_row(
9231 &self,
9232 row: u32,
9233 window: &mut Window,
9234 cx: &mut Context<Self>,
9235 ) -> Option<(Anchor, Breakpoint)> {
9236 let snapshot = self.snapshot(window, cx);
9237 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9238
9239 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9240 }
9241
9242 pub(crate) fn breakpoint_at_anchor(
9243 &self,
9244 breakpoint_position: Anchor,
9245 snapshot: &EditorSnapshot,
9246 cx: &mut Context<Self>,
9247 ) -> Option<(Anchor, Breakpoint)> {
9248 let project = self.project.clone()?;
9249
9250 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9251 snapshot
9252 .buffer_snapshot
9253 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9254 })?;
9255
9256 let enclosing_excerpt = breakpoint_position.excerpt_id;
9257 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9258 let buffer_snapshot = buffer.read(cx).snapshot();
9259
9260 let row = buffer_snapshot
9261 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9262 .row;
9263
9264 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9265 let anchor_end = snapshot
9266 .buffer_snapshot
9267 .anchor_after(Point::new(row, line_len));
9268
9269 let bp = self
9270 .breakpoint_store
9271 .as_ref()?
9272 .read_with(cx, |breakpoint_store, cx| {
9273 breakpoint_store
9274 .breakpoints(
9275 &buffer,
9276 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9277 &buffer_snapshot,
9278 cx,
9279 )
9280 .next()
9281 .and_then(|(anchor, bp)| {
9282 let breakpoint_row = buffer_snapshot
9283 .summary_for_anchor::<text::PointUtf16>(anchor)
9284 .row;
9285
9286 if breakpoint_row == row {
9287 snapshot
9288 .buffer_snapshot
9289 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9290 .map(|anchor| (anchor, bp.clone()))
9291 } else {
9292 None
9293 }
9294 })
9295 });
9296 bp
9297 }
9298
9299 pub fn edit_log_breakpoint(
9300 &mut self,
9301 _: &EditLogBreakpoint,
9302 window: &mut Window,
9303 cx: &mut Context<Self>,
9304 ) {
9305 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9306 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9307 message: None,
9308 state: BreakpointState::Enabled,
9309 condition: None,
9310 hit_condition: None,
9311 });
9312
9313 self.add_edit_breakpoint_block(
9314 anchor,
9315 &breakpoint,
9316 BreakpointPromptEditAction::Log,
9317 window,
9318 cx,
9319 );
9320 }
9321 }
9322
9323 fn breakpoints_at_cursors(
9324 &self,
9325 window: &mut Window,
9326 cx: &mut Context<Self>,
9327 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9328 let snapshot = self.snapshot(window, cx);
9329 let cursors = self
9330 .selections
9331 .disjoint_anchors()
9332 .into_iter()
9333 .map(|selection| {
9334 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9335
9336 let breakpoint_position = self
9337 .breakpoint_at_row(cursor_position.row, window, cx)
9338 .map(|bp| bp.0)
9339 .unwrap_or_else(|| {
9340 snapshot
9341 .display_snapshot
9342 .buffer_snapshot
9343 .anchor_after(Point::new(cursor_position.row, 0))
9344 });
9345
9346 let breakpoint = self
9347 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9348 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9349
9350 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9351 })
9352 // 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.
9353 .collect::<HashMap<Anchor, _>>();
9354
9355 cursors.into_iter().collect()
9356 }
9357
9358 pub fn enable_breakpoint(
9359 &mut self,
9360 _: &crate::actions::EnableBreakpoint,
9361 window: &mut Window,
9362 cx: &mut Context<Self>,
9363 ) {
9364 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9365 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9366 continue;
9367 };
9368 self.edit_breakpoint_at_anchor(
9369 anchor,
9370 breakpoint,
9371 BreakpointEditAction::InvertState,
9372 cx,
9373 );
9374 }
9375 }
9376
9377 pub fn disable_breakpoint(
9378 &mut self,
9379 _: &crate::actions::DisableBreakpoint,
9380 window: &mut Window,
9381 cx: &mut Context<Self>,
9382 ) {
9383 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9384 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9385 continue;
9386 };
9387 self.edit_breakpoint_at_anchor(
9388 anchor,
9389 breakpoint,
9390 BreakpointEditAction::InvertState,
9391 cx,
9392 );
9393 }
9394 }
9395
9396 pub fn toggle_breakpoint(
9397 &mut self,
9398 _: &crate::actions::ToggleBreakpoint,
9399 window: &mut Window,
9400 cx: &mut Context<Self>,
9401 ) {
9402 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9403 if let Some(breakpoint) = breakpoint {
9404 self.edit_breakpoint_at_anchor(
9405 anchor,
9406 breakpoint,
9407 BreakpointEditAction::Toggle,
9408 cx,
9409 );
9410 } else {
9411 self.edit_breakpoint_at_anchor(
9412 anchor,
9413 Breakpoint::new_standard(),
9414 BreakpointEditAction::Toggle,
9415 cx,
9416 );
9417 }
9418 }
9419 }
9420
9421 pub fn edit_breakpoint_at_anchor(
9422 &mut self,
9423 breakpoint_position: Anchor,
9424 breakpoint: Breakpoint,
9425 edit_action: BreakpointEditAction,
9426 cx: &mut Context<Self>,
9427 ) {
9428 let Some(breakpoint_store) = &self.breakpoint_store else {
9429 return;
9430 };
9431
9432 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9433 if breakpoint_position == Anchor::min() {
9434 self.buffer()
9435 .read(cx)
9436 .excerpt_buffer_ids()
9437 .into_iter()
9438 .next()
9439 } else {
9440 None
9441 }
9442 }) else {
9443 return;
9444 };
9445
9446 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9447 return;
9448 };
9449
9450 breakpoint_store.update(cx, |breakpoint_store, cx| {
9451 breakpoint_store.toggle_breakpoint(
9452 buffer,
9453 (breakpoint_position.text_anchor, breakpoint),
9454 edit_action,
9455 cx,
9456 );
9457 });
9458
9459 cx.notify();
9460 }
9461
9462 #[cfg(any(test, feature = "test-support"))]
9463 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9464 self.breakpoint_store.clone()
9465 }
9466
9467 pub fn prepare_restore_change(
9468 &self,
9469 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9470 hunk: &MultiBufferDiffHunk,
9471 cx: &mut App,
9472 ) -> Option<()> {
9473 if hunk.is_created_file() {
9474 return None;
9475 }
9476 let buffer = self.buffer.read(cx);
9477 let diff = buffer.diff_for(hunk.buffer_id)?;
9478 let buffer = buffer.buffer(hunk.buffer_id)?;
9479 let buffer = buffer.read(cx);
9480 let original_text = diff
9481 .read(cx)
9482 .base_text()
9483 .as_rope()
9484 .slice(hunk.diff_base_byte_range.clone());
9485 let buffer_snapshot = buffer.snapshot();
9486 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9487 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9488 probe
9489 .0
9490 .start
9491 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9492 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9493 }) {
9494 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9495 Some(())
9496 } else {
9497 None
9498 }
9499 }
9500
9501 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9502 self.manipulate_lines(window, cx, |lines| lines.reverse())
9503 }
9504
9505 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9506 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9507 }
9508
9509 fn manipulate_lines<Fn>(
9510 &mut self,
9511 window: &mut Window,
9512 cx: &mut Context<Self>,
9513 mut callback: Fn,
9514 ) where
9515 Fn: FnMut(&mut Vec<&str>),
9516 {
9517 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9518
9519 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9520 let buffer = self.buffer.read(cx).snapshot(cx);
9521
9522 let mut edits = Vec::new();
9523
9524 let selections = self.selections.all::<Point>(cx);
9525 let mut selections = selections.iter().peekable();
9526 let mut contiguous_row_selections = Vec::new();
9527 let mut new_selections = Vec::new();
9528 let mut added_lines = 0;
9529 let mut removed_lines = 0;
9530
9531 while let Some(selection) = selections.next() {
9532 let (start_row, end_row) = consume_contiguous_rows(
9533 &mut contiguous_row_selections,
9534 selection,
9535 &display_map,
9536 &mut selections,
9537 );
9538
9539 let start_point = Point::new(start_row.0, 0);
9540 let end_point = Point::new(
9541 end_row.previous_row().0,
9542 buffer.line_len(end_row.previous_row()),
9543 );
9544 let text = buffer
9545 .text_for_range(start_point..end_point)
9546 .collect::<String>();
9547
9548 let mut lines = text.split('\n').collect_vec();
9549
9550 let lines_before = lines.len();
9551 callback(&mut lines);
9552 let lines_after = lines.len();
9553
9554 edits.push((start_point..end_point, lines.join("\n")));
9555
9556 // Selections must change based on added and removed line count
9557 let start_row =
9558 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9559 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9560 new_selections.push(Selection {
9561 id: selection.id,
9562 start: start_row,
9563 end: end_row,
9564 goal: SelectionGoal::None,
9565 reversed: selection.reversed,
9566 });
9567
9568 if lines_after > lines_before {
9569 added_lines += lines_after - lines_before;
9570 } else if lines_before > lines_after {
9571 removed_lines += lines_before - lines_after;
9572 }
9573 }
9574
9575 self.transact(window, cx, |this, window, cx| {
9576 let buffer = this.buffer.update(cx, |buffer, cx| {
9577 buffer.edit(edits, None, cx);
9578 buffer.snapshot(cx)
9579 });
9580
9581 // Recalculate offsets on newly edited buffer
9582 let new_selections = new_selections
9583 .iter()
9584 .map(|s| {
9585 let start_point = Point::new(s.start.0, 0);
9586 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9587 Selection {
9588 id: s.id,
9589 start: buffer.point_to_offset(start_point),
9590 end: buffer.point_to_offset(end_point),
9591 goal: s.goal,
9592 reversed: s.reversed,
9593 }
9594 })
9595 .collect();
9596
9597 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9598 s.select(new_selections);
9599 });
9600
9601 this.request_autoscroll(Autoscroll::fit(), cx);
9602 });
9603 }
9604
9605 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9606 self.manipulate_text(window, cx, |text| {
9607 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9608 if has_upper_case_characters {
9609 text.to_lowercase()
9610 } else {
9611 text.to_uppercase()
9612 }
9613 })
9614 }
9615
9616 pub fn convert_to_upper_case(
9617 &mut self,
9618 _: &ConvertToUpperCase,
9619 window: &mut Window,
9620 cx: &mut Context<Self>,
9621 ) {
9622 self.manipulate_text(window, cx, |text| text.to_uppercase())
9623 }
9624
9625 pub fn convert_to_lower_case(
9626 &mut self,
9627 _: &ConvertToLowerCase,
9628 window: &mut Window,
9629 cx: &mut Context<Self>,
9630 ) {
9631 self.manipulate_text(window, cx, |text| text.to_lowercase())
9632 }
9633
9634 pub fn convert_to_title_case(
9635 &mut self,
9636 _: &ConvertToTitleCase,
9637 window: &mut Window,
9638 cx: &mut Context<Self>,
9639 ) {
9640 self.manipulate_text(window, cx, |text| {
9641 text.split('\n')
9642 .map(|line| line.to_case(Case::Title))
9643 .join("\n")
9644 })
9645 }
9646
9647 pub fn convert_to_snake_case(
9648 &mut self,
9649 _: &ConvertToSnakeCase,
9650 window: &mut Window,
9651 cx: &mut Context<Self>,
9652 ) {
9653 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9654 }
9655
9656 pub fn convert_to_kebab_case(
9657 &mut self,
9658 _: &ConvertToKebabCase,
9659 window: &mut Window,
9660 cx: &mut Context<Self>,
9661 ) {
9662 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9663 }
9664
9665 pub fn convert_to_upper_camel_case(
9666 &mut self,
9667 _: &ConvertToUpperCamelCase,
9668 window: &mut Window,
9669 cx: &mut Context<Self>,
9670 ) {
9671 self.manipulate_text(window, cx, |text| {
9672 text.split('\n')
9673 .map(|line| line.to_case(Case::UpperCamel))
9674 .join("\n")
9675 })
9676 }
9677
9678 pub fn convert_to_lower_camel_case(
9679 &mut self,
9680 _: &ConvertToLowerCamelCase,
9681 window: &mut Window,
9682 cx: &mut Context<Self>,
9683 ) {
9684 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9685 }
9686
9687 pub fn convert_to_opposite_case(
9688 &mut self,
9689 _: &ConvertToOppositeCase,
9690 window: &mut Window,
9691 cx: &mut Context<Self>,
9692 ) {
9693 self.manipulate_text(window, cx, |text| {
9694 text.chars()
9695 .fold(String::with_capacity(text.len()), |mut t, c| {
9696 if c.is_uppercase() {
9697 t.extend(c.to_lowercase());
9698 } else {
9699 t.extend(c.to_uppercase());
9700 }
9701 t
9702 })
9703 })
9704 }
9705
9706 pub fn convert_to_rot13(
9707 &mut self,
9708 _: &ConvertToRot13,
9709 window: &mut Window,
9710 cx: &mut Context<Self>,
9711 ) {
9712 self.manipulate_text(window, cx, |text| {
9713 text.chars()
9714 .map(|c| match c {
9715 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9716 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9717 _ => c,
9718 })
9719 .collect()
9720 })
9721 }
9722
9723 pub fn convert_to_rot47(
9724 &mut self,
9725 _: &ConvertToRot47,
9726 window: &mut Window,
9727 cx: &mut Context<Self>,
9728 ) {
9729 self.manipulate_text(window, cx, |text| {
9730 text.chars()
9731 .map(|c| {
9732 let code_point = c as u32;
9733 if code_point >= 33 && code_point <= 126 {
9734 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9735 }
9736 c
9737 })
9738 .collect()
9739 })
9740 }
9741
9742 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9743 where
9744 Fn: FnMut(&str) -> String,
9745 {
9746 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9747 let buffer = self.buffer.read(cx).snapshot(cx);
9748
9749 let mut new_selections = Vec::new();
9750 let mut edits = Vec::new();
9751 let mut selection_adjustment = 0i32;
9752
9753 for selection in self.selections.all::<usize>(cx) {
9754 let selection_is_empty = selection.is_empty();
9755
9756 let (start, end) = if selection_is_empty {
9757 let word_range = movement::surrounding_word(
9758 &display_map,
9759 selection.start.to_display_point(&display_map),
9760 );
9761 let start = word_range.start.to_offset(&display_map, Bias::Left);
9762 let end = word_range.end.to_offset(&display_map, Bias::Left);
9763 (start, end)
9764 } else {
9765 (selection.start, selection.end)
9766 };
9767
9768 let text = buffer.text_for_range(start..end).collect::<String>();
9769 let old_length = text.len() as i32;
9770 let text = callback(&text);
9771
9772 new_selections.push(Selection {
9773 start: (start as i32 - selection_adjustment) as usize,
9774 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9775 goal: SelectionGoal::None,
9776 ..selection
9777 });
9778
9779 selection_adjustment += old_length - text.len() as i32;
9780
9781 edits.push((start..end, text));
9782 }
9783
9784 self.transact(window, cx, |this, window, cx| {
9785 this.buffer.update(cx, |buffer, cx| {
9786 buffer.edit(edits, None, cx);
9787 });
9788
9789 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9790 s.select(new_selections);
9791 });
9792
9793 this.request_autoscroll(Autoscroll::fit(), cx);
9794 });
9795 }
9796
9797 pub fn duplicate(
9798 &mut self,
9799 upwards: bool,
9800 whole_lines: bool,
9801 window: &mut Window,
9802 cx: &mut Context<Self>,
9803 ) {
9804 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9805
9806 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9807 let buffer = &display_map.buffer_snapshot;
9808 let selections = self.selections.all::<Point>(cx);
9809
9810 let mut edits = Vec::new();
9811 let mut selections_iter = selections.iter().peekable();
9812 while let Some(selection) = selections_iter.next() {
9813 let mut rows = selection.spanned_rows(false, &display_map);
9814 // duplicate line-wise
9815 if whole_lines || selection.start == selection.end {
9816 // Avoid duplicating the same lines twice.
9817 while let Some(next_selection) = selections_iter.peek() {
9818 let next_rows = next_selection.spanned_rows(false, &display_map);
9819 if next_rows.start < rows.end {
9820 rows.end = next_rows.end;
9821 selections_iter.next().unwrap();
9822 } else {
9823 break;
9824 }
9825 }
9826
9827 // Copy the text from the selected row region and splice it either at the start
9828 // or end of the region.
9829 let start = Point::new(rows.start.0, 0);
9830 let end = Point::new(
9831 rows.end.previous_row().0,
9832 buffer.line_len(rows.end.previous_row()),
9833 );
9834 let text = buffer
9835 .text_for_range(start..end)
9836 .chain(Some("\n"))
9837 .collect::<String>();
9838 let insert_location = if upwards {
9839 Point::new(rows.end.0, 0)
9840 } else {
9841 start
9842 };
9843 edits.push((insert_location..insert_location, text));
9844 } else {
9845 // duplicate character-wise
9846 let start = selection.start;
9847 let end = selection.end;
9848 let text = buffer.text_for_range(start..end).collect::<String>();
9849 edits.push((selection.end..selection.end, text));
9850 }
9851 }
9852
9853 self.transact(window, cx, |this, _, cx| {
9854 this.buffer.update(cx, |buffer, cx| {
9855 buffer.edit(edits, None, cx);
9856 });
9857
9858 this.request_autoscroll(Autoscroll::fit(), cx);
9859 });
9860 }
9861
9862 pub fn duplicate_line_up(
9863 &mut self,
9864 _: &DuplicateLineUp,
9865 window: &mut Window,
9866 cx: &mut Context<Self>,
9867 ) {
9868 self.duplicate(true, true, window, cx);
9869 }
9870
9871 pub fn duplicate_line_down(
9872 &mut self,
9873 _: &DuplicateLineDown,
9874 window: &mut Window,
9875 cx: &mut Context<Self>,
9876 ) {
9877 self.duplicate(false, true, window, cx);
9878 }
9879
9880 pub fn duplicate_selection(
9881 &mut self,
9882 _: &DuplicateSelection,
9883 window: &mut Window,
9884 cx: &mut Context<Self>,
9885 ) {
9886 self.duplicate(false, false, window, cx);
9887 }
9888
9889 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9890 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9891
9892 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9893 let buffer = self.buffer.read(cx).snapshot(cx);
9894
9895 let mut edits = Vec::new();
9896 let mut unfold_ranges = Vec::new();
9897 let mut refold_creases = Vec::new();
9898
9899 let selections = self.selections.all::<Point>(cx);
9900 let mut selections = selections.iter().peekable();
9901 let mut contiguous_row_selections = Vec::new();
9902 let mut new_selections = Vec::new();
9903
9904 while let Some(selection) = selections.next() {
9905 // Find all the selections that span a contiguous row range
9906 let (start_row, end_row) = consume_contiguous_rows(
9907 &mut contiguous_row_selections,
9908 selection,
9909 &display_map,
9910 &mut selections,
9911 );
9912
9913 // Move the text spanned by the row range to be before the line preceding the row range
9914 if start_row.0 > 0 {
9915 let range_to_move = Point::new(
9916 start_row.previous_row().0,
9917 buffer.line_len(start_row.previous_row()),
9918 )
9919 ..Point::new(
9920 end_row.previous_row().0,
9921 buffer.line_len(end_row.previous_row()),
9922 );
9923 let insertion_point = display_map
9924 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9925 .0;
9926
9927 // Don't move lines across excerpts
9928 if buffer
9929 .excerpt_containing(insertion_point..range_to_move.end)
9930 .is_some()
9931 {
9932 let text = buffer
9933 .text_for_range(range_to_move.clone())
9934 .flat_map(|s| s.chars())
9935 .skip(1)
9936 .chain(['\n'])
9937 .collect::<String>();
9938
9939 edits.push((
9940 buffer.anchor_after(range_to_move.start)
9941 ..buffer.anchor_before(range_to_move.end),
9942 String::new(),
9943 ));
9944 let insertion_anchor = buffer.anchor_after(insertion_point);
9945 edits.push((insertion_anchor..insertion_anchor, text));
9946
9947 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9948
9949 // Move selections up
9950 new_selections.extend(contiguous_row_selections.drain(..).map(
9951 |mut selection| {
9952 selection.start.row -= row_delta;
9953 selection.end.row -= row_delta;
9954 selection
9955 },
9956 ));
9957
9958 // Move folds up
9959 unfold_ranges.push(range_to_move.clone());
9960 for fold in display_map.folds_in_range(
9961 buffer.anchor_before(range_to_move.start)
9962 ..buffer.anchor_after(range_to_move.end),
9963 ) {
9964 let mut start = fold.range.start.to_point(&buffer);
9965 let mut end = fold.range.end.to_point(&buffer);
9966 start.row -= row_delta;
9967 end.row -= row_delta;
9968 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9969 }
9970 }
9971 }
9972
9973 // If we didn't move line(s), preserve the existing selections
9974 new_selections.append(&mut contiguous_row_selections);
9975 }
9976
9977 self.transact(window, cx, |this, window, cx| {
9978 this.unfold_ranges(&unfold_ranges, true, true, cx);
9979 this.buffer.update(cx, |buffer, cx| {
9980 for (range, text) in edits {
9981 buffer.edit([(range, text)], None, cx);
9982 }
9983 });
9984 this.fold_creases(refold_creases, true, window, cx);
9985 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9986 s.select(new_selections);
9987 })
9988 });
9989 }
9990
9991 pub fn move_line_down(
9992 &mut self,
9993 _: &MoveLineDown,
9994 window: &mut Window,
9995 cx: &mut Context<Self>,
9996 ) {
9997 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9998
9999 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10000 let buffer = self.buffer.read(cx).snapshot(cx);
10001
10002 let mut edits = Vec::new();
10003 let mut unfold_ranges = Vec::new();
10004 let mut refold_creases = Vec::new();
10005
10006 let selections = self.selections.all::<Point>(cx);
10007 let mut selections = selections.iter().peekable();
10008 let mut contiguous_row_selections = Vec::new();
10009 let mut new_selections = Vec::new();
10010
10011 while let Some(selection) = selections.next() {
10012 // Find all the selections that span a contiguous row range
10013 let (start_row, end_row) = consume_contiguous_rows(
10014 &mut contiguous_row_selections,
10015 selection,
10016 &display_map,
10017 &mut selections,
10018 );
10019
10020 // Move the text spanned by the row range to be after the last line of the row range
10021 if end_row.0 <= buffer.max_point().row {
10022 let range_to_move =
10023 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10024 let insertion_point = display_map
10025 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10026 .0;
10027
10028 // Don't move lines across excerpt boundaries
10029 if buffer
10030 .excerpt_containing(range_to_move.start..insertion_point)
10031 .is_some()
10032 {
10033 let mut text = String::from("\n");
10034 text.extend(buffer.text_for_range(range_to_move.clone()));
10035 text.pop(); // Drop trailing newline
10036 edits.push((
10037 buffer.anchor_after(range_to_move.start)
10038 ..buffer.anchor_before(range_to_move.end),
10039 String::new(),
10040 ));
10041 let insertion_anchor = buffer.anchor_after(insertion_point);
10042 edits.push((insertion_anchor..insertion_anchor, text));
10043
10044 let row_delta = insertion_point.row - range_to_move.end.row + 1;
10045
10046 // Move selections down
10047 new_selections.extend(contiguous_row_selections.drain(..).map(
10048 |mut selection| {
10049 selection.start.row += row_delta;
10050 selection.end.row += row_delta;
10051 selection
10052 },
10053 ));
10054
10055 // Move folds down
10056 unfold_ranges.push(range_to_move.clone());
10057 for fold in display_map.folds_in_range(
10058 buffer.anchor_before(range_to_move.start)
10059 ..buffer.anchor_after(range_to_move.end),
10060 ) {
10061 let mut start = fold.range.start.to_point(&buffer);
10062 let mut end = fold.range.end.to_point(&buffer);
10063 start.row += row_delta;
10064 end.row += row_delta;
10065 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10066 }
10067 }
10068 }
10069
10070 // If we didn't move line(s), preserve the existing selections
10071 new_selections.append(&mut contiguous_row_selections);
10072 }
10073
10074 self.transact(window, cx, |this, window, cx| {
10075 this.unfold_ranges(&unfold_ranges, true, true, cx);
10076 this.buffer.update(cx, |buffer, cx| {
10077 for (range, text) in edits {
10078 buffer.edit([(range, text)], None, cx);
10079 }
10080 });
10081 this.fold_creases(refold_creases, true, window, cx);
10082 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10083 s.select(new_selections)
10084 });
10085 });
10086 }
10087
10088 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10089 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10090 let text_layout_details = &self.text_layout_details(window);
10091 self.transact(window, cx, |this, window, cx| {
10092 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10093 let mut edits: Vec<(Range<usize>, String)> = Default::default();
10094 s.move_with(|display_map, selection| {
10095 if !selection.is_empty() {
10096 return;
10097 }
10098
10099 let mut head = selection.head();
10100 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10101 if head.column() == display_map.line_len(head.row()) {
10102 transpose_offset = display_map
10103 .buffer_snapshot
10104 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10105 }
10106
10107 if transpose_offset == 0 {
10108 return;
10109 }
10110
10111 *head.column_mut() += 1;
10112 head = display_map.clip_point(head, Bias::Right);
10113 let goal = SelectionGoal::HorizontalPosition(
10114 display_map
10115 .x_for_display_point(head, text_layout_details)
10116 .into(),
10117 );
10118 selection.collapse_to(head, goal);
10119
10120 let transpose_start = display_map
10121 .buffer_snapshot
10122 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10123 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10124 let transpose_end = display_map
10125 .buffer_snapshot
10126 .clip_offset(transpose_offset + 1, Bias::Right);
10127 if let Some(ch) =
10128 display_map.buffer_snapshot.chars_at(transpose_start).next()
10129 {
10130 edits.push((transpose_start..transpose_offset, String::new()));
10131 edits.push((transpose_end..transpose_end, ch.to_string()));
10132 }
10133 }
10134 });
10135 edits
10136 });
10137 this.buffer
10138 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10139 let selections = this.selections.all::<usize>(cx);
10140 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10141 s.select(selections);
10142 });
10143 });
10144 }
10145
10146 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10147 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10148 self.rewrap_impl(RewrapOptions::default(), cx)
10149 }
10150
10151 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10152 let buffer = self.buffer.read(cx).snapshot(cx);
10153 let selections = self.selections.all::<Point>(cx);
10154 let mut selections = selections.iter().peekable();
10155
10156 let mut edits = Vec::new();
10157 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10158
10159 while let Some(selection) = selections.next() {
10160 let mut start_row = selection.start.row;
10161 let mut end_row = selection.end.row;
10162
10163 // Skip selections that overlap with a range that has already been rewrapped.
10164 let selection_range = start_row..end_row;
10165 if rewrapped_row_ranges
10166 .iter()
10167 .any(|range| range.overlaps(&selection_range))
10168 {
10169 continue;
10170 }
10171
10172 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10173
10174 // Since not all lines in the selection may be at the same indent
10175 // level, choose the indent size that is the most common between all
10176 // of the lines.
10177 //
10178 // If there is a tie, we use the deepest indent.
10179 let (indent_size, indent_end) = {
10180 let mut indent_size_occurrences = HashMap::default();
10181 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10182
10183 for row in start_row..=end_row {
10184 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10185 rows_by_indent_size.entry(indent).or_default().push(row);
10186 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10187 }
10188
10189 let indent_size = indent_size_occurrences
10190 .into_iter()
10191 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10192 .map(|(indent, _)| indent)
10193 .unwrap_or_default();
10194 let row = rows_by_indent_size[&indent_size][0];
10195 let indent_end = Point::new(row, indent_size.len);
10196
10197 (indent_size, indent_end)
10198 };
10199
10200 let mut line_prefix = indent_size.chars().collect::<String>();
10201
10202 let mut inside_comment = false;
10203 if let Some(comment_prefix) =
10204 buffer
10205 .language_scope_at(selection.head())
10206 .and_then(|language| {
10207 language
10208 .line_comment_prefixes()
10209 .iter()
10210 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10211 .cloned()
10212 })
10213 {
10214 line_prefix.push_str(&comment_prefix);
10215 inside_comment = true;
10216 }
10217
10218 let language_settings = buffer.language_settings_at(selection.head(), cx);
10219 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10220 RewrapBehavior::InComments => inside_comment,
10221 RewrapBehavior::InSelections => !selection.is_empty(),
10222 RewrapBehavior::Anywhere => true,
10223 };
10224
10225 let should_rewrap = options.override_language_settings
10226 || allow_rewrap_based_on_language
10227 || self.hard_wrap.is_some();
10228 if !should_rewrap {
10229 continue;
10230 }
10231
10232 if selection.is_empty() {
10233 'expand_upwards: while start_row > 0 {
10234 let prev_row = start_row - 1;
10235 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10236 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10237 {
10238 start_row = prev_row;
10239 } else {
10240 break 'expand_upwards;
10241 }
10242 }
10243
10244 'expand_downwards: while end_row < buffer.max_point().row {
10245 let next_row = end_row + 1;
10246 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10247 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10248 {
10249 end_row = next_row;
10250 } else {
10251 break 'expand_downwards;
10252 }
10253 }
10254 }
10255
10256 let start = Point::new(start_row, 0);
10257 let start_offset = start.to_offset(&buffer);
10258 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10259 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10260 let Some(lines_without_prefixes) = selection_text
10261 .lines()
10262 .map(|line| {
10263 line.strip_prefix(&line_prefix)
10264 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10265 .ok_or_else(|| {
10266 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10267 })
10268 })
10269 .collect::<Result<Vec<_>, _>>()
10270 .log_err()
10271 else {
10272 continue;
10273 };
10274
10275 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10276 buffer
10277 .language_settings_at(Point::new(start_row, 0), cx)
10278 .preferred_line_length as usize
10279 });
10280 let wrapped_text = wrap_with_prefix(
10281 line_prefix,
10282 lines_without_prefixes.join("\n"),
10283 wrap_column,
10284 tab_size,
10285 options.preserve_existing_whitespace,
10286 );
10287
10288 // TODO: should always use char-based diff while still supporting cursor behavior that
10289 // matches vim.
10290 let mut diff_options = DiffOptions::default();
10291 if options.override_language_settings {
10292 diff_options.max_word_diff_len = 0;
10293 diff_options.max_word_diff_line_count = 0;
10294 } else {
10295 diff_options.max_word_diff_len = usize::MAX;
10296 diff_options.max_word_diff_line_count = usize::MAX;
10297 }
10298
10299 for (old_range, new_text) in
10300 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10301 {
10302 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10303 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10304 edits.push((edit_start..edit_end, new_text));
10305 }
10306
10307 rewrapped_row_ranges.push(start_row..=end_row);
10308 }
10309
10310 self.buffer
10311 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10312 }
10313
10314 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10315 let mut text = String::new();
10316 let buffer = self.buffer.read(cx).snapshot(cx);
10317 let mut selections = self.selections.all::<Point>(cx);
10318 let mut clipboard_selections = Vec::with_capacity(selections.len());
10319 {
10320 let max_point = buffer.max_point();
10321 let mut is_first = true;
10322 for selection in &mut selections {
10323 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10324 if is_entire_line {
10325 selection.start = Point::new(selection.start.row, 0);
10326 if !selection.is_empty() && selection.end.column == 0 {
10327 selection.end = cmp::min(max_point, selection.end);
10328 } else {
10329 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10330 }
10331 selection.goal = SelectionGoal::None;
10332 }
10333 if is_first {
10334 is_first = false;
10335 } else {
10336 text += "\n";
10337 }
10338 let mut len = 0;
10339 for chunk in buffer.text_for_range(selection.start..selection.end) {
10340 text.push_str(chunk);
10341 len += chunk.len();
10342 }
10343 clipboard_selections.push(ClipboardSelection {
10344 len,
10345 is_entire_line,
10346 first_line_indent: buffer
10347 .indent_size_for_line(MultiBufferRow(selection.start.row))
10348 .len,
10349 });
10350 }
10351 }
10352
10353 self.transact(window, cx, |this, window, cx| {
10354 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10355 s.select(selections);
10356 });
10357 this.insert("", window, cx);
10358 });
10359 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10360 }
10361
10362 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10363 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10364 let item = self.cut_common(window, cx);
10365 cx.write_to_clipboard(item);
10366 }
10367
10368 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10369 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10370 self.change_selections(None, window, cx, |s| {
10371 s.move_with(|snapshot, sel| {
10372 if sel.is_empty() {
10373 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10374 }
10375 });
10376 });
10377 let item = self.cut_common(window, cx);
10378 cx.set_global(KillRing(item))
10379 }
10380
10381 pub fn kill_ring_yank(
10382 &mut self,
10383 _: &KillRingYank,
10384 window: &mut Window,
10385 cx: &mut Context<Self>,
10386 ) {
10387 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10388 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10389 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10390 (kill_ring.text().to_string(), kill_ring.metadata_json())
10391 } else {
10392 return;
10393 }
10394 } else {
10395 return;
10396 };
10397 self.do_paste(&text, metadata, false, window, cx);
10398 }
10399
10400 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10401 self.do_copy(true, cx);
10402 }
10403
10404 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10405 self.do_copy(false, cx);
10406 }
10407
10408 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10409 let selections = self.selections.all::<Point>(cx);
10410 let buffer = self.buffer.read(cx).read(cx);
10411 let mut text = String::new();
10412
10413 let mut clipboard_selections = Vec::with_capacity(selections.len());
10414 {
10415 let max_point = buffer.max_point();
10416 let mut is_first = true;
10417 for selection in &selections {
10418 let mut start = selection.start;
10419 let mut end = selection.end;
10420 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10421 if is_entire_line {
10422 start = Point::new(start.row, 0);
10423 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10424 }
10425
10426 let mut trimmed_selections = Vec::new();
10427 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10428 let row = MultiBufferRow(start.row);
10429 let first_indent = buffer.indent_size_for_line(row);
10430 if first_indent.len == 0 || start.column > first_indent.len {
10431 trimmed_selections.push(start..end);
10432 } else {
10433 trimmed_selections.push(
10434 Point::new(row.0, first_indent.len)
10435 ..Point::new(row.0, buffer.line_len(row)),
10436 );
10437 for row in start.row + 1..=end.row {
10438 let mut line_len = buffer.line_len(MultiBufferRow(row));
10439 if row == end.row {
10440 line_len = end.column;
10441 }
10442 if line_len == 0 {
10443 trimmed_selections
10444 .push(Point::new(row, 0)..Point::new(row, line_len));
10445 continue;
10446 }
10447 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10448 if row_indent_size.len >= first_indent.len {
10449 trimmed_selections.push(
10450 Point::new(row, first_indent.len)..Point::new(row, line_len),
10451 );
10452 } else {
10453 trimmed_selections.clear();
10454 trimmed_selections.push(start..end);
10455 break;
10456 }
10457 }
10458 }
10459 } else {
10460 trimmed_selections.push(start..end);
10461 }
10462
10463 for trimmed_range in trimmed_selections {
10464 if is_first {
10465 is_first = false;
10466 } else {
10467 text += "\n";
10468 }
10469 let mut len = 0;
10470 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10471 text.push_str(chunk);
10472 len += chunk.len();
10473 }
10474 clipboard_selections.push(ClipboardSelection {
10475 len,
10476 is_entire_line,
10477 first_line_indent: buffer
10478 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10479 .len,
10480 });
10481 }
10482 }
10483 }
10484
10485 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10486 text,
10487 clipboard_selections,
10488 ));
10489 }
10490
10491 pub fn do_paste(
10492 &mut self,
10493 text: &String,
10494 clipboard_selections: Option<Vec<ClipboardSelection>>,
10495 handle_entire_lines: bool,
10496 window: &mut Window,
10497 cx: &mut Context<Self>,
10498 ) {
10499 if self.read_only(cx) {
10500 return;
10501 }
10502
10503 let clipboard_text = Cow::Borrowed(text);
10504
10505 self.transact(window, cx, |this, window, cx| {
10506 if let Some(mut clipboard_selections) = clipboard_selections {
10507 let old_selections = this.selections.all::<usize>(cx);
10508 let all_selections_were_entire_line =
10509 clipboard_selections.iter().all(|s| s.is_entire_line);
10510 let first_selection_indent_column =
10511 clipboard_selections.first().map(|s| s.first_line_indent);
10512 if clipboard_selections.len() != old_selections.len() {
10513 clipboard_selections.drain(..);
10514 }
10515 let cursor_offset = this.selections.last::<usize>(cx).head();
10516 let mut auto_indent_on_paste = true;
10517
10518 this.buffer.update(cx, |buffer, cx| {
10519 let snapshot = buffer.read(cx);
10520 auto_indent_on_paste = snapshot
10521 .language_settings_at(cursor_offset, cx)
10522 .auto_indent_on_paste;
10523
10524 let mut start_offset = 0;
10525 let mut edits = Vec::new();
10526 let mut original_indent_columns = Vec::new();
10527 for (ix, selection) in old_selections.iter().enumerate() {
10528 let to_insert;
10529 let entire_line;
10530 let original_indent_column;
10531 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10532 let end_offset = start_offset + clipboard_selection.len;
10533 to_insert = &clipboard_text[start_offset..end_offset];
10534 entire_line = clipboard_selection.is_entire_line;
10535 start_offset = end_offset + 1;
10536 original_indent_column = Some(clipboard_selection.first_line_indent);
10537 } else {
10538 to_insert = clipboard_text.as_str();
10539 entire_line = all_selections_were_entire_line;
10540 original_indent_column = first_selection_indent_column
10541 }
10542
10543 // If the corresponding selection was empty when this slice of the
10544 // clipboard text was written, then the entire line containing the
10545 // selection was copied. If this selection is also currently empty,
10546 // then paste the line before the current line of the buffer.
10547 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10548 let column = selection.start.to_point(&snapshot).column as usize;
10549 let line_start = selection.start - column;
10550 line_start..line_start
10551 } else {
10552 selection.range()
10553 };
10554
10555 edits.push((range, to_insert));
10556 original_indent_columns.push(original_indent_column);
10557 }
10558 drop(snapshot);
10559
10560 buffer.edit(
10561 edits,
10562 if auto_indent_on_paste {
10563 Some(AutoindentMode::Block {
10564 original_indent_columns,
10565 })
10566 } else {
10567 None
10568 },
10569 cx,
10570 );
10571 });
10572
10573 let selections = this.selections.all::<usize>(cx);
10574 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10575 s.select(selections)
10576 });
10577 } else {
10578 this.insert(&clipboard_text, window, cx);
10579 }
10580 });
10581 }
10582
10583 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10584 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10585 if let Some(item) = cx.read_from_clipboard() {
10586 let entries = item.entries();
10587
10588 match entries.first() {
10589 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10590 // of all the pasted entries.
10591 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10592 .do_paste(
10593 clipboard_string.text(),
10594 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10595 true,
10596 window,
10597 cx,
10598 ),
10599 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10600 }
10601 }
10602 }
10603
10604 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10605 if self.read_only(cx) {
10606 return;
10607 }
10608
10609 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10610
10611 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10612 if let Some((selections, _)) =
10613 self.selection_history.transaction(transaction_id).cloned()
10614 {
10615 self.change_selections(None, window, cx, |s| {
10616 s.select_anchors(selections.to_vec());
10617 });
10618 } else {
10619 log::error!(
10620 "No entry in selection_history found for undo. \
10621 This may correspond to a bug where undo does not update the selection. \
10622 If this is occurring, please add details to \
10623 https://github.com/zed-industries/zed/issues/22692"
10624 );
10625 }
10626 self.request_autoscroll(Autoscroll::fit(), cx);
10627 self.unmark_text(window, cx);
10628 self.refresh_inline_completion(true, false, window, cx);
10629 cx.emit(EditorEvent::Edited { transaction_id });
10630 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10631 }
10632 }
10633
10634 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10635 if self.read_only(cx) {
10636 return;
10637 }
10638
10639 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10640
10641 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10642 if let Some((_, Some(selections))) =
10643 self.selection_history.transaction(transaction_id).cloned()
10644 {
10645 self.change_selections(None, window, cx, |s| {
10646 s.select_anchors(selections.to_vec());
10647 });
10648 } else {
10649 log::error!(
10650 "No entry in selection_history found for redo. \
10651 This may correspond to a bug where undo does not update the selection. \
10652 If this is occurring, please add details to \
10653 https://github.com/zed-industries/zed/issues/22692"
10654 );
10655 }
10656 self.request_autoscroll(Autoscroll::fit(), cx);
10657 self.unmark_text(window, cx);
10658 self.refresh_inline_completion(true, false, window, cx);
10659 cx.emit(EditorEvent::Edited { transaction_id });
10660 }
10661 }
10662
10663 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10664 self.buffer
10665 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10666 }
10667
10668 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10669 self.buffer
10670 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10671 }
10672
10673 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10674 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10675 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10676 s.move_with(|map, selection| {
10677 let cursor = if selection.is_empty() {
10678 movement::left(map, selection.start)
10679 } else {
10680 selection.start
10681 };
10682 selection.collapse_to(cursor, SelectionGoal::None);
10683 });
10684 })
10685 }
10686
10687 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10688 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10689 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10690 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10691 })
10692 }
10693
10694 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10695 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10696 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10697 s.move_with(|map, selection| {
10698 let cursor = if selection.is_empty() {
10699 movement::right(map, selection.end)
10700 } else {
10701 selection.end
10702 };
10703 selection.collapse_to(cursor, SelectionGoal::None)
10704 });
10705 })
10706 }
10707
10708 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10709 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10710 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10711 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10712 })
10713 }
10714
10715 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10716 if self.take_rename(true, window, cx).is_some() {
10717 return;
10718 }
10719
10720 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10721 cx.propagate();
10722 return;
10723 }
10724
10725 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10726
10727 let text_layout_details = &self.text_layout_details(window);
10728 let selection_count = self.selections.count();
10729 let first_selection = self.selections.first_anchor();
10730
10731 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10732 s.move_with(|map, selection| {
10733 if !selection.is_empty() {
10734 selection.goal = SelectionGoal::None;
10735 }
10736 let (cursor, goal) = movement::up(
10737 map,
10738 selection.start,
10739 selection.goal,
10740 false,
10741 text_layout_details,
10742 );
10743 selection.collapse_to(cursor, goal);
10744 });
10745 });
10746
10747 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10748 {
10749 cx.propagate();
10750 }
10751 }
10752
10753 pub fn move_up_by_lines(
10754 &mut self,
10755 action: &MoveUpByLines,
10756 window: &mut Window,
10757 cx: &mut Context<Self>,
10758 ) {
10759 if self.take_rename(true, window, cx).is_some() {
10760 return;
10761 }
10762
10763 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10764 cx.propagate();
10765 return;
10766 }
10767
10768 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10769
10770 let text_layout_details = &self.text_layout_details(window);
10771
10772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10773 s.move_with(|map, selection| {
10774 if !selection.is_empty() {
10775 selection.goal = SelectionGoal::None;
10776 }
10777 let (cursor, goal) = movement::up_by_rows(
10778 map,
10779 selection.start,
10780 action.lines,
10781 selection.goal,
10782 false,
10783 text_layout_details,
10784 );
10785 selection.collapse_to(cursor, goal);
10786 });
10787 })
10788 }
10789
10790 pub fn move_down_by_lines(
10791 &mut self,
10792 action: &MoveDownByLines,
10793 window: &mut Window,
10794 cx: &mut Context<Self>,
10795 ) {
10796 if self.take_rename(true, window, cx).is_some() {
10797 return;
10798 }
10799
10800 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10801 cx.propagate();
10802 return;
10803 }
10804
10805 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10806
10807 let text_layout_details = &self.text_layout_details(window);
10808
10809 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10810 s.move_with(|map, selection| {
10811 if !selection.is_empty() {
10812 selection.goal = SelectionGoal::None;
10813 }
10814 let (cursor, goal) = movement::down_by_rows(
10815 map,
10816 selection.start,
10817 action.lines,
10818 selection.goal,
10819 false,
10820 text_layout_details,
10821 );
10822 selection.collapse_to(cursor, goal);
10823 });
10824 })
10825 }
10826
10827 pub fn select_down_by_lines(
10828 &mut self,
10829 action: &SelectDownByLines,
10830 window: &mut Window,
10831 cx: &mut Context<Self>,
10832 ) {
10833 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10834 let text_layout_details = &self.text_layout_details(window);
10835 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10836 s.move_heads_with(|map, head, goal| {
10837 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10838 })
10839 })
10840 }
10841
10842 pub fn select_up_by_lines(
10843 &mut self,
10844 action: &SelectUpByLines,
10845 window: &mut Window,
10846 cx: &mut Context<Self>,
10847 ) {
10848 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10849 let text_layout_details = &self.text_layout_details(window);
10850 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10851 s.move_heads_with(|map, head, goal| {
10852 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10853 })
10854 })
10855 }
10856
10857 pub fn select_page_up(
10858 &mut self,
10859 _: &SelectPageUp,
10860 window: &mut Window,
10861 cx: &mut Context<Self>,
10862 ) {
10863 let Some(row_count) = self.visible_row_count() else {
10864 return;
10865 };
10866
10867 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10868
10869 let text_layout_details = &self.text_layout_details(window);
10870
10871 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10872 s.move_heads_with(|map, head, goal| {
10873 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10874 })
10875 })
10876 }
10877
10878 pub fn move_page_up(
10879 &mut self,
10880 action: &MovePageUp,
10881 window: &mut Window,
10882 cx: &mut Context<Self>,
10883 ) {
10884 if self.take_rename(true, window, cx).is_some() {
10885 return;
10886 }
10887
10888 if self
10889 .context_menu
10890 .borrow_mut()
10891 .as_mut()
10892 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10893 .unwrap_or(false)
10894 {
10895 return;
10896 }
10897
10898 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10899 cx.propagate();
10900 return;
10901 }
10902
10903 let Some(row_count) = self.visible_row_count() else {
10904 return;
10905 };
10906
10907 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10908
10909 let autoscroll = if action.center_cursor {
10910 Autoscroll::center()
10911 } else {
10912 Autoscroll::fit()
10913 };
10914
10915 let text_layout_details = &self.text_layout_details(window);
10916
10917 self.change_selections(Some(autoscroll), window, cx, |s| {
10918 s.move_with(|map, selection| {
10919 if !selection.is_empty() {
10920 selection.goal = SelectionGoal::None;
10921 }
10922 let (cursor, goal) = movement::up_by_rows(
10923 map,
10924 selection.end,
10925 row_count,
10926 selection.goal,
10927 false,
10928 text_layout_details,
10929 );
10930 selection.collapse_to(cursor, goal);
10931 });
10932 });
10933 }
10934
10935 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10936 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10937 let text_layout_details = &self.text_layout_details(window);
10938 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10939 s.move_heads_with(|map, head, goal| {
10940 movement::up(map, head, goal, false, text_layout_details)
10941 })
10942 })
10943 }
10944
10945 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10946 self.take_rename(true, window, cx);
10947
10948 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10949 cx.propagate();
10950 return;
10951 }
10952
10953 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10954
10955 let text_layout_details = &self.text_layout_details(window);
10956 let selection_count = self.selections.count();
10957 let first_selection = self.selections.first_anchor();
10958
10959 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10960 s.move_with(|map, selection| {
10961 if !selection.is_empty() {
10962 selection.goal = SelectionGoal::None;
10963 }
10964 let (cursor, goal) = movement::down(
10965 map,
10966 selection.end,
10967 selection.goal,
10968 false,
10969 text_layout_details,
10970 );
10971 selection.collapse_to(cursor, goal);
10972 });
10973 });
10974
10975 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10976 {
10977 cx.propagate();
10978 }
10979 }
10980
10981 pub fn select_page_down(
10982 &mut self,
10983 _: &SelectPageDown,
10984 window: &mut Window,
10985 cx: &mut Context<Self>,
10986 ) {
10987 let Some(row_count) = self.visible_row_count() else {
10988 return;
10989 };
10990
10991 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10992
10993 let text_layout_details = &self.text_layout_details(window);
10994
10995 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10996 s.move_heads_with(|map, head, goal| {
10997 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10998 })
10999 })
11000 }
11001
11002 pub fn move_page_down(
11003 &mut self,
11004 action: &MovePageDown,
11005 window: &mut Window,
11006 cx: &mut Context<Self>,
11007 ) {
11008 if self.take_rename(true, window, cx).is_some() {
11009 return;
11010 }
11011
11012 if self
11013 .context_menu
11014 .borrow_mut()
11015 .as_mut()
11016 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11017 .unwrap_or(false)
11018 {
11019 return;
11020 }
11021
11022 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11023 cx.propagate();
11024 return;
11025 }
11026
11027 let Some(row_count) = self.visible_row_count() else {
11028 return;
11029 };
11030
11031 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11032
11033 let autoscroll = if action.center_cursor {
11034 Autoscroll::center()
11035 } else {
11036 Autoscroll::fit()
11037 };
11038
11039 let text_layout_details = &self.text_layout_details(window);
11040 self.change_selections(Some(autoscroll), window, cx, |s| {
11041 s.move_with(|map, selection| {
11042 if !selection.is_empty() {
11043 selection.goal = SelectionGoal::None;
11044 }
11045 let (cursor, goal) = movement::down_by_rows(
11046 map,
11047 selection.end,
11048 row_count,
11049 selection.goal,
11050 false,
11051 text_layout_details,
11052 );
11053 selection.collapse_to(cursor, goal);
11054 });
11055 });
11056 }
11057
11058 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11059 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11060 let text_layout_details = &self.text_layout_details(window);
11061 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11062 s.move_heads_with(|map, head, goal| {
11063 movement::down(map, head, goal, false, text_layout_details)
11064 })
11065 });
11066 }
11067
11068 pub fn context_menu_first(
11069 &mut self,
11070 _: &ContextMenuFirst,
11071 _window: &mut Window,
11072 cx: &mut Context<Self>,
11073 ) {
11074 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11075 context_menu.select_first(self.completion_provider.as_deref(), cx);
11076 }
11077 }
11078
11079 pub fn context_menu_prev(
11080 &mut self,
11081 _: &ContextMenuPrevious,
11082 _window: &mut Window,
11083 cx: &mut Context<Self>,
11084 ) {
11085 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11086 context_menu.select_prev(self.completion_provider.as_deref(), cx);
11087 }
11088 }
11089
11090 pub fn context_menu_next(
11091 &mut self,
11092 _: &ContextMenuNext,
11093 _window: &mut Window,
11094 cx: &mut Context<Self>,
11095 ) {
11096 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11097 context_menu.select_next(self.completion_provider.as_deref(), cx);
11098 }
11099 }
11100
11101 pub fn context_menu_last(
11102 &mut self,
11103 _: &ContextMenuLast,
11104 _window: &mut Window,
11105 cx: &mut Context<Self>,
11106 ) {
11107 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11108 context_menu.select_last(self.completion_provider.as_deref(), cx);
11109 }
11110 }
11111
11112 pub fn move_to_previous_word_start(
11113 &mut self,
11114 _: &MoveToPreviousWordStart,
11115 window: &mut Window,
11116 cx: &mut Context<Self>,
11117 ) {
11118 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11119 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11120 s.move_cursors_with(|map, head, _| {
11121 (
11122 movement::previous_word_start(map, head),
11123 SelectionGoal::None,
11124 )
11125 });
11126 })
11127 }
11128
11129 pub fn move_to_previous_subword_start(
11130 &mut self,
11131 _: &MoveToPreviousSubwordStart,
11132 window: &mut Window,
11133 cx: &mut Context<Self>,
11134 ) {
11135 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11136 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11137 s.move_cursors_with(|map, head, _| {
11138 (
11139 movement::previous_subword_start(map, head),
11140 SelectionGoal::None,
11141 )
11142 });
11143 })
11144 }
11145
11146 pub fn select_to_previous_word_start(
11147 &mut self,
11148 _: &SelectToPreviousWordStart,
11149 window: &mut Window,
11150 cx: &mut Context<Self>,
11151 ) {
11152 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11153 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11154 s.move_heads_with(|map, head, _| {
11155 (
11156 movement::previous_word_start(map, head),
11157 SelectionGoal::None,
11158 )
11159 });
11160 })
11161 }
11162
11163 pub fn select_to_previous_subword_start(
11164 &mut self,
11165 _: &SelectToPreviousSubwordStart,
11166 window: &mut Window,
11167 cx: &mut Context<Self>,
11168 ) {
11169 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11170 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11171 s.move_heads_with(|map, head, _| {
11172 (
11173 movement::previous_subword_start(map, head),
11174 SelectionGoal::None,
11175 )
11176 });
11177 })
11178 }
11179
11180 pub fn delete_to_previous_word_start(
11181 &mut self,
11182 action: &DeleteToPreviousWordStart,
11183 window: &mut Window,
11184 cx: &mut Context<Self>,
11185 ) {
11186 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11187 self.transact(window, cx, |this, window, cx| {
11188 this.select_autoclose_pair(window, cx);
11189 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11190 s.move_with(|map, selection| {
11191 if selection.is_empty() {
11192 let cursor = if action.ignore_newlines {
11193 movement::previous_word_start(map, selection.head())
11194 } else {
11195 movement::previous_word_start_or_newline(map, selection.head())
11196 };
11197 selection.set_head(cursor, SelectionGoal::None);
11198 }
11199 });
11200 });
11201 this.insert("", window, cx);
11202 });
11203 }
11204
11205 pub fn delete_to_previous_subword_start(
11206 &mut self,
11207 _: &DeleteToPreviousSubwordStart,
11208 window: &mut Window,
11209 cx: &mut Context<Self>,
11210 ) {
11211 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11212 self.transact(window, cx, |this, window, cx| {
11213 this.select_autoclose_pair(window, cx);
11214 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11215 s.move_with(|map, selection| {
11216 if selection.is_empty() {
11217 let cursor = movement::previous_subword_start(map, selection.head());
11218 selection.set_head(cursor, SelectionGoal::None);
11219 }
11220 });
11221 });
11222 this.insert("", window, cx);
11223 });
11224 }
11225
11226 pub fn move_to_next_word_end(
11227 &mut self,
11228 _: &MoveToNextWordEnd,
11229 window: &mut Window,
11230 cx: &mut Context<Self>,
11231 ) {
11232 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11233 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11234 s.move_cursors_with(|map, head, _| {
11235 (movement::next_word_end(map, head), SelectionGoal::None)
11236 });
11237 })
11238 }
11239
11240 pub fn move_to_next_subword_end(
11241 &mut self,
11242 _: &MoveToNextSubwordEnd,
11243 window: &mut Window,
11244 cx: &mut Context<Self>,
11245 ) {
11246 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11247 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11248 s.move_cursors_with(|map, head, _| {
11249 (movement::next_subword_end(map, head), SelectionGoal::None)
11250 });
11251 })
11252 }
11253
11254 pub fn select_to_next_word_end(
11255 &mut self,
11256 _: &SelectToNextWordEnd,
11257 window: &mut Window,
11258 cx: &mut Context<Self>,
11259 ) {
11260 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11261 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11262 s.move_heads_with(|map, head, _| {
11263 (movement::next_word_end(map, head), SelectionGoal::None)
11264 });
11265 })
11266 }
11267
11268 pub fn select_to_next_subword_end(
11269 &mut self,
11270 _: &SelectToNextSubwordEnd,
11271 window: &mut Window,
11272 cx: &mut Context<Self>,
11273 ) {
11274 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11275 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11276 s.move_heads_with(|map, head, _| {
11277 (movement::next_subword_end(map, head), SelectionGoal::None)
11278 });
11279 })
11280 }
11281
11282 pub fn delete_to_next_word_end(
11283 &mut self,
11284 action: &DeleteToNextWordEnd,
11285 window: &mut Window,
11286 cx: &mut Context<Self>,
11287 ) {
11288 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11289 self.transact(window, cx, |this, window, cx| {
11290 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11291 s.move_with(|map, selection| {
11292 if selection.is_empty() {
11293 let cursor = if action.ignore_newlines {
11294 movement::next_word_end(map, selection.head())
11295 } else {
11296 movement::next_word_end_or_newline(map, selection.head())
11297 };
11298 selection.set_head(cursor, SelectionGoal::None);
11299 }
11300 });
11301 });
11302 this.insert("", window, cx);
11303 });
11304 }
11305
11306 pub fn delete_to_next_subword_end(
11307 &mut self,
11308 _: &DeleteToNextSubwordEnd,
11309 window: &mut Window,
11310 cx: &mut Context<Self>,
11311 ) {
11312 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11313 self.transact(window, cx, |this, window, cx| {
11314 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11315 s.move_with(|map, selection| {
11316 if selection.is_empty() {
11317 let cursor = movement::next_subword_end(map, selection.head());
11318 selection.set_head(cursor, SelectionGoal::None);
11319 }
11320 });
11321 });
11322 this.insert("", window, cx);
11323 });
11324 }
11325
11326 pub fn move_to_beginning_of_line(
11327 &mut self,
11328 action: &MoveToBeginningOfLine,
11329 window: &mut Window,
11330 cx: &mut Context<Self>,
11331 ) {
11332 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11333 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11334 s.move_cursors_with(|map, head, _| {
11335 (
11336 movement::indented_line_beginning(
11337 map,
11338 head,
11339 action.stop_at_soft_wraps,
11340 action.stop_at_indent,
11341 ),
11342 SelectionGoal::None,
11343 )
11344 });
11345 })
11346 }
11347
11348 pub fn select_to_beginning_of_line(
11349 &mut self,
11350 action: &SelectToBeginningOfLine,
11351 window: &mut Window,
11352 cx: &mut Context<Self>,
11353 ) {
11354 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11355 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11356 s.move_heads_with(|map, head, _| {
11357 (
11358 movement::indented_line_beginning(
11359 map,
11360 head,
11361 action.stop_at_soft_wraps,
11362 action.stop_at_indent,
11363 ),
11364 SelectionGoal::None,
11365 )
11366 });
11367 });
11368 }
11369
11370 pub fn delete_to_beginning_of_line(
11371 &mut self,
11372 action: &DeleteToBeginningOfLine,
11373 window: &mut Window,
11374 cx: &mut Context<Self>,
11375 ) {
11376 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11377 self.transact(window, cx, |this, window, cx| {
11378 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11379 s.move_with(|_, selection| {
11380 selection.reversed = true;
11381 });
11382 });
11383
11384 this.select_to_beginning_of_line(
11385 &SelectToBeginningOfLine {
11386 stop_at_soft_wraps: false,
11387 stop_at_indent: action.stop_at_indent,
11388 },
11389 window,
11390 cx,
11391 );
11392 this.backspace(&Backspace, window, cx);
11393 });
11394 }
11395
11396 pub fn move_to_end_of_line(
11397 &mut self,
11398 action: &MoveToEndOfLine,
11399 window: &mut Window,
11400 cx: &mut Context<Self>,
11401 ) {
11402 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11403 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11404 s.move_cursors_with(|map, head, _| {
11405 (
11406 movement::line_end(map, head, action.stop_at_soft_wraps),
11407 SelectionGoal::None,
11408 )
11409 });
11410 })
11411 }
11412
11413 pub fn select_to_end_of_line(
11414 &mut self,
11415 action: &SelectToEndOfLine,
11416 window: &mut Window,
11417 cx: &mut Context<Self>,
11418 ) {
11419 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11420 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11421 s.move_heads_with(|map, head, _| {
11422 (
11423 movement::line_end(map, head, action.stop_at_soft_wraps),
11424 SelectionGoal::None,
11425 )
11426 });
11427 })
11428 }
11429
11430 pub fn delete_to_end_of_line(
11431 &mut self,
11432 _: &DeleteToEndOfLine,
11433 window: &mut Window,
11434 cx: &mut Context<Self>,
11435 ) {
11436 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11437 self.transact(window, cx, |this, window, cx| {
11438 this.select_to_end_of_line(
11439 &SelectToEndOfLine {
11440 stop_at_soft_wraps: false,
11441 },
11442 window,
11443 cx,
11444 );
11445 this.delete(&Delete, window, cx);
11446 });
11447 }
11448
11449 pub fn cut_to_end_of_line(
11450 &mut self,
11451 _: &CutToEndOfLine,
11452 window: &mut Window,
11453 cx: &mut Context<Self>,
11454 ) {
11455 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11456 self.transact(window, cx, |this, window, cx| {
11457 this.select_to_end_of_line(
11458 &SelectToEndOfLine {
11459 stop_at_soft_wraps: false,
11460 },
11461 window,
11462 cx,
11463 );
11464 this.cut(&Cut, window, cx);
11465 });
11466 }
11467
11468 pub fn move_to_start_of_paragraph(
11469 &mut self,
11470 _: &MoveToStartOfParagraph,
11471 window: &mut Window,
11472 cx: &mut Context<Self>,
11473 ) {
11474 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11475 cx.propagate();
11476 return;
11477 }
11478 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11479 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11480 s.move_with(|map, selection| {
11481 selection.collapse_to(
11482 movement::start_of_paragraph(map, selection.head(), 1),
11483 SelectionGoal::None,
11484 )
11485 });
11486 })
11487 }
11488
11489 pub fn move_to_end_of_paragraph(
11490 &mut self,
11491 _: &MoveToEndOfParagraph,
11492 window: &mut Window,
11493 cx: &mut Context<Self>,
11494 ) {
11495 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11496 cx.propagate();
11497 return;
11498 }
11499 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11500 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11501 s.move_with(|map, selection| {
11502 selection.collapse_to(
11503 movement::end_of_paragraph(map, selection.head(), 1),
11504 SelectionGoal::None,
11505 )
11506 });
11507 })
11508 }
11509
11510 pub fn select_to_start_of_paragraph(
11511 &mut self,
11512 _: &SelectToStartOfParagraph,
11513 window: &mut Window,
11514 cx: &mut Context<Self>,
11515 ) {
11516 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11517 cx.propagate();
11518 return;
11519 }
11520 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11521 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11522 s.move_heads_with(|map, head, _| {
11523 (
11524 movement::start_of_paragraph(map, head, 1),
11525 SelectionGoal::None,
11526 )
11527 });
11528 })
11529 }
11530
11531 pub fn select_to_end_of_paragraph(
11532 &mut self,
11533 _: &SelectToEndOfParagraph,
11534 window: &mut Window,
11535 cx: &mut Context<Self>,
11536 ) {
11537 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11538 cx.propagate();
11539 return;
11540 }
11541 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11542 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11543 s.move_heads_with(|map, head, _| {
11544 (
11545 movement::end_of_paragraph(map, head, 1),
11546 SelectionGoal::None,
11547 )
11548 });
11549 })
11550 }
11551
11552 pub fn move_to_start_of_excerpt(
11553 &mut self,
11554 _: &MoveToStartOfExcerpt,
11555 window: &mut Window,
11556 cx: &mut Context<Self>,
11557 ) {
11558 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11559 cx.propagate();
11560 return;
11561 }
11562 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11563 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11564 s.move_with(|map, selection| {
11565 selection.collapse_to(
11566 movement::start_of_excerpt(
11567 map,
11568 selection.head(),
11569 workspace::searchable::Direction::Prev,
11570 ),
11571 SelectionGoal::None,
11572 )
11573 });
11574 })
11575 }
11576
11577 pub fn move_to_start_of_next_excerpt(
11578 &mut self,
11579 _: &MoveToStartOfNextExcerpt,
11580 window: &mut Window,
11581 cx: &mut Context<Self>,
11582 ) {
11583 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11584 cx.propagate();
11585 return;
11586 }
11587
11588 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11589 s.move_with(|map, selection| {
11590 selection.collapse_to(
11591 movement::start_of_excerpt(
11592 map,
11593 selection.head(),
11594 workspace::searchable::Direction::Next,
11595 ),
11596 SelectionGoal::None,
11597 )
11598 });
11599 })
11600 }
11601
11602 pub fn move_to_end_of_excerpt(
11603 &mut self,
11604 _: &MoveToEndOfExcerpt,
11605 window: &mut Window,
11606 cx: &mut Context<Self>,
11607 ) {
11608 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11609 cx.propagate();
11610 return;
11611 }
11612 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11613 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11614 s.move_with(|map, selection| {
11615 selection.collapse_to(
11616 movement::end_of_excerpt(
11617 map,
11618 selection.head(),
11619 workspace::searchable::Direction::Next,
11620 ),
11621 SelectionGoal::None,
11622 )
11623 });
11624 })
11625 }
11626
11627 pub fn move_to_end_of_previous_excerpt(
11628 &mut self,
11629 _: &MoveToEndOfPreviousExcerpt,
11630 window: &mut Window,
11631 cx: &mut Context<Self>,
11632 ) {
11633 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11634 cx.propagate();
11635 return;
11636 }
11637 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11638 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11639 s.move_with(|map, selection| {
11640 selection.collapse_to(
11641 movement::end_of_excerpt(
11642 map,
11643 selection.head(),
11644 workspace::searchable::Direction::Prev,
11645 ),
11646 SelectionGoal::None,
11647 )
11648 });
11649 })
11650 }
11651
11652 pub fn select_to_start_of_excerpt(
11653 &mut self,
11654 _: &SelectToStartOfExcerpt,
11655 window: &mut Window,
11656 cx: &mut Context<Self>,
11657 ) {
11658 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11659 cx.propagate();
11660 return;
11661 }
11662 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11663 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11664 s.move_heads_with(|map, head, _| {
11665 (
11666 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11667 SelectionGoal::None,
11668 )
11669 });
11670 })
11671 }
11672
11673 pub fn select_to_start_of_next_excerpt(
11674 &mut self,
11675 _: &SelectToStartOfNextExcerpt,
11676 window: &mut Window,
11677 cx: &mut Context<Self>,
11678 ) {
11679 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11680 cx.propagate();
11681 return;
11682 }
11683 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11684 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11685 s.move_heads_with(|map, head, _| {
11686 (
11687 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11688 SelectionGoal::None,
11689 )
11690 });
11691 })
11692 }
11693
11694 pub fn select_to_end_of_excerpt(
11695 &mut self,
11696 _: &SelectToEndOfExcerpt,
11697 window: &mut Window,
11698 cx: &mut Context<Self>,
11699 ) {
11700 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11701 cx.propagate();
11702 return;
11703 }
11704 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11705 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11706 s.move_heads_with(|map, head, _| {
11707 (
11708 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11709 SelectionGoal::None,
11710 )
11711 });
11712 })
11713 }
11714
11715 pub fn select_to_end_of_previous_excerpt(
11716 &mut self,
11717 _: &SelectToEndOfPreviousExcerpt,
11718 window: &mut Window,
11719 cx: &mut Context<Self>,
11720 ) {
11721 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11722 cx.propagate();
11723 return;
11724 }
11725 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11726 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11727 s.move_heads_with(|map, head, _| {
11728 (
11729 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11730 SelectionGoal::None,
11731 )
11732 });
11733 })
11734 }
11735
11736 pub fn move_to_beginning(
11737 &mut self,
11738 _: &MoveToBeginning,
11739 window: &mut Window,
11740 cx: &mut Context<Self>,
11741 ) {
11742 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11743 cx.propagate();
11744 return;
11745 }
11746 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11747 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11748 s.select_ranges(vec![0..0]);
11749 });
11750 }
11751
11752 pub fn select_to_beginning(
11753 &mut self,
11754 _: &SelectToBeginning,
11755 window: &mut Window,
11756 cx: &mut Context<Self>,
11757 ) {
11758 let mut selection = self.selections.last::<Point>(cx);
11759 selection.set_head(Point::zero(), SelectionGoal::None);
11760 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11761 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11762 s.select(vec![selection]);
11763 });
11764 }
11765
11766 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11767 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11768 cx.propagate();
11769 return;
11770 }
11771 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11772 let cursor = self.buffer.read(cx).read(cx).len();
11773 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11774 s.select_ranges(vec![cursor..cursor])
11775 });
11776 }
11777
11778 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11779 self.nav_history = nav_history;
11780 }
11781
11782 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11783 self.nav_history.as_ref()
11784 }
11785
11786 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11787 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11788 }
11789
11790 fn push_to_nav_history(
11791 &mut self,
11792 cursor_anchor: Anchor,
11793 new_position: Option<Point>,
11794 is_deactivate: bool,
11795 cx: &mut Context<Self>,
11796 ) {
11797 if let Some(nav_history) = self.nav_history.as_mut() {
11798 let buffer = self.buffer.read(cx).read(cx);
11799 let cursor_position = cursor_anchor.to_point(&buffer);
11800 let scroll_state = self.scroll_manager.anchor();
11801 let scroll_top_row = scroll_state.top_row(&buffer);
11802 drop(buffer);
11803
11804 if let Some(new_position) = new_position {
11805 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11806 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11807 return;
11808 }
11809 }
11810
11811 nav_history.push(
11812 Some(NavigationData {
11813 cursor_anchor,
11814 cursor_position,
11815 scroll_anchor: scroll_state,
11816 scroll_top_row,
11817 }),
11818 cx,
11819 );
11820 cx.emit(EditorEvent::PushedToNavHistory {
11821 anchor: cursor_anchor,
11822 is_deactivate,
11823 })
11824 }
11825 }
11826
11827 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11828 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11829 let buffer = self.buffer.read(cx).snapshot(cx);
11830 let mut selection = self.selections.first::<usize>(cx);
11831 selection.set_head(buffer.len(), SelectionGoal::None);
11832 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11833 s.select(vec![selection]);
11834 });
11835 }
11836
11837 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11838 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11839 let end = self.buffer.read(cx).read(cx).len();
11840 self.change_selections(None, window, cx, |s| {
11841 s.select_ranges(vec![0..end]);
11842 });
11843 }
11844
11845 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11846 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11847 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11848 let mut selections = self.selections.all::<Point>(cx);
11849 let max_point = display_map.buffer_snapshot.max_point();
11850 for selection in &mut selections {
11851 let rows = selection.spanned_rows(true, &display_map);
11852 selection.start = Point::new(rows.start.0, 0);
11853 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11854 selection.reversed = false;
11855 }
11856 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11857 s.select(selections);
11858 });
11859 }
11860
11861 pub fn split_selection_into_lines(
11862 &mut self,
11863 _: &SplitSelectionIntoLines,
11864 window: &mut Window,
11865 cx: &mut Context<Self>,
11866 ) {
11867 let selections = self
11868 .selections
11869 .all::<Point>(cx)
11870 .into_iter()
11871 .map(|selection| selection.start..selection.end)
11872 .collect::<Vec<_>>();
11873 self.unfold_ranges(&selections, true, true, cx);
11874
11875 let mut new_selection_ranges = Vec::new();
11876 {
11877 let buffer = self.buffer.read(cx).read(cx);
11878 for selection in selections {
11879 for row in selection.start.row..selection.end.row {
11880 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11881 new_selection_ranges.push(cursor..cursor);
11882 }
11883
11884 let is_multiline_selection = selection.start.row != selection.end.row;
11885 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11886 // so this action feels more ergonomic when paired with other selection operations
11887 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11888 if !should_skip_last {
11889 new_selection_ranges.push(selection.end..selection.end);
11890 }
11891 }
11892 }
11893 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11894 s.select_ranges(new_selection_ranges);
11895 });
11896 }
11897
11898 pub fn add_selection_above(
11899 &mut self,
11900 _: &AddSelectionAbove,
11901 window: &mut Window,
11902 cx: &mut Context<Self>,
11903 ) {
11904 self.add_selection(true, window, cx);
11905 }
11906
11907 pub fn add_selection_below(
11908 &mut self,
11909 _: &AddSelectionBelow,
11910 window: &mut Window,
11911 cx: &mut Context<Self>,
11912 ) {
11913 self.add_selection(false, window, cx);
11914 }
11915
11916 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11917 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11918
11919 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11920 let mut selections = self.selections.all::<Point>(cx);
11921 let text_layout_details = self.text_layout_details(window);
11922 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11923 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11924 let range = oldest_selection.display_range(&display_map).sorted();
11925
11926 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11927 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11928 let positions = start_x.min(end_x)..start_x.max(end_x);
11929
11930 selections.clear();
11931 let mut stack = Vec::new();
11932 for row in range.start.row().0..=range.end.row().0 {
11933 if let Some(selection) = self.selections.build_columnar_selection(
11934 &display_map,
11935 DisplayRow(row),
11936 &positions,
11937 oldest_selection.reversed,
11938 &text_layout_details,
11939 ) {
11940 stack.push(selection.id);
11941 selections.push(selection);
11942 }
11943 }
11944
11945 if above {
11946 stack.reverse();
11947 }
11948
11949 AddSelectionsState { above, stack }
11950 });
11951
11952 let last_added_selection = *state.stack.last().unwrap();
11953 let mut new_selections = Vec::new();
11954 if above == state.above {
11955 let end_row = if above {
11956 DisplayRow(0)
11957 } else {
11958 display_map.max_point().row()
11959 };
11960
11961 'outer: for selection in selections {
11962 if selection.id == last_added_selection {
11963 let range = selection.display_range(&display_map).sorted();
11964 debug_assert_eq!(range.start.row(), range.end.row());
11965 let mut row = range.start.row();
11966 let positions =
11967 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11968 px(start)..px(end)
11969 } else {
11970 let start_x =
11971 display_map.x_for_display_point(range.start, &text_layout_details);
11972 let end_x =
11973 display_map.x_for_display_point(range.end, &text_layout_details);
11974 start_x.min(end_x)..start_x.max(end_x)
11975 };
11976
11977 while row != end_row {
11978 if above {
11979 row.0 -= 1;
11980 } else {
11981 row.0 += 1;
11982 }
11983
11984 if let Some(new_selection) = self.selections.build_columnar_selection(
11985 &display_map,
11986 row,
11987 &positions,
11988 selection.reversed,
11989 &text_layout_details,
11990 ) {
11991 state.stack.push(new_selection.id);
11992 if above {
11993 new_selections.push(new_selection);
11994 new_selections.push(selection);
11995 } else {
11996 new_selections.push(selection);
11997 new_selections.push(new_selection);
11998 }
11999
12000 continue 'outer;
12001 }
12002 }
12003 }
12004
12005 new_selections.push(selection);
12006 }
12007 } else {
12008 new_selections = selections;
12009 new_selections.retain(|s| s.id != last_added_selection);
12010 state.stack.pop();
12011 }
12012
12013 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12014 s.select(new_selections);
12015 });
12016 if state.stack.len() > 1 {
12017 self.add_selections_state = Some(state);
12018 }
12019 }
12020
12021 pub fn select_next_match_internal(
12022 &mut self,
12023 display_map: &DisplaySnapshot,
12024 replace_newest: bool,
12025 autoscroll: Option<Autoscroll>,
12026 window: &mut Window,
12027 cx: &mut Context<Self>,
12028 ) -> Result<()> {
12029 fn select_next_match_ranges(
12030 this: &mut Editor,
12031 range: Range<usize>,
12032 reversed: bool,
12033 replace_newest: bool,
12034 auto_scroll: Option<Autoscroll>,
12035 window: &mut Window,
12036 cx: &mut Context<Editor>,
12037 ) {
12038 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12039 this.change_selections(auto_scroll, window, cx, |s| {
12040 if replace_newest {
12041 s.delete(s.newest_anchor().id);
12042 }
12043 if reversed {
12044 s.insert_range(range.end..range.start);
12045 } else {
12046 s.insert_range(range);
12047 }
12048 });
12049 }
12050
12051 let buffer = &display_map.buffer_snapshot;
12052 let mut selections = self.selections.all::<usize>(cx);
12053 if let Some(mut select_next_state) = self.select_next_state.take() {
12054 let query = &select_next_state.query;
12055 if !select_next_state.done {
12056 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12057 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12058 let mut next_selected_range = None;
12059
12060 let bytes_after_last_selection =
12061 buffer.bytes_in_range(last_selection.end..buffer.len());
12062 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12063 let query_matches = query
12064 .stream_find_iter(bytes_after_last_selection)
12065 .map(|result| (last_selection.end, result))
12066 .chain(
12067 query
12068 .stream_find_iter(bytes_before_first_selection)
12069 .map(|result| (0, result)),
12070 );
12071
12072 for (start_offset, query_match) in query_matches {
12073 let query_match = query_match.unwrap(); // can only fail due to I/O
12074 let offset_range =
12075 start_offset + query_match.start()..start_offset + query_match.end();
12076 let display_range = offset_range.start.to_display_point(display_map)
12077 ..offset_range.end.to_display_point(display_map);
12078
12079 if !select_next_state.wordwise
12080 || (!movement::is_inside_word(display_map, display_range.start)
12081 && !movement::is_inside_word(display_map, display_range.end))
12082 {
12083 // TODO: This is n^2, because we might check all the selections
12084 if !selections
12085 .iter()
12086 .any(|selection| selection.range().overlaps(&offset_range))
12087 {
12088 next_selected_range = Some(offset_range);
12089 break;
12090 }
12091 }
12092 }
12093
12094 if let Some(next_selected_range) = next_selected_range {
12095 select_next_match_ranges(
12096 self,
12097 next_selected_range,
12098 last_selection.reversed,
12099 replace_newest,
12100 autoscroll,
12101 window,
12102 cx,
12103 );
12104 } else {
12105 select_next_state.done = true;
12106 }
12107 }
12108
12109 self.select_next_state = Some(select_next_state);
12110 } else {
12111 let mut only_carets = true;
12112 let mut same_text_selected = true;
12113 let mut selected_text = None;
12114
12115 let mut selections_iter = selections.iter().peekable();
12116 while let Some(selection) = selections_iter.next() {
12117 if selection.start != selection.end {
12118 only_carets = false;
12119 }
12120
12121 if same_text_selected {
12122 if selected_text.is_none() {
12123 selected_text =
12124 Some(buffer.text_for_range(selection.range()).collect::<String>());
12125 }
12126
12127 if let Some(next_selection) = selections_iter.peek() {
12128 if next_selection.range().len() == selection.range().len() {
12129 let next_selected_text = buffer
12130 .text_for_range(next_selection.range())
12131 .collect::<String>();
12132 if Some(next_selected_text) != selected_text {
12133 same_text_selected = false;
12134 selected_text = None;
12135 }
12136 } else {
12137 same_text_selected = false;
12138 selected_text = None;
12139 }
12140 }
12141 }
12142 }
12143
12144 if only_carets {
12145 for selection in &mut selections {
12146 let word_range = movement::surrounding_word(
12147 display_map,
12148 selection.start.to_display_point(display_map),
12149 );
12150 selection.start = word_range.start.to_offset(display_map, Bias::Left);
12151 selection.end = word_range.end.to_offset(display_map, Bias::Left);
12152 selection.goal = SelectionGoal::None;
12153 selection.reversed = false;
12154 select_next_match_ranges(
12155 self,
12156 selection.start..selection.end,
12157 selection.reversed,
12158 replace_newest,
12159 autoscroll,
12160 window,
12161 cx,
12162 );
12163 }
12164
12165 if selections.len() == 1 {
12166 let selection = selections
12167 .last()
12168 .expect("ensured that there's only one selection");
12169 let query = buffer
12170 .text_for_range(selection.start..selection.end)
12171 .collect::<String>();
12172 let is_empty = query.is_empty();
12173 let select_state = SelectNextState {
12174 query: AhoCorasick::new(&[query])?,
12175 wordwise: true,
12176 done: is_empty,
12177 };
12178 self.select_next_state = Some(select_state);
12179 } else {
12180 self.select_next_state = None;
12181 }
12182 } else if let Some(selected_text) = selected_text {
12183 self.select_next_state = Some(SelectNextState {
12184 query: AhoCorasick::new(&[selected_text])?,
12185 wordwise: false,
12186 done: false,
12187 });
12188 self.select_next_match_internal(
12189 display_map,
12190 replace_newest,
12191 autoscroll,
12192 window,
12193 cx,
12194 )?;
12195 }
12196 }
12197 Ok(())
12198 }
12199
12200 pub fn select_all_matches(
12201 &mut self,
12202 _action: &SelectAllMatches,
12203 window: &mut Window,
12204 cx: &mut Context<Self>,
12205 ) -> Result<()> {
12206 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12207
12208 self.push_to_selection_history();
12209 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12210
12211 self.select_next_match_internal(&display_map, false, None, window, cx)?;
12212 let Some(select_next_state) = self.select_next_state.as_mut() else {
12213 return Ok(());
12214 };
12215 if select_next_state.done {
12216 return Ok(());
12217 }
12218
12219 let mut new_selections = Vec::new();
12220
12221 let reversed = self.selections.oldest::<usize>(cx).reversed;
12222 let buffer = &display_map.buffer_snapshot;
12223 let query_matches = select_next_state
12224 .query
12225 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12226
12227 for query_match in query_matches.into_iter() {
12228 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12229 let offset_range = if reversed {
12230 query_match.end()..query_match.start()
12231 } else {
12232 query_match.start()..query_match.end()
12233 };
12234 let display_range = offset_range.start.to_display_point(&display_map)
12235 ..offset_range.end.to_display_point(&display_map);
12236
12237 if !select_next_state.wordwise
12238 || (!movement::is_inside_word(&display_map, display_range.start)
12239 && !movement::is_inside_word(&display_map, display_range.end))
12240 {
12241 new_selections.push(offset_range.start..offset_range.end);
12242 }
12243 }
12244
12245 select_next_state.done = true;
12246 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12247 self.change_selections(None, window, cx, |selections| {
12248 selections.select_ranges(new_selections)
12249 });
12250
12251 Ok(())
12252 }
12253
12254 pub fn select_next(
12255 &mut self,
12256 action: &SelectNext,
12257 window: &mut Window,
12258 cx: &mut Context<Self>,
12259 ) -> Result<()> {
12260 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12261 self.push_to_selection_history();
12262 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12263 self.select_next_match_internal(
12264 &display_map,
12265 action.replace_newest,
12266 Some(Autoscroll::newest()),
12267 window,
12268 cx,
12269 )?;
12270 Ok(())
12271 }
12272
12273 pub fn select_previous(
12274 &mut self,
12275 action: &SelectPrevious,
12276 window: &mut Window,
12277 cx: &mut Context<Self>,
12278 ) -> Result<()> {
12279 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12280 self.push_to_selection_history();
12281 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12282 let buffer = &display_map.buffer_snapshot;
12283 let mut selections = self.selections.all::<usize>(cx);
12284 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12285 let query = &select_prev_state.query;
12286 if !select_prev_state.done {
12287 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12288 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12289 let mut next_selected_range = None;
12290 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12291 let bytes_before_last_selection =
12292 buffer.reversed_bytes_in_range(0..last_selection.start);
12293 let bytes_after_first_selection =
12294 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12295 let query_matches = query
12296 .stream_find_iter(bytes_before_last_selection)
12297 .map(|result| (last_selection.start, result))
12298 .chain(
12299 query
12300 .stream_find_iter(bytes_after_first_selection)
12301 .map(|result| (buffer.len(), result)),
12302 );
12303 for (end_offset, query_match) in query_matches {
12304 let query_match = query_match.unwrap(); // can only fail due to I/O
12305 let offset_range =
12306 end_offset - query_match.end()..end_offset - query_match.start();
12307 let display_range = offset_range.start.to_display_point(&display_map)
12308 ..offset_range.end.to_display_point(&display_map);
12309
12310 if !select_prev_state.wordwise
12311 || (!movement::is_inside_word(&display_map, display_range.start)
12312 && !movement::is_inside_word(&display_map, display_range.end))
12313 {
12314 next_selected_range = Some(offset_range);
12315 break;
12316 }
12317 }
12318
12319 if let Some(next_selected_range) = next_selected_range {
12320 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12321 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12322 if action.replace_newest {
12323 s.delete(s.newest_anchor().id);
12324 }
12325 if last_selection.reversed {
12326 s.insert_range(next_selected_range.end..next_selected_range.start);
12327 } else {
12328 s.insert_range(next_selected_range);
12329 }
12330 });
12331 } else {
12332 select_prev_state.done = true;
12333 }
12334 }
12335
12336 self.select_prev_state = Some(select_prev_state);
12337 } else {
12338 let mut only_carets = true;
12339 let mut same_text_selected = true;
12340 let mut selected_text = None;
12341
12342 let mut selections_iter = selections.iter().peekable();
12343 while let Some(selection) = selections_iter.next() {
12344 if selection.start != selection.end {
12345 only_carets = false;
12346 }
12347
12348 if same_text_selected {
12349 if selected_text.is_none() {
12350 selected_text =
12351 Some(buffer.text_for_range(selection.range()).collect::<String>());
12352 }
12353
12354 if let Some(next_selection) = selections_iter.peek() {
12355 if next_selection.range().len() == selection.range().len() {
12356 let next_selected_text = buffer
12357 .text_for_range(next_selection.range())
12358 .collect::<String>();
12359 if Some(next_selected_text) != selected_text {
12360 same_text_selected = false;
12361 selected_text = None;
12362 }
12363 } else {
12364 same_text_selected = false;
12365 selected_text = None;
12366 }
12367 }
12368 }
12369 }
12370
12371 if only_carets {
12372 for selection in &mut selections {
12373 let word_range = movement::surrounding_word(
12374 &display_map,
12375 selection.start.to_display_point(&display_map),
12376 );
12377 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12378 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12379 selection.goal = SelectionGoal::None;
12380 selection.reversed = false;
12381 }
12382 if selections.len() == 1 {
12383 let selection = selections
12384 .last()
12385 .expect("ensured that there's only one selection");
12386 let query = buffer
12387 .text_for_range(selection.start..selection.end)
12388 .collect::<String>();
12389 let is_empty = query.is_empty();
12390 let select_state = SelectNextState {
12391 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12392 wordwise: true,
12393 done: is_empty,
12394 };
12395 self.select_prev_state = Some(select_state);
12396 } else {
12397 self.select_prev_state = None;
12398 }
12399
12400 self.unfold_ranges(
12401 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12402 false,
12403 true,
12404 cx,
12405 );
12406 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12407 s.select(selections);
12408 });
12409 } else if let Some(selected_text) = selected_text {
12410 self.select_prev_state = Some(SelectNextState {
12411 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12412 wordwise: false,
12413 done: false,
12414 });
12415 self.select_previous(action, window, cx)?;
12416 }
12417 }
12418 Ok(())
12419 }
12420
12421 pub fn find_next_match(
12422 &mut self,
12423 _: &FindNextMatch,
12424 window: &mut Window,
12425 cx: &mut Context<Self>,
12426 ) -> Result<()> {
12427 let selections = self.selections.disjoint_anchors();
12428 match selections.first() {
12429 Some(first) if selections.len() >= 2 => {
12430 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12431 s.select_ranges([first.range()]);
12432 });
12433 }
12434 _ => self.select_next(
12435 &SelectNext {
12436 replace_newest: true,
12437 },
12438 window,
12439 cx,
12440 )?,
12441 }
12442 Ok(())
12443 }
12444
12445 pub fn find_previous_match(
12446 &mut self,
12447 _: &FindPreviousMatch,
12448 window: &mut Window,
12449 cx: &mut Context<Self>,
12450 ) -> Result<()> {
12451 let selections = self.selections.disjoint_anchors();
12452 match selections.last() {
12453 Some(last) if selections.len() >= 2 => {
12454 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12455 s.select_ranges([last.range()]);
12456 });
12457 }
12458 _ => self.select_previous(
12459 &SelectPrevious {
12460 replace_newest: true,
12461 },
12462 window,
12463 cx,
12464 )?,
12465 }
12466 Ok(())
12467 }
12468
12469 pub fn toggle_comments(
12470 &mut self,
12471 action: &ToggleComments,
12472 window: &mut Window,
12473 cx: &mut Context<Self>,
12474 ) {
12475 if self.read_only(cx) {
12476 return;
12477 }
12478 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12479 let text_layout_details = &self.text_layout_details(window);
12480 self.transact(window, cx, |this, window, cx| {
12481 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12482 let mut edits = Vec::new();
12483 let mut selection_edit_ranges = Vec::new();
12484 let mut last_toggled_row = None;
12485 let snapshot = this.buffer.read(cx).read(cx);
12486 let empty_str: Arc<str> = Arc::default();
12487 let mut suffixes_inserted = Vec::new();
12488 let ignore_indent = action.ignore_indent;
12489
12490 fn comment_prefix_range(
12491 snapshot: &MultiBufferSnapshot,
12492 row: MultiBufferRow,
12493 comment_prefix: &str,
12494 comment_prefix_whitespace: &str,
12495 ignore_indent: bool,
12496 ) -> Range<Point> {
12497 let indent_size = if ignore_indent {
12498 0
12499 } else {
12500 snapshot.indent_size_for_line(row).len
12501 };
12502
12503 let start = Point::new(row.0, indent_size);
12504
12505 let mut line_bytes = snapshot
12506 .bytes_in_range(start..snapshot.max_point())
12507 .flatten()
12508 .copied();
12509
12510 // If this line currently begins with the line comment prefix, then record
12511 // the range containing the prefix.
12512 if line_bytes
12513 .by_ref()
12514 .take(comment_prefix.len())
12515 .eq(comment_prefix.bytes())
12516 {
12517 // Include any whitespace that matches the comment prefix.
12518 let matching_whitespace_len = line_bytes
12519 .zip(comment_prefix_whitespace.bytes())
12520 .take_while(|(a, b)| a == b)
12521 .count() as u32;
12522 let end = Point::new(
12523 start.row,
12524 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12525 );
12526 start..end
12527 } else {
12528 start..start
12529 }
12530 }
12531
12532 fn comment_suffix_range(
12533 snapshot: &MultiBufferSnapshot,
12534 row: MultiBufferRow,
12535 comment_suffix: &str,
12536 comment_suffix_has_leading_space: bool,
12537 ) -> Range<Point> {
12538 let end = Point::new(row.0, snapshot.line_len(row));
12539 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12540
12541 let mut line_end_bytes = snapshot
12542 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12543 .flatten()
12544 .copied();
12545
12546 let leading_space_len = if suffix_start_column > 0
12547 && line_end_bytes.next() == Some(b' ')
12548 && comment_suffix_has_leading_space
12549 {
12550 1
12551 } else {
12552 0
12553 };
12554
12555 // If this line currently begins with the line comment prefix, then record
12556 // the range containing the prefix.
12557 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12558 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12559 start..end
12560 } else {
12561 end..end
12562 }
12563 }
12564
12565 // TODO: Handle selections that cross excerpts
12566 for selection in &mut selections {
12567 let start_column = snapshot
12568 .indent_size_for_line(MultiBufferRow(selection.start.row))
12569 .len;
12570 let language = if let Some(language) =
12571 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12572 {
12573 language
12574 } else {
12575 continue;
12576 };
12577
12578 selection_edit_ranges.clear();
12579
12580 // If multiple selections contain a given row, avoid processing that
12581 // row more than once.
12582 let mut start_row = MultiBufferRow(selection.start.row);
12583 if last_toggled_row == Some(start_row) {
12584 start_row = start_row.next_row();
12585 }
12586 let end_row =
12587 if selection.end.row > selection.start.row && selection.end.column == 0 {
12588 MultiBufferRow(selection.end.row - 1)
12589 } else {
12590 MultiBufferRow(selection.end.row)
12591 };
12592 last_toggled_row = Some(end_row);
12593
12594 if start_row > end_row {
12595 continue;
12596 }
12597
12598 // If the language has line comments, toggle those.
12599 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12600
12601 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12602 if ignore_indent {
12603 full_comment_prefixes = full_comment_prefixes
12604 .into_iter()
12605 .map(|s| Arc::from(s.trim_end()))
12606 .collect();
12607 }
12608
12609 if !full_comment_prefixes.is_empty() {
12610 let first_prefix = full_comment_prefixes
12611 .first()
12612 .expect("prefixes is non-empty");
12613 let prefix_trimmed_lengths = full_comment_prefixes
12614 .iter()
12615 .map(|p| p.trim_end_matches(' ').len())
12616 .collect::<SmallVec<[usize; 4]>>();
12617
12618 let mut all_selection_lines_are_comments = true;
12619
12620 for row in start_row.0..=end_row.0 {
12621 let row = MultiBufferRow(row);
12622 if start_row < end_row && snapshot.is_line_blank(row) {
12623 continue;
12624 }
12625
12626 let prefix_range = full_comment_prefixes
12627 .iter()
12628 .zip(prefix_trimmed_lengths.iter().copied())
12629 .map(|(prefix, trimmed_prefix_len)| {
12630 comment_prefix_range(
12631 snapshot.deref(),
12632 row,
12633 &prefix[..trimmed_prefix_len],
12634 &prefix[trimmed_prefix_len..],
12635 ignore_indent,
12636 )
12637 })
12638 .max_by_key(|range| range.end.column - range.start.column)
12639 .expect("prefixes is non-empty");
12640
12641 if prefix_range.is_empty() {
12642 all_selection_lines_are_comments = false;
12643 }
12644
12645 selection_edit_ranges.push(prefix_range);
12646 }
12647
12648 if all_selection_lines_are_comments {
12649 edits.extend(
12650 selection_edit_ranges
12651 .iter()
12652 .cloned()
12653 .map(|range| (range, empty_str.clone())),
12654 );
12655 } else {
12656 let min_column = selection_edit_ranges
12657 .iter()
12658 .map(|range| range.start.column)
12659 .min()
12660 .unwrap_or(0);
12661 edits.extend(selection_edit_ranges.iter().map(|range| {
12662 let position = Point::new(range.start.row, min_column);
12663 (position..position, first_prefix.clone())
12664 }));
12665 }
12666 } else if let Some((full_comment_prefix, comment_suffix)) =
12667 language.block_comment_delimiters()
12668 {
12669 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12670 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12671 let prefix_range = comment_prefix_range(
12672 snapshot.deref(),
12673 start_row,
12674 comment_prefix,
12675 comment_prefix_whitespace,
12676 ignore_indent,
12677 );
12678 let suffix_range = comment_suffix_range(
12679 snapshot.deref(),
12680 end_row,
12681 comment_suffix.trim_start_matches(' '),
12682 comment_suffix.starts_with(' '),
12683 );
12684
12685 if prefix_range.is_empty() || suffix_range.is_empty() {
12686 edits.push((
12687 prefix_range.start..prefix_range.start,
12688 full_comment_prefix.clone(),
12689 ));
12690 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12691 suffixes_inserted.push((end_row, comment_suffix.len()));
12692 } else {
12693 edits.push((prefix_range, empty_str.clone()));
12694 edits.push((suffix_range, empty_str.clone()));
12695 }
12696 } else {
12697 continue;
12698 }
12699 }
12700
12701 drop(snapshot);
12702 this.buffer.update(cx, |buffer, cx| {
12703 buffer.edit(edits, None, cx);
12704 });
12705
12706 // Adjust selections so that they end before any comment suffixes that
12707 // were inserted.
12708 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12709 let mut selections = this.selections.all::<Point>(cx);
12710 let snapshot = this.buffer.read(cx).read(cx);
12711 for selection in &mut selections {
12712 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12713 match row.cmp(&MultiBufferRow(selection.end.row)) {
12714 Ordering::Less => {
12715 suffixes_inserted.next();
12716 continue;
12717 }
12718 Ordering::Greater => break,
12719 Ordering::Equal => {
12720 if selection.end.column == snapshot.line_len(row) {
12721 if selection.is_empty() {
12722 selection.start.column -= suffix_len as u32;
12723 }
12724 selection.end.column -= suffix_len as u32;
12725 }
12726 break;
12727 }
12728 }
12729 }
12730 }
12731
12732 drop(snapshot);
12733 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12734 s.select(selections)
12735 });
12736
12737 let selections = this.selections.all::<Point>(cx);
12738 let selections_on_single_row = selections.windows(2).all(|selections| {
12739 selections[0].start.row == selections[1].start.row
12740 && selections[0].end.row == selections[1].end.row
12741 && selections[0].start.row == selections[0].end.row
12742 });
12743 let selections_selecting = selections
12744 .iter()
12745 .any(|selection| selection.start != selection.end);
12746 let advance_downwards = action.advance_downwards
12747 && selections_on_single_row
12748 && !selections_selecting
12749 && !matches!(this.mode, EditorMode::SingleLine { .. });
12750
12751 if advance_downwards {
12752 let snapshot = this.buffer.read(cx).snapshot(cx);
12753
12754 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12755 s.move_cursors_with(|display_snapshot, display_point, _| {
12756 let mut point = display_point.to_point(display_snapshot);
12757 point.row += 1;
12758 point = snapshot.clip_point(point, Bias::Left);
12759 let display_point = point.to_display_point(display_snapshot);
12760 let goal = SelectionGoal::HorizontalPosition(
12761 display_snapshot
12762 .x_for_display_point(display_point, text_layout_details)
12763 .into(),
12764 );
12765 (display_point, goal)
12766 })
12767 });
12768 }
12769 });
12770 }
12771
12772 pub fn select_enclosing_symbol(
12773 &mut self,
12774 _: &SelectEnclosingSymbol,
12775 window: &mut Window,
12776 cx: &mut Context<Self>,
12777 ) {
12778 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12779
12780 let buffer = self.buffer.read(cx).snapshot(cx);
12781 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12782
12783 fn update_selection(
12784 selection: &Selection<usize>,
12785 buffer_snap: &MultiBufferSnapshot,
12786 ) -> Option<Selection<usize>> {
12787 let cursor = selection.head();
12788 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12789 for symbol in symbols.iter().rev() {
12790 let start = symbol.range.start.to_offset(buffer_snap);
12791 let end = symbol.range.end.to_offset(buffer_snap);
12792 let new_range = start..end;
12793 if start < selection.start || end > selection.end {
12794 return Some(Selection {
12795 id: selection.id,
12796 start: new_range.start,
12797 end: new_range.end,
12798 goal: SelectionGoal::None,
12799 reversed: selection.reversed,
12800 });
12801 }
12802 }
12803 None
12804 }
12805
12806 let mut selected_larger_symbol = false;
12807 let new_selections = old_selections
12808 .iter()
12809 .map(|selection| match update_selection(selection, &buffer) {
12810 Some(new_selection) => {
12811 if new_selection.range() != selection.range() {
12812 selected_larger_symbol = true;
12813 }
12814 new_selection
12815 }
12816 None => selection.clone(),
12817 })
12818 .collect::<Vec<_>>();
12819
12820 if selected_larger_symbol {
12821 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12822 s.select(new_selections);
12823 });
12824 }
12825 }
12826
12827 pub fn select_larger_syntax_node(
12828 &mut self,
12829 _: &SelectLargerSyntaxNode,
12830 window: &mut Window,
12831 cx: &mut Context<Self>,
12832 ) {
12833 let Some(visible_row_count) = self.visible_row_count() else {
12834 return;
12835 };
12836 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12837 if old_selections.is_empty() {
12838 return;
12839 }
12840
12841 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12842
12843 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12844 let buffer = self.buffer.read(cx).snapshot(cx);
12845
12846 let mut selected_larger_node = false;
12847 let mut new_selections = old_selections
12848 .iter()
12849 .map(|selection| {
12850 let old_range = selection.start..selection.end;
12851
12852 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12853 // manually select word at selection
12854 if ["string_content", "inline"].contains(&node.kind()) {
12855 let word_range = {
12856 let display_point = buffer
12857 .offset_to_point(old_range.start)
12858 .to_display_point(&display_map);
12859 let Range { start, end } =
12860 movement::surrounding_word(&display_map, display_point);
12861 start.to_point(&display_map).to_offset(&buffer)
12862 ..end.to_point(&display_map).to_offset(&buffer)
12863 };
12864 // ignore if word is already selected
12865 if !word_range.is_empty() && old_range != word_range {
12866 let last_word_range = {
12867 let display_point = buffer
12868 .offset_to_point(old_range.end)
12869 .to_display_point(&display_map);
12870 let Range { start, end } =
12871 movement::surrounding_word(&display_map, display_point);
12872 start.to_point(&display_map).to_offset(&buffer)
12873 ..end.to_point(&display_map).to_offset(&buffer)
12874 };
12875 // only select word if start and end point belongs to same word
12876 if word_range == last_word_range {
12877 selected_larger_node = true;
12878 return Selection {
12879 id: selection.id,
12880 start: word_range.start,
12881 end: word_range.end,
12882 goal: SelectionGoal::None,
12883 reversed: selection.reversed,
12884 };
12885 }
12886 }
12887 }
12888 }
12889
12890 let mut new_range = old_range.clone();
12891 let mut new_node = None;
12892 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12893 {
12894 new_node = Some(node);
12895 new_range = match containing_range {
12896 MultiOrSingleBufferOffsetRange::Single(_) => break,
12897 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12898 };
12899 if !display_map.intersects_fold(new_range.start)
12900 && !display_map.intersects_fold(new_range.end)
12901 {
12902 break;
12903 }
12904 }
12905
12906 if let Some(node) = new_node {
12907 // Log the ancestor, to support using this action as a way to explore TreeSitter
12908 // nodes. Parent and grandparent are also logged because this operation will not
12909 // visit nodes that have the same range as their parent.
12910 log::info!("Node: {node:?}");
12911 let parent = node.parent();
12912 log::info!("Parent: {parent:?}");
12913 let grandparent = parent.and_then(|x| x.parent());
12914 log::info!("Grandparent: {grandparent:?}");
12915 }
12916
12917 selected_larger_node |= new_range != old_range;
12918 Selection {
12919 id: selection.id,
12920 start: new_range.start,
12921 end: new_range.end,
12922 goal: SelectionGoal::None,
12923 reversed: selection.reversed,
12924 }
12925 })
12926 .collect::<Vec<_>>();
12927
12928 if !selected_larger_node {
12929 return; // don't put this call in the history
12930 }
12931
12932 // scroll based on transformation done to the last selection created by the user
12933 let (last_old, last_new) = old_selections
12934 .last()
12935 .zip(new_selections.last().cloned())
12936 .expect("old_selections isn't empty");
12937
12938 // revert selection
12939 let is_selection_reversed = {
12940 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12941 new_selections.last_mut().expect("checked above").reversed =
12942 should_newest_selection_be_reversed;
12943 should_newest_selection_be_reversed
12944 };
12945
12946 if selected_larger_node {
12947 self.select_syntax_node_history.disable_clearing = true;
12948 self.change_selections(None, window, cx, |s| {
12949 s.select(new_selections.clone());
12950 });
12951 self.select_syntax_node_history.disable_clearing = false;
12952 }
12953
12954 let start_row = last_new.start.to_display_point(&display_map).row().0;
12955 let end_row = last_new.end.to_display_point(&display_map).row().0;
12956 let selection_height = end_row - start_row + 1;
12957 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12958
12959 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12960 let scroll_behavior = if fits_on_the_screen {
12961 self.request_autoscroll(Autoscroll::fit(), cx);
12962 SelectSyntaxNodeScrollBehavior::FitSelection
12963 } else if is_selection_reversed {
12964 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12965 SelectSyntaxNodeScrollBehavior::CursorTop
12966 } else {
12967 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12968 SelectSyntaxNodeScrollBehavior::CursorBottom
12969 };
12970
12971 self.select_syntax_node_history.push((
12972 old_selections,
12973 scroll_behavior,
12974 is_selection_reversed,
12975 ));
12976 }
12977
12978 pub fn select_smaller_syntax_node(
12979 &mut self,
12980 _: &SelectSmallerSyntaxNode,
12981 window: &mut Window,
12982 cx: &mut Context<Self>,
12983 ) {
12984 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12985
12986 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12987 self.select_syntax_node_history.pop()
12988 {
12989 if let Some(selection) = selections.last_mut() {
12990 selection.reversed = is_selection_reversed;
12991 }
12992
12993 self.select_syntax_node_history.disable_clearing = true;
12994 self.change_selections(None, window, cx, |s| {
12995 s.select(selections.to_vec());
12996 });
12997 self.select_syntax_node_history.disable_clearing = false;
12998
12999 match scroll_behavior {
13000 SelectSyntaxNodeScrollBehavior::CursorTop => {
13001 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13002 }
13003 SelectSyntaxNodeScrollBehavior::FitSelection => {
13004 self.request_autoscroll(Autoscroll::fit(), cx);
13005 }
13006 SelectSyntaxNodeScrollBehavior::CursorBottom => {
13007 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13008 }
13009 }
13010 }
13011 }
13012
13013 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13014 if !EditorSettings::get_global(cx).gutter.runnables {
13015 self.clear_tasks();
13016 return Task::ready(());
13017 }
13018 let project = self.project.as_ref().map(Entity::downgrade);
13019 let task_sources = self.lsp_task_sources(cx);
13020 cx.spawn_in(window, async move |editor, cx| {
13021 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13022 let Some(project) = project.and_then(|p| p.upgrade()) else {
13023 return;
13024 };
13025 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13026 this.display_map.update(cx, |map, cx| map.snapshot(cx))
13027 }) else {
13028 return;
13029 };
13030
13031 let hide_runnables = project
13032 .update(cx, |project, cx| {
13033 // Do not display any test indicators in non-dev server remote projects.
13034 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13035 })
13036 .unwrap_or(true);
13037 if hide_runnables {
13038 return;
13039 }
13040 let new_rows =
13041 cx.background_spawn({
13042 let snapshot = display_snapshot.clone();
13043 async move {
13044 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13045 }
13046 })
13047 .await;
13048 let Ok(lsp_tasks) =
13049 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13050 else {
13051 return;
13052 };
13053 let lsp_tasks = lsp_tasks.await;
13054
13055 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13056 lsp_tasks
13057 .into_iter()
13058 .flat_map(|(kind, tasks)| {
13059 tasks.into_iter().filter_map(move |(location, task)| {
13060 Some((kind.clone(), location?, task))
13061 })
13062 })
13063 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13064 let buffer = location.target.buffer;
13065 let buffer_snapshot = buffer.read(cx).snapshot();
13066 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13067 |(excerpt_id, snapshot, _)| {
13068 if snapshot.remote_id() == buffer_snapshot.remote_id() {
13069 display_snapshot
13070 .buffer_snapshot
13071 .anchor_in_excerpt(excerpt_id, location.target.range.start)
13072 } else {
13073 None
13074 }
13075 },
13076 );
13077 if let Some(offset) = offset {
13078 let task_buffer_range =
13079 location.target.range.to_point(&buffer_snapshot);
13080 let context_buffer_range =
13081 task_buffer_range.to_offset(&buffer_snapshot);
13082 let context_range = BufferOffset(context_buffer_range.start)
13083 ..BufferOffset(context_buffer_range.end);
13084
13085 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13086 .or_insert_with(|| RunnableTasks {
13087 templates: Vec::new(),
13088 offset,
13089 column: task_buffer_range.start.column,
13090 extra_variables: HashMap::default(),
13091 context_range,
13092 })
13093 .templates
13094 .push((kind, task.original_task().clone()));
13095 }
13096
13097 acc
13098 })
13099 }) else {
13100 return;
13101 };
13102
13103 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13104 editor
13105 .update(cx, |editor, _| {
13106 editor.clear_tasks();
13107 for (key, mut value) in rows {
13108 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13109 value.templates.extend(lsp_tasks.templates);
13110 }
13111
13112 editor.insert_tasks(key, value);
13113 }
13114 for (key, value) in lsp_tasks_by_rows {
13115 editor.insert_tasks(key, value);
13116 }
13117 })
13118 .ok();
13119 })
13120 }
13121 fn fetch_runnable_ranges(
13122 snapshot: &DisplaySnapshot,
13123 range: Range<Anchor>,
13124 ) -> Vec<language::RunnableRange> {
13125 snapshot.buffer_snapshot.runnable_ranges(range).collect()
13126 }
13127
13128 fn runnable_rows(
13129 project: Entity<Project>,
13130 snapshot: DisplaySnapshot,
13131 runnable_ranges: Vec<RunnableRange>,
13132 mut cx: AsyncWindowContext,
13133 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13134 runnable_ranges
13135 .into_iter()
13136 .filter_map(|mut runnable| {
13137 let tasks = cx
13138 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13139 .ok()?;
13140 if tasks.is_empty() {
13141 return None;
13142 }
13143
13144 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13145
13146 let row = snapshot
13147 .buffer_snapshot
13148 .buffer_line_for_row(MultiBufferRow(point.row))?
13149 .1
13150 .start
13151 .row;
13152
13153 let context_range =
13154 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13155 Some((
13156 (runnable.buffer_id, row),
13157 RunnableTasks {
13158 templates: tasks,
13159 offset: snapshot
13160 .buffer_snapshot
13161 .anchor_before(runnable.run_range.start),
13162 context_range,
13163 column: point.column,
13164 extra_variables: runnable.extra_captures,
13165 },
13166 ))
13167 })
13168 .collect()
13169 }
13170
13171 fn templates_with_tags(
13172 project: &Entity<Project>,
13173 runnable: &mut Runnable,
13174 cx: &mut App,
13175 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13176 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13177 let (worktree_id, file) = project
13178 .buffer_for_id(runnable.buffer, cx)
13179 .and_then(|buffer| buffer.read(cx).file())
13180 .map(|file| (file.worktree_id(cx), file.clone()))
13181 .unzip();
13182
13183 (
13184 project.task_store().read(cx).task_inventory().cloned(),
13185 worktree_id,
13186 file,
13187 )
13188 });
13189
13190 let mut templates_with_tags = mem::take(&mut runnable.tags)
13191 .into_iter()
13192 .flat_map(|RunnableTag(tag)| {
13193 inventory
13194 .as_ref()
13195 .into_iter()
13196 .flat_map(|inventory| {
13197 inventory.read(cx).list_tasks(
13198 file.clone(),
13199 Some(runnable.language.clone()),
13200 worktree_id,
13201 cx,
13202 )
13203 })
13204 .filter(move |(_, template)| {
13205 template.tags.iter().any(|source_tag| source_tag == &tag)
13206 })
13207 })
13208 .sorted_by_key(|(kind, _)| kind.to_owned())
13209 .collect::<Vec<_>>();
13210 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13211 // Strongest source wins; if we have worktree tag binding, prefer that to
13212 // global and language bindings;
13213 // if we have a global binding, prefer that to language binding.
13214 let first_mismatch = templates_with_tags
13215 .iter()
13216 .position(|(tag_source, _)| tag_source != leading_tag_source);
13217 if let Some(index) = first_mismatch {
13218 templates_with_tags.truncate(index);
13219 }
13220 }
13221
13222 templates_with_tags
13223 }
13224
13225 pub fn move_to_enclosing_bracket(
13226 &mut self,
13227 _: &MoveToEnclosingBracket,
13228 window: &mut Window,
13229 cx: &mut Context<Self>,
13230 ) {
13231 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13232 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13233 s.move_offsets_with(|snapshot, selection| {
13234 let Some(enclosing_bracket_ranges) =
13235 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13236 else {
13237 return;
13238 };
13239
13240 let mut best_length = usize::MAX;
13241 let mut best_inside = false;
13242 let mut best_in_bracket_range = false;
13243 let mut best_destination = None;
13244 for (open, close) in enclosing_bracket_ranges {
13245 let close = close.to_inclusive();
13246 let length = close.end() - open.start;
13247 let inside = selection.start >= open.end && selection.end <= *close.start();
13248 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13249 || close.contains(&selection.head());
13250
13251 // If best is next to a bracket and current isn't, skip
13252 if !in_bracket_range && best_in_bracket_range {
13253 continue;
13254 }
13255
13256 // Prefer smaller lengths unless best is inside and current isn't
13257 if length > best_length && (best_inside || !inside) {
13258 continue;
13259 }
13260
13261 best_length = length;
13262 best_inside = inside;
13263 best_in_bracket_range = in_bracket_range;
13264 best_destination = Some(
13265 if close.contains(&selection.start) && close.contains(&selection.end) {
13266 if inside { open.end } else { open.start }
13267 } else if inside {
13268 *close.start()
13269 } else {
13270 *close.end()
13271 },
13272 );
13273 }
13274
13275 if let Some(destination) = best_destination {
13276 selection.collapse_to(destination, SelectionGoal::None);
13277 }
13278 })
13279 });
13280 }
13281
13282 pub fn undo_selection(
13283 &mut self,
13284 _: &UndoSelection,
13285 window: &mut Window,
13286 cx: &mut Context<Self>,
13287 ) {
13288 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13289 self.end_selection(window, cx);
13290 self.selection_history.mode = SelectionHistoryMode::Undoing;
13291 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13292 self.change_selections(None, window, cx, |s| {
13293 s.select_anchors(entry.selections.to_vec())
13294 });
13295 self.select_next_state = entry.select_next_state;
13296 self.select_prev_state = entry.select_prev_state;
13297 self.add_selections_state = entry.add_selections_state;
13298 self.request_autoscroll(Autoscroll::newest(), cx);
13299 }
13300 self.selection_history.mode = SelectionHistoryMode::Normal;
13301 }
13302
13303 pub fn redo_selection(
13304 &mut self,
13305 _: &RedoSelection,
13306 window: &mut Window,
13307 cx: &mut Context<Self>,
13308 ) {
13309 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13310 self.end_selection(window, cx);
13311 self.selection_history.mode = SelectionHistoryMode::Redoing;
13312 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13313 self.change_selections(None, window, cx, |s| {
13314 s.select_anchors(entry.selections.to_vec())
13315 });
13316 self.select_next_state = entry.select_next_state;
13317 self.select_prev_state = entry.select_prev_state;
13318 self.add_selections_state = entry.add_selections_state;
13319 self.request_autoscroll(Autoscroll::newest(), cx);
13320 }
13321 self.selection_history.mode = SelectionHistoryMode::Normal;
13322 }
13323
13324 pub fn expand_excerpts(
13325 &mut self,
13326 action: &ExpandExcerpts,
13327 _: &mut Window,
13328 cx: &mut Context<Self>,
13329 ) {
13330 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13331 }
13332
13333 pub fn expand_excerpts_down(
13334 &mut self,
13335 action: &ExpandExcerptsDown,
13336 _: &mut Window,
13337 cx: &mut Context<Self>,
13338 ) {
13339 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13340 }
13341
13342 pub fn expand_excerpts_up(
13343 &mut self,
13344 action: &ExpandExcerptsUp,
13345 _: &mut Window,
13346 cx: &mut Context<Self>,
13347 ) {
13348 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13349 }
13350
13351 pub fn expand_excerpts_for_direction(
13352 &mut self,
13353 lines: u32,
13354 direction: ExpandExcerptDirection,
13355
13356 cx: &mut Context<Self>,
13357 ) {
13358 let selections = self.selections.disjoint_anchors();
13359
13360 let lines = if lines == 0 {
13361 EditorSettings::get_global(cx).expand_excerpt_lines
13362 } else {
13363 lines
13364 };
13365
13366 self.buffer.update(cx, |buffer, cx| {
13367 let snapshot = buffer.snapshot(cx);
13368 let mut excerpt_ids = selections
13369 .iter()
13370 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13371 .collect::<Vec<_>>();
13372 excerpt_ids.sort();
13373 excerpt_ids.dedup();
13374 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13375 })
13376 }
13377
13378 pub fn expand_excerpt(
13379 &mut self,
13380 excerpt: ExcerptId,
13381 direction: ExpandExcerptDirection,
13382 window: &mut Window,
13383 cx: &mut Context<Self>,
13384 ) {
13385 let current_scroll_position = self.scroll_position(cx);
13386 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13387 let mut should_scroll_up = false;
13388
13389 if direction == ExpandExcerptDirection::Down {
13390 let multi_buffer = self.buffer.read(cx);
13391 let snapshot = multi_buffer.snapshot(cx);
13392 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13393 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13394 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13395 let buffer_snapshot = buffer.read(cx).snapshot();
13396 let excerpt_end_row =
13397 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13398 let last_row = buffer_snapshot.max_point().row;
13399 let lines_below = last_row.saturating_sub(excerpt_end_row);
13400 should_scroll_up = lines_below >= lines_to_expand;
13401 }
13402 }
13403 }
13404 }
13405
13406 self.buffer.update(cx, |buffer, cx| {
13407 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13408 });
13409
13410 if should_scroll_up {
13411 let new_scroll_position =
13412 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13413 self.set_scroll_position(new_scroll_position, window, cx);
13414 }
13415 }
13416
13417 pub fn go_to_singleton_buffer_point(
13418 &mut self,
13419 point: Point,
13420 window: &mut Window,
13421 cx: &mut Context<Self>,
13422 ) {
13423 self.go_to_singleton_buffer_range(point..point, window, cx);
13424 }
13425
13426 pub fn go_to_singleton_buffer_range(
13427 &mut self,
13428 range: Range<Point>,
13429 window: &mut Window,
13430 cx: &mut Context<Self>,
13431 ) {
13432 let multibuffer = self.buffer().read(cx);
13433 let Some(buffer) = multibuffer.as_singleton() else {
13434 return;
13435 };
13436 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13437 return;
13438 };
13439 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13440 return;
13441 };
13442 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13443 s.select_anchor_ranges([start..end])
13444 });
13445 }
13446
13447 pub fn go_to_diagnostic(
13448 &mut self,
13449 _: &GoToDiagnostic,
13450 window: &mut Window,
13451 cx: &mut Context<Self>,
13452 ) {
13453 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13454 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13455 }
13456
13457 pub fn go_to_prev_diagnostic(
13458 &mut self,
13459 _: &GoToPreviousDiagnostic,
13460 window: &mut Window,
13461 cx: &mut Context<Self>,
13462 ) {
13463 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13464 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13465 }
13466
13467 pub fn go_to_diagnostic_impl(
13468 &mut self,
13469 direction: Direction,
13470 window: &mut Window,
13471 cx: &mut Context<Self>,
13472 ) {
13473 let buffer = self.buffer.read(cx).snapshot(cx);
13474 let selection = self.selections.newest::<usize>(cx);
13475
13476 let mut active_group_id = None;
13477 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13478 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13479 active_group_id = Some(active_group.group_id);
13480 }
13481 }
13482
13483 fn filtered(
13484 snapshot: EditorSnapshot,
13485 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13486 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13487 diagnostics
13488 .filter(|entry| entry.range.start != entry.range.end)
13489 .filter(|entry| !entry.diagnostic.is_unnecessary)
13490 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13491 }
13492
13493 let snapshot = self.snapshot(window, cx);
13494 let before = filtered(
13495 snapshot.clone(),
13496 buffer
13497 .diagnostics_in_range(0..selection.start)
13498 .filter(|entry| entry.range.start <= selection.start),
13499 );
13500 let after = filtered(
13501 snapshot,
13502 buffer
13503 .diagnostics_in_range(selection.start..buffer.len())
13504 .filter(|entry| entry.range.start >= selection.start),
13505 );
13506
13507 let mut found: Option<DiagnosticEntry<usize>> = None;
13508 if direction == Direction::Prev {
13509 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13510 {
13511 for diagnostic in prev_diagnostics.into_iter().rev() {
13512 if diagnostic.range.start != selection.start
13513 || active_group_id
13514 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13515 {
13516 found = Some(diagnostic);
13517 break 'outer;
13518 }
13519 }
13520 }
13521 } else {
13522 for diagnostic in after.chain(before) {
13523 if diagnostic.range.start != selection.start
13524 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13525 {
13526 found = Some(diagnostic);
13527 break;
13528 }
13529 }
13530 }
13531 let Some(next_diagnostic) = found else {
13532 return;
13533 };
13534
13535 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13536 return;
13537 };
13538 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13539 s.select_ranges(vec![
13540 next_diagnostic.range.start..next_diagnostic.range.start,
13541 ])
13542 });
13543 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13544 self.refresh_inline_completion(false, true, window, cx);
13545 }
13546
13547 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13548 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13549 let snapshot = self.snapshot(window, cx);
13550 let selection = self.selections.newest::<Point>(cx);
13551 self.go_to_hunk_before_or_after_position(
13552 &snapshot,
13553 selection.head(),
13554 Direction::Next,
13555 window,
13556 cx,
13557 );
13558 }
13559
13560 pub fn go_to_hunk_before_or_after_position(
13561 &mut self,
13562 snapshot: &EditorSnapshot,
13563 position: Point,
13564 direction: Direction,
13565 window: &mut Window,
13566 cx: &mut Context<Editor>,
13567 ) {
13568 let row = if direction == Direction::Next {
13569 self.hunk_after_position(snapshot, position)
13570 .map(|hunk| hunk.row_range.start)
13571 } else {
13572 self.hunk_before_position(snapshot, position)
13573 };
13574
13575 if let Some(row) = row {
13576 let destination = Point::new(row.0, 0);
13577 let autoscroll = Autoscroll::center();
13578
13579 self.unfold_ranges(&[destination..destination], false, false, cx);
13580 self.change_selections(Some(autoscroll), window, cx, |s| {
13581 s.select_ranges([destination..destination]);
13582 });
13583 }
13584 }
13585
13586 fn hunk_after_position(
13587 &mut self,
13588 snapshot: &EditorSnapshot,
13589 position: Point,
13590 ) -> Option<MultiBufferDiffHunk> {
13591 snapshot
13592 .buffer_snapshot
13593 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13594 .find(|hunk| hunk.row_range.start.0 > position.row)
13595 .or_else(|| {
13596 snapshot
13597 .buffer_snapshot
13598 .diff_hunks_in_range(Point::zero()..position)
13599 .find(|hunk| hunk.row_range.end.0 < position.row)
13600 })
13601 }
13602
13603 fn go_to_prev_hunk(
13604 &mut self,
13605 _: &GoToPreviousHunk,
13606 window: &mut Window,
13607 cx: &mut Context<Self>,
13608 ) {
13609 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13610 let snapshot = self.snapshot(window, cx);
13611 let selection = self.selections.newest::<Point>(cx);
13612 self.go_to_hunk_before_or_after_position(
13613 &snapshot,
13614 selection.head(),
13615 Direction::Prev,
13616 window,
13617 cx,
13618 );
13619 }
13620
13621 fn hunk_before_position(
13622 &mut self,
13623 snapshot: &EditorSnapshot,
13624 position: Point,
13625 ) -> Option<MultiBufferRow> {
13626 snapshot
13627 .buffer_snapshot
13628 .diff_hunk_before(position)
13629 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13630 }
13631
13632 fn go_to_next_change(
13633 &mut self,
13634 _: &GoToNextChange,
13635 window: &mut Window,
13636 cx: &mut Context<Self>,
13637 ) {
13638 if let Some(selections) = self
13639 .change_list
13640 .next_change(1, Direction::Next)
13641 .map(|s| s.to_vec())
13642 {
13643 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13644 let map = s.display_map();
13645 s.select_display_ranges(selections.iter().map(|a| {
13646 let point = a.to_display_point(&map);
13647 point..point
13648 }))
13649 })
13650 }
13651 }
13652
13653 fn go_to_previous_change(
13654 &mut self,
13655 _: &GoToPreviousChange,
13656 window: &mut Window,
13657 cx: &mut Context<Self>,
13658 ) {
13659 if let Some(selections) = self
13660 .change_list
13661 .next_change(1, Direction::Prev)
13662 .map(|s| s.to_vec())
13663 {
13664 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13665 let map = s.display_map();
13666 s.select_display_ranges(selections.iter().map(|a| {
13667 let point = a.to_display_point(&map);
13668 point..point
13669 }))
13670 })
13671 }
13672 }
13673
13674 fn go_to_line<T: 'static>(
13675 &mut self,
13676 position: Anchor,
13677 highlight_color: Option<Hsla>,
13678 window: &mut Window,
13679 cx: &mut Context<Self>,
13680 ) {
13681 let snapshot = self.snapshot(window, cx).display_snapshot;
13682 let position = position.to_point(&snapshot.buffer_snapshot);
13683 let start = snapshot
13684 .buffer_snapshot
13685 .clip_point(Point::new(position.row, 0), Bias::Left);
13686 let end = start + Point::new(1, 0);
13687 let start = snapshot.buffer_snapshot.anchor_before(start);
13688 let end = snapshot.buffer_snapshot.anchor_before(end);
13689
13690 self.highlight_rows::<T>(
13691 start..end,
13692 highlight_color
13693 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13694 Default::default(),
13695 cx,
13696 );
13697 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13698 }
13699
13700 pub fn go_to_definition(
13701 &mut self,
13702 _: &GoToDefinition,
13703 window: &mut Window,
13704 cx: &mut Context<Self>,
13705 ) -> Task<Result<Navigated>> {
13706 let definition =
13707 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13708 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13709 cx.spawn_in(window, async move |editor, cx| {
13710 if definition.await? == Navigated::Yes {
13711 return Ok(Navigated::Yes);
13712 }
13713 match fallback_strategy {
13714 GoToDefinitionFallback::None => Ok(Navigated::No),
13715 GoToDefinitionFallback::FindAllReferences => {
13716 match editor.update_in(cx, |editor, window, cx| {
13717 editor.find_all_references(&FindAllReferences, window, cx)
13718 })? {
13719 Some(references) => references.await,
13720 None => Ok(Navigated::No),
13721 }
13722 }
13723 }
13724 })
13725 }
13726
13727 pub fn go_to_declaration(
13728 &mut self,
13729 _: &GoToDeclaration,
13730 window: &mut Window,
13731 cx: &mut Context<Self>,
13732 ) -> Task<Result<Navigated>> {
13733 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13734 }
13735
13736 pub fn go_to_declaration_split(
13737 &mut self,
13738 _: &GoToDeclaration,
13739 window: &mut Window,
13740 cx: &mut Context<Self>,
13741 ) -> Task<Result<Navigated>> {
13742 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13743 }
13744
13745 pub fn go_to_implementation(
13746 &mut self,
13747 _: &GoToImplementation,
13748 window: &mut Window,
13749 cx: &mut Context<Self>,
13750 ) -> Task<Result<Navigated>> {
13751 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13752 }
13753
13754 pub fn go_to_implementation_split(
13755 &mut self,
13756 _: &GoToImplementationSplit,
13757 window: &mut Window,
13758 cx: &mut Context<Self>,
13759 ) -> Task<Result<Navigated>> {
13760 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13761 }
13762
13763 pub fn go_to_type_definition(
13764 &mut self,
13765 _: &GoToTypeDefinition,
13766 window: &mut Window,
13767 cx: &mut Context<Self>,
13768 ) -> Task<Result<Navigated>> {
13769 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13770 }
13771
13772 pub fn go_to_definition_split(
13773 &mut self,
13774 _: &GoToDefinitionSplit,
13775 window: &mut Window,
13776 cx: &mut Context<Self>,
13777 ) -> Task<Result<Navigated>> {
13778 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13779 }
13780
13781 pub fn go_to_type_definition_split(
13782 &mut self,
13783 _: &GoToTypeDefinitionSplit,
13784 window: &mut Window,
13785 cx: &mut Context<Self>,
13786 ) -> Task<Result<Navigated>> {
13787 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13788 }
13789
13790 fn go_to_definition_of_kind(
13791 &mut self,
13792 kind: GotoDefinitionKind,
13793 split: bool,
13794 window: &mut Window,
13795 cx: &mut Context<Self>,
13796 ) -> Task<Result<Navigated>> {
13797 let Some(provider) = self.semantics_provider.clone() else {
13798 return Task::ready(Ok(Navigated::No));
13799 };
13800 let head = self.selections.newest::<usize>(cx).head();
13801 let buffer = self.buffer.read(cx);
13802 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13803 text_anchor
13804 } else {
13805 return Task::ready(Ok(Navigated::No));
13806 };
13807
13808 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13809 return Task::ready(Ok(Navigated::No));
13810 };
13811
13812 cx.spawn_in(window, async move |editor, cx| {
13813 let definitions = definitions.await?;
13814 let navigated = editor
13815 .update_in(cx, |editor, window, cx| {
13816 editor.navigate_to_hover_links(
13817 Some(kind),
13818 definitions
13819 .into_iter()
13820 .filter(|location| {
13821 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13822 })
13823 .map(HoverLink::Text)
13824 .collect::<Vec<_>>(),
13825 split,
13826 window,
13827 cx,
13828 )
13829 })?
13830 .await?;
13831 anyhow::Ok(navigated)
13832 })
13833 }
13834
13835 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13836 let selection = self.selections.newest_anchor();
13837 let head = selection.head();
13838 let tail = selection.tail();
13839
13840 let Some((buffer, start_position)) =
13841 self.buffer.read(cx).text_anchor_for_position(head, cx)
13842 else {
13843 return;
13844 };
13845
13846 let end_position = if head != tail {
13847 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13848 return;
13849 };
13850 Some(pos)
13851 } else {
13852 None
13853 };
13854
13855 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13856 let url = if let Some(end_pos) = end_position {
13857 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13858 } else {
13859 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13860 };
13861
13862 if let Some(url) = url {
13863 editor.update(cx, |_, cx| {
13864 cx.open_url(&url);
13865 })
13866 } else {
13867 Ok(())
13868 }
13869 });
13870
13871 url_finder.detach();
13872 }
13873
13874 pub fn open_selected_filename(
13875 &mut self,
13876 _: &OpenSelectedFilename,
13877 window: &mut Window,
13878 cx: &mut Context<Self>,
13879 ) {
13880 let Some(workspace) = self.workspace() else {
13881 return;
13882 };
13883
13884 let position = self.selections.newest_anchor().head();
13885
13886 let Some((buffer, buffer_position)) =
13887 self.buffer.read(cx).text_anchor_for_position(position, cx)
13888 else {
13889 return;
13890 };
13891
13892 let project = self.project.clone();
13893
13894 cx.spawn_in(window, async move |_, cx| {
13895 let result = find_file(&buffer, project, buffer_position, cx).await;
13896
13897 if let Some((_, path)) = result {
13898 workspace
13899 .update_in(cx, |workspace, window, cx| {
13900 workspace.open_resolved_path(path, window, cx)
13901 })?
13902 .await?;
13903 }
13904 anyhow::Ok(())
13905 })
13906 .detach();
13907 }
13908
13909 pub(crate) fn navigate_to_hover_links(
13910 &mut self,
13911 kind: Option<GotoDefinitionKind>,
13912 mut definitions: Vec<HoverLink>,
13913 split: bool,
13914 window: &mut Window,
13915 cx: &mut Context<Editor>,
13916 ) -> Task<Result<Navigated>> {
13917 // If there is one definition, just open it directly
13918 if definitions.len() == 1 {
13919 let definition = definitions.pop().unwrap();
13920
13921 enum TargetTaskResult {
13922 Location(Option<Location>),
13923 AlreadyNavigated,
13924 }
13925
13926 let target_task = match definition {
13927 HoverLink::Text(link) => {
13928 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13929 }
13930 HoverLink::InlayHint(lsp_location, server_id) => {
13931 let computation =
13932 self.compute_target_location(lsp_location, server_id, window, cx);
13933 cx.background_spawn(async move {
13934 let location = computation.await?;
13935 Ok(TargetTaskResult::Location(location))
13936 })
13937 }
13938 HoverLink::Url(url) => {
13939 cx.open_url(&url);
13940 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13941 }
13942 HoverLink::File(path) => {
13943 if let Some(workspace) = self.workspace() {
13944 cx.spawn_in(window, async move |_, cx| {
13945 workspace
13946 .update_in(cx, |workspace, window, cx| {
13947 workspace.open_resolved_path(path, window, cx)
13948 })?
13949 .await
13950 .map(|_| TargetTaskResult::AlreadyNavigated)
13951 })
13952 } else {
13953 Task::ready(Ok(TargetTaskResult::Location(None)))
13954 }
13955 }
13956 };
13957 cx.spawn_in(window, async move |editor, cx| {
13958 let target = match target_task.await.context("target resolution task")? {
13959 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13960 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13961 TargetTaskResult::Location(Some(target)) => target,
13962 };
13963
13964 editor.update_in(cx, |editor, window, cx| {
13965 let Some(workspace) = editor.workspace() else {
13966 return Navigated::No;
13967 };
13968 let pane = workspace.read(cx).active_pane().clone();
13969
13970 let range = target.range.to_point(target.buffer.read(cx));
13971 let range = editor.range_for_match(&range);
13972 let range = collapse_multiline_range(range);
13973
13974 if !split
13975 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13976 {
13977 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13978 } else {
13979 window.defer(cx, move |window, cx| {
13980 let target_editor: Entity<Self> =
13981 workspace.update(cx, |workspace, cx| {
13982 let pane = if split {
13983 workspace.adjacent_pane(window, cx)
13984 } else {
13985 workspace.active_pane().clone()
13986 };
13987
13988 workspace.open_project_item(
13989 pane,
13990 target.buffer.clone(),
13991 true,
13992 true,
13993 window,
13994 cx,
13995 )
13996 });
13997 target_editor.update(cx, |target_editor, cx| {
13998 // When selecting a definition in a different buffer, disable the nav history
13999 // to avoid creating a history entry at the previous cursor location.
14000 pane.update(cx, |pane, _| pane.disable_history());
14001 target_editor.go_to_singleton_buffer_range(range, window, cx);
14002 pane.update(cx, |pane, _| pane.enable_history());
14003 });
14004 });
14005 }
14006 Navigated::Yes
14007 })
14008 })
14009 } else if !definitions.is_empty() {
14010 cx.spawn_in(window, async move |editor, cx| {
14011 let (title, location_tasks, workspace) = editor
14012 .update_in(cx, |editor, window, cx| {
14013 let tab_kind = match kind {
14014 Some(GotoDefinitionKind::Implementation) => "Implementations",
14015 _ => "Definitions",
14016 };
14017 let title = definitions
14018 .iter()
14019 .find_map(|definition| match definition {
14020 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14021 let buffer = origin.buffer.read(cx);
14022 format!(
14023 "{} for {}",
14024 tab_kind,
14025 buffer
14026 .text_for_range(origin.range.clone())
14027 .collect::<String>()
14028 )
14029 }),
14030 HoverLink::InlayHint(_, _) => None,
14031 HoverLink::Url(_) => None,
14032 HoverLink::File(_) => None,
14033 })
14034 .unwrap_or(tab_kind.to_string());
14035 let location_tasks = definitions
14036 .into_iter()
14037 .map(|definition| match definition {
14038 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14039 HoverLink::InlayHint(lsp_location, server_id) => editor
14040 .compute_target_location(lsp_location, server_id, window, cx),
14041 HoverLink::Url(_) => Task::ready(Ok(None)),
14042 HoverLink::File(_) => Task::ready(Ok(None)),
14043 })
14044 .collect::<Vec<_>>();
14045 (title, location_tasks, editor.workspace().clone())
14046 })
14047 .context("location tasks preparation")?;
14048
14049 let locations = future::join_all(location_tasks)
14050 .await
14051 .into_iter()
14052 .filter_map(|location| location.transpose())
14053 .collect::<Result<_>>()
14054 .context("location tasks")?;
14055
14056 let Some(workspace) = workspace else {
14057 return Ok(Navigated::No);
14058 };
14059 let opened = workspace
14060 .update_in(cx, |workspace, window, cx| {
14061 Self::open_locations_in_multibuffer(
14062 workspace,
14063 locations,
14064 title,
14065 split,
14066 MultibufferSelectionMode::First,
14067 window,
14068 cx,
14069 )
14070 })
14071 .ok();
14072
14073 anyhow::Ok(Navigated::from_bool(opened.is_some()))
14074 })
14075 } else {
14076 Task::ready(Ok(Navigated::No))
14077 }
14078 }
14079
14080 fn compute_target_location(
14081 &self,
14082 lsp_location: lsp::Location,
14083 server_id: LanguageServerId,
14084 window: &mut Window,
14085 cx: &mut Context<Self>,
14086 ) -> Task<anyhow::Result<Option<Location>>> {
14087 let Some(project) = self.project.clone() else {
14088 return Task::ready(Ok(None));
14089 };
14090
14091 cx.spawn_in(window, async move |editor, cx| {
14092 let location_task = editor.update(cx, |_, cx| {
14093 project.update(cx, |project, cx| {
14094 let language_server_name = project
14095 .language_server_statuses(cx)
14096 .find(|(id, _)| server_id == *id)
14097 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14098 language_server_name.map(|language_server_name| {
14099 project.open_local_buffer_via_lsp(
14100 lsp_location.uri.clone(),
14101 server_id,
14102 language_server_name,
14103 cx,
14104 )
14105 })
14106 })
14107 })?;
14108 let location = match location_task {
14109 Some(task) => Some({
14110 let target_buffer_handle = task.await.context("open local buffer")?;
14111 let range = target_buffer_handle.update(cx, |target_buffer, _| {
14112 let target_start = target_buffer
14113 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14114 let target_end = target_buffer
14115 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14116 target_buffer.anchor_after(target_start)
14117 ..target_buffer.anchor_before(target_end)
14118 })?;
14119 Location {
14120 buffer: target_buffer_handle,
14121 range,
14122 }
14123 }),
14124 None => None,
14125 };
14126 Ok(location)
14127 })
14128 }
14129
14130 pub fn find_all_references(
14131 &mut self,
14132 _: &FindAllReferences,
14133 window: &mut Window,
14134 cx: &mut Context<Self>,
14135 ) -> Option<Task<Result<Navigated>>> {
14136 let selection = self.selections.newest::<usize>(cx);
14137 let multi_buffer = self.buffer.read(cx);
14138 let head = selection.head();
14139
14140 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14141 let head_anchor = multi_buffer_snapshot.anchor_at(
14142 head,
14143 if head < selection.tail() {
14144 Bias::Right
14145 } else {
14146 Bias::Left
14147 },
14148 );
14149
14150 match self
14151 .find_all_references_task_sources
14152 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14153 {
14154 Ok(_) => {
14155 log::info!(
14156 "Ignoring repeated FindAllReferences invocation with the position of already running task"
14157 );
14158 return None;
14159 }
14160 Err(i) => {
14161 self.find_all_references_task_sources.insert(i, head_anchor);
14162 }
14163 }
14164
14165 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14166 let workspace = self.workspace()?;
14167 let project = workspace.read(cx).project().clone();
14168 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14169 Some(cx.spawn_in(window, async move |editor, cx| {
14170 let _cleanup = cx.on_drop(&editor, move |editor, _| {
14171 if let Ok(i) = editor
14172 .find_all_references_task_sources
14173 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14174 {
14175 editor.find_all_references_task_sources.remove(i);
14176 }
14177 });
14178
14179 let locations = references.await?;
14180 if locations.is_empty() {
14181 return anyhow::Ok(Navigated::No);
14182 }
14183
14184 workspace.update_in(cx, |workspace, window, cx| {
14185 let title = locations
14186 .first()
14187 .as_ref()
14188 .map(|location| {
14189 let buffer = location.buffer.read(cx);
14190 format!(
14191 "References to `{}`",
14192 buffer
14193 .text_for_range(location.range.clone())
14194 .collect::<String>()
14195 )
14196 })
14197 .unwrap();
14198 Self::open_locations_in_multibuffer(
14199 workspace,
14200 locations,
14201 title,
14202 false,
14203 MultibufferSelectionMode::First,
14204 window,
14205 cx,
14206 );
14207 Navigated::Yes
14208 })
14209 }))
14210 }
14211
14212 /// Opens a multibuffer with the given project locations in it
14213 pub fn open_locations_in_multibuffer(
14214 workspace: &mut Workspace,
14215 mut locations: Vec<Location>,
14216 title: String,
14217 split: bool,
14218 multibuffer_selection_mode: MultibufferSelectionMode,
14219 window: &mut Window,
14220 cx: &mut Context<Workspace>,
14221 ) {
14222 // If there are multiple definitions, open them in a multibuffer
14223 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14224 let mut locations = locations.into_iter().peekable();
14225 let mut ranges: Vec<Range<Anchor>> = Vec::new();
14226 let capability = workspace.project().read(cx).capability();
14227
14228 let excerpt_buffer = cx.new(|cx| {
14229 let mut multibuffer = MultiBuffer::new(capability);
14230 while let Some(location) = locations.next() {
14231 let buffer = location.buffer.read(cx);
14232 let mut ranges_for_buffer = Vec::new();
14233 let range = location.range.to_point(buffer);
14234 ranges_for_buffer.push(range.clone());
14235
14236 while let Some(next_location) = locations.peek() {
14237 if next_location.buffer == location.buffer {
14238 ranges_for_buffer.push(next_location.range.to_point(buffer));
14239 locations.next();
14240 } else {
14241 break;
14242 }
14243 }
14244
14245 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14246 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14247 PathKey::for_buffer(&location.buffer, cx),
14248 location.buffer.clone(),
14249 ranges_for_buffer,
14250 DEFAULT_MULTIBUFFER_CONTEXT,
14251 cx,
14252 );
14253 ranges.extend(new_ranges)
14254 }
14255
14256 multibuffer.with_title(title)
14257 });
14258
14259 let editor = cx.new(|cx| {
14260 Editor::for_multibuffer(
14261 excerpt_buffer,
14262 Some(workspace.project().clone()),
14263 window,
14264 cx,
14265 )
14266 });
14267 editor.update(cx, |editor, cx| {
14268 match multibuffer_selection_mode {
14269 MultibufferSelectionMode::First => {
14270 if let Some(first_range) = ranges.first() {
14271 editor.change_selections(None, window, cx, |selections| {
14272 selections.clear_disjoint();
14273 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14274 });
14275 }
14276 editor.highlight_background::<Self>(
14277 &ranges,
14278 |theme| theme.editor_highlighted_line_background,
14279 cx,
14280 );
14281 }
14282 MultibufferSelectionMode::All => {
14283 editor.change_selections(None, window, cx, |selections| {
14284 selections.clear_disjoint();
14285 selections.select_anchor_ranges(ranges);
14286 });
14287 }
14288 }
14289 editor.register_buffers_with_language_servers(cx);
14290 });
14291
14292 let item = Box::new(editor);
14293 let item_id = item.item_id();
14294
14295 if split {
14296 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14297 } else {
14298 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14299 let (preview_item_id, preview_item_idx) =
14300 workspace.active_pane().update(cx, |pane, _| {
14301 (pane.preview_item_id(), pane.preview_item_idx())
14302 });
14303
14304 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14305
14306 if let Some(preview_item_id) = preview_item_id {
14307 workspace.active_pane().update(cx, |pane, cx| {
14308 pane.remove_item(preview_item_id, false, false, window, cx);
14309 });
14310 }
14311 } else {
14312 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14313 }
14314 }
14315 workspace.active_pane().update(cx, |pane, cx| {
14316 pane.set_preview_item_id(Some(item_id), cx);
14317 });
14318 }
14319
14320 pub fn rename(
14321 &mut self,
14322 _: &Rename,
14323 window: &mut Window,
14324 cx: &mut Context<Self>,
14325 ) -> Option<Task<Result<()>>> {
14326 use language::ToOffset as _;
14327
14328 let provider = self.semantics_provider.clone()?;
14329 let selection = self.selections.newest_anchor().clone();
14330 let (cursor_buffer, cursor_buffer_position) = self
14331 .buffer
14332 .read(cx)
14333 .text_anchor_for_position(selection.head(), cx)?;
14334 let (tail_buffer, cursor_buffer_position_end) = self
14335 .buffer
14336 .read(cx)
14337 .text_anchor_for_position(selection.tail(), cx)?;
14338 if tail_buffer != cursor_buffer {
14339 return None;
14340 }
14341
14342 let snapshot = cursor_buffer.read(cx).snapshot();
14343 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14344 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14345 let prepare_rename = provider
14346 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14347 .unwrap_or_else(|| Task::ready(Ok(None)));
14348 drop(snapshot);
14349
14350 Some(cx.spawn_in(window, async move |this, cx| {
14351 let rename_range = if let Some(range) = prepare_rename.await? {
14352 Some(range)
14353 } else {
14354 this.update(cx, |this, cx| {
14355 let buffer = this.buffer.read(cx).snapshot(cx);
14356 let mut buffer_highlights = this
14357 .document_highlights_for_position(selection.head(), &buffer)
14358 .filter(|highlight| {
14359 highlight.start.excerpt_id == selection.head().excerpt_id
14360 && highlight.end.excerpt_id == selection.head().excerpt_id
14361 });
14362 buffer_highlights
14363 .next()
14364 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14365 })?
14366 };
14367 if let Some(rename_range) = rename_range {
14368 this.update_in(cx, |this, window, cx| {
14369 let snapshot = cursor_buffer.read(cx).snapshot();
14370 let rename_buffer_range = rename_range.to_offset(&snapshot);
14371 let cursor_offset_in_rename_range =
14372 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14373 let cursor_offset_in_rename_range_end =
14374 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14375
14376 this.take_rename(false, window, cx);
14377 let buffer = this.buffer.read(cx).read(cx);
14378 let cursor_offset = selection.head().to_offset(&buffer);
14379 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14380 let rename_end = rename_start + rename_buffer_range.len();
14381 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14382 let mut old_highlight_id = None;
14383 let old_name: Arc<str> = buffer
14384 .chunks(rename_start..rename_end, true)
14385 .map(|chunk| {
14386 if old_highlight_id.is_none() {
14387 old_highlight_id = chunk.syntax_highlight_id;
14388 }
14389 chunk.text
14390 })
14391 .collect::<String>()
14392 .into();
14393
14394 drop(buffer);
14395
14396 // Position the selection in the rename editor so that it matches the current selection.
14397 this.show_local_selections = false;
14398 let rename_editor = cx.new(|cx| {
14399 let mut editor = Editor::single_line(window, cx);
14400 editor.buffer.update(cx, |buffer, cx| {
14401 buffer.edit([(0..0, old_name.clone())], None, cx)
14402 });
14403 let rename_selection_range = match cursor_offset_in_rename_range
14404 .cmp(&cursor_offset_in_rename_range_end)
14405 {
14406 Ordering::Equal => {
14407 editor.select_all(&SelectAll, window, cx);
14408 return editor;
14409 }
14410 Ordering::Less => {
14411 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14412 }
14413 Ordering::Greater => {
14414 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14415 }
14416 };
14417 if rename_selection_range.end > old_name.len() {
14418 editor.select_all(&SelectAll, window, cx);
14419 } else {
14420 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14421 s.select_ranges([rename_selection_range]);
14422 });
14423 }
14424 editor
14425 });
14426 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14427 if e == &EditorEvent::Focused {
14428 cx.emit(EditorEvent::FocusedIn)
14429 }
14430 })
14431 .detach();
14432
14433 let write_highlights =
14434 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14435 let read_highlights =
14436 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14437 let ranges = write_highlights
14438 .iter()
14439 .flat_map(|(_, ranges)| ranges.iter())
14440 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14441 .cloned()
14442 .collect();
14443
14444 this.highlight_text::<Rename>(
14445 ranges,
14446 HighlightStyle {
14447 fade_out: Some(0.6),
14448 ..Default::default()
14449 },
14450 cx,
14451 );
14452 let rename_focus_handle = rename_editor.focus_handle(cx);
14453 window.focus(&rename_focus_handle);
14454 let block_id = this.insert_blocks(
14455 [BlockProperties {
14456 style: BlockStyle::Flex,
14457 placement: BlockPlacement::Below(range.start),
14458 height: Some(1),
14459 render: Arc::new({
14460 let rename_editor = rename_editor.clone();
14461 move |cx: &mut BlockContext| {
14462 let mut text_style = cx.editor_style.text.clone();
14463 if let Some(highlight_style) = old_highlight_id
14464 .and_then(|h| h.style(&cx.editor_style.syntax))
14465 {
14466 text_style = text_style.highlight(highlight_style);
14467 }
14468 div()
14469 .block_mouse_down()
14470 .pl(cx.anchor_x)
14471 .child(EditorElement::new(
14472 &rename_editor,
14473 EditorStyle {
14474 background: cx.theme().system().transparent,
14475 local_player: cx.editor_style.local_player,
14476 text: text_style,
14477 scrollbar_width: cx.editor_style.scrollbar_width,
14478 syntax: cx.editor_style.syntax.clone(),
14479 status: cx.editor_style.status.clone(),
14480 inlay_hints_style: HighlightStyle {
14481 font_weight: Some(FontWeight::BOLD),
14482 ..make_inlay_hints_style(cx.app)
14483 },
14484 inline_completion_styles: make_suggestion_styles(
14485 cx.app,
14486 ),
14487 ..EditorStyle::default()
14488 },
14489 ))
14490 .into_any_element()
14491 }
14492 }),
14493 priority: 0,
14494 }],
14495 Some(Autoscroll::fit()),
14496 cx,
14497 )[0];
14498 this.pending_rename = Some(RenameState {
14499 range,
14500 old_name,
14501 editor: rename_editor,
14502 block_id,
14503 });
14504 })?;
14505 }
14506
14507 Ok(())
14508 }))
14509 }
14510
14511 pub fn confirm_rename(
14512 &mut self,
14513 _: &ConfirmRename,
14514 window: &mut Window,
14515 cx: &mut Context<Self>,
14516 ) -> Option<Task<Result<()>>> {
14517 let rename = self.take_rename(false, window, cx)?;
14518 let workspace = self.workspace()?.downgrade();
14519 let (buffer, start) = self
14520 .buffer
14521 .read(cx)
14522 .text_anchor_for_position(rename.range.start, cx)?;
14523 let (end_buffer, _) = self
14524 .buffer
14525 .read(cx)
14526 .text_anchor_for_position(rename.range.end, cx)?;
14527 if buffer != end_buffer {
14528 return None;
14529 }
14530
14531 let old_name = rename.old_name;
14532 let new_name = rename.editor.read(cx).text(cx);
14533
14534 let rename = self.semantics_provider.as_ref()?.perform_rename(
14535 &buffer,
14536 start,
14537 new_name.clone(),
14538 cx,
14539 )?;
14540
14541 Some(cx.spawn_in(window, async move |editor, cx| {
14542 let project_transaction = rename.await?;
14543 Self::open_project_transaction(
14544 &editor,
14545 workspace,
14546 project_transaction,
14547 format!("Rename: {} → {}", old_name, new_name),
14548 cx,
14549 )
14550 .await?;
14551
14552 editor.update(cx, |editor, cx| {
14553 editor.refresh_document_highlights(cx);
14554 })?;
14555 Ok(())
14556 }))
14557 }
14558
14559 fn take_rename(
14560 &mut self,
14561 moving_cursor: bool,
14562 window: &mut Window,
14563 cx: &mut Context<Self>,
14564 ) -> Option<RenameState> {
14565 let rename = self.pending_rename.take()?;
14566 if rename.editor.focus_handle(cx).is_focused(window) {
14567 window.focus(&self.focus_handle);
14568 }
14569
14570 self.remove_blocks(
14571 [rename.block_id].into_iter().collect(),
14572 Some(Autoscroll::fit()),
14573 cx,
14574 );
14575 self.clear_highlights::<Rename>(cx);
14576 self.show_local_selections = true;
14577
14578 if moving_cursor {
14579 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14580 editor.selections.newest::<usize>(cx).head()
14581 });
14582
14583 // Update the selection to match the position of the selection inside
14584 // the rename editor.
14585 let snapshot = self.buffer.read(cx).read(cx);
14586 let rename_range = rename.range.to_offset(&snapshot);
14587 let cursor_in_editor = snapshot
14588 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14589 .min(rename_range.end);
14590 drop(snapshot);
14591
14592 self.change_selections(None, window, cx, |s| {
14593 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14594 });
14595 } else {
14596 self.refresh_document_highlights(cx);
14597 }
14598
14599 Some(rename)
14600 }
14601
14602 pub fn pending_rename(&self) -> Option<&RenameState> {
14603 self.pending_rename.as_ref()
14604 }
14605
14606 fn format(
14607 &mut self,
14608 _: &Format,
14609 window: &mut Window,
14610 cx: &mut Context<Self>,
14611 ) -> Option<Task<Result<()>>> {
14612 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14613
14614 let project = match &self.project {
14615 Some(project) => project.clone(),
14616 None => return None,
14617 };
14618
14619 Some(self.perform_format(
14620 project,
14621 FormatTrigger::Manual,
14622 FormatTarget::Buffers,
14623 window,
14624 cx,
14625 ))
14626 }
14627
14628 fn format_selections(
14629 &mut self,
14630 _: &FormatSelections,
14631 window: &mut Window,
14632 cx: &mut Context<Self>,
14633 ) -> Option<Task<Result<()>>> {
14634 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14635
14636 let project = match &self.project {
14637 Some(project) => project.clone(),
14638 None => return None,
14639 };
14640
14641 let ranges = self
14642 .selections
14643 .all_adjusted(cx)
14644 .into_iter()
14645 .map(|selection| selection.range())
14646 .collect_vec();
14647
14648 Some(self.perform_format(
14649 project,
14650 FormatTrigger::Manual,
14651 FormatTarget::Ranges(ranges),
14652 window,
14653 cx,
14654 ))
14655 }
14656
14657 fn perform_format(
14658 &mut self,
14659 project: Entity<Project>,
14660 trigger: FormatTrigger,
14661 target: FormatTarget,
14662 window: &mut Window,
14663 cx: &mut Context<Self>,
14664 ) -> Task<Result<()>> {
14665 let buffer = self.buffer.clone();
14666 let (buffers, target) = match target {
14667 FormatTarget::Buffers => {
14668 let mut buffers = buffer.read(cx).all_buffers();
14669 if trigger == FormatTrigger::Save {
14670 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14671 }
14672 (buffers, LspFormatTarget::Buffers)
14673 }
14674 FormatTarget::Ranges(selection_ranges) => {
14675 let multi_buffer = buffer.read(cx);
14676 let snapshot = multi_buffer.read(cx);
14677 let mut buffers = HashSet::default();
14678 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14679 BTreeMap::new();
14680 for selection_range in selection_ranges {
14681 for (buffer, buffer_range, _) in
14682 snapshot.range_to_buffer_ranges(selection_range)
14683 {
14684 let buffer_id = buffer.remote_id();
14685 let start = buffer.anchor_before(buffer_range.start);
14686 let end = buffer.anchor_after(buffer_range.end);
14687 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14688 buffer_id_to_ranges
14689 .entry(buffer_id)
14690 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14691 .or_insert_with(|| vec![start..end]);
14692 }
14693 }
14694 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14695 }
14696 };
14697
14698 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14699 let selections_prev = transaction_id_prev
14700 .and_then(|transaction_id_prev| {
14701 // default to selections as they were after the last edit, if we have them,
14702 // instead of how they are now.
14703 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14704 // will take you back to where you made the last edit, instead of staying where you scrolled
14705 self.selection_history
14706 .transaction(transaction_id_prev)
14707 .map(|t| t.0.clone())
14708 })
14709 .unwrap_or_else(|| {
14710 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14711 self.selections.disjoint_anchors()
14712 });
14713
14714 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14715 let format = project.update(cx, |project, cx| {
14716 project.format(buffers, target, true, trigger, cx)
14717 });
14718
14719 cx.spawn_in(window, async move |editor, cx| {
14720 let transaction = futures::select_biased! {
14721 transaction = format.log_err().fuse() => transaction,
14722 () = timeout => {
14723 log::warn!("timed out waiting for formatting");
14724 None
14725 }
14726 };
14727
14728 buffer
14729 .update(cx, |buffer, cx| {
14730 if let Some(transaction) = transaction {
14731 if !buffer.is_singleton() {
14732 buffer.push_transaction(&transaction.0, cx);
14733 }
14734 }
14735 cx.notify();
14736 })
14737 .ok();
14738
14739 if let Some(transaction_id_now) =
14740 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14741 {
14742 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14743 if has_new_transaction {
14744 _ = editor.update(cx, |editor, _| {
14745 editor
14746 .selection_history
14747 .insert_transaction(transaction_id_now, selections_prev);
14748 });
14749 }
14750 }
14751
14752 Ok(())
14753 })
14754 }
14755
14756 fn organize_imports(
14757 &mut self,
14758 _: &OrganizeImports,
14759 window: &mut Window,
14760 cx: &mut Context<Self>,
14761 ) -> Option<Task<Result<()>>> {
14762 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14763 let project = match &self.project {
14764 Some(project) => project.clone(),
14765 None => return None,
14766 };
14767 Some(self.perform_code_action_kind(
14768 project,
14769 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14770 window,
14771 cx,
14772 ))
14773 }
14774
14775 fn perform_code_action_kind(
14776 &mut self,
14777 project: Entity<Project>,
14778 kind: CodeActionKind,
14779 window: &mut Window,
14780 cx: &mut Context<Self>,
14781 ) -> Task<Result<()>> {
14782 let buffer = self.buffer.clone();
14783 let buffers = buffer.read(cx).all_buffers();
14784 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14785 let apply_action = project.update(cx, |project, cx| {
14786 project.apply_code_action_kind(buffers, kind, true, cx)
14787 });
14788 cx.spawn_in(window, async move |_, cx| {
14789 let transaction = futures::select_biased! {
14790 () = timeout => {
14791 log::warn!("timed out waiting for executing code action");
14792 None
14793 }
14794 transaction = apply_action.log_err().fuse() => transaction,
14795 };
14796 buffer
14797 .update(cx, |buffer, cx| {
14798 // check if we need this
14799 if let Some(transaction) = transaction {
14800 if !buffer.is_singleton() {
14801 buffer.push_transaction(&transaction.0, cx);
14802 }
14803 }
14804 cx.notify();
14805 })
14806 .ok();
14807 Ok(())
14808 })
14809 }
14810
14811 fn restart_language_server(
14812 &mut self,
14813 _: &RestartLanguageServer,
14814 _: &mut Window,
14815 cx: &mut Context<Self>,
14816 ) {
14817 if let Some(project) = self.project.clone() {
14818 self.buffer.update(cx, |multi_buffer, cx| {
14819 project.update(cx, |project, cx| {
14820 project.restart_language_servers_for_buffers(
14821 multi_buffer.all_buffers().into_iter().collect(),
14822 cx,
14823 );
14824 });
14825 })
14826 }
14827 }
14828
14829 fn stop_language_server(
14830 &mut self,
14831 _: &StopLanguageServer,
14832 _: &mut Window,
14833 cx: &mut Context<Self>,
14834 ) {
14835 if let Some(project) = self.project.clone() {
14836 self.buffer.update(cx, |multi_buffer, cx| {
14837 project.update(cx, |project, cx| {
14838 project.stop_language_servers_for_buffers(
14839 multi_buffer.all_buffers().into_iter().collect(),
14840 cx,
14841 );
14842 cx.emit(project::Event::RefreshInlayHints);
14843 });
14844 });
14845 }
14846 }
14847
14848 fn cancel_language_server_work(
14849 workspace: &mut Workspace,
14850 _: &actions::CancelLanguageServerWork,
14851 _: &mut Window,
14852 cx: &mut Context<Workspace>,
14853 ) {
14854 let project = workspace.project();
14855 let buffers = workspace
14856 .active_item(cx)
14857 .and_then(|item| item.act_as::<Editor>(cx))
14858 .map_or(HashSet::default(), |editor| {
14859 editor.read(cx).buffer.read(cx).all_buffers()
14860 });
14861 project.update(cx, |project, cx| {
14862 project.cancel_language_server_work_for_buffers(buffers, cx);
14863 });
14864 }
14865
14866 fn show_character_palette(
14867 &mut self,
14868 _: &ShowCharacterPalette,
14869 window: &mut Window,
14870 _: &mut Context<Self>,
14871 ) {
14872 window.show_character_palette();
14873 }
14874
14875 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14876 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14877 let buffer = self.buffer.read(cx).snapshot(cx);
14878 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14879 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14880 let is_valid = buffer
14881 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14882 .any(|entry| {
14883 entry.diagnostic.is_primary
14884 && !entry.range.is_empty()
14885 && entry.range.start == primary_range_start
14886 && entry.diagnostic.message == active_diagnostics.active_message
14887 });
14888
14889 if !is_valid {
14890 self.dismiss_diagnostics(cx);
14891 }
14892 }
14893 }
14894
14895 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14896 match &self.active_diagnostics {
14897 ActiveDiagnostic::Group(group) => Some(group),
14898 _ => None,
14899 }
14900 }
14901
14902 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14903 self.dismiss_diagnostics(cx);
14904 self.active_diagnostics = ActiveDiagnostic::All;
14905 }
14906
14907 fn activate_diagnostics(
14908 &mut self,
14909 buffer_id: BufferId,
14910 diagnostic: DiagnosticEntry<usize>,
14911 window: &mut Window,
14912 cx: &mut Context<Self>,
14913 ) {
14914 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14915 return;
14916 }
14917 self.dismiss_diagnostics(cx);
14918 let snapshot = self.snapshot(window, cx);
14919 let buffer = self.buffer.read(cx).snapshot(cx);
14920 let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
14921 return;
14922 };
14923
14924 let diagnostic_group = buffer
14925 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14926 .collect::<Vec<_>>();
14927
14928 let blocks =
14929 renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
14930
14931 let blocks = self.display_map.update(cx, |display_map, cx| {
14932 display_map.insert_blocks(blocks, cx).into_iter().collect()
14933 });
14934 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14935 active_range: buffer.anchor_before(diagnostic.range.start)
14936 ..buffer.anchor_after(diagnostic.range.end),
14937 active_message: diagnostic.diagnostic.message.clone(),
14938 group_id: diagnostic.diagnostic.group_id,
14939 blocks,
14940 });
14941 cx.notify();
14942 }
14943
14944 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14945 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14946 return;
14947 };
14948
14949 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14950 if let ActiveDiagnostic::Group(group) = prev {
14951 self.display_map.update(cx, |display_map, cx| {
14952 display_map.remove_blocks(group.blocks, cx);
14953 });
14954 cx.notify();
14955 }
14956 }
14957
14958 /// Disable inline diagnostics rendering for this editor.
14959 pub fn disable_inline_diagnostics(&mut self) {
14960 self.inline_diagnostics_enabled = false;
14961 self.inline_diagnostics_update = Task::ready(());
14962 self.inline_diagnostics.clear();
14963 }
14964
14965 pub fn inline_diagnostics_enabled(&self) -> bool {
14966 self.inline_diagnostics_enabled
14967 }
14968
14969 pub fn show_inline_diagnostics(&self) -> bool {
14970 self.show_inline_diagnostics
14971 }
14972
14973 pub fn toggle_inline_diagnostics(
14974 &mut self,
14975 _: &ToggleInlineDiagnostics,
14976 window: &mut Window,
14977 cx: &mut Context<Editor>,
14978 ) {
14979 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14980 self.refresh_inline_diagnostics(false, window, cx);
14981 }
14982
14983 fn refresh_inline_diagnostics(
14984 &mut self,
14985 debounce: bool,
14986 window: &mut Window,
14987 cx: &mut Context<Self>,
14988 ) {
14989 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14990 self.inline_diagnostics_update = Task::ready(());
14991 self.inline_diagnostics.clear();
14992 return;
14993 }
14994
14995 let debounce_ms = ProjectSettings::get_global(cx)
14996 .diagnostics
14997 .inline
14998 .update_debounce_ms;
14999 let debounce = if debounce && debounce_ms > 0 {
15000 Some(Duration::from_millis(debounce_ms))
15001 } else {
15002 None
15003 };
15004 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15005 let editor = editor.upgrade().unwrap();
15006
15007 if let Some(debounce) = debounce {
15008 cx.background_executor().timer(debounce).await;
15009 }
15010 let Some(snapshot) = editor
15011 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15012 .ok()
15013 else {
15014 return;
15015 };
15016
15017 let new_inline_diagnostics = cx
15018 .background_spawn(async move {
15019 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15020 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15021 let message = diagnostic_entry
15022 .diagnostic
15023 .message
15024 .split_once('\n')
15025 .map(|(line, _)| line)
15026 .map(SharedString::new)
15027 .unwrap_or_else(|| {
15028 SharedString::from(diagnostic_entry.diagnostic.message)
15029 });
15030 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15031 let (Ok(i) | Err(i)) = inline_diagnostics
15032 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15033 inline_diagnostics.insert(
15034 i,
15035 (
15036 start_anchor,
15037 InlineDiagnostic {
15038 message,
15039 group_id: diagnostic_entry.diagnostic.group_id,
15040 start: diagnostic_entry.range.start.to_point(&snapshot),
15041 is_primary: diagnostic_entry.diagnostic.is_primary,
15042 severity: diagnostic_entry.diagnostic.severity,
15043 },
15044 ),
15045 );
15046 }
15047 inline_diagnostics
15048 })
15049 .await;
15050
15051 editor
15052 .update(cx, |editor, cx| {
15053 editor.inline_diagnostics = new_inline_diagnostics;
15054 cx.notify();
15055 })
15056 .ok();
15057 });
15058 }
15059
15060 pub fn set_selections_from_remote(
15061 &mut self,
15062 selections: Vec<Selection<Anchor>>,
15063 pending_selection: Option<Selection<Anchor>>,
15064 window: &mut Window,
15065 cx: &mut Context<Self>,
15066 ) {
15067 let old_cursor_position = self.selections.newest_anchor().head();
15068 self.selections.change_with(cx, |s| {
15069 s.select_anchors(selections);
15070 if let Some(pending_selection) = pending_selection {
15071 s.set_pending(pending_selection, SelectMode::Character);
15072 } else {
15073 s.clear_pending();
15074 }
15075 });
15076 self.selections_did_change(false, &old_cursor_position, true, window, cx);
15077 }
15078
15079 fn push_to_selection_history(&mut self) {
15080 self.selection_history.push(SelectionHistoryEntry {
15081 selections: self.selections.disjoint_anchors(),
15082 select_next_state: self.select_next_state.clone(),
15083 select_prev_state: self.select_prev_state.clone(),
15084 add_selections_state: self.add_selections_state.clone(),
15085 });
15086 }
15087
15088 pub fn transact(
15089 &mut self,
15090 window: &mut Window,
15091 cx: &mut Context<Self>,
15092 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15093 ) -> Option<TransactionId> {
15094 self.start_transaction_at(Instant::now(), window, cx);
15095 update(self, window, cx);
15096 self.end_transaction_at(Instant::now(), cx)
15097 }
15098
15099 pub fn start_transaction_at(
15100 &mut self,
15101 now: Instant,
15102 window: &mut Window,
15103 cx: &mut Context<Self>,
15104 ) {
15105 self.end_selection(window, cx);
15106 if let Some(tx_id) = self
15107 .buffer
15108 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15109 {
15110 self.selection_history
15111 .insert_transaction(tx_id, self.selections.disjoint_anchors());
15112 cx.emit(EditorEvent::TransactionBegun {
15113 transaction_id: tx_id,
15114 })
15115 }
15116 }
15117
15118 pub fn end_transaction_at(
15119 &mut self,
15120 now: Instant,
15121 cx: &mut Context<Self>,
15122 ) -> Option<TransactionId> {
15123 if let Some(transaction_id) = self
15124 .buffer
15125 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15126 {
15127 if let Some((_, end_selections)) =
15128 self.selection_history.transaction_mut(transaction_id)
15129 {
15130 *end_selections = Some(self.selections.disjoint_anchors());
15131 } else {
15132 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15133 }
15134
15135 cx.emit(EditorEvent::Edited { transaction_id });
15136 Some(transaction_id)
15137 } else {
15138 None
15139 }
15140 }
15141
15142 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15143 if self.selection_mark_mode {
15144 self.change_selections(None, window, cx, |s| {
15145 s.move_with(|_, sel| {
15146 sel.collapse_to(sel.head(), SelectionGoal::None);
15147 });
15148 })
15149 }
15150 self.selection_mark_mode = true;
15151 cx.notify();
15152 }
15153
15154 pub fn swap_selection_ends(
15155 &mut self,
15156 _: &actions::SwapSelectionEnds,
15157 window: &mut Window,
15158 cx: &mut Context<Self>,
15159 ) {
15160 self.change_selections(None, window, cx, |s| {
15161 s.move_with(|_, sel| {
15162 if sel.start != sel.end {
15163 sel.reversed = !sel.reversed
15164 }
15165 });
15166 });
15167 self.request_autoscroll(Autoscroll::newest(), cx);
15168 cx.notify();
15169 }
15170
15171 pub fn toggle_fold(
15172 &mut self,
15173 _: &actions::ToggleFold,
15174 window: &mut Window,
15175 cx: &mut Context<Self>,
15176 ) {
15177 if self.is_singleton(cx) {
15178 let selection = self.selections.newest::<Point>(cx);
15179
15180 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15181 let range = if selection.is_empty() {
15182 let point = selection.head().to_display_point(&display_map);
15183 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15184 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15185 .to_point(&display_map);
15186 start..end
15187 } else {
15188 selection.range()
15189 };
15190 if display_map.folds_in_range(range).next().is_some() {
15191 self.unfold_lines(&Default::default(), window, cx)
15192 } else {
15193 self.fold(&Default::default(), window, cx)
15194 }
15195 } else {
15196 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15197 let buffer_ids: HashSet<_> = self
15198 .selections
15199 .disjoint_anchor_ranges()
15200 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15201 .collect();
15202
15203 let should_unfold = buffer_ids
15204 .iter()
15205 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15206
15207 for buffer_id in buffer_ids {
15208 if should_unfold {
15209 self.unfold_buffer(buffer_id, cx);
15210 } else {
15211 self.fold_buffer(buffer_id, cx);
15212 }
15213 }
15214 }
15215 }
15216
15217 pub fn toggle_fold_recursive(
15218 &mut self,
15219 _: &actions::ToggleFoldRecursive,
15220 window: &mut Window,
15221 cx: &mut Context<Self>,
15222 ) {
15223 let selection = self.selections.newest::<Point>(cx);
15224
15225 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15226 let range = if selection.is_empty() {
15227 let point = selection.head().to_display_point(&display_map);
15228 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15229 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15230 .to_point(&display_map);
15231 start..end
15232 } else {
15233 selection.range()
15234 };
15235 if display_map.folds_in_range(range).next().is_some() {
15236 self.unfold_recursive(&Default::default(), window, cx)
15237 } else {
15238 self.fold_recursive(&Default::default(), window, cx)
15239 }
15240 }
15241
15242 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15243 if self.is_singleton(cx) {
15244 let mut to_fold = Vec::new();
15245 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15246 let selections = self.selections.all_adjusted(cx);
15247
15248 for selection in selections {
15249 let range = selection.range().sorted();
15250 let buffer_start_row = range.start.row;
15251
15252 if range.start.row != range.end.row {
15253 let mut found = false;
15254 let mut row = range.start.row;
15255 while row <= range.end.row {
15256 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15257 {
15258 found = true;
15259 row = crease.range().end.row + 1;
15260 to_fold.push(crease);
15261 } else {
15262 row += 1
15263 }
15264 }
15265 if found {
15266 continue;
15267 }
15268 }
15269
15270 for row in (0..=range.start.row).rev() {
15271 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15272 if crease.range().end.row >= buffer_start_row {
15273 to_fold.push(crease);
15274 if row <= range.start.row {
15275 break;
15276 }
15277 }
15278 }
15279 }
15280 }
15281
15282 self.fold_creases(to_fold, true, window, cx);
15283 } else {
15284 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15285 let buffer_ids = self
15286 .selections
15287 .disjoint_anchor_ranges()
15288 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15289 .collect::<HashSet<_>>();
15290 for buffer_id in buffer_ids {
15291 self.fold_buffer(buffer_id, cx);
15292 }
15293 }
15294 }
15295
15296 fn fold_at_level(
15297 &mut self,
15298 fold_at: &FoldAtLevel,
15299 window: &mut Window,
15300 cx: &mut Context<Self>,
15301 ) {
15302 if !self.buffer.read(cx).is_singleton() {
15303 return;
15304 }
15305
15306 let fold_at_level = fold_at.0;
15307 let snapshot = self.buffer.read(cx).snapshot(cx);
15308 let mut to_fold = Vec::new();
15309 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15310
15311 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15312 while start_row < end_row {
15313 match self
15314 .snapshot(window, cx)
15315 .crease_for_buffer_row(MultiBufferRow(start_row))
15316 {
15317 Some(crease) => {
15318 let nested_start_row = crease.range().start.row + 1;
15319 let nested_end_row = crease.range().end.row;
15320
15321 if current_level < fold_at_level {
15322 stack.push((nested_start_row, nested_end_row, current_level + 1));
15323 } else if current_level == fold_at_level {
15324 to_fold.push(crease);
15325 }
15326
15327 start_row = nested_end_row + 1;
15328 }
15329 None => start_row += 1,
15330 }
15331 }
15332 }
15333
15334 self.fold_creases(to_fold, true, window, cx);
15335 }
15336
15337 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15338 if self.buffer.read(cx).is_singleton() {
15339 let mut fold_ranges = Vec::new();
15340 let snapshot = self.buffer.read(cx).snapshot(cx);
15341
15342 for row in 0..snapshot.max_row().0 {
15343 if let Some(foldable_range) = self
15344 .snapshot(window, cx)
15345 .crease_for_buffer_row(MultiBufferRow(row))
15346 {
15347 fold_ranges.push(foldable_range);
15348 }
15349 }
15350
15351 self.fold_creases(fold_ranges, true, window, cx);
15352 } else {
15353 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15354 editor
15355 .update_in(cx, |editor, _, cx| {
15356 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15357 editor.fold_buffer(buffer_id, cx);
15358 }
15359 })
15360 .ok();
15361 });
15362 }
15363 }
15364
15365 pub fn fold_function_bodies(
15366 &mut self,
15367 _: &actions::FoldFunctionBodies,
15368 window: &mut Window,
15369 cx: &mut Context<Self>,
15370 ) {
15371 let snapshot = self.buffer.read(cx).snapshot(cx);
15372
15373 let ranges = snapshot
15374 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15375 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15376 .collect::<Vec<_>>();
15377
15378 let creases = ranges
15379 .into_iter()
15380 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15381 .collect();
15382
15383 self.fold_creases(creases, true, window, cx);
15384 }
15385
15386 pub fn fold_recursive(
15387 &mut self,
15388 _: &actions::FoldRecursive,
15389 window: &mut Window,
15390 cx: &mut Context<Self>,
15391 ) {
15392 let mut to_fold = Vec::new();
15393 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15394 let selections = self.selections.all_adjusted(cx);
15395
15396 for selection in selections {
15397 let range = selection.range().sorted();
15398 let buffer_start_row = range.start.row;
15399
15400 if range.start.row != range.end.row {
15401 let mut found = false;
15402 for row in range.start.row..=range.end.row {
15403 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15404 found = true;
15405 to_fold.push(crease);
15406 }
15407 }
15408 if found {
15409 continue;
15410 }
15411 }
15412
15413 for row in (0..=range.start.row).rev() {
15414 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15415 if crease.range().end.row >= buffer_start_row {
15416 to_fold.push(crease);
15417 } else {
15418 break;
15419 }
15420 }
15421 }
15422 }
15423
15424 self.fold_creases(to_fold, true, window, cx);
15425 }
15426
15427 pub fn fold_at(
15428 &mut self,
15429 buffer_row: MultiBufferRow,
15430 window: &mut Window,
15431 cx: &mut Context<Self>,
15432 ) {
15433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15434
15435 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15436 let autoscroll = self
15437 .selections
15438 .all::<Point>(cx)
15439 .iter()
15440 .any(|selection| crease.range().overlaps(&selection.range()));
15441
15442 self.fold_creases(vec![crease], autoscroll, window, cx);
15443 }
15444 }
15445
15446 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15447 if self.is_singleton(cx) {
15448 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15449 let buffer = &display_map.buffer_snapshot;
15450 let selections = self.selections.all::<Point>(cx);
15451 let ranges = selections
15452 .iter()
15453 .map(|s| {
15454 let range = s.display_range(&display_map).sorted();
15455 let mut start = range.start.to_point(&display_map);
15456 let mut end = range.end.to_point(&display_map);
15457 start.column = 0;
15458 end.column = buffer.line_len(MultiBufferRow(end.row));
15459 start..end
15460 })
15461 .collect::<Vec<_>>();
15462
15463 self.unfold_ranges(&ranges, true, true, cx);
15464 } else {
15465 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15466 let buffer_ids = self
15467 .selections
15468 .disjoint_anchor_ranges()
15469 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15470 .collect::<HashSet<_>>();
15471 for buffer_id in buffer_ids {
15472 self.unfold_buffer(buffer_id, cx);
15473 }
15474 }
15475 }
15476
15477 pub fn unfold_recursive(
15478 &mut self,
15479 _: &UnfoldRecursive,
15480 _window: &mut Window,
15481 cx: &mut Context<Self>,
15482 ) {
15483 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15484 let selections = self.selections.all::<Point>(cx);
15485 let ranges = selections
15486 .iter()
15487 .map(|s| {
15488 let mut range = s.display_range(&display_map).sorted();
15489 *range.start.column_mut() = 0;
15490 *range.end.column_mut() = display_map.line_len(range.end.row());
15491 let start = range.start.to_point(&display_map);
15492 let end = range.end.to_point(&display_map);
15493 start..end
15494 })
15495 .collect::<Vec<_>>();
15496
15497 self.unfold_ranges(&ranges, true, true, cx);
15498 }
15499
15500 pub fn unfold_at(
15501 &mut self,
15502 buffer_row: MultiBufferRow,
15503 _window: &mut Window,
15504 cx: &mut Context<Self>,
15505 ) {
15506 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15507
15508 let intersection_range = Point::new(buffer_row.0, 0)
15509 ..Point::new(
15510 buffer_row.0,
15511 display_map.buffer_snapshot.line_len(buffer_row),
15512 );
15513
15514 let autoscroll = self
15515 .selections
15516 .all::<Point>(cx)
15517 .iter()
15518 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15519
15520 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15521 }
15522
15523 pub fn unfold_all(
15524 &mut self,
15525 _: &actions::UnfoldAll,
15526 _window: &mut Window,
15527 cx: &mut Context<Self>,
15528 ) {
15529 if self.buffer.read(cx).is_singleton() {
15530 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15531 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15532 } else {
15533 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15534 editor
15535 .update(cx, |editor, cx| {
15536 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15537 editor.unfold_buffer(buffer_id, cx);
15538 }
15539 })
15540 .ok();
15541 });
15542 }
15543 }
15544
15545 pub fn fold_selected_ranges(
15546 &mut self,
15547 _: &FoldSelectedRanges,
15548 window: &mut Window,
15549 cx: &mut Context<Self>,
15550 ) {
15551 let selections = self.selections.all_adjusted(cx);
15552 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15553 let ranges = selections
15554 .into_iter()
15555 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15556 .collect::<Vec<_>>();
15557 self.fold_creases(ranges, true, window, cx);
15558 }
15559
15560 pub fn fold_ranges<T: ToOffset + Clone>(
15561 &mut self,
15562 ranges: Vec<Range<T>>,
15563 auto_scroll: bool,
15564 window: &mut Window,
15565 cx: &mut Context<Self>,
15566 ) {
15567 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15568 let ranges = ranges
15569 .into_iter()
15570 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15571 .collect::<Vec<_>>();
15572 self.fold_creases(ranges, auto_scroll, window, cx);
15573 }
15574
15575 pub fn fold_creases<T: ToOffset + Clone>(
15576 &mut self,
15577 creases: Vec<Crease<T>>,
15578 auto_scroll: bool,
15579 _window: &mut Window,
15580 cx: &mut Context<Self>,
15581 ) {
15582 if creases.is_empty() {
15583 return;
15584 }
15585
15586 let mut buffers_affected = HashSet::default();
15587 let multi_buffer = self.buffer().read(cx);
15588 for crease in &creases {
15589 if let Some((_, buffer, _)) =
15590 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15591 {
15592 buffers_affected.insert(buffer.read(cx).remote_id());
15593 };
15594 }
15595
15596 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15597
15598 if auto_scroll {
15599 self.request_autoscroll(Autoscroll::fit(), cx);
15600 }
15601
15602 cx.notify();
15603
15604 self.scrollbar_marker_state.dirty = true;
15605 self.folds_did_change(cx);
15606 }
15607
15608 /// Removes any folds whose ranges intersect any of the given ranges.
15609 pub fn unfold_ranges<T: ToOffset + Clone>(
15610 &mut self,
15611 ranges: &[Range<T>],
15612 inclusive: bool,
15613 auto_scroll: bool,
15614 cx: &mut Context<Self>,
15615 ) {
15616 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15617 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15618 });
15619 self.folds_did_change(cx);
15620 }
15621
15622 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15623 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15624 return;
15625 }
15626 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15627 self.display_map.update(cx, |display_map, cx| {
15628 display_map.fold_buffers([buffer_id], cx)
15629 });
15630 cx.emit(EditorEvent::BufferFoldToggled {
15631 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15632 folded: true,
15633 });
15634 cx.notify();
15635 }
15636
15637 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15638 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15639 return;
15640 }
15641 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15642 self.display_map.update(cx, |display_map, cx| {
15643 display_map.unfold_buffers([buffer_id], cx);
15644 });
15645 cx.emit(EditorEvent::BufferFoldToggled {
15646 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15647 folded: false,
15648 });
15649 cx.notify();
15650 }
15651
15652 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15653 self.display_map.read(cx).is_buffer_folded(buffer)
15654 }
15655
15656 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15657 self.display_map.read(cx).folded_buffers()
15658 }
15659
15660 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15661 self.display_map.update(cx, |display_map, cx| {
15662 display_map.disable_header_for_buffer(buffer_id, cx);
15663 });
15664 cx.notify();
15665 }
15666
15667 /// Removes any folds with the given ranges.
15668 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15669 &mut self,
15670 ranges: &[Range<T>],
15671 type_id: TypeId,
15672 auto_scroll: bool,
15673 cx: &mut Context<Self>,
15674 ) {
15675 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15676 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15677 });
15678 self.folds_did_change(cx);
15679 }
15680
15681 fn remove_folds_with<T: ToOffset + Clone>(
15682 &mut self,
15683 ranges: &[Range<T>],
15684 auto_scroll: bool,
15685 cx: &mut Context<Self>,
15686 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15687 ) {
15688 if ranges.is_empty() {
15689 return;
15690 }
15691
15692 let mut buffers_affected = HashSet::default();
15693 let multi_buffer = self.buffer().read(cx);
15694 for range in ranges {
15695 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15696 buffers_affected.insert(buffer.read(cx).remote_id());
15697 };
15698 }
15699
15700 self.display_map.update(cx, update);
15701
15702 if auto_scroll {
15703 self.request_autoscroll(Autoscroll::fit(), cx);
15704 }
15705
15706 cx.notify();
15707 self.scrollbar_marker_state.dirty = true;
15708 self.active_indent_guides_state.dirty = true;
15709 }
15710
15711 pub fn update_fold_widths(
15712 &mut self,
15713 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15714 cx: &mut Context<Self>,
15715 ) -> bool {
15716 self.display_map
15717 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15718 }
15719
15720 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15721 self.display_map.read(cx).fold_placeholder.clone()
15722 }
15723
15724 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15725 self.buffer.update(cx, |buffer, cx| {
15726 buffer.set_all_diff_hunks_expanded(cx);
15727 });
15728 }
15729
15730 pub fn expand_all_diff_hunks(
15731 &mut self,
15732 _: &ExpandAllDiffHunks,
15733 _window: &mut Window,
15734 cx: &mut Context<Self>,
15735 ) {
15736 self.buffer.update(cx, |buffer, cx| {
15737 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15738 });
15739 }
15740
15741 pub fn toggle_selected_diff_hunks(
15742 &mut self,
15743 _: &ToggleSelectedDiffHunks,
15744 _window: &mut Window,
15745 cx: &mut Context<Self>,
15746 ) {
15747 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15748 self.toggle_diff_hunks_in_ranges(ranges, cx);
15749 }
15750
15751 pub fn diff_hunks_in_ranges<'a>(
15752 &'a self,
15753 ranges: &'a [Range<Anchor>],
15754 buffer: &'a MultiBufferSnapshot,
15755 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15756 ranges.iter().flat_map(move |range| {
15757 let end_excerpt_id = range.end.excerpt_id;
15758 let range = range.to_point(buffer);
15759 let mut peek_end = range.end;
15760 if range.end.row < buffer.max_row().0 {
15761 peek_end = Point::new(range.end.row + 1, 0);
15762 }
15763 buffer
15764 .diff_hunks_in_range(range.start..peek_end)
15765 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15766 })
15767 }
15768
15769 pub fn has_stageable_diff_hunks_in_ranges(
15770 &self,
15771 ranges: &[Range<Anchor>],
15772 snapshot: &MultiBufferSnapshot,
15773 ) -> bool {
15774 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15775 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15776 }
15777
15778 pub fn toggle_staged_selected_diff_hunks(
15779 &mut self,
15780 _: &::git::ToggleStaged,
15781 _: &mut Window,
15782 cx: &mut Context<Self>,
15783 ) {
15784 let snapshot = self.buffer.read(cx).snapshot(cx);
15785 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15786 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15787 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15788 }
15789
15790 pub fn set_render_diff_hunk_controls(
15791 &mut self,
15792 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15793 cx: &mut Context<Self>,
15794 ) {
15795 self.render_diff_hunk_controls = render_diff_hunk_controls;
15796 cx.notify();
15797 }
15798
15799 pub fn stage_and_next(
15800 &mut self,
15801 _: &::git::StageAndNext,
15802 window: &mut Window,
15803 cx: &mut Context<Self>,
15804 ) {
15805 self.do_stage_or_unstage_and_next(true, window, cx);
15806 }
15807
15808 pub fn unstage_and_next(
15809 &mut self,
15810 _: &::git::UnstageAndNext,
15811 window: &mut Window,
15812 cx: &mut Context<Self>,
15813 ) {
15814 self.do_stage_or_unstage_and_next(false, window, cx);
15815 }
15816
15817 pub fn stage_or_unstage_diff_hunks(
15818 &mut self,
15819 stage: bool,
15820 ranges: Vec<Range<Anchor>>,
15821 cx: &mut Context<Self>,
15822 ) {
15823 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15824 cx.spawn(async move |this, cx| {
15825 task.await?;
15826 this.update(cx, |this, cx| {
15827 let snapshot = this.buffer.read(cx).snapshot(cx);
15828 let chunk_by = this
15829 .diff_hunks_in_ranges(&ranges, &snapshot)
15830 .chunk_by(|hunk| hunk.buffer_id);
15831 for (buffer_id, hunks) in &chunk_by {
15832 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15833 }
15834 })
15835 })
15836 .detach_and_log_err(cx);
15837 }
15838
15839 fn save_buffers_for_ranges_if_needed(
15840 &mut self,
15841 ranges: &[Range<Anchor>],
15842 cx: &mut Context<Editor>,
15843 ) -> Task<Result<()>> {
15844 let multibuffer = self.buffer.read(cx);
15845 let snapshot = multibuffer.read(cx);
15846 let buffer_ids: HashSet<_> = ranges
15847 .iter()
15848 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15849 .collect();
15850 drop(snapshot);
15851
15852 let mut buffers = HashSet::default();
15853 for buffer_id in buffer_ids {
15854 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15855 let buffer = buffer_entity.read(cx);
15856 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15857 {
15858 buffers.insert(buffer_entity);
15859 }
15860 }
15861 }
15862
15863 if let Some(project) = &self.project {
15864 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15865 } else {
15866 Task::ready(Ok(()))
15867 }
15868 }
15869
15870 fn do_stage_or_unstage_and_next(
15871 &mut self,
15872 stage: bool,
15873 window: &mut Window,
15874 cx: &mut Context<Self>,
15875 ) {
15876 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15877
15878 if ranges.iter().any(|range| range.start != range.end) {
15879 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15880 return;
15881 }
15882
15883 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15884 let snapshot = self.snapshot(window, cx);
15885 let position = self.selections.newest::<Point>(cx).head();
15886 let mut row = snapshot
15887 .buffer_snapshot
15888 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15889 .find(|hunk| hunk.row_range.start.0 > position.row)
15890 .map(|hunk| hunk.row_range.start);
15891
15892 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15893 // Outside of the project diff editor, wrap around to the beginning.
15894 if !all_diff_hunks_expanded {
15895 row = row.or_else(|| {
15896 snapshot
15897 .buffer_snapshot
15898 .diff_hunks_in_range(Point::zero()..position)
15899 .find(|hunk| hunk.row_range.end.0 < position.row)
15900 .map(|hunk| hunk.row_range.start)
15901 });
15902 }
15903
15904 if let Some(row) = row {
15905 let destination = Point::new(row.0, 0);
15906 let autoscroll = Autoscroll::center();
15907
15908 self.unfold_ranges(&[destination..destination], false, false, cx);
15909 self.change_selections(Some(autoscroll), window, cx, |s| {
15910 s.select_ranges([destination..destination]);
15911 });
15912 }
15913 }
15914
15915 fn do_stage_or_unstage(
15916 &self,
15917 stage: bool,
15918 buffer_id: BufferId,
15919 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15920 cx: &mut App,
15921 ) -> Option<()> {
15922 let project = self.project.as_ref()?;
15923 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15924 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15925 let buffer_snapshot = buffer.read(cx).snapshot();
15926 let file_exists = buffer_snapshot
15927 .file()
15928 .is_some_and(|file| file.disk_state().exists());
15929 diff.update(cx, |diff, cx| {
15930 diff.stage_or_unstage_hunks(
15931 stage,
15932 &hunks
15933 .map(|hunk| buffer_diff::DiffHunk {
15934 buffer_range: hunk.buffer_range,
15935 diff_base_byte_range: hunk.diff_base_byte_range,
15936 secondary_status: hunk.secondary_status,
15937 range: Point::zero()..Point::zero(), // unused
15938 })
15939 .collect::<Vec<_>>(),
15940 &buffer_snapshot,
15941 file_exists,
15942 cx,
15943 )
15944 });
15945 None
15946 }
15947
15948 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15949 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15950 self.buffer
15951 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15952 }
15953
15954 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15955 self.buffer.update(cx, |buffer, cx| {
15956 let ranges = vec![Anchor::min()..Anchor::max()];
15957 if !buffer.all_diff_hunks_expanded()
15958 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15959 {
15960 buffer.collapse_diff_hunks(ranges, cx);
15961 true
15962 } else {
15963 false
15964 }
15965 })
15966 }
15967
15968 fn toggle_diff_hunks_in_ranges(
15969 &mut self,
15970 ranges: Vec<Range<Anchor>>,
15971 cx: &mut Context<Editor>,
15972 ) {
15973 self.buffer.update(cx, |buffer, cx| {
15974 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15975 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15976 })
15977 }
15978
15979 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15980 self.buffer.update(cx, |buffer, cx| {
15981 let snapshot = buffer.snapshot(cx);
15982 let excerpt_id = range.end.excerpt_id;
15983 let point_range = range.to_point(&snapshot);
15984 let expand = !buffer.single_hunk_is_expanded(range, cx);
15985 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15986 })
15987 }
15988
15989 pub(crate) fn apply_all_diff_hunks(
15990 &mut self,
15991 _: &ApplyAllDiffHunks,
15992 window: &mut Window,
15993 cx: &mut Context<Self>,
15994 ) {
15995 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15996
15997 let buffers = self.buffer.read(cx).all_buffers();
15998 for branch_buffer in buffers {
15999 branch_buffer.update(cx, |branch_buffer, cx| {
16000 branch_buffer.merge_into_base(Vec::new(), cx);
16001 });
16002 }
16003
16004 if let Some(project) = self.project.clone() {
16005 self.save(true, project, window, cx).detach_and_log_err(cx);
16006 }
16007 }
16008
16009 pub(crate) fn apply_selected_diff_hunks(
16010 &mut self,
16011 _: &ApplyDiffHunk,
16012 window: &mut Window,
16013 cx: &mut Context<Self>,
16014 ) {
16015 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16016 let snapshot = self.snapshot(window, cx);
16017 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16018 let mut ranges_by_buffer = HashMap::default();
16019 self.transact(window, cx, |editor, _window, cx| {
16020 for hunk in hunks {
16021 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16022 ranges_by_buffer
16023 .entry(buffer.clone())
16024 .or_insert_with(Vec::new)
16025 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16026 }
16027 }
16028
16029 for (buffer, ranges) in ranges_by_buffer {
16030 buffer.update(cx, |buffer, cx| {
16031 buffer.merge_into_base(ranges, cx);
16032 });
16033 }
16034 });
16035
16036 if let Some(project) = self.project.clone() {
16037 self.save(true, project, window, cx).detach_and_log_err(cx);
16038 }
16039 }
16040
16041 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16042 if hovered != self.gutter_hovered {
16043 self.gutter_hovered = hovered;
16044 cx.notify();
16045 }
16046 }
16047
16048 pub fn insert_blocks(
16049 &mut self,
16050 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16051 autoscroll: Option<Autoscroll>,
16052 cx: &mut Context<Self>,
16053 ) -> Vec<CustomBlockId> {
16054 let blocks = self
16055 .display_map
16056 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16057 if let Some(autoscroll) = autoscroll {
16058 self.request_autoscroll(autoscroll, cx);
16059 }
16060 cx.notify();
16061 blocks
16062 }
16063
16064 pub fn resize_blocks(
16065 &mut self,
16066 heights: HashMap<CustomBlockId, u32>,
16067 autoscroll: Option<Autoscroll>,
16068 cx: &mut Context<Self>,
16069 ) {
16070 self.display_map
16071 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16072 if let Some(autoscroll) = autoscroll {
16073 self.request_autoscroll(autoscroll, cx);
16074 }
16075 cx.notify();
16076 }
16077
16078 pub fn replace_blocks(
16079 &mut self,
16080 renderers: HashMap<CustomBlockId, RenderBlock>,
16081 autoscroll: Option<Autoscroll>,
16082 cx: &mut Context<Self>,
16083 ) {
16084 self.display_map
16085 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16086 if let Some(autoscroll) = autoscroll {
16087 self.request_autoscroll(autoscroll, cx);
16088 }
16089 cx.notify();
16090 }
16091
16092 pub fn remove_blocks(
16093 &mut self,
16094 block_ids: HashSet<CustomBlockId>,
16095 autoscroll: Option<Autoscroll>,
16096 cx: &mut Context<Self>,
16097 ) {
16098 self.display_map.update(cx, |display_map, cx| {
16099 display_map.remove_blocks(block_ids, cx)
16100 });
16101 if let Some(autoscroll) = autoscroll {
16102 self.request_autoscroll(autoscroll, cx);
16103 }
16104 cx.notify();
16105 }
16106
16107 pub fn row_for_block(
16108 &self,
16109 block_id: CustomBlockId,
16110 cx: &mut Context<Self>,
16111 ) -> Option<DisplayRow> {
16112 self.display_map
16113 .update(cx, |map, cx| map.row_for_block(block_id, cx))
16114 }
16115
16116 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16117 self.focused_block = Some(focused_block);
16118 }
16119
16120 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16121 self.focused_block.take()
16122 }
16123
16124 pub fn insert_creases(
16125 &mut self,
16126 creases: impl IntoIterator<Item = Crease<Anchor>>,
16127 cx: &mut Context<Self>,
16128 ) -> Vec<CreaseId> {
16129 self.display_map
16130 .update(cx, |map, cx| map.insert_creases(creases, cx))
16131 }
16132
16133 pub fn remove_creases(
16134 &mut self,
16135 ids: impl IntoIterator<Item = CreaseId>,
16136 cx: &mut Context<Self>,
16137 ) {
16138 self.display_map
16139 .update(cx, |map, cx| map.remove_creases(ids, cx));
16140 }
16141
16142 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16143 self.display_map
16144 .update(cx, |map, cx| map.snapshot(cx))
16145 .longest_row()
16146 }
16147
16148 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16149 self.display_map
16150 .update(cx, |map, cx| map.snapshot(cx))
16151 .max_point()
16152 }
16153
16154 pub fn text(&self, cx: &App) -> String {
16155 self.buffer.read(cx).read(cx).text()
16156 }
16157
16158 pub fn is_empty(&self, cx: &App) -> bool {
16159 self.buffer.read(cx).read(cx).is_empty()
16160 }
16161
16162 pub fn text_option(&self, cx: &App) -> Option<String> {
16163 let text = self.text(cx);
16164 let text = text.trim();
16165
16166 if text.is_empty() {
16167 return None;
16168 }
16169
16170 Some(text.to_string())
16171 }
16172
16173 pub fn set_text(
16174 &mut self,
16175 text: impl Into<Arc<str>>,
16176 window: &mut Window,
16177 cx: &mut Context<Self>,
16178 ) {
16179 self.transact(window, cx, |this, _, cx| {
16180 this.buffer
16181 .read(cx)
16182 .as_singleton()
16183 .expect("you can only call set_text on editors for singleton buffers")
16184 .update(cx, |buffer, cx| buffer.set_text(text, cx));
16185 });
16186 }
16187
16188 pub fn display_text(&self, cx: &mut App) -> String {
16189 self.display_map
16190 .update(cx, |map, cx| map.snapshot(cx))
16191 .text()
16192 }
16193
16194 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16195 let mut wrap_guides = smallvec::smallvec![];
16196
16197 if self.show_wrap_guides == Some(false) {
16198 return wrap_guides;
16199 }
16200
16201 let settings = self.buffer.read(cx).language_settings(cx);
16202 if settings.show_wrap_guides {
16203 match self.soft_wrap_mode(cx) {
16204 SoftWrap::Column(soft_wrap) => {
16205 wrap_guides.push((soft_wrap as usize, true));
16206 }
16207 SoftWrap::Bounded(soft_wrap) => {
16208 wrap_guides.push((soft_wrap as usize, true));
16209 }
16210 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16211 }
16212 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16213 }
16214
16215 wrap_guides
16216 }
16217
16218 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16219 let settings = self.buffer.read(cx).language_settings(cx);
16220 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16221 match mode {
16222 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16223 SoftWrap::None
16224 }
16225 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16226 language_settings::SoftWrap::PreferredLineLength => {
16227 SoftWrap::Column(settings.preferred_line_length)
16228 }
16229 language_settings::SoftWrap::Bounded => {
16230 SoftWrap::Bounded(settings.preferred_line_length)
16231 }
16232 }
16233 }
16234
16235 pub fn set_soft_wrap_mode(
16236 &mut self,
16237 mode: language_settings::SoftWrap,
16238
16239 cx: &mut Context<Self>,
16240 ) {
16241 self.soft_wrap_mode_override = Some(mode);
16242 cx.notify();
16243 }
16244
16245 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16246 self.hard_wrap = hard_wrap;
16247 cx.notify();
16248 }
16249
16250 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16251 self.text_style_refinement = Some(style);
16252 }
16253
16254 /// called by the Element so we know what style we were most recently rendered with.
16255 pub(crate) fn set_style(
16256 &mut self,
16257 style: EditorStyle,
16258 window: &mut Window,
16259 cx: &mut Context<Self>,
16260 ) {
16261 let rem_size = window.rem_size();
16262 self.display_map.update(cx, |map, cx| {
16263 map.set_font(
16264 style.text.font(),
16265 style.text.font_size.to_pixels(rem_size),
16266 cx,
16267 )
16268 });
16269 self.style = Some(style);
16270 }
16271
16272 pub fn style(&self) -> Option<&EditorStyle> {
16273 self.style.as_ref()
16274 }
16275
16276 // Called by the element. This method is not designed to be called outside of the editor
16277 // element's layout code because it does not notify when rewrapping is computed synchronously.
16278 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16279 self.display_map
16280 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16281 }
16282
16283 pub fn set_soft_wrap(&mut self) {
16284 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16285 }
16286
16287 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16288 if self.soft_wrap_mode_override.is_some() {
16289 self.soft_wrap_mode_override.take();
16290 } else {
16291 let soft_wrap = match self.soft_wrap_mode(cx) {
16292 SoftWrap::GitDiff => return,
16293 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16294 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16295 language_settings::SoftWrap::None
16296 }
16297 };
16298 self.soft_wrap_mode_override = Some(soft_wrap);
16299 }
16300 cx.notify();
16301 }
16302
16303 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16304 let Some(workspace) = self.workspace() else {
16305 return;
16306 };
16307 let fs = workspace.read(cx).app_state().fs.clone();
16308 let current_show = TabBarSettings::get_global(cx).show;
16309 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16310 setting.show = Some(!current_show);
16311 });
16312 }
16313
16314 pub fn toggle_indent_guides(
16315 &mut self,
16316 _: &ToggleIndentGuides,
16317 _: &mut Window,
16318 cx: &mut Context<Self>,
16319 ) {
16320 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16321 self.buffer
16322 .read(cx)
16323 .language_settings(cx)
16324 .indent_guides
16325 .enabled
16326 });
16327 self.show_indent_guides = Some(!currently_enabled);
16328 cx.notify();
16329 }
16330
16331 fn should_show_indent_guides(&self) -> Option<bool> {
16332 self.show_indent_guides
16333 }
16334
16335 pub fn toggle_line_numbers(
16336 &mut self,
16337 _: &ToggleLineNumbers,
16338 _: &mut Window,
16339 cx: &mut Context<Self>,
16340 ) {
16341 let mut editor_settings = EditorSettings::get_global(cx).clone();
16342 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16343 EditorSettings::override_global(editor_settings, cx);
16344 }
16345
16346 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16347 if let Some(show_line_numbers) = self.show_line_numbers {
16348 return show_line_numbers;
16349 }
16350 EditorSettings::get_global(cx).gutter.line_numbers
16351 }
16352
16353 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16354 self.use_relative_line_numbers
16355 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16356 }
16357
16358 pub fn toggle_relative_line_numbers(
16359 &mut self,
16360 _: &ToggleRelativeLineNumbers,
16361 _: &mut Window,
16362 cx: &mut Context<Self>,
16363 ) {
16364 let is_relative = self.should_use_relative_line_numbers(cx);
16365 self.set_relative_line_number(Some(!is_relative), cx)
16366 }
16367
16368 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16369 self.use_relative_line_numbers = is_relative;
16370 cx.notify();
16371 }
16372
16373 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16374 self.show_gutter = show_gutter;
16375 cx.notify();
16376 }
16377
16378 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16379 self.show_scrollbars = show_scrollbars;
16380 cx.notify();
16381 }
16382
16383 pub fn disable_scrolling(&mut self, cx: &mut Context<Self>) {
16384 self.disable_scrolling = true;
16385 cx.notify();
16386 }
16387
16388 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16389 self.show_line_numbers = Some(show_line_numbers);
16390 cx.notify();
16391 }
16392
16393 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16394 self.disable_expand_excerpt_buttons = true;
16395 cx.notify();
16396 }
16397
16398 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16399 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16400 cx.notify();
16401 }
16402
16403 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16404 self.show_code_actions = Some(show_code_actions);
16405 cx.notify();
16406 }
16407
16408 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16409 self.show_runnables = Some(show_runnables);
16410 cx.notify();
16411 }
16412
16413 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16414 self.show_breakpoints = Some(show_breakpoints);
16415 cx.notify();
16416 }
16417
16418 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16419 if self.display_map.read(cx).masked != masked {
16420 self.display_map.update(cx, |map, _| map.masked = masked);
16421 }
16422 cx.notify()
16423 }
16424
16425 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16426 self.show_wrap_guides = Some(show_wrap_guides);
16427 cx.notify();
16428 }
16429
16430 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16431 self.show_indent_guides = Some(show_indent_guides);
16432 cx.notify();
16433 }
16434
16435 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16436 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16437 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16438 if let Some(dir) = file.abs_path(cx).parent() {
16439 return Some(dir.to_owned());
16440 }
16441 }
16442
16443 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16444 return Some(project_path.path.to_path_buf());
16445 }
16446 }
16447
16448 None
16449 }
16450
16451 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16452 self.active_excerpt(cx)?
16453 .1
16454 .read(cx)
16455 .file()
16456 .and_then(|f| f.as_local())
16457 }
16458
16459 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16460 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16461 let buffer = buffer.read(cx);
16462 if let Some(project_path) = buffer.project_path(cx) {
16463 let project = self.project.as_ref()?.read(cx);
16464 project.absolute_path(&project_path, cx)
16465 } else {
16466 buffer
16467 .file()
16468 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16469 }
16470 })
16471 }
16472
16473 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16474 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16475 let project_path = buffer.read(cx).project_path(cx)?;
16476 let project = self.project.as_ref()?.read(cx);
16477 let entry = project.entry_for_path(&project_path, cx)?;
16478 let path = entry.path.to_path_buf();
16479 Some(path)
16480 })
16481 }
16482
16483 pub fn reveal_in_finder(
16484 &mut self,
16485 _: &RevealInFileManager,
16486 _window: &mut Window,
16487 cx: &mut Context<Self>,
16488 ) {
16489 if let Some(target) = self.target_file(cx) {
16490 cx.reveal_path(&target.abs_path(cx));
16491 }
16492 }
16493
16494 pub fn copy_path(
16495 &mut self,
16496 _: &zed_actions::workspace::CopyPath,
16497 _window: &mut Window,
16498 cx: &mut Context<Self>,
16499 ) {
16500 if let Some(path) = self.target_file_abs_path(cx) {
16501 if let Some(path) = path.to_str() {
16502 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16503 }
16504 }
16505 }
16506
16507 pub fn copy_relative_path(
16508 &mut self,
16509 _: &zed_actions::workspace::CopyRelativePath,
16510 _window: &mut Window,
16511 cx: &mut Context<Self>,
16512 ) {
16513 if let Some(path) = self.target_file_path(cx) {
16514 if let Some(path) = path.to_str() {
16515 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16516 }
16517 }
16518 }
16519
16520 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16521 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16522 buffer.read(cx).project_path(cx)
16523 } else {
16524 None
16525 }
16526 }
16527
16528 // Returns true if the editor handled a go-to-line request
16529 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16530 maybe!({
16531 let breakpoint_store = self.breakpoint_store.as_ref()?;
16532
16533 let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16534 else {
16535 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16536 return None;
16537 };
16538
16539 let position = active_stack_frame.position;
16540 let buffer_id = position.buffer_id?;
16541 let snapshot = self
16542 .project
16543 .as_ref()?
16544 .read(cx)
16545 .buffer_for_id(buffer_id, cx)?
16546 .read(cx)
16547 .snapshot();
16548
16549 let mut handled = false;
16550 for (id, ExcerptRange { context, .. }) in
16551 self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16552 {
16553 if context.start.cmp(&position, &snapshot).is_ge()
16554 || context.end.cmp(&position, &snapshot).is_lt()
16555 {
16556 continue;
16557 }
16558 let snapshot = self.buffer.read(cx).snapshot(cx);
16559 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16560
16561 handled = true;
16562 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16563 self.go_to_line::<DebugCurrentRowHighlight>(
16564 multibuffer_anchor,
16565 Some(cx.theme().colors().editor_debugger_active_line_background),
16566 window,
16567 cx,
16568 );
16569
16570 cx.notify();
16571 }
16572
16573 handled.then_some(())
16574 })
16575 .is_some()
16576 }
16577
16578 pub fn copy_file_name_without_extension(
16579 &mut self,
16580 _: &CopyFileNameWithoutExtension,
16581 _: &mut Window,
16582 cx: &mut Context<Self>,
16583 ) {
16584 if let Some(file) = self.target_file(cx) {
16585 if let Some(file_stem) = file.path().file_stem() {
16586 if let Some(name) = file_stem.to_str() {
16587 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16588 }
16589 }
16590 }
16591 }
16592
16593 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16594 if let Some(file) = self.target_file(cx) {
16595 if let Some(file_name) = file.path().file_name() {
16596 if let Some(name) = file_name.to_str() {
16597 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16598 }
16599 }
16600 }
16601 }
16602
16603 pub fn toggle_git_blame(
16604 &mut self,
16605 _: &::git::Blame,
16606 window: &mut Window,
16607 cx: &mut Context<Self>,
16608 ) {
16609 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16610
16611 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16612 self.start_git_blame(true, window, cx);
16613 }
16614
16615 cx.notify();
16616 }
16617
16618 pub fn toggle_git_blame_inline(
16619 &mut self,
16620 _: &ToggleGitBlameInline,
16621 window: &mut Window,
16622 cx: &mut Context<Self>,
16623 ) {
16624 self.toggle_git_blame_inline_internal(true, window, cx);
16625 cx.notify();
16626 }
16627
16628 pub fn open_git_blame_commit(
16629 &mut self,
16630 _: &OpenGitBlameCommit,
16631 window: &mut Window,
16632 cx: &mut Context<Self>,
16633 ) {
16634 self.open_git_blame_commit_internal(window, cx);
16635 }
16636
16637 fn open_git_blame_commit_internal(
16638 &mut self,
16639 window: &mut Window,
16640 cx: &mut Context<Self>,
16641 ) -> Option<()> {
16642 let blame = self.blame.as_ref()?;
16643 let snapshot = self.snapshot(window, cx);
16644 let cursor = self.selections.newest::<Point>(cx).head();
16645 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16646 let blame_entry = blame
16647 .update(cx, |blame, cx| {
16648 blame
16649 .blame_for_rows(
16650 &[RowInfo {
16651 buffer_id: Some(buffer.remote_id()),
16652 buffer_row: Some(point.row),
16653 ..Default::default()
16654 }],
16655 cx,
16656 )
16657 .next()
16658 })
16659 .flatten()?;
16660 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16661 let repo = blame.read(cx).repository(cx)?;
16662 let workspace = self.workspace()?.downgrade();
16663 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16664 None
16665 }
16666
16667 pub fn git_blame_inline_enabled(&self) -> bool {
16668 self.git_blame_inline_enabled
16669 }
16670
16671 pub fn toggle_selection_menu(
16672 &mut self,
16673 _: &ToggleSelectionMenu,
16674 _: &mut Window,
16675 cx: &mut Context<Self>,
16676 ) {
16677 self.show_selection_menu = self
16678 .show_selection_menu
16679 .map(|show_selections_menu| !show_selections_menu)
16680 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16681
16682 cx.notify();
16683 }
16684
16685 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16686 self.show_selection_menu
16687 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16688 }
16689
16690 fn start_git_blame(
16691 &mut self,
16692 user_triggered: bool,
16693 window: &mut Window,
16694 cx: &mut Context<Self>,
16695 ) {
16696 if let Some(project) = self.project.as_ref() {
16697 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16698 return;
16699 };
16700
16701 if buffer.read(cx).file().is_none() {
16702 return;
16703 }
16704
16705 let focused = self.focus_handle(cx).contains_focused(window, cx);
16706
16707 let project = project.clone();
16708 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16709 self.blame_subscription =
16710 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16711 self.blame = Some(blame);
16712 }
16713 }
16714
16715 fn toggle_git_blame_inline_internal(
16716 &mut self,
16717 user_triggered: bool,
16718 window: &mut Window,
16719 cx: &mut Context<Self>,
16720 ) {
16721 if self.git_blame_inline_enabled {
16722 self.git_blame_inline_enabled = false;
16723 self.show_git_blame_inline = false;
16724 self.show_git_blame_inline_delay_task.take();
16725 } else {
16726 self.git_blame_inline_enabled = true;
16727 self.start_git_blame_inline(user_triggered, window, cx);
16728 }
16729
16730 cx.notify();
16731 }
16732
16733 fn start_git_blame_inline(
16734 &mut self,
16735 user_triggered: bool,
16736 window: &mut Window,
16737 cx: &mut Context<Self>,
16738 ) {
16739 self.start_git_blame(user_triggered, window, cx);
16740
16741 if ProjectSettings::get_global(cx)
16742 .git
16743 .inline_blame_delay()
16744 .is_some()
16745 {
16746 self.start_inline_blame_timer(window, cx);
16747 } else {
16748 self.show_git_blame_inline = true
16749 }
16750 }
16751
16752 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16753 self.blame.as_ref()
16754 }
16755
16756 pub fn show_git_blame_gutter(&self) -> bool {
16757 self.show_git_blame_gutter
16758 }
16759
16760 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16761 self.show_git_blame_gutter && self.has_blame_entries(cx)
16762 }
16763
16764 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16765 self.show_git_blame_inline
16766 && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16767 && !self.newest_selection_head_on_empty_line(cx)
16768 && self.has_blame_entries(cx)
16769 }
16770
16771 fn has_blame_entries(&self, cx: &App) -> bool {
16772 self.blame()
16773 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16774 }
16775
16776 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16777 let cursor_anchor = self.selections.newest_anchor().head();
16778
16779 let snapshot = self.buffer.read(cx).snapshot(cx);
16780 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16781
16782 snapshot.line_len(buffer_row) == 0
16783 }
16784
16785 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16786 let buffer_and_selection = maybe!({
16787 let selection = self.selections.newest::<Point>(cx);
16788 let selection_range = selection.range();
16789
16790 let multi_buffer = self.buffer().read(cx);
16791 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16792 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16793
16794 let (buffer, range, _) = if selection.reversed {
16795 buffer_ranges.first()
16796 } else {
16797 buffer_ranges.last()
16798 }?;
16799
16800 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16801 ..text::ToPoint::to_point(&range.end, &buffer).row;
16802 Some((
16803 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16804 selection,
16805 ))
16806 });
16807
16808 let Some((buffer, selection)) = buffer_and_selection else {
16809 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16810 };
16811
16812 let Some(project) = self.project.as_ref() else {
16813 return Task::ready(Err(anyhow!("editor does not have project")));
16814 };
16815
16816 project.update(cx, |project, cx| {
16817 project.get_permalink_to_line(&buffer, selection, cx)
16818 })
16819 }
16820
16821 pub fn copy_permalink_to_line(
16822 &mut self,
16823 _: &CopyPermalinkToLine,
16824 window: &mut Window,
16825 cx: &mut Context<Self>,
16826 ) {
16827 let permalink_task = self.get_permalink_to_line(cx);
16828 let workspace = self.workspace();
16829
16830 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16831 Ok(permalink) => {
16832 cx.update(|_, cx| {
16833 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16834 })
16835 .ok();
16836 }
16837 Err(err) => {
16838 let message = format!("Failed to copy permalink: {err}");
16839
16840 Err::<(), anyhow::Error>(err).log_err();
16841
16842 if let Some(workspace) = workspace {
16843 workspace
16844 .update_in(cx, |workspace, _, cx| {
16845 struct CopyPermalinkToLine;
16846
16847 workspace.show_toast(
16848 Toast::new(
16849 NotificationId::unique::<CopyPermalinkToLine>(),
16850 message,
16851 ),
16852 cx,
16853 )
16854 })
16855 .ok();
16856 }
16857 }
16858 })
16859 .detach();
16860 }
16861
16862 pub fn copy_file_location(
16863 &mut self,
16864 _: &CopyFileLocation,
16865 _: &mut Window,
16866 cx: &mut Context<Self>,
16867 ) {
16868 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16869 if let Some(file) = self.target_file(cx) {
16870 if let Some(path) = file.path().to_str() {
16871 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16872 }
16873 }
16874 }
16875
16876 pub fn open_permalink_to_line(
16877 &mut self,
16878 _: &OpenPermalinkToLine,
16879 window: &mut Window,
16880 cx: &mut Context<Self>,
16881 ) {
16882 let permalink_task = self.get_permalink_to_line(cx);
16883 let workspace = self.workspace();
16884
16885 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16886 Ok(permalink) => {
16887 cx.update(|_, cx| {
16888 cx.open_url(permalink.as_ref());
16889 })
16890 .ok();
16891 }
16892 Err(err) => {
16893 let message = format!("Failed to open permalink: {err}");
16894
16895 Err::<(), anyhow::Error>(err).log_err();
16896
16897 if let Some(workspace) = workspace {
16898 workspace
16899 .update(cx, |workspace, cx| {
16900 struct OpenPermalinkToLine;
16901
16902 workspace.show_toast(
16903 Toast::new(
16904 NotificationId::unique::<OpenPermalinkToLine>(),
16905 message,
16906 ),
16907 cx,
16908 )
16909 })
16910 .ok();
16911 }
16912 }
16913 })
16914 .detach();
16915 }
16916
16917 pub fn insert_uuid_v4(
16918 &mut self,
16919 _: &InsertUuidV4,
16920 window: &mut Window,
16921 cx: &mut Context<Self>,
16922 ) {
16923 self.insert_uuid(UuidVersion::V4, window, cx);
16924 }
16925
16926 pub fn insert_uuid_v7(
16927 &mut self,
16928 _: &InsertUuidV7,
16929 window: &mut Window,
16930 cx: &mut Context<Self>,
16931 ) {
16932 self.insert_uuid(UuidVersion::V7, window, cx);
16933 }
16934
16935 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16936 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16937 self.transact(window, cx, |this, window, cx| {
16938 let edits = this
16939 .selections
16940 .all::<Point>(cx)
16941 .into_iter()
16942 .map(|selection| {
16943 let uuid = match version {
16944 UuidVersion::V4 => uuid::Uuid::new_v4(),
16945 UuidVersion::V7 => uuid::Uuid::now_v7(),
16946 };
16947
16948 (selection.range(), uuid.to_string())
16949 });
16950 this.edit(edits, cx);
16951 this.refresh_inline_completion(true, false, window, cx);
16952 });
16953 }
16954
16955 pub fn open_selections_in_multibuffer(
16956 &mut self,
16957 _: &OpenSelectionsInMultibuffer,
16958 window: &mut Window,
16959 cx: &mut Context<Self>,
16960 ) {
16961 let multibuffer = self.buffer.read(cx);
16962
16963 let Some(buffer) = multibuffer.as_singleton() else {
16964 return;
16965 };
16966
16967 let Some(workspace) = self.workspace() else {
16968 return;
16969 };
16970
16971 let locations = self
16972 .selections
16973 .disjoint_anchors()
16974 .iter()
16975 .map(|range| Location {
16976 buffer: buffer.clone(),
16977 range: range.start.text_anchor..range.end.text_anchor,
16978 })
16979 .collect::<Vec<_>>();
16980
16981 let title = multibuffer.title(cx).to_string();
16982
16983 cx.spawn_in(window, async move |_, cx| {
16984 workspace.update_in(cx, |workspace, window, cx| {
16985 Self::open_locations_in_multibuffer(
16986 workspace,
16987 locations,
16988 format!("Selections for '{title}'"),
16989 false,
16990 MultibufferSelectionMode::All,
16991 window,
16992 cx,
16993 );
16994 })
16995 })
16996 .detach();
16997 }
16998
16999 /// Adds a row highlight for the given range. If a row has multiple highlights, the
17000 /// last highlight added will be used.
17001 ///
17002 /// If the range ends at the beginning of a line, then that line will not be highlighted.
17003 pub fn highlight_rows<T: 'static>(
17004 &mut self,
17005 range: Range<Anchor>,
17006 color: Hsla,
17007 options: RowHighlightOptions,
17008 cx: &mut Context<Self>,
17009 ) {
17010 let snapshot = self.buffer().read(cx).snapshot(cx);
17011 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17012 let ix = row_highlights.binary_search_by(|highlight| {
17013 Ordering::Equal
17014 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17015 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17016 });
17017
17018 if let Err(mut ix) = ix {
17019 let index = post_inc(&mut self.highlight_order);
17020
17021 // If this range intersects with the preceding highlight, then merge it with
17022 // the preceding highlight. Otherwise insert a new highlight.
17023 let mut merged = false;
17024 if ix > 0 {
17025 let prev_highlight = &mut row_highlights[ix - 1];
17026 if prev_highlight
17027 .range
17028 .end
17029 .cmp(&range.start, &snapshot)
17030 .is_ge()
17031 {
17032 ix -= 1;
17033 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17034 prev_highlight.range.end = range.end;
17035 }
17036 merged = true;
17037 prev_highlight.index = index;
17038 prev_highlight.color = color;
17039 prev_highlight.options = options;
17040 }
17041 }
17042
17043 if !merged {
17044 row_highlights.insert(
17045 ix,
17046 RowHighlight {
17047 range: range.clone(),
17048 index,
17049 color,
17050 options,
17051 type_id: TypeId::of::<T>(),
17052 },
17053 );
17054 }
17055
17056 // If any of the following highlights intersect with this one, merge them.
17057 while let Some(next_highlight) = row_highlights.get(ix + 1) {
17058 let highlight = &row_highlights[ix];
17059 if next_highlight
17060 .range
17061 .start
17062 .cmp(&highlight.range.end, &snapshot)
17063 .is_le()
17064 {
17065 if next_highlight
17066 .range
17067 .end
17068 .cmp(&highlight.range.end, &snapshot)
17069 .is_gt()
17070 {
17071 row_highlights[ix].range.end = next_highlight.range.end;
17072 }
17073 row_highlights.remove(ix + 1);
17074 } else {
17075 break;
17076 }
17077 }
17078 }
17079 }
17080
17081 /// Remove any highlighted row ranges of the given type that intersect the
17082 /// given ranges.
17083 pub fn remove_highlighted_rows<T: 'static>(
17084 &mut self,
17085 ranges_to_remove: Vec<Range<Anchor>>,
17086 cx: &mut Context<Self>,
17087 ) {
17088 let snapshot = self.buffer().read(cx).snapshot(cx);
17089 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17090 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17091 row_highlights.retain(|highlight| {
17092 while let Some(range_to_remove) = ranges_to_remove.peek() {
17093 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17094 Ordering::Less | Ordering::Equal => {
17095 ranges_to_remove.next();
17096 }
17097 Ordering::Greater => {
17098 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17099 Ordering::Less | Ordering::Equal => {
17100 return false;
17101 }
17102 Ordering::Greater => break,
17103 }
17104 }
17105 }
17106 }
17107
17108 true
17109 })
17110 }
17111
17112 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17113 pub fn clear_row_highlights<T: 'static>(&mut self) {
17114 self.highlighted_rows.remove(&TypeId::of::<T>());
17115 }
17116
17117 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17118 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17119 self.highlighted_rows
17120 .get(&TypeId::of::<T>())
17121 .map_or(&[] as &[_], |vec| vec.as_slice())
17122 .iter()
17123 .map(|highlight| (highlight.range.clone(), highlight.color))
17124 }
17125
17126 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17127 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17128 /// Allows to ignore certain kinds of highlights.
17129 pub fn highlighted_display_rows(
17130 &self,
17131 window: &mut Window,
17132 cx: &mut App,
17133 ) -> BTreeMap<DisplayRow, LineHighlight> {
17134 let snapshot = self.snapshot(window, cx);
17135 let mut used_highlight_orders = HashMap::default();
17136 self.highlighted_rows
17137 .iter()
17138 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17139 .fold(
17140 BTreeMap::<DisplayRow, LineHighlight>::new(),
17141 |mut unique_rows, highlight| {
17142 let start = highlight.range.start.to_display_point(&snapshot);
17143 let end = highlight.range.end.to_display_point(&snapshot);
17144 let start_row = start.row().0;
17145 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17146 && end.column() == 0
17147 {
17148 end.row().0.saturating_sub(1)
17149 } else {
17150 end.row().0
17151 };
17152 for row in start_row..=end_row {
17153 let used_index =
17154 used_highlight_orders.entry(row).or_insert(highlight.index);
17155 if highlight.index >= *used_index {
17156 *used_index = highlight.index;
17157 unique_rows.insert(
17158 DisplayRow(row),
17159 LineHighlight {
17160 include_gutter: highlight.options.include_gutter,
17161 border: None,
17162 background: highlight.color.into(),
17163 type_id: Some(highlight.type_id),
17164 },
17165 );
17166 }
17167 }
17168 unique_rows
17169 },
17170 )
17171 }
17172
17173 pub fn highlighted_display_row_for_autoscroll(
17174 &self,
17175 snapshot: &DisplaySnapshot,
17176 ) -> Option<DisplayRow> {
17177 self.highlighted_rows
17178 .values()
17179 .flat_map(|highlighted_rows| highlighted_rows.iter())
17180 .filter_map(|highlight| {
17181 if highlight.options.autoscroll {
17182 Some(highlight.range.start.to_display_point(snapshot).row())
17183 } else {
17184 None
17185 }
17186 })
17187 .min()
17188 }
17189
17190 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17191 self.highlight_background::<SearchWithinRange>(
17192 ranges,
17193 |colors| colors.editor_document_highlight_read_background,
17194 cx,
17195 )
17196 }
17197
17198 pub fn set_breadcrumb_header(&mut self, new_header: String) {
17199 self.breadcrumb_header = Some(new_header);
17200 }
17201
17202 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17203 self.clear_background_highlights::<SearchWithinRange>(cx);
17204 }
17205
17206 pub fn highlight_background<T: 'static>(
17207 &mut self,
17208 ranges: &[Range<Anchor>],
17209 color_fetcher: fn(&ThemeColors) -> Hsla,
17210 cx: &mut Context<Self>,
17211 ) {
17212 self.background_highlights
17213 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17214 self.scrollbar_marker_state.dirty = true;
17215 cx.notify();
17216 }
17217
17218 pub fn clear_background_highlights<T: 'static>(
17219 &mut self,
17220 cx: &mut Context<Self>,
17221 ) -> Option<BackgroundHighlight> {
17222 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17223 if !text_highlights.1.is_empty() {
17224 self.scrollbar_marker_state.dirty = true;
17225 cx.notify();
17226 }
17227 Some(text_highlights)
17228 }
17229
17230 pub fn highlight_gutter<T: 'static>(
17231 &mut self,
17232 ranges: &[Range<Anchor>],
17233 color_fetcher: fn(&App) -> Hsla,
17234 cx: &mut Context<Self>,
17235 ) {
17236 self.gutter_highlights
17237 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17238 cx.notify();
17239 }
17240
17241 pub fn clear_gutter_highlights<T: 'static>(
17242 &mut self,
17243 cx: &mut Context<Self>,
17244 ) -> Option<GutterHighlight> {
17245 cx.notify();
17246 self.gutter_highlights.remove(&TypeId::of::<T>())
17247 }
17248
17249 #[cfg(feature = "test-support")]
17250 pub fn all_text_background_highlights(
17251 &self,
17252 window: &mut Window,
17253 cx: &mut Context<Self>,
17254 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17255 let snapshot = self.snapshot(window, cx);
17256 let buffer = &snapshot.buffer_snapshot;
17257 let start = buffer.anchor_before(0);
17258 let end = buffer.anchor_after(buffer.len());
17259 let theme = cx.theme().colors();
17260 self.background_highlights_in_range(start..end, &snapshot, theme)
17261 }
17262
17263 #[cfg(feature = "test-support")]
17264 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17265 let snapshot = self.buffer().read(cx).snapshot(cx);
17266
17267 let highlights = self
17268 .background_highlights
17269 .get(&TypeId::of::<items::BufferSearchHighlights>());
17270
17271 if let Some((_color, ranges)) = highlights {
17272 ranges
17273 .iter()
17274 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17275 .collect_vec()
17276 } else {
17277 vec![]
17278 }
17279 }
17280
17281 fn document_highlights_for_position<'a>(
17282 &'a self,
17283 position: Anchor,
17284 buffer: &'a MultiBufferSnapshot,
17285 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17286 let read_highlights = self
17287 .background_highlights
17288 .get(&TypeId::of::<DocumentHighlightRead>())
17289 .map(|h| &h.1);
17290 let write_highlights = self
17291 .background_highlights
17292 .get(&TypeId::of::<DocumentHighlightWrite>())
17293 .map(|h| &h.1);
17294 let left_position = position.bias_left(buffer);
17295 let right_position = position.bias_right(buffer);
17296 read_highlights
17297 .into_iter()
17298 .chain(write_highlights)
17299 .flat_map(move |ranges| {
17300 let start_ix = match ranges.binary_search_by(|probe| {
17301 let cmp = probe.end.cmp(&left_position, buffer);
17302 if cmp.is_ge() {
17303 Ordering::Greater
17304 } else {
17305 Ordering::Less
17306 }
17307 }) {
17308 Ok(i) | Err(i) => i,
17309 };
17310
17311 ranges[start_ix..]
17312 .iter()
17313 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17314 })
17315 }
17316
17317 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17318 self.background_highlights
17319 .get(&TypeId::of::<T>())
17320 .map_or(false, |(_, highlights)| !highlights.is_empty())
17321 }
17322
17323 pub fn background_highlights_in_range(
17324 &self,
17325 search_range: Range<Anchor>,
17326 display_snapshot: &DisplaySnapshot,
17327 theme: &ThemeColors,
17328 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17329 let mut results = Vec::new();
17330 for (color_fetcher, ranges) in self.background_highlights.values() {
17331 let color = color_fetcher(theme);
17332 let start_ix = match ranges.binary_search_by(|probe| {
17333 let cmp = probe
17334 .end
17335 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17336 if cmp.is_gt() {
17337 Ordering::Greater
17338 } else {
17339 Ordering::Less
17340 }
17341 }) {
17342 Ok(i) | Err(i) => i,
17343 };
17344 for range in &ranges[start_ix..] {
17345 if range
17346 .start
17347 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17348 .is_ge()
17349 {
17350 break;
17351 }
17352
17353 let start = range.start.to_display_point(display_snapshot);
17354 let end = range.end.to_display_point(display_snapshot);
17355 results.push((start..end, color))
17356 }
17357 }
17358 results
17359 }
17360
17361 pub fn background_highlight_row_ranges<T: 'static>(
17362 &self,
17363 search_range: Range<Anchor>,
17364 display_snapshot: &DisplaySnapshot,
17365 count: usize,
17366 ) -> Vec<RangeInclusive<DisplayPoint>> {
17367 let mut results = Vec::new();
17368 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17369 return vec![];
17370 };
17371
17372 let start_ix = match ranges.binary_search_by(|probe| {
17373 let cmp = probe
17374 .end
17375 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17376 if cmp.is_gt() {
17377 Ordering::Greater
17378 } else {
17379 Ordering::Less
17380 }
17381 }) {
17382 Ok(i) | Err(i) => i,
17383 };
17384 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17385 if let (Some(start_display), Some(end_display)) = (start, end) {
17386 results.push(
17387 start_display.to_display_point(display_snapshot)
17388 ..=end_display.to_display_point(display_snapshot),
17389 );
17390 }
17391 };
17392 let mut start_row: Option<Point> = None;
17393 let mut end_row: Option<Point> = None;
17394 if ranges.len() > count {
17395 return Vec::new();
17396 }
17397 for range in &ranges[start_ix..] {
17398 if range
17399 .start
17400 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17401 .is_ge()
17402 {
17403 break;
17404 }
17405 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17406 if let Some(current_row) = &end_row {
17407 if end.row == current_row.row {
17408 continue;
17409 }
17410 }
17411 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17412 if start_row.is_none() {
17413 assert_eq!(end_row, None);
17414 start_row = Some(start);
17415 end_row = Some(end);
17416 continue;
17417 }
17418 if let Some(current_end) = end_row.as_mut() {
17419 if start.row > current_end.row + 1 {
17420 push_region(start_row, end_row);
17421 start_row = Some(start);
17422 end_row = Some(end);
17423 } else {
17424 // Merge two hunks.
17425 *current_end = end;
17426 }
17427 } else {
17428 unreachable!();
17429 }
17430 }
17431 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17432 push_region(start_row, end_row);
17433 results
17434 }
17435
17436 pub fn gutter_highlights_in_range(
17437 &self,
17438 search_range: Range<Anchor>,
17439 display_snapshot: &DisplaySnapshot,
17440 cx: &App,
17441 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17442 let mut results = Vec::new();
17443 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17444 let color = color_fetcher(cx);
17445 let start_ix = match ranges.binary_search_by(|probe| {
17446 let cmp = probe
17447 .end
17448 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17449 if cmp.is_gt() {
17450 Ordering::Greater
17451 } else {
17452 Ordering::Less
17453 }
17454 }) {
17455 Ok(i) | Err(i) => i,
17456 };
17457 for range in &ranges[start_ix..] {
17458 if range
17459 .start
17460 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17461 .is_ge()
17462 {
17463 break;
17464 }
17465
17466 let start = range.start.to_display_point(display_snapshot);
17467 let end = range.end.to_display_point(display_snapshot);
17468 results.push((start..end, color))
17469 }
17470 }
17471 results
17472 }
17473
17474 /// Get the text ranges corresponding to the redaction query
17475 pub fn redacted_ranges(
17476 &self,
17477 search_range: Range<Anchor>,
17478 display_snapshot: &DisplaySnapshot,
17479 cx: &App,
17480 ) -> Vec<Range<DisplayPoint>> {
17481 display_snapshot
17482 .buffer_snapshot
17483 .redacted_ranges(search_range, |file| {
17484 if let Some(file) = file {
17485 file.is_private()
17486 && EditorSettings::get(
17487 Some(SettingsLocation {
17488 worktree_id: file.worktree_id(cx),
17489 path: file.path().as_ref(),
17490 }),
17491 cx,
17492 )
17493 .redact_private_values
17494 } else {
17495 false
17496 }
17497 })
17498 .map(|range| {
17499 range.start.to_display_point(display_snapshot)
17500 ..range.end.to_display_point(display_snapshot)
17501 })
17502 .collect()
17503 }
17504
17505 pub fn highlight_text<T: 'static>(
17506 &mut self,
17507 ranges: Vec<Range<Anchor>>,
17508 style: HighlightStyle,
17509 cx: &mut Context<Self>,
17510 ) {
17511 self.display_map.update(cx, |map, _| {
17512 map.highlight_text(TypeId::of::<T>(), ranges, style)
17513 });
17514 cx.notify();
17515 }
17516
17517 pub(crate) fn highlight_inlays<T: 'static>(
17518 &mut self,
17519 highlights: Vec<InlayHighlight>,
17520 style: HighlightStyle,
17521 cx: &mut Context<Self>,
17522 ) {
17523 self.display_map.update(cx, |map, _| {
17524 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17525 });
17526 cx.notify();
17527 }
17528
17529 pub fn text_highlights<'a, T: 'static>(
17530 &'a self,
17531 cx: &'a App,
17532 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17533 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17534 }
17535
17536 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17537 let cleared = self
17538 .display_map
17539 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17540 if cleared {
17541 cx.notify();
17542 }
17543 }
17544
17545 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17546 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17547 && self.focus_handle.is_focused(window)
17548 }
17549
17550 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17551 self.show_cursor_when_unfocused = is_enabled;
17552 cx.notify();
17553 }
17554
17555 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17556 cx.notify();
17557 }
17558
17559 fn on_debug_session_event(
17560 &mut self,
17561 _session: Entity<Session>,
17562 event: &SessionEvent,
17563 cx: &mut Context<Self>,
17564 ) {
17565 match event {
17566 SessionEvent::InvalidateInlineValue => {
17567 self.refresh_inline_values(cx);
17568 }
17569 _ => {}
17570 }
17571 }
17572
17573 fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17574 let Some(project) = self.project.clone() else {
17575 return;
17576 };
17577 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17578 return;
17579 };
17580 if !self.inline_value_cache.enabled {
17581 let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17582 self.splice_inlays(&inlays, Vec::new(), cx);
17583 return;
17584 }
17585
17586 let current_execution_position = self
17587 .highlighted_rows
17588 .get(&TypeId::of::<DebugCurrentRowHighlight>())
17589 .and_then(|lines| lines.last().map(|line| line.range.start));
17590
17591 self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17592 let snapshot = editor
17593 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17594 .ok()?;
17595
17596 let inline_values = editor
17597 .update(cx, |_, cx| {
17598 let Some(current_execution_position) = current_execution_position else {
17599 return Some(Task::ready(Ok(Vec::new())));
17600 };
17601
17602 // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17603 // anchor is in the same buffer
17604 let range =
17605 buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17606 project.inline_values(buffer, range, cx)
17607 })
17608 .ok()
17609 .flatten()?
17610 .await
17611 .context("refreshing debugger inlays")
17612 .log_err()?;
17613
17614 let (excerpt_id, buffer_id) = snapshot
17615 .excerpts()
17616 .next()
17617 .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17618 editor
17619 .update(cx, |editor, cx| {
17620 let new_inlays = inline_values
17621 .into_iter()
17622 .map(|debugger_value| {
17623 Inlay::debugger_hint(
17624 post_inc(&mut editor.next_inlay_id),
17625 Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17626 debugger_value.text(),
17627 )
17628 })
17629 .collect::<Vec<_>>();
17630 let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17631 std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17632
17633 editor.splice_inlays(&inlay_ids, new_inlays, cx);
17634 })
17635 .ok()?;
17636 Some(())
17637 });
17638 }
17639
17640 fn on_buffer_event(
17641 &mut self,
17642 multibuffer: &Entity<MultiBuffer>,
17643 event: &multi_buffer::Event,
17644 window: &mut Window,
17645 cx: &mut Context<Self>,
17646 ) {
17647 match event {
17648 multi_buffer::Event::Edited {
17649 singleton_buffer_edited,
17650 edited_buffer: buffer_edited,
17651 } => {
17652 self.scrollbar_marker_state.dirty = true;
17653 self.active_indent_guides_state.dirty = true;
17654 self.refresh_active_diagnostics(cx);
17655 self.refresh_code_actions(window, cx);
17656 if self.has_active_inline_completion() {
17657 self.update_visible_inline_completion(window, cx);
17658 }
17659 if let Some(buffer) = buffer_edited {
17660 let buffer_id = buffer.read(cx).remote_id();
17661 if !self.registered_buffers.contains_key(&buffer_id) {
17662 if let Some(project) = self.project.as_ref() {
17663 project.update(cx, |project, cx| {
17664 self.registered_buffers.insert(
17665 buffer_id,
17666 project.register_buffer_with_language_servers(&buffer, cx),
17667 );
17668 })
17669 }
17670 }
17671 }
17672 cx.emit(EditorEvent::BufferEdited);
17673 cx.emit(SearchEvent::MatchesInvalidated);
17674 if *singleton_buffer_edited {
17675 if let Some(project) = &self.project {
17676 #[allow(clippy::mutable_key_type)]
17677 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17678 multibuffer
17679 .all_buffers()
17680 .into_iter()
17681 .filter_map(|buffer| {
17682 buffer.update(cx, |buffer, cx| {
17683 let language = buffer.language()?;
17684 let should_discard = project.update(cx, |project, cx| {
17685 project.is_local()
17686 && !project.has_language_servers_for(buffer, cx)
17687 });
17688 should_discard.not().then_some(language.clone())
17689 })
17690 })
17691 .collect::<HashSet<_>>()
17692 });
17693 if !languages_affected.is_empty() {
17694 self.refresh_inlay_hints(
17695 InlayHintRefreshReason::BufferEdited(languages_affected),
17696 cx,
17697 );
17698 }
17699 }
17700 }
17701
17702 let Some(project) = &self.project else { return };
17703 let (telemetry, is_via_ssh) = {
17704 let project = project.read(cx);
17705 let telemetry = project.client().telemetry().clone();
17706 let is_via_ssh = project.is_via_ssh();
17707 (telemetry, is_via_ssh)
17708 };
17709 refresh_linked_ranges(self, window, cx);
17710 telemetry.log_edit_event("editor", is_via_ssh);
17711 }
17712 multi_buffer::Event::ExcerptsAdded {
17713 buffer,
17714 predecessor,
17715 excerpts,
17716 } => {
17717 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17718 let buffer_id = buffer.read(cx).remote_id();
17719 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17720 if let Some(project) = &self.project {
17721 get_uncommitted_diff_for_buffer(
17722 project,
17723 [buffer.clone()],
17724 self.buffer.clone(),
17725 cx,
17726 )
17727 .detach();
17728 }
17729 }
17730 cx.emit(EditorEvent::ExcerptsAdded {
17731 buffer: buffer.clone(),
17732 predecessor: *predecessor,
17733 excerpts: excerpts.clone(),
17734 });
17735 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17736 }
17737 multi_buffer::Event::ExcerptsRemoved {
17738 ids,
17739 removed_buffer_ids,
17740 } => {
17741 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17742 let buffer = self.buffer.read(cx);
17743 self.registered_buffers
17744 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17745 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17746 cx.emit(EditorEvent::ExcerptsRemoved {
17747 ids: ids.clone(),
17748 removed_buffer_ids: removed_buffer_ids.clone(),
17749 })
17750 }
17751 multi_buffer::Event::ExcerptsEdited {
17752 excerpt_ids,
17753 buffer_ids,
17754 } => {
17755 self.display_map.update(cx, |map, cx| {
17756 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17757 });
17758 cx.emit(EditorEvent::ExcerptsEdited {
17759 ids: excerpt_ids.clone(),
17760 })
17761 }
17762 multi_buffer::Event::ExcerptsExpanded { ids } => {
17763 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17764 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17765 }
17766 multi_buffer::Event::Reparsed(buffer_id) => {
17767 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17768 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17769
17770 cx.emit(EditorEvent::Reparsed(*buffer_id));
17771 }
17772 multi_buffer::Event::DiffHunksToggled => {
17773 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17774 }
17775 multi_buffer::Event::LanguageChanged(buffer_id) => {
17776 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17777 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17778 cx.emit(EditorEvent::Reparsed(*buffer_id));
17779 cx.notify();
17780 }
17781 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17782 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17783 multi_buffer::Event::FileHandleChanged
17784 | multi_buffer::Event::Reloaded
17785 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17786 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17787 multi_buffer::Event::DiagnosticsUpdated => {
17788 self.refresh_active_diagnostics(cx);
17789 self.refresh_inline_diagnostics(true, window, cx);
17790 self.scrollbar_marker_state.dirty = true;
17791 cx.notify();
17792 }
17793 _ => {}
17794 };
17795 }
17796
17797 fn on_display_map_changed(
17798 &mut self,
17799 _: Entity<DisplayMap>,
17800 _: &mut Window,
17801 cx: &mut Context<Self>,
17802 ) {
17803 cx.notify();
17804 }
17805
17806 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17807 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17808 self.update_edit_prediction_settings(cx);
17809 self.refresh_inline_completion(true, false, window, cx);
17810 self.refresh_inlay_hints(
17811 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17812 self.selections.newest_anchor().head(),
17813 &self.buffer.read(cx).snapshot(cx),
17814 cx,
17815 )),
17816 cx,
17817 );
17818
17819 let old_cursor_shape = self.cursor_shape;
17820
17821 {
17822 let editor_settings = EditorSettings::get_global(cx);
17823 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17824 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17825 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17826 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17827 }
17828
17829 if old_cursor_shape != self.cursor_shape {
17830 cx.emit(EditorEvent::CursorShapeChanged);
17831 }
17832
17833 let project_settings = ProjectSettings::get_global(cx);
17834 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17835
17836 if self.mode.is_full() {
17837 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17838 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17839 if self.show_inline_diagnostics != show_inline_diagnostics {
17840 self.show_inline_diagnostics = show_inline_diagnostics;
17841 self.refresh_inline_diagnostics(false, window, cx);
17842 }
17843
17844 if self.git_blame_inline_enabled != inline_blame_enabled {
17845 self.toggle_git_blame_inline_internal(false, window, cx);
17846 }
17847 }
17848
17849 cx.notify();
17850 }
17851
17852 pub fn set_searchable(&mut self, searchable: bool) {
17853 self.searchable = searchable;
17854 }
17855
17856 pub fn searchable(&self) -> bool {
17857 self.searchable
17858 }
17859
17860 fn open_proposed_changes_editor(
17861 &mut self,
17862 _: &OpenProposedChangesEditor,
17863 window: &mut Window,
17864 cx: &mut Context<Self>,
17865 ) {
17866 let Some(workspace) = self.workspace() else {
17867 cx.propagate();
17868 return;
17869 };
17870
17871 let selections = self.selections.all::<usize>(cx);
17872 let multi_buffer = self.buffer.read(cx);
17873 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17874 let mut new_selections_by_buffer = HashMap::default();
17875 for selection in selections {
17876 for (buffer, range, _) in
17877 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17878 {
17879 let mut range = range.to_point(buffer);
17880 range.start.column = 0;
17881 range.end.column = buffer.line_len(range.end.row);
17882 new_selections_by_buffer
17883 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17884 .or_insert(Vec::new())
17885 .push(range)
17886 }
17887 }
17888
17889 let proposed_changes_buffers = new_selections_by_buffer
17890 .into_iter()
17891 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17892 .collect::<Vec<_>>();
17893 let proposed_changes_editor = cx.new(|cx| {
17894 ProposedChangesEditor::new(
17895 "Proposed changes",
17896 proposed_changes_buffers,
17897 self.project.clone(),
17898 window,
17899 cx,
17900 )
17901 });
17902
17903 window.defer(cx, move |window, cx| {
17904 workspace.update(cx, |workspace, cx| {
17905 workspace.active_pane().update(cx, |pane, cx| {
17906 pane.add_item(
17907 Box::new(proposed_changes_editor),
17908 true,
17909 true,
17910 None,
17911 window,
17912 cx,
17913 );
17914 });
17915 });
17916 });
17917 }
17918
17919 pub fn open_excerpts_in_split(
17920 &mut self,
17921 _: &OpenExcerptsSplit,
17922 window: &mut Window,
17923 cx: &mut Context<Self>,
17924 ) {
17925 self.open_excerpts_common(None, true, window, cx)
17926 }
17927
17928 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17929 self.open_excerpts_common(None, false, window, cx)
17930 }
17931
17932 fn open_excerpts_common(
17933 &mut self,
17934 jump_data: Option<JumpData>,
17935 split: bool,
17936 window: &mut Window,
17937 cx: &mut Context<Self>,
17938 ) {
17939 let Some(workspace) = self.workspace() else {
17940 cx.propagate();
17941 return;
17942 };
17943
17944 if self.buffer.read(cx).is_singleton() {
17945 cx.propagate();
17946 return;
17947 }
17948
17949 let mut new_selections_by_buffer = HashMap::default();
17950 match &jump_data {
17951 Some(JumpData::MultiBufferPoint {
17952 excerpt_id,
17953 position,
17954 anchor,
17955 line_offset_from_top,
17956 }) => {
17957 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17958 if let Some(buffer) = multi_buffer_snapshot
17959 .buffer_id_for_excerpt(*excerpt_id)
17960 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17961 {
17962 let buffer_snapshot = buffer.read(cx).snapshot();
17963 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17964 language::ToPoint::to_point(anchor, &buffer_snapshot)
17965 } else {
17966 buffer_snapshot.clip_point(*position, Bias::Left)
17967 };
17968 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17969 new_selections_by_buffer.insert(
17970 buffer,
17971 (
17972 vec![jump_to_offset..jump_to_offset],
17973 Some(*line_offset_from_top),
17974 ),
17975 );
17976 }
17977 }
17978 Some(JumpData::MultiBufferRow {
17979 row,
17980 line_offset_from_top,
17981 }) => {
17982 let point = MultiBufferPoint::new(row.0, 0);
17983 if let Some((buffer, buffer_point, _)) =
17984 self.buffer.read(cx).point_to_buffer_point(point, cx)
17985 {
17986 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17987 new_selections_by_buffer
17988 .entry(buffer)
17989 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17990 .0
17991 .push(buffer_offset..buffer_offset)
17992 }
17993 }
17994 None => {
17995 let selections = self.selections.all::<usize>(cx);
17996 let multi_buffer = self.buffer.read(cx);
17997 for selection in selections {
17998 for (snapshot, range, _, anchor) in multi_buffer
17999 .snapshot(cx)
18000 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18001 {
18002 if let Some(anchor) = anchor {
18003 // selection is in a deleted hunk
18004 let Some(buffer_id) = anchor.buffer_id else {
18005 continue;
18006 };
18007 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18008 continue;
18009 };
18010 let offset = text::ToOffset::to_offset(
18011 &anchor.text_anchor,
18012 &buffer_handle.read(cx).snapshot(),
18013 );
18014 let range = offset..offset;
18015 new_selections_by_buffer
18016 .entry(buffer_handle)
18017 .or_insert((Vec::new(), None))
18018 .0
18019 .push(range)
18020 } else {
18021 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18022 else {
18023 continue;
18024 };
18025 new_selections_by_buffer
18026 .entry(buffer_handle)
18027 .or_insert((Vec::new(), None))
18028 .0
18029 .push(range)
18030 }
18031 }
18032 }
18033 }
18034 }
18035
18036 new_selections_by_buffer
18037 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18038
18039 if new_selections_by_buffer.is_empty() {
18040 return;
18041 }
18042
18043 // We defer the pane interaction because we ourselves are a workspace item
18044 // and activating a new item causes the pane to call a method on us reentrantly,
18045 // which panics if we're on the stack.
18046 window.defer(cx, move |window, cx| {
18047 workspace.update(cx, |workspace, cx| {
18048 let pane = if split {
18049 workspace.adjacent_pane(window, cx)
18050 } else {
18051 workspace.active_pane().clone()
18052 };
18053
18054 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18055 let editor = buffer
18056 .read(cx)
18057 .file()
18058 .is_none()
18059 .then(|| {
18060 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18061 // so `workspace.open_project_item` will never find them, always opening a new editor.
18062 // Instead, we try to activate the existing editor in the pane first.
18063 let (editor, pane_item_index) =
18064 pane.read(cx).items().enumerate().find_map(|(i, item)| {
18065 let editor = item.downcast::<Editor>()?;
18066 let singleton_buffer =
18067 editor.read(cx).buffer().read(cx).as_singleton()?;
18068 if singleton_buffer == buffer {
18069 Some((editor, i))
18070 } else {
18071 None
18072 }
18073 })?;
18074 pane.update(cx, |pane, cx| {
18075 pane.activate_item(pane_item_index, true, true, window, cx)
18076 });
18077 Some(editor)
18078 })
18079 .flatten()
18080 .unwrap_or_else(|| {
18081 workspace.open_project_item::<Self>(
18082 pane.clone(),
18083 buffer,
18084 true,
18085 true,
18086 window,
18087 cx,
18088 )
18089 });
18090
18091 editor.update(cx, |editor, cx| {
18092 let autoscroll = match scroll_offset {
18093 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18094 None => Autoscroll::newest(),
18095 };
18096 let nav_history = editor.nav_history.take();
18097 editor.change_selections(Some(autoscroll), window, cx, |s| {
18098 s.select_ranges(ranges);
18099 });
18100 editor.nav_history = nav_history;
18101 });
18102 }
18103 })
18104 });
18105 }
18106
18107 // For now, don't allow opening excerpts in buffers that aren't backed by
18108 // regular project files.
18109 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18110 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18111 }
18112
18113 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18114 let snapshot = self.buffer.read(cx).read(cx);
18115 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18116 Some(
18117 ranges
18118 .iter()
18119 .map(move |range| {
18120 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18121 })
18122 .collect(),
18123 )
18124 }
18125
18126 fn selection_replacement_ranges(
18127 &self,
18128 range: Range<OffsetUtf16>,
18129 cx: &mut App,
18130 ) -> Vec<Range<OffsetUtf16>> {
18131 let selections = self.selections.all::<OffsetUtf16>(cx);
18132 let newest_selection = selections
18133 .iter()
18134 .max_by_key(|selection| selection.id)
18135 .unwrap();
18136 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18137 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18138 let snapshot = self.buffer.read(cx).read(cx);
18139 selections
18140 .into_iter()
18141 .map(|mut selection| {
18142 selection.start.0 =
18143 (selection.start.0 as isize).saturating_add(start_delta) as usize;
18144 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18145 snapshot.clip_offset_utf16(selection.start, Bias::Left)
18146 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18147 })
18148 .collect()
18149 }
18150
18151 fn report_editor_event(
18152 &self,
18153 event_type: &'static str,
18154 file_extension: Option<String>,
18155 cx: &App,
18156 ) {
18157 if cfg!(any(test, feature = "test-support")) {
18158 return;
18159 }
18160
18161 let Some(project) = &self.project else { return };
18162
18163 // If None, we are in a file without an extension
18164 let file = self
18165 .buffer
18166 .read(cx)
18167 .as_singleton()
18168 .and_then(|b| b.read(cx).file());
18169 let file_extension = file_extension.or(file
18170 .as_ref()
18171 .and_then(|file| Path::new(file.file_name(cx)).extension())
18172 .and_then(|e| e.to_str())
18173 .map(|a| a.to_string()));
18174
18175 let vim_mode = vim_enabled(cx);
18176
18177 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18178 let copilot_enabled = edit_predictions_provider
18179 == language::language_settings::EditPredictionProvider::Copilot;
18180 let copilot_enabled_for_language = self
18181 .buffer
18182 .read(cx)
18183 .language_settings(cx)
18184 .show_edit_predictions;
18185
18186 let project = project.read(cx);
18187 telemetry::event!(
18188 event_type,
18189 file_extension,
18190 vim_mode,
18191 copilot_enabled,
18192 copilot_enabled_for_language,
18193 edit_predictions_provider,
18194 is_via_ssh = project.is_via_ssh(),
18195 );
18196 }
18197
18198 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18199 /// with each line being an array of {text, highlight} objects.
18200 fn copy_highlight_json(
18201 &mut self,
18202 _: &CopyHighlightJson,
18203 window: &mut Window,
18204 cx: &mut Context<Self>,
18205 ) {
18206 #[derive(Serialize)]
18207 struct Chunk<'a> {
18208 text: String,
18209 highlight: Option<&'a str>,
18210 }
18211
18212 let snapshot = self.buffer.read(cx).snapshot(cx);
18213 let range = self
18214 .selected_text_range(false, window, cx)
18215 .and_then(|selection| {
18216 if selection.range.is_empty() {
18217 None
18218 } else {
18219 Some(selection.range)
18220 }
18221 })
18222 .unwrap_or_else(|| 0..snapshot.len());
18223
18224 let chunks = snapshot.chunks(range, true);
18225 let mut lines = Vec::new();
18226 let mut line: VecDeque<Chunk> = VecDeque::new();
18227
18228 let Some(style) = self.style.as_ref() else {
18229 return;
18230 };
18231
18232 for chunk in chunks {
18233 let highlight = chunk
18234 .syntax_highlight_id
18235 .and_then(|id| id.name(&style.syntax));
18236 let mut chunk_lines = chunk.text.split('\n').peekable();
18237 while let Some(text) = chunk_lines.next() {
18238 let mut merged_with_last_token = false;
18239 if let Some(last_token) = line.back_mut() {
18240 if last_token.highlight == highlight {
18241 last_token.text.push_str(text);
18242 merged_with_last_token = true;
18243 }
18244 }
18245
18246 if !merged_with_last_token {
18247 line.push_back(Chunk {
18248 text: text.into(),
18249 highlight,
18250 });
18251 }
18252
18253 if chunk_lines.peek().is_some() {
18254 if line.len() > 1 && line.front().unwrap().text.is_empty() {
18255 line.pop_front();
18256 }
18257 if line.len() > 1 && line.back().unwrap().text.is_empty() {
18258 line.pop_back();
18259 }
18260
18261 lines.push(mem::take(&mut line));
18262 }
18263 }
18264 }
18265
18266 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18267 return;
18268 };
18269 cx.write_to_clipboard(ClipboardItem::new_string(lines));
18270 }
18271
18272 pub fn open_context_menu(
18273 &mut self,
18274 _: &OpenContextMenu,
18275 window: &mut Window,
18276 cx: &mut Context<Self>,
18277 ) {
18278 self.request_autoscroll(Autoscroll::newest(), cx);
18279 let position = self.selections.newest_display(cx).start;
18280 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18281 }
18282
18283 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18284 &self.inlay_hint_cache
18285 }
18286
18287 pub fn replay_insert_event(
18288 &mut self,
18289 text: &str,
18290 relative_utf16_range: Option<Range<isize>>,
18291 window: &mut Window,
18292 cx: &mut Context<Self>,
18293 ) {
18294 if !self.input_enabled {
18295 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18296 return;
18297 }
18298 if let Some(relative_utf16_range) = relative_utf16_range {
18299 let selections = self.selections.all::<OffsetUtf16>(cx);
18300 self.change_selections(None, window, cx, |s| {
18301 let new_ranges = selections.into_iter().map(|range| {
18302 let start = OffsetUtf16(
18303 range
18304 .head()
18305 .0
18306 .saturating_add_signed(relative_utf16_range.start),
18307 );
18308 let end = OffsetUtf16(
18309 range
18310 .head()
18311 .0
18312 .saturating_add_signed(relative_utf16_range.end),
18313 );
18314 start..end
18315 });
18316 s.select_ranges(new_ranges);
18317 });
18318 }
18319
18320 self.handle_input(text, window, cx);
18321 }
18322
18323 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18324 let Some(provider) = self.semantics_provider.as_ref() else {
18325 return false;
18326 };
18327
18328 let mut supports = false;
18329 self.buffer().update(cx, |this, cx| {
18330 this.for_each_buffer(|buffer| {
18331 supports |= provider.supports_inlay_hints(buffer, cx);
18332 });
18333 });
18334
18335 supports
18336 }
18337
18338 pub fn is_focused(&self, window: &Window) -> bool {
18339 self.focus_handle.is_focused(window)
18340 }
18341
18342 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18343 cx.emit(EditorEvent::Focused);
18344
18345 if let Some(descendant) = self
18346 .last_focused_descendant
18347 .take()
18348 .and_then(|descendant| descendant.upgrade())
18349 {
18350 window.focus(&descendant);
18351 } else {
18352 if let Some(blame) = self.blame.as_ref() {
18353 blame.update(cx, GitBlame::focus)
18354 }
18355
18356 self.blink_manager.update(cx, BlinkManager::enable);
18357 self.show_cursor_names(window, cx);
18358 self.buffer.update(cx, |buffer, cx| {
18359 buffer.finalize_last_transaction(cx);
18360 if self.leader_peer_id.is_none() {
18361 buffer.set_active_selections(
18362 &self.selections.disjoint_anchors(),
18363 self.selections.line_mode,
18364 self.cursor_shape,
18365 cx,
18366 );
18367 }
18368 });
18369 }
18370 }
18371
18372 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18373 cx.emit(EditorEvent::FocusedIn)
18374 }
18375
18376 fn handle_focus_out(
18377 &mut self,
18378 event: FocusOutEvent,
18379 _window: &mut Window,
18380 cx: &mut Context<Self>,
18381 ) {
18382 if event.blurred != self.focus_handle {
18383 self.last_focused_descendant = Some(event.blurred);
18384 }
18385 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18386 }
18387
18388 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18389 self.blink_manager.update(cx, BlinkManager::disable);
18390 self.buffer
18391 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18392
18393 if let Some(blame) = self.blame.as_ref() {
18394 blame.update(cx, GitBlame::blur)
18395 }
18396 if !self.hover_state.focused(window, cx) {
18397 hide_hover(self, cx);
18398 }
18399 if !self
18400 .context_menu
18401 .borrow()
18402 .as_ref()
18403 .is_some_and(|context_menu| context_menu.focused(window, cx))
18404 {
18405 self.hide_context_menu(window, cx);
18406 }
18407 self.discard_inline_completion(false, cx);
18408 cx.emit(EditorEvent::Blurred);
18409 cx.notify();
18410 }
18411
18412 pub fn register_action<A: Action>(
18413 &mut self,
18414 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18415 ) -> Subscription {
18416 let id = self.next_editor_action_id.post_inc();
18417 let listener = Arc::new(listener);
18418 self.editor_actions.borrow_mut().insert(
18419 id,
18420 Box::new(move |window, _| {
18421 let listener = listener.clone();
18422 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18423 let action = action.downcast_ref().unwrap();
18424 if phase == DispatchPhase::Bubble {
18425 listener(action, window, cx)
18426 }
18427 })
18428 }),
18429 );
18430
18431 let editor_actions = self.editor_actions.clone();
18432 Subscription::new(move || {
18433 editor_actions.borrow_mut().remove(&id);
18434 })
18435 }
18436
18437 pub fn file_header_size(&self) -> u32 {
18438 FILE_HEADER_HEIGHT
18439 }
18440
18441 pub fn restore(
18442 &mut self,
18443 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18444 window: &mut Window,
18445 cx: &mut Context<Self>,
18446 ) {
18447 let workspace = self.workspace();
18448 let project = self.project.as_ref();
18449 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18450 let mut tasks = Vec::new();
18451 for (buffer_id, changes) in revert_changes {
18452 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18453 buffer.update(cx, |buffer, cx| {
18454 buffer.edit(
18455 changes
18456 .into_iter()
18457 .map(|(range, text)| (range, text.to_string())),
18458 None,
18459 cx,
18460 );
18461 });
18462
18463 if let Some(project) =
18464 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18465 {
18466 project.update(cx, |project, cx| {
18467 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18468 })
18469 }
18470 }
18471 }
18472 tasks
18473 });
18474 cx.spawn_in(window, async move |_, cx| {
18475 for (buffer, task) in save_tasks {
18476 let result = task.await;
18477 if result.is_err() {
18478 let Some(path) = buffer
18479 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18480 .ok()
18481 else {
18482 continue;
18483 };
18484 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18485 let Some(task) = cx
18486 .update_window_entity(&workspace, |workspace, window, cx| {
18487 workspace
18488 .open_path_preview(path, None, false, false, false, window, cx)
18489 })
18490 .ok()
18491 else {
18492 continue;
18493 };
18494 task.await.log_err();
18495 }
18496 }
18497 }
18498 })
18499 .detach();
18500 self.change_selections(None, window, cx, |selections| selections.refresh());
18501 }
18502
18503 pub fn to_pixel_point(
18504 &self,
18505 source: multi_buffer::Anchor,
18506 editor_snapshot: &EditorSnapshot,
18507 window: &mut Window,
18508 ) -> Option<gpui::Point<Pixels>> {
18509 let source_point = source.to_display_point(editor_snapshot);
18510 self.display_to_pixel_point(source_point, editor_snapshot, window)
18511 }
18512
18513 pub fn display_to_pixel_point(
18514 &self,
18515 source: DisplayPoint,
18516 editor_snapshot: &EditorSnapshot,
18517 window: &mut Window,
18518 ) -> Option<gpui::Point<Pixels>> {
18519 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18520 let text_layout_details = self.text_layout_details(window);
18521 let scroll_top = text_layout_details
18522 .scroll_anchor
18523 .scroll_position(editor_snapshot)
18524 .y;
18525
18526 if source.row().as_f32() < scroll_top.floor() {
18527 return None;
18528 }
18529 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18530 let source_y = line_height * (source.row().as_f32() - scroll_top);
18531 Some(gpui::Point::new(source_x, source_y))
18532 }
18533
18534 pub fn has_visible_completions_menu(&self) -> bool {
18535 !self.edit_prediction_preview_is_active()
18536 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18537 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18538 })
18539 }
18540
18541 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18542 self.addons
18543 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18544 }
18545
18546 pub fn unregister_addon<T: Addon>(&mut self) {
18547 self.addons.remove(&std::any::TypeId::of::<T>());
18548 }
18549
18550 pub fn addon<T: Addon>(&self) -> Option<&T> {
18551 let type_id = std::any::TypeId::of::<T>();
18552 self.addons
18553 .get(&type_id)
18554 .and_then(|item| item.to_any().downcast_ref::<T>())
18555 }
18556
18557 pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18558 let type_id = std::any::TypeId::of::<T>();
18559 self.addons
18560 .get_mut(&type_id)
18561 .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18562 }
18563
18564 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18565 let text_layout_details = self.text_layout_details(window);
18566 let style = &text_layout_details.editor_style;
18567 let font_id = window.text_system().resolve_font(&style.text.font());
18568 let font_size = style.text.font_size.to_pixels(window.rem_size());
18569 let line_height = style.text.line_height_in_pixels(window.rem_size());
18570 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18571
18572 gpui::Size::new(em_width, line_height)
18573 }
18574
18575 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18576 self.load_diff_task.clone()
18577 }
18578
18579 fn read_metadata_from_db(
18580 &mut self,
18581 item_id: u64,
18582 workspace_id: WorkspaceId,
18583 window: &mut Window,
18584 cx: &mut Context<Editor>,
18585 ) {
18586 if self.is_singleton(cx)
18587 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18588 {
18589 let buffer_snapshot = OnceCell::new();
18590
18591 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18592 if !folds.is_empty() {
18593 let snapshot =
18594 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18595 self.fold_ranges(
18596 folds
18597 .into_iter()
18598 .map(|(start, end)| {
18599 snapshot.clip_offset(start, Bias::Left)
18600 ..snapshot.clip_offset(end, Bias::Right)
18601 })
18602 .collect(),
18603 false,
18604 window,
18605 cx,
18606 );
18607 }
18608 }
18609
18610 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18611 if !selections.is_empty() {
18612 let snapshot =
18613 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18614 self.change_selections(None, window, cx, |s| {
18615 s.select_ranges(selections.into_iter().map(|(start, end)| {
18616 snapshot.clip_offset(start, Bias::Left)
18617 ..snapshot.clip_offset(end, Bias::Right)
18618 }));
18619 });
18620 }
18621 };
18622 }
18623
18624 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18625 }
18626}
18627
18628fn vim_enabled(cx: &App) -> bool {
18629 cx.global::<SettingsStore>()
18630 .raw_user_settings()
18631 .get("vim_mode")
18632 == Some(&serde_json::Value::Bool(true))
18633}
18634
18635// Consider user intent and default settings
18636fn choose_completion_range(
18637 completion: &Completion,
18638 intent: CompletionIntent,
18639 buffer: &Entity<Buffer>,
18640 cx: &mut Context<Editor>,
18641) -> Range<usize> {
18642 fn should_replace(
18643 completion: &Completion,
18644 insert_range: &Range<text::Anchor>,
18645 intent: CompletionIntent,
18646 completion_mode_setting: LspInsertMode,
18647 buffer: &Buffer,
18648 ) -> bool {
18649 // specific actions take precedence over settings
18650 match intent {
18651 CompletionIntent::CompleteWithInsert => return false,
18652 CompletionIntent::CompleteWithReplace => return true,
18653 CompletionIntent::Complete | CompletionIntent::Compose => {}
18654 }
18655
18656 match completion_mode_setting {
18657 LspInsertMode::Insert => false,
18658 LspInsertMode::Replace => true,
18659 LspInsertMode::ReplaceSubsequence => {
18660 let mut text_to_replace = buffer.chars_for_range(
18661 buffer.anchor_before(completion.replace_range.start)
18662 ..buffer.anchor_after(completion.replace_range.end),
18663 );
18664 let mut completion_text = completion.new_text.chars();
18665
18666 // is `text_to_replace` a subsequence of `completion_text`
18667 text_to_replace
18668 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18669 }
18670 LspInsertMode::ReplaceSuffix => {
18671 let range_after_cursor = insert_range.end..completion.replace_range.end;
18672
18673 let text_after_cursor = buffer
18674 .text_for_range(
18675 buffer.anchor_before(range_after_cursor.start)
18676 ..buffer.anchor_after(range_after_cursor.end),
18677 )
18678 .collect::<String>();
18679 completion.new_text.ends_with(&text_after_cursor)
18680 }
18681 }
18682 }
18683
18684 let buffer = buffer.read(cx);
18685
18686 if let CompletionSource::Lsp {
18687 insert_range: Some(insert_range),
18688 ..
18689 } = &completion.source
18690 {
18691 let completion_mode_setting =
18692 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18693 .completions
18694 .lsp_insert_mode;
18695
18696 if !should_replace(
18697 completion,
18698 &insert_range,
18699 intent,
18700 completion_mode_setting,
18701 buffer,
18702 ) {
18703 return insert_range.to_offset(buffer);
18704 }
18705 }
18706
18707 completion.replace_range.to_offset(buffer)
18708}
18709
18710fn insert_extra_newline_brackets(
18711 buffer: &MultiBufferSnapshot,
18712 range: Range<usize>,
18713 language: &language::LanguageScope,
18714) -> bool {
18715 let leading_whitespace_len = buffer
18716 .reversed_chars_at(range.start)
18717 .take_while(|c| c.is_whitespace() && *c != '\n')
18718 .map(|c| c.len_utf8())
18719 .sum::<usize>();
18720 let trailing_whitespace_len = buffer
18721 .chars_at(range.end)
18722 .take_while(|c| c.is_whitespace() && *c != '\n')
18723 .map(|c| c.len_utf8())
18724 .sum::<usize>();
18725 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18726
18727 language.brackets().any(|(pair, enabled)| {
18728 let pair_start = pair.start.trim_end();
18729 let pair_end = pair.end.trim_start();
18730
18731 enabled
18732 && pair.newline
18733 && buffer.contains_str_at(range.end, pair_end)
18734 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18735 })
18736}
18737
18738fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18739 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18740 [(buffer, range, _)] => (*buffer, range.clone()),
18741 _ => return false,
18742 };
18743 let pair = {
18744 let mut result: Option<BracketMatch> = None;
18745
18746 for pair in buffer
18747 .all_bracket_ranges(range.clone())
18748 .filter(move |pair| {
18749 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18750 })
18751 {
18752 let len = pair.close_range.end - pair.open_range.start;
18753
18754 if let Some(existing) = &result {
18755 let existing_len = existing.close_range.end - existing.open_range.start;
18756 if len > existing_len {
18757 continue;
18758 }
18759 }
18760
18761 result = Some(pair);
18762 }
18763
18764 result
18765 };
18766 let Some(pair) = pair else {
18767 return false;
18768 };
18769 pair.newline_only
18770 && buffer
18771 .chars_for_range(pair.open_range.end..range.start)
18772 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18773 .all(|c| c.is_whitespace() && c != '\n')
18774}
18775
18776fn get_uncommitted_diff_for_buffer(
18777 project: &Entity<Project>,
18778 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18779 buffer: Entity<MultiBuffer>,
18780 cx: &mut App,
18781) -> Task<()> {
18782 let mut tasks = Vec::new();
18783 project.update(cx, |project, cx| {
18784 for buffer in buffers {
18785 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18786 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18787 }
18788 }
18789 });
18790 cx.spawn(async move |cx| {
18791 let diffs = future::join_all(tasks).await;
18792 buffer
18793 .update(cx, |buffer, cx| {
18794 for diff in diffs.into_iter().flatten() {
18795 buffer.add_diff(diff, cx);
18796 }
18797 })
18798 .ok();
18799 })
18800}
18801
18802fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18803 let tab_size = tab_size.get() as usize;
18804 let mut width = offset;
18805
18806 for ch in text.chars() {
18807 width += if ch == '\t' {
18808 tab_size - (width % tab_size)
18809 } else {
18810 1
18811 };
18812 }
18813
18814 width - offset
18815}
18816
18817#[cfg(test)]
18818mod tests {
18819 use super::*;
18820
18821 #[test]
18822 fn test_string_size_with_expanded_tabs() {
18823 let nz = |val| NonZeroU32::new(val).unwrap();
18824 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18825 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18826 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18827 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18828 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18829 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18830 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18831 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18832 }
18833}
18834
18835/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18836struct WordBreakingTokenizer<'a> {
18837 input: &'a str,
18838}
18839
18840impl<'a> WordBreakingTokenizer<'a> {
18841 fn new(input: &'a str) -> Self {
18842 Self { input }
18843 }
18844}
18845
18846fn is_char_ideographic(ch: char) -> bool {
18847 use unicode_script::Script::*;
18848 use unicode_script::UnicodeScript;
18849 matches!(ch.script(), Han | Tangut | Yi)
18850}
18851
18852fn is_grapheme_ideographic(text: &str) -> bool {
18853 text.chars().any(is_char_ideographic)
18854}
18855
18856fn is_grapheme_whitespace(text: &str) -> bool {
18857 text.chars().any(|x| x.is_whitespace())
18858}
18859
18860fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18861 text.chars().next().map_or(false, |ch| {
18862 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18863 })
18864}
18865
18866#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18867enum WordBreakToken<'a> {
18868 Word { token: &'a str, grapheme_len: usize },
18869 InlineWhitespace { token: &'a str, grapheme_len: usize },
18870 Newline,
18871}
18872
18873impl<'a> Iterator for WordBreakingTokenizer<'a> {
18874 /// Yields a span, the count of graphemes in the token, and whether it was
18875 /// whitespace. Note that it also breaks at word boundaries.
18876 type Item = WordBreakToken<'a>;
18877
18878 fn next(&mut self) -> Option<Self::Item> {
18879 use unicode_segmentation::UnicodeSegmentation;
18880 if self.input.is_empty() {
18881 return None;
18882 }
18883
18884 let mut iter = self.input.graphemes(true).peekable();
18885 let mut offset = 0;
18886 let mut grapheme_len = 0;
18887 if let Some(first_grapheme) = iter.next() {
18888 let is_newline = first_grapheme == "\n";
18889 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18890 offset += first_grapheme.len();
18891 grapheme_len += 1;
18892 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18893 if let Some(grapheme) = iter.peek().copied() {
18894 if should_stay_with_preceding_ideograph(grapheme) {
18895 offset += grapheme.len();
18896 grapheme_len += 1;
18897 }
18898 }
18899 } else {
18900 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18901 let mut next_word_bound = words.peek().copied();
18902 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18903 next_word_bound = words.next();
18904 }
18905 while let Some(grapheme) = iter.peek().copied() {
18906 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18907 break;
18908 };
18909 if is_grapheme_whitespace(grapheme) != is_whitespace
18910 || (grapheme == "\n") != is_newline
18911 {
18912 break;
18913 };
18914 offset += grapheme.len();
18915 grapheme_len += 1;
18916 iter.next();
18917 }
18918 }
18919 let token = &self.input[..offset];
18920 self.input = &self.input[offset..];
18921 if token == "\n" {
18922 Some(WordBreakToken::Newline)
18923 } else if is_whitespace {
18924 Some(WordBreakToken::InlineWhitespace {
18925 token,
18926 grapheme_len,
18927 })
18928 } else {
18929 Some(WordBreakToken::Word {
18930 token,
18931 grapheme_len,
18932 })
18933 }
18934 } else {
18935 None
18936 }
18937 }
18938}
18939
18940#[test]
18941fn test_word_breaking_tokenizer() {
18942 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18943 ("", &[]),
18944 (" ", &[whitespace(" ", 2)]),
18945 ("Ʒ", &[word("Ʒ", 1)]),
18946 ("Ǽ", &[word("Ǽ", 1)]),
18947 ("⋑", &[word("⋑", 1)]),
18948 ("⋑⋑", &[word("⋑⋑", 2)]),
18949 (
18950 "原理,进而",
18951 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18952 ),
18953 (
18954 "hello world",
18955 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18956 ),
18957 (
18958 "hello, world",
18959 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18960 ),
18961 (
18962 " hello world",
18963 &[
18964 whitespace(" ", 2),
18965 word("hello", 5),
18966 whitespace(" ", 1),
18967 word("world", 5),
18968 ],
18969 ),
18970 (
18971 "这是什么 \n 钢笔",
18972 &[
18973 word("这", 1),
18974 word("是", 1),
18975 word("什", 1),
18976 word("么", 1),
18977 whitespace(" ", 1),
18978 newline(),
18979 whitespace(" ", 1),
18980 word("钢", 1),
18981 word("笔", 1),
18982 ],
18983 ),
18984 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18985 ];
18986
18987 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18988 WordBreakToken::Word {
18989 token,
18990 grapheme_len,
18991 }
18992 }
18993
18994 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18995 WordBreakToken::InlineWhitespace {
18996 token,
18997 grapheme_len,
18998 }
18999 }
19000
19001 fn newline() -> WordBreakToken<'static> {
19002 WordBreakToken::Newline
19003 }
19004
19005 for (input, result) in tests {
19006 assert_eq!(
19007 WordBreakingTokenizer::new(input)
19008 .collect::<Vec<_>>()
19009 .as_slice(),
19010 *result,
19011 );
19012 }
19013}
19014
19015fn wrap_with_prefix(
19016 line_prefix: String,
19017 unwrapped_text: String,
19018 wrap_column: usize,
19019 tab_size: NonZeroU32,
19020 preserve_existing_whitespace: bool,
19021) -> String {
19022 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19023 let mut wrapped_text = String::new();
19024 let mut current_line = line_prefix.clone();
19025
19026 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19027 let mut current_line_len = line_prefix_len;
19028 let mut in_whitespace = false;
19029 for token in tokenizer {
19030 let have_preceding_whitespace = in_whitespace;
19031 match token {
19032 WordBreakToken::Word {
19033 token,
19034 grapheme_len,
19035 } => {
19036 in_whitespace = false;
19037 if current_line_len + grapheme_len > wrap_column
19038 && current_line_len != line_prefix_len
19039 {
19040 wrapped_text.push_str(current_line.trim_end());
19041 wrapped_text.push('\n');
19042 current_line.truncate(line_prefix.len());
19043 current_line_len = line_prefix_len;
19044 }
19045 current_line.push_str(token);
19046 current_line_len += grapheme_len;
19047 }
19048 WordBreakToken::InlineWhitespace {
19049 mut token,
19050 mut grapheme_len,
19051 } => {
19052 in_whitespace = true;
19053 if have_preceding_whitespace && !preserve_existing_whitespace {
19054 continue;
19055 }
19056 if !preserve_existing_whitespace {
19057 token = " ";
19058 grapheme_len = 1;
19059 }
19060 if current_line_len + grapheme_len > wrap_column {
19061 wrapped_text.push_str(current_line.trim_end());
19062 wrapped_text.push('\n');
19063 current_line.truncate(line_prefix.len());
19064 current_line_len = line_prefix_len;
19065 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19066 current_line.push_str(token);
19067 current_line_len += grapheme_len;
19068 }
19069 }
19070 WordBreakToken::Newline => {
19071 in_whitespace = true;
19072 if preserve_existing_whitespace {
19073 wrapped_text.push_str(current_line.trim_end());
19074 wrapped_text.push('\n');
19075 current_line.truncate(line_prefix.len());
19076 current_line_len = line_prefix_len;
19077 } else if have_preceding_whitespace {
19078 continue;
19079 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19080 {
19081 wrapped_text.push_str(current_line.trim_end());
19082 wrapped_text.push('\n');
19083 current_line.truncate(line_prefix.len());
19084 current_line_len = line_prefix_len;
19085 } else if current_line_len != line_prefix_len {
19086 current_line.push(' ');
19087 current_line_len += 1;
19088 }
19089 }
19090 }
19091 }
19092
19093 if !current_line.is_empty() {
19094 wrapped_text.push_str(¤t_line);
19095 }
19096 wrapped_text
19097}
19098
19099#[test]
19100fn test_wrap_with_prefix() {
19101 assert_eq!(
19102 wrap_with_prefix(
19103 "# ".to_string(),
19104 "abcdefg".to_string(),
19105 4,
19106 NonZeroU32::new(4).unwrap(),
19107 false,
19108 ),
19109 "# abcdefg"
19110 );
19111 assert_eq!(
19112 wrap_with_prefix(
19113 "".to_string(),
19114 "\thello world".to_string(),
19115 8,
19116 NonZeroU32::new(4).unwrap(),
19117 false,
19118 ),
19119 "hello\nworld"
19120 );
19121 assert_eq!(
19122 wrap_with_prefix(
19123 "// ".to_string(),
19124 "xx \nyy zz aa bb cc".to_string(),
19125 12,
19126 NonZeroU32::new(4).unwrap(),
19127 false,
19128 ),
19129 "// xx yy zz\n// aa bb cc"
19130 );
19131 assert_eq!(
19132 wrap_with_prefix(
19133 String::new(),
19134 "这是什么 \n 钢笔".to_string(),
19135 3,
19136 NonZeroU32::new(4).unwrap(),
19137 false,
19138 ),
19139 "这是什\n么 钢\n笔"
19140 );
19141}
19142
19143pub trait CollaborationHub {
19144 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19145 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19146 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19147}
19148
19149impl CollaborationHub for Entity<Project> {
19150 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19151 self.read(cx).collaborators()
19152 }
19153
19154 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19155 self.read(cx).user_store().read(cx).participant_indices()
19156 }
19157
19158 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19159 let this = self.read(cx);
19160 let user_ids = this.collaborators().values().map(|c| c.user_id);
19161 this.user_store().read_with(cx, |user_store, cx| {
19162 user_store.participant_names(user_ids, cx)
19163 })
19164 }
19165}
19166
19167pub trait SemanticsProvider {
19168 fn hover(
19169 &self,
19170 buffer: &Entity<Buffer>,
19171 position: text::Anchor,
19172 cx: &mut App,
19173 ) -> Option<Task<Vec<project::Hover>>>;
19174
19175 fn inline_values(
19176 &self,
19177 buffer_handle: Entity<Buffer>,
19178 range: Range<text::Anchor>,
19179 cx: &mut App,
19180 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19181
19182 fn inlay_hints(
19183 &self,
19184 buffer_handle: Entity<Buffer>,
19185 range: Range<text::Anchor>,
19186 cx: &mut App,
19187 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19188
19189 fn resolve_inlay_hint(
19190 &self,
19191 hint: InlayHint,
19192 buffer_handle: Entity<Buffer>,
19193 server_id: LanguageServerId,
19194 cx: &mut App,
19195 ) -> Option<Task<anyhow::Result<InlayHint>>>;
19196
19197 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19198
19199 fn document_highlights(
19200 &self,
19201 buffer: &Entity<Buffer>,
19202 position: text::Anchor,
19203 cx: &mut App,
19204 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19205
19206 fn definitions(
19207 &self,
19208 buffer: &Entity<Buffer>,
19209 position: text::Anchor,
19210 kind: GotoDefinitionKind,
19211 cx: &mut App,
19212 ) -> Option<Task<Result<Vec<LocationLink>>>>;
19213
19214 fn range_for_rename(
19215 &self,
19216 buffer: &Entity<Buffer>,
19217 position: text::Anchor,
19218 cx: &mut App,
19219 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19220
19221 fn perform_rename(
19222 &self,
19223 buffer: &Entity<Buffer>,
19224 position: text::Anchor,
19225 new_name: String,
19226 cx: &mut App,
19227 ) -> Option<Task<Result<ProjectTransaction>>>;
19228}
19229
19230pub trait CompletionProvider {
19231 fn completions(
19232 &self,
19233 excerpt_id: ExcerptId,
19234 buffer: &Entity<Buffer>,
19235 buffer_position: text::Anchor,
19236 trigger: CompletionContext,
19237 window: &mut Window,
19238 cx: &mut Context<Editor>,
19239 ) -> Task<Result<Option<Vec<Completion>>>>;
19240
19241 fn resolve_completions(
19242 &self,
19243 buffer: Entity<Buffer>,
19244 completion_indices: Vec<usize>,
19245 completions: Rc<RefCell<Box<[Completion]>>>,
19246 cx: &mut Context<Editor>,
19247 ) -> Task<Result<bool>>;
19248
19249 fn apply_additional_edits_for_completion(
19250 &self,
19251 _buffer: Entity<Buffer>,
19252 _completions: Rc<RefCell<Box<[Completion]>>>,
19253 _completion_index: usize,
19254 _push_to_history: bool,
19255 _cx: &mut Context<Editor>,
19256 ) -> Task<Result<Option<language::Transaction>>> {
19257 Task::ready(Ok(None))
19258 }
19259
19260 fn is_completion_trigger(
19261 &self,
19262 buffer: &Entity<Buffer>,
19263 position: language::Anchor,
19264 text: &str,
19265 trigger_in_words: bool,
19266 cx: &mut Context<Editor>,
19267 ) -> bool;
19268
19269 fn sort_completions(&self) -> bool {
19270 true
19271 }
19272
19273 fn filter_completions(&self) -> bool {
19274 true
19275 }
19276}
19277
19278pub trait CodeActionProvider {
19279 fn id(&self) -> Arc<str>;
19280
19281 fn code_actions(
19282 &self,
19283 buffer: &Entity<Buffer>,
19284 range: Range<text::Anchor>,
19285 window: &mut Window,
19286 cx: &mut App,
19287 ) -> Task<Result<Vec<CodeAction>>>;
19288
19289 fn apply_code_action(
19290 &self,
19291 buffer_handle: Entity<Buffer>,
19292 action: CodeAction,
19293 excerpt_id: ExcerptId,
19294 push_to_history: bool,
19295 window: &mut Window,
19296 cx: &mut App,
19297 ) -> Task<Result<ProjectTransaction>>;
19298}
19299
19300impl CodeActionProvider for Entity<Project> {
19301 fn id(&self) -> Arc<str> {
19302 "project".into()
19303 }
19304
19305 fn code_actions(
19306 &self,
19307 buffer: &Entity<Buffer>,
19308 range: Range<text::Anchor>,
19309 _window: &mut Window,
19310 cx: &mut App,
19311 ) -> Task<Result<Vec<CodeAction>>> {
19312 self.update(cx, |project, cx| {
19313 let code_lens = project.code_lens(buffer, range.clone(), cx);
19314 let code_actions = project.code_actions(buffer, range, None, cx);
19315 cx.background_spawn(async move {
19316 let (code_lens, code_actions) = join(code_lens, code_actions).await;
19317 Ok(code_lens
19318 .context("code lens fetch")?
19319 .into_iter()
19320 .chain(code_actions.context("code action fetch")?)
19321 .collect())
19322 })
19323 })
19324 }
19325
19326 fn apply_code_action(
19327 &self,
19328 buffer_handle: Entity<Buffer>,
19329 action: CodeAction,
19330 _excerpt_id: ExcerptId,
19331 push_to_history: bool,
19332 _window: &mut Window,
19333 cx: &mut App,
19334 ) -> Task<Result<ProjectTransaction>> {
19335 self.update(cx, |project, cx| {
19336 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19337 })
19338 }
19339}
19340
19341fn snippet_completions(
19342 project: &Project,
19343 buffer: &Entity<Buffer>,
19344 buffer_position: text::Anchor,
19345 cx: &mut App,
19346) -> Task<Result<Vec<Completion>>> {
19347 let languages = buffer.read(cx).languages_at(buffer_position);
19348 let snippet_store = project.snippets().read(cx);
19349
19350 let scopes: Vec<_> = languages
19351 .iter()
19352 .filter_map(|language| {
19353 let language_name = language.lsp_id();
19354 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19355
19356 if snippets.is_empty() {
19357 None
19358 } else {
19359 Some((language.default_scope(), snippets))
19360 }
19361 })
19362 .collect();
19363
19364 if scopes.is_empty() {
19365 return Task::ready(Ok(vec![]));
19366 }
19367
19368 let snapshot = buffer.read(cx).text_snapshot();
19369 let chars: String = snapshot
19370 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19371 .collect();
19372 let executor = cx.background_executor().clone();
19373
19374 cx.background_spawn(async move {
19375 let mut all_results: Vec<Completion> = Vec::new();
19376 for (scope, snippets) in scopes.into_iter() {
19377 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19378 let mut last_word = chars
19379 .chars()
19380 .take_while(|c| classifier.is_word(*c))
19381 .collect::<String>();
19382 last_word = last_word.chars().rev().collect();
19383
19384 if last_word.is_empty() {
19385 return Ok(vec![]);
19386 }
19387
19388 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19389 let to_lsp = |point: &text::Anchor| {
19390 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19391 point_to_lsp(end)
19392 };
19393 let lsp_end = to_lsp(&buffer_position);
19394
19395 let candidates = snippets
19396 .iter()
19397 .enumerate()
19398 .flat_map(|(ix, snippet)| {
19399 snippet
19400 .prefix
19401 .iter()
19402 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19403 })
19404 .collect::<Vec<StringMatchCandidate>>();
19405
19406 let mut matches = fuzzy::match_strings(
19407 &candidates,
19408 &last_word,
19409 last_word.chars().any(|c| c.is_uppercase()),
19410 100,
19411 &Default::default(),
19412 executor.clone(),
19413 )
19414 .await;
19415
19416 // Remove all candidates where the query's start does not match the start of any word in the candidate
19417 if let Some(query_start) = last_word.chars().next() {
19418 matches.retain(|string_match| {
19419 split_words(&string_match.string).any(|word| {
19420 // Check that the first codepoint of the word as lowercase matches the first
19421 // codepoint of the query as lowercase
19422 word.chars()
19423 .flat_map(|codepoint| codepoint.to_lowercase())
19424 .zip(query_start.to_lowercase())
19425 .all(|(word_cp, query_cp)| word_cp == query_cp)
19426 })
19427 });
19428 }
19429
19430 let matched_strings = matches
19431 .into_iter()
19432 .map(|m| m.string)
19433 .collect::<HashSet<_>>();
19434
19435 let mut result: Vec<Completion> = snippets
19436 .iter()
19437 .filter_map(|snippet| {
19438 let matching_prefix = snippet
19439 .prefix
19440 .iter()
19441 .find(|prefix| matched_strings.contains(*prefix))?;
19442 let start = as_offset - last_word.len();
19443 let start = snapshot.anchor_before(start);
19444 let range = start..buffer_position;
19445 let lsp_start = to_lsp(&start);
19446 let lsp_range = lsp::Range {
19447 start: lsp_start,
19448 end: lsp_end,
19449 };
19450 Some(Completion {
19451 replace_range: range,
19452 new_text: snippet.body.clone(),
19453 source: CompletionSource::Lsp {
19454 insert_range: None,
19455 server_id: LanguageServerId(usize::MAX),
19456 resolved: true,
19457 lsp_completion: Box::new(lsp::CompletionItem {
19458 label: snippet.prefix.first().unwrap().clone(),
19459 kind: Some(CompletionItemKind::SNIPPET),
19460 label_details: snippet.description.as_ref().map(|description| {
19461 lsp::CompletionItemLabelDetails {
19462 detail: Some(description.clone()),
19463 description: None,
19464 }
19465 }),
19466 insert_text_format: Some(InsertTextFormat::SNIPPET),
19467 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19468 lsp::InsertReplaceEdit {
19469 new_text: snippet.body.clone(),
19470 insert: lsp_range,
19471 replace: lsp_range,
19472 },
19473 )),
19474 filter_text: Some(snippet.body.clone()),
19475 sort_text: Some(char::MAX.to_string()),
19476 ..lsp::CompletionItem::default()
19477 }),
19478 lsp_defaults: None,
19479 },
19480 label: CodeLabel {
19481 text: matching_prefix.clone(),
19482 runs: Vec::new(),
19483 filter_range: 0..matching_prefix.len(),
19484 },
19485 icon_path: None,
19486 documentation: snippet.description.clone().map(|description| {
19487 CompletionDocumentation::SingleLine(description.into())
19488 }),
19489 insert_text_mode: None,
19490 confirm: None,
19491 })
19492 })
19493 .collect();
19494
19495 all_results.append(&mut result);
19496 }
19497
19498 Ok(all_results)
19499 })
19500}
19501
19502impl CompletionProvider for Entity<Project> {
19503 fn completions(
19504 &self,
19505 _excerpt_id: ExcerptId,
19506 buffer: &Entity<Buffer>,
19507 buffer_position: text::Anchor,
19508 options: CompletionContext,
19509 _window: &mut Window,
19510 cx: &mut Context<Editor>,
19511 ) -> Task<Result<Option<Vec<Completion>>>> {
19512 self.update(cx, |project, cx| {
19513 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19514 let project_completions = project.completions(buffer, buffer_position, options, cx);
19515 cx.background_spawn(async move {
19516 let snippets_completions = snippets.await?;
19517 match project_completions.await? {
19518 Some(mut completions) => {
19519 completions.extend(snippets_completions);
19520 Ok(Some(completions))
19521 }
19522 None => {
19523 if snippets_completions.is_empty() {
19524 Ok(None)
19525 } else {
19526 Ok(Some(snippets_completions))
19527 }
19528 }
19529 }
19530 })
19531 })
19532 }
19533
19534 fn resolve_completions(
19535 &self,
19536 buffer: Entity<Buffer>,
19537 completion_indices: Vec<usize>,
19538 completions: Rc<RefCell<Box<[Completion]>>>,
19539 cx: &mut Context<Editor>,
19540 ) -> Task<Result<bool>> {
19541 self.update(cx, |project, cx| {
19542 project.lsp_store().update(cx, |lsp_store, cx| {
19543 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19544 })
19545 })
19546 }
19547
19548 fn apply_additional_edits_for_completion(
19549 &self,
19550 buffer: Entity<Buffer>,
19551 completions: Rc<RefCell<Box<[Completion]>>>,
19552 completion_index: usize,
19553 push_to_history: bool,
19554 cx: &mut Context<Editor>,
19555 ) -> Task<Result<Option<language::Transaction>>> {
19556 self.update(cx, |project, cx| {
19557 project.lsp_store().update(cx, |lsp_store, cx| {
19558 lsp_store.apply_additional_edits_for_completion(
19559 buffer,
19560 completions,
19561 completion_index,
19562 push_to_history,
19563 cx,
19564 )
19565 })
19566 })
19567 }
19568
19569 fn is_completion_trigger(
19570 &self,
19571 buffer: &Entity<Buffer>,
19572 position: language::Anchor,
19573 text: &str,
19574 trigger_in_words: bool,
19575 cx: &mut Context<Editor>,
19576 ) -> bool {
19577 let mut chars = text.chars();
19578 let char = if let Some(char) = chars.next() {
19579 char
19580 } else {
19581 return false;
19582 };
19583 if chars.next().is_some() {
19584 return false;
19585 }
19586
19587 let buffer = buffer.read(cx);
19588 let snapshot = buffer.snapshot();
19589 if !snapshot.settings_at(position, cx).show_completions_on_input {
19590 return false;
19591 }
19592 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19593 if trigger_in_words && classifier.is_word(char) {
19594 return true;
19595 }
19596
19597 buffer.completion_triggers().contains(text)
19598 }
19599}
19600
19601impl SemanticsProvider for Entity<Project> {
19602 fn hover(
19603 &self,
19604 buffer: &Entity<Buffer>,
19605 position: text::Anchor,
19606 cx: &mut App,
19607 ) -> Option<Task<Vec<project::Hover>>> {
19608 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19609 }
19610
19611 fn document_highlights(
19612 &self,
19613 buffer: &Entity<Buffer>,
19614 position: text::Anchor,
19615 cx: &mut App,
19616 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19617 Some(self.update(cx, |project, cx| {
19618 project.document_highlights(buffer, position, cx)
19619 }))
19620 }
19621
19622 fn definitions(
19623 &self,
19624 buffer: &Entity<Buffer>,
19625 position: text::Anchor,
19626 kind: GotoDefinitionKind,
19627 cx: &mut App,
19628 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19629 Some(self.update(cx, |project, cx| match kind {
19630 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19631 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19632 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19633 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19634 }))
19635 }
19636
19637 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19638 // TODO: make this work for remote projects
19639 self.update(cx, |project, cx| {
19640 if project
19641 .active_debug_session(cx)
19642 .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19643 {
19644 return true;
19645 }
19646
19647 buffer.update(cx, |buffer, cx| {
19648 project.any_language_server_supports_inlay_hints(buffer, cx)
19649 })
19650 })
19651 }
19652
19653 fn inline_values(
19654 &self,
19655 buffer_handle: Entity<Buffer>,
19656 range: Range<text::Anchor>,
19657 cx: &mut App,
19658 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19659 self.update(cx, |project, cx| {
19660 let (session, active_stack_frame) = project.active_debug_session(cx)?;
19661
19662 Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19663 })
19664 }
19665
19666 fn inlay_hints(
19667 &self,
19668 buffer_handle: Entity<Buffer>,
19669 range: Range<text::Anchor>,
19670 cx: &mut App,
19671 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19672 Some(self.update(cx, |project, cx| {
19673 project.inlay_hints(buffer_handle, range, cx)
19674 }))
19675 }
19676
19677 fn resolve_inlay_hint(
19678 &self,
19679 hint: InlayHint,
19680 buffer_handle: Entity<Buffer>,
19681 server_id: LanguageServerId,
19682 cx: &mut App,
19683 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19684 Some(self.update(cx, |project, cx| {
19685 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19686 }))
19687 }
19688
19689 fn range_for_rename(
19690 &self,
19691 buffer: &Entity<Buffer>,
19692 position: text::Anchor,
19693 cx: &mut App,
19694 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19695 Some(self.update(cx, |project, cx| {
19696 let buffer = buffer.clone();
19697 let task = project.prepare_rename(buffer.clone(), position, cx);
19698 cx.spawn(async move |_, cx| {
19699 Ok(match task.await? {
19700 PrepareRenameResponse::Success(range) => Some(range),
19701 PrepareRenameResponse::InvalidPosition => None,
19702 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19703 // Fallback on using TreeSitter info to determine identifier range
19704 buffer.update(cx, |buffer, _| {
19705 let snapshot = buffer.snapshot();
19706 let (range, kind) = snapshot.surrounding_word(position);
19707 if kind != Some(CharKind::Word) {
19708 return None;
19709 }
19710 Some(
19711 snapshot.anchor_before(range.start)
19712 ..snapshot.anchor_after(range.end),
19713 )
19714 })?
19715 }
19716 })
19717 })
19718 }))
19719 }
19720
19721 fn perform_rename(
19722 &self,
19723 buffer: &Entity<Buffer>,
19724 position: text::Anchor,
19725 new_name: String,
19726 cx: &mut App,
19727 ) -> Option<Task<Result<ProjectTransaction>>> {
19728 Some(self.update(cx, |project, cx| {
19729 project.perform_rename(buffer.clone(), position, new_name, cx)
19730 }))
19731 }
19732}
19733
19734fn inlay_hint_settings(
19735 location: Anchor,
19736 snapshot: &MultiBufferSnapshot,
19737 cx: &mut Context<Editor>,
19738) -> InlayHintSettings {
19739 let file = snapshot.file_at(location);
19740 let language = snapshot.language_at(location).map(|l| l.name());
19741 language_settings(language, file, cx).inlay_hints
19742}
19743
19744fn consume_contiguous_rows(
19745 contiguous_row_selections: &mut Vec<Selection<Point>>,
19746 selection: &Selection<Point>,
19747 display_map: &DisplaySnapshot,
19748 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19749) -> (MultiBufferRow, MultiBufferRow) {
19750 contiguous_row_selections.push(selection.clone());
19751 let start_row = MultiBufferRow(selection.start.row);
19752 let mut end_row = ending_row(selection, display_map);
19753
19754 while let Some(next_selection) = selections.peek() {
19755 if next_selection.start.row <= end_row.0 {
19756 end_row = ending_row(next_selection, display_map);
19757 contiguous_row_selections.push(selections.next().unwrap().clone());
19758 } else {
19759 break;
19760 }
19761 }
19762 (start_row, end_row)
19763}
19764
19765fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19766 if next_selection.end.column > 0 || next_selection.is_empty() {
19767 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19768 } else {
19769 MultiBufferRow(next_selection.end.row)
19770 }
19771}
19772
19773impl EditorSnapshot {
19774 pub fn remote_selections_in_range<'a>(
19775 &'a self,
19776 range: &'a Range<Anchor>,
19777 collaboration_hub: &dyn CollaborationHub,
19778 cx: &'a App,
19779 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19780 let participant_names = collaboration_hub.user_names(cx);
19781 let participant_indices = collaboration_hub.user_participant_indices(cx);
19782 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19783 let collaborators_by_replica_id = collaborators_by_peer_id
19784 .iter()
19785 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19786 .collect::<HashMap<_, _>>();
19787 self.buffer_snapshot
19788 .selections_in_range(range, false)
19789 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19790 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19791 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19792 let user_name = participant_names.get(&collaborator.user_id).cloned();
19793 Some(RemoteSelection {
19794 replica_id,
19795 selection,
19796 cursor_shape,
19797 line_mode,
19798 participant_index,
19799 peer_id: collaborator.peer_id,
19800 user_name,
19801 })
19802 })
19803 }
19804
19805 pub fn hunks_for_ranges(
19806 &self,
19807 ranges: impl IntoIterator<Item = Range<Point>>,
19808 ) -> Vec<MultiBufferDiffHunk> {
19809 let mut hunks = Vec::new();
19810 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19811 HashMap::default();
19812 for query_range in ranges {
19813 let query_rows =
19814 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19815 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19816 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19817 ) {
19818 // Include deleted hunks that are adjacent to the query range, because
19819 // otherwise they would be missed.
19820 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19821 if hunk.status().is_deleted() {
19822 intersects_range |= hunk.row_range.start == query_rows.end;
19823 intersects_range |= hunk.row_range.end == query_rows.start;
19824 }
19825 if intersects_range {
19826 if !processed_buffer_rows
19827 .entry(hunk.buffer_id)
19828 .or_default()
19829 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19830 {
19831 continue;
19832 }
19833 hunks.push(hunk);
19834 }
19835 }
19836 }
19837
19838 hunks
19839 }
19840
19841 fn display_diff_hunks_for_rows<'a>(
19842 &'a self,
19843 display_rows: Range<DisplayRow>,
19844 folded_buffers: &'a HashSet<BufferId>,
19845 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19846 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19847 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19848
19849 self.buffer_snapshot
19850 .diff_hunks_in_range(buffer_start..buffer_end)
19851 .filter_map(|hunk| {
19852 if folded_buffers.contains(&hunk.buffer_id) {
19853 return None;
19854 }
19855
19856 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19857 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19858
19859 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19860 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19861
19862 let display_hunk = if hunk_display_start.column() != 0 {
19863 DisplayDiffHunk::Folded {
19864 display_row: hunk_display_start.row(),
19865 }
19866 } else {
19867 let mut end_row = hunk_display_end.row();
19868 if hunk_display_end.column() > 0 {
19869 end_row.0 += 1;
19870 }
19871 let is_created_file = hunk.is_created_file();
19872 DisplayDiffHunk::Unfolded {
19873 status: hunk.status(),
19874 diff_base_byte_range: hunk.diff_base_byte_range,
19875 display_row_range: hunk_display_start.row()..end_row,
19876 multi_buffer_range: Anchor::range_in_buffer(
19877 hunk.excerpt_id,
19878 hunk.buffer_id,
19879 hunk.buffer_range,
19880 ),
19881 is_created_file,
19882 }
19883 };
19884
19885 Some(display_hunk)
19886 })
19887 }
19888
19889 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19890 self.display_snapshot.buffer_snapshot.language_at(position)
19891 }
19892
19893 pub fn is_focused(&self) -> bool {
19894 self.is_focused
19895 }
19896
19897 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19898 self.placeholder_text.as_ref()
19899 }
19900
19901 pub fn scroll_position(&self) -> gpui::Point<f32> {
19902 self.scroll_anchor.scroll_position(&self.display_snapshot)
19903 }
19904
19905 fn gutter_dimensions(
19906 &self,
19907 font_id: FontId,
19908 font_size: Pixels,
19909 max_line_number_width: Pixels,
19910 cx: &App,
19911 ) -> Option<GutterDimensions> {
19912 if !self.show_gutter {
19913 return None;
19914 }
19915
19916 let descent = cx.text_system().descent(font_id, font_size);
19917 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19918 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19919
19920 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19921 matches!(
19922 ProjectSettings::get_global(cx).git.git_gutter,
19923 Some(GitGutterSetting::TrackedFiles)
19924 )
19925 });
19926 let gutter_settings = EditorSettings::get_global(cx).gutter;
19927 let show_line_numbers = self
19928 .show_line_numbers
19929 .unwrap_or(gutter_settings.line_numbers);
19930 let line_gutter_width = if show_line_numbers {
19931 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19932 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19933 max_line_number_width.max(min_width_for_number_on_gutter)
19934 } else {
19935 0.0.into()
19936 };
19937
19938 let show_code_actions = self
19939 .show_code_actions
19940 .unwrap_or(gutter_settings.code_actions);
19941
19942 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19943 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19944
19945 let git_blame_entries_width =
19946 self.git_blame_gutter_max_author_length
19947 .map(|max_author_length| {
19948 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19949 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19950
19951 /// The number of characters to dedicate to gaps and margins.
19952 const SPACING_WIDTH: usize = 4;
19953
19954 let max_char_count = max_author_length.min(renderer.max_author_length())
19955 + ::git::SHORT_SHA_LENGTH
19956 + MAX_RELATIVE_TIMESTAMP.len()
19957 + SPACING_WIDTH;
19958
19959 em_advance * max_char_count
19960 });
19961
19962 let is_singleton = self.buffer_snapshot.is_singleton();
19963
19964 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19965 left_padding += if !is_singleton {
19966 em_width * 4.0
19967 } else if show_code_actions || show_runnables || show_breakpoints {
19968 em_width * 3.0
19969 } else if show_git_gutter && show_line_numbers {
19970 em_width * 2.0
19971 } else if show_git_gutter || show_line_numbers {
19972 em_width
19973 } else {
19974 px(0.)
19975 };
19976
19977 let shows_folds = is_singleton && gutter_settings.folds;
19978
19979 let right_padding = if shows_folds && show_line_numbers {
19980 em_width * 4.0
19981 } else if shows_folds || (!is_singleton && show_line_numbers) {
19982 em_width * 3.0
19983 } else if show_line_numbers {
19984 em_width
19985 } else {
19986 px(0.)
19987 };
19988
19989 Some(GutterDimensions {
19990 left_padding,
19991 right_padding,
19992 width: line_gutter_width + left_padding + right_padding,
19993 margin: -descent,
19994 git_blame_entries_width,
19995 })
19996 }
19997
19998 pub fn render_crease_toggle(
19999 &self,
20000 buffer_row: MultiBufferRow,
20001 row_contains_cursor: bool,
20002 editor: Entity<Editor>,
20003 window: &mut Window,
20004 cx: &mut App,
20005 ) -> Option<AnyElement> {
20006 let folded = self.is_line_folded(buffer_row);
20007 let mut is_foldable = false;
20008
20009 if let Some(crease) = self
20010 .crease_snapshot
20011 .query_row(buffer_row, &self.buffer_snapshot)
20012 {
20013 is_foldable = true;
20014 match crease {
20015 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20016 if let Some(render_toggle) = render_toggle {
20017 let toggle_callback =
20018 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20019 if folded {
20020 editor.update(cx, |editor, cx| {
20021 editor.fold_at(buffer_row, window, cx)
20022 });
20023 } else {
20024 editor.update(cx, |editor, cx| {
20025 editor.unfold_at(buffer_row, window, cx)
20026 });
20027 }
20028 });
20029 return Some((render_toggle)(
20030 buffer_row,
20031 folded,
20032 toggle_callback,
20033 window,
20034 cx,
20035 ));
20036 }
20037 }
20038 }
20039 }
20040
20041 is_foldable |= self.starts_indent(buffer_row);
20042
20043 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20044 Some(
20045 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20046 .toggle_state(folded)
20047 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20048 if folded {
20049 this.unfold_at(buffer_row, window, cx);
20050 } else {
20051 this.fold_at(buffer_row, window, cx);
20052 }
20053 }))
20054 .into_any_element(),
20055 )
20056 } else {
20057 None
20058 }
20059 }
20060
20061 pub fn render_crease_trailer(
20062 &self,
20063 buffer_row: MultiBufferRow,
20064 window: &mut Window,
20065 cx: &mut App,
20066 ) -> Option<AnyElement> {
20067 let folded = self.is_line_folded(buffer_row);
20068 if let Crease::Inline { render_trailer, .. } = self
20069 .crease_snapshot
20070 .query_row(buffer_row, &self.buffer_snapshot)?
20071 {
20072 let render_trailer = render_trailer.as_ref()?;
20073 Some(render_trailer(buffer_row, folded, window, cx))
20074 } else {
20075 None
20076 }
20077 }
20078}
20079
20080impl Deref for EditorSnapshot {
20081 type Target = DisplaySnapshot;
20082
20083 fn deref(&self) -> &Self::Target {
20084 &self.display_snapshot
20085 }
20086}
20087
20088#[derive(Clone, Debug, PartialEq, Eq)]
20089pub enum EditorEvent {
20090 InputIgnored {
20091 text: Arc<str>,
20092 },
20093 InputHandled {
20094 utf16_range_to_replace: Option<Range<isize>>,
20095 text: Arc<str>,
20096 },
20097 ExcerptsAdded {
20098 buffer: Entity<Buffer>,
20099 predecessor: ExcerptId,
20100 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20101 },
20102 ExcerptsRemoved {
20103 ids: Vec<ExcerptId>,
20104 removed_buffer_ids: Vec<BufferId>,
20105 },
20106 BufferFoldToggled {
20107 ids: Vec<ExcerptId>,
20108 folded: bool,
20109 },
20110 ExcerptsEdited {
20111 ids: Vec<ExcerptId>,
20112 },
20113 ExcerptsExpanded {
20114 ids: Vec<ExcerptId>,
20115 },
20116 BufferEdited,
20117 Edited {
20118 transaction_id: clock::Lamport,
20119 },
20120 Reparsed(BufferId),
20121 Focused,
20122 FocusedIn,
20123 Blurred,
20124 DirtyChanged,
20125 Saved,
20126 TitleChanged,
20127 DiffBaseChanged,
20128 SelectionsChanged {
20129 local: bool,
20130 },
20131 ScrollPositionChanged {
20132 local: bool,
20133 autoscroll: bool,
20134 },
20135 Closed,
20136 TransactionUndone {
20137 transaction_id: clock::Lamport,
20138 },
20139 TransactionBegun {
20140 transaction_id: clock::Lamport,
20141 },
20142 Reloaded,
20143 CursorShapeChanged,
20144 PushedToNavHistory {
20145 anchor: Anchor,
20146 is_deactivate: bool,
20147 },
20148}
20149
20150impl EventEmitter<EditorEvent> for Editor {}
20151
20152impl Focusable for Editor {
20153 fn focus_handle(&self, _cx: &App) -> FocusHandle {
20154 self.focus_handle.clone()
20155 }
20156}
20157
20158impl Render for Editor {
20159 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20160 let settings = ThemeSettings::get_global(cx);
20161
20162 let mut text_style = match self.mode {
20163 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20164 color: cx.theme().colors().editor_foreground,
20165 font_family: settings.ui_font.family.clone(),
20166 font_features: settings.ui_font.features.clone(),
20167 font_fallbacks: settings.ui_font.fallbacks.clone(),
20168 font_size: rems(0.875).into(),
20169 font_weight: settings.ui_font.weight,
20170 line_height: relative(settings.buffer_line_height.value()),
20171 ..Default::default()
20172 },
20173 EditorMode::Full { .. } => TextStyle {
20174 color: cx.theme().colors().editor_foreground,
20175 font_family: settings.buffer_font.family.clone(),
20176 font_features: settings.buffer_font.features.clone(),
20177 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20178 font_size: settings.buffer_font_size(cx).into(),
20179 font_weight: settings.buffer_font.weight,
20180 line_height: relative(settings.buffer_line_height.value()),
20181 ..Default::default()
20182 },
20183 };
20184 if let Some(text_style_refinement) = &self.text_style_refinement {
20185 text_style.refine(text_style_refinement)
20186 }
20187
20188 let background = match self.mode {
20189 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20190 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20191 EditorMode::Full { .. } => cx.theme().colors().editor_background,
20192 };
20193
20194 EditorElement::new(
20195 &cx.entity(),
20196 EditorStyle {
20197 background,
20198 local_player: cx.theme().players().local(),
20199 text: text_style,
20200 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20201 syntax: cx.theme().syntax().clone(),
20202 status: cx.theme().status().clone(),
20203 inlay_hints_style: make_inlay_hints_style(cx),
20204 inline_completion_styles: make_suggestion_styles(cx),
20205 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20206 },
20207 )
20208 }
20209}
20210
20211impl EntityInputHandler for Editor {
20212 fn text_for_range(
20213 &mut self,
20214 range_utf16: Range<usize>,
20215 adjusted_range: &mut Option<Range<usize>>,
20216 _: &mut Window,
20217 cx: &mut Context<Self>,
20218 ) -> Option<String> {
20219 let snapshot = self.buffer.read(cx).read(cx);
20220 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20221 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20222 if (start.0..end.0) != range_utf16 {
20223 adjusted_range.replace(start.0..end.0);
20224 }
20225 Some(snapshot.text_for_range(start..end).collect())
20226 }
20227
20228 fn selected_text_range(
20229 &mut self,
20230 ignore_disabled_input: bool,
20231 _: &mut Window,
20232 cx: &mut Context<Self>,
20233 ) -> Option<UTF16Selection> {
20234 // Prevent the IME menu from appearing when holding down an alphabetic key
20235 // while input is disabled.
20236 if !ignore_disabled_input && !self.input_enabled {
20237 return None;
20238 }
20239
20240 let selection = self.selections.newest::<OffsetUtf16>(cx);
20241 let range = selection.range();
20242
20243 Some(UTF16Selection {
20244 range: range.start.0..range.end.0,
20245 reversed: selection.reversed,
20246 })
20247 }
20248
20249 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20250 let snapshot = self.buffer.read(cx).read(cx);
20251 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20252 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20253 }
20254
20255 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20256 self.clear_highlights::<InputComposition>(cx);
20257 self.ime_transaction.take();
20258 }
20259
20260 fn replace_text_in_range(
20261 &mut self,
20262 range_utf16: Option<Range<usize>>,
20263 text: &str,
20264 window: &mut Window,
20265 cx: &mut Context<Self>,
20266 ) {
20267 if !self.input_enabled {
20268 cx.emit(EditorEvent::InputIgnored { text: text.into() });
20269 return;
20270 }
20271
20272 self.transact(window, cx, |this, window, cx| {
20273 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20274 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20275 Some(this.selection_replacement_ranges(range_utf16, cx))
20276 } else {
20277 this.marked_text_ranges(cx)
20278 };
20279
20280 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20281 let newest_selection_id = this.selections.newest_anchor().id;
20282 this.selections
20283 .all::<OffsetUtf16>(cx)
20284 .iter()
20285 .zip(ranges_to_replace.iter())
20286 .find_map(|(selection, range)| {
20287 if selection.id == newest_selection_id {
20288 Some(
20289 (range.start.0 as isize - selection.head().0 as isize)
20290 ..(range.end.0 as isize - selection.head().0 as isize),
20291 )
20292 } else {
20293 None
20294 }
20295 })
20296 });
20297
20298 cx.emit(EditorEvent::InputHandled {
20299 utf16_range_to_replace: range_to_replace,
20300 text: text.into(),
20301 });
20302
20303 if let Some(new_selected_ranges) = new_selected_ranges {
20304 this.change_selections(None, window, cx, |selections| {
20305 selections.select_ranges(new_selected_ranges)
20306 });
20307 this.backspace(&Default::default(), window, cx);
20308 }
20309
20310 this.handle_input(text, window, cx);
20311 });
20312
20313 if let Some(transaction) = self.ime_transaction {
20314 self.buffer.update(cx, |buffer, cx| {
20315 buffer.group_until_transaction(transaction, cx);
20316 });
20317 }
20318
20319 self.unmark_text(window, cx);
20320 }
20321
20322 fn replace_and_mark_text_in_range(
20323 &mut self,
20324 range_utf16: Option<Range<usize>>,
20325 text: &str,
20326 new_selected_range_utf16: Option<Range<usize>>,
20327 window: &mut Window,
20328 cx: &mut Context<Self>,
20329 ) {
20330 if !self.input_enabled {
20331 return;
20332 }
20333
20334 let transaction = self.transact(window, cx, |this, window, cx| {
20335 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20336 let snapshot = this.buffer.read(cx).read(cx);
20337 if let Some(relative_range_utf16) = range_utf16.as_ref() {
20338 for marked_range in &mut marked_ranges {
20339 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20340 marked_range.start.0 += relative_range_utf16.start;
20341 marked_range.start =
20342 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20343 marked_range.end =
20344 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20345 }
20346 }
20347 Some(marked_ranges)
20348 } else if let Some(range_utf16) = range_utf16 {
20349 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20350 Some(this.selection_replacement_ranges(range_utf16, cx))
20351 } else {
20352 None
20353 };
20354
20355 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20356 let newest_selection_id = this.selections.newest_anchor().id;
20357 this.selections
20358 .all::<OffsetUtf16>(cx)
20359 .iter()
20360 .zip(ranges_to_replace.iter())
20361 .find_map(|(selection, range)| {
20362 if selection.id == newest_selection_id {
20363 Some(
20364 (range.start.0 as isize - selection.head().0 as isize)
20365 ..(range.end.0 as isize - selection.head().0 as isize),
20366 )
20367 } else {
20368 None
20369 }
20370 })
20371 });
20372
20373 cx.emit(EditorEvent::InputHandled {
20374 utf16_range_to_replace: range_to_replace,
20375 text: text.into(),
20376 });
20377
20378 if let Some(ranges) = ranges_to_replace {
20379 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20380 }
20381
20382 let marked_ranges = {
20383 let snapshot = this.buffer.read(cx).read(cx);
20384 this.selections
20385 .disjoint_anchors()
20386 .iter()
20387 .map(|selection| {
20388 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20389 })
20390 .collect::<Vec<_>>()
20391 };
20392
20393 if text.is_empty() {
20394 this.unmark_text(window, cx);
20395 } else {
20396 this.highlight_text::<InputComposition>(
20397 marked_ranges.clone(),
20398 HighlightStyle {
20399 underline: Some(UnderlineStyle {
20400 thickness: px(1.),
20401 color: None,
20402 wavy: false,
20403 }),
20404 ..Default::default()
20405 },
20406 cx,
20407 );
20408 }
20409
20410 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20411 let use_autoclose = this.use_autoclose;
20412 let use_auto_surround = this.use_auto_surround;
20413 this.set_use_autoclose(false);
20414 this.set_use_auto_surround(false);
20415 this.handle_input(text, window, cx);
20416 this.set_use_autoclose(use_autoclose);
20417 this.set_use_auto_surround(use_auto_surround);
20418
20419 if let Some(new_selected_range) = new_selected_range_utf16 {
20420 let snapshot = this.buffer.read(cx).read(cx);
20421 let new_selected_ranges = marked_ranges
20422 .into_iter()
20423 .map(|marked_range| {
20424 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20425 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20426 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20427 snapshot.clip_offset_utf16(new_start, Bias::Left)
20428 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20429 })
20430 .collect::<Vec<_>>();
20431
20432 drop(snapshot);
20433 this.change_selections(None, window, cx, |selections| {
20434 selections.select_ranges(new_selected_ranges)
20435 });
20436 }
20437 });
20438
20439 self.ime_transaction = self.ime_transaction.or(transaction);
20440 if let Some(transaction) = self.ime_transaction {
20441 self.buffer.update(cx, |buffer, cx| {
20442 buffer.group_until_transaction(transaction, cx);
20443 });
20444 }
20445
20446 if self.text_highlights::<InputComposition>(cx).is_none() {
20447 self.ime_transaction.take();
20448 }
20449 }
20450
20451 fn bounds_for_range(
20452 &mut self,
20453 range_utf16: Range<usize>,
20454 element_bounds: gpui::Bounds<Pixels>,
20455 window: &mut Window,
20456 cx: &mut Context<Self>,
20457 ) -> Option<gpui::Bounds<Pixels>> {
20458 let text_layout_details = self.text_layout_details(window);
20459 let gpui::Size {
20460 width: em_width,
20461 height: line_height,
20462 } = self.character_size(window);
20463
20464 let snapshot = self.snapshot(window, cx);
20465 let scroll_position = snapshot.scroll_position();
20466 let scroll_left = scroll_position.x * em_width;
20467
20468 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20469 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20470 + self.gutter_dimensions.width
20471 + self.gutter_dimensions.margin;
20472 let y = line_height * (start.row().as_f32() - scroll_position.y);
20473
20474 Some(Bounds {
20475 origin: element_bounds.origin + point(x, y),
20476 size: size(em_width, line_height),
20477 })
20478 }
20479
20480 fn character_index_for_point(
20481 &mut self,
20482 point: gpui::Point<Pixels>,
20483 _window: &mut Window,
20484 _cx: &mut Context<Self>,
20485 ) -> Option<usize> {
20486 let position_map = self.last_position_map.as_ref()?;
20487 if !position_map.text_hitbox.contains(&point) {
20488 return None;
20489 }
20490 let display_point = position_map.point_for_position(point).previous_valid;
20491 let anchor = position_map
20492 .snapshot
20493 .display_point_to_anchor(display_point, Bias::Left);
20494 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20495 Some(utf16_offset.0)
20496 }
20497}
20498
20499trait SelectionExt {
20500 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20501 fn spanned_rows(
20502 &self,
20503 include_end_if_at_line_start: bool,
20504 map: &DisplaySnapshot,
20505 ) -> Range<MultiBufferRow>;
20506}
20507
20508impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20509 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20510 let start = self
20511 .start
20512 .to_point(&map.buffer_snapshot)
20513 .to_display_point(map);
20514 let end = self
20515 .end
20516 .to_point(&map.buffer_snapshot)
20517 .to_display_point(map);
20518 if self.reversed {
20519 end..start
20520 } else {
20521 start..end
20522 }
20523 }
20524
20525 fn spanned_rows(
20526 &self,
20527 include_end_if_at_line_start: bool,
20528 map: &DisplaySnapshot,
20529 ) -> Range<MultiBufferRow> {
20530 let start = self.start.to_point(&map.buffer_snapshot);
20531 let mut end = self.end.to_point(&map.buffer_snapshot);
20532 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20533 end.row -= 1;
20534 }
20535
20536 let buffer_start = map.prev_line_boundary(start).0;
20537 let buffer_end = map.next_line_boundary(end).0;
20538 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20539 }
20540}
20541
20542impl<T: InvalidationRegion> InvalidationStack<T> {
20543 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20544 where
20545 S: Clone + ToOffset,
20546 {
20547 while let Some(region) = self.last() {
20548 let all_selections_inside_invalidation_ranges =
20549 if selections.len() == region.ranges().len() {
20550 selections
20551 .iter()
20552 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20553 .all(|(selection, invalidation_range)| {
20554 let head = selection.head().to_offset(buffer);
20555 invalidation_range.start <= head && invalidation_range.end >= head
20556 })
20557 } else {
20558 false
20559 };
20560
20561 if all_selections_inside_invalidation_ranges {
20562 break;
20563 } else {
20564 self.pop();
20565 }
20566 }
20567 }
20568}
20569
20570impl<T> Default for InvalidationStack<T> {
20571 fn default() -> Self {
20572 Self(Default::default())
20573 }
20574}
20575
20576impl<T> Deref for InvalidationStack<T> {
20577 type Target = Vec<T>;
20578
20579 fn deref(&self) -> &Self::Target {
20580 &self.0
20581 }
20582}
20583
20584impl<T> DerefMut for InvalidationStack<T> {
20585 fn deref_mut(&mut self) -> &mut Self::Target {
20586 &mut self.0
20587 }
20588}
20589
20590impl InvalidationRegion for SnippetState {
20591 fn ranges(&self) -> &[Range<Anchor>] {
20592 &self.ranges[self.active_index]
20593 }
20594}
20595
20596fn inline_completion_edit_text(
20597 current_snapshot: &BufferSnapshot,
20598 edits: &[(Range<Anchor>, String)],
20599 edit_preview: &EditPreview,
20600 include_deletions: bool,
20601 cx: &App,
20602) -> HighlightedText {
20603 let edits = edits
20604 .iter()
20605 .map(|(anchor, text)| {
20606 (
20607 anchor.start.text_anchor..anchor.end.text_anchor,
20608 text.clone(),
20609 )
20610 })
20611 .collect::<Vec<_>>();
20612
20613 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20614}
20615
20616pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20617 match severity {
20618 DiagnosticSeverity::ERROR => colors.error,
20619 DiagnosticSeverity::WARNING => colors.warning,
20620 DiagnosticSeverity::INFORMATION => colors.info,
20621 DiagnosticSeverity::HINT => colors.info,
20622 _ => colors.ignored,
20623 }
20624}
20625
20626pub fn styled_runs_for_code_label<'a>(
20627 label: &'a CodeLabel,
20628 syntax_theme: &'a theme::SyntaxTheme,
20629) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20630 let fade_out = HighlightStyle {
20631 fade_out: Some(0.35),
20632 ..Default::default()
20633 };
20634
20635 let mut prev_end = label.filter_range.end;
20636 label
20637 .runs
20638 .iter()
20639 .enumerate()
20640 .flat_map(move |(ix, (range, highlight_id))| {
20641 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20642 style
20643 } else {
20644 return Default::default();
20645 };
20646 let mut muted_style = style;
20647 muted_style.highlight(fade_out);
20648
20649 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20650 if range.start >= label.filter_range.end {
20651 if range.start > prev_end {
20652 runs.push((prev_end..range.start, fade_out));
20653 }
20654 runs.push((range.clone(), muted_style));
20655 } else if range.end <= label.filter_range.end {
20656 runs.push((range.clone(), style));
20657 } else {
20658 runs.push((range.start..label.filter_range.end, style));
20659 runs.push((label.filter_range.end..range.end, muted_style));
20660 }
20661 prev_end = cmp::max(prev_end, range.end);
20662
20663 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20664 runs.push((prev_end..label.text.len(), fade_out));
20665 }
20666
20667 runs
20668 })
20669}
20670
20671pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20672 let mut prev_index = 0;
20673 let mut prev_codepoint: Option<char> = None;
20674 text.char_indices()
20675 .chain([(text.len(), '\0')])
20676 .filter_map(move |(index, codepoint)| {
20677 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20678 let is_boundary = index == text.len()
20679 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20680 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20681 if is_boundary {
20682 let chunk = &text[prev_index..index];
20683 prev_index = index;
20684 Some(chunk)
20685 } else {
20686 None
20687 }
20688 })
20689}
20690
20691pub trait RangeToAnchorExt: Sized {
20692 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20693
20694 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20695 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20696 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20697 }
20698}
20699
20700impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20701 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20702 let start_offset = self.start.to_offset(snapshot);
20703 let end_offset = self.end.to_offset(snapshot);
20704 if start_offset == end_offset {
20705 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20706 } else {
20707 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20708 }
20709 }
20710}
20711
20712pub trait RowExt {
20713 fn as_f32(&self) -> f32;
20714
20715 fn next_row(&self) -> Self;
20716
20717 fn previous_row(&self) -> Self;
20718
20719 fn minus(&self, other: Self) -> u32;
20720}
20721
20722impl RowExt for DisplayRow {
20723 fn as_f32(&self) -> f32 {
20724 self.0 as f32
20725 }
20726
20727 fn next_row(&self) -> Self {
20728 Self(self.0 + 1)
20729 }
20730
20731 fn previous_row(&self) -> Self {
20732 Self(self.0.saturating_sub(1))
20733 }
20734
20735 fn minus(&self, other: Self) -> u32 {
20736 self.0 - other.0
20737 }
20738}
20739
20740impl RowExt for MultiBufferRow {
20741 fn as_f32(&self) -> f32 {
20742 self.0 as f32
20743 }
20744
20745 fn next_row(&self) -> Self {
20746 Self(self.0 + 1)
20747 }
20748
20749 fn previous_row(&self) -> Self {
20750 Self(self.0.saturating_sub(1))
20751 }
20752
20753 fn minus(&self, other: Self) -> u32 {
20754 self.0 - other.0
20755 }
20756}
20757
20758trait RowRangeExt {
20759 type Row;
20760
20761 fn len(&self) -> usize;
20762
20763 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20764}
20765
20766impl RowRangeExt for Range<MultiBufferRow> {
20767 type Row = MultiBufferRow;
20768
20769 fn len(&self) -> usize {
20770 (self.end.0 - self.start.0) as usize
20771 }
20772
20773 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20774 (self.start.0..self.end.0).map(MultiBufferRow)
20775 }
20776}
20777
20778impl RowRangeExt for Range<DisplayRow> {
20779 type Row = DisplayRow;
20780
20781 fn len(&self) -> usize {
20782 (self.end.0 - self.start.0) as usize
20783 }
20784
20785 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20786 (self.start.0..self.end.0).map(DisplayRow)
20787 }
20788}
20789
20790/// If select range has more than one line, we
20791/// just point the cursor to range.start.
20792fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20793 if range.start.row == range.end.row {
20794 range
20795 } else {
20796 range.start..range.start
20797 }
20798}
20799pub struct KillRing(ClipboardItem);
20800impl Global for KillRing {}
20801
20802const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20803
20804enum BreakpointPromptEditAction {
20805 Log,
20806 Condition,
20807 HitCondition,
20808}
20809
20810struct BreakpointPromptEditor {
20811 pub(crate) prompt: Entity<Editor>,
20812 editor: WeakEntity<Editor>,
20813 breakpoint_anchor: Anchor,
20814 breakpoint: Breakpoint,
20815 edit_action: BreakpointPromptEditAction,
20816 block_ids: HashSet<CustomBlockId>,
20817 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20818 _subscriptions: Vec<Subscription>,
20819}
20820
20821impl BreakpointPromptEditor {
20822 const MAX_LINES: u8 = 4;
20823
20824 fn new(
20825 editor: WeakEntity<Editor>,
20826 breakpoint_anchor: Anchor,
20827 breakpoint: Breakpoint,
20828 edit_action: BreakpointPromptEditAction,
20829 window: &mut Window,
20830 cx: &mut Context<Self>,
20831 ) -> Self {
20832 let base_text = match edit_action {
20833 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20834 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20835 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20836 }
20837 .map(|msg| msg.to_string())
20838 .unwrap_or_default();
20839
20840 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20841 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20842
20843 let prompt = cx.new(|cx| {
20844 let mut prompt = Editor::new(
20845 EditorMode::AutoHeight {
20846 max_lines: Self::MAX_LINES as usize,
20847 },
20848 buffer,
20849 None,
20850 window,
20851 cx,
20852 );
20853 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20854 prompt.set_show_cursor_when_unfocused(false, cx);
20855 prompt.set_placeholder_text(
20856 match edit_action {
20857 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20858 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20859 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20860 },
20861 cx,
20862 );
20863
20864 prompt
20865 });
20866
20867 Self {
20868 prompt,
20869 editor,
20870 breakpoint_anchor,
20871 breakpoint,
20872 edit_action,
20873 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20874 block_ids: Default::default(),
20875 _subscriptions: vec![],
20876 }
20877 }
20878
20879 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20880 self.block_ids.extend(block_ids)
20881 }
20882
20883 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20884 if let Some(editor) = self.editor.upgrade() {
20885 let message = self
20886 .prompt
20887 .read(cx)
20888 .buffer
20889 .read(cx)
20890 .as_singleton()
20891 .expect("A multi buffer in breakpoint prompt isn't possible")
20892 .read(cx)
20893 .as_rope()
20894 .to_string();
20895
20896 editor.update(cx, |editor, cx| {
20897 editor.edit_breakpoint_at_anchor(
20898 self.breakpoint_anchor,
20899 self.breakpoint.clone(),
20900 match self.edit_action {
20901 BreakpointPromptEditAction::Log => {
20902 BreakpointEditAction::EditLogMessage(message.into())
20903 }
20904 BreakpointPromptEditAction::Condition => {
20905 BreakpointEditAction::EditCondition(message.into())
20906 }
20907 BreakpointPromptEditAction::HitCondition => {
20908 BreakpointEditAction::EditHitCondition(message.into())
20909 }
20910 },
20911 cx,
20912 );
20913
20914 editor.remove_blocks(self.block_ids.clone(), None, cx);
20915 cx.focus_self(window);
20916 });
20917 }
20918 }
20919
20920 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20921 self.editor
20922 .update(cx, |editor, cx| {
20923 editor.remove_blocks(self.block_ids.clone(), None, cx);
20924 window.focus(&editor.focus_handle);
20925 })
20926 .log_err();
20927 }
20928
20929 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20930 let settings = ThemeSettings::get_global(cx);
20931 let text_style = TextStyle {
20932 color: if self.prompt.read(cx).read_only(cx) {
20933 cx.theme().colors().text_disabled
20934 } else {
20935 cx.theme().colors().text
20936 },
20937 font_family: settings.buffer_font.family.clone(),
20938 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20939 font_size: settings.buffer_font_size(cx).into(),
20940 font_weight: settings.buffer_font.weight,
20941 line_height: relative(settings.buffer_line_height.value()),
20942 ..Default::default()
20943 };
20944 EditorElement::new(
20945 &self.prompt,
20946 EditorStyle {
20947 background: cx.theme().colors().editor_background,
20948 local_player: cx.theme().players().local(),
20949 text: text_style,
20950 ..Default::default()
20951 },
20952 )
20953 }
20954}
20955
20956impl Render for BreakpointPromptEditor {
20957 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20958 let gutter_dimensions = *self.gutter_dimensions.lock();
20959 h_flex()
20960 .key_context("Editor")
20961 .bg(cx.theme().colors().editor_background)
20962 .border_y_1()
20963 .border_color(cx.theme().status().info_border)
20964 .size_full()
20965 .py(window.line_height() / 2.5)
20966 .on_action(cx.listener(Self::confirm))
20967 .on_action(cx.listener(Self::cancel))
20968 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20969 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20970 }
20971}
20972
20973impl Focusable for BreakpointPromptEditor {
20974 fn focus_handle(&self, cx: &App) -> FocusHandle {
20975 self.prompt.focus_handle(cx)
20976 }
20977}
20978
20979fn all_edits_insertions_or_deletions(
20980 edits: &Vec<(Range<Anchor>, String)>,
20981 snapshot: &MultiBufferSnapshot,
20982) -> bool {
20983 let mut all_insertions = true;
20984 let mut all_deletions = true;
20985
20986 for (range, new_text) in edits.iter() {
20987 let range_is_empty = range.to_offset(&snapshot).is_empty();
20988 let text_is_empty = new_text.is_empty();
20989
20990 if range_is_empty != text_is_empty {
20991 if range_is_empty {
20992 all_deletions = false;
20993 } else {
20994 all_insertions = false;
20995 }
20996 } else {
20997 return false;
20998 }
20999
21000 if !all_insertions && !all_deletions {
21001 return false;
21002 }
21003 }
21004 all_insertions || all_deletions
21005}
21006
21007struct MissingEditPredictionKeybindingTooltip;
21008
21009impl Render for MissingEditPredictionKeybindingTooltip {
21010 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21011 ui::tooltip_container(window, cx, |container, _, cx| {
21012 container
21013 .flex_shrink_0()
21014 .max_w_80()
21015 .min_h(rems_from_px(124.))
21016 .justify_between()
21017 .child(
21018 v_flex()
21019 .flex_1()
21020 .text_ui_sm(cx)
21021 .child(Label::new("Conflict with Accept Keybinding"))
21022 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21023 )
21024 .child(
21025 h_flex()
21026 .pb_1()
21027 .gap_1()
21028 .items_end()
21029 .w_full()
21030 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21031 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21032 }))
21033 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21034 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21035 })),
21036 )
21037 })
21038 }
21039}
21040
21041#[derive(Debug, Clone, Copy, PartialEq)]
21042pub struct LineHighlight {
21043 pub background: Background,
21044 pub border: Option<gpui::Hsla>,
21045 pub include_gutter: bool,
21046 pub type_id: Option<TypeId>,
21047}
21048
21049fn render_diff_hunk_controls(
21050 row: u32,
21051 status: &DiffHunkStatus,
21052 hunk_range: Range<Anchor>,
21053 is_created_file: bool,
21054 line_height: Pixels,
21055 editor: &Entity<Editor>,
21056 _window: &mut Window,
21057 cx: &mut App,
21058) -> AnyElement {
21059 h_flex()
21060 .h(line_height)
21061 .mr_1()
21062 .gap_1()
21063 .px_0p5()
21064 .pb_1()
21065 .border_x_1()
21066 .border_b_1()
21067 .border_color(cx.theme().colors().border_variant)
21068 .rounded_b_lg()
21069 .bg(cx.theme().colors().editor_background)
21070 .gap_1()
21071 .occlude()
21072 .shadow_md()
21073 .child(if status.has_secondary_hunk() {
21074 Button::new(("stage", row as u64), "Stage")
21075 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21076 .tooltip({
21077 let focus_handle = editor.focus_handle(cx);
21078 move |window, cx| {
21079 Tooltip::for_action_in(
21080 "Stage Hunk",
21081 &::git::ToggleStaged,
21082 &focus_handle,
21083 window,
21084 cx,
21085 )
21086 }
21087 })
21088 .on_click({
21089 let editor = editor.clone();
21090 move |_event, _window, cx| {
21091 editor.update(cx, |editor, cx| {
21092 editor.stage_or_unstage_diff_hunks(
21093 true,
21094 vec![hunk_range.start..hunk_range.start],
21095 cx,
21096 );
21097 });
21098 }
21099 })
21100 } else {
21101 Button::new(("unstage", row as u64), "Unstage")
21102 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21103 .tooltip({
21104 let focus_handle = editor.focus_handle(cx);
21105 move |window, cx| {
21106 Tooltip::for_action_in(
21107 "Unstage Hunk",
21108 &::git::ToggleStaged,
21109 &focus_handle,
21110 window,
21111 cx,
21112 )
21113 }
21114 })
21115 .on_click({
21116 let editor = editor.clone();
21117 move |_event, _window, cx| {
21118 editor.update(cx, |editor, cx| {
21119 editor.stage_or_unstage_diff_hunks(
21120 false,
21121 vec![hunk_range.start..hunk_range.start],
21122 cx,
21123 );
21124 });
21125 }
21126 })
21127 })
21128 .child(
21129 Button::new(("restore", row as u64), "Restore")
21130 .tooltip({
21131 let focus_handle = editor.focus_handle(cx);
21132 move |window, cx| {
21133 Tooltip::for_action_in(
21134 "Restore Hunk",
21135 &::git::Restore,
21136 &focus_handle,
21137 window,
21138 cx,
21139 )
21140 }
21141 })
21142 .on_click({
21143 let editor = editor.clone();
21144 move |_event, window, cx| {
21145 editor.update(cx, |editor, cx| {
21146 let snapshot = editor.snapshot(window, cx);
21147 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21148 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21149 });
21150 }
21151 })
21152 .disabled(is_created_file),
21153 )
21154 .when(
21155 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21156 |el| {
21157 el.child(
21158 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21159 .shape(IconButtonShape::Square)
21160 .icon_size(IconSize::Small)
21161 // .disabled(!has_multiple_hunks)
21162 .tooltip({
21163 let focus_handle = editor.focus_handle(cx);
21164 move |window, cx| {
21165 Tooltip::for_action_in(
21166 "Next Hunk",
21167 &GoToHunk,
21168 &focus_handle,
21169 window,
21170 cx,
21171 )
21172 }
21173 })
21174 .on_click({
21175 let editor = editor.clone();
21176 move |_event, window, cx| {
21177 editor.update(cx, |editor, cx| {
21178 let snapshot = editor.snapshot(window, cx);
21179 let position =
21180 hunk_range.end.to_point(&snapshot.buffer_snapshot);
21181 editor.go_to_hunk_before_or_after_position(
21182 &snapshot,
21183 position,
21184 Direction::Next,
21185 window,
21186 cx,
21187 );
21188 editor.expand_selected_diff_hunks(cx);
21189 });
21190 }
21191 }),
21192 )
21193 .child(
21194 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21195 .shape(IconButtonShape::Square)
21196 .icon_size(IconSize::Small)
21197 // .disabled(!has_multiple_hunks)
21198 .tooltip({
21199 let focus_handle = editor.focus_handle(cx);
21200 move |window, cx| {
21201 Tooltip::for_action_in(
21202 "Previous Hunk",
21203 &GoToPreviousHunk,
21204 &focus_handle,
21205 window,
21206 cx,
21207 )
21208 }
21209 })
21210 .on_click({
21211 let editor = editor.clone();
21212 move |_event, window, cx| {
21213 editor.update(cx, |editor, cx| {
21214 let snapshot = editor.snapshot(window, cx);
21215 let point =
21216 hunk_range.start.to_point(&snapshot.buffer_snapshot);
21217 editor.go_to_hunk_before_or_after_position(
21218 &snapshot,
21219 point,
21220 Direction::Prev,
21221 window,
21222 cx,
21223 );
21224 editor.expand_selected_diff_hunks(cx);
21225 });
21226 }
21227 }),
21228 )
21229 },
21230 )
21231 .into_any_element()
21232}