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 ActiveDebugLine {}
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/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
819/// a breakpoint on them.
820#[derive(Clone, Copy, Debug)]
821struct PhantomBreakpointIndicator {
822 display_row: DisplayRow,
823 /// There's a small debounce between hovering over the line and showing the indicator.
824 /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
825 is_active: bool,
826 collides_with_existing_breakpoint: bool,
827}
828/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
829///
830/// See the [module level documentation](self) for more information.
831pub struct Editor {
832 focus_handle: FocusHandle,
833 last_focused_descendant: Option<WeakFocusHandle>,
834 /// The text buffer being edited
835 buffer: Entity<MultiBuffer>,
836 /// Map of how text in the buffer should be displayed.
837 /// Handles soft wraps, folds, fake inlay text insertions, etc.
838 pub display_map: Entity<DisplayMap>,
839 pub selections: SelectionsCollection,
840 pub scroll_manager: ScrollManager,
841 /// When inline assist editors are linked, they all render cursors because
842 /// typing enters text into each of them, even the ones that aren't focused.
843 pub(crate) show_cursor_when_unfocused: bool,
844 columnar_selection_tail: Option<Anchor>,
845 add_selections_state: Option<AddSelectionsState>,
846 select_next_state: Option<SelectNextState>,
847 select_prev_state: Option<SelectNextState>,
848 selection_history: SelectionHistory,
849 autoclose_regions: Vec<AutocloseRegion>,
850 snippet_stack: InvalidationStack<SnippetState>,
851 select_syntax_node_history: SelectSyntaxNodeHistory,
852 ime_transaction: Option<TransactionId>,
853 active_diagnostics: ActiveDiagnostic,
854 show_inline_diagnostics: bool,
855 inline_diagnostics_update: Task<()>,
856 inline_diagnostics_enabled: bool,
857 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
858 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
859 hard_wrap: Option<usize>,
860
861 // TODO: make this a access method
862 pub project: Option<Entity<Project>>,
863 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
864 completion_provider: Option<Box<dyn CompletionProvider>>,
865 collaboration_hub: Option<Box<dyn CollaborationHub>>,
866 blink_manager: Entity<BlinkManager>,
867 show_cursor_names: bool,
868 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
869 pub show_local_selections: bool,
870 mode: EditorMode,
871 show_breadcrumbs: bool,
872 show_gutter: bool,
873 show_scrollbars: bool,
874 disable_scrolling: bool,
875 disable_expand_excerpt_buttons: bool,
876 show_line_numbers: Option<bool>,
877 use_relative_line_numbers: Option<bool>,
878 show_git_diff_gutter: Option<bool>,
879 show_code_actions: Option<bool>,
880 show_runnables: Option<bool>,
881 show_breakpoints: Option<bool>,
882 show_wrap_guides: Option<bool>,
883 show_indent_guides: Option<bool>,
884 placeholder_text: Option<Arc<str>>,
885 highlight_order: usize,
886 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
887 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
888 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
889 scrollbar_marker_state: ScrollbarMarkerState,
890 active_indent_guides_state: ActiveIndentGuidesState,
891 nav_history: Option<ItemNavHistory>,
892 context_menu: RefCell<Option<CodeContextMenu>>,
893 context_menu_options: Option<ContextMenuOptions>,
894 mouse_context_menu: Option<MouseContextMenu>,
895 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
896 inline_blame_popover: Option<InlineBlamePopover>,
897 signature_help_state: SignatureHelpState,
898 auto_signature_help: Option<bool>,
899 find_all_references_task_sources: Vec<Anchor>,
900 next_completion_id: CompletionId,
901 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
902 code_actions_task: Option<Task<Result<()>>>,
903 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
904 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
905 document_highlights_task: Option<Task<()>>,
906 linked_editing_range_task: Option<Task<Option<()>>>,
907 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
908 pending_rename: Option<RenameState>,
909 searchable: bool,
910 cursor_shape: CursorShape,
911 current_line_highlight: Option<CurrentLineHighlight>,
912 collapse_matches: bool,
913 autoindent_mode: Option<AutoindentMode>,
914 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
915 input_enabled: bool,
916 use_modal_editing: bool,
917 read_only: bool,
918 leader_peer_id: Option<PeerId>,
919 remote_id: Option<ViewId>,
920 pub hover_state: HoverState,
921 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
922 gutter_hovered: bool,
923 hovered_link_state: Option<HoveredLinkState>,
924 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
925 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
926 active_inline_completion: Option<InlineCompletionState>,
927 /// Used to prevent flickering as the user types while the menu is open
928 stale_inline_completion_in_menu: Option<InlineCompletionState>,
929 edit_prediction_settings: EditPredictionSettings,
930 inline_completions_hidden_for_vim_mode: bool,
931 show_inline_completions_override: Option<bool>,
932 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
933 edit_prediction_preview: EditPredictionPreview,
934 edit_prediction_indent_conflict: bool,
935 edit_prediction_requires_modifier_in_indent_conflict: bool,
936 inlay_hint_cache: InlayHintCache,
937 next_inlay_id: usize,
938 _subscriptions: Vec<Subscription>,
939 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
940 gutter_dimensions: GutterDimensions,
941 style: Option<EditorStyle>,
942 text_style_refinement: Option<TextStyleRefinement>,
943 next_editor_action_id: EditorActionId,
944 editor_actions:
945 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
946 use_autoclose: bool,
947 use_auto_surround: bool,
948 auto_replace_emoji_shortcode: bool,
949 jsx_tag_auto_close_enabled_in_any_buffer: bool,
950 show_git_blame_gutter: bool,
951 show_git_blame_inline: bool,
952 show_git_blame_inline_delay_task: Option<Task<()>>,
953 git_blame_inline_enabled: bool,
954 render_diff_hunk_controls: RenderDiffHunkControlsFn,
955 serialize_dirty_buffers: bool,
956 show_selection_menu: Option<bool>,
957 blame: Option<Entity<GitBlame>>,
958 blame_subscription: Option<Subscription>,
959 custom_context_menu: Option<
960 Box<
961 dyn 'static
962 + Fn(
963 &mut Self,
964 DisplayPoint,
965 &mut Window,
966 &mut Context<Self>,
967 ) -> Option<Entity<ui::ContextMenu>>,
968 >,
969 >,
970 last_bounds: Option<Bounds<Pixels>>,
971 last_position_map: Option<Rc<PositionMap>>,
972 expect_bounds_change: Option<Bounds<Pixels>>,
973 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
974 tasks_update_task: Option<Task<()>>,
975 breakpoint_store: Option<Entity<BreakpointStore>>,
976 gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
977 in_project_search: bool,
978 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
979 breadcrumb_header: Option<String>,
980 focused_block: Option<FocusedBlock>,
981 next_scroll_position: NextScrollCursorCenterTopBottom,
982 addons: HashMap<TypeId, Box<dyn Addon>>,
983 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
984 load_diff_task: Option<Shared<Task<()>>>,
985 selection_mark_mode: bool,
986 toggle_fold_multiple_buffers: Task<()>,
987 _scroll_cursor_center_top_bottom_task: Task<()>,
988 serialize_selections: Task<()>,
989 serialize_folds: Task<()>,
990 mouse_cursor_hidden: bool,
991 hide_mouse_mode: HideMouseMode,
992 pub change_list: ChangeList,
993 inline_value_cache: InlineValueCache,
994}
995
996#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
997enum NextScrollCursorCenterTopBottom {
998 #[default]
999 Center,
1000 Top,
1001 Bottom,
1002}
1003
1004impl NextScrollCursorCenterTopBottom {
1005 fn next(&self) -> Self {
1006 match self {
1007 Self::Center => Self::Top,
1008 Self::Top => Self::Bottom,
1009 Self::Bottom => Self::Center,
1010 }
1011 }
1012}
1013
1014#[derive(Clone)]
1015pub struct EditorSnapshot {
1016 pub mode: EditorMode,
1017 show_gutter: bool,
1018 show_line_numbers: Option<bool>,
1019 show_git_diff_gutter: Option<bool>,
1020 show_code_actions: Option<bool>,
1021 show_runnables: Option<bool>,
1022 show_breakpoints: Option<bool>,
1023 git_blame_gutter_max_author_length: Option<usize>,
1024 pub display_snapshot: DisplaySnapshot,
1025 pub placeholder_text: Option<Arc<str>>,
1026 is_focused: bool,
1027 scroll_anchor: ScrollAnchor,
1028 ongoing_scroll: OngoingScroll,
1029 current_line_highlight: CurrentLineHighlight,
1030 gutter_hovered: bool,
1031}
1032
1033#[derive(Default, Debug, Clone, Copy)]
1034pub struct GutterDimensions {
1035 pub left_padding: Pixels,
1036 pub right_padding: Pixels,
1037 pub width: Pixels,
1038 pub margin: Pixels,
1039 pub git_blame_entries_width: Option<Pixels>,
1040}
1041
1042impl GutterDimensions {
1043 /// The full width of the space taken up by the gutter.
1044 pub fn full_width(&self) -> Pixels {
1045 self.margin + self.width
1046 }
1047
1048 /// The width of the space reserved for the fold indicators,
1049 /// use alongside 'justify_end' and `gutter_width` to
1050 /// right align content with the line numbers
1051 pub fn fold_area_width(&self) -> Pixels {
1052 self.margin + self.right_padding
1053 }
1054}
1055
1056#[derive(Debug)]
1057pub struct RemoteSelection {
1058 pub replica_id: ReplicaId,
1059 pub selection: Selection<Anchor>,
1060 pub cursor_shape: CursorShape,
1061 pub peer_id: PeerId,
1062 pub line_mode: bool,
1063 pub participant_index: Option<ParticipantIndex>,
1064 pub user_name: Option<SharedString>,
1065}
1066
1067#[derive(Clone, Debug)]
1068struct SelectionHistoryEntry {
1069 selections: Arc<[Selection<Anchor>]>,
1070 select_next_state: Option<SelectNextState>,
1071 select_prev_state: Option<SelectNextState>,
1072 add_selections_state: Option<AddSelectionsState>,
1073}
1074
1075enum SelectionHistoryMode {
1076 Normal,
1077 Undoing,
1078 Redoing,
1079}
1080
1081#[derive(Clone, PartialEq, Eq, Hash)]
1082struct HoveredCursor {
1083 replica_id: u16,
1084 selection_id: usize,
1085}
1086
1087impl Default for SelectionHistoryMode {
1088 fn default() -> Self {
1089 Self::Normal
1090 }
1091}
1092
1093#[derive(Default)]
1094struct SelectionHistory {
1095 #[allow(clippy::type_complexity)]
1096 selections_by_transaction:
1097 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1098 mode: SelectionHistoryMode,
1099 undo_stack: VecDeque<SelectionHistoryEntry>,
1100 redo_stack: VecDeque<SelectionHistoryEntry>,
1101}
1102
1103impl SelectionHistory {
1104 fn insert_transaction(
1105 &mut self,
1106 transaction_id: TransactionId,
1107 selections: Arc<[Selection<Anchor>]>,
1108 ) {
1109 self.selections_by_transaction
1110 .insert(transaction_id, (selections, None));
1111 }
1112
1113 #[allow(clippy::type_complexity)]
1114 fn transaction(
1115 &self,
1116 transaction_id: TransactionId,
1117 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1118 self.selections_by_transaction.get(&transaction_id)
1119 }
1120
1121 #[allow(clippy::type_complexity)]
1122 fn transaction_mut(
1123 &mut self,
1124 transaction_id: TransactionId,
1125 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1126 self.selections_by_transaction.get_mut(&transaction_id)
1127 }
1128
1129 fn push(&mut self, entry: SelectionHistoryEntry) {
1130 if !entry.selections.is_empty() {
1131 match self.mode {
1132 SelectionHistoryMode::Normal => {
1133 self.push_undo(entry);
1134 self.redo_stack.clear();
1135 }
1136 SelectionHistoryMode::Undoing => self.push_redo(entry),
1137 SelectionHistoryMode::Redoing => self.push_undo(entry),
1138 }
1139 }
1140 }
1141
1142 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1143 if self
1144 .undo_stack
1145 .back()
1146 .map_or(true, |e| e.selections != entry.selections)
1147 {
1148 self.undo_stack.push_back(entry);
1149 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1150 self.undo_stack.pop_front();
1151 }
1152 }
1153 }
1154
1155 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1156 if self
1157 .redo_stack
1158 .back()
1159 .map_or(true, |e| e.selections != entry.selections)
1160 {
1161 self.redo_stack.push_back(entry);
1162 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1163 self.redo_stack.pop_front();
1164 }
1165 }
1166 }
1167}
1168
1169#[derive(Clone, Copy)]
1170pub struct RowHighlightOptions {
1171 pub autoscroll: bool,
1172 pub include_gutter: bool,
1173}
1174
1175impl Default for RowHighlightOptions {
1176 fn default() -> Self {
1177 Self {
1178 autoscroll: Default::default(),
1179 include_gutter: true,
1180 }
1181 }
1182}
1183
1184struct RowHighlight {
1185 index: usize,
1186 range: Range<Anchor>,
1187 color: Hsla,
1188 options: RowHighlightOptions,
1189 type_id: TypeId,
1190}
1191
1192#[derive(Clone, Debug)]
1193struct AddSelectionsState {
1194 above: bool,
1195 stack: Vec<usize>,
1196}
1197
1198#[derive(Clone)]
1199struct SelectNextState {
1200 query: AhoCorasick,
1201 wordwise: bool,
1202 done: bool,
1203}
1204
1205impl std::fmt::Debug for SelectNextState {
1206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1207 f.debug_struct(std::any::type_name::<Self>())
1208 .field("wordwise", &self.wordwise)
1209 .field("done", &self.done)
1210 .finish()
1211 }
1212}
1213
1214#[derive(Debug)]
1215struct AutocloseRegion {
1216 selection_id: usize,
1217 range: Range<Anchor>,
1218 pair: BracketPair,
1219}
1220
1221#[derive(Debug)]
1222struct SnippetState {
1223 ranges: Vec<Vec<Range<Anchor>>>,
1224 active_index: usize,
1225 choices: Vec<Option<Vec<String>>>,
1226}
1227
1228#[doc(hidden)]
1229pub struct RenameState {
1230 pub range: Range<Anchor>,
1231 pub old_name: Arc<str>,
1232 pub editor: Entity<Editor>,
1233 block_id: CustomBlockId,
1234}
1235
1236struct InvalidationStack<T>(Vec<T>);
1237
1238struct RegisteredInlineCompletionProvider {
1239 provider: Arc<dyn InlineCompletionProviderHandle>,
1240 _subscription: Subscription,
1241}
1242
1243#[derive(Debug, PartialEq, Eq)]
1244pub struct ActiveDiagnosticGroup {
1245 pub active_range: Range<Anchor>,
1246 pub active_message: String,
1247 pub group_id: usize,
1248 pub blocks: HashSet<CustomBlockId>,
1249}
1250
1251#[derive(Debug, PartialEq, Eq)]
1252#[allow(clippy::large_enum_variant)]
1253pub(crate) enum ActiveDiagnostic {
1254 None,
1255 All,
1256 Group(ActiveDiagnosticGroup),
1257}
1258
1259#[derive(Serialize, Deserialize, Clone, Debug)]
1260pub struct ClipboardSelection {
1261 /// The number of bytes in this selection.
1262 pub len: usize,
1263 /// Whether this was a full-line selection.
1264 pub is_entire_line: bool,
1265 /// The indentation of the first line when this content was originally copied.
1266 pub first_line_indent: u32,
1267}
1268
1269// selections, scroll behavior, was newest selection reversed
1270type SelectSyntaxNodeHistoryState = (
1271 Box<[Selection<usize>]>,
1272 SelectSyntaxNodeScrollBehavior,
1273 bool,
1274);
1275
1276#[derive(Default)]
1277struct SelectSyntaxNodeHistory {
1278 stack: Vec<SelectSyntaxNodeHistoryState>,
1279 // disable temporarily to allow changing selections without losing the stack
1280 pub disable_clearing: bool,
1281}
1282
1283impl SelectSyntaxNodeHistory {
1284 pub fn try_clear(&mut self) {
1285 if !self.disable_clearing {
1286 self.stack.clear();
1287 }
1288 }
1289
1290 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1291 self.stack.push(selection);
1292 }
1293
1294 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1295 self.stack.pop()
1296 }
1297}
1298
1299enum SelectSyntaxNodeScrollBehavior {
1300 CursorTop,
1301 FitSelection,
1302 CursorBottom,
1303}
1304
1305#[derive(Debug)]
1306pub(crate) struct NavigationData {
1307 cursor_anchor: Anchor,
1308 cursor_position: Point,
1309 scroll_anchor: ScrollAnchor,
1310 scroll_top_row: u32,
1311}
1312
1313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1314pub enum GotoDefinitionKind {
1315 Symbol,
1316 Declaration,
1317 Type,
1318 Implementation,
1319}
1320
1321#[derive(Debug, Clone)]
1322enum InlayHintRefreshReason {
1323 ModifiersChanged(bool),
1324 Toggle(bool),
1325 SettingsChange(InlayHintSettings),
1326 NewLinesShown,
1327 BufferEdited(HashSet<Arc<Language>>),
1328 RefreshRequested,
1329 ExcerptsRemoved(Vec<ExcerptId>),
1330}
1331
1332impl InlayHintRefreshReason {
1333 fn description(&self) -> &'static str {
1334 match self {
1335 Self::ModifiersChanged(_) => "modifiers changed",
1336 Self::Toggle(_) => "toggle",
1337 Self::SettingsChange(_) => "settings change",
1338 Self::NewLinesShown => "new lines shown",
1339 Self::BufferEdited(_) => "buffer edited",
1340 Self::RefreshRequested => "refresh requested",
1341 Self::ExcerptsRemoved(_) => "excerpts removed",
1342 }
1343 }
1344}
1345
1346pub enum FormatTarget {
1347 Buffers,
1348 Ranges(Vec<Range<MultiBufferPoint>>),
1349}
1350
1351pub(crate) struct FocusedBlock {
1352 id: BlockId,
1353 focus_handle: WeakFocusHandle,
1354}
1355
1356#[derive(Clone)]
1357enum JumpData {
1358 MultiBufferRow {
1359 row: MultiBufferRow,
1360 line_offset_from_top: u32,
1361 },
1362 MultiBufferPoint {
1363 excerpt_id: ExcerptId,
1364 position: Point,
1365 anchor: text::Anchor,
1366 line_offset_from_top: u32,
1367 },
1368}
1369
1370pub enum MultibufferSelectionMode {
1371 First,
1372 All,
1373}
1374
1375#[derive(Clone, Copy, Debug, Default)]
1376pub struct RewrapOptions {
1377 pub override_language_settings: bool,
1378 pub preserve_existing_whitespace: bool,
1379}
1380
1381impl Editor {
1382 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1383 let buffer = cx.new(|cx| Buffer::local("", cx));
1384 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1385 Self::new(
1386 EditorMode::SingleLine { auto_width: false },
1387 buffer,
1388 None,
1389 window,
1390 cx,
1391 )
1392 }
1393
1394 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1395 let buffer = cx.new(|cx| Buffer::local("", cx));
1396 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1397 Self::new(EditorMode::full(), buffer, None, window, cx)
1398 }
1399
1400 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1401 let buffer = cx.new(|cx| Buffer::local("", cx));
1402 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1403 Self::new(
1404 EditorMode::SingleLine { auto_width: true },
1405 buffer,
1406 None,
1407 window,
1408 cx,
1409 )
1410 }
1411
1412 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1413 let buffer = cx.new(|cx| Buffer::local("", cx));
1414 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1415 Self::new(
1416 EditorMode::AutoHeight { max_lines },
1417 buffer,
1418 None,
1419 window,
1420 cx,
1421 )
1422 }
1423
1424 pub fn for_buffer(
1425 buffer: Entity<Buffer>,
1426 project: Option<Entity<Project>>,
1427 window: &mut Window,
1428 cx: &mut Context<Self>,
1429 ) -> Self {
1430 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1431 Self::new(EditorMode::full(), buffer, project, window, cx)
1432 }
1433
1434 pub fn for_multibuffer(
1435 buffer: Entity<MultiBuffer>,
1436 project: Option<Entity<Project>>,
1437 window: &mut Window,
1438 cx: &mut Context<Self>,
1439 ) -> Self {
1440 Self::new(EditorMode::full(), buffer, project, window, cx)
1441 }
1442
1443 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1444 let mut clone = Self::new(
1445 self.mode,
1446 self.buffer.clone(),
1447 self.project.clone(),
1448 window,
1449 cx,
1450 );
1451 self.display_map.update(cx, |display_map, cx| {
1452 let snapshot = display_map.snapshot(cx);
1453 clone.display_map.update(cx, |display_map, cx| {
1454 display_map.set_state(&snapshot, cx);
1455 });
1456 });
1457 clone.folds_did_change(cx);
1458 clone.selections.clone_state(&self.selections);
1459 clone.scroll_manager.clone_state(&self.scroll_manager);
1460 clone.searchable = self.searchable;
1461 clone.read_only = self.read_only;
1462 clone
1463 }
1464
1465 pub fn new(
1466 mode: EditorMode,
1467 buffer: Entity<MultiBuffer>,
1468 project: Option<Entity<Project>>,
1469 window: &mut Window,
1470 cx: &mut Context<Self>,
1471 ) -> Self {
1472 let style = window.text_style();
1473 let font_size = style.font_size.to_pixels(window.rem_size());
1474 let editor = cx.entity().downgrade();
1475 let fold_placeholder = FoldPlaceholder {
1476 constrain_width: true,
1477 render: Arc::new(move |fold_id, fold_range, cx| {
1478 let editor = editor.clone();
1479 div()
1480 .id(fold_id)
1481 .bg(cx.theme().colors().ghost_element_background)
1482 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1483 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1484 .rounded_xs()
1485 .size_full()
1486 .cursor_pointer()
1487 .child("⋯")
1488 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1489 .on_click(move |_, _window, cx| {
1490 editor
1491 .update(cx, |editor, cx| {
1492 editor.unfold_ranges(
1493 &[fold_range.start..fold_range.end],
1494 true,
1495 false,
1496 cx,
1497 );
1498 cx.stop_propagation();
1499 })
1500 .ok();
1501 })
1502 .into_any()
1503 }),
1504 merge_adjacent: true,
1505 ..Default::default()
1506 };
1507 let display_map = cx.new(|cx| {
1508 DisplayMap::new(
1509 buffer.clone(),
1510 style.font(),
1511 font_size,
1512 None,
1513 FILE_HEADER_HEIGHT,
1514 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1515 fold_placeholder,
1516 cx,
1517 )
1518 });
1519
1520 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1521
1522 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1523
1524 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1525 .then(|| language_settings::SoftWrap::None);
1526
1527 let mut project_subscriptions = Vec::new();
1528 if mode.is_full() {
1529 if let Some(project) = project.as_ref() {
1530 project_subscriptions.push(cx.subscribe_in(
1531 project,
1532 window,
1533 |editor, _, event, window, cx| match event {
1534 project::Event::RefreshCodeLens => {
1535 // we always query lens with actions, without storing them, always refreshing them
1536 }
1537 project::Event::RefreshInlayHints => {
1538 editor
1539 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1540 }
1541 project::Event::SnippetEdit(id, snippet_edits) => {
1542 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1543 let focus_handle = editor.focus_handle(cx);
1544 if focus_handle.is_focused(window) {
1545 let snapshot = buffer.read(cx).snapshot();
1546 for (range, snippet) in snippet_edits {
1547 let editor_range =
1548 language::range_from_lsp(*range).to_offset(&snapshot);
1549 editor
1550 .insert_snippet(
1551 &[editor_range],
1552 snippet.clone(),
1553 window,
1554 cx,
1555 )
1556 .ok();
1557 }
1558 }
1559 }
1560 }
1561 _ => {}
1562 },
1563 ));
1564 if let Some(task_inventory) = project
1565 .read(cx)
1566 .task_store()
1567 .read(cx)
1568 .task_inventory()
1569 .cloned()
1570 {
1571 project_subscriptions.push(cx.observe_in(
1572 &task_inventory,
1573 window,
1574 |editor, _, window, cx| {
1575 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1576 },
1577 ));
1578 };
1579
1580 project_subscriptions.push(cx.subscribe_in(
1581 &project.read(cx).breakpoint_store(),
1582 window,
1583 |editor, _, event, window, cx| match event {
1584 BreakpointStoreEvent::ClearDebugLines => {
1585 editor.clear_row_highlights::<ActiveDebugLine>();
1586 editor.refresh_inline_values(cx);
1587 }
1588 BreakpointStoreEvent::SetDebugLine => {
1589 if editor.go_to_active_debug_line(window, cx) {
1590 cx.stop_propagation();
1591 }
1592
1593 editor.refresh_inline_values(cx);
1594 }
1595 _ => {}
1596 },
1597 ));
1598 }
1599 }
1600
1601 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1602
1603 let inlay_hint_settings =
1604 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1605 let focus_handle = cx.focus_handle();
1606 cx.on_focus(&focus_handle, window, Self::handle_focus)
1607 .detach();
1608 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1609 .detach();
1610 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1611 .detach();
1612 cx.on_blur(&focus_handle, window, Self::handle_blur)
1613 .detach();
1614
1615 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1616 Some(false)
1617 } else {
1618 None
1619 };
1620
1621 let breakpoint_store = match (mode, project.as_ref()) {
1622 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1623 _ => None,
1624 };
1625
1626 let mut code_action_providers = Vec::new();
1627 let mut load_uncommitted_diff = None;
1628 if let Some(project) = project.clone() {
1629 load_uncommitted_diff = Some(
1630 get_uncommitted_diff_for_buffer(
1631 &project,
1632 buffer.read(cx).all_buffers(),
1633 buffer.clone(),
1634 cx,
1635 )
1636 .shared(),
1637 );
1638 code_action_providers.push(Rc::new(project) as Rc<_>);
1639 }
1640
1641 let mut this = Self {
1642 focus_handle,
1643 show_cursor_when_unfocused: false,
1644 last_focused_descendant: None,
1645 buffer: buffer.clone(),
1646 display_map: display_map.clone(),
1647 selections,
1648 scroll_manager: ScrollManager::new(cx),
1649 columnar_selection_tail: None,
1650 add_selections_state: None,
1651 select_next_state: None,
1652 select_prev_state: None,
1653 selection_history: Default::default(),
1654 autoclose_regions: Default::default(),
1655 snippet_stack: Default::default(),
1656 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1657 ime_transaction: Default::default(),
1658 active_diagnostics: ActiveDiagnostic::None,
1659 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1660 inline_diagnostics_update: Task::ready(()),
1661 inline_diagnostics: Vec::new(),
1662 soft_wrap_mode_override,
1663 hard_wrap: None,
1664 completion_provider: project.clone().map(|project| Box::new(project) as _),
1665 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1666 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1667 project,
1668 blink_manager: blink_manager.clone(),
1669 show_local_selections: true,
1670 show_scrollbars: true,
1671 disable_scrolling: false,
1672 mode,
1673 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1674 show_gutter: mode.is_full(),
1675 show_line_numbers: None,
1676 use_relative_line_numbers: None,
1677 disable_expand_excerpt_buttons: false,
1678 show_git_diff_gutter: None,
1679 show_code_actions: None,
1680 show_runnables: None,
1681 show_breakpoints: None,
1682 show_wrap_guides: None,
1683 show_indent_guides,
1684 placeholder_text: None,
1685 highlight_order: 0,
1686 highlighted_rows: HashMap::default(),
1687 background_highlights: Default::default(),
1688 gutter_highlights: TreeMap::default(),
1689 scrollbar_marker_state: ScrollbarMarkerState::default(),
1690 active_indent_guides_state: ActiveIndentGuidesState::default(),
1691 nav_history: None,
1692 context_menu: RefCell::new(None),
1693 context_menu_options: None,
1694 mouse_context_menu: None,
1695 completion_tasks: Default::default(),
1696 inline_blame_popover: Default::default(),
1697 signature_help_state: SignatureHelpState::default(),
1698 auto_signature_help: None,
1699 find_all_references_task_sources: Vec::new(),
1700 next_completion_id: 0,
1701 next_inlay_id: 0,
1702 code_action_providers,
1703 available_code_actions: Default::default(),
1704 code_actions_task: Default::default(),
1705 quick_selection_highlight_task: Default::default(),
1706 debounced_selection_highlight_task: Default::default(),
1707 document_highlights_task: Default::default(),
1708 linked_editing_range_task: Default::default(),
1709 pending_rename: Default::default(),
1710 searchable: true,
1711 cursor_shape: EditorSettings::get_global(cx)
1712 .cursor_shape
1713 .unwrap_or_default(),
1714 current_line_highlight: None,
1715 autoindent_mode: Some(AutoindentMode::EachLine),
1716 collapse_matches: false,
1717 workspace: None,
1718 input_enabled: true,
1719 use_modal_editing: mode.is_full(),
1720 read_only: false,
1721 use_autoclose: true,
1722 use_auto_surround: true,
1723 auto_replace_emoji_shortcode: false,
1724 jsx_tag_auto_close_enabled_in_any_buffer: false,
1725 leader_peer_id: None,
1726 remote_id: None,
1727 hover_state: Default::default(),
1728 pending_mouse_down: None,
1729 hovered_link_state: Default::default(),
1730 edit_prediction_provider: None,
1731 active_inline_completion: None,
1732 stale_inline_completion_in_menu: None,
1733 edit_prediction_preview: EditPredictionPreview::Inactive {
1734 released_too_fast: false,
1735 },
1736 inline_diagnostics_enabled: mode.is_full(),
1737 inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
1738 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1739
1740 gutter_hovered: false,
1741 pixel_position_of_newest_cursor: None,
1742 last_bounds: None,
1743 last_position_map: None,
1744 expect_bounds_change: None,
1745 gutter_dimensions: GutterDimensions::default(),
1746 style: None,
1747 show_cursor_names: false,
1748 hovered_cursors: Default::default(),
1749 next_editor_action_id: EditorActionId::default(),
1750 editor_actions: Rc::default(),
1751 inline_completions_hidden_for_vim_mode: false,
1752 show_inline_completions_override: None,
1753 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1754 edit_prediction_settings: EditPredictionSettings::Disabled,
1755 edit_prediction_indent_conflict: false,
1756 edit_prediction_requires_modifier_in_indent_conflict: true,
1757 custom_context_menu: None,
1758 show_git_blame_gutter: false,
1759 show_git_blame_inline: false,
1760 show_selection_menu: None,
1761 show_git_blame_inline_delay_task: None,
1762 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1763 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1764 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1765 .session
1766 .restore_unsaved_buffers,
1767 blame: None,
1768 blame_subscription: None,
1769 tasks: Default::default(),
1770
1771 breakpoint_store,
1772 gutter_breakpoint_indicator: (None, None),
1773 _subscriptions: vec![
1774 cx.observe(&buffer, Self::on_buffer_changed),
1775 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1776 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1777 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1778 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1779 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1780 cx.observe_window_activation(window, |editor, window, cx| {
1781 let active = window.is_window_active();
1782 editor.blink_manager.update(cx, |blink_manager, cx| {
1783 if active {
1784 blink_manager.enable(cx);
1785 } else {
1786 blink_manager.disable(cx);
1787 }
1788 });
1789 }),
1790 ],
1791 tasks_update_task: None,
1792 linked_edit_ranges: Default::default(),
1793 in_project_search: false,
1794 previous_search_ranges: None,
1795 breadcrumb_header: None,
1796 focused_block: None,
1797 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1798 addons: HashMap::default(),
1799 registered_buffers: HashMap::default(),
1800 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1801 selection_mark_mode: false,
1802 toggle_fold_multiple_buffers: Task::ready(()),
1803 serialize_selections: Task::ready(()),
1804 serialize_folds: Task::ready(()),
1805 text_style_refinement: None,
1806 load_diff_task: load_uncommitted_diff,
1807 mouse_cursor_hidden: false,
1808 hide_mouse_mode: EditorSettings::get_global(cx)
1809 .hide_mouse
1810 .unwrap_or_default(),
1811 change_list: ChangeList::new(),
1812 };
1813 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1814 this._subscriptions
1815 .push(cx.observe(breakpoints, |_, _, cx| {
1816 cx.notify();
1817 }));
1818 }
1819 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1820 this._subscriptions.extend(project_subscriptions);
1821
1822 this._subscriptions.push(cx.subscribe_in(
1823 &cx.entity(),
1824 window,
1825 |editor, _, e: &EditorEvent, window, cx| match e {
1826 EditorEvent::ScrollPositionChanged { local, .. } => {
1827 if *local {
1828 let new_anchor = editor.scroll_manager.anchor();
1829 let snapshot = editor.snapshot(window, cx);
1830 editor.update_restoration_data(cx, move |data| {
1831 data.scroll_position = (
1832 new_anchor.top_row(&snapshot.buffer_snapshot),
1833 new_anchor.offset,
1834 );
1835 });
1836 editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
1837 editor.inline_blame_popover.take();
1838 }
1839 }
1840 EditorEvent::Edited { .. } => {
1841 if !vim_enabled(cx) {
1842 let (map, selections) = editor.selections.all_adjusted_display(cx);
1843 let pop_state = editor
1844 .change_list
1845 .last()
1846 .map(|previous| {
1847 previous.len() == selections.len()
1848 && previous.iter().enumerate().all(|(ix, p)| {
1849 p.to_display_point(&map).row()
1850 == selections[ix].head().row()
1851 })
1852 })
1853 .unwrap_or(false);
1854 let new_positions = selections
1855 .into_iter()
1856 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1857 .collect();
1858 editor
1859 .change_list
1860 .push_to_change_list(pop_state, new_positions);
1861 }
1862 }
1863 _ => (),
1864 },
1865 ));
1866
1867 if let Some(dap_store) = this
1868 .project
1869 .as_ref()
1870 .map(|project| project.read(cx).dap_store())
1871 {
1872 let weak_editor = cx.weak_entity();
1873
1874 this._subscriptions
1875 .push(
1876 cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
1877 let session_entity = cx.entity();
1878 weak_editor
1879 .update(cx, |editor, cx| {
1880 editor._subscriptions.push(
1881 cx.subscribe(&session_entity, Self::on_debug_session_event),
1882 );
1883 })
1884 .ok();
1885 }),
1886 );
1887
1888 for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
1889 this._subscriptions
1890 .push(cx.subscribe(&session, Self::on_debug_session_event));
1891 }
1892 }
1893
1894 this.end_selection(window, cx);
1895 this.scroll_manager.show_scrollbars(window, cx);
1896 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1897
1898 if mode.is_full() {
1899 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1900 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1901
1902 if this.git_blame_inline_enabled {
1903 this.git_blame_inline_enabled = true;
1904 this.start_git_blame_inline(false, window, cx);
1905 }
1906
1907 this.go_to_active_debug_line(window, cx);
1908
1909 if let Some(buffer) = buffer.read(cx).as_singleton() {
1910 if let Some(project) = this.project.as_ref() {
1911 let handle = project.update(cx, |project, cx| {
1912 project.register_buffer_with_language_servers(&buffer, cx)
1913 });
1914 this.registered_buffers
1915 .insert(buffer.read(cx).remote_id(), handle);
1916 }
1917 }
1918 }
1919
1920 this.report_editor_event("Editor Opened", None, cx);
1921 this
1922 }
1923
1924 pub fn deploy_mouse_context_menu(
1925 &mut self,
1926 position: gpui::Point<Pixels>,
1927 context_menu: Entity<ContextMenu>,
1928 window: &mut Window,
1929 cx: &mut Context<Self>,
1930 ) {
1931 self.mouse_context_menu = Some(MouseContextMenu::new(
1932 self,
1933 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1934 context_menu,
1935 window,
1936 cx,
1937 ));
1938 }
1939
1940 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1941 self.mouse_context_menu
1942 .as_ref()
1943 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1944 }
1945
1946 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1947 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1948 }
1949
1950 fn key_context_internal(
1951 &self,
1952 has_active_edit_prediction: bool,
1953 window: &Window,
1954 cx: &App,
1955 ) -> KeyContext {
1956 let mut key_context = KeyContext::new_with_defaults();
1957 key_context.add("Editor");
1958 let mode = match self.mode {
1959 EditorMode::SingleLine { .. } => "single_line",
1960 EditorMode::AutoHeight { .. } => "auto_height",
1961 EditorMode::Full { .. } => "full",
1962 };
1963
1964 if EditorSettings::jupyter_enabled(cx) {
1965 key_context.add("jupyter");
1966 }
1967
1968 key_context.set("mode", mode);
1969 if self.pending_rename.is_some() {
1970 key_context.add("renaming");
1971 }
1972
1973 match self.context_menu.borrow().as_ref() {
1974 Some(CodeContextMenu::Completions(_)) => {
1975 key_context.add("menu");
1976 key_context.add("showing_completions");
1977 }
1978 Some(CodeContextMenu::CodeActions(_)) => {
1979 key_context.add("menu");
1980 key_context.add("showing_code_actions")
1981 }
1982 None => {}
1983 }
1984
1985 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1986 if !self.focus_handle(cx).contains_focused(window, cx)
1987 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1988 {
1989 for addon in self.addons.values() {
1990 addon.extend_key_context(&mut key_context, cx)
1991 }
1992 }
1993
1994 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1995 if let Some(extension) = singleton_buffer
1996 .read(cx)
1997 .file()
1998 .and_then(|file| file.path().extension()?.to_str())
1999 {
2000 key_context.set("extension", extension.to_string());
2001 }
2002 } else {
2003 key_context.add("multibuffer");
2004 }
2005
2006 if has_active_edit_prediction {
2007 if self.edit_prediction_in_conflict() {
2008 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
2009 } else {
2010 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
2011 key_context.add("copilot_suggestion");
2012 }
2013 }
2014
2015 if self.selection_mark_mode {
2016 key_context.add("selection_mode");
2017 }
2018
2019 key_context
2020 }
2021
2022 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
2023 self.mouse_cursor_hidden = match origin {
2024 HideMouseCursorOrigin::TypingAction => {
2025 matches!(
2026 self.hide_mouse_mode,
2027 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
2028 )
2029 }
2030 HideMouseCursorOrigin::MovementAction => {
2031 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
2032 }
2033 };
2034 }
2035
2036 pub fn edit_prediction_in_conflict(&self) -> bool {
2037 if !self.show_edit_predictions_in_menu() {
2038 return false;
2039 }
2040
2041 let showing_completions = self
2042 .context_menu
2043 .borrow()
2044 .as_ref()
2045 .map_or(false, |context| {
2046 matches!(context, CodeContextMenu::Completions(_))
2047 });
2048
2049 showing_completions
2050 || self.edit_prediction_requires_modifier()
2051 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
2052 // bindings to insert tab characters.
2053 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
2054 }
2055
2056 pub fn accept_edit_prediction_keybind(
2057 &self,
2058 window: &Window,
2059 cx: &App,
2060 ) -> AcceptEditPredictionBinding {
2061 let key_context = self.key_context_internal(true, window, cx);
2062 let in_conflict = self.edit_prediction_in_conflict();
2063
2064 AcceptEditPredictionBinding(
2065 window
2066 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
2067 .into_iter()
2068 .filter(|binding| {
2069 !in_conflict
2070 || binding
2071 .keystrokes()
2072 .first()
2073 .map_or(false, |keystroke| keystroke.modifiers.modified())
2074 })
2075 .rev()
2076 .min_by_key(|binding| {
2077 binding
2078 .keystrokes()
2079 .first()
2080 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
2081 }),
2082 )
2083 }
2084
2085 pub fn new_file(
2086 workspace: &mut Workspace,
2087 _: &workspace::NewFile,
2088 window: &mut Window,
2089 cx: &mut Context<Workspace>,
2090 ) {
2091 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
2092 "Failed to create buffer",
2093 window,
2094 cx,
2095 |e, _, _| match e.error_code() {
2096 ErrorCode::RemoteUpgradeRequired => Some(format!(
2097 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2098 e.error_tag("required").unwrap_or("the latest version")
2099 )),
2100 _ => None,
2101 },
2102 );
2103 }
2104
2105 pub fn new_in_workspace(
2106 workspace: &mut Workspace,
2107 window: &mut Window,
2108 cx: &mut Context<Workspace>,
2109 ) -> Task<Result<Entity<Editor>>> {
2110 let project = workspace.project().clone();
2111 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2112
2113 cx.spawn_in(window, async move |workspace, cx| {
2114 let buffer = create.await?;
2115 workspace.update_in(cx, |workspace, window, cx| {
2116 let editor =
2117 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
2118 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2119 editor
2120 })
2121 })
2122 }
2123
2124 fn new_file_vertical(
2125 workspace: &mut Workspace,
2126 _: &workspace::NewFileSplitVertical,
2127 window: &mut Window,
2128 cx: &mut Context<Workspace>,
2129 ) {
2130 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
2131 }
2132
2133 fn new_file_horizontal(
2134 workspace: &mut Workspace,
2135 _: &workspace::NewFileSplitHorizontal,
2136 window: &mut Window,
2137 cx: &mut Context<Workspace>,
2138 ) {
2139 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2140 }
2141
2142 fn new_file_in_direction(
2143 workspace: &mut Workspace,
2144 direction: SplitDirection,
2145 window: &mut Window,
2146 cx: &mut Context<Workspace>,
2147 ) {
2148 let project = workspace.project().clone();
2149 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2150
2151 cx.spawn_in(window, async move |workspace, cx| {
2152 let buffer = create.await?;
2153 workspace.update_in(cx, move |workspace, window, cx| {
2154 workspace.split_item(
2155 direction,
2156 Box::new(
2157 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2158 ),
2159 window,
2160 cx,
2161 )
2162 })?;
2163 anyhow::Ok(())
2164 })
2165 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2166 match e.error_code() {
2167 ErrorCode::RemoteUpgradeRequired => Some(format!(
2168 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2169 e.error_tag("required").unwrap_or("the latest version")
2170 )),
2171 _ => None,
2172 }
2173 });
2174 }
2175
2176 pub fn leader_peer_id(&self) -> Option<PeerId> {
2177 self.leader_peer_id
2178 }
2179
2180 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2181 &self.buffer
2182 }
2183
2184 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2185 self.workspace.as_ref()?.0.upgrade()
2186 }
2187
2188 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2189 self.buffer().read(cx).title(cx)
2190 }
2191
2192 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2193 let git_blame_gutter_max_author_length = self
2194 .render_git_blame_gutter(cx)
2195 .then(|| {
2196 if let Some(blame) = self.blame.as_ref() {
2197 let max_author_length =
2198 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2199 Some(max_author_length)
2200 } else {
2201 None
2202 }
2203 })
2204 .flatten();
2205
2206 EditorSnapshot {
2207 mode: self.mode,
2208 show_gutter: self.show_gutter,
2209 show_line_numbers: self.show_line_numbers,
2210 show_git_diff_gutter: self.show_git_diff_gutter,
2211 show_code_actions: self.show_code_actions,
2212 show_runnables: self.show_runnables,
2213 show_breakpoints: self.show_breakpoints,
2214 git_blame_gutter_max_author_length,
2215 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2216 scroll_anchor: self.scroll_manager.anchor(),
2217 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2218 placeholder_text: self.placeholder_text.clone(),
2219 is_focused: self.focus_handle.is_focused(window),
2220 current_line_highlight: self
2221 .current_line_highlight
2222 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2223 gutter_hovered: self.gutter_hovered,
2224 }
2225 }
2226
2227 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2228 self.buffer.read(cx).language_at(point, cx)
2229 }
2230
2231 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2232 self.buffer.read(cx).read(cx).file_at(point).cloned()
2233 }
2234
2235 pub fn active_excerpt(
2236 &self,
2237 cx: &App,
2238 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2239 self.buffer
2240 .read(cx)
2241 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2242 }
2243
2244 pub fn mode(&self) -> EditorMode {
2245 self.mode
2246 }
2247
2248 pub fn set_mode(&mut self, mode: EditorMode) {
2249 self.mode = mode;
2250 }
2251
2252 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2253 self.collaboration_hub.as_deref()
2254 }
2255
2256 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2257 self.collaboration_hub = Some(hub);
2258 }
2259
2260 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2261 self.in_project_search = in_project_search;
2262 }
2263
2264 pub fn set_custom_context_menu(
2265 &mut self,
2266 f: impl 'static
2267 + Fn(
2268 &mut Self,
2269 DisplayPoint,
2270 &mut Window,
2271 &mut Context<Self>,
2272 ) -> Option<Entity<ui::ContextMenu>>,
2273 ) {
2274 self.custom_context_menu = Some(Box::new(f))
2275 }
2276
2277 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2278 self.completion_provider = provider;
2279 }
2280
2281 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2282 self.semantics_provider.clone()
2283 }
2284
2285 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2286 self.semantics_provider = provider;
2287 }
2288
2289 pub fn set_edit_prediction_provider<T>(
2290 &mut self,
2291 provider: Option<Entity<T>>,
2292 window: &mut Window,
2293 cx: &mut Context<Self>,
2294 ) where
2295 T: EditPredictionProvider,
2296 {
2297 self.edit_prediction_provider =
2298 provider.map(|provider| RegisteredInlineCompletionProvider {
2299 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2300 if this.focus_handle.is_focused(window) {
2301 this.update_visible_inline_completion(window, cx);
2302 }
2303 }),
2304 provider: Arc::new(provider),
2305 });
2306 self.update_edit_prediction_settings(cx);
2307 self.refresh_inline_completion(false, false, window, cx);
2308 }
2309
2310 pub fn placeholder_text(&self) -> Option<&str> {
2311 self.placeholder_text.as_deref()
2312 }
2313
2314 pub fn set_placeholder_text(
2315 &mut self,
2316 placeholder_text: impl Into<Arc<str>>,
2317 cx: &mut Context<Self>,
2318 ) {
2319 let placeholder_text = Some(placeholder_text.into());
2320 if self.placeholder_text != placeholder_text {
2321 self.placeholder_text = placeholder_text;
2322 cx.notify();
2323 }
2324 }
2325
2326 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2327 self.cursor_shape = cursor_shape;
2328
2329 // Disrupt blink for immediate user feedback that the cursor shape has changed
2330 self.blink_manager.update(cx, BlinkManager::show_cursor);
2331
2332 cx.notify();
2333 }
2334
2335 pub fn set_current_line_highlight(
2336 &mut self,
2337 current_line_highlight: Option<CurrentLineHighlight>,
2338 ) {
2339 self.current_line_highlight = current_line_highlight;
2340 }
2341
2342 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2343 self.collapse_matches = collapse_matches;
2344 }
2345
2346 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2347 let buffers = self.buffer.read(cx).all_buffers();
2348 let Some(project) = self.project.as_ref() else {
2349 return;
2350 };
2351 project.update(cx, |project, cx| {
2352 for buffer in buffers {
2353 self.registered_buffers
2354 .entry(buffer.read(cx).remote_id())
2355 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2356 }
2357 })
2358 }
2359
2360 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2361 if self.collapse_matches {
2362 return range.start..range.start;
2363 }
2364 range.clone()
2365 }
2366
2367 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2368 if self.display_map.read(cx).clip_at_line_ends != clip {
2369 self.display_map
2370 .update(cx, |map, _| map.clip_at_line_ends = clip);
2371 }
2372 }
2373
2374 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2375 self.input_enabled = input_enabled;
2376 }
2377
2378 pub fn set_inline_completions_hidden_for_vim_mode(
2379 &mut self,
2380 hidden: bool,
2381 window: &mut Window,
2382 cx: &mut Context<Self>,
2383 ) {
2384 if hidden != self.inline_completions_hidden_for_vim_mode {
2385 self.inline_completions_hidden_for_vim_mode = hidden;
2386 if hidden {
2387 self.update_visible_inline_completion(window, cx);
2388 } else {
2389 self.refresh_inline_completion(true, false, window, cx);
2390 }
2391 }
2392 }
2393
2394 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2395 self.menu_inline_completions_policy = value;
2396 }
2397
2398 pub fn set_autoindent(&mut self, autoindent: bool) {
2399 if autoindent {
2400 self.autoindent_mode = Some(AutoindentMode::EachLine);
2401 } else {
2402 self.autoindent_mode = None;
2403 }
2404 }
2405
2406 pub fn read_only(&self, cx: &App) -> bool {
2407 self.read_only || self.buffer.read(cx).read_only()
2408 }
2409
2410 pub fn set_read_only(&mut self, read_only: bool) {
2411 self.read_only = read_only;
2412 }
2413
2414 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2415 self.use_autoclose = autoclose;
2416 }
2417
2418 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2419 self.use_auto_surround = auto_surround;
2420 }
2421
2422 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2423 self.auto_replace_emoji_shortcode = auto_replace;
2424 }
2425
2426 pub fn toggle_edit_predictions(
2427 &mut self,
2428 _: &ToggleEditPrediction,
2429 window: &mut Window,
2430 cx: &mut Context<Self>,
2431 ) {
2432 if self.show_inline_completions_override.is_some() {
2433 self.set_show_edit_predictions(None, window, cx);
2434 } else {
2435 let show_edit_predictions = !self.edit_predictions_enabled();
2436 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2437 }
2438 }
2439
2440 pub fn set_show_edit_predictions(
2441 &mut self,
2442 show_edit_predictions: Option<bool>,
2443 window: &mut Window,
2444 cx: &mut Context<Self>,
2445 ) {
2446 self.show_inline_completions_override = show_edit_predictions;
2447 self.update_edit_prediction_settings(cx);
2448
2449 if let Some(false) = show_edit_predictions {
2450 self.discard_inline_completion(false, cx);
2451 } else {
2452 self.refresh_inline_completion(false, true, window, cx);
2453 }
2454 }
2455
2456 fn inline_completions_disabled_in_scope(
2457 &self,
2458 buffer: &Entity<Buffer>,
2459 buffer_position: language::Anchor,
2460 cx: &App,
2461 ) -> bool {
2462 let snapshot = buffer.read(cx).snapshot();
2463 let settings = snapshot.settings_at(buffer_position, cx);
2464
2465 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2466 return false;
2467 };
2468
2469 scope.override_name().map_or(false, |scope_name| {
2470 settings
2471 .edit_predictions_disabled_in
2472 .iter()
2473 .any(|s| s == scope_name)
2474 })
2475 }
2476
2477 pub fn set_use_modal_editing(&mut self, to: bool) {
2478 self.use_modal_editing = to;
2479 }
2480
2481 pub fn use_modal_editing(&self) -> bool {
2482 self.use_modal_editing
2483 }
2484
2485 fn selections_did_change(
2486 &mut self,
2487 local: bool,
2488 old_cursor_position: &Anchor,
2489 show_completions: bool,
2490 window: &mut Window,
2491 cx: &mut Context<Self>,
2492 ) {
2493 window.invalidate_character_coordinates();
2494
2495 // Copy selections to primary selection buffer
2496 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2497 if local {
2498 let selections = self.selections.all::<usize>(cx);
2499 let buffer_handle = self.buffer.read(cx).read(cx);
2500
2501 let mut text = String::new();
2502 for (index, selection) in selections.iter().enumerate() {
2503 let text_for_selection = buffer_handle
2504 .text_for_range(selection.start..selection.end)
2505 .collect::<String>();
2506
2507 text.push_str(&text_for_selection);
2508 if index != selections.len() - 1 {
2509 text.push('\n');
2510 }
2511 }
2512
2513 if !text.is_empty() {
2514 cx.write_to_primary(ClipboardItem::new_string(text));
2515 }
2516 }
2517
2518 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2519 self.buffer.update(cx, |buffer, cx| {
2520 buffer.set_active_selections(
2521 &self.selections.disjoint_anchors(),
2522 self.selections.line_mode,
2523 self.cursor_shape,
2524 cx,
2525 )
2526 });
2527 }
2528 let display_map = self
2529 .display_map
2530 .update(cx, |display_map, cx| display_map.snapshot(cx));
2531 let buffer = &display_map.buffer_snapshot;
2532 self.add_selections_state = None;
2533 self.select_next_state = None;
2534 self.select_prev_state = None;
2535 self.select_syntax_node_history.try_clear();
2536 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2537 self.snippet_stack
2538 .invalidate(&self.selections.disjoint_anchors(), buffer);
2539 self.take_rename(false, window, cx);
2540
2541 let new_cursor_position = self.selections.newest_anchor().head();
2542
2543 self.push_to_nav_history(
2544 *old_cursor_position,
2545 Some(new_cursor_position.to_point(buffer)),
2546 false,
2547 cx,
2548 );
2549
2550 if local {
2551 let new_cursor_position = self.selections.newest_anchor().head();
2552 let mut context_menu = self.context_menu.borrow_mut();
2553 let completion_menu = match context_menu.as_ref() {
2554 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2555 _ => {
2556 *context_menu = None;
2557 None
2558 }
2559 };
2560 if let Some(buffer_id) = new_cursor_position.buffer_id {
2561 if !self.registered_buffers.contains_key(&buffer_id) {
2562 if let Some(project) = self.project.as_ref() {
2563 project.update(cx, |project, cx| {
2564 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2565 return;
2566 };
2567 self.registered_buffers.insert(
2568 buffer_id,
2569 project.register_buffer_with_language_servers(&buffer, cx),
2570 );
2571 })
2572 }
2573 }
2574 }
2575
2576 if let Some(completion_menu) = completion_menu {
2577 let cursor_position = new_cursor_position.to_offset(buffer);
2578 let (word_range, kind) =
2579 buffer.surrounding_word(completion_menu.initial_position, true);
2580 if kind == Some(CharKind::Word)
2581 && word_range.to_inclusive().contains(&cursor_position)
2582 {
2583 let mut completion_menu = completion_menu.clone();
2584 drop(context_menu);
2585
2586 let query = Self::completion_query(buffer, cursor_position);
2587 cx.spawn(async move |this, cx| {
2588 completion_menu
2589 .filter(query.as_deref(), cx.background_executor().clone())
2590 .await;
2591
2592 this.update(cx, |this, cx| {
2593 let mut context_menu = this.context_menu.borrow_mut();
2594 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2595 else {
2596 return;
2597 };
2598
2599 if menu.id > completion_menu.id {
2600 return;
2601 }
2602
2603 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2604 drop(context_menu);
2605 cx.notify();
2606 })
2607 })
2608 .detach();
2609
2610 if show_completions {
2611 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2612 }
2613 } else {
2614 drop(context_menu);
2615 self.hide_context_menu(window, cx);
2616 }
2617 } else {
2618 drop(context_menu);
2619 }
2620
2621 hide_hover(self, cx);
2622
2623 if old_cursor_position.to_display_point(&display_map).row()
2624 != new_cursor_position.to_display_point(&display_map).row()
2625 {
2626 self.available_code_actions.take();
2627 }
2628 self.refresh_code_actions(window, cx);
2629 self.refresh_document_highlights(cx);
2630 self.refresh_selected_text_highlights(false, window, cx);
2631 refresh_matching_bracket_highlights(self, window, cx);
2632 self.update_visible_inline_completion(window, cx);
2633 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2634 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2635 self.inline_blame_popover.take();
2636 if self.git_blame_inline_enabled {
2637 self.start_inline_blame_timer(window, cx);
2638 }
2639 }
2640
2641 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2642 cx.emit(EditorEvent::SelectionsChanged { local });
2643
2644 let selections = &self.selections.disjoint;
2645 if selections.len() == 1 {
2646 cx.emit(SearchEvent::ActiveMatchChanged)
2647 }
2648 if local {
2649 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2650 let inmemory_selections = selections
2651 .iter()
2652 .map(|s| {
2653 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2654 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2655 })
2656 .collect();
2657 self.update_restoration_data(cx, |data| {
2658 data.selections = inmemory_selections;
2659 });
2660
2661 if WorkspaceSettings::get(None, cx).restore_on_startup
2662 != RestoreOnStartupBehavior::None
2663 {
2664 if let Some(workspace_id) =
2665 self.workspace.as_ref().and_then(|workspace| workspace.1)
2666 {
2667 let snapshot = self.buffer().read(cx).snapshot(cx);
2668 let selections = selections.clone();
2669 let background_executor = cx.background_executor().clone();
2670 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2671 self.serialize_selections = cx.background_spawn(async move {
2672 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2673 let db_selections = selections
2674 .iter()
2675 .map(|selection| {
2676 (
2677 selection.start.to_offset(&snapshot),
2678 selection.end.to_offset(&snapshot),
2679 )
2680 })
2681 .collect();
2682
2683 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2684 .await
2685 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2686 .log_err();
2687 });
2688 }
2689 }
2690 }
2691 }
2692
2693 cx.notify();
2694 }
2695
2696 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2697 use text::ToOffset as _;
2698 use text::ToPoint as _;
2699
2700 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2701 return;
2702 }
2703
2704 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2705 return;
2706 };
2707
2708 let snapshot = singleton.read(cx).snapshot();
2709 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2710 let display_snapshot = display_map.snapshot(cx);
2711
2712 display_snapshot
2713 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2714 .map(|fold| {
2715 fold.range.start.text_anchor.to_point(&snapshot)
2716 ..fold.range.end.text_anchor.to_point(&snapshot)
2717 })
2718 .collect()
2719 });
2720 self.update_restoration_data(cx, |data| {
2721 data.folds = inmemory_folds;
2722 });
2723
2724 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2725 return;
2726 };
2727 let background_executor = cx.background_executor().clone();
2728 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2729 let db_folds = self.display_map.update(cx, |display_map, cx| {
2730 display_map
2731 .snapshot(cx)
2732 .folds_in_range(0..snapshot.len())
2733 .map(|fold| {
2734 (
2735 fold.range.start.text_anchor.to_offset(&snapshot),
2736 fold.range.end.text_anchor.to_offset(&snapshot),
2737 )
2738 })
2739 .collect()
2740 });
2741 self.serialize_folds = cx.background_spawn(async move {
2742 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2743 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2744 .await
2745 .with_context(|| {
2746 format!(
2747 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2748 )
2749 })
2750 .log_err();
2751 });
2752 }
2753
2754 pub fn sync_selections(
2755 &mut self,
2756 other: Entity<Editor>,
2757 cx: &mut Context<Self>,
2758 ) -> gpui::Subscription {
2759 let other_selections = other.read(cx).selections.disjoint.to_vec();
2760 self.selections.change_with(cx, |selections| {
2761 selections.select_anchors(other_selections);
2762 });
2763
2764 let other_subscription =
2765 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2766 EditorEvent::SelectionsChanged { local: true } => {
2767 let other_selections = other.read(cx).selections.disjoint.to_vec();
2768 if other_selections.is_empty() {
2769 return;
2770 }
2771 this.selections.change_with(cx, |selections| {
2772 selections.select_anchors(other_selections);
2773 });
2774 }
2775 _ => {}
2776 });
2777
2778 let this_subscription =
2779 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2780 EditorEvent::SelectionsChanged { local: true } => {
2781 let these_selections = this.selections.disjoint.to_vec();
2782 if these_selections.is_empty() {
2783 return;
2784 }
2785 other.update(cx, |other_editor, cx| {
2786 other_editor.selections.change_with(cx, |selections| {
2787 selections.select_anchors(these_selections);
2788 })
2789 });
2790 }
2791 _ => {}
2792 });
2793
2794 Subscription::join(other_subscription, this_subscription)
2795 }
2796
2797 pub fn change_selections<R>(
2798 &mut self,
2799 autoscroll: Option<Autoscroll>,
2800 window: &mut Window,
2801 cx: &mut Context<Self>,
2802 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2803 ) -> R {
2804 self.change_selections_inner(autoscroll, true, window, cx, change)
2805 }
2806
2807 fn change_selections_inner<R>(
2808 &mut self,
2809 autoscroll: Option<Autoscroll>,
2810 request_completions: bool,
2811 window: &mut Window,
2812 cx: &mut Context<Self>,
2813 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2814 ) -> R {
2815 let old_cursor_position = self.selections.newest_anchor().head();
2816 self.push_to_selection_history();
2817
2818 let (changed, result) = self.selections.change_with(cx, change);
2819
2820 if changed {
2821 if let Some(autoscroll) = autoscroll {
2822 self.request_autoscroll(autoscroll, cx);
2823 }
2824 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2825
2826 if self.should_open_signature_help_automatically(
2827 &old_cursor_position,
2828 self.signature_help_state.backspace_pressed(),
2829 cx,
2830 ) {
2831 self.show_signature_help(&ShowSignatureHelp, window, cx);
2832 }
2833 self.signature_help_state.set_backspace_pressed(false);
2834 }
2835
2836 result
2837 }
2838
2839 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2840 where
2841 I: IntoIterator<Item = (Range<S>, T)>,
2842 S: ToOffset,
2843 T: Into<Arc<str>>,
2844 {
2845 if self.read_only(cx) {
2846 return;
2847 }
2848
2849 self.buffer
2850 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2851 }
2852
2853 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2854 where
2855 I: IntoIterator<Item = (Range<S>, T)>,
2856 S: ToOffset,
2857 T: Into<Arc<str>>,
2858 {
2859 if self.read_only(cx) {
2860 return;
2861 }
2862
2863 self.buffer.update(cx, |buffer, cx| {
2864 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2865 });
2866 }
2867
2868 pub fn edit_with_block_indent<I, S, T>(
2869 &mut self,
2870 edits: I,
2871 original_indent_columns: Vec<Option<u32>>,
2872 cx: &mut Context<Self>,
2873 ) where
2874 I: IntoIterator<Item = (Range<S>, T)>,
2875 S: ToOffset,
2876 T: Into<Arc<str>>,
2877 {
2878 if self.read_only(cx) {
2879 return;
2880 }
2881
2882 self.buffer.update(cx, |buffer, cx| {
2883 buffer.edit(
2884 edits,
2885 Some(AutoindentMode::Block {
2886 original_indent_columns,
2887 }),
2888 cx,
2889 )
2890 });
2891 }
2892
2893 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2894 self.hide_context_menu(window, cx);
2895
2896 match phase {
2897 SelectPhase::Begin {
2898 position,
2899 add,
2900 click_count,
2901 } => self.begin_selection(position, add, click_count, window, cx),
2902 SelectPhase::BeginColumnar {
2903 position,
2904 goal_column,
2905 reset,
2906 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2907 SelectPhase::Extend {
2908 position,
2909 click_count,
2910 } => self.extend_selection(position, click_count, window, cx),
2911 SelectPhase::Update {
2912 position,
2913 goal_column,
2914 scroll_delta,
2915 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2916 SelectPhase::End => self.end_selection(window, cx),
2917 }
2918 }
2919
2920 fn extend_selection(
2921 &mut self,
2922 position: DisplayPoint,
2923 click_count: usize,
2924 window: &mut Window,
2925 cx: &mut Context<Self>,
2926 ) {
2927 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2928 let tail = self.selections.newest::<usize>(cx).tail();
2929 self.begin_selection(position, false, click_count, window, cx);
2930
2931 let position = position.to_offset(&display_map, Bias::Left);
2932 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2933
2934 let mut pending_selection = self
2935 .selections
2936 .pending_anchor()
2937 .expect("extend_selection not called with pending selection");
2938 if position >= tail {
2939 pending_selection.start = tail_anchor;
2940 } else {
2941 pending_selection.end = tail_anchor;
2942 pending_selection.reversed = true;
2943 }
2944
2945 let mut pending_mode = self.selections.pending_mode().unwrap();
2946 match &mut pending_mode {
2947 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2948 _ => {}
2949 }
2950
2951 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2952 s.set_pending(pending_selection, pending_mode)
2953 });
2954 }
2955
2956 fn begin_selection(
2957 &mut self,
2958 position: DisplayPoint,
2959 add: bool,
2960 click_count: usize,
2961 window: &mut Window,
2962 cx: &mut Context<Self>,
2963 ) {
2964 if !self.focus_handle.is_focused(window) {
2965 self.last_focused_descendant = None;
2966 window.focus(&self.focus_handle);
2967 }
2968
2969 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2970 let buffer = &display_map.buffer_snapshot;
2971 let newest_selection = self.selections.newest_anchor().clone();
2972 let position = display_map.clip_point(position, Bias::Left);
2973
2974 let start;
2975 let end;
2976 let mode;
2977 let mut auto_scroll;
2978 match click_count {
2979 1 => {
2980 start = buffer.anchor_before(position.to_point(&display_map));
2981 end = start;
2982 mode = SelectMode::Character;
2983 auto_scroll = true;
2984 }
2985 2 => {
2986 let range = movement::surrounding_word(&display_map, position);
2987 start = buffer.anchor_before(range.start.to_point(&display_map));
2988 end = buffer.anchor_before(range.end.to_point(&display_map));
2989 mode = SelectMode::Word(start..end);
2990 auto_scroll = true;
2991 }
2992 3 => {
2993 let position = display_map
2994 .clip_point(position, Bias::Left)
2995 .to_point(&display_map);
2996 let line_start = display_map.prev_line_boundary(position).0;
2997 let next_line_start = buffer.clip_point(
2998 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2999 Bias::Left,
3000 );
3001 start = buffer.anchor_before(line_start);
3002 end = buffer.anchor_before(next_line_start);
3003 mode = SelectMode::Line(start..end);
3004 auto_scroll = true;
3005 }
3006 _ => {
3007 start = buffer.anchor_before(0);
3008 end = buffer.anchor_before(buffer.len());
3009 mode = SelectMode::All;
3010 auto_scroll = false;
3011 }
3012 }
3013 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
3014
3015 let point_to_delete: Option<usize> = {
3016 let selected_points: Vec<Selection<Point>> =
3017 self.selections.disjoint_in_range(start..end, cx);
3018
3019 if !add || click_count > 1 {
3020 None
3021 } else if !selected_points.is_empty() {
3022 Some(selected_points[0].id)
3023 } else {
3024 let clicked_point_already_selected =
3025 self.selections.disjoint.iter().find(|selection| {
3026 selection.start.to_point(buffer) == start.to_point(buffer)
3027 || selection.end.to_point(buffer) == end.to_point(buffer)
3028 });
3029
3030 clicked_point_already_selected.map(|selection| selection.id)
3031 }
3032 };
3033
3034 let selections_count = self.selections.count();
3035
3036 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
3037 if let Some(point_to_delete) = point_to_delete {
3038 s.delete(point_to_delete);
3039
3040 if selections_count == 1 {
3041 s.set_pending_anchor_range(start..end, mode);
3042 }
3043 } else {
3044 if !add {
3045 s.clear_disjoint();
3046 } else if click_count > 1 {
3047 s.delete(newest_selection.id)
3048 }
3049
3050 s.set_pending_anchor_range(start..end, mode);
3051 }
3052 });
3053 }
3054
3055 fn begin_columnar_selection(
3056 &mut self,
3057 position: DisplayPoint,
3058 goal_column: u32,
3059 reset: bool,
3060 window: &mut Window,
3061 cx: &mut Context<Self>,
3062 ) {
3063 if !self.focus_handle.is_focused(window) {
3064 self.last_focused_descendant = None;
3065 window.focus(&self.focus_handle);
3066 }
3067
3068 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3069
3070 if reset {
3071 let pointer_position = display_map
3072 .buffer_snapshot
3073 .anchor_before(position.to_point(&display_map));
3074
3075 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
3076 s.clear_disjoint();
3077 s.set_pending_anchor_range(
3078 pointer_position..pointer_position,
3079 SelectMode::Character,
3080 );
3081 });
3082 }
3083
3084 let tail = self.selections.newest::<Point>(cx).tail();
3085 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3086
3087 if !reset {
3088 self.select_columns(
3089 tail.to_display_point(&display_map),
3090 position,
3091 goal_column,
3092 &display_map,
3093 window,
3094 cx,
3095 );
3096 }
3097 }
3098
3099 fn update_selection(
3100 &mut self,
3101 position: DisplayPoint,
3102 goal_column: u32,
3103 scroll_delta: gpui::Point<f32>,
3104 window: &mut Window,
3105 cx: &mut Context<Self>,
3106 ) {
3107 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3108
3109 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3110 let tail = tail.to_display_point(&display_map);
3111 self.select_columns(tail, position, goal_column, &display_map, window, cx);
3112 } else if let Some(mut pending) = self.selections.pending_anchor() {
3113 let buffer = self.buffer.read(cx).snapshot(cx);
3114 let head;
3115 let tail;
3116 let mode = self.selections.pending_mode().unwrap();
3117 match &mode {
3118 SelectMode::Character => {
3119 head = position.to_point(&display_map);
3120 tail = pending.tail().to_point(&buffer);
3121 }
3122 SelectMode::Word(original_range) => {
3123 let original_display_range = original_range.start.to_display_point(&display_map)
3124 ..original_range.end.to_display_point(&display_map);
3125 let original_buffer_range = original_display_range.start.to_point(&display_map)
3126 ..original_display_range.end.to_point(&display_map);
3127 if movement::is_inside_word(&display_map, position)
3128 || original_display_range.contains(&position)
3129 {
3130 let word_range = movement::surrounding_word(&display_map, position);
3131 if word_range.start < original_display_range.start {
3132 head = word_range.start.to_point(&display_map);
3133 } else {
3134 head = word_range.end.to_point(&display_map);
3135 }
3136 } else {
3137 head = position.to_point(&display_map);
3138 }
3139
3140 if head <= original_buffer_range.start {
3141 tail = original_buffer_range.end;
3142 } else {
3143 tail = original_buffer_range.start;
3144 }
3145 }
3146 SelectMode::Line(original_range) => {
3147 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3148
3149 let position = display_map
3150 .clip_point(position, Bias::Left)
3151 .to_point(&display_map);
3152 let line_start = display_map.prev_line_boundary(position).0;
3153 let next_line_start = buffer.clip_point(
3154 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3155 Bias::Left,
3156 );
3157
3158 if line_start < original_range.start {
3159 head = line_start
3160 } else {
3161 head = next_line_start
3162 }
3163
3164 if head <= original_range.start {
3165 tail = original_range.end;
3166 } else {
3167 tail = original_range.start;
3168 }
3169 }
3170 SelectMode::All => {
3171 return;
3172 }
3173 };
3174
3175 if head < tail {
3176 pending.start = buffer.anchor_before(head);
3177 pending.end = buffer.anchor_before(tail);
3178 pending.reversed = true;
3179 } else {
3180 pending.start = buffer.anchor_before(tail);
3181 pending.end = buffer.anchor_before(head);
3182 pending.reversed = false;
3183 }
3184
3185 self.change_selections(None, window, cx, |s| {
3186 s.set_pending(pending, mode);
3187 });
3188 } else {
3189 log::error!("update_selection dispatched with no pending selection");
3190 return;
3191 }
3192
3193 self.apply_scroll_delta(scroll_delta, window, cx);
3194 cx.notify();
3195 }
3196
3197 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3198 self.columnar_selection_tail.take();
3199 if self.selections.pending_anchor().is_some() {
3200 let selections = self.selections.all::<usize>(cx);
3201 self.change_selections(None, window, cx, |s| {
3202 s.select(selections);
3203 s.clear_pending();
3204 });
3205 }
3206 }
3207
3208 fn select_columns(
3209 &mut self,
3210 tail: DisplayPoint,
3211 head: DisplayPoint,
3212 goal_column: u32,
3213 display_map: &DisplaySnapshot,
3214 window: &mut Window,
3215 cx: &mut Context<Self>,
3216 ) {
3217 let start_row = cmp::min(tail.row(), head.row());
3218 let end_row = cmp::max(tail.row(), head.row());
3219 let start_column = cmp::min(tail.column(), goal_column);
3220 let end_column = cmp::max(tail.column(), goal_column);
3221 let reversed = start_column < tail.column();
3222
3223 let selection_ranges = (start_row.0..=end_row.0)
3224 .map(DisplayRow)
3225 .filter_map(|row| {
3226 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3227 let start = display_map
3228 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3229 .to_point(display_map);
3230 let end = display_map
3231 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3232 .to_point(display_map);
3233 if reversed {
3234 Some(end..start)
3235 } else {
3236 Some(start..end)
3237 }
3238 } else {
3239 None
3240 }
3241 })
3242 .collect::<Vec<_>>();
3243
3244 self.change_selections(None, window, cx, |s| {
3245 s.select_ranges(selection_ranges);
3246 });
3247 cx.notify();
3248 }
3249
3250 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3251 self.selections
3252 .all_adjusted(cx)
3253 .iter()
3254 .any(|selection| !selection.is_empty())
3255 }
3256
3257 pub fn has_pending_nonempty_selection(&self) -> bool {
3258 let pending_nonempty_selection = match self.selections.pending_anchor() {
3259 Some(Selection { start, end, .. }) => start != end,
3260 None => false,
3261 };
3262
3263 pending_nonempty_selection
3264 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3265 }
3266
3267 pub fn has_pending_selection(&self) -> bool {
3268 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3269 }
3270
3271 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3272 self.selection_mark_mode = false;
3273
3274 if self.clear_expanded_diff_hunks(cx) {
3275 cx.notify();
3276 return;
3277 }
3278 if self.dismiss_menus_and_popups(true, window, cx) {
3279 return;
3280 }
3281
3282 if self.mode.is_full()
3283 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3284 {
3285 return;
3286 }
3287
3288 cx.propagate();
3289 }
3290
3291 pub fn dismiss_menus_and_popups(
3292 &mut self,
3293 is_user_requested: bool,
3294 window: &mut Window,
3295 cx: &mut Context<Self>,
3296 ) -> bool {
3297 if self.take_rename(false, window, cx).is_some() {
3298 return true;
3299 }
3300
3301 if hide_hover(self, cx) {
3302 return true;
3303 }
3304
3305 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3306 return true;
3307 }
3308
3309 if self.hide_context_menu(window, cx).is_some() {
3310 return true;
3311 }
3312
3313 if self.mouse_context_menu.take().is_some() {
3314 return true;
3315 }
3316
3317 if is_user_requested && self.discard_inline_completion(true, cx) {
3318 return true;
3319 }
3320
3321 if self.snippet_stack.pop().is_some() {
3322 return true;
3323 }
3324
3325 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3326 self.dismiss_diagnostics(cx);
3327 return true;
3328 }
3329
3330 false
3331 }
3332
3333 fn linked_editing_ranges_for(
3334 &self,
3335 selection: Range<text::Anchor>,
3336 cx: &App,
3337 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3338 if self.linked_edit_ranges.is_empty() {
3339 return None;
3340 }
3341 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3342 selection.end.buffer_id.and_then(|end_buffer_id| {
3343 if selection.start.buffer_id != Some(end_buffer_id) {
3344 return None;
3345 }
3346 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3347 let snapshot = buffer.read(cx).snapshot();
3348 self.linked_edit_ranges
3349 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3350 .map(|ranges| (ranges, snapshot, buffer))
3351 })?;
3352 use text::ToOffset as TO;
3353 // find offset from the start of current range to current cursor position
3354 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3355
3356 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3357 let start_difference = start_offset - start_byte_offset;
3358 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3359 let end_difference = end_offset - start_byte_offset;
3360 // Current range has associated linked ranges.
3361 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3362 for range in linked_ranges.iter() {
3363 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3364 let end_offset = start_offset + end_difference;
3365 let start_offset = start_offset + start_difference;
3366 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3367 continue;
3368 }
3369 if self.selections.disjoint_anchor_ranges().any(|s| {
3370 if s.start.buffer_id != selection.start.buffer_id
3371 || s.end.buffer_id != selection.end.buffer_id
3372 {
3373 return false;
3374 }
3375 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3376 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3377 }) {
3378 continue;
3379 }
3380 let start = buffer_snapshot.anchor_after(start_offset);
3381 let end = buffer_snapshot.anchor_after(end_offset);
3382 linked_edits
3383 .entry(buffer.clone())
3384 .or_default()
3385 .push(start..end);
3386 }
3387 Some(linked_edits)
3388 }
3389
3390 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3391 let text: Arc<str> = text.into();
3392
3393 if self.read_only(cx) {
3394 return;
3395 }
3396
3397 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3398
3399 let selections = self.selections.all_adjusted(cx);
3400 let mut bracket_inserted = false;
3401 let mut edits = Vec::new();
3402 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3403 let mut new_selections = Vec::with_capacity(selections.len());
3404 let mut new_autoclose_regions = Vec::new();
3405 let snapshot = self.buffer.read(cx).read(cx);
3406 let mut clear_linked_edit_ranges = false;
3407
3408 for (selection, autoclose_region) in
3409 self.selections_with_autoclose_regions(selections, &snapshot)
3410 {
3411 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3412 // Determine if the inserted text matches the opening or closing
3413 // bracket of any of this language's bracket pairs.
3414 let mut bracket_pair = None;
3415 let mut is_bracket_pair_start = false;
3416 let mut is_bracket_pair_end = false;
3417 if !text.is_empty() {
3418 let mut bracket_pair_matching_end = None;
3419 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3420 // and they are removing the character that triggered IME popup.
3421 for (pair, enabled) in scope.brackets() {
3422 if !pair.close && !pair.surround {
3423 continue;
3424 }
3425
3426 if enabled && pair.start.ends_with(text.as_ref()) {
3427 let prefix_len = pair.start.len() - text.len();
3428 let preceding_text_matches_prefix = prefix_len == 0
3429 || (selection.start.column >= (prefix_len as u32)
3430 && snapshot.contains_str_at(
3431 Point::new(
3432 selection.start.row,
3433 selection.start.column - (prefix_len as u32),
3434 ),
3435 &pair.start[..prefix_len],
3436 ));
3437 if preceding_text_matches_prefix {
3438 bracket_pair = Some(pair.clone());
3439 is_bracket_pair_start = true;
3440 break;
3441 }
3442 }
3443 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3444 {
3445 // take first bracket pair matching end, but don't break in case a later bracket
3446 // pair matches start
3447 bracket_pair_matching_end = Some(pair.clone());
3448 }
3449 }
3450 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3451 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3452 is_bracket_pair_end = true;
3453 }
3454 }
3455
3456 if let Some(bracket_pair) = bracket_pair {
3457 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3458 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3459 let auto_surround =
3460 self.use_auto_surround && snapshot_settings.use_auto_surround;
3461 if selection.is_empty() {
3462 if is_bracket_pair_start {
3463 // If the inserted text is a suffix of an opening bracket and the
3464 // selection is preceded by the rest of the opening bracket, then
3465 // insert the closing bracket.
3466 let following_text_allows_autoclose = snapshot
3467 .chars_at(selection.start)
3468 .next()
3469 .map_or(true, |c| scope.should_autoclose_before(c));
3470
3471 let preceding_text_allows_autoclose = selection.start.column == 0
3472 || snapshot.reversed_chars_at(selection.start).next().map_or(
3473 true,
3474 |c| {
3475 bracket_pair.start != bracket_pair.end
3476 || !snapshot
3477 .char_classifier_at(selection.start)
3478 .is_word(c)
3479 },
3480 );
3481
3482 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3483 && bracket_pair.start.len() == 1
3484 {
3485 let target = bracket_pair.start.chars().next().unwrap();
3486 let current_line_count = snapshot
3487 .reversed_chars_at(selection.start)
3488 .take_while(|&c| c != '\n')
3489 .filter(|&c| c == target)
3490 .count();
3491 current_line_count % 2 == 1
3492 } else {
3493 false
3494 };
3495
3496 if autoclose
3497 && bracket_pair.close
3498 && following_text_allows_autoclose
3499 && preceding_text_allows_autoclose
3500 && !is_closing_quote
3501 {
3502 let anchor = snapshot.anchor_before(selection.end);
3503 new_selections.push((selection.map(|_| anchor), text.len()));
3504 new_autoclose_regions.push((
3505 anchor,
3506 text.len(),
3507 selection.id,
3508 bracket_pair.clone(),
3509 ));
3510 edits.push((
3511 selection.range(),
3512 format!("{}{}", text, bracket_pair.end).into(),
3513 ));
3514 bracket_inserted = true;
3515 continue;
3516 }
3517 }
3518
3519 if let Some(region) = autoclose_region {
3520 // If the selection is followed by an auto-inserted closing bracket,
3521 // then don't insert that closing bracket again; just move the selection
3522 // past the closing bracket.
3523 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3524 && text.as_ref() == region.pair.end.as_str();
3525 if should_skip {
3526 let anchor = snapshot.anchor_after(selection.end);
3527 new_selections
3528 .push((selection.map(|_| anchor), region.pair.end.len()));
3529 continue;
3530 }
3531 }
3532
3533 let always_treat_brackets_as_autoclosed = snapshot
3534 .language_settings_at(selection.start, cx)
3535 .always_treat_brackets_as_autoclosed;
3536 if always_treat_brackets_as_autoclosed
3537 && is_bracket_pair_end
3538 && snapshot.contains_str_at(selection.end, text.as_ref())
3539 {
3540 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3541 // and the inserted text is a closing bracket and the selection is followed
3542 // by the closing bracket then move the selection past the closing bracket.
3543 let anchor = snapshot.anchor_after(selection.end);
3544 new_selections.push((selection.map(|_| anchor), text.len()));
3545 continue;
3546 }
3547 }
3548 // If an opening bracket is 1 character long and is typed while
3549 // text is selected, then surround that text with the bracket pair.
3550 else if auto_surround
3551 && bracket_pair.surround
3552 && is_bracket_pair_start
3553 && bracket_pair.start.chars().count() == 1
3554 {
3555 edits.push((selection.start..selection.start, text.clone()));
3556 edits.push((
3557 selection.end..selection.end,
3558 bracket_pair.end.as_str().into(),
3559 ));
3560 bracket_inserted = true;
3561 new_selections.push((
3562 Selection {
3563 id: selection.id,
3564 start: snapshot.anchor_after(selection.start),
3565 end: snapshot.anchor_before(selection.end),
3566 reversed: selection.reversed,
3567 goal: selection.goal,
3568 },
3569 0,
3570 ));
3571 continue;
3572 }
3573 }
3574 }
3575
3576 if self.auto_replace_emoji_shortcode
3577 && selection.is_empty()
3578 && text.as_ref().ends_with(':')
3579 {
3580 if let Some(possible_emoji_short_code) =
3581 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3582 {
3583 if !possible_emoji_short_code.is_empty() {
3584 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3585 let emoji_shortcode_start = Point::new(
3586 selection.start.row,
3587 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3588 );
3589
3590 // Remove shortcode from buffer
3591 edits.push((
3592 emoji_shortcode_start..selection.start,
3593 "".to_string().into(),
3594 ));
3595 new_selections.push((
3596 Selection {
3597 id: selection.id,
3598 start: snapshot.anchor_after(emoji_shortcode_start),
3599 end: snapshot.anchor_before(selection.start),
3600 reversed: selection.reversed,
3601 goal: selection.goal,
3602 },
3603 0,
3604 ));
3605
3606 // Insert emoji
3607 let selection_start_anchor = snapshot.anchor_after(selection.start);
3608 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3609 edits.push((selection.start..selection.end, emoji.to_string().into()));
3610
3611 continue;
3612 }
3613 }
3614 }
3615 }
3616
3617 // If not handling any auto-close operation, then just replace the selected
3618 // text with the given input and move the selection to the end of the
3619 // newly inserted text.
3620 let anchor = snapshot.anchor_after(selection.end);
3621 if !self.linked_edit_ranges.is_empty() {
3622 let start_anchor = snapshot.anchor_before(selection.start);
3623
3624 let is_word_char = text.chars().next().map_or(true, |char| {
3625 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3626 classifier.is_word(char)
3627 });
3628
3629 if is_word_char {
3630 if let Some(ranges) = self
3631 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3632 {
3633 for (buffer, edits) in ranges {
3634 linked_edits
3635 .entry(buffer.clone())
3636 .or_default()
3637 .extend(edits.into_iter().map(|range| (range, text.clone())));
3638 }
3639 }
3640 } else {
3641 clear_linked_edit_ranges = true;
3642 }
3643 }
3644
3645 new_selections.push((selection.map(|_| anchor), 0));
3646 edits.push((selection.start..selection.end, text.clone()));
3647 }
3648
3649 drop(snapshot);
3650
3651 self.transact(window, cx, |this, window, cx| {
3652 if clear_linked_edit_ranges {
3653 this.linked_edit_ranges.clear();
3654 }
3655 let initial_buffer_versions =
3656 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3657
3658 this.buffer.update(cx, |buffer, cx| {
3659 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3660 });
3661 for (buffer, edits) in linked_edits {
3662 buffer.update(cx, |buffer, cx| {
3663 let snapshot = buffer.snapshot();
3664 let edits = edits
3665 .into_iter()
3666 .map(|(range, text)| {
3667 use text::ToPoint as TP;
3668 let end_point = TP::to_point(&range.end, &snapshot);
3669 let start_point = TP::to_point(&range.start, &snapshot);
3670 (start_point..end_point, text)
3671 })
3672 .sorted_by_key(|(range, _)| range.start);
3673 buffer.edit(edits, None, cx);
3674 })
3675 }
3676 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3677 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3678 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3679 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3680 .zip(new_selection_deltas)
3681 .map(|(selection, delta)| Selection {
3682 id: selection.id,
3683 start: selection.start + delta,
3684 end: selection.end + delta,
3685 reversed: selection.reversed,
3686 goal: SelectionGoal::None,
3687 })
3688 .collect::<Vec<_>>();
3689
3690 let mut i = 0;
3691 for (position, delta, selection_id, pair) in new_autoclose_regions {
3692 let position = position.to_offset(&map.buffer_snapshot) + delta;
3693 let start = map.buffer_snapshot.anchor_before(position);
3694 let end = map.buffer_snapshot.anchor_after(position);
3695 while let Some(existing_state) = this.autoclose_regions.get(i) {
3696 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3697 Ordering::Less => i += 1,
3698 Ordering::Greater => break,
3699 Ordering::Equal => {
3700 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3701 Ordering::Less => i += 1,
3702 Ordering::Equal => break,
3703 Ordering::Greater => break,
3704 }
3705 }
3706 }
3707 }
3708 this.autoclose_regions.insert(
3709 i,
3710 AutocloseRegion {
3711 selection_id,
3712 range: start..end,
3713 pair,
3714 },
3715 );
3716 }
3717
3718 let had_active_inline_completion = this.has_active_inline_completion();
3719 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3720 s.select(new_selections)
3721 });
3722
3723 if !bracket_inserted {
3724 if let Some(on_type_format_task) =
3725 this.trigger_on_type_formatting(text.to_string(), window, cx)
3726 {
3727 on_type_format_task.detach_and_log_err(cx);
3728 }
3729 }
3730
3731 let editor_settings = EditorSettings::get_global(cx);
3732 if bracket_inserted
3733 && (editor_settings.auto_signature_help
3734 || editor_settings.show_signature_help_after_edits)
3735 {
3736 this.show_signature_help(&ShowSignatureHelp, window, cx);
3737 }
3738
3739 let trigger_in_words =
3740 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3741 if this.hard_wrap.is_some() {
3742 let latest: Range<Point> = this.selections.newest(cx).range();
3743 if latest.is_empty()
3744 && this
3745 .buffer()
3746 .read(cx)
3747 .snapshot(cx)
3748 .line_len(MultiBufferRow(latest.start.row))
3749 == latest.start.column
3750 {
3751 this.rewrap_impl(
3752 RewrapOptions {
3753 override_language_settings: true,
3754 preserve_existing_whitespace: true,
3755 },
3756 cx,
3757 )
3758 }
3759 }
3760 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3761 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3762 this.refresh_inline_completion(true, false, window, cx);
3763 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3764 });
3765 }
3766
3767 fn find_possible_emoji_shortcode_at_position(
3768 snapshot: &MultiBufferSnapshot,
3769 position: Point,
3770 ) -> Option<String> {
3771 let mut chars = Vec::new();
3772 let mut found_colon = false;
3773 for char in snapshot.reversed_chars_at(position).take(100) {
3774 // Found a possible emoji shortcode in the middle of the buffer
3775 if found_colon {
3776 if char.is_whitespace() {
3777 chars.reverse();
3778 return Some(chars.iter().collect());
3779 }
3780 // If the previous character is not a whitespace, we are in the middle of a word
3781 // and we only want to complete the shortcode if the word is made up of other emojis
3782 let mut containing_word = String::new();
3783 for ch in snapshot
3784 .reversed_chars_at(position)
3785 .skip(chars.len() + 1)
3786 .take(100)
3787 {
3788 if ch.is_whitespace() {
3789 break;
3790 }
3791 containing_word.push(ch);
3792 }
3793 let containing_word = containing_word.chars().rev().collect::<String>();
3794 if util::word_consists_of_emojis(containing_word.as_str()) {
3795 chars.reverse();
3796 return Some(chars.iter().collect());
3797 }
3798 }
3799
3800 if char.is_whitespace() || !char.is_ascii() {
3801 return None;
3802 }
3803 if char == ':' {
3804 found_colon = true;
3805 } else {
3806 chars.push(char);
3807 }
3808 }
3809 // Found a possible emoji shortcode at the beginning of the buffer
3810 chars.reverse();
3811 Some(chars.iter().collect())
3812 }
3813
3814 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3815 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3816 self.transact(window, cx, |this, window, cx| {
3817 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3818 let selections = this.selections.all::<usize>(cx);
3819 let multi_buffer = this.buffer.read(cx);
3820 let buffer = multi_buffer.snapshot(cx);
3821 selections
3822 .iter()
3823 .map(|selection| {
3824 let start_point = selection.start.to_point(&buffer);
3825 let mut indent =
3826 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3827 indent.len = cmp::min(indent.len, start_point.column);
3828 let start = selection.start;
3829 let end = selection.end;
3830 let selection_is_empty = start == end;
3831 let language_scope = buffer.language_scope_at(start);
3832 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3833 &language_scope
3834 {
3835 let insert_extra_newline =
3836 insert_extra_newline_brackets(&buffer, start..end, language)
3837 || insert_extra_newline_tree_sitter(&buffer, start..end);
3838
3839 // Comment extension on newline is allowed only for cursor selections
3840 let comment_delimiter = maybe!({
3841 if !selection_is_empty {
3842 return None;
3843 }
3844
3845 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3846 return None;
3847 }
3848
3849 let delimiters = language.line_comment_prefixes();
3850 let max_len_of_delimiter =
3851 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3852 let (snapshot, range) =
3853 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3854
3855 let mut index_of_first_non_whitespace = 0;
3856 let comment_candidate = snapshot
3857 .chars_for_range(range)
3858 .skip_while(|c| {
3859 let should_skip = c.is_whitespace();
3860 if should_skip {
3861 index_of_first_non_whitespace += 1;
3862 }
3863 should_skip
3864 })
3865 .take(max_len_of_delimiter)
3866 .collect::<String>();
3867 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3868 comment_candidate.starts_with(comment_prefix.as_ref())
3869 })?;
3870 let cursor_is_placed_after_comment_marker =
3871 index_of_first_non_whitespace + comment_prefix.len()
3872 <= start_point.column as usize;
3873 if cursor_is_placed_after_comment_marker {
3874 Some(comment_prefix.clone())
3875 } else {
3876 None
3877 }
3878 });
3879 (comment_delimiter, insert_extra_newline)
3880 } else {
3881 (None, false)
3882 };
3883
3884 let capacity_for_delimiter = comment_delimiter
3885 .as_deref()
3886 .map(str::len)
3887 .unwrap_or_default();
3888 let mut new_text =
3889 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3890 new_text.push('\n');
3891 new_text.extend(indent.chars());
3892 if let Some(delimiter) = &comment_delimiter {
3893 new_text.push_str(delimiter);
3894 }
3895 if insert_extra_newline {
3896 new_text = new_text.repeat(2);
3897 }
3898
3899 let anchor = buffer.anchor_after(end);
3900 let new_selection = selection.map(|_| anchor);
3901 (
3902 (start..end, new_text),
3903 (insert_extra_newline, new_selection),
3904 )
3905 })
3906 .unzip()
3907 };
3908
3909 this.edit_with_autoindent(edits, cx);
3910 let buffer = this.buffer.read(cx).snapshot(cx);
3911 let new_selections = selection_fixup_info
3912 .into_iter()
3913 .map(|(extra_newline_inserted, new_selection)| {
3914 let mut cursor = new_selection.end.to_point(&buffer);
3915 if extra_newline_inserted {
3916 cursor.row -= 1;
3917 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3918 }
3919 new_selection.map(|_| cursor)
3920 })
3921 .collect();
3922
3923 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3924 s.select(new_selections)
3925 });
3926 this.refresh_inline_completion(true, false, window, cx);
3927 });
3928 }
3929
3930 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3931 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3932
3933 let buffer = self.buffer.read(cx);
3934 let snapshot = buffer.snapshot(cx);
3935
3936 let mut edits = Vec::new();
3937 let mut rows = Vec::new();
3938
3939 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3940 let cursor = selection.head();
3941 let row = cursor.row;
3942
3943 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3944
3945 let newline = "\n".to_string();
3946 edits.push((start_of_line..start_of_line, newline));
3947
3948 rows.push(row + rows_inserted as u32);
3949 }
3950
3951 self.transact(window, cx, |editor, window, cx| {
3952 editor.edit(edits, cx);
3953
3954 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3955 let mut index = 0;
3956 s.move_cursors_with(|map, _, _| {
3957 let row = rows[index];
3958 index += 1;
3959
3960 let point = Point::new(row, 0);
3961 let boundary = map.next_line_boundary(point).1;
3962 let clipped = map.clip_point(boundary, Bias::Left);
3963
3964 (clipped, SelectionGoal::None)
3965 });
3966 });
3967
3968 let mut indent_edits = Vec::new();
3969 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3970 for row in rows {
3971 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3972 for (row, indent) in indents {
3973 if indent.len == 0 {
3974 continue;
3975 }
3976
3977 let text = match indent.kind {
3978 IndentKind::Space => " ".repeat(indent.len as usize),
3979 IndentKind::Tab => "\t".repeat(indent.len as usize),
3980 };
3981 let point = Point::new(row.0, 0);
3982 indent_edits.push((point..point, text));
3983 }
3984 }
3985 editor.edit(indent_edits, cx);
3986 });
3987 }
3988
3989 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3990 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3991
3992 let buffer = self.buffer.read(cx);
3993 let snapshot = buffer.snapshot(cx);
3994
3995 let mut edits = Vec::new();
3996 let mut rows = Vec::new();
3997 let mut rows_inserted = 0;
3998
3999 for selection in self.selections.all_adjusted(cx) {
4000 let cursor = selection.head();
4001 let row = cursor.row;
4002
4003 let point = Point::new(row + 1, 0);
4004 let start_of_line = snapshot.clip_point(point, Bias::Left);
4005
4006 let newline = "\n".to_string();
4007 edits.push((start_of_line..start_of_line, newline));
4008
4009 rows_inserted += 1;
4010 rows.push(row + rows_inserted);
4011 }
4012
4013 self.transact(window, cx, |editor, window, cx| {
4014 editor.edit(edits, cx);
4015
4016 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4017 let mut index = 0;
4018 s.move_cursors_with(|map, _, _| {
4019 let row = rows[index];
4020 index += 1;
4021
4022 let point = Point::new(row, 0);
4023 let boundary = map.next_line_boundary(point).1;
4024 let clipped = map.clip_point(boundary, Bias::Left);
4025
4026 (clipped, SelectionGoal::None)
4027 });
4028 });
4029
4030 let mut indent_edits = Vec::new();
4031 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4032 for row in rows {
4033 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4034 for (row, indent) in indents {
4035 if indent.len == 0 {
4036 continue;
4037 }
4038
4039 let text = match indent.kind {
4040 IndentKind::Space => " ".repeat(indent.len as usize),
4041 IndentKind::Tab => "\t".repeat(indent.len as usize),
4042 };
4043 let point = Point::new(row.0, 0);
4044 indent_edits.push((point..point, text));
4045 }
4046 }
4047 editor.edit(indent_edits, cx);
4048 });
4049 }
4050
4051 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
4052 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4053 original_indent_columns: Vec::new(),
4054 });
4055 self.insert_with_autoindent_mode(text, autoindent, window, cx);
4056 }
4057
4058 fn insert_with_autoindent_mode(
4059 &mut self,
4060 text: &str,
4061 autoindent_mode: Option<AutoindentMode>,
4062 window: &mut Window,
4063 cx: &mut Context<Self>,
4064 ) {
4065 if self.read_only(cx) {
4066 return;
4067 }
4068
4069 let text: Arc<str> = text.into();
4070 self.transact(window, cx, |this, window, cx| {
4071 let old_selections = this.selections.all_adjusted(cx);
4072 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4073 let anchors = {
4074 let snapshot = buffer.read(cx);
4075 old_selections
4076 .iter()
4077 .map(|s| {
4078 let anchor = snapshot.anchor_after(s.head());
4079 s.map(|_| anchor)
4080 })
4081 .collect::<Vec<_>>()
4082 };
4083 buffer.edit(
4084 old_selections
4085 .iter()
4086 .map(|s| (s.start..s.end, text.clone())),
4087 autoindent_mode,
4088 cx,
4089 );
4090 anchors
4091 });
4092
4093 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4094 s.select_anchors(selection_anchors);
4095 });
4096
4097 cx.notify();
4098 });
4099 }
4100
4101 fn trigger_completion_on_input(
4102 &mut self,
4103 text: &str,
4104 trigger_in_words: bool,
4105 window: &mut Window,
4106 cx: &mut Context<Self>,
4107 ) {
4108 let ignore_completion_provider = self
4109 .context_menu
4110 .borrow()
4111 .as_ref()
4112 .map(|menu| match menu {
4113 CodeContextMenu::Completions(completions_menu) => {
4114 completions_menu.ignore_completion_provider
4115 }
4116 CodeContextMenu::CodeActions(_) => false,
4117 })
4118 .unwrap_or(false);
4119
4120 if ignore_completion_provider {
4121 self.show_word_completions(&ShowWordCompletions, window, cx);
4122 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
4123 self.show_completions(
4124 &ShowCompletions {
4125 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4126 },
4127 window,
4128 cx,
4129 );
4130 } else {
4131 self.hide_context_menu(window, cx);
4132 }
4133 }
4134
4135 fn is_completion_trigger(
4136 &self,
4137 text: &str,
4138 trigger_in_words: bool,
4139 cx: &mut Context<Self>,
4140 ) -> bool {
4141 let position = self.selections.newest_anchor().head();
4142 let multibuffer = self.buffer.read(cx);
4143 let Some(buffer) = position
4144 .buffer_id
4145 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4146 else {
4147 return false;
4148 };
4149
4150 if let Some(completion_provider) = &self.completion_provider {
4151 completion_provider.is_completion_trigger(
4152 &buffer,
4153 position.text_anchor,
4154 text,
4155 trigger_in_words,
4156 cx,
4157 )
4158 } else {
4159 false
4160 }
4161 }
4162
4163 /// If any empty selections is touching the start of its innermost containing autoclose
4164 /// region, expand it to select the brackets.
4165 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4166 let selections = self.selections.all::<usize>(cx);
4167 let buffer = self.buffer.read(cx).read(cx);
4168 let new_selections = self
4169 .selections_with_autoclose_regions(selections, &buffer)
4170 .map(|(mut selection, region)| {
4171 if !selection.is_empty() {
4172 return selection;
4173 }
4174
4175 if let Some(region) = region {
4176 let mut range = region.range.to_offset(&buffer);
4177 if selection.start == range.start && range.start >= region.pair.start.len() {
4178 range.start -= region.pair.start.len();
4179 if buffer.contains_str_at(range.start, ®ion.pair.start)
4180 && buffer.contains_str_at(range.end, ®ion.pair.end)
4181 {
4182 range.end += region.pair.end.len();
4183 selection.start = range.start;
4184 selection.end = range.end;
4185
4186 return selection;
4187 }
4188 }
4189 }
4190
4191 let always_treat_brackets_as_autoclosed = buffer
4192 .language_settings_at(selection.start, cx)
4193 .always_treat_brackets_as_autoclosed;
4194
4195 if !always_treat_brackets_as_autoclosed {
4196 return selection;
4197 }
4198
4199 if let Some(scope) = buffer.language_scope_at(selection.start) {
4200 for (pair, enabled) in scope.brackets() {
4201 if !enabled || !pair.close {
4202 continue;
4203 }
4204
4205 if buffer.contains_str_at(selection.start, &pair.end) {
4206 let pair_start_len = pair.start.len();
4207 if buffer.contains_str_at(
4208 selection.start.saturating_sub(pair_start_len),
4209 &pair.start,
4210 ) {
4211 selection.start -= pair_start_len;
4212 selection.end += pair.end.len();
4213
4214 return selection;
4215 }
4216 }
4217 }
4218 }
4219
4220 selection
4221 })
4222 .collect();
4223
4224 drop(buffer);
4225 self.change_selections(None, window, cx, |selections| {
4226 selections.select(new_selections)
4227 });
4228 }
4229
4230 /// Iterate the given selections, and for each one, find the smallest surrounding
4231 /// autoclose region. This uses the ordering of the selections and the autoclose
4232 /// regions to avoid repeated comparisons.
4233 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4234 &'a self,
4235 selections: impl IntoIterator<Item = Selection<D>>,
4236 buffer: &'a MultiBufferSnapshot,
4237 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4238 let mut i = 0;
4239 let mut regions = self.autoclose_regions.as_slice();
4240 selections.into_iter().map(move |selection| {
4241 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4242
4243 let mut enclosing = None;
4244 while let Some(pair_state) = regions.get(i) {
4245 if pair_state.range.end.to_offset(buffer) < range.start {
4246 regions = ®ions[i + 1..];
4247 i = 0;
4248 } else if pair_state.range.start.to_offset(buffer) > range.end {
4249 break;
4250 } else {
4251 if pair_state.selection_id == selection.id {
4252 enclosing = Some(pair_state);
4253 }
4254 i += 1;
4255 }
4256 }
4257
4258 (selection, enclosing)
4259 })
4260 }
4261
4262 /// Remove any autoclose regions that no longer contain their selection.
4263 fn invalidate_autoclose_regions(
4264 &mut self,
4265 mut selections: &[Selection<Anchor>],
4266 buffer: &MultiBufferSnapshot,
4267 ) {
4268 self.autoclose_regions.retain(|state| {
4269 let mut i = 0;
4270 while let Some(selection) = selections.get(i) {
4271 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4272 selections = &selections[1..];
4273 continue;
4274 }
4275 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4276 break;
4277 }
4278 if selection.id == state.selection_id {
4279 return true;
4280 } else {
4281 i += 1;
4282 }
4283 }
4284 false
4285 });
4286 }
4287
4288 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4289 let offset = position.to_offset(buffer);
4290 let (word_range, kind) = buffer.surrounding_word(offset, true);
4291 if offset > word_range.start && kind == Some(CharKind::Word) {
4292 Some(
4293 buffer
4294 .text_for_range(word_range.start..offset)
4295 .collect::<String>(),
4296 )
4297 } else {
4298 None
4299 }
4300 }
4301
4302 pub fn toggle_inline_values(
4303 &mut self,
4304 _: &ToggleInlineValues,
4305 _: &mut Window,
4306 cx: &mut Context<Self>,
4307 ) {
4308 self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
4309
4310 self.refresh_inline_values(cx);
4311 }
4312
4313 pub fn toggle_inlay_hints(
4314 &mut self,
4315 _: &ToggleInlayHints,
4316 _: &mut Window,
4317 cx: &mut Context<Self>,
4318 ) {
4319 self.refresh_inlay_hints(
4320 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4321 cx,
4322 );
4323 }
4324
4325 pub fn inlay_hints_enabled(&self) -> bool {
4326 self.inlay_hint_cache.enabled
4327 }
4328
4329 pub fn inline_values_enabled(&self) -> bool {
4330 self.inline_value_cache.enabled
4331 }
4332
4333 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4334 if self.semantics_provider.is_none() || !self.mode.is_full() {
4335 return;
4336 }
4337
4338 let reason_description = reason.description();
4339 let ignore_debounce = matches!(
4340 reason,
4341 InlayHintRefreshReason::SettingsChange(_)
4342 | InlayHintRefreshReason::Toggle(_)
4343 | InlayHintRefreshReason::ExcerptsRemoved(_)
4344 | InlayHintRefreshReason::ModifiersChanged(_)
4345 );
4346 let (invalidate_cache, required_languages) = match reason {
4347 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4348 match self.inlay_hint_cache.modifiers_override(enabled) {
4349 Some(enabled) => {
4350 if enabled {
4351 (InvalidationStrategy::RefreshRequested, None)
4352 } else {
4353 self.splice_inlays(
4354 &self
4355 .visible_inlay_hints(cx)
4356 .iter()
4357 .map(|inlay| inlay.id)
4358 .collect::<Vec<InlayId>>(),
4359 Vec::new(),
4360 cx,
4361 );
4362 return;
4363 }
4364 }
4365 None => return,
4366 }
4367 }
4368 InlayHintRefreshReason::Toggle(enabled) => {
4369 if self.inlay_hint_cache.toggle(enabled) {
4370 if enabled {
4371 (InvalidationStrategy::RefreshRequested, None)
4372 } else {
4373 self.splice_inlays(
4374 &self
4375 .visible_inlay_hints(cx)
4376 .iter()
4377 .map(|inlay| inlay.id)
4378 .collect::<Vec<InlayId>>(),
4379 Vec::new(),
4380 cx,
4381 );
4382 return;
4383 }
4384 } else {
4385 return;
4386 }
4387 }
4388 InlayHintRefreshReason::SettingsChange(new_settings) => {
4389 match self.inlay_hint_cache.update_settings(
4390 &self.buffer,
4391 new_settings,
4392 self.visible_inlay_hints(cx),
4393 cx,
4394 ) {
4395 ControlFlow::Break(Some(InlaySplice {
4396 to_remove,
4397 to_insert,
4398 })) => {
4399 self.splice_inlays(&to_remove, to_insert, cx);
4400 return;
4401 }
4402 ControlFlow::Break(None) => return,
4403 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4404 }
4405 }
4406 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4407 if let Some(InlaySplice {
4408 to_remove,
4409 to_insert,
4410 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4411 {
4412 self.splice_inlays(&to_remove, to_insert, cx);
4413 }
4414 self.display_map.update(cx, |display_map, _| {
4415 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4416 });
4417 return;
4418 }
4419 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4420 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4421 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4422 }
4423 InlayHintRefreshReason::RefreshRequested => {
4424 (InvalidationStrategy::RefreshRequested, None)
4425 }
4426 };
4427
4428 if let Some(InlaySplice {
4429 to_remove,
4430 to_insert,
4431 }) = self.inlay_hint_cache.spawn_hint_refresh(
4432 reason_description,
4433 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4434 invalidate_cache,
4435 ignore_debounce,
4436 cx,
4437 ) {
4438 self.splice_inlays(&to_remove, to_insert, cx);
4439 }
4440 }
4441
4442 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4443 self.display_map
4444 .read(cx)
4445 .current_inlays()
4446 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4447 .cloned()
4448 .collect()
4449 }
4450
4451 pub fn excerpts_for_inlay_hints_query(
4452 &self,
4453 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4454 cx: &mut Context<Editor>,
4455 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4456 let Some(project) = self.project.as_ref() else {
4457 return HashMap::default();
4458 };
4459 let project = project.read(cx);
4460 let multi_buffer = self.buffer().read(cx);
4461 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4462 let multi_buffer_visible_start = self
4463 .scroll_manager
4464 .anchor()
4465 .anchor
4466 .to_point(&multi_buffer_snapshot);
4467 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4468 multi_buffer_visible_start
4469 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4470 Bias::Left,
4471 );
4472 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4473 multi_buffer_snapshot
4474 .range_to_buffer_ranges(multi_buffer_visible_range)
4475 .into_iter()
4476 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4477 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4478 let buffer_file = project::File::from_dyn(buffer.file())?;
4479 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4480 let worktree_entry = buffer_worktree
4481 .read(cx)
4482 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4483 if worktree_entry.is_ignored {
4484 return None;
4485 }
4486
4487 let language = buffer.language()?;
4488 if let Some(restrict_to_languages) = restrict_to_languages {
4489 if !restrict_to_languages.contains(language) {
4490 return None;
4491 }
4492 }
4493 Some((
4494 excerpt_id,
4495 (
4496 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4497 buffer.version().clone(),
4498 excerpt_visible_range,
4499 ),
4500 ))
4501 })
4502 .collect()
4503 }
4504
4505 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4506 TextLayoutDetails {
4507 text_system: window.text_system().clone(),
4508 editor_style: self.style.clone().unwrap(),
4509 rem_size: window.rem_size(),
4510 scroll_anchor: self.scroll_manager.anchor(),
4511 visible_rows: self.visible_line_count(),
4512 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4513 }
4514 }
4515
4516 pub fn splice_inlays(
4517 &self,
4518 to_remove: &[InlayId],
4519 to_insert: Vec<Inlay>,
4520 cx: &mut Context<Self>,
4521 ) {
4522 self.display_map.update(cx, |display_map, cx| {
4523 display_map.splice_inlays(to_remove, to_insert, cx)
4524 });
4525 cx.notify();
4526 }
4527
4528 fn trigger_on_type_formatting(
4529 &self,
4530 input: String,
4531 window: &mut Window,
4532 cx: &mut Context<Self>,
4533 ) -> Option<Task<Result<()>>> {
4534 if input.len() != 1 {
4535 return None;
4536 }
4537
4538 let project = self.project.as_ref()?;
4539 let position = self.selections.newest_anchor().head();
4540 let (buffer, buffer_position) = self
4541 .buffer
4542 .read(cx)
4543 .text_anchor_for_position(position, cx)?;
4544
4545 let settings = language_settings::language_settings(
4546 buffer
4547 .read(cx)
4548 .language_at(buffer_position)
4549 .map(|l| l.name()),
4550 buffer.read(cx).file(),
4551 cx,
4552 );
4553 if !settings.use_on_type_format {
4554 return None;
4555 }
4556
4557 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4558 // hence we do LSP request & edit on host side only — add formats to host's history.
4559 let push_to_lsp_host_history = true;
4560 // If this is not the host, append its history with new edits.
4561 let push_to_client_history = project.read(cx).is_via_collab();
4562
4563 let on_type_formatting = project.update(cx, |project, cx| {
4564 project.on_type_format(
4565 buffer.clone(),
4566 buffer_position,
4567 input,
4568 push_to_lsp_host_history,
4569 cx,
4570 )
4571 });
4572 Some(cx.spawn_in(window, async move |editor, cx| {
4573 if let Some(transaction) = on_type_formatting.await? {
4574 if push_to_client_history {
4575 buffer
4576 .update(cx, |buffer, _| {
4577 buffer.push_transaction(transaction, Instant::now());
4578 buffer.finalize_last_transaction();
4579 })
4580 .ok();
4581 }
4582 editor.update(cx, |editor, cx| {
4583 editor.refresh_document_highlights(cx);
4584 })?;
4585 }
4586 Ok(())
4587 }))
4588 }
4589
4590 pub fn show_word_completions(
4591 &mut self,
4592 _: &ShowWordCompletions,
4593 window: &mut Window,
4594 cx: &mut Context<Self>,
4595 ) {
4596 self.open_completions_menu(true, None, window, cx);
4597 }
4598
4599 pub fn show_completions(
4600 &mut self,
4601 options: &ShowCompletions,
4602 window: &mut Window,
4603 cx: &mut Context<Self>,
4604 ) {
4605 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4606 }
4607
4608 fn open_completions_menu(
4609 &mut self,
4610 ignore_completion_provider: bool,
4611 trigger: Option<&str>,
4612 window: &mut Window,
4613 cx: &mut Context<Self>,
4614 ) {
4615 if self.pending_rename.is_some() {
4616 return;
4617 }
4618 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4619 return;
4620 }
4621
4622 let position = self.selections.newest_anchor().head();
4623 if position.diff_base_anchor.is_some() {
4624 return;
4625 }
4626 let (buffer, buffer_position) =
4627 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4628 output
4629 } else {
4630 return;
4631 };
4632 let buffer_snapshot = buffer.read(cx).snapshot();
4633 let show_completion_documentation = buffer_snapshot
4634 .settings_at(buffer_position, cx)
4635 .show_completion_documentation;
4636
4637 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4638
4639 let trigger_kind = match trigger {
4640 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4641 CompletionTriggerKind::TRIGGER_CHARACTER
4642 }
4643 _ => CompletionTriggerKind::INVOKED,
4644 };
4645 let completion_context = CompletionContext {
4646 trigger_character: trigger.and_then(|trigger| {
4647 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4648 Some(String::from(trigger))
4649 } else {
4650 None
4651 }
4652 }),
4653 trigger_kind,
4654 };
4655
4656 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4657 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4658 let word_to_exclude = buffer_snapshot
4659 .text_for_range(old_range.clone())
4660 .collect::<String>();
4661 (
4662 buffer_snapshot.anchor_before(old_range.start)
4663 ..buffer_snapshot.anchor_after(old_range.end),
4664 Some(word_to_exclude),
4665 )
4666 } else {
4667 (buffer_position..buffer_position, None)
4668 };
4669
4670 let completion_settings = language_settings(
4671 buffer_snapshot
4672 .language_at(buffer_position)
4673 .map(|language| language.name()),
4674 buffer_snapshot.file(),
4675 cx,
4676 )
4677 .completions;
4678
4679 // The document can be large, so stay in reasonable bounds when searching for words,
4680 // otherwise completion pop-up might be slow to appear.
4681 const WORD_LOOKUP_ROWS: u32 = 5_000;
4682 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4683 let min_word_search = buffer_snapshot.clip_point(
4684 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4685 Bias::Left,
4686 );
4687 let max_word_search = buffer_snapshot.clip_point(
4688 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4689 Bias::Right,
4690 );
4691 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4692 ..buffer_snapshot.point_to_offset(max_word_search);
4693
4694 let provider = self
4695 .completion_provider
4696 .as_ref()
4697 .filter(|_| !ignore_completion_provider);
4698 let skip_digits = query
4699 .as_ref()
4700 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4701
4702 let (mut words, provided_completions) = match provider {
4703 Some(provider) => {
4704 let completions = provider.completions(
4705 position.excerpt_id,
4706 &buffer,
4707 buffer_position,
4708 completion_context,
4709 window,
4710 cx,
4711 );
4712
4713 let words = match completion_settings.words {
4714 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4715 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4716 .background_spawn(async move {
4717 buffer_snapshot.words_in_range(WordsQuery {
4718 fuzzy_contents: None,
4719 range: word_search_range,
4720 skip_digits,
4721 })
4722 }),
4723 };
4724
4725 (words, completions)
4726 }
4727 None => (
4728 cx.background_spawn(async move {
4729 buffer_snapshot.words_in_range(WordsQuery {
4730 fuzzy_contents: None,
4731 range: word_search_range,
4732 skip_digits,
4733 })
4734 }),
4735 Task::ready(Ok(None)),
4736 ),
4737 };
4738
4739 let sort_completions = provider
4740 .as_ref()
4741 .map_or(false, |provider| provider.sort_completions());
4742
4743 let filter_completions = provider
4744 .as_ref()
4745 .map_or(true, |provider| provider.filter_completions());
4746
4747 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
4748
4749 let id = post_inc(&mut self.next_completion_id);
4750 let task = cx.spawn_in(window, async move |editor, cx| {
4751 async move {
4752 editor.update(cx, |this, _| {
4753 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4754 })?;
4755
4756 let mut completions = Vec::new();
4757 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4758 completions.extend(provided_completions);
4759 if completion_settings.words == WordsCompletionMode::Fallback {
4760 words = Task::ready(BTreeMap::default());
4761 }
4762 }
4763
4764 let mut words = words.await;
4765 if let Some(word_to_exclude) = &word_to_exclude {
4766 words.remove(word_to_exclude);
4767 }
4768 for lsp_completion in &completions {
4769 words.remove(&lsp_completion.new_text);
4770 }
4771 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4772 replace_range: old_range.clone(),
4773 new_text: word.clone(),
4774 label: CodeLabel::plain(word, None),
4775 icon_path: None,
4776 documentation: None,
4777 source: CompletionSource::BufferWord {
4778 word_range,
4779 resolved: false,
4780 },
4781 insert_text_mode: Some(InsertTextMode::AS_IS),
4782 confirm: None,
4783 }));
4784
4785 let menu = if completions.is_empty() {
4786 None
4787 } else {
4788 let mut menu = CompletionsMenu::new(
4789 id,
4790 sort_completions,
4791 show_completion_documentation,
4792 ignore_completion_provider,
4793 position,
4794 buffer.clone(),
4795 completions.into(),
4796 snippet_sort_order,
4797 );
4798
4799 menu.filter(
4800 if filter_completions {
4801 query.as_deref()
4802 } else {
4803 None
4804 },
4805 cx.background_executor().clone(),
4806 )
4807 .await;
4808
4809 menu.visible().then_some(menu)
4810 };
4811
4812 editor.update_in(cx, |editor, window, cx| {
4813 match editor.context_menu.borrow().as_ref() {
4814 None => {}
4815 Some(CodeContextMenu::Completions(prev_menu)) => {
4816 if prev_menu.id > id {
4817 return;
4818 }
4819 }
4820 _ => return,
4821 }
4822
4823 if editor.focus_handle.is_focused(window) && menu.is_some() {
4824 let mut menu = menu.unwrap();
4825 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4826
4827 *editor.context_menu.borrow_mut() =
4828 Some(CodeContextMenu::Completions(menu));
4829
4830 if editor.show_edit_predictions_in_menu() {
4831 editor.update_visible_inline_completion(window, cx);
4832 } else {
4833 editor.discard_inline_completion(false, cx);
4834 }
4835
4836 cx.notify();
4837 } else if editor.completion_tasks.len() <= 1 {
4838 // If there are no more completion tasks and the last menu was
4839 // empty, we should hide it.
4840 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4841 // If it was already hidden and we don't show inline
4842 // completions in the menu, we should also show the
4843 // inline-completion when available.
4844 if was_hidden && editor.show_edit_predictions_in_menu() {
4845 editor.update_visible_inline_completion(window, cx);
4846 }
4847 }
4848 })?;
4849
4850 anyhow::Ok(())
4851 }
4852 .log_err()
4853 .await
4854 });
4855
4856 self.completion_tasks.push((id, task));
4857 }
4858
4859 #[cfg(feature = "test-support")]
4860 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4861 let menu = self.context_menu.borrow();
4862 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4863 let completions = menu.completions.borrow();
4864 Some(completions.to_vec())
4865 } else {
4866 None
4867 }
4868 }
4869
4870 pub fn confirm_completion(
4871 &mut self,
4872 action: &ConfirmCompletion,
4873 window: &mut Window,
4874 cx: &mut Context<Self>,
4875 ) -> Option<Task<Result<()>>> {
4876 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4877 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4878 }
4879
4880 pub fn confirm_completion_insert(
4881 &mut self,
4882 _: &ConfirmCompletionInsert,
4883 window: &mut Window,
4884 cx: &mut Context<Self>,
4885 ) -> Option<Task<Result<()>>> {
4886 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4887 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4888 }
4889
4890 pub fn confirm_completion_replace(
4891 &mut self,
4892 _: &ConfirmCompletionReplace,
4893 window: &mut Window,
4894 cx: &mut Context<Self>,
4895 ) -> Option<Task<Result<()>>> {
4896 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4897 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4898 }
4899
4900 pub fn compose_completion(
4901 &mut self,
4902 action: &ComposeCompletion,
4903 window: &mut Window,
4904 cx: &mut Context<Self>,
4905 ) -> Option<Task<Result<()>>> {
4906 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4907 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4908 }
4909
4910 fn do_completion(
4911 &mut self,
4912 item_ix: Option<usize>,
4913 intent: CompletionIntent,
4914 window: &mut Window,
4915 cx: &mut Context<Editor>,
4916 ) -> Option<Task<Result<()>>> {
4917 use language::ToOffset as _;
4918
4919 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4920 else {
4921 return None;
4922 };
4923
4924 let candidate_id = {
4925 let entries = completions_menu.entries.borrow();
4926 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4927 if self.show_edit_predictions_in_menu() {
4928 self.discard_inline_completion(true, cx);
4929 }
4930 mat.candidate_id
4931 };
4932
4933 let buffer_handle = completions_menu.buffer;
4934 let completion = completions_menu
4935 .completions
4936 .borrow()
4937 .get(candidate_id)?
4938 .clone();
4939 cx.stop_propagation();
4940
4941 let snippet;
4942 let new_text;
4943 if completion.is_snippet() {
4944 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4945 new_text = snippet.as_ref().unwrap().text.clone();
4946 } else {
4947 snippet = None;
4948 new_text = completion.new_text.clone();
4949 };
4950
4951 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4952 let buffer = buffer_handle.read(cx);
4953 let snapshot = self.buffer.read(cx).snapshot(cx);
4954 let replace_range_multibuffer = {
4955 let excerpt = snapshot
4956 .excerpt_containing(self.selections.newest_anchor().range())
4957 .unwrap();
4958 let multibuffer_anchor = snapshot
4959 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4960 .unwrap()
4961 ..snapshot
4962 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4963 .unwrap();
4964 multibuffer_anchor.start.to_offset(&snapshot)
4965 ..multibuffer_anchor.end.to_offset(&snapshot)
4966 };
4967 let newest_anchor = self.selections.newest_anchor();
4968 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4969 return None;
4970 }
4971
4972 let old_text = buffer
4973 .text_for_range(replace_range.clone())
4974 .collect::<String>();
4975 let lookbehind = newest_anchor
4976 .start
4977 .text_anchor
4978 .to_offset(buffer)
4979 .saturating_sub(replace_range.start);
4980 let lookahead = replace_range
4981 .end
4982 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4983 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4984 let suffix = &old_text[lookbehind.min(old_text.len())..];
4985
4986 let selections = self.selections.all::<usize>(cx);
4987 let mut ranges = Vec::new();
4988 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4989
4990 for selection in &selections {
4991 let range = if selection.id == newest_anchor.id {
4992 replace_range_multibuffer.clone()
4993 } else {
4994 let mut range = selection.range();
4995
4996 // if prefix is present, don't duplicate it
4997 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4998 range.start = range.start.saturating_sub(lookbehind);
4999
5000 // if suffix is also present, mimic the newest cursor and replace it
5001 if selection.id != newest_anchor.id
5002 && snapshot.contains_str_at(range.end, suffix)
5003 {
5004 range.end += lookahead;
5005 }
5006 }
5007 range
5008 };
5009
5010 ranges.push(range);
5011
5012 if !self.linked_edit_ranges.is_empty() {
5013 let start_anchor = snapshot.anchor_before(selection.head());
5014 let end_anchor = snapshot.anchor_after(selection.tail());
5015 if let Some(ranges) = self
5016 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
5017 {
5018 for (buffer, edits) in ranges {
5019 linked_edits
5020 .entry(buffer.clone())
5021 .or_default()
5022 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
5023 }
5024 }
5025 }
5026 }
5027
5028 cx.emit(EditorEvent::InputHandled {
5029 utf16_range_to_replace: None,
5030 text: new_text.clone().into(),
5031 });
5032
5033 self.transact(window, cx, |this, window, cx| {
5034 if let Some(mut snippet) = snippet {
5035 snippet.text = new_text.to_string();
5036 this.insert_snippet(&ranges, snippet, window, cx).log_err();
5037 } else {
5038 this.buffer.update(cx, |buffer, cx| {
5039 let auto_indent = match completion.insert_text_mode {
5040 Some(InsertTextMode::AS_IS) => None,
5041 _ => this.autoindent_mode.clone(),
5042 };
5043 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
5044 buffer.edit(edits, auto_indent, cx);
5045 });
5046 }
5047 for (buffer, edits) in linked_edits {
5048 buffer.update(cx, |buffer, cx| {
5049 let snapshot = buffer.snapshot();
5050 let edits = edits
5051 .into_iter()
5052 .map(|(range, text)| {
5053 use text::ToPoint as TP;
5054 let end_point = TP::to_point(&range.end, &snapshot);
5055 let start_point = TP::to_point(&range.start, &snapshot);
5056 (start_point..end_point, text)
5057 })
5058 .sorted_by_key(|(range, _)| range.start);
5059 buffer.edit(edits, None, cx);
5060 })
5061 }
5062
5063 this.refresh_inline_completion(true, false, window, cx);
5064 });
5065
5066 let show_new_completions_on_confirm = completion
5067 .confirm
5068 .as_ref()
5069 .map_or(false, |confirm| confirm(intent, window, cx));
5070 if show_new_completions_on_confirm {
5071 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
5072 }
5073
5074 let provider = self.completion_provider.as_ref()?;
5075 drop(completion);
5076 let apply_edits = provider.apply_additional_edits_for_completion(
5077 buffer_handle,
5078 completions_menu.completions.clone(),
5079 candidate_id,
5080 true,
5081 cx,
5082 );
5083
5084 let editor_settings = EditorSettings::get_global(cx);
5085 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
5086 // After the code completion is finished, users often want to know what signatures are needed.
5087 // so we should automatically call signature_help
5088 self.show_signature_help(&ShowSignatureHelp, window, cx);
5089 }
5090
5091 Some(cx.foreground_executor().spawn(async move {
5092 apply_edits.await?;
5093 Ok(())
5094 }))
5095 }
5096
5097 pub fn toggle_code_actions(
5098 &mut self,
5099 action: &ToggleCodeActions,
5100 window: &mut Window,
5101 cx: &mut Context<Self>,
5102 ) {
5103 let quick_launch = action.quick_launch;
5104 let mut context_menu = self.context_menu.borrow_mut();
5105 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
5106 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
5107 // Toggle if we're selecting the same one
5108 *context_menu = None;
5109 cx.notify();
5110 return;
5111 } else {
5112 // Otherwise, clear it and start a new one
5113 *context_menu = None;
5114 cx.notify();
5115 }
5116 }
5117 drop(context_menu);
5118 let snapshot = self.snapshot(window, cx);
5119 let deployed_from_indicator = action.deployed_from_indicator;
5120 let mut task = self.code_actions_task.take();
5121 let action = action.clone();
5122 cx.spawn_in(window, async move |editor, cx| {
5123 while let Some(prev_task) = task {
5124 prev_task.await.log_err();
5125 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
5126 }
5127
5128 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
5129 if editor.focus_handle.is_focused(window) {
5130 let multibuffer_point = action
5131 .deployed_from_indicator
5132 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
5133 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
5134 let (buffer, buffer_row) = snapshot
5135 .buffer_snapshot
5136 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
5137 .and_then(|(buffer_snapshot, range)| {
5138 editor
5139 .buffer
5140 .read(cx)
5141 .buffer(buffer_snapshot.remote_id())
5142 .map(|buffer| (buffer, range.start.row))
5143 })?;
5144 let (_, code_actions) = editor
5145 .available_code_actions
5146 .clone()
5147 .and_then(|(location, code_actions)| {
5148 let snapshot = location.buffer.read(cx).snapshot();
5149 let point_range = location.range.to_point(&snapshot);
5150 let point_range = point_range.start.row..=point_range.end.row;
5151 if point_range.contains(&buffer_row) {
5152 Some((location, code_actions))
5153 } else {
5154 None
5155 }
5156 })
5157 .unzip();
5158 let buffer_id = buffer.read(cx).remote_id();
5159 let tasks = editor
5160 .tasks
5161 .get(&(buffer_id, buffer_row))
5162 .map(|t| Arc::new(t.to_owned()));
5163 if tasks.is_none() && code_actions.is_none() {
5164 return None;
5165 }
5166
5167 editor.completion_tasks.clear();
5168 editor.discard_inline_completion(false, cx);
5169 let task_context =
5170 tasks
5171 .as_ref()
5172 .zip(editor.project.clone())
5173 .map(|(tasks, project)| {
5174 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5175 });
5176
5177 Some(cx.spawn_in(window, async move |editor, cx| {
5178 let task_context = match task_context {
5179 Some(task_context) => task_context.await,
5180 None => None,
5181 };
5182 let resolved_tasks =
5183 tasks
5184 .zip(task_context.clone())
5185 .map(|(tasks, task_context)| ResolvedTasks {
5186 templates: tasks.resolve(&task_context).collect(),
5187 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5188 multibuffer_point.row,
5189 tasks.column,
5190 )),
5191 });
5192 let spawn_straight_away = quick_launch
5193 && resolved_tasks
5194 .as_ref()
5195 .map_or(false, |tasks| tasks.templates.len() == 1)
5196 && code_actions
5197 .as_ref()
5198 .map_or(true, |actions| actions.is_empty());
5199 let debug_scenarios = editor.update(cx, |editor, cx| {
5200 if cx.has_flag::<DebuggerFeatureFlag>() {
5201 maybe!({
5202 let project = editor.project.as_ref()?;
5203 let dap_store = project.read(cx).dap_store();
5204 let mut scenarios = vec![];
5205 let resolved_tasks = resolved_tasks.as_ref()?;
5206 let debug_adapter: SharedString = buffer
5207 .read(cx)
5208 .language()?
5209 .context_provider()?
5210 .debug_adapter()?
5211 .into();
5212 dap_store.update(cx, |this, cx| {
5213 for (_, task) in &resolved_tasks.templates {
5214 if let Some(scenario) = this
5215 .debug_scenario_for_build_task(
5216 task.resolved.clone(),
5217 SharedString::from(
5218 task.original_task().label.clone(),
5219 ),
5220 debug_adapter.clone(),
5221 cx,
5222 )
5223 {
5224 scenarios.push(scenario);
5225 }
5226 }
5227 });
5228 Some(scenarios)
5229 })
5230 .unwrap_or_default()
5231 } else {
5232 vec![]
5233 }
5234 })?;
5235 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5236 *editor.context_menu.borrow_mut() =
5237 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5238 buffer,
5239 actions: CodeActionContents::new(
5240 resolved_tasks,
5241 code_actions,
5242 debug_scenarios,
5243 task_context.unwrap_or_default(),
5244 ),
5245 selected_item: Default::default(),
5246 scroll_handle: UniformListScrollHandle::default(),
5247 deployed_from_indicator,
5248 }));
5249 if spawn_straight_away {
5250 if let Some(task) = editor.confirm_code_action(
5251 &ConfirmCodeAction { item_ix: Some(0) },
5252 window,
5253 cx,
5254 ) {
5255 cx.notify();
5256 return task;
5257 }
5258 }
5259 cx.notify();
5260 Task::ready(Ok(()))
5261 }) {
5262 task.await
5263 } else {
5264 Ok(())
5265 }
5266 }))
5267 } else {
5268 Some(Task::ready(Ok(())))
5269 }
5270 })?;
5271 if let Some(task) = spawned_test_task {
5272 task.await?;
5273 }
5274
5275 Ok::<_, anyhow::Error>(())
5276 })
5277 .detach_and_log_err(cx);
5278 }
5279
5280 pub fn confirm_code_action(
5281 &mut self,
5282 action: &ConfirmCodeAction,
5283 window: &mut Window,
5284 cx: &mut Context<Self>,
5285 ) -> Option<Task<Result<()>>> {
5286 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5287
5288 let actions_menu =
5289 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5290 menu
5291 } else {
5292 return None;
5293 };
5294
5295 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5296 let action = actions_menu.actions.get(action_ix)?;
5297 let title = action.label();
5298 let buffer = actions_menu.buffer;
5299 let workspace = self.workspace()?;
5300
5301 match action {
5302 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5303 workspace.update(cx, |workspace, cx| {
5304 workspace.schedule_resolved_task(
5305 task_source_kind,
5306 resolved_task,
5307 false,
5308 window,
5309 cx,
5310 );
5311
5312 Some(Task::ready(Ok(())))
5313 })
5314 }
5315 CodeActionsItem::CodeAction {
5316 excerpt_id,
5317 action,
5318 provider,
5319 } => {
5320 let apply_code_action =
5321 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5322 let workspace = workspace.downgrade();
5323 Some(cx.spawn_in(window, async move |editor, cx| {
5324 let project_transaction = apply_code_action.await?;
5325 Self::open_project_transaction(
5326 &editor,
5327 workspace,
5328 project_transaction,
5329 title,
5330 cx,
5331 )
5332 .await
5333 }))
5334 }
5335 CodeActionsItem::DebugScenario(scenario) => {
5336 let context = actions_menu.actions.context.clone();
5337
5338 workspace.update(cx, |workspace, cx| {
5339 workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
5340 });
5341 Some(Task::ready(Ok(())))
5342 }
5343 }
5344 }
5345
5346 pub async fn open_project_transaction(
5347 this: &WeakEntity<Editor>,
5348 workspace: WeakEntity<Workspace>,
5349 transaction: ProjectTransaction,
5350 title: String,
5351 cx: &mut AsyncWindowContext,
5352 ) -> Result<()> {
5353 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5354 cx.update(|_, cx| {
5355 entries.sort_unstable_by_key(|(buffer, _)| {
5356 buffer.read(cx).file().map(|f| f.path().clone())
5357 });
5358 })?;
5359
5360 // If the project transaction's edits are all contained within this editor, then
5361 // avoid opening a new editor to display them.
5362
5363 if let Some((buffer, transaction)) = entries.first() {
5364 if entries.len() == 1 {
5365 let excerpt = this.update(cx, |editor, cx| {
5366 editor
5367 .buffer()
5368 .read(cx)
5369 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5370 })?;
5371 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5372 if excerpted_buffer == *buffer {
5373 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5374 let excerpt_range = excerpt_range.to_offset(buffer);
5375 buffer
5376 .edited_ranges_for_transaction::<usize>(transaction)
5377 .all(|range| {
5378 excerpt_range.start <= range.start
5379 && excerpt_range.end >= range.end
5380 })
5381 })?;
5382
5383 if all_edits_within_excerpt {
5384 return Ok(());
5385 }
5386 }
5387 }
5388 }
5389 } else {
5390 return Ok(());
5391 }
5392
5393 let mut ranges_to_highlight = Vec::new();
5394 let excerpt_buffer = cx.new(|cx| {
5395 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5396 for (buffer_handle, transaction) in &entries {
5397 let edited_ranges = buffer_handle
5398 .read(cx)
5399 .edited_ranges_for_transaction::<Point>(transaction)
5400 .collect::<Vec<_>>();
5401 let (ranges, _) = multibuffer.set_excerpts_for_path(
5402 PathKey::for_buffer(buffer_handle, cx),
5403 buffer_handle.clone(),
5404 edited_ranges,
5405 DEFAULT_MULTIBUFFER_CONTEXT,
5406 cx,
5407 );
5408
5409 ranges_to_highlight.extend(ranges);
5410 }
5411 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5412 multibuffer
5413 })?;
5414
5415 workspace.update_in(cx, |workspace, window, cx| {
5416 let project = workspace.project().clone();
5417 let editor =
5418 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5419 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5420 editor.update(cx, |editor, cx| {
5421 editor.highlight_background::<Self>(
5422 &ranges_to_highlight,
5423 |theme| theme.editor_highlighted_line_background,
5424 cx,
5425 );
5426 });
5427 })?;
5428
5429 Ok(())
5430 }
5431
5432 pub fn clear_code_action_providers(&mut self) {
5433 self.code_action_providers.clear();
5434 self.available_code_actions.take();
5435 }
5436
5437 pub fn add_code_action_provider(
5438 &mut self,
5439 provider: Rc<dyn CodeActionProvider>,
5440 window: &mut Window,
5441 cx: &mut Context<Self>,
5442 ) {
5443 if self
5444 .code_action_providers
5445 .iter()
5446 .any(|existing_provider| existing_provider.id() == provider.id())
5447 {
5448 return;
5449 }
5450
5451 self.code_action_providers.push(provider);
5452 self.refresh_code_actions(window, cx);
5453 }
5454
5455 pub fn remove_code_action_provider(
5456 &mut self,
5457 id: Arc<str>,
5458 window: &mut Window,
5459 cx: &mut Context<Self>,
5460 ) {
5461 self.code_action_providers
5462 .retain(|provider| provider.id() != id);
5463 self.refresh_code_actions(window, cx);
5464 }
5465
5466 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5467 let newest_selection = self.selections.newest_anchor().clone();
5468 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5469 let buffer = self.buffer.read(cx);
5470 if newest_selection.head().diff_base_anchor.is_some() {
5471 return None;
5472 }
5473 let (start_buffer, start) =
5474 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5475 let (end_buffer, end) =
5476 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5477 if start_buffer != end_buffer {
5478 return None;
5479 }
5480
5481 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5482 cx.background_executor()
5483 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5484 .await;
5485
5486 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5487 let providers = this.code_action_providers.clone();
5488 let tasks = this
5489 .code_action_providers
5490 .iter()
5491 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5492 .collect::<Vec<_>>();
5493 (providers, tasks)
5494 })?;
5495
5496 let mut actions = Vec::new();
5497 for (provider, provider_actions) in
5498 providers.into_iter().zip(future::join_all(tasks).await)
5499 {
5500 if let Some(provider_actions) = provider_actions.log_err() {
5501 actions.extend(provider_actions.into_iter().map(|action| {
5502 AvailableCodeAction {
5503 excerpt_id: newest_selection.start.excerpt_id,
5504 action,
5505 provider: provider.clone(),
5506 }
5507 }));
5508 }
5509 }
5510
5511 this.update(cx, |this, cx| {
5512 this.available_code_actions = if actions.is_empty() {
5513 None
5514 } else {
5515 Some((
5516 Location {
5517 buffer: start_buffer,
5518 range: start..end,
5519 },
5520 actions.into(),
5521 ))
5522 };
5523 cx.notify();
5524 })
5525 }));
5526 None
5527 }
5528
5529 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5530 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5531 self.show_git_blame_inline = false;
5532
5533 self.show_git_blame_inline_delay_task =
5534 Some(cx.spawn_in(window, async move |this, cx| {
5535 cx.background_executor().timer(delay).await;
5536
5537 this.update(cx, |this, cx| {
5538 this.show_git_blame_inline = true;
5539 cx.notify();
5540 })
5541 .log_err();
5542 }));
5543 }
5544 }
5545
5546 fn show_blame_popover(
5547 &mut self,
5548 blame_entry: &BlameEntry,
5549 position: gpui::Point<Pixels>,
5550 cx: &mut Context<Self>,
5551 ) {
5552 if let Some(state) = &mut self.inline_blame_popover {
5553 state.hide_task.take();
5554 cx.notify();
5555 } else {
5556 let delay = EditorSettings::get_global(cx).hover_popover_delay;
5557 let show_task = cx.spawn(async move |editor, cx| {
5558 cx.background_executor()
5559 .timer(std::time::Duration::from_millis(delay))
5560 .await;
5561 editor
5562 .update(cx, |editor, cx| {
5563 if let Some(state) = &mut editor.inline_blame_popover {
5564 state.show_task = None;
5565 cx.notify();
5566 }
5567 })
5568 .ok();
5569 });
5570 let Some(blame) = self.blame.as_ref() else {
5571 return;
5572 };
5573 let blame = blame.read(cx);
5574 let details = blame.details_for_entry(&blame_entry);
5575 let markdown = cx.new(|cx| {
5576 Markdown::new(
5577 details
5578 .as_ref()
5579 .map(|message| message.message.clone())
5580 .unwrap_or_default(),
5581 None,
5582 None,
5583 cx,
5584 )
5585 });
5586 self.inline_blame_popover = Some(InlineBlamePopover {
5587 position,
5588 show_task: Some(show_task),
5589 hide_task: None,
5590 popover_bounds: None,
5591 popover_state: InlineBlamePopoverState {
5592 scroll_handle: ScrollHandle::new(),
5593 commit_message: details,
5594 markdown,
5595 },
5596 });
5597 }
5598 }
5599
5600 fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
5601 if let Some(state) = &mut self.inline_blame_popover {
5602 if state.show_task.is_some() {
5603 self.inline_blame_popover.take();
5604 cx.notify();
5605 } else {
5606 let hide_task = cx.spawn(async move |editor, cx| {
5607 cx.background_executor()
5608 .timer(std::time::Duration::from_millis(100))
5609 .await;
5610 editor
5611 .update(cx, |editor, cx| {
5612 editor.inline_blame_popover.take();
5613 cx.notify();
5614 })
5615 .ok();
5616 });
5617 state.hide_task = Some(hide_task);
5618 }
5619 }
5620 }
5621
5622 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5623 if self.pending_rename.is_some() {
5624 return None;
5625 }
5626
5627 let provider = self.semantics_provider.clone()?;
5628 let buffer = self.buffer.read(cx);
5629 let newest_selection = self.selections.newest_anchor().clone();
5630 let cursor_position = newest_selection.head();
5631 let (cursor_buffer, cursor_buffer_position) =
5632 buffer.text_anchor_for_position(cursor_position, cx)?;
5633 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5634 if cursor_buffer != tail_buffer {
5635 return None;
5636 }
5637 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5638 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5639 cx.background_executor()
5640 .timer(Duration::from_millis(debounce))
5641 .await;
5642
5643 let highlights = if let Some(highlights) = cx
5644 .update(|cx| {
5645 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5646 })
5647 .ok()
5648 .flatten()
5649 {
5650 highlights.await.log_err()
5651 } else {
5652 None
5653 };
5654
5655 if let Some(highlights) = highlights {
5656 this.update(cx, |this, cx| {
5657 if this.pending_rename.is_some() {
5658 return;
5659 }
5660
5661 let buffer_id = cursor_position.buffer_id;
5662 let buffer = this.buffer.read(cx);
5663 if !buffer
5664 .text_anchor_for_position(cursor_position, cx)
5665 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5666 {
5667 return;
5668 }
5669
5670 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5671 let mut write_ranges = Vec::new();
5672 let mut read_ranges = Vec::new();
5673 for highlight in highlights {
5674 for (excerpt_id, excerpt_range) in
5675 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5676 {
5677 let start = highlight
5678 .range
5679 .start
5680 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5681 let end = highlight
5682 .range
5683 .end
5684 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5685 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5686 continue;
5687 }
5688
5689 let range = Anchor {
5690 buffer_id,
5691 excerpt_id,
5692 text_anchor: start,
5693 diff_base_anchor: None,
5694 }..Anchor {
5695 buffer_id,
5696 excerpt_id,
5697 text_anchor: end,
5698 diff_base_anchor: None,
5699 };
5700 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5701 write_ranges.push(range);
5702 } else {
5703 read_ranges.push(range);
5704 }
5705 }
5706 }
5707
5708 this.highlight_background::<DocumentHighlightRead>(
5709 &read_ranges,
5710 |theme| theme.editor_document_highlight_read_background,
5711 cx,
5712 );
5713 this.highlight_background::<DocumentHighlightWrite>(
5714 &write_ranges,
5715 |theme| theme.editor_document_highlight_write_background,
5716 cx,
5717 );
5718 cx.notify();
5719 })
5720 .log_err();
5721 }
5722 }));
5723 None
5724 }
5725
5726 fn prepare_highlight_query_from_selection(
5727 &mut self,
5728 cx: &mut Context<Editor>,
5729 ) -> Option<(String, Range<Anchor>)> {
5730 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5731 return None;
5732 }
5733 if !EditorSettings::get_global(cx).selection_highlight {
5734 return None;
5735 }
5736 if self.selections.count() != 1 || self.selections.line_mode {
5737 return None;
5738 }
5739 let selection = self.selections.newest::<Point>(cx);
5740 if selection.is_empty() || selection.start.row != selection.end.row {
5741 return None;
5742 }
5743 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5744 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5745 let query = multi_buffer_snapshot
5746 .text_for_range(selection_anchor_range.clone())
5747 .collect::<String>();
5748 if query.trim().is_empty() {
5749 return None;
5750 }
5751 Some((query, selection_anchor_range))
5752 }
5753
5754 fn update_selection_occurrence_highlights(
5755 &mut self,
5756 query_text: String,
5757 query_range: Range<Anchor>,
5758 multi_buffer_range_to_query: Range<Point>,
5759 use_debounce: bool,
5760 window: &mut Window,
5761 cx: &mut Context<Editor>,
5762 ) -> Task<()> {
5763 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5764 cx.spawn_in(window, async move |editor, cx| {
5765 if use_debounce {
5766 cx.background_executor()
5767 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5768 .await;
5769 }
5770 let match_task = cx.background_spawn(async move {
5771 let buffer_ranges = multi_buffer_snapshot
5772 .range_to_buffer_ranges(multi_buffer_range_to_query)
5773 .into_iter()
5774 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5775 let mut match_ranges = Vec::new();
5776 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5777 match_ranges.extend(
5778 project::search::SearchQuery::text(
5779 query_text.clone(),
5780 false,
5781 false,
5782 false,
5783 Default::default(),
5784 Default::default(),
5785 false,
5786 None,
5787 )
5788 .unwrap()
5789 .search(&buffer_snapshot, Some(search_range.clone()))
5790 .await
5791 .into_iter()
5792 .filter_map(|match_range| {
5793 let match_start = buffer_snapshot
5794 .anchor_after(search_range.start + match_range.start);
5795 let match_end =
5796 buffer_snapshot.anchor_before(search_range.start + match_range.end);
5797 let match_anchor_range = Anchor::range_in_buffer(
5798 excerpt_id,
5799 buffer_snapshot.remote_id(),
5800 match_start..match_end,
5801 );
5802 (match_anchor_range != query_range).then_some(match_anchor_range)
5803 }),
5804 );
5805 }
5806 match_ranges
5807 });
5808 let match_ranges = match_task.await;
5809 editor
5810 .update_in(cx, |editor, _, cx| {
5811 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5812 if !match_ranges.is_empty() {
5813 editor.highlight_background::<SelectedTextHighlight>(
5814 &match_ranges,
5815 |theme| theme.editor_document_highlight_bracket_background,
5816 cx,
5817 )
5818 }
5819 })
5820 .log_err();
5821 })
5822 }
5823
5824 fn refresh_selected_text_highlights(
5825 &mut self,
5826 on_buffer_edit: bool,
5827 window: &mut Window,
5828 cx: &mut Context<Editor>,
5829 ) {
5830 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5831 else {
5832 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5833 self.quick_selection_highlight_task.take();
5834 self.debounced_selection_highlight_task.take();
5835 return;
5836 };
5837 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5838 if on_buffer_edit
5839 || self
5840 .quick_selection_highlight_task
5841 .as_ref()
5842 .map_or(true, |(prev_anchor_range, _)| {
5843 prev_anchor_range != &query_range
5844 })
5845 {
5846 let multi_buffer_visible_start = self
5847 .scroll_manager
5848 .anchor()
5849 .anchor
5850 .to_point(&multi_buffer_snapshot);
5851 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5852 multi_buffer_visible_start
5853 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5854 Bias::Left,
5855 );
5856 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5857 self.quick_selection_highlight_task = Some((
5858 query_range.clone(),
5859 self.update_selection_occurrence_highlights(
5860 query_text.clone(),
5861 query_range.clone(),
5862 multi_buffer_visible_range,
5863 false,
5864 window,
5865 cx,
5866 ),
5867 ));
5868 }
5869 if on_buffer_edit
5870 || self
5871 .debounced_selection_highlight_task
5872 .as_ref()
5873 .map_or(true, |(prev_anchor_range, _)| {
5874 prev_anchor_range != &query_range
5875 })
5876 {
5877 let multi_buffer_start = multi_buffer_snapshot
5878 .anchor_before(0)
5879 .to_point(&multi_buffer_snapshot);
5880 let multi_buffer_end = multi_buffer_snapshot
5881 .anchor_after(multi_buffer_snapshot.len())
5882 .to_point(&multi_buffer_snapshot);
5883 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5884 self.debounced_selection_highlight_task = Some((
5885 query_range.clone(),
5886 self.update_selection_occurrence_highlights(
5887 query_text,
5888 query_range,
5889 multi_buffer_full_range,
5890 true,
5891 window,
5892 cx,
5893 ),
5894 ));
5895 }
5896 }
5897
5898 pub fn refresh_inline_completion(
5899 &mut self,
5900 debounce: bool,
5901 user_requested: bool,
5902 window: &mut Window,
5903 cx: &mut Context<Self>,
5904 ) -> Option<()> {
5905 let provider = self.edit_prediction_provider()?;
5906 let cursor = self.selections.newest_anchor().head();
5907 let (buffer, cursor_buffer_position) =
5908 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5909
5910 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5911 self.discard_inline_completion(false, cx);
5912 return None;
5913 }
5914
5915 if !user_requested
5916 && (!self.should_show_edit_predictions()
5917 || !self.is_focused(window)
5918 || buffer.read(cx).is_empty())
5919 {
5920 self.discard_inline_completion(false, cx);
5921 return None;
5922 }
5923
5924 self.update_visible_inline_completion(window, cx);
5925 provider.refresh(
5926 self.project.clone(),
5927 buffer,
5928 cursor_buffer_position,
5929 debounce,
5930 cx,
5931 );
5932 Some(())
5933 }
5934
5935 fn show_edit_predictions_in_menu(&self) -> bool {
5936 match self.edit_prediction_settings {
5937 EditPredictionSettings::Disabled => false,
5938 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5939 }
5940 }
5941
5942 pub fn edit_predictions_enabled(&self) -> bool {
5943 match self.edit_prediction_settings {
5944 EditPredictionSettings::Disabled => false,
5945 EditPredictionSettings::Enabled { .. } => true,
5946 }
5947 }
5948
5949 fn edit_prediction_requires_modifier(&self) -> bool {
5950 match self.edit_prediction_settings {
5951 EditPredictionSettings::Disabled => false,
5952 EditPredictionSettings::Enabled {
5953 preview_requires_modifier,
5954 ..
5955 } => preview_requires_modifier,
5956 }
5957 }
5958
5959 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5960 if self.edit_prediction_provider.is_none() {
5961 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5962 } else {
5963 let selection = self.selections.newest_anchor();
5964 let cursor = selection.head();
5965
5966 if let Some((buffer, cursor_buffer_position)) =
5967 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5968 {
5969 self.edit_prediction_settings =
5970 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5971 }
5972 }
5973 }
5974
5975 fn edit_prediction_settings_at_position(
5976 &self,
5977 buffer: &Entity<Buffer>,
5978 buffer_position: language::Anchor,
5979 cx: &App,
5980 ) -> EditPredictionSettings {
5981 if !self.mode.is_full()
5982 || !self.show_inline_completions_override.unwrap_or(true)
5983 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5984 {
5985 return EditPredictionSettings::Disabled;
5986 }
5987
5988 let buffer = buffer.read(cx);
5989
5990 let file = buffer.file();
5991
5992 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5993 return EditPredictionSettings::Disabled;
5994 };
5995
5996 let by_provider = matches!(
5997 self.menu_inline_completions_policy,
5998 MenuInlineCompletionsPolicy::ByProvider
5999 );
6000
6001 let show_in_menu = by_provider
6002 && self
6003 .edit_prediction_provider
6004 .as_ref()
6005 .map_or(false, |provider| {
6006 provider.provider.show_completions_in_menu()
6007 });
6008
6009 let preview_requires_modifier =
6010 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
6011
6012 EditPredictionSettings::Enabled {
6013 show_in_menu,
6014 preview_requires_modifier,
6015 }
6016 }
6017
6018 fn should_show_edit_predictions(&self) -> bool {
6019 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
6020 }
6021
6022 pub fn edit_prediction_preview_is_active(&self) -> bool {
6023 matches!(
6024 self.edit_prediction_preview,
6025 EditPredictionPreview::Active { .. }
6026 )
6027 }
6028
6029 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
6030 let cursor = self.selections.newest_anchor().head();
6031 if let Some((buffer, cursor_position)) =
6032 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
6033 {
6034 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
6035 } else {
6036 false
6037 }
6038 }
6039
6040 fn edit_predictions_enabled_in_buffer(
6041 &self,
6042 buffer: &Entity<Buffer>,
6043 buffer_position: language::Anchor,
6044 cx: &App,
6045 ) -> bool {
6046 maybe!({
6047 if self.read_only(cx) {
6048 return Some(false);
6049 }
6050 let provider = self.edit_prediction_provider()?;
6051 if !provider.is_enabled(&buffer, buffer_position, cx) {
6052 return Some(false);
6053 }
6054 let buffer = buffer.read(cx);
6055 let Some(file) = buffer.file() else {
6056 return Some(true);
6057 };
6058 let settings = all_language_settings(Some(file), cx);
6059 Some(settings.edit_predictions_enabled_for_file(file, cx))
6060 })
6061 .unwrap_or(false)
6062 }
6063
6064 fn cycle_inline_completion(
6065 &mut self,
6066 direction: Direction,
6067 window: &mut Window,
6068 cx: &mut Context<Self>,
6069 ) -> Option<()> {
6070 let provider = self.edit_prediction_provider()?;
6071 let cursor = self.selections.newest_anchor().head();
6072 let (buffer, cursor_buffer_position) =
6073 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6074 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
6075 return None;
6076 }
6077
6078 provider.cycle(buffer, cursor_buffer_position, direction, cx);
6079 self.update_visible_inline_completion(window, cx);
6080
6081 Some(())
6082 }
6083
6084 pub fn show_inline_completion(
6085 &mut self,
6086 _: &ShowEditPrediction,
6087 window: &mut Window,
6088 cx: &mut Context<Self>,
6089 ) {
6090 if !self.has_active_inline_completion() {
6091 self.refresh_inline_completion(false, true, window, cx);
6092 return;
6093 }
6094
6095 self.update_visible_inline_completion(window, cx);
6096 }
6097
6098 pub fn display_cursor_names(
6099 &mut self,
6100 _: &DisplayCursorNames,
6101 window: &mut Window,
6102 cx: &mut Context<Self>,
6103 ) {
6104 self.show_cursor_names(window, cx);
6105 }
6106
6107 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6108 self.show_cursor_names = true;
6109 cx.notify();
6110 cx.spawn_in(window, async move |this, cx| {
6111 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
6112 this.update(cx, |this, cx| {
6113 this.show_cursor_names = false;
6114 cx.notify()
6115 })
6116 .ok()
6117 })
6118 .detach();
6119 }
6120
6121 pub fn next_edit_prediction(
6122 &mut self,
6123 _: &NextEditPrediction,
6124 window: &mut Window,
6125 cx: &mut Context<Self>,
6126 ) {
6127 if self.has_active_inline_completion() {
6128 self.cycle_inline_completion(Direction::Next, window, cx);
6129 } else {
6130 let is_copilot_disabled = self
6131 .refresh_inline_completion(false, true, window, cx)
6132 .is_none();
6133 if is_copilot_disabled {
6134 cx.propagate();
6135 }
6136 }
6137 }
6138
6139 pub fn previous_edit_prediction(
6140 &mut self,
6141 _: &PreviousEditPrediction,
6142 window: &mut Window,
6143 cx: &mut Context<Self>,
6144 ) {
6145 if self.has_active_inline_completion() {
6146 self.cycle_inline_completion(Direction::Prev, window, cx);
6147 } else {
6148 let is_copilot_disabled = self
6149 .refresh_inline_completion(false, true, window, cx)
6150 .is_none();
6151 if is_copilot_disabled {
6152 cx.propagate();
6153 }
6154 }
6155 }
6156
6157 pub fn accept_edit_prediction(
6158 &mut self,
6159 _: &AcceptEditPrediction,
6160 window: &mut Window,
6161 cx: &mut Context<Self>,
6162 ) {
6163 if self.show_edit_predictions_in_menu() {
6164 self.hide_context_menu(window, cx);
6165 }
6166
6167 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6168 return;
6169 };
6170
6171 self.report_inline_completion_event(
6172 active_inline_completion.completion_id.clone(),
6173 true,
6174 cx,
6175 );
6176
6177 match &active_inline_completion.completion {
6178 InlineCompletion::Move { target, .. } => {
6179 let target = *target;
6180
6181 if let Some(position_map) = &self.last_position_map {
6182 if position_map
6183 .visible_row_range
6184 .contains(&target.to_display_point(&position_map.snapshot).row())
6185 || !self.edit_prediction_requires_modifier()
6186 {
6187 self.unfold_ranges(&[target..target], true, false, cx);
6188 // Note that this is also done in vim's handler of the Tab action.
6189 self.change_selections(
6190 Some(Autoscroll::newest()),
6191 window,
6192 cx,
6193 |selections| {
6194 selections.select_anchor_ranges([target..target]);
6195 },
6196 );
6197 self.clear_row_highlights::<EditPredictionPreview>();
6198
6199 self.edit_prediction_preview
6200 .set_previous_scroll_position(None);
6201 } else {
6202 self.edit_prediction_preview
6203 .set_previous_scroll_position(Some(
6204 position_map.snapshot.scroll_anchor,
6205 ));
6206
6207 self.highlight_rows::<EditPredictionPreview>(
6208 target..target,
6209 cx.theme().colors().editor_highlighted_line_background,
6210 RowHighlightOptions {
6211 autoscroll: true,
6212 ..Default::default()
6213 },
6214 cx,
6215 );
6216 self.request_autoscroll(Autoscroll::fit(), cx);
6217 }
6218 }
6219 }
6220 InlineCompletion::Edit { edits, .. } => {
6221 if let Some(provider) = self.edit_prediction_provider() {
6222 provider.accept(cx);
6223 }
6224
6225 let snapshot = self.buffer.read(cx).snapshot(cx);
6226 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
6227
6228 self.buffer.update(cx, |buffer, cx| {
6229 buffer.edit(edits.iter().cloned(), None, cx)
6230 });
6231
6232 self.change_selections(None, window, cx, |s| {
6233 s.select_anchor_ranges([last_edit_end..last_edit_end])
6234 });
6235
6236 self.update_visible_inline_completion(window, cx);
6237 if self.active_inline_completion.is_none() {
6238 self.refresh_inline_completion(true, true, window, cx);
6239 }
6240
6241 cx.notify();
6242 }
6243 }
6244
6245 self.edit_prediction_requires_modifier_in_indent_conflict = false;
6246 }
6247
6248 pub fn accept_partial_inline_completion(
6249 &mut self,
6250 _: &AcceptPartialEditPrediction,
6251 window: &mut Window,
6252 cx: &mut Context<Self>,
6253 ) {
6254 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6255 return;
6256 };
6257 if self.selections.count() != 1 {
6258 return;
6259 }
6260
6261 self.report_inline_completion_event(
6262 active_inline_completion.completion_id.clone(),
6263 true,
6264 cx,
6265 );
6266
6267 match &active_inline_completion.completion {
6268 InlineCompletion::Move { target, .. } => {
6269 let target = *target;
6270 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6271 selections.select_anchor_ranges([target..target]);
6272 });
6273 }
6274 InlineCompletion::Edit { edits, .. } => {
6275 // Find an insertion that starts at the cursor position.
6276 let snapshot = self.buffer.read(cx).snapshot(cx);
6277 let cursor_offset = self.selections.newest::<usize>(cx).head();
6278 let insertion = edits.iter().find_map(|(range, text)| {
6279 let range = range.to_offset(&snapshot);
6280 if range.is_empty() && range.start == cursor_offset {
6281 Some(text)
6282 } else {
6283 None
6284 }
6285 });
6286
6287 if let Some(text) = insertion {
6288 let mut partial_completion = text
6289 .chars()
6290 .by_ref()
6291 .take_while(|c| c.is_alphabetic())
6292 .collect::<String>();
6293 if partial_completion.is_empty() {
6294 partial_completion = text
6295 .chars()
6296 .by_ref()
6297 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6298 .collect::<String>();
6299 }
6300
6301 cx.emit(EditorEvent::InputHandled {
6302 utf16_range_to_replace: None,
6303 text: partial_completion.clone().into(),
6304 });
6305
6306 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6307
6308 self.refresh_inline_completion(true, true, window, cx);
6309 cx.notify();
6310 } else {
6311 self.accept_edit_prediction(&Default::default(), window, cx);
6312 }
6313 }
6314 }
6315 }
6316
6317 fn discard_inline_completion(
6318 &mut self,
6319 should_report_inline_completion_event: bool,
6320 cx: &mut Context<Self>,
6321 ) -> bool {
6322 if should_report_inline_completion_event {
6323 let completion_id = self
6324 .active_inline_completion
6325 .as_ref()
6326 .and_then(|active_completion| active_completion.completion_id.clone());
6327
6328 self.report_inline_completion_event(completion_id, false, cx);
6329 }
6330
6331 if let Some(provider) = self.edit_prediction_provider() {
6332 provider.discard(cx);
6333 }
6334
6335 self.take_active_inline_completion(cx)
6336 }
6337
6338 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6339 let Some(provider) = self.edit_prediction_provider() else {
6340 return;
6341 };
6342
6343 let Some((_, buffer, _)) = self
6344 .buffer
6345 .read(cx)
6346 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6347 else {
6348 return;
6349 };
6350
6351 let extension = buffer
6352 .read(cx)
6353 .file()
6354 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6355
6356 let event_type = match accepted {
6357 true => "Edit Prediction Accepted",
6358 false => "Edit Prediction Discarded",
6359 };
6360 telemetry::event!(
6361 event_type,
6362 provider = provider.name(),
6363 prediction_id = id,
6364 suggestion_accepted = accepted,
6365 file_extension = extension,
6366 );
6367 }
6368
6369 pub fn has_active_inline_completion(&self) -> bool {
6370 self.active_inline_completion.is_some()
6371 }
6372
6373 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6374 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6375 return false;
6376 };
6377
6378 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6379 self.clear_highlights::<InlineCompletionHighlight>(cx);
6380 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6381 true
6382 }
6383
6384 /// Returns true when we're displaying the edit prediction popover below the cursor
6385 /// like we are not previewing and the LSP autocomplete menu is visible
6386 /// or we are in `when_holding_modifier` mode.
6387 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6388 if self.edit_prediction_preview_is_active()
6389 || !self.show_edit_predictions_in_menu()
6390 || !self.edit_predictions_enabled()
6391 {
6392 return false;
6393 }
6394
6395 if self.has_visible_completions_menu() {
6396 return true;
6397 }
6398
6399 has_completion && self.edit_prediction_requires_modifier()
6400 }
6401
6402 fn handle_modifiers_changed(
6403 &mut self,
6404 modifiers: Modifiers,
6405 position_map: &PositionMap,
6406 window: &mut Window,
6407 cx: &mut Context<Self>,
6408 ) {
6409 if self.show_edit_predictions_in_menu() {
6410 self.update_edit_prediction_preview(&modifiers, window, cx);
6411 }
6412
6413 self.update_selection_mode(&modifiers, position_map, window, cx);
6414
6415 let mouse_position = window.mouse_position();
6416 if !position_map.text_hitbox.is_hovered(window) {
6417 return;
6418 }
6419
6420 self.update_hovered_link(
6421 position_map.point_for_position(mouse_position),
6422 &position_map.snapshot,
6423 modifiers,
6424 window,
6425 cx,
6426 )
6427 }
6428
6429 fn update_selection_mode(
6430 &mut self,
6431 modifiers: &Modifiers,
6432 position_map: &PositionMap,
6433 window: &mut Window,
6434 cx: &mut Context<Self>,
6435 ) {
6436 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6437 return;
6438 }
6439
6440 let mouse_position = window.mouse_position();
6441 let point_for_position = position_map.point_for_position(mouse_position);
6442 let position = point_for_position.previous_valid;
6443
6444 self.select(
6445 SelectPhase::BeginColumnar {
6446 position,
6447 reset: false,
6448 goal_column: point_for_position.exact_unclipped.column(),
6449 },
6450 window,
6451 cx,
6452 );
6453 }
6454
6455 fn update_edit_prediction_preview(
6456 &mut self,
6457 modifiers: &Modifiers,
6458 window: &mut Window,
6459 cx: &mut Context<Self>,
6460 ) {
6461 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6462 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6463 return;
6464 };
6465
6466 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6467 if matches!(
6468 self.edit_prediction_preview,
6469 EditPredictionPreview::Inactive { .. }
6470 ) {
6471 self.edit_prediction_preview = EditPredictionPreview::Active {
6472 previous_scroll_position: None,
6473 since: Instant::now(),
6474 };
6475
6476 self.update_visible_inline_completion(window, cx);
6477 cx.notify();
6478 }
6479 } else if let EditPredictionPreview::Active {
6480 previous_scroll_position,
6481 since,
6482 } = self.edit_prediction_preview
6483 {
6484 if let (Some(previous_scroll_position), Some(position_map)) =
6485 (previous_scroll_position, self.last_position_map.as_ref())
6486 {
6487 self.set_scroll_position(
6488 previous_scroll_position
6489 .scroll_position(&position_map.snapshot.display_snapshot),
6490 window,
6491 cx,
6492 );
6493 }
6494
6495 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6496 released_too_fast: since.elapsed() < Duration::from_millis(200),
6497 };
6498 self.clear_row_highlights::<EditPredictionPreview>();
6499 self.update_visible_inline_completion(window, cx);
6500 cx.notify();
6501 }
6502 }
6503
6504 fn update_visible_inline_completion(
6505 &mut self,
6506 _window: &mut Window,
6507 cx: &mut Context<Self>,
6508 ) -> Option<()> {
6509 let selection = self.selections.newest_anchor();
6510 let cursor = selection.head();
6511 let multibuffer = self.buffer.read(cx).snapshot(cx);
6512 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6513 let excerpt_id = cursor.excerpt_id;
6514
6515 let show_in_menu = self.show_edit_predictions_in_menu();
6516 let completions_menu_has_precedence = !show_in_menu
6517 && (self.context_menu.borrow().is_some()
6518 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6519
6520 if completions_menu_has_precedence
6521 || !offset_selection.is_empty()
6522 || self
6523 .active_inline_completion
6524 .as_ref()
6525 .map_or(false, |completion| {
6526 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6527 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6528 !invalidation_range.contains(&offset_selection.head())
6529 })
6530 {
6531 self.discard_inline_completion(false, cx);
6532 return None;
6533 }
6534
6535 self.take_active_inline_completion(cx);
6536 let Some(provider) = self.edit_prediction_provider() else {
6537 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6538 return None;
6539 };
6540
6541 let (buffer, cursor_buffer_position) =
6542 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6543
6544 self.edit_prediction_settings =
6545 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6546
6547 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6548
6549 if self.edit_prediction_indent_conflict {
6550 let cursor_point = cursor.to_point(&multibuffer);
6551
6552 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6553
6554 if let Some((_, indent)) = indents.iter().next() {
6555 if indent.len == cursor_point.column {
6556 self.edit_prediction_indent_conflict = false;
6557 }
6558 }
6559 }
6560
6561 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6562 let edits = inline_completion
6563 .edits
6564 .into_iter()
6565 .flat_map(|(range, new_text)| {
6566 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6567 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6568 Some((start..end, new_text))
6569 })
6570 .collect::<Vec<_>>();
6571 if edits.is_empty() {
6572 return None;
6573 }
6574
6575 let first_edit_start = edits.first().unwrap().0.start;
6576 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6577 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6578
6579 let last_edit_end = edits.last().unwrap().0.end;
6580 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6581 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6582
6583 let cursor_row = cursor.to_point(&multibuffer).row;
6584
6585 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6586
6587 let mut inlay_ids = Vec::new();
6588 let invalidation_row_range;
6589 let move_invalidation_row_range = if cursor_row < edit_start_row {
6590 Some(cursor_row..edit_end_row)
6591 } else if cursor_row > edit_end_row {
6592 Some(edit_start_row..cursor_row)
6593 } else {
6594 None
6595 };
6596 let is_move =
6597 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6598 let completion = if is_move {
6599 invalidation_row_range =
6600 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6601 let target = first_edit_start;
6602 InlineCompletion::Move { target, snapshot }
6603 } else {
6604 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6605 && !self.inline_completions_hidden_for_vim_mode;
6606
6607 if show_completions_in_buffer {
6608 if edits
6609 .iter()
6610 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6611 {
6612 let mut inlays = Vec::new();
6613 for (range, new_text) in &edits {
6614 let inlay = Inlay::inline_completion(
6615 post_inc(&mut self.next_inlay_id),
6616 range.start,
6617 new_text.as_str(),
6618 );
6619 inlay_ids.push(inlay.id);
6620 inlays.push(inlay);
6621 }
6622
6623 self.splice_inlays(&[], inlays, cx);
6624 } else {
6625 let background_color = cx.theme().status().deleted_background;
6626 self.highlight_text::<InlineCompletionHighlight>(
6627 edits.iter().map(|(range, _)| range.clone()).collect(),
6628 HighlightStyle {
6629 background_color: Some(background_color),
6630 ..Default::default()
6631 },
6632 cx,
6633 );
6634 }
6635 }
6636
6637 invalidation_row_range = edit_start_row..edit_end_row;
6638
6639 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6640 if provider.show_tab_accept_marker() {
6641 EditDisplayMode::TabAccept
6642 } else {
6643 EditDisplayMode::Inline
6644 }
6645 } else {
6646 EditDisplayMode::DiffPopover
6647 };
6648
6649 InlineCompletion::Edit {
6650 edits,
6651 edit_preview: inline_completion.edit_preview,
6652 display_mode,
6653 snapshot,
6654 }
6655 };
6656
6657 let invalidation_range = multibuffer
6658 .anchor_before(Point::new(invalidation_row_range.start, 0))
6659 ..multibuffer.anchor_after(Point::new(
6660 invalidation_row_range.end,
6661 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6662 ));
6663
6664 self.stale_inline_completion_in_menu = None;
6665 self.active_inline_completion = Some(InlineCompletionState {
6666 inlay_ids,
6667 completion,
6668 completion_id: inline_completion.id,
6669 invalidation_range,
6670 });
6671
6672 cx.notify();
6673
6674 Some(())
6675 }
6676
6677 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6678 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6679 }
6680
6681 fn render_code_actions_indicator(
6682 &self,
6683 _style: &EditorStyle,
6684 row: DisplayRow,
6685 is_active: bool,
6686 breakpoint: Option<&(Anchor, Breakpoint)>,
6687 cx: &mut Context<Self>,
6688 ) -> Option<IconButton> {
6689 let color = Color::Muted;
6690 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6691 let show_tooltip = !self.context_menu_visible();
6692
6693 if self.available_code_actions.is_some() {
6694 Some(
6695 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6696 .shape(ui::IconButtonShape::Square)
6697 .icon_size(IconSize::XSmall)
6698 .icon_color(color)
6699 .toggle_state(is_active)
6700 .when(show_tooltip, |this| {
6701 this.tooltip({
6702 let focus_handle = self.focus_handle.clone();
6703 move |window, cx| {
6704 Tooltip::for_action_in(
6705 "Toggle Code Actions",
6706 &ToggleCodeActions {
6707 deployed_from_indicator: None,
6708 quick_launch: false,
6709 },
6710 &focus_handle,
6711 window,
6712 cx,
6713 )
6714 }
6715 })
6716 })
6717 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
6718 let quick_launch = e.down.button == MouseButton::Left;
6719 window.focus(&editor.focus_handle(cx));
6720 editor.toggle_code_actions(
6721 &ToggleCodeActions {
6722 deployed_from_indicator: Some(row),
6723 quick_launch,
6724 },
6725 window,
6726 cx,
6727 );
6728 }))
6729 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6730 editor.set_breakpoint_context_menu(
6731 row,
6732 position,
6733 event.down.position,
6734 window,
6735 cx,
6736 );
6737 })),
6738 )
6739 } else {
6740 None
6741 }
6742 }
6743
6744 fn clear_tasks(&mut self) {
6745 self.tasks.clear()
6746 }
6747
6748 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6749 if self.tasks.insert(key, value).is_some() {
6750 // This case should hopefully be rare, but just in case...
6751 log::error!(
6752 "multiple different run targets found on a single line, only the last target will be rendered"
6753 )
6754 }
6755 }
6756
6757 /// Get all display points of breakpoints that will be rendered within editor
6758 ///
6759 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6760 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6761 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6762 fn active_breakpoints(
6763 &self,
6764 range: Range<DisplayRow>,
6765 window: &mut Window,
6766 cx: &mut Context<Self>,
6767 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6768 let mut breakpoint_display_points = HashMap::default();
6769
6770 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6771 return breakpoint_display_points;
6772 };
6773
6774 let snapshot = self.snapshot(window, cx);
6775
6776 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6777 let Some(project) = self.project.as_ref() else {
6778 return breakpoint_display_points;
6779 };
6780
6781 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6782 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6783
6784 for (buffer_snapshot, range, excerpt_id) in
6785 multi_buffer_snapshot.range_to_buffer_ranges(range)
6786 {
6787 let Some(buffer) = project.read_with(cx, |this, cx| {
6788 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6789 }) else {
6790 continue;
6791 };
6792 let breakpoints = breakpoint_store.read(cx).breakpoints(
6793 &buffer,
6794 Some(
6795 buffer_snapshot.anchor_before(range.start)
6796 ..buffer_snapshot.anchor_after(range.end),
6797 ),
6798 buffer_snapshot,
6799 cx,
6800 );
6801 for (anchor, breakpoint) in breakpoints {
6802 let multi_buffer_anchor =
6803 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6804 let position = multi_buffer_anchor
6805 .to_point(&multi_buffer_snapshot)
6806 .to_display_point(&snapshot);
6807
6808 breakpoint_display_points
6809 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6810 }
6811 }
6812
6813 breakpoint_display_points
6814 }
6815
6816 fn breakpoint_context_menu(
6817 &self,
6818 anchor: Anchor,
6819 window: &mut Window,
6820 cx: &mut Context<Self>,
6821 ) -> Entity<ui::ContextMenu> {
6822 let weak_editor = cx.weak_entity();
6823 let focus_handle = self.focus_handle(cx);
6824
6825 let row = self
6826 .buffer
6827 .read(cx)
6828 .snapshot(cx)
6829 .summary_for_anchor::<Point>(&anchor)
6830 .row;
6831
6832 let breakpoint = self
6833 .breakpoint_at_row(row, window, cx)
6834 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6835
6836 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6837 "Edit Log Breakpoint"
6838 } else {
6839 "Set Log Breakpoint"
6840 };
6841
6842 let condition_breakpoint_msg = if breakpoint
6843 .as_ref()
6844 .is_some_and(|bp| bp.1.condition.is_some())
6845 {
6846 "Edit Condition Breakpoint"
6847 } else {
6848 "Set Condition Breakpoint"
6849 };
6850
6851 let hit_condition_breakpoint_msg = if breakpoint
6852 .as_ref()
6853 .is_some_and(|bp| bp.1.hit_condition.is_some())
6854 {
6855 "Edit Hit Condition Breakpoint"
6856 } else {
6857 "Set Hit Condition Breakpoint"
6858 };
6859
6860 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6861 "Unset Breakpoint"
6862 } else {
6863 "Set Breakpoint"
6864 };
6865
6866 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6867 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6868
6869 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6870 BreakpointState::Enabled => Some("Disable"),
6871 BreakpointState::Disabled => Some("Enable"),
6872 });
6873
6874 let (anchor, breakpoint) =
6875 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6876
6877 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6878 menu.on_blur_subscription(Subscription::new(|| {}))
6879 .context(focus_handle)
6880 .when(run_to_cursor, |this| {
6881 let weak_editor = weak_editor.clone();
6882 this.entry("Run to cursor", None, move |window, cx| {
6883 weak_editor
6884 .update(cx, |editor, cx| {
6885 editor.change_selections(None, window, cx, |s| {
6886 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6887 });
6888 })
6889 .ok();
6890
6891 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6892 })
6893 .separator()
6894 })
6895 .when_some(toggle_state_msg, |this, msg| {
6896 this.entry(msg, None, {
6897 let weak_editor = weak_editor.clone();
6898 let breakpoint = breakpoint.clone();
6899 move |_window, cx| {
6900 weak_editor
6901 .update(cx, |this, cx| {
6902 this.edit_breakpoint_at_anchor(
6903 anchor,
6904 breakpoint.as_ref().clone(),
6905 BreakpointEditAction::InvertState,
6906 cx,
6907 );
6908 })
6909 .log_err();
6910 }
6911 })
6912 })
6913 .entry(set_breakpoint_msg, None, {
6914 let weak_editor = weak_editor.clone();
6915 let breakpoint = breakpoint.clone();
6916 move |_window, cx| {
6917 weak_editor
6918 .update(cx, |this, cx| {
6919 this.edit_breakpoint_at_anchor(
6920 anchor,
6921 breakpoint.as_ref().clone(),
6922 BreakpointEditAction::Toggle,
6923 cx,
6924 );
6925 })
6926 .log_err();
6927 }
6928 })
6929 .entry(log_breakpoint_msg, None, {
6930 let breakpoint = breakpoint.clone();
6931 let weak_editor = weak_editor.clone();
6932 move |window, cx| {
6933 weak_editor
6934 .update(cx, |this, cx| {
6935 this.add_edit_breakpoint_block(
6936 anchor,
6937 breakpoint.as_ref(),
6938 BreakpointPromptEditAction::Log,
6939 window,
6940 cx,
6941 );
6942 })
6943 .log_err();
6944 }
6945 })
6946 .entry(condition_breakpoint_msg, None, {
6947 let breakpoint = breakpoint.clone();
6948 let weak_editor = weak_editor.clone();
6949 move |window, cx| {
6950 weak_editor
6951 .update(cx, |this, cx| {
6952 this.add_edit_breakpoint_block(
6953 anchor,
6954 breakpoint.as_ref(),
6955 BreakpointPromptEditAction::Condition,
6956 window,
6957 cx,
6958 );
6959 })
6960 .log_err();
6961 }
6962 })
6963 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6964 weak_editor
6965 .update(cx, |this, cx| {
6966 this.add_edit_breakpoint_block(
6967 anchor,
6968 breakpoint.as_ref(),
6969 BreakpointPromptEditAction::HitCondition,
6970 window,
6971 cx,
6972 );
6973 })
6974 .log_err();
6975 })
6976 })
6977 }
6978
6979 fn render_breakpoint(
6980 &self,
6981 position: Anchor,
6982 row: DisplayRow,
6983 breakpoint: &Breakpoint,
6984 cx: &mut Context<Self>,
6985 ) -> IconButton {
6986 // Is it a breakpoint that shows up when hovering over gutter?
6987 let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
6988 (false, false),
6989 |PhantomBreakpointIndicator {
6990 is_active,
6991 display_row,
6992 collides_with_existing_breakpoint,
6993 }| {
6994 (
6995 is_active && display_row == row,
6996 collides_with_existing_breakpoint,
6997 )
6998 },
6999 );
7000
7001 let (color, icon) = {
7002 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
7003 (false, false) => ui::IconName::DebugBreakpoint,
7004 (true, false) => ui::IconName::DebugLogBreakpoint,
7005 (false, true) => ui::IconName::DebugDisabledBreakpoint,
7006 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
7007 };
7008
7009 let color = if is_phantom {
7010 Color::Hint
7011 } else {
7012 Color::Debugger
7013 };
7014
7015 (color, icon)
7016 };
7017
7018 let breakpoint = Arc::from(breakpoint.clone());
7019
7020 let alt_as_text = gpui::Keystroke {
7021 modifiers: Modifiers::secondary_key(),
7022 ..Default::default()
7023 };
7024 let primary_action_text = if breakpoint.is_disabled() {
7025 "enable"
7026 } else if is_phantom && !collides_with_existing {
7027 "set"
7028 } else {
7029 "unset"
7030 };
7031 let mut primary_text = format!("Click to {primary_action_text}");
7032 if collides_with_existing && !breakpoint.is_disabled() {
7033 use std::fmt::Write;
7034 write!(primary_text, ", {alt_as_text}-click to disable").ok();
7035 }
7036 let primary_text = SharedString::from(primary_text);
7037 let focus_handle = self.focus_handle.clone();
7038 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
7039 .icon_size(IconSize::XSmall)
7040 .size(ui::ButtonSize::None)
7041 .icon_color(color)
7042 .style(ButtonStyle::Transparent)
7043 .on_click(cx.listener({
7044 let breakpoint = breakpoint.clone();
7045
7046 move |editor, event: &ClickEvent, window, cx| {
7047 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
7048 BreakpointEditAction::InvertState
7049 } else {
7050 BreakpointEditAction::Toggle
7051 };
7052
7053 window.focus(&editor.focus_handle(cx));
7054 editor.edit_breakpoint_at_anchor(
7055 position,
7056 breakpoint.as_ref().clone(),
7057 edit_action,
7058 cx,
7059 );
7060 }
7061 }))
7062 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7063 editor.set_breakpoint_context_menu(
7064 row,
7065 Some(position),
7066 event.down.position,
7067 window,
7068 cx,
7069 );
7070 }))
7071 .tooltip(move |window, cx| {
7072 Tooltip::with_meta_in(
7073 primary_text.clone(),
7074 None,
7075 "Right-click for more options",
7076 &focus_handle,
7077 window,
7078 cx,
7079 )
7080 })
7081 }
7082
7083 fn build_tasks_context(
7084 project: &Entity<Project>,
7085 buffer: &Entity<Buffer>,
7086 buffer_row: u32,
7087 tasks: &Arc<RunnableTasks>,
7088 cx: &mut Context<Self>,
7089 ) -> Task<Option<task::TaskContext>> {
7090 let position = Point::new(buffer_row, tasks.column);
7091 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
7092 let location = Location {
7093 buffer: buffer.clone(),
7094 range: range_start..range_start,
7095 };
7096 // Fill in the environmental variables from the tree-sitter captures
7097 let mut captured_task_variables = TaskVariables::default();
7098 for (capture_name, value) in tasks.extra_variables.clone() {
7099 captured_task_variables.insert(
7100 task::VariableName::Custom(capture_name.into()),
7101 value.clone(),
7102 );
7103 }
7104 project.update(cx, |project, cx| {
7105 project.task_store().update(cx, |task_store, cx| {
7106 task_store.task_context_for_location(captured_task_variables, location, cx)
7107 })
7108 })
7109 }
7110
7111 pub fn spawn_nearest_task(
7112 &mut self,
7113 action: &SpawnNearestTask,
7114 window: &mut Window,
7115 cx: &mut Context<Self>,
7116 ) {
7117 let Some((workspace, _)) = self.workspace.clone() else {
7118 return;
7119 };
7120 let Some(project) = self.project.clone() else {
7121 return;
7122 };
7123
7124 // Try to find a closest, enclosing node using tree-sitter that has a
7125 // task
7126 let Some((buffer, buffer_row, tasks)) = self
7127 .find_enclosing_node_task(cx)
7128 // Or find the task that's closest in row-distance.
7129 .or_else(|| self.find_closest_task(cx))
7130 else {
7131 return;
7132 };
7133
7134 let reveal_strategy = action.reveal;
7135 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
7136 cx.spawn_in(window, async move |_, cx| {
7137 let context = task_context.await?;
7138 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
7139
7140 let resolved = &mut resolved_task.resolved;
7141 resolved.reveal = reveal_strategy;
7142
7143 workspace
7144 .update_in(cx, |workspace, window, cx| {
7145 workspace.schedule_resolved_task(
7146 task_source_kind,
7147 resolved_task,
7148 false,
7149 window,
7150 cx,
7151 );
7152 })
7153 .ok()
7154 })
7155 .detach();
7156 }
7157
7158 fn find_closest_task(
7159 &mut self,
7160 cx: &mut Context<Self>,
7161 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7162 let cursor_row = self.selections.newest_adjusted(cx).head().row;
7163
7164 let ((buffer_id, row), tasks) = self
7165 .tasks
7166 .iter()
7167 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
7168
7169 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
7170 let tasks = Arc::new(tasks.to_owned());
7171 Some((buffer, *row, tasks))
7172 }
7173
7174 fn find_enclosing_node_task(
7175 &mut self,
7176 cx: &mut Context<Self>,
7177 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7178 let snapshot = self.buffer.read(cx).snapshot(cx);
7179 let offset = self.selections.newest::<usize>(cx).head();
7180 let excerpt = snapshot.excerpt_containing(offset..offset)?;
7181 let buffer_id = excerpt.buffer().remote_id();
7182
7183 let layer = excerpt.buffer().syntax_layer_at(offset)?;
7184 let mut cursor = layer.node().walk();
7185
7186 while cursor.goto_first_child_for_byte(offset).is_some() {
7187 if cursor.node().end_byte() == offset {
7188 cursor.goto_next_sibling();
7189 }
7190 }
7191
7192 // Ascend to the smallest ancestor that contains the range and has a task.
7193 loop {
7194 let node = cursor.node();
7195 let node_range = node.byte_range();
7196 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
7197
7198 // Check if this node contains our offset
7199 if node_range.start <= offset && node_range.end >= offset {
7200 // If it contains offset, check for task
7201 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
7202 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
7203 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
7204 }
7205 }
7206
7207 if !cursor.goto_parent() {
7208 break;
7209 }
7210 }
7211 None
7212 }
7213
7214 fn render_run_indicator(
7215 &self,
7216 _style: &EditorStyle,
7217 is_active: bool,
7218 row: DisplayRow,
7219 breakpoint: Option<(Anchor, Breakpoint)>,
7220 cx: &mut Context<Self>,
7221 ) -> IconButton {
7222 let color = Color::Muted;
7223 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
7224
7225 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
7226 .shape(ui::IconButtonShape::Square)
7227 .icon_size(IconSize::XSmall)
7228 .icon_color(color)
7229 .toggle_state(is_active)
7230 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
7231 let quick_launch = e.down.button == MouseButton::Left;
7232 window.focus(&editor.focus_handle(cx));
7233 editor.toggle_code_actions(
7234 &ToggleCodeActions {
7235 deployed_from_indicator: Some(row),
7236 quick_launch,
7237 },
7238 window,
7239 cx,
7240 );
7241 }))
7242 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7243 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
7244 }))
7245 }
7246
7247 pub fn context_menu_visible(&self) -> bool {
7248 !self.edit_prediction_preview_is_active()
7249 && self
7250 .context_menu
7251 .borrow()
7252 .as_ref()
7253 .map_or(false, |menu| menu.visible())
7254 }
7255
7256 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
7257 self.context_menu
7258 .borrow()
7259 .as_ref()
7260 .map(|menu| menu.origin())
7261 }
7262
7263 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
7264 self.context_menu_options = Some(options);
7265 }
7266
7267 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
7268 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
7269
7270 fn render_edit_prediction_popover(
7271 &mut self,
7272 text_bounds: &Bounds<Pixels>,
7273 content_origin: gpui::Point<Pixels>,
7274 editor_snapshot: &EditorSnapshot,
7275 visible_row_range: Range<DisplayRow>,
7276 scroll_top: f32,
7277 scroll_bottom: f32,
7278 line_layouts: &[LineWithInvisibles],
7279 line_height: Pixels,
7280 scroll_pixel_position: gpui::Point<Pixels>,
7281 newest_selection_head: Option<DisplayPoint>,
7282 editor_width: Pixels,
7283 style: &EditorStyle,
7284 window: &mut Window,
7285 cx: &mut App,
7286 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7287 let active_inline_completion = self.active_inline_completion.as_ref()?;
7288
7289 if self.edit_prediction_visible_in_cursor_popover(true) {
7290 return None;
7291 }
7292
7293 match &active_inline_completion.completion {
7294 InlineCompletion::Move { target, .. } => {
7295 let target_display_point = target.to_display_point(editor_snapshot);
7296
7297 if self.edit_prediction_requires_modifier() {
7298 if !self.edit_prediction_preview_is_active() {
7299 return None;
7300 }
7301
7302 self.render_edit_prediction_modifier_jump_popover(
7303 text_bounds,
7304 content_origin,
7305 visible_row_range,
7306 line_layouts,
7307 line_height,
7308 scroll_pixel_position,
7309 newest_selection_head,
7310 target_display_point,
7311 window,
7312 cx,
7313 )
7314 } else {
7315 self.render_edit_prediction_eager_jump_popover(
7316 text_bounds,
7317 content_origin,
7318 editor_snapshot,
7319 visible_row_range,
7320 scroll_top,
7321 scroll_bottom,
7322 line_height,
7323 scroll_pixel_position,
7324 target_display_point,
7325 editor_width,
7326 window,
7327 cx,
7328 )
7329 }
7330 }
7331 InlineCompletion::Edit {
7332 display_mode: EditDisplayMode::Inline,
7333 ..
7334 } => None,
7335 InlineCompletion::Edit {
7336 display_mode: EditDisplayMode::TabAccept,
7337 edits,
7338 ..
7339 } => {
7340 let range = &edits.first()?.0;
7341 let target_display_point = range.end.to_display_point(editor_snapshot);
7342
7343 self.render_edit_prediction_end_of_line_popover(
7344 "Accept",
7345 editor_snapshot,
7346 visible_row_range,
7347 target_display_point,
7348 line_height,
7349 scroll_pixel_position,
7350 content_origin,
7351 editor_width,
7352 window,
7353 cx,
7354 )
7355 }
7356 InlineCompletion::Edit {
7357 edits,
7358 edit_preview,
7359 display_mode: EditDisplayMode::DiffPopover,
7360 snapshot,
7361 } => self.render_edit_prediction_diff_popover(
7362 text_bounds,
7363 content_origin,
7364 editor_snapshot,
7365 visible_row_range,
7366 line_layouts,
7367 line_height,
7368 scroll_pixel_position,
7369 newest_selection_head,
7370 editor_width,
7371 style,
7372 edits,
7373 edit_preview,
7374 snapshot,
7375 window,
7376 cx,
7377 ),
7378 }
7379 }
7380
7381 fn render_edit_prediction_modifier_jump_popover(
7382 &mut self,
7383 text_bounds: &Bounds<Pixels>,
7384 content_origin: gpui::Point<Pixels>,
7385 visible_row_range: Range<DisplayRow>,
7386 line_layouts: &[LineWithInvisibles],
7387 line_height: Pixels,
7388 scroll_pixel_position: gpui::Point<Pixels>,
7389 newest_selection_head: Option<DisplayPoint>,
7390 target_display_point: DisplayPoint,
7391 window: &mut Window,
7392 cx: &mut App,
7393 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7394 let scrolled_content_origin =
7395 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7396
7397 const SCROLL_PADDING_Y: Pixels = px(12.);
7398
7399 if target_display_point.row() < visible_row_range.start {
7400 return self.render_edit_prediction_scroll_popover(
7401 |_| SCROLL_PADDING_Y,
7402 IconName::ArrowUp,
7403 visible_row_range,
7404 line_layouts,
7405 newest_selection_head,
7406 scrolled_content_origin,
7407 window,
7408 cx,
7409 );
7410 } else if target_display_point.row() >= visible_row_range.end {
7411 return self.render_edit_prediction_scroll_popover(
7412 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7413 IconName::ArrowDown,
7414 visible_row_range,
7415 line_layouts,
7416 newest_selection_head,
7417 scrolled_content_origin,
7418 window,
7419 cx,
7420 );
7421 }
7422
7423 const POLE_WIDTH: Pixels = px(2.);
7424
7425 let line_layout =
7426 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7427 let target_column = target_display_point.column() as usize;
7428
7429 let target_x = line_layout.x_for_index(target_column);
7430 let target_y =
7431 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7432
7433 let flag_on_right = target_x < text_bounds.size.width / 2.;
7434
7435 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7436 border_color.l += 0.001;
7437
7438 let mut element = v_flex()
7439 .items_end()
7440 .when(flag_on_right, |el| el.items_start())
7441 .child(if flag_on_right {
7442 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7443 .rounded_bl(px(0.))
7444 .rounded_tl(px(0.))
7445 .border_l_2()
7446 .border_color(border_color)
7447 } else {
7448 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7449 .rounded_br(px(0.))
7450 .rounded_tr(px(0.))
7451 .border_r_2()
7452 .border_color(border_color)
7453 })
7454 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7455 .into_any();
7456
7457 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7458
7459 let mut origin = scrolled_content_origin + point(target_x, target_y)
7460 - point(
7461 if flag_on_right {
7462 POLE_WIDTH
7463 } else {
7464 size.width - POLE_WIDTH
7465 },
7466 size.height - line_height,
7467 );
7468
7469 origin.x = origin.x.max(content_origin.x);
7470
7471 element.prepaint_at(origin, window, cx);
7472
7473 Some((element, origin))
7474 }
7475
7476 fn render_edit_prediction_scroll_popover(
7477 &mut self,
7478 to_y: impl Fn(Size<Pixels>) -> Pixels,
7479 scroll_icon: IconName,
7480 visible_row_range: Range<DisplayRow>,
7481 line_layouts: &[LineWithInvisibles],
7482 newest_selection_head: Option<DisplayPoint>,
7483 scrolled_content_origin: gpui::Point<Pixels>,
7484 window: &mut Window,
7485 cx: &mut App,
7486 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7487 let mut element = self
7488 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7489 .into_any();
7490
7491 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7492
7493 let cursor = newest_selection_head?;
7494 let cursor_row_layout =
7495 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7496 let cursor_column = cursor.column() as usize;
7497
7498 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7499
7500 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7501
7502 element.prepaint_at(origin, window, cx);
7503 Some((element, origin))
7504 }
7505
7506 fn render_edit_prediction_eager_jump_popover(
7507 &mut self,
7508 text_bounds: &Bounds<Pixels>,
7509 content_origin: gpui::Point<Pixels>,
7510 editor_snapshot: &EditorSnapshot,
7511 visible_row_range: Range<DisplayRow>,
7512 scroll_top: f32,
7513 scroll_bottom: f32,
7514 line_height: Pixels,
7515 scroll_pixel_position: gpui::Point<Pixels>,
7516 target_display_point: DisplayPoint,
7517 editor_width: Pixels,
7518 window: &mut Window,
7519 cx: &mut App,
7520 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7521 if target_display_point.row().as_f32() < scroll_top {
7522 let mut element = self
7523 .render_edit_prediction_line_popover(
7524 "Jump to Edit",
7525 Some(IconName::ArrowUp),
7526 window,
7527 cx,
7528 )?
7529 .into_any();
7530
7531 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7532 let offset = point(
7533 (text_bounds.size.width - size.width) / 2.,
7534 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7535 );
7536
7537 let origin = text_bounds.origin + offset;
7538 element.prepaint_at(origin, window, cx);
7539 Some((element, origin))
7540 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7541 let mut element = self
7542 .render_edit_prediction_line_popover(
7543 "Jump to Edit",
7544 Some(IconName::ArrowDown),
7545 window,
7546 cx,
7547 )?
7548 .into_any();
7549
7550 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7551 let offset = point(
7552 (text_bounds.size.width - size.width) / 2.,
7553 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7554 );
7555
7556 let origin = text_bounds.origin + offset;
7557 element.prepaint_at(origin, window, cx);
7558 Some((element, origin))
7559 } else {
7560 self.render_edit_prediction_end_of_line_popover(
7561 "Jump to Edit",
7562 editor_snapshot,
7563 visible_row_range,
7564 target_display_point,
7565 line_height,
7566 scroll_pixel_position,
7567 content_origin,
7568 editor_width,
7569 window,
7570 cx,
7571 )
7572 }
7573 }
7574
7575 fn render_edit_prediction_end_of_line_popover(
7576 self: &mut Editor,
7577 label: &'static str,
7578 editor_snapshot: &EditorSnapshot,
7579 visible_row_range: Range<DisplayRow>,
7580 target_display_point: DisplayPoint,
7581 line_height: Pixels,
7582 scroll_pixel_position: gpui::Point<Pixels>,
7583 content_origin: gpui::Point<Pixels>,
7584 editor_width: Pixels,
7585 window: &mut Window,
7586 cx: &mut App,
7587 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7588 let target_line_end = DisplayPoint::new(
7589 target_display_point.row(),
7590 editor_snapshot.line_len(target_display_point.row()),
7591 );
7592
7593 let mut element = self
7594 .render_edit_prediction_line_popover(label, None, window, cx)?
7595 .into_any();
7596
7597 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7598
7599 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7600
7601 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7602 let mut origin = start_point
7603 + line_origin
7604 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7605 origin.x = origin.x.max(content_origin.x);
7606
7607 let max_x = content_origin.x + editor_width - size.width;
7608
7609 if origin.x > max_x {
7610 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7611
7612 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7613 origin.y += offset;
7614 IconName::ArrowUp
7615 } else {
7616 origin.y -= offset;
7617 IconName::ArrowDown
7618 };
7619
7620 element = self
7621 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7622 .into_any();
7623
7624 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7625
7626 origin.x = content_origin.x + editor_width - size.width - px(2.);
7627 }
7628
7629 element.prepaint_at(origin, window, cx);
7630 Some((element, origin))
7631 }
7632
7633 fn render_edit_prediction_diff_popover(
7634 self: &Editor,
7635 text_bounds: &Bounds<Pixels>,
7636 content_origin: gpui::Point<Pixels>,
7637 editor_snapshot: &EditorSnapshot,
7638 visible_row_range: Range<DisplayRow>,
7639 line_layouts: &[LineWithInvisibles],
7640 line_height: Pixels,
7641 scroll_pixel_position: gpui::Point<Pixels>,
7642 newest_selection_head: Option<DisplayPoint>,
7643 editor_width: Pixels,
7644 style: &EditorStyle,
7645 edits: &Vec<(Range<Anchor>, String)>,
7646 edit_preview: &Option<language::EditPreview>,
7647 snapshot: &language::BufferSnapshot,
7648 window: &mut Window,
7649 cx: &mut App,
7650 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7651 let edit_start = edits
7652 .first()
7653 .unwrap()
7654 .0
7655 .start
7656 .to_display_point(editor_snapshot);
7657 let edit_end = edits
7658 .last()
7659 .unwrap()
7660 .0
7661 .end
7662 .to_display_point(editor_snapshot);
7663
7664 let is_visible = visible_row_range.contains(&edit_start.row())
7665 || visible_row_range.contains(&edit_end.row());
7666 if !is_visible {
7667 return None;
7668 }
7669
7670 let highlighted_edits =
7671 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7672
7673 let styled_text = highlighted_edits.to_styled_text(&style.text);
7674 let line_count = highlighted_edits.text.lines().count();
7675
7676 const BORDER_WIDTH: Pixels = px(1.);
7677
7678 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7679 let has_keybind = keybind.is_some();
7680
7681 let mut element = h_flex()
7682 .items_start()
7683 .child(
7684 h_flex()
7685 .bg(cx.theme().colors().editor_background)
7686 .border(BORDER_WIDTH)
7687 .shadow_sm()
7688 .border_color(cx.theme().colors().border)
7689 .rounded_l_lg()
7690 .when(line_count > 1, |el| el.rounded_br_lg())
7691 .pr_1()
7692 .child(styled_text),
7693 )
7694 .child(
7695 h_flex()
7696 .h(line_height + BORDER_WIDTH * 2.)
7697 .px_1p5()
7698 .gap_1()
7699 // Workaround: For some reason, there's a gap if we don't do this
7700 .ml(-BORDER_WIDTH)
7701 .shadow(smallvec![gpui::BoxShadow {
7702 color: gpui::black().opacity(0.05),
7703 offset: point(px(1.), px(1.)),
7704 blur_radius: px(2.),
7705 spread_radius: px(0.),
7706 }])
7707 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7708 .border(BORDER_WIDTH)
7709 .border_color(cx.theme().colors().border)
7710 .rounded_r_lg()
7711 .id("edit_prediction_diff_popover_keybind")
7712 .when(!has_keybind, |el| {
7713 let status_colors = cx.theme().status();
7714
7715 el.bg(status_colors.error_background)
7716 .border_color(status_colors.error.opacity(0.6))
7717 .child(Icon::new(IconName::Info).color(Color::Error))
7718 .cursor_default()
7719 .hoverable_tooltip(move |_window, cx| {
7720 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7721 })
7722 })
7723 .children(keybind),
7724 )
7725 .into_any();
7726
7727 let longest_row =
7728 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7729 let longest_line_width = if visible_row_range.contains(&longest_row) {
7730 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7731 } else {
7732 layout_line(
7733 longest_row,
7734 editor_snapshot,
7735 style,
7736 editor_width,
7737 |_| false,
7738 window,
7739 cx,
7740 )
7741 .width
7742 };
7743
7744 let viewport_bounds =
7745 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7746 right: -EditorElement::SCROLLBAR_WIDTH,
7747 ..Default::default()
7748 });
7749
7750 let x_after_longest =
7751 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7752 - scroll_pixel_position.x;
7753
7754 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7755
7756 // Fully visible if it can be displayed within the window (allow overlapping other
7757 // panes). However, this is only allowed if the popover starts within text_bounds.
7758 let can_position_to_the_right = x_after_longest < text_bounds.right()
7759 && x_after_longest + element_bounds.width < viewport_bounds.right();
7760
7761 let mut origin = if can_position_to_the_right {
7762 point(
7763 x_after_longest,
7764 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7765 - scroll_pixel_position.y,
7766 )
7767 } else {
7768 let cursor_row = newest_selection_head.map(|head| head.row());
7769 let above_edit = edit_start
7770 .row()
7771 .0
7772 .checked_sub(line_count as u32)
7773 .map(DisplayRow);
7774 let below_edit = Some(edit_end.row() + 1);
7775 let above_cursor =
7776 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7777 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7778
7779 // Place the edit popover adjacent to the edit if there is a location
7780 // available that is onscreen and does not obscure the cursor. Otherwise,
7781 // place it adjacent to the cursor.
7782 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7783 .into_iter()
7784 .flatten()
7785 .find(|&start_row| {
7786 let end_row = start_row + line_count as u32;
7787 visible_row_range.contains(&start_row)
7788 && visible_row_range.contains(&end_row)
7789 && cursor_row.map_or(true, |cursor_row| {
7790 !((start_row..end_row).contains(&cursor_row))
7791 })
7792 })?;
7793
7794 content_origin
7795 + point(
7796 -scroll_pixel_position.x,
7797 row_target.as_f32() * line_height - scroll_pixel_position.y,
7798 )
7799 };
7800
7801 origin.x -= BORDER_WIDTH;
7802
7803 window.defer_draw(element, origin, 1);
7804
7805 // Do not return an element, since it will already be drawn due to defer_draw.
7806 None
7807 }
7808
7809 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7810 px(30.)
7811 }
7812
7813 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7814 if self.read_only(cx) {
7815 cx.theme().players().read_only()
7816 } else {
7817 self.style.as_ref().unwrap().local_player
7818 }
7819 }
7820
7821 fn render_edit_prediction_accept_keybind(
7822 &self,
7823 window: &mut Window,
7824 cx: &App,
7825 ) -> Option<AnyElement> {
7826 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7827 let accept_keystroke = accept_binding.keystroke()?;
7828
7829 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7830
7831 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7832 Color::Accent
7833 } else {
7834 Color::Muted
7835 };
7836
7837 h_flex()
7838 .px_0p5()
7839 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7840 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7841 .text_size(TextSize::XSmall.rems(cx))
7842 .child(h_flex().children(ui::render_modifiers(
7843 &accept_keystroke.modifiers,
7844 PlatformStyle::platform(),
7845 Some(modifiers_color),
7846 Some(IconSize::XSmall.rems().into()),
7847 true,
7848 )))
7849 .when(is_platform_style_mac, |parent| {
7850 parent.child(accept_keystroke.key.clone())
7851 })
7852 .when(!is_platform_style_mac, |parent| {
7853 parent.child(
7854 Key::new(
7855 util::capitalize(&accept_keystroke.key),
7856 Some(Color::Default),
7857 )
7858 .size(Some(IconSize::XSmall.rems().into())),
7859 )
7860 })
7861 .into_any()
7862 .into()
7863 }
7864
7865 fn render_edit_prediction_line_popover(
7866 &self,
7867 label: impl Into<SharedString>,
7868 icon: Option<IconName>,
7869 window: &mut Window,
7870 cx: &App,
7871 ) -> Option<Stateful<Div>> {
7872 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7873
7874 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7875 let has_keybind = keybind.is_some();
7876
7877 let result = h_flex()
7878 .id("ep-line-popover")
7879 .py_0p5()
7880 .pl_1()
7881 .pr(padding_right)
7882 .gap_1()
7883 .rounded_md()
7884 .border_1()
7885 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7886 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7887 .shadow_sm()
7888 .when(!has_keybind, |el| {
7889 let status_colors = cx.theme().status();
7890
7891 el.bg(status_colors.error_background)
7892 .border_color(status_colors.error.opacity(0.6))
7893 .pl_2()
7894 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7895 .cursor_default()
7896 .hoverable_tooltip(move |_window, cx| {
7897 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7898 })
7899 })
7900 .children(keybind)
7901 .child(
7902 Label::new(label)
7903 .size(LabelSize::Small)
7904 .when(!has_keybind, |el| {
7905 el.color(cx.theme().status().error.into()).strikethrough()
7906 }),
7907 )
7908 .when(!has_keybind, |el| {
7909 el.child(
7910 h_flex().ml_1().child(
7911 Icon::new(IconName::Info)
7912 .size(IconSize::Small)
7913 .color(cx.theme().status().error.into()),
7914 ),
7915 )
7916 })
7917 .when_some(icon, |element, icon| {
7918 element.child(
7919 div()
7920 .mt(px(1.5))
7921 .child(Icon::new(icon).size(IconSize::Small)),
7922 )
7923 });
7924
7925 Some(result)
7926 }
7927
7928 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7929 let accent_color = cx.theme().colors().text_accent;
7930 let editor_bg_color = cx.theme().colors().editor_background;
7931 editor_bg_color.blend(accent_color.opacity(0.1))
7932 }
7933
7934 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7935 let accent_color = cx.theme().colors().text_accent;
7936 let editor_bg_color = cx.theme().colors().editor_background;
7937 editor_bg_color.blend(accent_color.opacity(0.6))
7938 }
7939
7940 fn render_edit_prediction_cursor_popover(
7941 &self,
7942 min_width: Pixels,
7943 max_width: Pixels,
7944 cursor_point: Point,
7945 style: &EditorStyle,
7946 accept_keystroke: Option<&gpui::Keystroke>,
7947 _window: &Window,
7948 cx: &mut Context<Editor>,
7949 ) -> Option<AnyElement> {
7950 let provider = self.edit_prediction_provider.as_ref()?;
7951
7952 if provider.provider.needs_terms_acceptance(cx) {
7953 return Some(
7954 h_flex()
7955 .min_w(min_width)
7956 .flex_1()
7957 .px_2()
7958 .py_1()
7959 .gap_3()
7960 .elevation_2(cx)
7961 .hover(|style| style.bg(cx.theme().colors().element_hover))
7962 .id("accept-terms")
7963 .cursor_pointer()
7964 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7965 .on_click(cx.listener(|this, _event, window, cx| {
7966 cx.stop_propagation();
7967 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7968 window.dispatch_action(
7969 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7970 cx,
7971 );
7972 }))
7973 .child(
7974 h_flex()
7975 .flex_1()
7976 .gap_2()
7977 .child(Icon::new(IconName::ZedPredict))
7978 .child(Label::new("Accept Terms of Service"))
7979 .child(div().w_full())
7980 .child(
7981 Icon::new(IconName::ArrowUpRight)
7982 .color(Color::Muted)
7983 .size(IconSize::Small),
7984 )
7985 .into_any_element(),
7986 )
7987 .into_any(),
7988 );
7989 }
7990
7991 let is_refreshing = provider.provider.is_refreshing(cx);
7992
7993 fn pending_completion_container() -> Div {
7994 h_flex()
7995 .h_full()
7996 .flex_1()
7997 .gap_2()
7998 .child(Icon::new(IconName::ZedPredict))
7999 }
8000
8001 let completion = match &self.active_inline_completion {
8002 Some(prediction) => {
8003 if !self.has_visible_completions_menu() {
8004 const RADIUS: Pixels = px(6.);
8005 const BORDER_WIDTH: Pixels = px(1.);
8006
8007 return Some(
8008 h_flex()
8009 .elevation_2(cx)
8010 .border(BORDER_WIDTH)
8011 .border_color(cx.theme().colors().border)
8012 .when(accept_keystroke.is_none(), |el| {
8013 el.border_color(cx.theme().status().error)
8014 })
8015 .rounded(RADIUS)
8016 .rounded_tl(px(0.))
8017 .overflow_hidden()
8018 .child(div().px_1p5().child(match &prediction.completion {
8019 InlineCompletion::Move { target, snapshot } => {
8020 use text::ToPoint as _;
8021 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
8022 {
8023 Icon::new(IconName::ZedPredictDown)
8024 } else {
8025 Icon::new(IconName::ZedPredictUp)
8026 }
8027 }
8028 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
8029 }))
8030 .child(
8031 h_flex()
8032 .gap_1()
8033 .py_1()
8034 .px_2()
8035 .rounded_r(RADIUS - BORDER_WIDTH)
8036 .border_l_1()
8037 .border_color(cx.theme().colors().border)
8038 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8039 .when(self.edit_prediction_preview.released_too_fast(), |el| {
8040 el.child(
8041 Label::new("Hold")
8042 .size(LabelSize::Small)
8043 .when(accept_keystroke.is_none(), |el| {
8044 el.strikethrough()
8045 })
8046 .line_height_style(LineHeightStyle::UiLabel),
8047 )
8048 })
8049 .id("edit_prediction_cursor_popover_keybind")
8050 .when(accept_keystroke.is_none(), |el| {
8051 let status_colors = cx.theme().status();
8052
8053 el.bg(status_colors.error_background)
8054 .border_color(status_colors.error.opacity(0.6))
8055 .child(Icon::new(IconName::Info).color(Color::Error))
8056 .cursor_default()
8057 .hoverable_tooltip(move |_window, cx| {
8058 cx.new(|_| MissingEditPredictionKeybindingTooltip)
8059 .into()
8060 })
8061 })
8062 .when_some(
8063 accept_keystroke.as_ref(),
8064 |el, accept_keystroke| {
8065 el.child(h_flex().children(ui::render_modifiers(
8066 &accept_keystroke.modifiers,
8067 PlatformStyle::platform(),
8068 Some(Color::Default),
8069 Some(IconSize::XSmall.rems().into()),
8070 false,
8071 )))
8072 },
8073 ),
8074 )
8075 .into_any(),
8076 );
8077 }
8078
8079 self.render_edit_prediction_cursor_popover_preview(
8080 prediction,
8081 cursor_point,
8082 style,
8083 cx,
8084 )?
8085 }
8086
8087 None if is_refreshing => match &self.stale_inline_completion_in_menu {
8088 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
8089 stale_completion,
8090 cursor_point,
8091 style,
8092 cx,
8093 )?,
8094
8095 None => {
8096 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
8097 }
8098 },
8099
8100 None => pending_completion_container().child(Label::new("No Prediction")),
8101 };
8102
8103 let completion = if is_refreshing {
8104 completion
8105 .with_animation(
8106 "loading-completion",
8107 Animation::new(Duration::from_secs(2))
8108 .repeat()
8109 .with_easing(pulsating_between(0.4, 0.8)),
8110 |label, delta| label.opacity(delta),
8111 )
8112 .into_any_element()
8113 } else {
8114 completion.into_any_element()
8115 };
8116
8117 let has_completion = self.active_inline_completion.is_some();
8118
8119 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
8120 Some(
8121 h_flex()
8122 .min_w(min_width)
8123 .max_w(max_width)
8124 .flex_1()
8125 .elevation_2(cx)
8126 .border_color(cx.theme().colors().border)
8127 .child(
8128 div()
8129 .flex_1()
8130 .py_1()
8131 .px_2()
8132 .overflow_hidden()
8133 .child(completion),
8134 )
8135 .when_some(accept_keystroke, |el, accept_keystroke| {
8136 if !accept_keystroke.modifiers.modified() {
8137 return el;
8138 }
8139
8140 el.child(
8141 h_flex()
8142 .h_full()
8143 .border_l_1()
8144 .rounded_r_lg()
8145 .border_color(cx.theme().colors().border)
8146 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8147 .gap_1()
8148 .py_1()
8149 .px_2()
8150 .child(
8151 h_flex()
8152 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8153 .when(is_platform_style_mac, |parent| parent.gap_1())
8154 .child(h_flex().children(ui::render_modifiers(
8155 &accept_keystroke.modifiers,
8156 PlatformStyle::platform(),
8157 Some(if !has_completion {
8158 Color::Muted
8159 } else {
8160 Color::Default
8161 }),
8162 None,
8163 false,
8164 ))),
8165 )
8166 .child(Label::new("Preview").into_any_element())
8167 .opacity(if has_completion { 1.0 } else { 0.4 }),
8168 )
8169 })
8170 .into_any(),
8171 )
8172 }
8173
8174 fn render_edit_prediction_cursor_popover_preview(
8175 &self,
8176 completion: &InlineCompletionState,
8177 cursor_point: Point,
8178 style: &EditorStyle,
8179 cx: &mut Context<Editor>,
8180 ) -> Option<Div> {
8181 use text::ToPoint as _;
8182
8183 fn render_relative_row_jump(
8184 prefix: impl Into<String>,
8185 current_row: u32,
8186 target_row: u32,
8187 ) -> Div {
8188 let (row_diff, arrow) = if target_row < current_row {
8189 (current_row - target_row, IconName::ArrowUp)
8190 } else {
8191 (target_row - current_row, IconName::ArrowDown)
8192 };
8193
8194 h_flex()
8195 .child(
8196 Label::new(format!("{}{}", prefix.into(), row_diff))
8197 .color(Color::Muted)
8198 .size(LabelSize::Small),
8199 )
8200 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
8201 }
8202
8203 match &completion.completion {
8204 InlineCompletion::Move {
8205 target, snapshot, ..
8206 } => Some(
8207 h_flex()
8208 .px_2()
8209 .gap_2()
8210 .flex_1()
8211 .child(
8212 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
8213 Icon::new(IconName::ZedPredictDown)
8214 } else {
8215 Icon::new(IconName::ZedPredictUp)
8216 },
8217 )
8218 .child(Label::new("Jump to Edit")),
8219 ),
8220
8221 InlineCompletion::Edit {
8222 edits,
8223 edit_preview,
8224 snapshot,
8225 display_mode: _,
8226 } => {
8227 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
8228
8229 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
8230 &snapshot,
8231 &edits,
8232 edit_preview.as_ref()?,
8233 true,
8234 cx,
8235 )
8236 .first_line_preview();
8237
8238 let styled_text = gpui::StyledText::new(highlighted_edits.text)
8239 .with_default_highlights(&style.text, highlighted_edits.highlights);
8240
8241 let preview = h_flex()
8242 .gap_1()
8243 .min_w_16()
8244 .child(styled_text)
8245 .when(has_more_lines, |parent| parent.child("…"));
8246
8247 let left = if first_edit_row != cursor_point.row {
8248 render_relative_row_jump("", cursor_point.row, first_edit_row)
8249 .into_any_element()
8250 } else {
8251 Icon::new(IconName::ZedPredict).into_any_element()
8252 };
8253
8254 Some(
8255 h_flex()
8256 .h_full()
8257 .flex_1()
8258 .gap_2()
8259 .pr_1()
8260 .overflow_x_hidden()
8261 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8262 .child(left)
8263 .child(preview),
8264 )
8265 }
8266 }
8267 }
8268
8269 fn render_context_menu(
8270 &self,
8271 style: &EditorStyle,
8272 max_height_in_lines: u32,
8273 window: &mut Window,
8274 cx: &mut Context<Editor>,
8275 ) -> Option<AnyElement> {
8276 let menu = self.context_menu.borrow();
8277 let menu = menu.as_ref()?;
8278 if !menu.visible() {
8279 return None;
8280 };
8281 Some(menu.render(style, max_height_in_lines, window, cx))
8282 }
8283
8284 fn render_context_menu_aside(
8285 &mut self,
8286 max_size: Size<Pixels>,
8287 window: &mut Window,
8288 cx: &mut Context<Editor>,
8289 ) -> Option<AnyElement> {
8290 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
8291 if menu.visible() {
8292 menu.render_aside(self, max_size, window, cx)
8293 } else {
8294 None
8295 }
8296 })
8297 }
8298
8299 fn hide_context_menu(
8300 &mut self,
8301 window: &mut Window,
8302 cx: &mut Context<Self>,
8303 ) -> Option<CodeContextMenu> {
8304 cx.notify();
8305 self.completion_tasks.clear();
8306 let context_menu = self.context_menu.borrow_mut().take();
8307 self.stale_inline_completion_in_menu.take();
8308 self.update_visible_inline_completion(window, cx);
8309 context_menu
8310 }
8311
8312 fn show_snippet_choices(
8313 &mut self,
8314 choices: &Vec<String>,
8315 selection: Range<Anchor>,
8316 cx: &mut Context<Self>,
8317 ) {
8318 if selection.start.buffer_id.is_none() {
8319 return;
8320 }
8321 let buffer_id = selection.start.buffer_id.unwrap();
8322 let buffer = self.buffer().read(cx).buffer(buffer_id);
8323 let id = post_inc(&mut self.next_completion_id);
8324 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
8325
8326 if let Some(buffer) = buffer {
8327 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8328 CompletionsMenu::new_snippet_choices(
8329 id,
8330 true,
8331 choices,
8332 selection,
8333 buffer,
8334 snippet_sort_order,
8335 ),
8336 ));
8337 }
8338 }
8339
8340 pub fn insert_snippet(
8341 &mut self,
8342 insertion_ranges: &[Range<usize>],
8343 snippet: Snippet,
8344 window: &mut Window,
8345 cx: &mut Context<Self>,
8346 ) -> Result<()> {
8347 struct Tabstop<T> {
8348 is_end_tabstop: bool,
8349 ranges: Vec<Range<T>>,
8350 choices: Option<Vec<String>>,
8351 }
8352
8353 let tabstops = self.buffer.update(cx, |buffer, cx| {
8354 let snippet_text: Arc<str> = snippet.text.clone().into();
8355 let edits = insertion_ranges
8356 .iter()
8357 .cloned()
8358 .map(|range| (range, snippet_text.clone()));
8359 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8360
8361 let snapshot = &*buffer.read(cx);
8362 let snippet = &snippet;
8363 snippet
8364 .tabstops
8365 .iter()
8366 .map(|tabstop| {
8367 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8368 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8369 });
8370 let mut tabstop_ranges = tabstop
8371 .ranges
8372 .iter()
8373 .flat_map(|tabstop_range| {
8374 let mut delta = 0_isize;
8375 insertion_ranges.iter().map(move |insertion_range| {
8376 let insertion_start = insertion_range.start as isize + delta;
8377 delta +=
8378 snippet.text.len() as isize - insertion_range.len() as isize;
8379
8380 let start = ((insertion_start + tabstop_range.start) as usize)
8381 .min(snapshot.len());
8382 let end = ((insertion_start + tabstop_range.end) as usize)
8383 .min(snapshot.len());
8384 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8385 })
8386 })
8387 .collect::<Vec<_>>();
8388 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8389
8390 Tabstop {
8391 is_end_tabstop,
8392 ranges: tabstop_ranges,
8393 choices: tabstop.choices.clone(),
8394 }
8395 })
8396 .collect::<Vec<_>>()
8397 });
8398 if let Some(tabstop) = tabstops.first() {
8399 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8400 s.select_ranges(tabstop.ranges.iter().cloned());
8401 });
8402
8403 if let Some(choices) = &tabstop.choices {
8404 if let Some(selection) = tabstop.ranges.first() {
8405 self.show_snippet_choices(choices, selection.clone(), cx)
8406 }
8407 }
8408
8409 // If we're already at the last tabstop and it's at the end of the snippet,
8410 // we're done, we don't need to keep the state around.
8411 if !tabstop.is_end_tabstop {
8412 let choices = tabstops
8413 .iter()
8414 .map(|tabstop| tabstop.choices.clone())
8415 .collect();
8416
8417 let ranges = tabstops
8418 .into_iter()
8419 .map(|tabstop| tabstop.ranges)
8420 .collect::<Vec<_>>();
8421
8422 self.snippet_stack.push(SnippetState {
8423 active_index: 0,
8424 ranges,
8425 choices,
8426 });
8427 }
8428
8429 // Check whether the just-entered snippet ends with an auto-closable bracket.
8430 if self.autoclose_regions.is_empty() {
8431 let snapshot = self.buffer.read(cx).snapshot(cx);
8432 for selection in &mut self.selections.all::<Point>(cx) {
8433 let selection_head = selection.head();
8434 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8435 continue;
8436 };
8437
8438 let mut bracket_pair = None;
8439 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8440 let prev_chars = snapshot
8441 .reversed_chars_at(selection_head)
8442 .collect::<String>();
8443 for (pair, enabled) in scope.brackets() {
8444 if enabled
8445 && pair.close
8446 && prev_chars.starts_with(pair.start.as_str())
8447 && next_chars.starts_with(pair.end.as_str())
8448 {
8449 bracket_pair = Some(pair.clone());
8450 break;
8451 }
8452 }
8453 if let Some(pair) = bracket_pair {
8454 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8455 let autoclose_enabled =
8456 self.use_autoclose && snapshot_settings.use_autoclose;
8457 if autoclose_enabled {
8458 let start = snapshot.anchor_after(selection_head);
8459 let end = snapshot.anchor_after(selection_head);
8460 self.autoclose_regions.push(AutocloseRegion {
8461 selection_id: selection.id,
8462 range: start..end,
8463 pair,
8464 });
8465 }
8466 }
8467 }
8468 }
8469 }
8470 Ok(())
8471 }
8472
8473 pub fn move_to_next_snippet_tabstop(
8474 &mut self,
8475 window: &mut Window,
8476 cx: &mut Context<Self>,
8477 ) -> bool {
8478 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8479 }
8480
8481 pub fn move_to_prev_snippet_tabstop(
8482 &mut self,
8483 window: &mut Window,
8484 cx: &mut Context<Self>,
8485 ) -> bool {
8486 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8487 }
8488
8489 pub fn move_to_snippet_tabstop(
8490 &mut self,
8491 bias: Bias,
8492 window: &mut Window,
8493 cx: &mut Context<Self>,
8494 ) -> bool {
8495 if let Some(mut snippet) = self.snippet_stack.pop() {
8496 match bias {
8497 Bias::Left => {
8498 if snippet.active_index > 0 {
8499 snippet.active_index -= 1;
8500 } else {
8501 self.snippet_stack.push(snippet);
8502 return false;
8503 }
8504 }
8505 Bias::Right => {
8506 if snippet.active_index + 1 < snippet.ranges.len() {
8507 snippet.active_index += 1;
8508 } else {
8509 self.snippet_stack.push(snippet);
8510 return false;
8511 }
8512 }
8513 }
8514 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8515 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8516 s.select_anchor_ranges(current_ranges.iter().cloned())
8517 });
8518
8519 if let Some(choices) = &snippet.choices[snippet.active_index] {
8520 if let Some(selection) = current_ranges.first() {
8521 self.show_snippet_choices(&choices, selection.clone(), cx);
8522 }
8523 }
8524
8525 // If snippet state is not at the last tabstop, push it back on the stack
8526 if snippet.active_index + 1 < snippet.ranges.len() {
8527 self.snippet_stack.push(snippet);
8528 }
8529 return true;
8530 }
8531 }
8532
8533 false
8534 }
8535
8536 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8537 self.transact(window, cx, |this, window, cx| {
8538 this.select_all(&SelectAll, window, cx);
8539 this.insert("", window, cx);
8540 });
8541 }
8542
8543 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8544 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8545 self.transact(window, cx, |this, window, cx| {
8546 this.select_autoclose_pair(window, cx);
8547 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8548 if !this.linked_edit_ranges.is_empty() {
8549 let selections = this.selections.all::<MultiBufferPoint>(cx);
8550 let snapshot = this.buffer.read(cx).snapshot(cx);
8551
8552 for selection in selections.iter() {
8553 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8554 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8555 if selection_start.buffer_id != selection_end.buffer_id {
8556 continue;
8557 }
8558 if let Some(ranges) =
8559 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8560 {
8561 for (buffer, entries) in ranges {
8562 linked_ranges.entry(buffer).or_default().extend(entries);
8563 }
8564 }
8565 }
8566 }
8567
8568 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8569 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8570 for selection in &mut selections {
8571 if selection.is_empty() {
8572 let old_head = selection.head();
8573 let mut new_head =
8574 movement::left(&display_map, old_head.to_display_point(&display_map))
8575 .to_point(&display_map);
8576 if let Some((buffer, line_buffer_range)) = display_map
8577 .buffer_snapshot
8578 .buffer_line_for_row(MultiBufferRow(old_head.row))
8579 {
8580 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8581 let indent_len = match indent_size.kind {
8582 IndentKind::Space => {
8583 buffer.settings_at(line_buffer_range.start, cx).tab_size
8584 }
8585 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8586 };
8587 if old_head.column <= indent_size.len && old_head.column > 0 {
8588 let indent_len = indent_len.get();
8589 new_head = cmp::min(
8590 new_head,
8591 MultiBufferPoint::new(
8592 old_head.row,
8593 ((old_head.column - 1) / indent_len) * indent_len,
8594 ),
8595 );
8596 }
8597 }
8598
8599 selection.set_head(new_head, SelectionGoal::None);
8600 }
8601 }
8602
8603 this.signature_help_state.set_backspace_pressed(true);
8604 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8605 s.select(selections)
8606 });
8607 this.insert("", window, cx);
8608 let empty_str: Arc<str> = Arc::from("");
8609 for (buffer, edits) in linked_ranges {
8610 let snapshot = buffer.read(cx).snapshot();
8611 use text::ToPoint as TP;
8612
8613 let edits = edits
8614 .into_iter()
8615 .map(|range| {
8616 let end_point = TP::to_point(&range.end, &snapshot);
8617 let mut start_point = TP::to_point(&range.start, &snapshot);
8618
8619 if end_point == start_point {
8620 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8621 .saturating_sub(1);
8622 start_point =
8623 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8624 };
8625
8626 (start_point..end_point, empty_str.clone())
8627 })
8628 .sorted_by_key(|(range, _)| range.start)
8629 .collect::<Vec<_>>();
8630 buffer.update(cx, |this, cx| {
8631 this.edit(edits, None, cx);
8632 })
8633 }
8634 this.refresh_inline_completion(true, false, window, cx);
8635 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8636 });
8637 }
8638
8639 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8640 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8641 self.transact(window, cx, |this, window, cx| {
8642 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8643 s.move_with(|map, selection| {
8644 if selection.is_empty() {
8645 let cursor = movement::right(map, selection.head());
8646 selection.end = cursor;
8647 selection.reversed = true;
8648 selection.goal = SelectionGoal::None;
8649 }
8650 })
8651 });
8652 this.insert("", window, cx);
8653 this.refresh_inline_completion(true, false, window, cx);
8654 });
8655 }
8656
8657 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8658 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8659 if self.move_to_prev_snippet_tabstop(window, cx) {
8660 return;
8661 }
8662 self.outdent(&Outdent, window, cx);
8663 }
8664
8665 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8666 if self.move_to_next_snippet_tabstop(window, cx) {
8667 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8668 return;
8669 }
8670 if self.read_only(cx) {
8671 return;
8672 }
8673 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8674 let mut selections = self.selections.all_adjusted(cx);
8675 let buffer = self.buffer.read(cx);
8676 let snapshot = buffer.snapshot(cx);
8677 let rows_iter = selections.iter().map(|s| s.head().row);
8678 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8679
8680 let has_some_cursor_in_whitespace = selections
8681 .iter()
8682 .filter(|selection| selection.is_empty())
8683 .any(|selection| {
8684 let cursor = selection.head();
8685 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8686 cursor.column < current_indent.len
8687 });
8688
8689 let mut edits = Vec::new();
8690 let mut prev_edited_row = 0;
8691 let mut row_delta = 0;
8692 for selection in &mut selections {
8693 if selection.start.row != prev_edited_row {
8694 row_delta = 0;
8695 }
8696 prev_edited_row = selection.end.row;
8697
8698 // If the selection is non-empty, then increase the indentation of the selected lines.
8699 if !selection.is_empty() {
8700 row_delta =
8701 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8702 continue;
8703 }
8704
8705 // If the selection is empty and the cursor is in the leading whitespace before the
8706 // suggested indentation, then auto-indent the line.
8707 let cursor = selection.head();
8708 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8709 if let Some(suggested_indent) =
8710 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8711 {
8712 // If there exist any empty selection in the leading whitespace, then skip
8713 // indent for selections at the boundary.
8714 if has_some_cursor_in_whitespace
8715 && cursor.column == current_indent.len
8716 && current_indent.len == suggested_indent.len
8717 {
8718 continue;
8719 }
8720
8721 if cursor.column < suggested_indent.len
8722 && cursor.column <= current_indent.len
8723 && current_indent.len <= suggested_indent.len
8724 {
8725 selection.start = Point::new(cursor.row, suggested_indent.len);
8726 selection.end = selection.start;
8727 if row_delta == 0 {
8728 edits.extend(Buffer::edit_for_indent_size_adjustment(
8729 cursor.row,
8730 current_indent,
8731 suggested_indent,
8732 ));
8733 row_delta = suggested_indent.len - current_indent.len;
8734 }
8735 continue;
8736 }
8737 }
8738
8739 // Otherwise, insert a hard or soft tab.
8740 let settings = buffer.language_settings_at(cursor, cx);
8741 let tab_size = if settings.hard_tabs {
8742 IndentSize::tab()
8743 } else {
8744 let tab_size = settings.tab_size.get();
8745 let indent_remainder = snapshot
8746 .text_for_range(Point::new(cursor.row, 0)..cursor)
8747 .flat_map(str::chars)
8748 .fold(row_delta % tab_size, |counter: u32, c| {
8749 if c == '\t' {
8750 0
8751 } else {
8752 (counter + 1) % tab_size
8753 }
8754 });
8755
8756 let chars_to_next_tab_stop = tab_size - indent_remainder;
8757 IndentSize::spaces(chars_to_next_tab_stop)
8758 };
8759 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8760 selection.end = selection.start;
8761 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8762 row_delta += tab_size.len;
8763 }
8764
8765 self.transact(window, cx, |this, window, cx| {
8766 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8767 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8768 s.select(selections)
8769 });
8770 this.refresh_inline_completion(true, false, window, cx);
8771 });
8772 }
8773
8774 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8775 if self.read_only(cx) {
8776 return;
8777 }
8778 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8779 let mut selections = self.selections.all::<Point>(cx);
8780 let mut prev_edited_row = 0;
8781 let mut row_delta = 0;
8782 let mut edits = Vec::new();
8783 let buffer = self.buffer.read(cx);
8784 let snapshot = buffer.snapshot(cx);
8785 for selection in &mut selections {
8786 if selection.start.row != prev_edited_row {
8787 row_delta = 0;
8788 }
8789 prev_edited_row = selection.end.row;
8790
8791 row_delta =
8792 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8793 }
8794
8795 self.transact(window, cx, |this, window, cx| {
8796 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8797 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8798 s.select(selections)
8799 });
8800 });
8801 }
8802
8803 fn indent_selection(
8804 buffer: &MultiBuffer,
8805 snapshot: &MultiBufferSnapshot,
8806 selection: &mut Selection<Point>,
8807 edits: &mut Vec<(Range<Point>, String)>,
8808 delta_for_start_row: u32,
8809 cx: &App,
8810 ) -> u32 {
8811 let settings = buffer.language_settings_at(selection.start, cx);
8812 let tab_size = settings.tab_size.get();
8813 let indent_kind = if settings.hard_tabs {
8814 IndentKind::Tab
8815 } else {
8816 IndentKind::Space
8817 };
8818 let mut start_row = selection.start.row;
8819 let mut end_row = selection.end.row + 1;
8820
8821 // If a selection ends at the beginning of a line, don't indent
8822 // that last line.
8823 if selection.end.column == 0 && selection.end.row > selection.start.row {
8824 end_row -= 1;
8825 }
8826
8827 // Avoid re-indenting a row that has already been indented by a
8828 // previous selection, but still update this selection's column
8829 // to reflect that indentation.
8830 if delta_for_start_row > 0 {
8831 start_row += 1;
8832 selection.start.column += delta_for_start_row;
8833 if selection.end.row == selection.start.row {
8834 selection.end.column += delta_for_start_row;
8835 }
8836 }
8837
8838 let mut delta_for_end_row = 0;
8839 let has_multiple_rows = start_row + 1 != end_row;
8840 for row in start_row..end_row {
8841 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8842 let indent_delta = match (current_indent.kind, indent_kind) {
8843 (IndentKind::Space, IndentKind::Space) => {
8844 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8845 IndentSize::spaces(columns_to_next_tab_stop)
8846 }
8847 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8848 (_, IndentKind::Tab) => IndentSize::tab(),
8849 };
8850
8851 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8852 0
8853 } else {
8854 selection.start.column
8855 };
8856 let row_start = Point::new(row, start);
8857 edits.push((
8858 row_start..row_start,
8859 indent_delta.chars().collect::<String>(),
8860 ));
8861
8862 // Update this selection's endpoints to reflect the indentation.
8863 if row == selection.start.row {
8864 selection.start.column += indent_delta.len;
8865 }
8866 if row == selection.end.row {
8867 selection.end.column += indent_delta.len;
8868 delta_for_end_row = indent_delta.len;
8869 }
8870 }
8871
8872 if selection.start.row == selection.end.row {
8873 delta_for_start_row + delta_for_end_row
8874 } else {
8875 delta_for_end_row
8876 }
8877 }
8878
8879 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8880 if self.read_only(cx) {
8881 return;
8882 }
8883 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8884 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8885 let selections = self.selections.all::<Point>(cx);
8886 let mut deletion_ranges = Vec::new();
8887 let mut last_outdent = None;
8888 {
8889 let buffer = self.buffer.read(cx);
8890 let snapshot = buffer.snapshot(cx);
8891 for selection in &selections {
8892 let settings = buffer.language_settings_at(selection.start, cx);
8893 let tab_size = settings.tab_size.get();
8894 let mut rows = selection.spanned_rows(false, &display_map);
8895
8896 // Avoid re-outdenting a row that has already been outdented by a
8897 // previous selection.
8898 if let Some(last_row) = last_outdent {
8899 if last_row == rows.start {
8900 rows.start = rows.start.next_row();
8901 }
8902 }
8903 let has_multiple_rows = rows.len() > 1;
8904 for row in rows.iter_rows() {
8905 let indent_size = snapshot.indent_size_for_line(row);
8906 if indent_size.len > 0 {
8907 let deletion_len = match indent_size.kind {
8908 IndentKind::Space => {
8909 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8910 if columns_to_prev_tab_stop == 0 {
8911 tab_size
8912 } else {
8913 columns_to_prev_tab_stop
8914 }
8915 }
8916 IndentKind::Tab => 1,
8917 };
8918 let start = if has_multiple_rows
8919 || deletion_len > selection.start.column
8920 || indent_size.len < selection.start.column
8921 {
8922 0
8923 } else {
8924 selection.start.column - deletion_len
8925 };
8926 deletion_ranges.push(
8927 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8928 );
8929 last_outdent = Some(row);
8930 }
8931 }
8932 }
8933 }
8934
8935 self.transact(window, cx, |this, window, cx| {
8936 this.buffer.update(cx, |buffer, cx| {
8937 let empty_str: Arc<str> = Arc::default();
8938 buffer.edit(
8939 deletion_ranges
8940 .into_iter()
8941 .map(|range| (range, empty_str.clone())),
8942 None,
8943 cx,
8944 );
8945 });
8946 let selections = this.selections.all::<usize>(cx);
8947 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8948 s.select(selections)
8949 });
8950 });
8951 }
8952
8953 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8954 if self.read_only(cx) {
8955 return;
8956 }
8957 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8958 let selections = self
8959 .selections
8960 .all::<usize>(cx)
8961 .into_iter()
8962 .map(|s| s.range());
8963
8964 self.transact(window, cx, |this, window, cx| {
8965 this.buffer.update(cx, |buffer, cx| {
8966 buffer.autoindent_ranges(selections, cx);
8967 });
8968 let selections = this.selections.all::<usize>(cx);
8969 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8970 s.select(selections)
8971 });
8972 });
8973 }
8974
8975 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8976 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8977 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8978 let selections = self.selections.all::<Point>(cx);
8979
8980 let mut new_cursors = Vec::new();
8981 let mut edit_ranges = Vec::new();
8982 let mut selections = selections.iter().peekable();
8983 while let Some(selection) = selections.next() {
8984 let mut rows = selection.spanned_rows(false, &display_map);
8985 let goal_display_column = selection.head().to_display_point(&display_map).column();
8986
8987 // Accumulate contiguous regions of rows that we want to delete.
8988 while let Some(next_selection) = selections.peek() {
8989 let next_rows = next_selection.spanned_rows(false, &display_map);
8990 if next_rows.start <= rows.end {
8991 rows.end = next_rows.end;
8992 selections.next().unwrap();
8993 } else {
8994 break;
8995 }
8996 }
8997
8998 let buffer = &display_map.buffer_snapshot;
8999 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
9000 let edit_end;
9001 let cursor_buffer_row;
9002 if buffer.max_point().row >= rows.end.0 {
9003 // If there's a line after the range, delete the \n from the end of the row range
9004 // and position the cursor on the next line.
9005 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
9006 cursor_buffer_row = rows.end;
9007 } else {
9008 // If there isn't a line after the range, delete the \n from the line before the
9009 // start of the row range and position the cursor there.
9010 edit_start = edit_start.saturating_sub(1);
9011 edit_end = buffer.len();
9012 cursor_buffer_row = rows.start.previous_row();
9013 }
9014
9015 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
9016 *cursor.column_mut() =
9017 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
9018
9019 new_cursors.push((
9020 selection.id,
9021 buffer.anchor_after(cursor.to_point(&display_map)),
9022 ));
9023 edit_ranges.push(edit_start..edit_end);
9024 }
9025
9026 self.transact(window, cx, |this, window, cx| {
9027 let buffer = this.buffer.update(cx, |buffer, cx| {
9028 let empty_str: Arc<str> = Arc::default();
9029 buffer.edit(
9030 edit_ranges
9031 .into_iter()
9032 .map(|range| (range, empty_str.clone())),
9033 None,
9034 cx,
9035 );
9036 buffer.snapshot(cx)
9037 });
9038 let new_selections = new_cursors
9039 .into_iter()
9040 .map(|(id, cursor)| {
9041 let cursor = cursor.to_point(&buffer);
9042 Selection {
9043 id,
9044 start: cursor,
9045 end: cursor,
9046 reversed: false,
9047 goal: SelectionGoal::None,
9048 }
9049 })
9050 .collect();
9051
9052 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9053 s.select(new_selections);
9054 });
9055 });
9056 }
9057
9058 pub fn join_lines_impl(
9059 &mut self,
9060 insert_whitespace: bool,
9061 window: &mut Window,
9062 cx: &mut Context<Self>,
9063 ) {
9064 if self.read_only(cx) {
9065 return;
9066 }
9067 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
9068 for selection in self.selections.all::<Point>(cx) {
9069 let start = MultiBufferRow(selection.start.row);
9070 // Treat single line selections as if they include the next line. Otherwise this action
9071 // would do nothing for single line selections individual cursors.
9072 let end = if selection.start.row == selection.end.row {
9073 MultiBufferRow(selection.start.row + 1)
9074 } else {
9075 MultiBufferRow(selection.end.row)
9076 };
9077
9078 if let Some(last_row_range) = row_ranges.last_mut() {
9079 if start <= last_row_range.end {
9080 last_row_range.end = end;
9081 continue;
9082 }
9083 }
9084 row_ranges.push(start..end);
9085 }
9086
9087 let snapshot = self.buffer.read(cx).snapshot(cx);
9088 let mut cursor_positions = Vec::new();
9089 for row_range in &row_ranges {
9090 let anchor = snapshot.anchor_before(Point::new(
9091 row_range.end.previous_row().0,
9092 snapshot.line_len(row_range.end.previous_row()),
9093 ));
9094 cursor_positions.push(anchor..anchor);
9095 }
9096
9097 self.transact(window, cx, |this, window, cx| {
9098 for row_range in row_ranges.into_iter().rev() {
9099 for row in row_range.iter_rows().rev() {
9100 let end_of_line = Point::new(row.0, snapshot.line_len(row));
9101 let next_line_row = row.next_row();
9102 let indent = snapshot.indent_size_for_line(next_line_row);
9103 let start_of_next_line = Point::new(next_line_row.0, indent.len);
9104
9105 let replace =
9106 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
9107 " "
9108 } else {
9109 ""
9110 };
9111
9112 this.buffer.update(cx, |buffer, cx| {
9113 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
9114 });
9115 }
9116 }
9117
9118 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9119 s.select_anchor_ranges(cursor_positions)
9120 });
9121 });
9122 }
9123
9124 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
9125 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9126 self.join_lines_impl(true, window, cx);
9127 }
9128
9129 pub fn sort_lines_case_sensitive(
9130 &mut self,
9131 _: &SortLinesCaseSensitive,
9132 window: &mut Window,
9133 cx: &mut Context<Self>,
9134 ) {
9135 self.manipulate_lines(window, cx, |lines| lines.sort())
9136 }
9137
9138 pub fn sort_lines_case_insensitive(
9139 &mut self,
9140 _: &SortLinesCaseInsensitive,
9141 window: &mut Window,
9142 cx: &mut Context<Self>,
9143 ) {
9144 self.manipulate_lines(window, cx, |lines| {
9145 lines.sort_by_key(|line| line.to_lowercase())
9146 })
9147 }
9148
9149 pub fn unique_lines_case_insensitive(
9150 &mut self,
9151 _: &UniqueLinesCaseInsensitive,
9152 window: &mut Window,
9153 cx: &mut Context<Self>,
9154 ) {
9155 self.manipulate_lines(window, cx, |lines| {
9156 let mut seen = HashSet::default();
9157 lines.retain(|line| seen.insert(line.to_lowercase()));
9158 })
9159 }
9160
9161 pub fn unique_lines_case_sensitive(
9162 &mut self,
9163 _: &UniqueLinesCaseSensitive,
9164 window: &mut Window,
9165 cx: &mut Context<Self>,
9166 ) {
9167 self.manipulate_lines(window, cx, |lines| {
9168 let mut seen = HashSet::default();
9169 lines.retain(|line| seen.insert(*line));
9170 })
9171 }
9172
9173 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
9174 let Some(project) = self.project.clone() else {
9175 return;
9176 };
9177 self.reload(project, window, cx)
9178 .detach_and_notify_err(window, cx);
9179 }
9180
9181 pub fn restore_file(
9182 &mut self,
9183 _: &::git::RestoreFile,
9184 window: &mut Window,
9185 cx: &mut Context<Self>,
9186 ) {
9187 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9188 let mut buffer_ids = HashSet::default();
9189 let snapshot = self.buffer().read(cx).snapshot(cx);
9190 for selection in self.selections.all::<usize>(cx) {
9191 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
9192 }
9193
9194 let buffer = self.buffer().read(cx);
9195 let ranges = buffer_ids
9196 .into_iter()
9197 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
9198 .collect::<Vec<_>>();
9199
9200 self.restore_hunks_in_ranges(ranges, window, cx);
9201 }
9202
9203 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
9204 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9205 let selections = self
9206 .selections
9207 .all(cx)
9208 .into_iter()
9209 .map(|s| s.range())
9210 .collect();
9211 self.restore_hunks_in_ranges(selections, window, cx);
9212 }
9213
9214 pub fn restore_hunks_in_ranges(
9215 &mut self,
9216 ranges: Vec<Range<Point>>,
9217 window: &mut Window,
9218 cx: &mut Context<Editor>,
9219 ) {
9220 let mut revert_changes = HashMap::default();
9221 let chunk_by = self
9222 .snapshot(window, cx)
9223 .hunks_for_ranges(ranges)
9224 .into_iter()
9225 .chunk_by(|hunk| hunk.buffer_id);
9226 for (buffer_id, hunks) in &chunk_by {
9227 let hunks = hunks.collect::<Vec<_>>();
9228 for hunk in &hunks {
9229 self.prepare_restore_change(&mut revert_changes, hunk, cx);
9230 }
9231 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
9232 }
9233 drop(chunk_by);
9234 if !revert_changes.is_empty() {
9235 self.transact(window, cx, |editor, window, cx| {
9236 editor.restore(revert_changes, window, cx);
9237 });
9238 }
9239 }
9240
9241 pub fn open_active_item_in_terminal(
9242 &mut self,
9243 _: &OpenInTerminal,
9244 window: &mut Window,
9245 cx: &mut Context<Self>,
9246 ) {
9247 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
9248 let project_path = buffer.read(cx).project_path(cx)?;
9249 let project = self.project.as_ref()?.read(cx);
9250 let entry = project.entry_for_path(&project_path, cx)?;
9251 let parent = match &entry.canonical_path {
9252 Some(canonical_path) => canonical_path.to_path_buf(),
9253 None => project.absolute_path(&project_path, cx)?,
9254 }
9255 .parent()?
9256 .to_path_buf();
9257 Some(parent)
9258 }) {
9259 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
9260 }
9261 }
9262
9263 fn set_breakpoint_context_menu(
9264 &mut self,
9265 display_row: DisplayRow,
9266 position: Option<Anchor>,
9267 clicked_point: gpui::Point<Pixels>,
9268 window: &mut Window,
9269 cx: &mut Context<Self>,
9270 ) {
9271 if !cx.has_flag::<DebuggerFeatureFlag>() {
9272 return;
9273 }
9274 let source = self
9275 .buffer
9276 .read(cx)
9277 .snapshot(cx)
9278 .anchor_before(Point::new(display_row.0, 0u32));
9279
9280 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
9281
9282 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
9283 self,
9284 source,
9285 clicked_point,
9286 context_menu,
9287 window,
9288 cx,
9289 );
9290 }
9291
9292 fn add_edit_breakpoint_block(
9293 &mut self,
9294 anchor: Anchor,
9295 breakpoint: &Breakpoint,
9296 edit_action: BreakpointPromptEditAction,
9297 window: &mut Window,
9298 cx: &mut Context<Self>,
9299 ) {
9300 let weak_editor = cx.weak_entity();
9301 let bp_prompt = cx.new(|cx| {
9302 BreakpointPromptEditor::new(
9303 weak_editor,
9304 anchor,
9305 breakpoint.clone(),
9306 edit_action,
9307 window,
9308 cx,
9309 )
9310 });
9311
9312 let height = bp_prompt.update(cx, |this, cx| {
9313 this.prompt
9314 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
9315 });
9316 let cloned_prompt = bp_prompt.clone();
9317 let blocks = vec![BlockProperties {
9318 style: BlockStyle::Sticky,
9319 placement: BlockPlacement::Above(anchor),
9320 height: Some(height),
9321 render: Arc::new(move |cx| {
9322 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
9323 cloned_prompt.clone().into_any_element()
9324 }),
9325 priority: 0,
9326 }];
9327
9328 let focus_handle = bp_prompt.focus_handle(cx);
9329 window.focus(&focus_handle);
9330
9331 let block_ids = self.insert_blocks(blocks, None, cx);
9332 bp_prompt.update(cx, |prompt, _| {
9333 prompt.add_block_ids(block_ids);
9334 });
9335 }
9336
9337 pub(crate) fn breakpoint_at_row(
9338 &self,
9339 row: u32,
9340 window: &mut Window,
9341 cx: &mut Context<Self>,
9342 ) -> Option<(Anchor, Breakpoint)> {
9343 let snapshot = self.snapshot(window, cx);
9344 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9345
9346 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9347 }
9348
9349 pub(crate) fn breakpoint_at_anchor(
9350 &self,
9351 breakpoint_position: Anchor,
9352 snapshot: &EditorSnapshot,
9353 cx: &mut Context<Self>,
9354 ) -> Option<(Anchor, Breakpoint)> {
9355 let project = self.project.clone()?;
9356
9357 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9358 snapshot
9359 .buffer_snapshot
9360 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9361 })?;
9362
9363 let enclosing_excerpt = breakpoint_position.excerpt_id;
9364 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9365 let buffer_snapshot = buffer.read(cx).snapshot();
9366
9367 let row = buffer_snapshot
9368 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9369 .row;
9370
9371 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9372 let anchor_end = snapshot
9373 .buffer_snapshot
9374 .anchor_after(Point::new(row, line_len));
9375
9376 let bp = self
9377 .breakpoint_store
9378 .as_ref()?
9379 .read_with(cx, |breakpoint_store, cx| {
9380 breakpoint_store
9381 .breakpoints(
9382 &buffer,
9383 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9384 &buffer_snapshot,
9385 cx,
9386 )
9387 .next()
9388 .and_then(|(anchor, bp)| {
9389 let breakpoint_row = buffer_snapshot
9390 .summary_for_anchor::<text::PointUtf16>(anchor)
9391 .row;
9392
9393 if breakpoint_row == row {
9394 snapshot
9395 .buffer_snapshot
9396 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9397 .map(|anchor| (anchor, bp.clone()))
9398 } else {
9399 None
9400 }
9401 })
9402 });
9403 bp
9404 }
9405
9406 pub fn edit_log_breakpoint(
9407 &mut self,
9408 _: &EditLogBreakpoint,
9409 window: &mut Window,
9410 cx: &mut Context<Self>,
9411 ) {
9412 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9413 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9414 message: None,
9415 state: BreakpointState::Enabled,
9416 condition: None,
9417 hit_condition: None,
9418 });
9419
9420 self.add_edit_breakpoint_block(
9421 anchor,
9422 &breakpoint,
9423 BreakpointPromptEditAction::Log,
9424 window,
9425 cx,
9426 );
9427 }
9428 }
9429
9430 fn breakpoints_at_cursors(
9431 &self,
9432 window: &mut Window,
9433 cx: &mut Context<Self>,
9434 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9435 let snapshot = self.snapshot(window, cx);
9436 let cursors = self
9437 .selections
9438 .disjoint_anchors()
9439 .into_iter()
9440 .map(|selection| {
9441 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9442
9443 let breakpoint_position = self
9444 .breakpoint_at_row(cursor_position.row, window, cx)
9445 .map(|bp| bp.0)
9446 .unwrap_or_else(|| {
9447 snapshot
9448 .display_snapshot
9449 .buffer_snapshot
9450 .anchor_after(Point::new(cursor_position.row, 0))
9451 });
9452
9453 let breakpoint = self
9454 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9455 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9456
9457 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9458 })
9459 // 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.
9460 .collect::<HashMap<Anchor, _>>();
9461
9462 cursors.into_iter().collect()
9463 }
9464
9465 pub fn enable_breakpoint(
9466 &mut self,
9467 _: &crate::actions::EnableBreakpoint,
9468 window: &mut Window,
9469 cx: &mut Context<Self>,
9470 ) {
9471 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9472 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9473 continue;
9474 };
9475 self.edit_breakpoint_at_anchor(
9476 anchor,
9477 breakpoint,
9478 BreakpointEditAction::InvertState,
9479 cx,
9480 );
9481 }
9482 }
9483
9484 pub fn disable_breakpoint(
9485 &mut self,
9486 _: &crate::actions::DisableBreakpoint,
9487 window: &mut Window,
9488 cx: &mut Context<Self>,
9489 ) {
9490 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9491 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9492 continue;
9493 };
9494 self.edit_breakpoint_at_anchor(
9495 anchor,
9496 breakpoint,
9497 BreakpointEditAction::InvertState,
9498 cx,
9499 );
9500 }
9501 }
9502
9503 pub fn toggle_breakpoint(
9504 &mut self,
9505 _: &crate::actions::ToggleBreakpoint,
9506 window: &mut Window,
9507 cx: &mut Context<Self>,
9508 ) {
9509 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9510 if let Some(breakpoint) = breakpoint {
9511 self.edit_breakpoint_at_anchor(
9512 anchor,
9513 breakpoint,
9514 BreakpointEditAction::Toggle,
9515 cx,
9516 );
9517 } else {
9518 self.edit_breakpoint_at_anchor(
9519 anchor,
9520 Breakpoint::new_standard(),
9521 BreakpointEditAction::Toggle,
9522 cx,
9523 );
9524 }
9525 }
9526 }
9527
9528 pub fn edit_breakpoint_at_anchor(
9529 &mut self,
9530 breakpoint_position: Anchor,
9531 breakpoint: Breakpoint,
9532 edit_action: BreakpointEditAction,
9533 cx: &mut Context<Self>,
9534 ) {
9535 let Some(breakpoint_store) = &self.breakpoint_store else {
9536 return;
9537 };
9538
9539 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9540 if breakpoint_position == Anchor::min() {
9541 self.buffer()
9542 .read(cx)
9543 .excerpt_buffer_ids()
9544 .into_iter()
9545 .next()
9546 } else {
9547 None
9548 }
9549 }) else {
9550 return;
9551 };
9552
9553 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9554 return;
9555 };
9556
9557 breakpoint_store.update(cx, |breakpoint_store, cx| {
9558 breakpoint_store.toggle_breakpoint(
9559 buffer,
9560 (breakpoint_position.text_anchor, breakpoint),
9561 edit_action,
9562 cx,
9563 );
9564 });
9565
9566 cx.notify();
9567 }
9568
9569 #[cfg(any(test, feature = "test-support"))]
9570 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9571 self.breakpoint_store.clone()
9572 }
9573
9574 pub fn prepare_restore_change(
9575 &self,
9576 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9577 hunk: &MultiBufferDiffHunk,
9578 cx: &mut App,
9579 ) -> Option<()> {
9580 if hunk.is_created_file() {
9581 return None;
9582 }
9583 let buffer = self.buffer.read(cx);
9584 let diff = buffer.diff_for(hunk.buffer_id)?;
9585 let buffer = buffer.buffer(hunk.buffer_id)?;
9586 let buffer = buffer.read(cx);
9587 let original_text = diff
9588 .read(cx)
9589 .base_text()
9590 .as_rope()
9591 .slice(hunk.diff_base_byte_range.clone());
9592 let buffer_snapshot = buffer.snapshot();
9593 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9594 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9595 probe
9596 .0
9597 .start
9598 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9599 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9600 }) {
9601 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9602 Some(())
9603 } else {
9604 None
9605 }
9606 }
9607
9608 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9609 self.manipulate_lines(window, cx, |lines| lines.reverse())
9610 }
9611
9612 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9613 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9614 }
9615
9616 fn manipulate_lines<Fn>(
9617 &mut self,
9618 window: &mut Window,
9619 cx: &mut Context<Self>,
9620 mut callback: Fn,
9621 ) where
9622 Fn: FnMut(&mut Vec<&str>),
9623 {
9624 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9625
9626 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9627 let buffer = self.buffer.read(cx).snapshot(cx);
9628
9629 let mut edits = Vec::new();
9630
9631 let selections = self.selections.all::<Point>(cx);
9632 let mut selections = selections.iter().peekable();
9633 let mut contiguous_row_selections = Vec::new();
9634 let mut new_selections = Vec::new();
9635 let mut added_lines = 0;
9636 let mut removed_lines = 0;
9637
9638 while let Some(selection) = selections.next() {
9639 let (start_row, end_row) = consume_contiguous_rows(
9640 &mut contiguous_row_selections,
9641 selection,
9642 &display_map,
9643 &mut selections,
9644 );
9645
9646 let start_point = Point::new(start_row.0, 0);
9647 let end_point = Point::new(
9648 end_row.previous_row().0,
9649 buffer.line_len(end_row.previous_row()),
9650 );
9651 let text = buffer
9652 .text_for_range(start_point..end_point)
9653 .collect::<String>();
9654
9655 let mut lines = text.split('\n').collect_vec();
9656
9657 let lines_before = lines.len();
9658 callback(&mut lines);
9659 let lines_after = lines.len();
9660
9661 edits.push((start_point..end_point, lines.join("\n")));
9662
9663 // Selections must change based on added and removed line count
9664 let start_row =
9665 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9666 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9667 new_selections.push(Selection {
9668 id: selection.id,
9669 start: start_row,
9670 end: end_row,
9671 goal: SelectionGoal::None,
9672 reversed: selection.reversed,
9673 });
9674
9675 if lines_after > lines_before {
9676 added_lines += lines_after - lines_before;
9677 } else if lines_before > lines_after {
9678 removed_lines += lines_before - lines_after;
9679 }
9680 }
9681
9682 self.transact(window, cx, |this, window, cx| {
9683 let buffer = this.buffer.update(cx, |buffer, cx| {
9684 buffer.edit(edits, None, cx);
9685 buffer.snapshot(cx)
9686 });
9687
9688 // Recalculate offsets on newly edited buffer
9689 let new_selections = new_selections
9690 .iter()
9691 .map(|s| {
9692 let start_point = Point::new(s.start.0, 0);
9693 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9694 Selection {
9695 id: s.id,
9696 start: buffer.point_to_offset(start_point),
9697 end: buffer.point_to_offset(end_point),
9698 goal: s.goal,
9699 reversed: s.reversed,
9700 }
9701 })
9702 .collect();
9703
9704 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9705 s.select(new_selections);
9706 });
9707
9708 this.request_autoscroll(Autoscroll::fit(), cx);
9709 });
9710 }
9711
9712 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9713 self.manipulate_text(window, cx, |text| {
9714 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9715 if has_upper_case_characters {
9716 text.to_lowercase()
9717 } else {
9718 text.to_uppercase()
9719 }
9720 })
9721 }
9722
9723 pub fn convert_to_upper_case(
9724 &mut self,
9725 _: &ConvertToUpperCase,
9726 window: &mut Window,
9727 cx: &mut Context<Self>,
9728 ) {
9729 self.manipulate_text(window, cx, |text| text.to_uppercase())
9730 }
9731
9732 pub fn convert_to_lower_case(
9733 &mut self,
9734 _: &ConvertToLowerCase,
9735 window: &mut Window,
9736 cx: &mut Context<Self>,
9737 ) {
9738 self.manipulate_text(window, cx, |text| text.to_lowercase())
9739 }
9740
9741 pub fn convert_to_title_case(
9742 &mut self,
9743 _: &ConvertToTitleCase,
9744 window: &mut Window,
9745 cx: &mut Context<Self>,
9746 ) {
9747 self.manipulate_text(window, cx, |text| {
9748 text.split('\n')
9749 .map(|line| line.to_case(Case::Title))
9750 .join("\n")
9751 })
9752 }
9753
9754 pub fn convert_to_snake_case(
9755 &mut self,
9756 _: &ConvertToSnakeCase,
9757 window: &mut Window,
9758 cx: &mut Context<Self>,
9759 ) {
9760 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9761 }
9762
9763 pub fn convert_to_kebab_case(
9764 &mut self,
9765 _: &ConvertToKebabCase,
9766 window: &mut Window,
9767 cx: &mut Context<Self>,
9768 ) {
9769 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9770 }
9771
9772 pub fn convert_to_upper_camel_case(
9773 &mut self,
9774 _: &ConvertToUpperCamelCase,
9775 window: &mut Window,
9776 cx: &mut Context<Self>,
9777 ) {
9778 self.manipulate_text(window, cx, |text| {
9779 text.split('\n')
9780 .map(|line| line.to_case(Case::UpperCamel))
9781 .join("\n")
9782 })
9783 }
9784
9785 pub fn convert_to_lower_camel_case(
9786 &mut self,
9787 _: &ConvertToLowerCamelCase,
9788 window: &mut Window,
9789 cx: &mut Context<Self>,
9790 ) {
9791 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9792 }
9793
9794 pub fn convert_to_opposite_case(
9795 &mut self,
9796 _: &ConvertToOppositeCase,
9797 window: &mut Window,
9798 cx: &mut Context<Self>,
9799 ) {
9800 self.manipulate_text(window, cx, |text| {
9801 text.chars()
9802 .fold(String::with_capacity(text.len()), |mut t, c| {
9803 if c.is_uppercase() {
9804 t.extend(c.to_lowercase());
9805 } else {
9806 t.extend(c.to_uppercase());
9807 }
9808 t
9809 })
9810 })
9811 }
9812
9813 pub fn convert_to_rot13(
9814 &mut self,
9815 _: &ConvertToRot13,
9816 window: &mut Window,
9817 cx: &mut Context<Self>,
9818 ) {
9819 self.manipulate_text(window, cx, |text| {
9820 text.chars()
9821 .map(|c| match c {
9822 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9823 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9824 _ => c,
9825 })
9826 .collect()
9827 })
9828 }
9829
9830 pub fn convert_to_rot47(
9831 &mut self,
9832 _: &ConvertToRot47,
9833 window: &mut Window,
9834 cx: &mut Context<Self>,
9835 ) {
9836 self.manipulate_text(window, cx, |text| {
9837 text.chars()
9838 .map(|c| {
9839 let code_point = c as u32;
9840 if code_point >= 33 && code_point <= 126 {
9841 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9842 }
9843 c
9844 })
9845 .collect()
9846 })
9847 }
9848
9849 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9850 where
9851 Fn: FnMut(&str) -> String,
9852 {
9853 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9854 let buffer = self.buffer.read(cx).snapshot(cx);
9855
9856 let mut new_selections = Vec::new();
9857 let mut edits = Vec::new();
9858 let mut selection_adjustment = 0i32;
9859
9860 for selection in self.selections.all::<usize>(cx) {
9861 let selection_is_empty = selection.is_empty();
9862
9863 let (start, end) = if selection_is_empty {
9864 let word_range = movement::surrounding_word(
9865 &display_map,
9866 selection.start.to_display_point(&display_map),
9867 );
9868 let start = word_range.start.to_offset(&display_map, Bias::Left);
9869 let end = word_range.end.to_offset(&display_map, Bias::Left);
9870 (start, end)
9871 } else {
9872 (selection.start, selection.end)
9873 };
9874
9875 let text = buffer.text_for_range(start..end).collect::<String>();
9876 let old_length = text.len() as i32;
9877 let text = callback(&text);
9878
9879 new_selections.push(Selection {
9880 start: (start as i32 - selection_adjustment) as usize,
9881 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9882 goal: SelectionGoal::None,
9883 ..selection
9884 });
9885
9886 selection_adjustment += old_length - text.len() as i32;
9887
9888 edits.push((start..end, text));
9889 }
9890
9891 self.transact(window, cx, |this, window, cx| {
9892 this.buffer.update(cx, |buffer, cx| {
9893 buffer.edit(edits, None, cx);
9894 });
9895
9896 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9897 s.select(new_selections);
9898 });
9899
9900 this.request_autoscroll(Autoscroll::fit(), cx);
9901 });
9902 }
9903
9904 pub fn duplicate(
9905 &mut self,
9906 upwards: bool,
9907 whole_lines: bool,
9908 window: &mut Window,
9909 cx: &mut Context<Self>,
9910 ) {
9911 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9912
9913 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9914 let buffer = &display_map.buffer_snapshot;
9915 let selections = self.selections.all::<Point>(cx);
9916
9917 let mut edits = Vec::new();
9918 let mut selections_iter = selections.iter().peekable();
9919 while let Some(selection) = selections_iter.next() {
9920 let mut rows = selection.spanned_rows(false, &display_map);
9921 // duplicate line-wise
9922 if whole_lines || selection.start == selection.end {
9923 // Avoid duplicating the same lines twice.
9924 while let Some(next_selection) = selections_iter.peek() {
9925 let next_rows = next_selection.spanned_rows(false, &display_map);
9926 if next_rows.start < rows.end {
9927 rows.end = next_rows.end;
9928 selections_iter.next().unwrap();
9929 } else {
9930 break;
9931 }
9932 }
9933
9934 // Copy the text from the selected row region and splice it either at the start
9935 // or end of the region.
9936 let start = Point::new(rows.start.0, 0);
9937 let end = Point::new(
9938 rows.end.previous_row().0,
9939 buffer.line_len(rows.end.previous_row()),
9940 );
9941 let text = buffer
9942 .text_for_range(start..end)
9943 .chain(Some("\n"))
9944 .collect::<String>();
9945 let insert_location = if upwards {
9946 Point::new(rows.end.0, 0)
9947 } else {
9948 start
9949 };
9950 edits.push((insert_location..insert_location, text));
9951 } else {
9952 // duplicate character-wise
9953 let start = selection.start;
9954 let end = selection.end;
9955 let text = buffer.text_for_range(start..end).collect::<String>();
9956 edits.push((selection.end..selection.end, text));
9957 }
9958 }
9959
9960 self.transact(window, cx, |this, _, cx| {
9961 this.buffer.update(cx, |buffer, cx| {
9962 buffer.edit(edits, None, cx);
9963 });
9964
9965 this.request_autoscroll(Autoscroll::fit(), cx);
9966 });
9967 }
9968
9969 pub fn duplicate_line_up(
9970 &mut self,
9971 _: &DuplicateLineUp,
9972 window: &mut Window,
9973 cx: &mut Context<Self>,
9974 ) {
9975 self.duplicate(true, true, window, cx);
9976 }
9977
9978 pub fn duplicate_line_down(
9979 &mut self,
9980 _: &DuplicateLineDown,
9981 window: &mut Window,
9982 cx: &mut Context<Self>,
9983 ) {
9984 self.duplicate(false, true, window, cx);
9985 }
9986
9987 pub fn duplicate_selection(
9988 &mut self,
9989 _: &DuplicateSelection,
9990 window: &mut Window,
9991 cx: &mut Context<Self>,
9992 ) {
9993 self.duplicate(false, false, window, cx);
9994 }
9995
9996 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
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 before the line preceding the row range
10021 if start_row.0 > 0 {
10022 let range_to_move = Point::new(
10023 start_row.previous_row().0,
10024 buffer.line_len(start_row.previous_row()),
10025 )
10026 ..Point::new(
10027 end_row.previous_row().0,
10028 buffer.line_len(end_row.previous_row()),
10029 );
10030 let insertion_point = display_map
10031 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10032 .0;
10033
10034 // Don't move lines across excerpts
10035 if buffer
10036 .excerpt_containing(insertion_point..range_to_move.end)
10037 .is_some()
10038 {
10039 let text = buffer
10040 .text_for_range(range_to_move.clone())
10041 .flat_map(|s| s.chars())
10042 .skip(1)
10043 .chain(['\n'])
10044 .collect::<String>();
10045
10046 edits.push((
10047 buffer.anchor_after(range_to_move.start)
10048 ..buffer.anchor_before(range_to_move.end),
10049 String::new(),
10050 ));
10051 let insertion_anchor = buffer.anchor_after(insertion_point);
10052 edits.push((insertion_anchor..insertion_anchor, text));
10053
10054 let row_delta = range_to_move.start.row - insertion_point.row + 1;
10055
10056 // Move selections up
10057 new_selections.extend(contiguous_row_selections.drain(..).map(
10058 |mut selection| {
10059 selection.start.row -= row_delta;
10060 selection.end.row -= row_delta;
10061 selection
10062 },
10063 ));
10064
10065 // Move folds up
10066 unfold_ranges.push(range_to_move.clone());
10067 for fold in display_map.folds_in_range(
10068 buffer.anchor_before(range_to_move.start)
10069 ..buffer.anchor_after(range_to_move.end),
10070 ) {
10071 let mut start = fold.range.start.to_point(&buffer);
10072 let mut end = fold.range.end.to_point(&buffer);
10073 start.row -= row_delta;
10074 end.row -= row_delta;
10075 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10076 }
10077 }
10078 }
10079
10080 // If we didn't move line(s), preserve the existing selections
10081 new_selections.append(&mut contiguous_row_selections);
10082 }
10083
10084 self.transact(window, cx, |this, window, cx| {
10085 this.unfold_ranges(&unfold_ranges, true, true, cx);
10086 this.buffer.update(cx, |buffer, cx| {
10087 for (range, text) in edits {
10088 buffer.edit([(range, text)], None, cx);
10089 }
10090 });
10091 this.fold_creases(refold_creases, true, window, cx);
10092 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10093 s.select(new_selections);
10094 })
10095 });
10096 }
10097
10098 pub fn move_line_down(
10099 &mut self,
10100 _: &MoveLineDown,
10101 window: &mut Window,
10102 cx: &mut Context<Self>,
10103 ) {
10104 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10105
10106 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10107 let buffer = self.buffer.read(cx).snapshot(cx);
10108
10109 let mut edits = Vec::new();
10110 let mut unfold_ranges = Vec::new();
10111 let mut refold_creases = Vec::new();
10112
10113 let selections = self.selections.all::<Point>(cx);
10114 let mut selections = selections.iter().peekable();
10115 let mut contiguous_row_selections = Vec::new();
10116 let mut new_selections = Vec::new();
10117
10118 while let Some(selection) = selections.next() {
10119 // Find all the selections that span a contiguous row range
10120 let (start_row, end_row) = consume_contiguous_rows(
10121 &mut contiguous_row_selections,
10122 selection,
10123 &display_map,
10124 &mut selections,
10125 );
10126
10127 // Move the text spanned by the row range to be after the last line of the row range
10128 if end_row.0 <= buffer.max_point().row {
10129 let range_to_move =
10130 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10131 let insertion_point = display_map
10132 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10133 .0;
10134
10135 // Don't move lines across excerpt boundaries
10136 if buffer
10137 .excerpt_containing(range_to_move.start..insertion_point)
10138 .is_some()
10139 {
10140 let mut text = String::from("\n");
10141 text.extend(buffer.text_for_range(range_to_move.clone()));
10142 text.pop(); // Drop trailing newline
10143 edits.push((
10144 buffer.anchor_after(range_to_move.start)
10145 ..buffer.anchor_before(range_to_move.end),
10146 String::new(),
10147 ));
10148 let insertion_anchor = buffer.anchor_after(insertion_point);
10149 edits.push((insertion_anchor..insertion_anchor, text));
10150
10151 let row_delta = insertion_point.row - range_to_move.end.row + 1;
10152
10153 // Move selections down
10154 new_selections.extend(contiguous_row_selections.drain(..).map(
10155 |mut selection| {
10156 selection.start.row += row_delta;
10157 selection.end.row += row_delta;
10158 selection
10159 },
10160 ));
10161
10162 // Move folds down
10163 unfold_ranges.push(range_to_move.clone());
10164 for fold in display_map.folds_in_range(
10165 buffer.anchor_before(range_to_move.start)
10166 ..buffer.anchor_after(range_to_move.end),
10167 ) {
10168 let mut start = fold.range.start.to_point(&buffer);
10169 let mut end = fold.range.end.to_point(&buffer);
10170 start.row += row_delta;
10171 end.row += row_delta;
10172 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10173 }
10174 }
10175 }
10176
10177 // If we didn't move line(s), preserve the existing selections
10178 new_selections.append(&mut contiguous_row_selections);
10179 }
10180
10181 self.transact(window, cx, |this, window, cx| {
10182 this.unfold_ranges(&unfold_ranges, true, true, cx);
10183 this.buffer.update(cx, |buffer, cx| {
10184 for (range, text) in edits {
10185 buffer.edit([(range, text)], None, cx);
10186 }
10187 });
10188 this.fold_creases(refold_creases, true, window, cx);
10189 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10190 s.select(new_selections)
10191 });
10192 });
10193 }
10194
10195 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10196 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10197 let text_layout_details = &self.text_layout_details(window);
10198 self.transact(window, cx, |this, window, cx| {
10199 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10200 let mut edits: Vec<(Range<usize>, String)> = Default::default();
10201 s.move_with(|display_map, selection| {
10202 if !selection.is_empty() {
10203 return;
10204 }
10205
10206 let mut head = selection.head();
10207 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10208 if head.column() == display_map.line_len(head.row()) {
10209 transpose_offset = display_map
10210 .buffer_snapshot
10211 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10212 }
10213
10214 if transpose_offset == 0 {
10215 return;
10216 }
10217
10218 *head.column_mut() += 1;
10219 head = display_map.clip_point(head, Bias::Right);
10220 let goal = SelectionGoal::HorizontalPosition(
10221 display_map
10222 .x_for_display_point(head, text_layout_details)
10223 .into(),
10224 );
10225 selection.collapse_to(head, goal);
10226
10227 let transpose_start = display_map
10228 .buffer_snapshot
10229 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10230 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10231 let transpose_end = display_map
10232 .buffer_snapshot
10233 .clip_offset(transpose_offset + 1, Bias::Right);
10234 if let Some(ch) =
10235 display_map.buffer_snapshot.chars_at(transpose_start).next()
10236 {
10237 edits.push((transpose_start..transpose_offset, String::new()));
10238 edits.push((transpose_end..transpose_end, ch.to_string()));
10239 }
10240 }
10241 });
10242 edits
10243 });
10244 this.buffer
10245 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10246 let selections = this.selections.all::<usize>(cx);
10247 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10248 s.select(selections);
10249 });
10250 });
10251 }
10252
10253 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10254 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10255 self.rewrap_impl(RewrapOptions::default(), cx)
10256 }
10257
10258 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10259 let buffer = self.buffer.read(cx).snapshot(cx);
10260 let selections = self.selections.all::<Point>(cx);
10261 let mut selections = selections.iter().peekable();
10262
10263 let mut edits = Vec::new();
10264 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10265
10266 while let Some(selection) = selections.next() {
10267 let mut start_row = selection.start.row;
10268 let mut end_row = selection.end.row;
10269
10270 // Skip selections that overlap with a range that has already been rewrapped.
10271 let selection_range = start_row..end_row;
10272 if rewrapped_row_ranges
10273 .iter()
10274 .any(|range| range.overlaps(&selection_range))
10275 {
10276 continue;
10277 }
10278
10279 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10280
10281 // Since not all lines in the selection may be at the same indent
10282 // level, choose the indent size that is the most common between all
10283 // of the lines.
10284 //
10285 // If there is a tie, we use the deepest indent.
10286 let (indent_size, indent_end) = {
10287 let mut indent_size_occurrences = HashMap::default();
10288 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10289
10290 for row in start_row..=end_row {
10291 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10292 rows_by_indent_size.entry(indent).or_default().push(row);
10293 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10294 }
10295
10296 let indent_size = indent_size_occurrences
10297 .into_iter()
10298 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10299 .map(|(indent, _)| indent)
10300 .unwrap_or_default();
10301 let row = rows_by_indent_size[&indent_size][0];
10302 let indent_end = Point::new(row, indent_size.len);
10303
10304 (indent_size, indent_end)
10305 };
10306
10307 let mut line_prefix = indent_size.chars().collect::<String>();
10308
10309 let mut inside_comment = false;
10310 if let Some(comment_prefix) =
10311 buffer
10312 .language_scope_at(selection.head())
10313 .and_then(|language| {
10314 language
10315 .line_comment_prefixes()
10316 .iter()
10317 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10318 .cloned()
10319 })
10320 {
10321 line_prefix.push_str(&comment_prefix);
10322 inside_comment = true;
10323 }
10324
10325 let language_settings = buffer.language_settings_at(selection.head(), cx);
10326 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10327 RewrapBehavior::InComments => inside_comment,
10328 RewrapBehavior::InSelections => !selection.is_empty(),
10329 RewrapBehavior::Anywhere => true,
10330 };
10331
10332 let should_rewrap = options.override_language_settings
10333 || allow_rewrap_based_on_language
10334 || self.hard_wrap.is_some();
10335 if !should_rewrap {
10336 continue;
10337 }
10338
10339 if selection.is_empty() {
10340 'expand_upwards: while start_row > 0 {
10341 let prev_row = start_row - 1;
10342 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10343 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10344 {
10345 start_row = prev_row;
10346 } else {
10347 break 'expand_upwards;
10348 }
10349 }
10350
10351 'expand_downwards: while end_row < buffer.max_point().row {
10352 let next_row = end_row + 1;
10353 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10354 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10355 {
10356 end_row = next_row;
10357 } else {
10358 break 'expand_downwards;
10359 }
10360 }
10361 }
10362
10363 let start = Point::new(start_row, 0);
10364 let start_offset = start.to_offset(&buffer);
10365 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10366 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10367 let Some(lines_without_prefixes) = selection_text
10368 .lines()
10369 .map(|line| {
10370 line.strip_prefix(&line_prefix)
10371 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10372 .ok_or_else(|| {
10373 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10374 })
10375 })
10376 .collect::<Result<Vec<_>, _>>()
10377 .log_err()
10378 else {
10379 continue;
10380 };
10381
10382 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10383 buffer
10384 .language_settings_at(Point::new(start_row, 0), cx)
10385 .preferred_line_length as usize
10386 });
10387 let wrapped_text = wrap_with_prefix(
10388 line_prefix,
10389 lines_without_prefixes.join("\n"),
10390 wrap_column,
10391 tab_size,
10392 options.preserve_existing_whitespace,
10393 );
10394
10395 // TODO: should always use char-based diff while still supporting cursor behavior that
10396 // matches vim.
10397 let mut diff_options = DiffOptions::default();
10398 if options.override_language_settings {
10399 diff_options.max_word_diff_len = 0;
10400 diff_options.max_word_diff_line_count = 0;
10401 } else {
10402 diff_options.max_word_diff_len = usize::MAX;
10403 diff_options.max_word_diff_line_count = usize::MAX;
10404 }
10405
10406 for (old_range, new_text) in
10407 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10408 {
10409 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10410 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10411 edits.push((edit_start..edit_end, new_text));
10412 }
10413
10414 rewrapped_row_ranges.push(start_row..=end_row);
10415 }
10416
10417 self.buffer
10418 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10419 }
10420
10421 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10422 let mut text = String::new();
10423 let buffer = self.buffer.read(cx).snapshot(cx);
10424 let mut selections = self.selections.all::<Point>(cx);
10425 let mut clipboard_selections = Vec::with_capacity(selections.len());
10426 {
10427 let max_point = buffer.max_point();
10428 let mut is_first = true;
10429 for selection in &mut selections {
10430 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10431 if is_entire_line {
10432 selection.start = Point::new(selection.start.row, 0);
10433 if !selection.is_empty() && selection.end.column == 0 {
10434 selection.end = cmp::min(max_point, selection.end);
10435 } else {
10436 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10437 }
10438 selection.goal = SelectionGoal::None;
10439 }
10440 if is_first {
10441 is_first = false;
10442 } else {
10443 text += "\n";
10444 }
10445 let mut len = 0;
10446 for chunk in buffer.text_for_range(selection.start..selection.end) {
10447 text.push_str(chunk);
10448 len += chunk.len();
10449 }
10450 clipboard_selections.push(ClipboardSelection {
10451 len,
10452 is_entire_line,
10453 first_line_indent: buffer
10454 .indent_size_for_line(MultiBufferRow(selection.start.row))
10455 .len,
10456 });
10457 }
10458 }
10459
10460 self.transact(window, cx, |this, window, cx| {
10461 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10462 s.select(selections);
10463 });
10464 this.insert("", window, cx);
10465 });
10466 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10467 }
10468
10469 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10470 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10471 let item = self.cut_common(window, cx);
10472 cx.write_to_clipboard(item);
10473 }
10474
10475 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10476 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10477 self.change_selections(None, window, cx, |s| {
10478 s.move_with(|snapshot, sel| {
10479 if sel.is_empty() {
10480 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10481 }
10482 });
10483 });
10484 let item = self.cut_common(window, cx);
10485 cx.set_global(KillRing(item))
10486 }
10487
10488 pub fn kill_ring_yank(
10489 &mut self,
10490 _: &KillRingYank,
10491 window: &mut Window,
10492 cx: &mut Context<Self>,
10493 ) {
10494 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10495 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10496 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10497 (kill_ring.text().to_string(), kill_ring.metadata_json())
10498 } else {
10499 return;
10500 }
10501 } else {
10502 return;
10503 };
10504 self.do_paste(&text, metadata, false, window, cx);
10505 }
10506
10507 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10508 self.do_copy(true, cx);
10509 }
10510
10511 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10512 self.do_copy(false, cx);
10513 }
10514
10515 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10516 let selections = self.selections.all::<Point>(cx);
10517 let buffer = self.buffer.read(cx).read(cx);
10518 let mut text = String::new();
10519
10520 let mut clipboard_selections = Vec::with_capacity(selections.len());
10521 {
10522 let max_point = buffer.max_point();
10523 let mut is_first = true;
10524 for selection in &selections {
10525 let mut start = selection.start;
10526 let mut end = selection.end;
10527 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10528 if is_entire_line {
10529 start = Point::new(start.row, 0);
10530 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10531 }
10532
10533 let mut trimmed_selections = Vec::new();
10534 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10535 let row = MultiBufferRow(start.row);
10536 let first_indent = buffer.indent_size_for_line(row);
10537 if first_indent.len == 0 || start.column > first_indent.len {
10538 trimmed_selections.push(start..end);
10539 } else {
10540 trimmed_selections.push(
10541 Point::new(row.0, first_indent.len)
10542 ..Point::new(row.0, buffer.line_len(row)),
10543 );
10544 for row in start.row + 1..=end.row {
10545 let mut line_len = buffer.line_len(MultiBufferRow(row));
10546 if row == end.row {
10547 line_len = end.column;
10548 }
10549 if line_len == 0 {
10550 trimmed_selections
10551 .push(Point::new(row, 0)..Point::new(row, line_len));
10552 continue;
10553 }
10554 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10555 if row_indent_size.len >= first_indent.len {
10556 trimmed_selections.push(
10557 Point::new(row, first_indent.len)..Point::new(row, line_len),
10558 );
10559 } else {
10560 trimmed_selections.clear();
10561 trimmed_selections.push(start..end);
10562 break;
10563 }
10564 }
10565 }
10566 } else {
10567 trimmed_selections.push(start..end);
10568 }
10569
10570 for trimmed_range in trimmed_selections {
10571 if is_first {
10572 is_first = false;
10573 } else {
10574 text += "\n";
10575 }
10576 let mut len = 0;
10577 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10578 text.push_str(chunk);
10579 len += chunk.len();
10580 }
10581 clipboard_selections.push(ClipboardSelection {
10582 len,
10583 is_entire_line,
10584 first_line_indent: buffer
10585 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10586 .len,
10587 });
10588 }
10589 }
10590 }
10591
10592 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10593 text,
10594 clipboard_selections,
10595 ));
10596 }
10597
10598 pub fn do_paste(
10599 &mut self,
10600 text: &String,
10601 clipboard_selections: Option<Vec<ClipboardSelection>>,
10602 handle_entire_lines: bool,
10603 window: &mut Window,
10604 cx: &mut Context<Self>,
10605 ) {
10606 if self.read_only(cx) {
10607 return;
10608 }
10609
10610 let clipboard_text = Cow::Borrowed(text);
10611
10612 self.transact(window, cx, |this, window, cx| {
10613 if let Some(mut clipboard_selections) = clipboard_selections {
10614 let old_selections = this.selections.all::<usize>(cx);
10615 let all_selections_were_entire_line =
10616 clipboard_selections.iter().all(|s| s.is_entire_line);
10617 let first_selection_indent_column =
10618 clipboard_selections.first().map(|s| s.first_line_indent);
10619 if clipboard_selections.len() != old_selections.len() {
10620 clipboard_selections.drain(..);
10621 }
10622 let cursor_offset = this.selections.last::<usize>(cx).head();
10623 let mut auto_indent_on_paste = true;
10624
10625 this.buffer.update(cx, |buffer, cx| {
10626 let snapshot = buffer.read(cx);
10627 auto_indent_on_paste = snapshot
10628 .language_settings_at(cursor_offset, cx)
10629 .auto_indent_on_paste;
10630
10631 let mut start_offset = 0;
10632 let mut edits = Vec::new();
10633 let mut original_indent_columns = Vec::new();
10634 for (ix, selection) in old_selections.iter().enumerate() {
10635 let to_insert;
10636 let entire_line;
10637 let original_indent_column;
10638 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10639 let end_offset = start_offset + clipboard_selection.len;
10640 to_insert = &clipboard_text[start_offset..end_offset];
10641 entire_line = clipboard_selection.is_entire_line;
10642 start_offset = end_offset + 1;
10643 original_indent_column = Some(clipboard_selection.first_line_indent);
10644 } else {
10645 to_insert = clipboard_text.as_str();
10646 entire_line = all_selections_were_entire_line;
10647 original_indent_column = first_selection_indent_column
10648 }
10649
10650 // If the corresponding selection was empty when this slice of the
10651 // clipboard text was written, then the entire line containing the
10652 // selection was copied. If this selection is also currently empty,
10653 // then paste the line before the current line of the buffer.
10654 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10655 let column = selection.start.to_point(&snapshot).column as usize;
10656 let line_start = selection.start - column;
10657 line_start..line_start
10658 } else {
10659 selection.range()
10660 };
10661
10662 edits.push((range, to_insert));
10663 original_indent_columns.push(original_indent_column);
10664 }
10665 drop(snapshot);
10666
10667 buffer.edit(
10668 edits,
10669 if auto_indent_on_paste {
10670 Some(AutoindentMode::Block {
10671 original_indent_columns,
10672 })
10673 } else {
10674 None
10675 },
10676 cx,
10677 );
10678 });
10679
10680 let selections = this.selections.all::<usize>(cx);
10681 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10682 s.select(selections)
10683 });
10684 } else {
10685 this.insert(&clipboard_text, window, cx);
10686 }
10687 });
10688 }
10689
10690 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10691 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10692 if let Some(item) = cx.read_from_clipboard() {
10693 let entries = item.entries();
10694
10695 match entries.first() {
10696 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10697 // of all the pasted entries.
10698 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10699 .do_paste(
10700 clipboard_string.text(),
10701 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10702 true,
10703 window,
10704 cx,
10705 ),
10706 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10707 }
10708 }
10709 }
10710
10711 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10712 if self.read_only(cx) {
10713 return;
10714 }
10715
10716 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10717
10718 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10719 if let Some((selections, _)) =
10720 self.selection_history.transaction(transaction_id).cloned()
10721 {
10722 self.change_selections(None, window, cx, |s| {
10723 s.select_anchors(selections.to_vec());
10724 });
10725 } else {
10726 log::error!(
10727 "No entry in selection_history found for undo. \
10728 This may correspond to a bug where undo does not update the selection. \
10729 If this is occurring, please add details to \
10730 https://github.com/zed-industries/zed/issues/22692"
10731 );
10732 }
10733 self.request_autoscroll(Autoscroll::fit(), cx);
10734 self.unmark_text(window, cx);
10735 self.refresh_inline_completion(true, false, window, cx);
10736 cx.emit(EditorEvent::Edited { transaction_id });
10737 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10738 }
10739 }
10740
10741 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10742 if self.read_only(cx) {
10743 return;
10744 }
10745
10746 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10747
10748 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10749 if let Some((_, Some(selections))) =
10750 self.selection_history.transaction(transaction_id).cloned()
10751 {
10752 self.change_selections(None, window, cx, |s| {
10753 s.select_anchors(selections.to_vec());
10754 });
10755 } else {
10756 log::error!(
10757 "No entry in selection_history found for redo. \
10758 This may correspond to a bug where undo does not update the selection. \
10759 If this is occurring, please add details to \
10760 https://github.com/zed-industries/zed/issues/22692"
10761 );
10762 }
10763 self.request_autoscroll(Autoscroll::fit(), cx);
10764 self.unmark_text(window, cx);
10765 self.refresh_inline_completion(true, false, window, cx);
10766 cx.emit(EditorEvent::Edited { transaction_id });
10767 }
10768 }
10769
10770 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10771 self.buffer
10772 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10773 }
10774
10775 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10776 self.buffer
10777 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10778 }
10779
10780 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10781 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10782 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10783 s.move_with(|map, selection| {
10784 let cursor = if selection.is_empty() {
10785 movement::left(map, selection.start)
10786 } else {
10787 selection.start
10788 };
10789 selection.collapse_to(cursor, SelectionGoal::None);
10790 });
10791 })
10792 }
10793
10794 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10795 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10796 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10797 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10798 })
10799 }
10800
10801 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10802 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10803 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10804 s.move_with(|map, selection| {
10805 let cursor = if selection.is_empty() {
10806 movement::right(map, selection.end)
10807 } else {
10808 selection.end
10809 };
10810 selection.collapse_to(cursor, SelectionGoal::None)
10811 });
10812 })
10813 }
10814
10815 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10816 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10817 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10818 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10819 })
10820 }
10821
10822 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10823 if self.take_rename(true, window, cx).is_some() {
10824 return;
10825 }
10826
10827 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10828 cx.propagate();
10829 return;
10830 }
10831
10832 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10833
10834 let text_layout_details = &self.text_layout_details(window);
10835 let selection_count = self.selections.count();
10836 let first_selection = self.selections.first_anchor();
10837
10838 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10839 s.move_with(|map, selection| {
10840 if !selection.is_empty() {
10841 selection.goal = SelectionGoal::None;
10842 }
10843 let (cursor, goal) = movement::up(
10844 map,
10845 selection.start,
10846 selection.goal,
10847 false,
10848 text_layout_details,
10849 );
10850 selection.collapse_to(cursor, goal);
10851 });
10852 });
10853
10854 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10855 {
10856 cx.propagate();
10857 }
10858 }
10859
10860 pub fn move_up_by_lines(
10861 &mut self,
10862 action: &MoveUpByLines,
10863 window: &mut Window,
10864 cx: &mut Context<Self>,
10865 ) {
10866 if self.take_rename(true, window, cx).is_some() {
10867 return;
10868 }
10869
10870 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10871 cx.propagate();
10872 return;
10873 }
10874
10875 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10876
10877 let text_layout_details = &self.text_layout_details(window);
10878
10879 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10880 s.move_with(|map, selection| {
10881 if !selection.is_empty() {
10882 selection.goal = SelectionGoal::None;
10883 }
10884 let (cursor, goal) = movement::up_by_rows(
10885 map,
10886 selection.start,
10887 action.lines,
10888 selection.goal,
10889 false,
10890 text_layout_details,
10891 );
10892 selection.collapse_to(cursor, goal);
10893 });
10894 })
10895 }
10896
10897 pub fn move_down_by_lines(
10898 &mut self,
10899 action: &MoveDownByLines,
10900 window: &mut Window,
10901 cx: &mut Context<Self>,
10902 ) {
10903 if self.take_rename(true, window, cx).is_some() {
10904 return;
10905 }
10906
10907 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10908 cx.propagate();
10909 return;
10910 }
10911
10912 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10913
10914 let text_layout_details = &self.text_layout_details(window);
10915
10916 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10917 s.move_with(|map, selection| {
10918 if !selection.is_empty() {
10919 selection.goal = SelectionGoal::None;
10920 }
10921 let (cursor, goal) = movement::down_by_rows(
10922 map,
10923 selection.start,
10924 action.lines,
10925 selection.goal,
10926 false,
10927 text_layout_details,
10928 );
10929 selection.collapse_to(cursor, goal);
10930 });
10931 })
10932 }
10933
10934 pub fn select_down_by_lines(
10935 &mut self,
10936 action: &SelectDownByLines,
10937 window: &mut Window,
10938 cx: &mut Context<Self>,
10939 ) {
10940 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10941 let text_layout_details = &self.text_layout_details(window);
10942 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10943 s.move_heads_with(|map, head, goal| {
10944 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10945 })
10946 })
10947 }
10948
10949 pub fn select_up_by_lines(
10950 &mut self,
10951 action: &SelectUpByLines,
10952 window: &mut Window,
10953 cx: &mut Context<Self>,
10954 ) {
10955 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10956 let text_layout_details = &self.text_layout_details(window);
10957 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10958 s.move_heads_with(|map, head, goal| {
10959 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10960 })
10961 })
10962 }
10963
10964 pub fn select_page_up(
10965 &mut self,
10966 _: &SelectPageUp,
10967 window: &mut Window,
10968 cx: &mut Context<Self>,
10969 ) {
10970 let Some(row_count) = self.visible_row_count() else {
10971 return;
10972 };
10973
10974 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10975
10976 let text_layout_details = &self.text_layout_details(window);
10977
10978 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10979 s.move_heads_with(|map, head, goal| {
10980 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10981 })
10982 })
10983 }
10984
10985 pub fn move_page_up(
10986 &mut self,
10987 action: &MovePageUp,
10988 window: &mut Window,
10989 cx: &mut Context<Self>,
10990 ) {
10991 if self.take_rename(true, window, cx).is_some() {
10992 return;
10993 }
10994
10995 if self
10996 .context_menu
10997 .borrow_mut()
10998 .as_mut()
10999 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11000 .unwrap_or(false)
11001 {
11002 return;
11003 }
11004
11005 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11006 cx.propagate();
11007 return;
11008 }
11009
11010 let Some(row_count) = self.visible_row_count() else {
11011 return;
11012 };
11013
11014 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11015
11016 let autoscroll = if action.center_cursor {
11017 Autoscroll::center()
11018 } else {
11019 Autoscroll::fit()
11020 };
11021
11022 let text_layout_details = &self.text_layout_details(window);
11023
11024 self.change_selections(Some(autoscroll), window, cx, |s| {
11025 s.move_with(|map, selection| {
11026 if !selection.is_empty() {
11027 selection.goal = SelectionGoal::None;
11028 }
11029 let (cursor, goal) = movement::up_by_rows(
11030 map,
11031 selection.end,
11032 row_count,
11033 selection.goal,
11034 false,
11035 text_layout_details,
11036 );
11037 selection.collapse_to(cursor, goal);
11038 });
11039 });
11040 }
11041
11042 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11043 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11044 let text_layout_details = &self.text_layout_details(window);
11045 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11046 s.move_heads_with(|map, head, goal| {
11047 movement::up(map, head, goal, false, text_layout_details)
11048 })
11049 })
11050 }
11051
11052 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11053 self.take_rename(true, window, cx);
11054
11055 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11056 cx.propagate();
11057 return;
11058 }
11059
11060 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11061
11062 let text_layout_details = &self.text_layout_details(window);
11063 let selection_count = self.selections.count();
11064 let first_selection = self.selections.first_anchor();
11065
11066 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11067 s.move_with(|map, selection| {
11068 if !selection.is_empty() {
11069 selection.goal = SelectionGoal::None;
11070 }
11071 let (cursor, goal) = movement::down(
11072 map,
11073 selection.end,
11074 selection.goal,
11075 false,
11076 text_layout_details,
11077 );
11078 selection.collapse_to(cursor, goal);
11079 });
11080 });
11081
11082 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11083 {
11084 cx.propagate();
11085 }
11086 }
11087
11088 pub fn select_page_down(
11089 &mut self,
11090 _: &SelectPageDown,
11091 window: &mut Window,
11092 cx: &mut Context<Self>,
11093 ) {
11094 let Some(row_count) = self.visible_row_count() else {
11095 return;
11096 };
11097
11098 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11099
11100 let text_layout_details = &self.text_layout_details(window);
11101
11102 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11103 s.move_heads_with(|map, head, goal| {
11104 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11105 })
11106 })
11107 }
11108
11109 pub fn move_page_down(
11110 &mut self,
11111 action: &MovePageDown,
11112 window: &mut Window,
11113 cx: &mut Context<Self>,
11114 ) {
11115 if self.take_rename(true, window, cx).is_some() {
11116 return;
11117 }
11118
11119 if self
11120 .context_menu
11121 .borrow_mut()
11122 .as_mut()
11123 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11124 .unwrap_or(false)
11125 {
11126 return;
11127 }
11128
11129 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11130 cx.propagate();
11131 return;
11132 }
11133
11134 let Some(row_count) = self.visible_row_count() else {
11135 return;
11136 };
11137
11138 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11139
11140 let autoscroll = if action.center_cursor {
11141 Autoscroll::center()
11142 } else {
11143 Autoscroll::fit()
11144 };
11145
11146 let text_layout_details = &self.text_layout_details(window);
11147 self.change_selections(Some(autoscroll), window, cx, |s| {
11148 s.move_with(|map, selection| {
11149 if !selection.is_empty() {
11150 selection.goal = SelectionGoal::None;
11151 }
11152 let (cursor, goal) = movement::down_by_rows(
11153 map,
11154 selection.end,
11155 row_count,
11156 selection.goal,
11157 false,
11158 text_layout_details,
11159 );
11160 selection.collapse_to(cursor, goal);
11161 });
11162 });
11163 }
11164
11165 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11166 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11167 let text_layout_details = &self.text_layout_details(window);
11168 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11169 s.move_heads_with(|map, head, goal| {
11170 movement::down(map, head, goal, false, text_layout_details)
11171 })
11172 });
11173 }
11174
11175 pub fn context_menu_first(
11176 &mut self,
11177 _: &ContextMenuFirst,
11178 _window: &mut Window,
11179 cx: &mut Context<Self>,
11180 ) {
11181 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11182 context_menu.select_first(self.completion_provider.as_deref(), cx);
11183 }
11184 }
11185
11186 pub fn context_menu_prev(
11187 &mut self,
11188 _: &ContextMenuPrevious,
11189 _window: &mut Window,
11190 cx: &mut Context<Self>,
11191 ) {
11192 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11193 context_menu.select_prev(self.completion_provider.as_deref(), cx);
11194 }
11195 }
11196
11197 pub fn context_menu_next(
11198 &mut self,
11199 _: &ContextMenuNext,
11200 _window: &mut Window,
11201 cx: &mut Context<Self>,
11202 ) {
11203 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11204 context_menu.select_next(self.completion_provider.as_deref(), cx);
11205 }
11206 }
11207
11208 pub fn context_menu_last(
11209 &mut self,
11210 _: &ContextMenuLast,
11211 _window: &mut Window,
11212 cx: &mut Context<Self>,
11213 ) {
11214 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11215 context_menu.select_last(self.completion_provider.as_deref(), cx);
11216 }
11217 }
11218
11219 pub fn move_to_previous_word_start(
11220 &mut self,
11221 _: &MoveToPreviousWordStart,
11222 window: &mut Window,
11223 cx: &mut Context<Self>,
11224 ) {
11225 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11226 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11227 s.move_cursors_with(|map, head, _| {
11228 (
11229 movement::previous_word_start(map, head),
11230 SelectionGoal::None,
11231 )
11232 });
11233 })
11234 }
11235
11236 pub fn move_to_previous_subword_start(
11237 &mut self,
11238 _: &MoveToPreviousSubwordStart,
11239 window: &mut Window,
11240 cx: &mut Context<Self>,
11241 ) {
11242 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11243 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11244 s.move_cursors_with(|map, head, _| {
11245 (
11246 movement::previous_subword_start(map, head),
11247 SelectionGoal::None,
11248 )
11249 });
11250 })
11251 }
11252
11253 pub fn select_to_previous_word_start(
11254 &mut self,
11255 _: &SelectToPreviousWordStart,
11256 window: &mut Window,
11257 cx: &mut Context<Self>,
11258 ) {
11259 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11260 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11261 s.move_heads_with(|map, head, _| {
11262 (
11263 movement::previous_word_start(map, head),
11264 SelectionGoal::None,
11265 )
11266 });
11267 })
11268 }
11269
11270 pub fn select_to_previous_subword_start(
11271 &mut self,
11272 _: &SelectToPreviousSubwordStart,
11273 window: &mut Window,
11274 cx: &mut Context<Self>,
11275 ) {
11276 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11277 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11278 s.move_heads_with(|map, head, _| {
11279 (
11280 movement::previous_subword_start(map, head),
11281 SelectionGoal::None,
11282 )
11283 });
11284 })
11285 }
11286
11287 pub fn delete_to_previous_word_start(
11288 &mut self,
11289 action: &DeleteToPreviousWordStart,
11290 window: &mut Window,
11291 cx: &mut Context<Self>,
11292 ) {
11293 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11294 self.transact(window, cx, |this, window, cx| {
11295 this.select_autoclose_pair(window, cx);
11296 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11297 s.move_with(|map, selection| {
11298 if selection.is_empty() {
11299 let cursor = if action.ignore_newlines {
11300 movement::previous_word_start(map, selection.head())
11301 } else {
11302 movement::previous_word_start_or_newline(map, selection.head())
11303 };
11304 selection.set_head(cursor, SelectionGoal::None);
11305 }
11306 });
11307 });
11308 this.insert("", window, cx);
11309 });
11310 }
11311
11312 pub fn delete_to_previous_subword_start(
11313 &mut self,
11314 _: &DeleteToPreviousSubwordStart,
11315 window: &mut Window,
11316 cx: &mut Context<Self>,
11317 ) {
11318 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11319 self.transact(window, cx, |this, window, cx| {
11320 this.select_autoclose_pair(window, cx);
11321 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11322 s.move_with(|map, selection| {
11323 if selection.is_empty() {
11324 let cursor = movement::previous_subword_start(map, selection.head());
11325 selection.set_head(cursor, SelectionGoal::None);
11326 }
11327 });
11328 });
11329 this.insert("", window, cx);
11330 });
11331 }
11332
11333 pub fn move_to_next_word_end(
11334 &mut self,
11335 _: &MoveToNextWordEnd,
11336 window: &mut Window,
11337 cx: &mut Context<Self>,
11338 ) {
11339 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11340 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11341 s.move_cursors_with(|map, head, _| {
11342 (movement::next_word_end(map, head), SelectionGoal::None)
11343 });
11344 })
11345 }
11346
11347 pub fn move_to_next_subword_end(
11348 &mut self,
11349 _: &MoveToNextSubwordEnd,
11350 window: &mut Window,
11351 cx: &mut Context<Self>,
11352 ) {
11353 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11354 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11355 s.move_cursors_with(|map, head, _| {
11356 (movement::next_subword_end(map, head), SelectionGoal::None)
11357 });
11358 })
11359 }
11360
11361 pub fn select_to_next_word_end(
11362 &mut self,
11363 _: &SelectToNextWordEnd,
11364 window: &mut Window,
11365 cx: &mut Context<Self>,
11366 ) {
11367 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11368 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11369 s.move_heads_with(|map, head, _| {
11370 (movement::next_word_end(map, head), SelectionGoal::None)
11371 });
11372 })
11373 }
11374
11375 pub fn select_to_next_subword_end(
11376 &mut self,
11377 _: &SelectToNextSubwordEnd,
11378 window: &mut Window,
11379 cx: &mut Context<Self>,
11380 ) {
11381 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11382 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11383 s.move_heads_with(|map, head, _| {
11384 (movement::next_subword_end(map, head), SelectionGoal::None)
11385 });
11386 })
11387 }
11388
11389 pub fn delete_to_next_word_end(
11390 &mut self,
11391 action: &DeleteToNextWordEnd,
11392 window: &mut Window,
11393 cx: &mut Context<Self>,
11394 ) {
11395 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11396 self.transact(window, cx, |this, window, cx| {
11397 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11398 s.move_with(|map, selection| {
11399 if selection.is_empty() {
11400 let cursor = if action.ignore_newlines {
11401 movement::next_word_end(map, selection.head())
11402 } else {
11403 movement::next_word_end_or_newline(map, selection.head())
11404 };
11405 selection.set_head(cursor, SelectionGoal::None);
11406 }
11407 });
11408 });
11409 this.insert("", window, cx);
11410 });
11411 }
11412
11413 pub fn delete_to_next_subword_end(
11414 &mut self,
11415 _: &DeleteToNextSubwordEnd,
11416 window: &mut Window,
11417 cx: &mut Context<Self>,
11418 ) {
11419 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11420 self.transact(window, cx, |this, window, cx| {
11421 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11422 s.move_with(|map, selection| {
11423 if selection.is_empty() {
11424 let cursor = movement::next_subword_end(map, selection.head());
11425 selection.set_head(cursor, SelectionGoal::None);
11426 }
11427 });
11428 });
11429 this.insert("", window, cx);
11430 });
11431 }
11432
11433 pub fn move_to_beginning_of_line(
11434 &mut self,
11435 action: &MoveToBeginningOfLine,
11436 window: &mut Window,
11437 cx: &mut Context<Self>,
11438 ) {
11439 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11440 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11441 s.move_cursors_with(|map, head, _| {
11442 (
11443 movement::indented_line_beginning(
11444 map,
11445 head,
11446 action.stop_at_soft_wraps,
11447 action.stop_at_indent,
11448 ),
11449 SelectionGoal::None,
11450 )
11451 });
11452 })
11453 }
11454
11455 pub fn select_to_beginning_of_line(
11456 &mut self,
11457 action: &SelectToBeginningOfLine,
11458 window: &mut Window,
11459 cx: &mut Context<Self>,
11460 ) {
11461 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11462 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11463 s.move_heads_with(|map, head, _| {
11464 (
11465 movement::indented_line_beginning(
11466 map,
11467 head,
11468 action.stop_at_soft_wraps,
11469 action.stop_at_indent,
11470 ),
11471 SelectionGoal::None,
11472 )
11473 });
11474 });
11475 }
11476
11477 pub fn delete_to_beginning_of_line(
11478 &mut self,
11479 action: &DeleteToBeginningOfLine,
11480 window: &mut Window,
11481 cx: &mut Context<Self>,
11482 ) {
11483 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11484 self.transact(window, cx, |this, window, cx| {
11485 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11486 s.move_with(|_, selection| {
11487 selection.reversed = true;
11488 });
11489 });
11490
11491 this.select_to_beginning_of_line(
11492 &SelectToBeginningOfLine {
11493 stop_at_soft_wraps: false,
11494 stop_at_indent: action.stop_at_indent,
11495 },
11496 window,
11497 cx,
11498 );
11499 this.backspace(&Backspace, window, cx);
11500 });
11501 }
11502
11503 pub fn move_to_end_of_line(
11504 &mut self,
11505 action: &MoveToEndOfLine,
11506 window: &mut Window,
11507 cx: &mut Context<Self>,
11508 ) {
11509 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11510 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11511 s.move_cursors_with(|map, head, _| {
11512 (
11513 movement::line_end(map, head, action.stop_at_soft_wraps),
11514 SelectionGoal::None,
11515 )
11516 });
11517 })
11518 }
11519
11520 pub fn select_to_end_of_line(
11521 &mut self,
11522 action: &SelectToEndOfLine,
11523 window: &mut Window,
11524 cx: &mut Context<Self>,
11525 ) {
11526 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11527 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11528 s.move_heads_with(|map, head, _| {
11529 (
11530 movement::line_end(map, head, action.stop_at_soft_wraps),
11531 SelectionGoal::None,
11532 )
11533 });
11534 })
11535 }
11536
11537 pub fn delete_to_end_of_line(
11538 &mut self,
11539 _: &DeleteToEndOfLine,
11540 window: &mut Window,
11541 cx: &mut Context<Self>,
11542 ) {
11543 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11544 self.transact(window, cx, |this, window, cx| {
11545 this.select_to_end_of_line(
11546 &SelectToEndOfLine {
11547 stop_at_soft_wraps: false,
11548 },
11549 window,
11550 cx,
11551 );
11552 this.delete(&Delete, window, cx);
11553 });
11554 }
11555
11556 pub fn cut_to_end_of_line(
11557 &mut self,
11558 _: &CutToEndOfLine,
11559 window: &mut Window,
11560 cx: &mut Context<Self>,
11561 ) {
11562 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11563 self.transact(window, cx, |this, window, cx| {
11564 this.select_to_end_of_line(
11565 &SelectToEndOfLine {
11566 stop_at_soft_wraps: false,
11567 },
11568 window,
11569 cx,
11570 );
11571 this.cut(&Cut, window, cx);
11572 });
11573 }
11574
11575 pub fn move_to_start_of_paragraph(
11576 &mut self,
11577 _: &MoveToStartOfParagraph,
11578 window: &mut Window,
11579 cx: &mut Context<Self>,
11580 ) {
11581 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11582 cx.propagate();
11583 return;
11584 }
11585 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11586 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11587 s.move_with(|map, selection| {
11588 selection.collapse_to(
11589 movement::start_of_paragraph(map, selection.head(), 1),
11590 SelectionGoal::None,
11591 )
11592 });
11593 })
11594 }
11595
11596 pub fn move_to_end_of_paragraph(
11597 &mut self,
11598 _: &MoveToEndOfParagraph,
11599 window: &mut Window,
11600 cx: &mut Context<Self>,
11601 ) {
11602 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11603 cx.propagate();
11604 return;
11605 }
11606 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11607 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11608 s.move_with(|map, selection| {
11609 selection.collapse_to(
11610 movement::end_of_paragraph(map, selection.head(), 1),
11611 SelectionGoal::None,
11612 )
11613 });
11614 })
11615 }
11616
11617 pub fn select_to_start_of_paragraph(
11618 &mut self,
11619 _: &SelectToStartOfParagraph,
11620 window: &mut Window,
11621 cx: &mut Context<Self>,
11622 ) {
11623 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11624 cx.propagate();
11625 return;
11626 }
11627 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11628 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11629 s.move_heads_with(|map, head, _| {
11630 (
11631 movement::start_of_paragraph(map, head, 1),
11632 SelectionGoal::None,
11633 )
11634 });
11635 })
11636 }
11637
11638 pub fn select_to_end_of_paragraph(
11639 &mut self,
11640 _: &SelectToEndOfParagraph,
11641 window: &mut Window,
11642 cx: &mut Context<Self>,
11643 ) {
11644 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11645 cx.propagate();
11646 return;
11647 }
11648 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11649 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11650 s.move_heads_with(|map, head, _| {
11651 (
11652 movement::end_of_paragraph(map, head, 1),
11653 SelectionGoal::None,
11654 )
11655 });
11656 })
11657 }
11658
11659 pub fn move_to_start_of_excerpt(
11660 &mut self,
11661 _: &MoveToStartOfExcerpt,
11662 window: &mut Window,
11663 cx: &mut Context<Self>,
11664 ) {
11665 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11666 cx.propagate();
11667 return;
11668 }
11669 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11670 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11671 s.move_with(|map, selection| {
11672 selection.collapse_to(
11673 movement::start_of_excerpt(
11674 map,
11675 selection.head(),
11676 workspace::searchable::Direction::Prev,
11677 ),
11678 SelectionGoal::None,
11679 )
11680 });
11681 })
11682 }
11683
11684 pub fn move_to_start_of_next_excerpt(
11685 &mut self,
11686 _: &MoveToStartOfNextExcerpt,
11687 window: &mut Window,
11688 cx: &mut Context<Self>,
11689 ) {
11690 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11691 cx.propagate();
11692 return;
11693 }
11694
11695 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11696 s.move_with(|map, selection| {
11697 selection.collapse_to(
11698 movement::start_of_excerpt(
11699 map,
11700 selection.head(),
11701 workspace::searchable::Direction::Next,
11702 ),
11703 SelectionGoal::None,
11704 )
11705 });
11706 })
11707 }
11708
11709 pub fn move_to_end_of_excerpt(
11710 &mut self,
11711 _: &MoveToEndOfExcerpt,
11712 window: &mut Window,
11713 cx: &mut Context<Self>,
11714 ) {
11715 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11716 cx.propagate();
11717 return;
11718 }
11719 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11720 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11721 s.move_with(|map, selection| {
11722 selection.collapse_to(
11723 movement::end_of_excerpt(
11724 map,
11725 selection.head(),
11726 workspace::searchable::Direction::Next,
11727 ),
11728 SelectionGoal::None,
11729 )
11730 });
11731 })
11732 }
11733
11734 pub fn move_to_end_of_previous_excerpt(
11735 &mut self,
11736 _: &MoveToEndOfPreviousExcerpt,
11737 window: &mut Window,
11738 cx: &mut Context<Self>,
11739 ) {
11740 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11741 cx.propagate();
11742 return;
11743 }
11744 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11745 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11746 s.move_with(|map, selection| {
11747 selection.collapse_to(
11748 movement::end_of_excerpt(
11749 map,
11750 selection.head(),
11751 workspace::searchable::Direction::Prev,
11752 ),
11753 SelectionGoal::None,
11754 )
11755 });
11756 })
11757 }
11758
11759 pub fn select_to_start_of_excerpt(
11760 &mut self,
11761 _: &SelectToStartOfExcerpt,
11762 window: &mut Window,
11763 cx: &mut Context<Self>,
11764 ) {
11765 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11766 cx.propagate();
11767 return;
11768 }
11769 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11770 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11771 s.move_heads_with(|map, head, _| {
11772 (
11773 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11774 SelectionGoal::None,
11775 )
11776 });
11777 })
11778 }
11779
11780 pub fn select_to_start_of_next_excerpt(
11781 &mut self,
11782 _: &SelectToStartOfNextExcerpt,
11783 window: &mut Window,
11784 cx: &mut Context<Self>,
11785 ) {
11786 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11787 cx.propagate();
11788 return;
11789 }
11790 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11791 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11792 s.move_heads_with(|map, head, _| {
11793 (
11794 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11795 SelectionGoal::None,
11796 )
11797 });
11798 })
11799 }
11800
11801 pub fn select_to_end_of_excerpt(
11802 &mut self,
11803 _: &SelectToEndOfExcerpt,
11804 window: &mut Window,
11805 cx: &mut Context<Self>,
11806 ) {
11807 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11808 cx.propagate();
11809 return;
11810 }
11811 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11812 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11813 s.move_heads_with(|map, head, _| {
11814 (
11815 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11816 SelectionGoal::None,
11817 )
11818 });
11819 })
11820 }
11821
11822 pub fn select_to_end_of_previous_excerpt(
11823 &mut self,
11824 _: &SelectToEndOfPreviousExcerpt,
11825 window: &mut Window,
11826 cx: &mut Context<Self>,
11827 ) {
11828 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11829 cx.propagate();
11830 return;
11831 }
11832 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11833 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11834 s.move_heads_with(|map, head, _| {
11835 (
11836 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11837 SelectionGoal::None,
11838 )
11839 });
11840 })
11841 }
11842
11843 pub fn move_to_beginning(
11844 &mut self,
11845 _: &MoveToBeginning,
11846 window: &mut Window,
11847 cx: &mut Context<Self>,
11848 ) {
11849 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11850 cx.propagate();
11851 return;
11852 }
11853 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11854 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11855 s.select_ranges(vec![0..0]);
11856 });
11857 }
11858
11859 pub fn select_to_beginning(
11860 &mut self,
11861 _: &SelectToBeginning,
11862 window: &mut Window,
11863 cx: &mut Context<Self>,
11864 ) {
11865 let mut selection = self.selections.last::<Point>(cx);
11866 selection.set_head(Point::zero(), SelectionGoal::None);
11867 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11868 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11869 s.select(vec![selection]);
11870 });
11871 }
11872
11873 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11874 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11875 cx.propagate();
11876 return;
11877 }
11878 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11879 let cursor = self.buffer.read(cx).read(cx).len();
11880 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11881 s.select_ranges(vec![cursor..cursor])
11882 });
11883 }
11884
11885 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11886 self.nav_history = nav_history;
11887 }
11888
11889 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11890 self.nav_history.as_ref()
11891 }
11892
11893 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11894 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11895 }
11896
11897 fn push_to_nav_history(
11898 &mut self,
11899 cursor_anchor: Anchor,
11900 new_position: Option<Point>,
11901 is_deactivate: bool,
11902 cx: &mut Context<Self>,
11903 ) {
11904 if let Some(nav_history) = self.nav_history.as_mut() {
11905 let buffer = self.buffer.read(cx).read(cx);
11906 let cursor_position = cursor_anchor.to_point(&buffer);
11907 let scroll_state = self.scroll_manager.anchor();
11908 let scroll_top_row = scroll_state.top_row(&buffer);
11909 drop(buffer);
11910
11911 if let Some(new_position) = new_position {
11912 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11913 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11914 return;
11915 }
11916 }
11917
11918 nav_history.push(
11919 Some(NavigationData {
11920 cursor_anchor,
11921 cursor_position,
11922 scroll_anchor: scroll_state,
11923 scroll_top_row,
11924 }),
11925 cx,
11926 );
11927 cx.emit(EditorEvent::PushedToNavHistory {
11928 anchor: cursor_anchor,
11929 is_deactivate,
11930 })
11931 }
11932 }
11933
11934 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11935 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11936 let buffer = self.buffer.read(cx).snapshot(cx);
11937 let mut selection = self.selections.first::<usize>(cx);
11938 selection.set_head(buffer.len(), SelectionGoal::None);
11939 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11940 s.select(vec![selection]);
11941 });
11942 }
11943
11944 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11945 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11946 let end = self.buffer.read(cx).read(cx).len();
11947 self.change_selections(None, window, cx, |s| {
11948 s.select_ranges(vec![0..end]);
11949 });
11950 }
11951
11952 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11953 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11954 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11955 let mut selections = self.selections.all::<Point>(cx);
11956 let max_point = display_map.buffer_snapshot.max_point();
11957 for selection in &mut selections {
11958 let rows = selection.spanned_rows(true, &display_map);
11959 selection.start = Point::new(rows.start.0, 0);
11960 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11961 selection.reversed = false;
11962 }
11963 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11964 s.select(selections);
11965 });
11966 }
11967
11968 pub fn split_selection_into_lines(
11969 &mut self,
11970 _: &SplitSelectionIntoLines,
11971 window: &mut Window,
11972 cx: &mut Context<Self>,
11973 ) {
11974 let selections = self
11975 .selections
11976 .all::<Point>(cx)
11977 .into_iter()
11978 .map(|selection| selection.start..selection.end)
11979 .collect::<Vec<_>>();
11980 self.unfold_ranges(&selections, true, true, cx);
11981
11982 let mut new_selection_ranges = Vec::new();
11983 {
11984 let buffer = self.buffer.read(cx).read(cx);
11985 for selection in selections {
11986 for row in selection.start.row..selection.end.row {
11987 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11988 new_selection_ranges.push(cursor..cursor);
11989 }
11990
11991 let is_multiline_selection = selection.start.row != selection.end.row;
11992 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11993 // so this action feels more ergonomic when paired with other selection operations
11994 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11995 if !should_skip_last {
11996 new_selection_ranges.push(selection.end..selection.end);
11997 }
11998 }
11999 }
12000 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12001 s.select_ranges(new_selection_ranges);
12002 });
12003 }
12004
12005 pub fn add_selection_above(
12006 &mut self,
12007 _: &AddSelectionAbove,
12008 window: &mut Window,
12009 cx: &mut Context<Self>,
12010 ) {
12011 self.add_selection(true, window, cx);
12012 }
12013
12014 pub fn add_selection_below(
12015 &mut self,
12016 _: &AddSelectionBelow,
12017 window: &mut Window,
12018 cx: &mut Context<Self>,
12019 ) {
12020 self.add_selection(false, window, cx);
12021 }
12022
12023 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12024 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12025
12026 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12027 let mut selections = self.selections.all::<Point>(cx);
12028 let text_layout_details = self.text_layout_details(window);
12029 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12030 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12031 let range = oldest_selection.display_range(&display_map).sorted();
12032
12033 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12034 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12035 let positions = start_x.min(end_x)..start_x.max(end_x);
12036
12037 selections.clear();
12038 let mut stack = Vec::new();
12039 for row in range.start.row().0..=range.end.row().0 {
12040 if let Some(selection) = self.selections.build_columnar_selection(
12041 &display_map,
12042 DisplayRow(row),
12043 &positions,
12044 oldest_selection.reversed,
12045 &text_layout_details,
12046 ) {
12047 stack.push(selection.id);
12048 selections.push(selection);
12049 }
12050 }
12051
12052 if above {
12053 stack.reverse();
12054 }
12055
12056 AddSelectionsState { above, stack }
12057 });
12058
12059 let last_added_selection = *state.stack.last().unwrap();
12060 let mut new_selections = Vec::new();
12061 if above == state.above {
12062 let end_row = if above {
12063 DisplayRow(0)
12064 } else {
12065 display_map.max_point().row()
12066 };
12067
12068 'outer: for selection in selections {
12069 if selection.id == last_added_selection {
12070 let range = selection.display_range(&display_map).sorted();
12071 debug_assert_eq!(range.start.row(), range.end.row());
12072 let mut row = range.start.row();
12073 let positions =
12074 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12075 px(start)..px(end)
12076 } else {
12077 let start_x =
12078 display_map.x_for_display_point(range.start, &text_layout_details);
12079 let end_x =
12080 display_map.x_for_display_point(range.end, &text_layout_details);
12081 start_x.min(end_x)..start_x.max(end_x)
12082 };
12083
12084 while row != end_row {
12085 if above {
12086 row.0 -= 1;
12087 } else {
12088 row.0 += 1;
12089 }
12090
12091 if let Some(new_selection) = self.selections.build_columnar_selection(
12092 &display_map,
12093 row,
12094 &positions,
12095 selection.reversed,
12096 &text_layout_details,
12097 ) {
12098 state.stack.push(new_selection.id);
12099 if above {
12100 new_selections.push(new_selection);
12101 new_selections.push(selection);
12102 } else {
12103 new_selections.push(selection);
12104 new_selections.push(new_selection);
12105 }
12106
12107 continue 'outer;
12108 }
12109 }
12110 }
12111
12112 new_selections.push(selection);
12113 }
12114 } else {
12115 new_selections = selections;
12116 new_selections.retain(|s| s.id != last_added_selection);
12117 state.stack.pop();
12118 }
12119
12120 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12121 s.select(new_selections);
12122 });
12123 if state.stack.len() > 1 {
12124 self.add_selections_state = Some(state);
12125 }
12126 }
12127
12128 pub fn select_next_match_internal(
12129 &mut self,
12130 display_map: &DisplaySnapshot,
12131 replace_newest: bool,
12132 autoscroll: Option<Autoscroll>,
12133 window: &mut Window,
12134 cx: &mut Context<Self>,
12135 ) -> Result<()> {
12136 fn select_next_match_ranges(
12137 this: &mut Editor,
12138 range: Range<usize>,
12139 reversed: bool,
12140 replace_newest: bool,
12141 auto_scroll: Option<Autoscroll>,
12142 window: &mut Window,
12143 cx: &mut Context<Editor>,
12144 ) {
12145 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12146 this.change_selections(auto_scroll, window, cx, |s| {
12147 if replace_newest {
12148 s.delete(s.newest_anchor().id);
12149 }
12150 if reversed {
12151 s.insert_range(range.end..range.start);
12152 } else {
12153 s.insert_range(range);
12154 }
12155 });
12156 }
12157
12158 let buffer = &display_map.buffer_snapshot;
12159 let mut selections = self.selections.all::<usize>(cx);
12160 if let Some(mut select_next_state) = self.select_next_state.take() {
12161 let query = &select_next_state.query;
12162 if !select_next_state.done {
12163 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12164 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12165 let mut next_selected_range = None;
12166
12167 let bytes_after_last_selection =
12168 buffer.bytes_in_range(last_selection.end..buffer.len());
12169 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12170 let query_matches = query
12171 .stream_find_iter(bytes_after_last_selection)
12172 .map(|result| (last_selection.end, result))
12173 .chain(
12174 query
12175 .stream_find_iter(bytes_before_first_selection)
12176 .map(|result| (0, result)),
12177 );
12178
12179 for (start_offset, query_match) in query_matches {
12180 let query_match = query_match.unwrap(); // can only fail due to I/O
12181 let offset_range =
12182 start_offset + query_match.start()..start_offset + query_match.end();
12183 let display_range = offset_range.start.to_display_point(display_map)
12184 ..offset_range.end.to_display_point(display_map);
12185
12186 if !select_next_state.wordwise
12187 || (!movement::is_inside_word(display_map, display_range.start)
12188 && !movement::is_inside_word(display_map, display_range.end))
12189 {
12190 // TODO: This is n^2, because we might check all the selections
12191 if !selections
12192 .iter()
12193 .any(|selection| selection.range().overlaps(&offset_range))
12194 {
12195 next_selected_range = Some(offset_range);
12196 break;
12197 }
12198 }
12199 }
12200
12201 if let Some(next_selected_range) = next_selected_range {
12202 select_next_match_ranges(
12203 self,
12204 next_selected_range,
12205 last_selection.reversed,
12206 replace_newest,
12207 autoscroll,
12208 window,
12209 cx,
12210 );
12211 } else {
12212 select_next_state.done = true;
12213 }
12214 }
12215
12216 self.select_next_state = Some(select_next_state);
12217 } else {
12218 let mut only_carets = true;
12219 let mut same_text_selected = true;
12220 let mut selected_text = None;
12221
12222 let mut selections_iter = selections.iter().peekable();
12223 while let Some(selection) = selections_iter.next() {
12224 if selection.start != selection.end {
12225 only_carets = false;
12226 }
12227
12228 if same_text_selected {
12229 if selected_text.is_none() {
12230 selected_text =
12231 Some(buffer.text_for_range(selection.range()).collect::<String>());
12232 }
12233
12234 if let Some(next_selection) = selections_iter.peek() {
12235 if next_selection.range().len() == selection.range().len() {
12236 let next_selected_text = buffer
12237 .text_for_range(next_selection.range())
12238 .collect::<String>();
12239 if Some(next_selected_text) != selected_text {
12240 same_text_selected = false;
12241 selected_text = None;
12242 }
12243 } else {
12244 same_text_selected = false;
12245 selected_text = None;
12246 }
12247 }
12248 }
12249 }
12250
12251 if only_carets {
12252 for selection in &mut selections {
12253 let word_range = movement::surrounding_word(
12254 display_map,
12255 selection.start.to_display_point(display_map),
12256 );
12257 selection.start = word_range.start.to_offset(display_map, Bias::Left);
12258 selection.end = word_range.end.to_offset(display_map, Bias::Left);
12259 selection.goal = SelectionGoal::None;
12260 selection.reversed = false;
12261 select_next_match_ranges(
12262 self,
12263 selection.start..selection.end,
12264 selection.reversed,
12265 replace_newest,
12266 autoscroll,
12267 window,
12268 cx,
12269 );
12270 }
12271
12272 if selections.len() == 1 {
12273 let selection = selections
12274 .last()
12275 .expect("ensured that there's only one selection");
12276 let query = buffer
12277 .text_for_range(selection.start..selection.end)
12278 .collect::<String>();
12279 let is_empty = query.is_empty();
12280 let select_state = SelectNextState {
12281 query: AhoCorasick::new(&[query])?,
12282 wordwise: true,
12283 done: is_empty,
12284 };
12285 self.select_next_state = Some(select_state);
12286 } else {
12287 self.select_next_state = None;
12288 }
12289 } else if let Some(selected_text) = selected_text {
12290 self.select_next_state = Some(SelectNextState {
12291 query: AhoCorasick::new(&[selected_text])?,
12292 wordwise: false,
12293 done: false,
12294 });
12295 self.select_next_match_internal(
12296 display_map,
12297 replace_newest,
12298 autoscroll,
12299 window,
12300 cx,
12301 )?;
12302 }
12303 }
12304 Ok(())
12305 }
12306
12307 pub fn select_all_matches(
12308 &mut self,
12309 _action: &SelectAllMatches,
12310 window: &mut Window,
12311 cx: &mut Context<Self>,
12312 ) -> Result<()> {
12313 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12314
12315 self.push_to_selection_history();
12316 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12317
12318 self.select_next_match_internal(&display_map, false, None, window, cx)?;
12319 let Some(select_next_state) = self.select_next_state.as_mut() else {
12320 return Ok(());
12321 };
12322 if select_next_state.done {
12323 return Ok(());
12324 }
12325
12326 let mut new_selections = Vec::new();
12327
12328 let reversed = self.selections.oldest::<usize>(cx).reversed;
12329 let buffer = &display_map.buffer_snapshot;
12330 let query_matches = select_next_state
12331 .query
12332 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12333
12334 for query_match in query_matches.into_iter() {
12335 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12336 let offset_range = if reversed {
12337 query_match.end()..query_match.start()
12338 } else {
12339 query_match.start()..query_match.end()
12340 };
12341 let display_range = offset_range.start.to_display_point(&display_map)
12342 ..offset_range.end.to_display_point(&display_map);
12343
12344 if !select_next_state.wordwise
12345 || (!movement::is_inside_word(&display_map, display_range.start)
12346 && !movement::is_inside_word(&display_map, display_range.end))
12347 {
12348 new_selections.push(offset_range.start..offset_range.end);
12349 }
12350 }
12351
12352 select_next_state.done = true;
12353 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12354 self.change_selections(None, window, cx, |selections| {
12355 selections.select_ranges(new_selections)
12356 });
12357
12358 Ok(())
12359 }
12360
12361 pub fn select_next(
12362 &mut self,
12363 action: &SelectNext,
12364 window: &mut Window,
12365 cx: &mut Context<Self>,
12366 ) -> Result<()> {
12367 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12368 self.push_to_selection_history();
12369 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12370 self.select_next_match_internal(
12371 &display_map,
12372 action.replace_newest,
12373 Some(Autoscroll::newest()),
12374 window,
12375 cx,
12376 )?;
12377 Ok(())
12378 }
12379
12380 pub fn select_previous(
12381 &mut self,
12382 action: &SelectPrevious,
12383 window: &mut Window,
12384 cx: &mut Context<Self>,
12385 ) -> Result<()> {
12386 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12387 self.push_to_selection_history();
12388 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12389 let buffer = &display_map.buffer_snapshot;
12390 let mut selections = self.selections.all::<usize>(cx);
12391 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12392 let query = &select_prev_state.query;
12393 if !select_prev_state.done {
12394 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12395 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12396 let mut next_selected_range = None;
12397 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12398 let bytes_before_last_selection =
12399 buffer.reversed_bytes_in_range(0..last_selection.start);
12400 let bytes_after_first_selection =
12401 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12402 let query_matches = query
12403 .stream_find_iter(bytes_before_last_selection)
12404 .map(|result| (last_selection.start, result))
12405 .chain(
12406 query
12407 .stream_find_iter(bytes_after_first_selection)
12408 .map(|result| (buffer.len(), result)),
12409 );
12410 for (end_offset, query_match) in query_matches {
12411 let query_match = query_match.unwrap(); // can only fail due to I/O
12412 let offset_range =
12413 end_offset - query_match.end()..end_offset - query_match.start();
12414 let display_range = offset_range.start.to_display_point(&display_map)
12415 ..offset_range.end.to_display_point(&display_map);
12416
12417 if !select_prev_state.wordwise
12418 || (!movement::is_inside_word(&display_map, display_range.start)
12419 && !movement::is_inside_word(&display_map, display_range.end))
12420 {
12421 next_selected_range = Some(offset_range);
12422 break;
12423 }
12424 }
12425
12426 if let Some(next_selected_range) = next_selected_range {
12427 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12428 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12429 if action.replace_newest {
12430 s.delete(s.newest_anchor().id);
12431 }
12432 if last_selection.reversed {
12433 s.insert_range(next_selected_range.end..next_selected_range.start);
12434 } else {
12435 s.insert_range(next_selected_range);
12436 }
12437 });
12438 } else {
12439 select_prev_state.done = true;
12440 }
12441 }
12442
12443 self.select_prev_state = Some(select_prev_state);
12444 } else {
12445 let mut only_carets = true;
12446 let mut same_text_selected = true;
12447 let mut selected_text = None;
12448
12449 let mut selections_iter = selections.iter().peekable();
12450 while let Some(selection) = selections_iter.next() {
12451 if selection.start != selection.end {
12452 only_carets = false;
12453 }
12454
12455 if same_text_selected {
12456 if selected_text.is_none() {
12457 selected_text =
12458 Some(buffer.text_for_range(selection.range()).collect::<String>());
12459 }
12460
12461 if let Some(next_selection) = selections_iter.peek() {
12462 if next_selection.range().len() == selection.range().len() {
12463 let next_selected_text = buffer
12464 .text_for_range(next_selection.range())
12465 .collect::<String>();
12466 if Some(next_selected_text) != selected_text {
12467 same_text_selected = false;
12468 selected_text = None;
12469 }
12470 } else {
12471 same_text_selected = false;
12472 selected_text = None;
12473 }
12474 }
12475 }
12476 }
12477
12478 if only_carets {
12479 for selection in &mut selections {
12480 let word_range = movement::surrounding_word(
12481 &display_map,
12482 selection.start.to_display_point(&display_map),
12483 );
12484 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12485 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12486 selection.goal = SelectionGoal::None;
12487 selection.reversed = false;
12488 }
12489 if selections.len() == 1 {
12490 let selection = selections
12491 .last()
12492 .expect("ensured that there's only one selection");
12493 let query = buffer
12494 .text_for_range(selection.start..selection.end)
12495 .collect::<String>();
12496 let is_empty = query.is_empty();
12497 let select_state = SelectNextState {
12498 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12499 wordwise: true,
12500 done: is_empty,
12501 };
12502 self.select_prev_state = Some(select_state);
12503 } else {
12504 self.select_prev_state = None;
12505 }
12506
12507 self.unfold_ranges(
12508 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12509 false,
12510 true,
12511 cx,
12512 );
12513 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12514 s.select(selections);
12515 });
12516 } else if let Some(selected_text) = selected_text {
12517 self.select_prev_state = Some(SelectNextState {
12518 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12519 wordwise: false,
12520 done: false,
12521 });
12522 self.select_previous(action, window, cx)?;
12523 }
12524 }
12525 Ok(())
12526 }
12527
12528 pub fn find_next_match(
12529 &mut self,
12530 _: &FindNextMatch,
12531 window: &mut Window,
12532 cx: &mut Context<Self>,
12533 ) -> Result<()> {
12534 let selections = self.selections.disjoint_anchors();
12535 match selections.first() {
12536 Some(first) if selections.len() >= 2 => {
12537 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12538 s.select_ranges([first.range()]);
12539 });
12540 }
12541 _ => self.select_next(
12542 &SelectNext {
12543 replace_newest: true,
12544 },
12545 window,
12546 cx,
12547 )?,
12548 }
12549 Ok(())
12550 }
12551
12552 pub fn find_previous_match(
12553 &mut self,
12554 _: &FindPreviousMatch,
12555 window: &mut Window,
12556 cx: &mut Context<Self>,
12557 ) -> Result<()> {
12558 let selections = self.selections.disjoint_anchors();
12559 match selections.last() {
12560 Some(last) if selections.len() >= 2 => {
12561 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12562 s.select_ranges([last.range()]);
12563 });
12564 }
12565 _ => self.select_previous(
12566 &SelectPrevious {
12567 replace_newest: true,
12568 },
12569 window,
12570 cx,
12571 )?,
12572 }
12573 Ok(())
12574 }
12575
12576 pub fn toggle_comments(
12577 &mut self,
12578 action: &ToggleComments,
12579 window: &mut Window,
12580 cx: &mut Context<Self>,
12581 ) {
12582 if self.read_only(cx) {
12583 return;
12584 }
12585 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12586 let text_layout_details = &self.text_layout_details(window);
12587 self.transact(window, cx, |this, window, cx| {
12588 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12589 let mut edits = Vec::new();
12590 let mut selection_edit_ranges = Vec::new();
12591 let mut last_toggled_row = None;
12592 let snapshot = this.buffer.read(cx).read(cx);
12593 let empty_str: Arc<str> = Arc::default();
12594 let mut suffixes_inserted = Vec::new();
12595 let ignore_indent = action.ignore_indent;
12596
12597 fn comment_prefix_range(
12598 snapshot: &MultiBufferSnapshot,
12599 row: MultiBufferRow,
12600 comment_prefix: &str,
12601 comment_prefix_whitespace: &str,
12602 ignore_indent: bool,
12603 ) -> Range<Point> {
12604 let indent_size = if ignore_indent {
12605 0
12606 } else {
12607 snapshot.indent_size_for_line(row).len
12608 };
12609
12610 let start = Point::new(row.0, indent_size);
12611
12612 let mut line_bytes = snapshot
12613 .bytes_in_range(start..snapshot.max_point())
12614 .flatten()
12615 .copied();
12616
12617 // If this line currently begins with the line comment prefix, then record
12618 // the range containing the prefix.
12619 if line_bytes
12620 .by_ref()
12621 .take(comment_prefix.len())
12622 .eq(comment_prefix.bytes())
12623 {
12624 // Include any whitespace that matches the comment prefix.
12625 let matching_whitespace_len = line_bytes
12626 .zip(comment_prefix_whitespace.bytes())
12627 .take_while(|(a, b)| a == b)
12628 .count() as u32;
12629 let end = Point::new(
12630 start.row,
12631 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12632 );
12633 start..end
12634 } else {
12635 start..start
12636 }
12637 }
12638
12639 fn comment_suffix_range(
12640 snapshot: &MultiBufferSnapshot,
12641 row: MultiBufferRow,
12642 comment_suffix: &str,
12643 comment_suffix_has_leading_space: bool,
12644 ) -> Range<Point> {
12645 let end = Point::new(row.0, snapshot.line_len(row));
12646 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12647
12648 let mut line_end_bytes = snapshot
12649 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12650 .flatten()
12651 .copied();
12652
12653 let leading_space_len = if suffix_start_column > 0
12654 && line_end_bytes.next() == Some(b' ')
12655 && comment_suffix_has_leading_space
12656 {
12657 1
12658 } else {
12659 0
12660 };
12661
12662 // If this line currently begins with the line comment prefix, then record
12663 // the range containing the prefix.
12664 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12665 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12666 start..end
12667 } else {
12668 end..end
12669 }
12670 }
12671
12672 // TODO: Handle selections that cross excerpts
12673 for selection in &mut selections {
12674 let start_column = snapshot
12675 .indent_size_for_line(MultiBufferRow(selection.start.row))
12676 .len;
12677 let language = if let Some(language) =
12678 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12679 {
12680 language
12681 } else {
12682 continue;
12683 };
12684
12685 selection_edit_ranges.clear();
12686
12687 // If multiple selections contain a given row, avoid processing that
12688 // row more than once.
12689 let mut start_row = MultiBufferRow(selection.start.row);
12690 if last_toggled_row == Some(start_row) {
12691 start_row = start_row.next_row();
12692 }
12693 let end_row =
12694 if selection.end.row > selection.start.row && selection.end.column == 0 {
12695 MultiBufferRow(selection.end.row - 1)
12696 } else {
12697 MultiBufferRow(selection.end.row)
12698 };
12699 last_toggled_row = Some(end_row);
12700
12701 if start_row > end_row {
12702 continue;
12703 }
12704
12705 // If the language has line comments, toggle those.
12706 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12707
12708 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12709 if ignore_indent {
12710 full_comment_prefixes = full_comment_prefixes
12711 .into_iter()
12712 .map(|s| Arc::from(s.trim_end()))
12713 .collect();
12714 }
12715
12716 if !full_comment_prefixes.is_empty() {
12717 let first_prefix = full_comment_prefixes
12718 .first()
12719 .expect("prefixes is non-empty");
12720 let prefix_trimmed_lengths = full_comment_prefixes
12721 .iter()
12722 .map(|p| p.trim_end_matches(' ').len())
12723 .collect::<SmallVec<[usize; 4]>>();
12724
12725 let mut all_selection_lines_are_comments = true;
12726
12727 for row in start_row.0..=end_row.0 {
12728 let row = MultiBufferRow(row);
12729 if start_row < end_row && snapshot.is_line_blank(row) {
12730 continue;
12731 }
12732
12733 let prefix_range = full_comment_prefixes
12734 .iter()
12735 .zip(prefix_trimmed_lengths.iter().copied())
12736 .map(|(prefix, trimmed_prefix_len)| {
12737 comment_prefix_range(
12738 snapshot.deref(),
12739 row,
12740 &prefix[..trimmed_prefix_len],
12741 &prefix[trimmed_prefix_len..],
12742 ignore_indent,
12743 )
12744 })
12745 .max_by_key(|range| range.end.column - range.start.column)
12746 .expect("prefixes is non-empty");
12747
12748 if prefix_range.is_empty() {
12749 all_selection_lines_are_comments = false;
12750 }
12751
12752 selection_edit_ranges.push(prefix_range);
12753 }
12754
12755 if all_selection_lines_are_comments {
12756 edits.extend(
12757 selection_edit_ranges
12758 .iter()
12759 .cloned()
12760 .map(|range| (range, empty_str.clone())),
12761 );
12762 } else {
12763 let min_column = selection_edit_ranges
12764 .iter()
12765 .map(|range| range.start.column)
12766 .min()
12767 .unwrap_or(0);
12768 edits.extend(selection_edit_ranges.iter().map(|range| {
12769 let position = Point::new(range.start.row, min_column);
12770 (position..position, first_prefix.clone())
12771 }));
12772 }
12773 } else if let Some((full_comment_prefix, comment_suffix)) =
12774 language.block_comment_delimiters()
12775 {
12776 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12777 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12778 let prefix_range = comment_prefix_range(
12779 snapshot.deref(),
12780 start_row,
12781 comment_prefix,
12782 comment_prefix_whitespace,
12783 ignore_indent,
12784 );
12785 let suffix_range = comment_suffix_range(
12786 snapshot.deref(),
12787 end_row,
12788 comment_suffix.trim_start_matches(' '),
12789 comment_suffix.starts_with(' '),
12790 );
12791
12792 if prefix_range.is_empty() || suffix_range.is_empty() {
12793 edits.push((
12794 prefix_range.start..prefix_range.start,
12795 full_comment_prefix.clone(),
12796 ));
12797 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12798 suffixes_inserted.push((end_row, comment_suffix.len()));
12799 } else {
12800 edits.push((prefix_range, empty_str.clone()));
12801 edits.push((suffix_range, empty_str.clone()));
12802 }
12803 } else {
12804 continue;
12805 }
12806 }
12807
12808 drop(snapshot);
12809 this.buffer.update(cx, |buffer, cx| {
12810 buffer.edit(edits, None, cx);
12811 });
12812
12813 // Adjust selections so that they end before any comment suffixes that
12814 // were inserted.
12815 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12816 let mut selections = this.selections.all::<Point>(cx);
12817 let snapshot = this.buffer.read(cx).read(cx);
12818 for selection in &mut selections {
12819 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12820 match row.cmp(&MultiBufferRow(selection.end.row)) {
12821 Ordering::Less => {
12822 suffixes_inserted.next();
12823 continue;
12824 }
12825 Ordering::Greater => break,
12826 Ordering::Equal => {
12827 if selection.end.column == snapshot.line_len(row) {
12828 if selection.is_empty() {
12829 selection.start.column -= suffix_len as u32;
12830 }
12831 selection.end.column -= suffix_len as u32;
12832 }
12833 break;
12834 }
12835 }
12836 }
12837 }
12838
12839 drop(snapshot);
12840 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12841 s.select(selections)
12842 });
12843
12844 let selections = this.selections.all::<Point>(cx);
12845 let selections_on_single_row = selections.windows(2).all(|selections| {
12846 selections[0].start.row == selections[1].start.row
12847 && selections[0].end.row == selections[1].end.row
12848 && selections[0].start.row == selections[0].end.row
12849 });
12850 let selections_selecting = selections
12851 .iter()
12852 .any(|selection| selection.start != selection.end);
12853 let advance_downwards = action.advance_downwards
12854 && selections_on_single_row
12855 && !selections_selecting
12856 && !matches!(this.mode, EditorMode::SingleLine { .. });
12857
12858 if advance_downwards {
12859 let snapshot = this.buffer.read(cx).snapshot(cx);
12860
12861 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12862 s.move_cursors_with(|display_snapshot, display_point, _| {
12863 let mut point = display_point.to_point(display_snapshot);
12864 point.row += 1;
12865 point = snapshot.clip_point(point, Bias::Left);
12866 let display_point = point.to_display_point(display_snapshot);
12867 let goal = SelectionGoal::HorizontalPosition(
12868 display_snapshot
12869 .x_for_display_point(display_point, text_layout_details)
12870 .into(),
12871 );
12872 (display_point, goal)
12873 })
12874 });
12875 }
12876 });
12877 }
12878
12879 pub fn select_enclosing_symbol(
12880 &mut self,
12881 _: &SelectEnclosingSymbol,
12882 window: &mut Window,
12883 cx: &mut Context<Self>,
12884 ) {
12885 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12886
12887 let buffer = self.buffer.read(cx).snapshot(cx);
12888 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12889
12890 fn update_selection(
12891 selection: &Selection<usize>,
12892 buffer_snap: &MultiBufferSnapshot,
12893 ) -> Option<Selection<usize>> {
12894 let cursor = selection.head();
12895 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12896 for symbol in symbols.iter().rev() {
12897 let start = symbol.range.start.to_offset(buffer_snap);
12898 let end = symbol.range.end.to_offset(buffer_snap);
12899 let new_range = start..end;
12900 if start < selection.start || end > selection.end {
12901 return Some(Selection {
12902 id: selection.id,
12903 start: new_range.start,
12904 end: new_range.end,
12905 goal: SelectionGoal::None,
12906 reversed: selection.reversed,
12907 });
12908 }
12909 }
12910 None
12911 }
12912
12913 let mut selected_larger_symbol = false;
12914 let new_selections = old_selections
12915 .iter()
12916 .map(|selection| match update_selection(selection, &buffer) {
12917 Some(new_selection) => {
12918 if new_selection.range() != selection.range() {
12919 selected_larger_symbol = true;
12920 }
12921 new_selection
12922 }
12923 None => selection.clone(),
12924 })
12925 .collect::<Vec<_>>();
12926
12927 if selected_larger_symbol {
12928 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12929 s.select(new_selections);
12930 });
12931 }
12932 }
12933
12934 pub fn select_larger_syntax_node(
12935 &mut self,
12936 _: &SelectLargerSyntaxNode,
12937 window: &mut Window,
12938 cx: &mut Context<Self>,
12939 ) {
12940 let Some(visible_row_count) = self.visible_row_count() else {
12941 return;
12942 };
12943 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12944 if old_selections.is_empty() {
12945 return;
12946 }
12947
12948 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12949
12950 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12951 let buffer = self.buffer.read(cx).snapshot(cx);
12952
12953 let mut selected_larger_node = false;
12954 let mut new_selections = old_selections
12955 .iter()
12956 .map(|selection| {
12957 let old_range = selection.start..selection.end;
12958
12959 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12960 // manually select word at selection
12961 if ["string_content", "inline"].contains(&node.kind()) {
12962 let word_range = {
12963 let display_point = buffer
12964 .offset_to_point(old_range.start)
12965 .to_display_point(&display_map);
12966 let Range { start, end } =
12967 movement::surrounding_word(&display_map, display_point);
12968 start.to_point(&display_map).to_offset(&buffer)
12969 ..end.to_point(&display_map).to_offset(&buffer)
12970 };
12971 // ignore if word is already selected
12972 if !word_range.is_empty() && old_range != word_range {
12973 let last_word_range = {
12974 let display_point = buffer
12975 .offset_to_point(old_range.end)
12976 .to_display_point(&display_map);
12977 let Range { start, end } =
12978 movement::surrounding_word(&display_map, display_point);
12979 start.to_point(&display_map).to_offset(&buffer)
12980 ..end.to_point(&display_map).to_offset(&buffer)
12981 };
12982 // only select word if start and end point belongs to same word
12983 if word_range == last_word_range {
12984 selected_larger_node = true;
12985 return Selection {
12986 id: selection.id,
12987 start: word_range.start,
12988 end: word_range.end,
12989 goal: SelectionGoal::None,
12990 reversed: selection.reversed,
12991 };
12992 }
12993 }
12994 }
12995 }
12996
12997 let mut new_range = old_range.clone();
12998 let mut new_node = None;
12999 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
13000 {
13001 new_node = Some(node);
13002 new_range = match containing_range {
13003 MultiOrSingleBufferOffsetRange::Single(_) => break,
13004 MultiOrSingleBufferOffsetRange::Multi(range) => range,
13005 };
13006 if !display_map.intersects_fold(new_range.start)
13007 && !display_map.intersects_fold(new_range.end)
13008 {
13009 break;
13010 }
13011 }
13012
13013 if let Some(node) = new_node {
13014 // Log the ancestor, to support using this action as a way to explore TreeSitter
13015 // nodes. Parent and grandparent are also logged because this operation will not
13016 // visit nodes that have the same range as their parent.
13017 log::info!("Node: {node:?}");
13018 let parent = node.parent();
13019 log::info!("Parent: {parent:?}");
13020 let grandparent = parent.and_then(|x| x.parent());
13021 log::info!("Grandparent: {grandparent:?}");
13022 }
13023
13024 selected_larger_node |= new_range != old_range;
13025 Selection {
13026 id: selection.id,
13027 start: new_range.start,
13028 end: new_range.end,
13029 goal: SelectionGoal::None,
13030 reversed: selection.reversed,
13031 }
13032 })
13033 .collect::<Vec<_>>();
13034
13035 if !selected_larger_node {
13036 return; // don't put this call in the history
13037 }
13038
13039 // scroll based on transformation done to the last selection created by the user
13040 let (last_old, last_new) = old_selections
13041 .last()
13042 .zip(new_selections.last().cloned())
13043 .expect("old_selections isn't empty");
13044
13045 // revert selection
13046 let is_selection_reversed = {
13047 let should_newest_selection_be_reversed = last_old.start != last_new.start;
13048 new_selections.last_mut().expect("checked above").reversed =
13049 should_newest_selection_be_reversed;
13050 should_newest_selection_be_reversed
13051 };
13052
13053 if selected_larger_node {
13054 self.select_syntax_node_history.disable_clearing = true;
13055 self.change_selections(None, window, cx, |s| {
13056 s.select(new_selections.clone());
13057 });
13058 self.select_syntax_node_history.disable_clearing = false;
13059 }
13060
13061 let start_row = last_new.start.to_display_point(&display_map).row().0;
13062 let end_row = last_new.end.to_display_point(&display_map).row().0;
13063 let selection_height = end_row - start_row + 1;
13064 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13065
13066 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13067 let scroll_behavior = if fits_on_the_screen {
13068 self.request_autoscroll(Autoscroll::fit(), cx);
13069 SelectSyntaxNodeScrollBehavior::FitSelection
13070 } else if is_selection_reversed {
13071 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13072 SelectSyntaxNodeScrollBehavior::CursorTop
13073 } else {
13074 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13075 SelectSyntaxNodeScrollBehavior::CursorBottom
13076 };
13077
13078 self.select_syntax_node_history.push((
13079 old_selections,
13080 scroll_behavior,
13081 is_selection_reversed,
13082 ));
13083 }
13084
13085 pub fn select_smaller_syntax_node(
13086 &mut self,
13087 _: &SelectSmallerSyntaxNode,
13088 window: &mut Window,
13089 cx: &mut Context<Self>,
13090 ) {
13091 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13092
13093 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13094 self.select_syntax_node_history.pop()
13095 {
13096 if let Some(selection) = selections.last_mut() {
13097 selection.reversed = is_selection_reversed;
13098 }
13099
13100 self.select_syntax_node_history.disable_clearing = true;
13101 self.change_selections(None, window, cx, |s| {
13102 s.select(selections.to_vec());
13103 });
13104 self.select_syntax_node_history.disable_clearing = false;
13105
13106 match scroll_behavior {
13107 SelectSyntaxNodeScrollBehavior::CursorTop => {
13108 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13109 }
13110 SelectSyntaxNodeScrollBehavior::FitSelection => {
13111 self.request_autoscroll(Autoscroll::fit(), cx);
13112 }
13113 SelectSyntaxNodeScrollBehavior::CursorBottom => {
13114 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13115 }
13116 }
13117 }
13118 }
13119
13120 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13121 if !EditorSettings::get_global(cx).gutter.runnables {
13122 self.clear_tasks();
13123 return Task::ready(());
13124 }
13125 let project = self.project.as_ref().map(Entity::downgrade);
13126 let task_sources = self.lsp_task_sources(cx);
13127 cx.spawn_in(window, async move |editor, cx| {
13128 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13129 let Some(project) = project.and_then(|p| p.upgrade()) else {
13130 return;
13131 };
13132 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13133 this.display_map.update(cx, |map, cx| map.snapshot(cx))
13134 }) else {
13135 return;
13136 };
13137
13138 let hide_runnables = project
13139 .update(cx, |project, cx| {
13140 // Do not display any test indicators in non-dev server remote projects.
13141 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13142 })
13143 .unwrap_or(true);
13144 if hide_runnables {
13145 return;
13146 }
13147 let new_rows =
13148 cx.background_spawn({
13149 let snapshot = display_snapshot.clone();
13150 async move {
13151 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13152 }
13153 })
13154 .await;
13155 let Ok(lsp_tasks) =
13156 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13157 else {
13158 return;
13159 };
13160 let lsp_tasks = lsp_tasks.await;
13161
13162 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13163 lsp_tasks
13164 .into_iter()
13165 .flat_map(|(kind, tasks)| {
13166 tasks.into_iter().filter_map(move |(location, task)| {
13167 Some((kind.clone(), location?, task))
13168 })
13169 })
13170 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13171 let buffer = location.target.buffer;
13172 let buffer_snapshot = buffer.read(cx).snapshot();
13173 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13174 |(excerpt_id, snapshot, _)| {
13175 if snapshot.remote_id() == buffer_snapshot.remote_id() {
13176 display_snapshot
13177 .buffer_snapshot
13178 .anchor_in_excerpt(excerpt_id, location.target.range.start)
13179 } else {
13180 None
13181 }
13182 },
13183 );
13184 if let Some(offset) = offset {
13185 let task_buffer_range =
13186 location.target.range.to_point(&buffer_snapshot);
13187 let context_buffer_range =
13188 task_buffer_range.to_offset(&buffer_snapshot);
13189 let context_range = BufferOffset(context_buffer_range.start)
13190 ..BufferOffset(context_buffer_range.end);
13191
13192 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13193 .or_insert_with(|| RunnableTasks {
13194 templates: Vec::new(),
13195 offset,
13196 column: task_buffer_range.start.column,
13197 extra_variables: HashMap::default(),
13198 context_range,
13199 })
13200 .templates
13201 .push((kind, task.original_task().clone()));
13202 }
13203
13204 acc
13205 })
13206 }) else {
13207 return;
13208 };
13209
13210 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13211 editor
13212 .update(cx, |editor, _| {
13213 editor.clear_tasks();
13214 for (key, mut value) in rows {
13215 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13216 value.templates.extend(lsp_tasks.templates);
13217 }
13218
13219 editor.insert_tasks(key, value);
13220 }
13221 for (key, value) in lsp_tasks_by_rows {
13222 editor.insert_tasks(key, value);
13223 }
13224 })
13225 .ok();
13226 })
13227 }
13228 fn fetch_runnable_ranges(
13229 snapshot: &DisplaySnapshot,
13230 range: Range<Anchor>,
13231 ) -> Vec<language::RunnableRange> {
13232 snapshot.buffer_snapshot.runnable_ranges(range).collect()
13233 }
13234
13235 fn runnable_rows(
13236 project: Entity<Project>,
13237 snapshot: DisplaySnapshot,
13238 runnable_ranges: Vec<RunnableRange>,
13239 mut cx: AsyncWindowContext,
13240 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13241 runnable_ranges
13242 .into_iter()
13243 .filter_map(|mut runnable| {
13244 let tasks = cx
13245 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13246 .ok()?;
13247 if tasks.is_empty() {
13248 return None;
13249 }
13250
13251 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13252
13253 let row = snapshot
13254 .buffer_snapshot
13255 .buffer_line_for_row(MultiBufferRow(point.row))?
13256 .1
13257 .start
13258 .row;
13259
13260 let context_range =
13261 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13262 Some((
13263 (runnable.buffer_id, row),
13264 RunnableTasks {
13265 templates: tasks,
13266 offset: snapshot
13267 .buffer_snapshot
13268 .anchor_before(runnable.run_range.start),
13269 context_range,
13270 column: point.column,
13271 extra_variables: runnable.extra_captures,
13272 },
13273 ))
13274 })
13275 .collect()
13276 }
13277
13278 fn templates_with_tags(
13279 project: &Entity<Project>,
13280 runnable: &mut Runnable,
13281 cx: &mut App,
13282 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13283 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13284 let (worktree_id, file) = project
13285 .buffer_for_id(runnable.buffer, cx)
13286 .and_then(|buffer| buffer.read(cx).file())
13287 .map(|file| (file.worktree_id(cx), file.clone()))
13288 .unzip();
13289
13290 (
13291 project.task_store().read(cx).task_inventory().cloned(),
13292 worktree_id,
13293 file,
13294 )
13295 });
13296
13297 let mut templates_with_tags = mem::take(&mut runnable.tags)
13298 .into_iter()
13299 .flat_map(|RunnableTag(tag)| {
13300 inventory
13301 .as_ref()
13302 .into_iter()
13303 .flat_map(|inventory| {
13304 inventory.read(cx).list_tasks(
13305 file.clone(),
13306 Some(runnable.language.clone()),
13307 worktree_id,
13308 cx,
13309 )
13310 })
13311 .filter(move |(_, template)| {
13312 template.tags.iter().any(|source_tag| source_tag == &tag)
13313 })
13314 })
13315 .sorted_by_key(|(kind, _)| kind.to_owned())
13316 .collect::<Vec<_>>();
13317 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13318 // Strongest source wins; if we have worktree tag binding, prefer that to
13319 // global and language bindings;
13320 // if we have a global binding, prefer that to language binding.
13321 let first_mismatch = templates_with_tags
13322 .iter()
13323 .position(|(tag_source, _)| tag_source != leading_tag_source);
13324 if let Some(index) = first_mismatch {
13325 templates_with_tags.truncate(index);
13326 }
13327 }
13328
13329 templates_with_tags
13330 }
13331
13332 pub fn move_to_enclosing_bracket(
13333 &mut self,
13334 _: &MoveToEnclosingBracket,
13335 window: &mut Window,
13336 cx: &mut Context<Self>,
13337 ) {
13338 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13339 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13340 s.move_offsets_with(|snapshot, selection| {
13341 let Some(enclosing_bracket_ranges) =
13342 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13343 else {
13344 return;
13345 };
13346
13347 let mut best_length = usize::MAX;
13348 let mut best_inside = false;
13349 let mut best_in_bracket_range = false;
13350 let mut best_destination = None;
13351 for (open, close) in enclosing_bracket_ranges {
13352 let close = close.to_inclusive();
13353 let length = close.end() - open.start;
13354 let inside = selection.start >= open.end && selection.end <= *close.start();
13355 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13356 || close.contains(&selection.head());
13357
13358 // If best is next to a bracket and current isn't, skip
13359 if !in_bracket_range && best_in_bracket_range {
13360 continue;
13361 }
13362
13363 // Prefer smaller lengths unless best is inside and current isn't
13364 if length > best_length && (best_inside || !inside) {
13365 continue;
13366 }
13367
13368 best_length = length;
13369 best_inside = inside;
13370 best_in_bracket_range = in_bracket_range;
13371 best_destination = Some(
13372 if close.contains(&selection.start) && close.contains(&selection.end) {
13373 if inside { open.end } else { open.start }
13374 } else if inside {
13375 *close.start()
13376 } else {
13377 *close.end()
13378 },
13379 );
13380 }
13381
13382 if let Some(destination) = best_destination {
13383 selection.collapse_to(destination, SelectionGoal::None);
13384 }
13385 })
13386 });
13387 }
13388
13389 pub fn undo_selection(
13390 &mut self,
13391 _: &UndoSelection,
13392 window: &mut Window,
13393 cx: &mut Context<Self>,
13394 ) {
13395 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13396 self.end_selection(window, cx);
13397 self.selection_history.mode = SelectionHistoryMode::Undoing;
13398 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13399 self.change_selections(None, window, cx, |s| {
13400 s.select_anchors(entry.selections.to_vec())
13401 });
13402 self.select_next_state = entry.select_next_state;
13403 self.select_prev_state = entry.select_prev_state;
13404 self.add_selections_state = entry.add_selections_state;
13405 self.request_autoscroll(Autoscroll::newest(), cx);
13406 }
13407 self.selection_history.mode = SelectionHistoryMode::Normal;
13408 }
13409
13410 pub fn redo_selection(
13411 &mut self,
13412 _: &RedoSelection,
13413 window: &mut Window,
13414 cx: &mut Context<Self>,
13415 ) {
13416 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13417 self.end_selection(window, cx);
13418 self.selection_history.mode = SelectionHistoryMode::Redoing;
13419 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13420 self.change_selections(None, window, cx, |s| {
13421 s.select_anchors(entry.selections.to_vec())
13422 });
13423 self.select_next_state = entry.select_next_state;
13424 self.select_prev_state = entry.select_prev_state;
13425 self.add_selections_state = entry.add_selections_state;
13426 self.request_autoscroll(Autoscroll::newest(), cx);
13427 }
13428 self.selection_history.mode = SelectionHistoryMode::Normal;
13429 }
13430
13431 pub fn expand_excerpts(
13432 &mut self,
13433 action: &ExpandExcerpts,
13434 _: &mut Window,
13435 cx: &mut Context<Self>,
13436 ) {
13437 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13438 }
13439
13440 pub fn expand_excerpts_down(
13441 &mut self,
13442 action: &ExpandExcerptsDown,
13443 _: &mut Window,
13444 cx: &mut Context<Self>,
13445 ) {
13446 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13447 }
13448
13449 pub fn expand_excerpts_up(
13450 &mut self,
13451 action: &ExpandExcerptsUp,
13452 _: &mut Window,
13453 cx: &mut Context<Self>,
13454 ) {
13455 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13456 }
13457
13458 pub fn expand_excerpts_for_direction(
13459 &mut self,
13460 lines: u32,
13461 direction: ExpandExcerptDirection,
13462
13463 cx: &mut Context<Self>,
13464 ) {
13465 let selections = self.selections.disjoint_anchors();
13466
13467 let lines = if lines == 0 {
13468 EditorSettings::get_global(cx).expand_excerpt_lines
13469 } else {
13470 lines
13471 };
13472
13473 self.buffer.update(cx, |buffer, cx| {
13474 let snapshot = buffer.snapshot(cx);
13475 let mut excerpt_ids = selections
13476 .iter()
13477 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13478 .collect::<Vec<_>>();
13479 excerpt_ids.sort();
13480 excerpt_ids.dedup();
13481 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13482 })
13483 }
13484
13485 pub fn expand_excerpt(
13486 &mut self,
13487 excerpt: ExcerptId,
13488 direction: ExpandExcerptDirection,
13489 window: &mut Window,
13490 cx: &mut Context<Self>,
13491 ) {
13492 let current_scroll_position = self.scroll_position(cx);
13493 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13494 let mut should_scroll_up = false;
13495
13496 if direction == ExpandExcerptDirection::Down {
13497 let multi_buffer = self.buffer.read(cx);
13498 let snapshot = multi_buffer.snapshot(cx);
13499 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13500 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13501 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13502 let buffer_snapshot = buffer.read(cx).snapshot();
13503 let excerpt_end_row =
13504 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13505 let last_row = buffer_snapshot.max_point().row;
13506 let lines_below = last_row.saturating_sub(excerpt_end_row);
13507 should_scroll_up = lines_below >= lines_to_expand;
13508 }
13509 }
13510 }
13511 }
13512
13513 self.buffer.update(cx, |buffer, cx| {
13514 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13515 });
13516
13517 if should_scroll_up {
13518 let new_scroll_position =
13519 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13520 self.set_scroll_position(new_scroll_position, window, cx);
13521 }
13522 }
13523
13524 pub fn go_to_singleton_buffer_point(
13525 &mut self,
13526 point: Point,
13527 window: &mut Window,
13528 cx: &mut Context<Self>,
13529 ) {
13530 self.go_to_singleton_buffer_range(point..point, window, cx);
13531 }
13532
13533 pub fn go_to_singleton_buffer_range(
13534 &mut self,
13535 range: Range<Point>,
13536 window: &mut Window,
13537 cx: &mut Context<Self>,
13538 ) {
13539 let multibuffer = self.buffer().read(cx);
13540 let Some(buffer) = multibuffer.as_singleton() else {
13541 return;
13542 };
13543 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13544 return;
13545 };
13546 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13547 return;
13548 };
13549 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13550 s.select_anchor_ranges([start..end])
13551 });
13552 }
13553
13554 pub fn go_to_diagnostic(
13555 &mut self,
13556 _: &GoToDiagnostic,
13557 window: &mut Window,
13558 cx: &mut Context<Self>,
13559 ) {
13560 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13561 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13562 }
13563
13564 pub fn go_to_prev_diagnostic(
13565 &mut self,
13566 _: &GoToPreviousDiagnostic,
13567 window: &mut Window,
13568 cx: &mut Context<Self>,
13569 ) {
13570 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13571 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13572 }
13573
13574 pub fn go_to_diagnostic_impl(
13575 &mut self,
13576 direction: Direction,
13577 window: &mut Window,
13578 cx: &mut Context<Self>,
13579 ) {
13580 let buffer = self.buffer.read(cx).snapshot(cx);
13581 let selection = self.selections.newest::<usize>(cx);
13582
13583 let mut active_group_id = None;
13584 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13585 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13586 active_group_id = Some(active_group.group_id);
13587 }
13588 }
13589
13590 fn filtered(
13591 snapshot: EditorSnapshot,
13592 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13593 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13594 diagnostics
13595 .filter(|entry| entry.range.start != entry.range.end)
13596 .filter(|entry| !entry.diagnostic.is_unnecessary)
13597 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13598 }
13599
13600 let snapshot = self.snapshot(window, cx);
13601 let before = filtered(
13602 snapshot.clone(),
13603 buffer
13604 .diagnostics_in_range(0..selection.start)
13605 .filter(|entry| entry.range.start <= selection.start),
13606 );
13607 let after = filtered(
13608 snapshot,
13609 buffer
13610 .diagnostics_in_range(selection.start..buffer.len())
13611 .filter(|entry| entry.range.start >= selection.start),
13612 );
13613
13614 let mut found: Option<DiagnosticEntry<usize>> = None;
13615 if direction == Direction::Prev {
13616 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13617 {
13618 for diagnostic in prev_diagnostics.into_iter().rev() {
13619 if diagnostic.range.start != selection.start
13620 || active_group_id
13621 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13622 {
13623 found = Some(diagnostic);
13624 break 'outer;
13625 }
13626 }
13627 }
13628 } else {
13629 for diagnostic in after.chain(before) {
13630 if diagnostic.range.start != selection.start
13631 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13632 {
13633 found = Some(diagnostic);
13634 break;
13635 }
13636 }
13637 }
13638 let Some(next_diagnostic) = found else {
13639 return;
13640 };
13641
13642 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13643 return;
13644 };
13645 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13646 s.select_ranges(vec![
13647 next_diagnostic.range.start..next_diagnostic.range.start,
13648 ])
13649 });
13650 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13651 self.refresh_inline_completion(false, true, window, cx);
13652 }
13653
13654 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13655 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13656 let snapshot = self.snapshot(window, cx);
13657 let selection = self.selections.newest::<Point>(cx);
13658 self.go_to_hunk_before_or_after_position(
13659 &snapshot,
13660 selection.head(),
13661 Direction::Next,
13662 window,
13663 cx,
13664 );
13665 }
13666
13667 pub fn go_to_hunk_before_or_after_position(
13668 &mut self,
13669 snapshot: &EditorSnapshot,
13670 position: Point,
13671 direction: Direction,
13672 window: &mut Window,
13673 cx: &mut Context<Editor>,
13674 ) {
13675 let row = if direction == Direction::Next {
13676 self.hunk_after_position(snapshot, position)
13677 .map(|hunk| hunk.row_range.start)
13678 } else {
13679 self.hunk_before_position(snapshot, position)
13680 };
13681
13682 if let Some(row) = row {
13683 let destination = Point::new(row.0, 0);
13684 let autoscroll = Autoscroll::center();
13685
13686 self.unfold_ranges(&[destination..destination], false, false, cx);
13687 self.change_selections(Some(autoscroll), window, cx, |s| {
13688 s.select_ranges([destination..destination]);
13689 });
13690 }
13691 }
13692
13693 fn hunk_after_position(
13694 &mut self,
13695 snapshot: &EditorSnapshot,
13696 position: Point,
13697 ) -> Option<MultiBufferDiffHunk> {
13698 snapshot
13699 .buffer_snapshot
13700 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13701 .find(|hunk| hunk.row_range.start.0 > position.row)
13702 .or_else(|| {
13703 snapshot
13704 .buffer_snapshot
13705 .diff_hunks_in_range(Point::zero()..position)
13706 .find(|hunk| hunk.row_range.end.0 < position.row)
13707 })
13708 }
13709
13710 fn go_to_prev_hunk(
13711 &mut self,
13712 _: &GoToPreviousHunk,
13713 window: &mut Window,
13714 cx: &mut Context<Self>,
13715 ) {
13716 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13717 let snapshot = self.snapshot(window, cx);
13718 let selection = self.selections.newest::<Point>(cx);
13719 self.go_to_hunk_before_or_after_position(
13720 &snapshot,
13721 selection.head(),
13722 Direction::Prev,
13723 window,
13724 cx,
13725 );
13726 }
13727
13728 fn hunk_before_position(
13729 &mut self,
13730 snapshot: &EditorSnapshot,
13731 position: Point,
13732 ) -> Option<MultiBufferRow> {
13733 snapshot
13734 .buffer_snapshot
13735 .diff_hunk_before(position)
13736 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13737 }
13738
13739 fn go_to_next_change(
13740 &mut self,
13741 _: &GoToNextChange,
13742 window: &mut Window,
13743 cx: &mut Context<Self>,
13744 ) {
13745 if let Some(selections) = self
13746 .change_list
13747 .next_change(1, Direction::Next)
13748 .map(|s| s.to_vec())
13749 {
13750 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13751 let map = s.display_map();
13752 s.select_display_ranges(selections.iter().map(|a| {
13753 let point = a.to_display_point(&map);
13754 point..point
13755 }))
13756 })
13757 }
13758 }
13759
13760 fn go_to_previous_change(
13761 &mut self,
13762 _: &GoToPreviousChange,
13763 window: &mut Window,
13764 cx: &mut Context<Self>,
13765 ) {
13766 if let Some(selections) = self
13767 .change_list
13768 .next_change(1, Direction::Prev)
13769 .map(|s| s.to_vec())
13770 {
13771 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13772 let map = s.display_map();
13773 s.select_display_ranges(selections.iter().map(|a| {
13774 let point = a.to_display_point(&map);
13775 point..point
13776 }))
13777 })
13778 }
13779 }
13780
13781 fn go_to_line<T: 'static>(
13782 &mut self,
13783 position: Anchor,
13784 highlight_color: Option<Hsla>,
13785 window: &mut Window,
13786 cx: &mut Context<Self>,
13787 ) {
13788 let snapshot = self.snapshot(window, cx).display_snapshot;
13789 let position = position.to_point(&snapshot.buffer_snapshot);
13790 let start = snapshot
13791 .buffer_snapshot
13792 .clip_point(Point::new(position.row, 0), Bias::Left);
13793 let end = start + Point::new(1, 0);
13794 let start = snapshot.buffer_snapshot.anchor_before(start);
13795 let end = snapshot.buffer_snapshot.anchor_before(end);
13796
13797 self.highlight_rows::<T>(
13798 start..end,
13799 highlight_color
13800 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13801 Default::default(),
13802 cx,
13803 );
13804 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13805 }
13806
13807 pub fn go_to_definition(
13808 &mut self,
13809 _: &GoToDefinition,
13810 window: &mut Window,
13811 cx: &mut Context<Self>,
13812 ) -> Task<Result<Navigated>> {
13813 let definition =
13814 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13815 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13816 cx.spawn_in(window, async move |editor, cx| {
13817 if definition.await? == Navigated::Yes {
13818 return Ok(Navigated::Yes);
13819 }
13820 match fallback_strategy {
13821 GoToDefinitionFallback::None => Ok(Navigated::No),
13822 GoToDefinitionFallback::FindAllReferences => {
13823 match editor.update_in(cx, |editor, window, cx| {
13824 editor.find_all_references(&FindAllReferences, window, cx)
13825 })? {
13826 Some(references) => references.await,
13827 None => Ok(Navigated::No),
13828 }
13829 }
13830 }
13831 })
13832 }
13833
13834 pub fn go_to_declaration(
13835 &mut self,
13836 _: &GoToDeclaration,
13837 window: &mut Window,
13838 cx: &mut Context<Self>,
13839 ) -> Task<Result<Navigated>> {
13840 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13841 }
13842
13843 pub fn go_to_declaration_split(
13844 &mut self,
13845 _: &GoToDeclaration,
13846 window: &mut Window,
13847 cx: &mut Context<Self>,
13848 ) -> Task<Result<Navigated>> {
13849 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13850 }
13851
13852 pub fn go_to_implementation(
13853 &mut self,
13854 _: &GoToImplementation,
13855 window: &mut Window,
13856 cx: &mut Context<Self>,
13857 ) -> Task<Result<Navigated>> {
13858 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13859 }
13860
13861 pub fn go_to_implementation_split(
13862 &mut self,
13863 _: &GoToImplementationSplit,
13864 window: &mut Window,
13865 cx: &mut Context<Self>,
13866 ) -> Task<Result<Navigated>> {
13867 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13868 }
13869
13870 pub fn go_to_type_definition(
13871 &mut self,
13872 _: &GoToTypeDefinition,
13873 window: &mut Window,
13874 cx: &mut Context<Self>,
13875 ) -> Task<Result<Navigated>> {
13876 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13877 }
13878
13879 pub fn go_to_definition_split(
13880 &mut self,
13881 _: &GoToDefinitionSplit,
13882 window: &mut Window,
13883 cx: &mut Context<Self>,
13884 ) -> Task<Result<Navigated>> {
13885 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13886 }
13887
13888 pub fn go_to_type_definition_split(
13889 &mut self,
13890 _: &GoToTypeDefinitionSplit,
13891 window: &mut Window,
13892 cx: &mut Context<Self>,
13893 ) -> Task<Result<Navigated>> {
13894 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13895 }
13896
13897 fn go_to_definition_of_kind(
13898 &mut self,
13899 kind: GotoDefinitionKind,
13900 split: bool,
13901 window: &mut Window,
13902 cx: &mut Context<Self>,
13903 ) -> Task<Result<Navigated>> {
13904 let Some(provider) = self.semantics_provider.clone() else {
13905 return Task::ready(Ok(Navigated::No));
13906 };
13907 let head = self.selections.newest::<usize>(cx).head();
13908 let buffer = self.buffer.read(cx);
13909 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13910 text_anchor
13911 } else {
13912 return Task::ready(Ok(Navigated::No));
13913 };
13914
13915 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13916 return Task::ready(Ok(Navigated::No));
13917 };
13918
13919 cx.spawn_in(window, async move |editor, cx| {
13920 let definitions = definitions.await?;
13921 let navigated = editor
13922 .update_in(cx, |editor, window, cx| {
13923 editor.navigate_to_hover_links(
13924 Some(kind),
13925 definitions
13926 .into_iter()
13927 .filter(|location| {
13928 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13929 })
13930 .map(HoverLink::Text)
13931 .collect::<Vec<_>>(),
13932 split,
13933 window,
13934 cx,
13935 )
13936 })?
13937 .await?;
13938 anyhow::Ok(navigated)
13939 })
13940 }
13941
13942 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13943 let selection = self.selections.newest_anchor();
13944 let head = selection.head();
13945 let tail = selection.tail();
13946
13947 let Some((buffer, start_position)) =
13948 self.buffer.read(cx).text_anchor_for_position(head, cx)
13949 else {
13950 return;
13951 };
13952
13953 let end_position = if head != tail {
13954 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13955 return;
13956 };
13957 Some(pos)
13958 } else {
13959 None
13960 };
13961
13962 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13963 let url = if let Some(end_pos) = end_position {
13964 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13965 } else {
13966 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13967 };
13968
13969 if let Some(url) = url {
13970 editor.update(cx, |_, cx| {
13971 cx.open_url(&url);
13972 })
13973 } else {
13974 Ok(())
13975 }
13976 });
13977
13978 url_finder.detach();
13979 }
13980
13981 pub fn open_selected_filename(
13982 &mut self,
13983 _: &OpenSelectedFilename,
13984 window: &mut Window,
13985 cx: &mut Context<Self>,
13986 ) {
13987 let Some(workspace) = self.workspace() else {
13988 return;
13989 };
13990
13991 let position = self.selections.newest_anchor().head();
13992
13993 let Some((buffer, buffer_position)) =
13994 self.buffer.read(cx).text_anchor_for_position(position, cx)
13995 else {
13996 return;
13997 };
13998
13999 let project = self.project.clone();
14000
14001 cx.spawn_in(window, async move |_, cx| {
14002 let result = find_file(&buffer, project, buffer_position, cx).await;
14003
14004 if let Some((_, path)) = result {
14005 workspace
14006 .update_in(cx, |workspace, window, cx| {
14007 workspace.open_resolved_path(path, window, cx)
14008 })?
14009 .await?;
14010 }
14011 anyhow::Ok(())
14012 })
14013 .detach();
14014 }
14015
14016 pub(crate) fn navigate_to_hover_links(
14017 &mut self,
14018 kind: Option<GotoDefinitionKind>,
14019 mut definitions: Vec<HoverLink>,
14020 split: bool,
14021 window: &mut Window,
14022 cx: &mut Context<Editor>,
14023 ) -> Task<Result<Navigated>> {
14024 // If there is one definition, just open it directly
14025 if definitions.len() == 1 {
14026 let definition = definitions.pop().unwrap();
14027
14028 enum TargetTaskResult {
14029 Location(Option<Location>),
14030 AlreadyNavigated,
14031 }
14032
14033 let target_task = match definition {
14034 HoverLink::Text(link) => {
14035 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14036 }
14037 HoverLink::InlayHint(lsp_location, server_id) => {
14038 let computation =
14039 self.compute_target_location(lsp_location, server_id, window, cx);
14040 cx.background_spawn(async move {
14041 let location = computation.await?;
14042 Ok(TargetTaskResult::Location(location))
14043 })
14044 }
14045 HoverLink::Url(url) => {
14046 cx.open_url(&url);
14047 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14048 }
14049 HoverLink::File(path) => {
14050 if let Some(workspace) = self.workspace() {
14051 cx.spawn_in(window, async move |_, cx| {
14052 workspace
14053 .update_in(cx, |workspace, window, cx| {
14054 workspace.open_resolved_path(path, window, cx)
14055 })?
14056 .await
14057 .map(|_| TargetTaskResult::AlreadyNavigated)
14058 })
14059 } else {
14060 Task::ready(Ok(TargetTaskResult::Location(None)))
14061 }
14062 }
14063 };
14064 cx.spawn_in(window, async move |editor, cx| {
14065 let target = match target_task.await.context("target resolution task")? {
14066 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14067 TargetTaskResult::Location(None) => return Ok(Navigated::No),
14068 TargetTaskResult::Location(Some(target)) => target,
14069 };
14070
14071 editor.update_in(cx, |editor, window, cx| {
14072 let Some(workspace) = editor.workspace() else {
14073 return Navigated::No;
14074 };
14075 let pane = workspace.read(cx).active_pane().clone();
14076
14077 let range = target.range.to_point(target.buffer.read(cx));
14078 let range = editor.range_for_match(&range);
14079 let range = collapse_multiline_range(range);
14080
14081 if !split
14082 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14083 {
14084 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14085 } else {
14086 window.defer(cx, move |window, cx| {
14087 let target_editor: Entity<Self> =
14088 workspace.update(cx, |workspace, cx| {
14089 let pane = if split {
14090 workspace.adjacent_pane(window, cx)
14091 } else {
14092 workspace.active_pane().clone()
14093 };
14094
14095 workspace.open_project_item(
14096 pane,
14097 target.buffer.clone(),
14098 true,
14099 true,
14100 window,
14101 cx,
14102 )
14103 });
14104 target_editor.update(cx, |target_editor, cx| {
14105 // When selecting a definition in a different buffer, disable the nav history
14106 // to avoid creating a history entry at the previous cursor location.
14107 pane.update(cx, |pane, _| pane.disable_history());
14108 target_editor.go_to_singleton_buffer_range(range, window, cx);
14109 pane.update(cx, |pane, _| pane.enable_history());
14110 });
14111 });
14112 }
14113 Navigated::Yes
14114 })
14115 })
14116 } else if !definitions.is_empty() {
14117 cx.spawn_in(window, async move |editor, cx| {
14118 let (title, location_tasks, workspace) = editor
14119 .update_in(cx, |editor, window, cx| {
14120 let tab_kind = match kind {
14121 Some(GotoDefinitionKind::Implementation) => "Implementations",
14122 _ => "Definitions",
14123 };
14124 let title = definitions
14125 .iter()
14126 .find_map(|definition| match definition {
14127 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14128 let buffer = origin.buffer.read(cx);
14129 format!(
14130 "{} for {}",
14131 tab_kind,
14132 buffer
14133 .text_for_range(origin.range.clone())
14134 .collect::<String>()
14135 )
14136 }),
14137 HoverLink::InlayHint(_, _) => None,
14138 HoverLink::Url(_) => None,
14139 HoverLink::File(_) => None,
14140 })
14141 .unwrap_or(tab_kind.to_string());
14142 let location_tasks = definitions
14143 .into_iter()
14144 .map(|definition| match definition {
14145 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14146 HoverLink::InlayHint(lsp_location, server_id) => editor
14147 .compute_target_location(lsp_location, server_id, window, cx),
14148 HoverLink::Url(_) => Task::ready(Ok(None)),
14149 HoverLink::File(_) => Task::ready(Ok(None)),
14150 })
14151 .collect::<Vec<_>>();
14152 (title, location_tasks, editor.workspace().clone())
14153 })
14154 .context("location tasks preparation")?;
14155
14156 let locations = future::join_all(location_tasks)
14157 .await
14158 .into_iter()
14159 .filter_map(|location| location.transpose())
14160 .collect::<Result<_>>()
14161 .context("location tasks")?;
14162
14163 let Some(workspace) = workspace else {
14164 return Ok(Navigated::No);
14165 };
14166 let opened = workspace
14167 .update_in(cx, |workspace, window, cx| {
14168 Self::open_locations_in_multibuffer(
14169 workspace,
14170 locations,
14171 title,
14172 split,
14173 MultibufferSelectionMode::First,
14174 window,
14175 cx,
14176 )
14177 })
14178 .ok();
14179
14180 anyhow::Ok(Navigated::from_bool(opened.is_some()))
14181 })
14182 } else {
14183 Task::ready(Ok(Navigated::No))
14184 }
14185 }
14186
14187 fn compute_target_location(
14188 &self,
14189 lsp_location: lsp::Location,
14190 server_id: LanguageServerId,
14191 window: &mut Window,
14192 cx: &mut Context<Self>,
14193 ) -> Task<anyhow::Result<Option<Location>>> {
14194 let Some(project) = self.project.clone() else {
14195 return Task::ready(Ok(None));
14196 };
14197
14198 cx.spawn_in(window, async move |editor, cx| {
14199 let location_task = editor.update(cx, |_, cx| {
14200 project.update(cx, |project, cx| {
14201 let language_server_name = project
14202 .language_server_statuses(cx)
14203 .find(|(id, _)| server_id == *id)
14204 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14205 language_server_name.map(|language_server_name| {
14206 project.open_local_buffer_via_lsp(
14207 lsp_location.uri.clone(),
14208 server_id,
14209 language_server_name,
14210 cx,
14211 )
14212 })
14213 })
14214 })?;
14215 let location = match location_task {
14216 Some(task) => Some({
14217 let target_buffer_handle = task.await.context("open local buffer")?;
14218 let range = target_buffer_handle.update(cx, |target_buffer, _| {
14219 let target_start = target_buffer
14220 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14221 let target_end = target_buffer
14222 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14223 target_buffer.anchor_after(target_start)
14224 ..target_buffer.anchor_before(target_end)
14225 })?;
14226 Location {
14227 buffer: target_buffer_handle,
14228 range,
14229 }
14230 }),
14231 None => None,
14232 };
14233 Ok(location)
14234 })
14235 }
14236
14237 pub fn find_all_references(
14238 &mut self,
14239 _: &FindAllReferences,
14240 window: &mut Window,
14241 cx: &mut Context<Self>,
14242 ) -> Option<Task<Result<Navigated>>> {
14243 let selection = self.selections.newest::<usize>(cx);
14244 let multi_buffer = self.buffer.read(cx);
14245 let head = selection.head();
14246
14247 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14248 let head_anchor = multi_buffer_snapshot.anchor_at(
14249 head,
14250 if head < selection.tail() {
14251 Bias::Right
14252 } else {
14253 Bias::Left
14254 },
14255 );
14256
14257 match self
14258 .find_all_references_task_sources
14259 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14260 {
14261 Ok(_) => {
14262 log::info!(
14263 "Ignoring repeated FindAllReferences invocation with the position of already running task"
14264 );
14265 return None;
14266 }
14267 Err(i) => {
14268 self.find_all_references_task_sources.insert(i, head_anchor);
14269 }
14270 }
14271
14272 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14273 let workspace = self.workspace()?;
14274 let project = workspace.read(cx).project().clone();
14275 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14276 Some(cx.spawn_in(window, async move |editor, cx| {
14277 let _cleanup = cx.on_drop(&editor, move |editor, _| {
14278 if let Ok(i) = editor
14279 .find_all_references_task_sources
14280 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14281 {
14282 editor.find_all_references_task_sources.remove(i);
14283 }
14284 });
14285
14286 let locations = references.await?;
14287 if locations.is_empty() {
14288 return anyhow::Ok(Navigated::No);
14289 }
14290
14291 workspace.update_in(cx, |workspace, window, cx| {
14292 let title = locations
14293 .first()
14294 .as_ref()
14295 .map(|location| {
14296 let buffer = location.buffer.read(cx);
14297 format!(
14298 "References to `{}`",
14299 buffer
14300 .text_for_range(location.range.clone())
14301 .collect::<String>()
14302 )
14303 })
14304 .unwrap();
14305 Self::open_locations_in_multibuffer(
14306 workspace,
14307 locations,
14308 title,
14309 false,
14310 MultibufferSelectionMode::First,
14311 window,
14312 cx,
14313 );
14314 Navigated::Yes
14315 })
14316 }))
14317 }
14318
14319 /// Opens a multibuffer with the given project locations in it
14320 pub fn open_locations_in_multibuffer(
14321 workspace: &mut Workspace,
14322 mut locations: Vec<Location>,
14323 title: String,
14324 split: bool,
14325 multibuffer_selection_mode: MultibufferSelectionMode,
14326 window: &mut Window,
14327 cx: &mut Context<Workspace>,
14328 ) {
14329 // If there are multiple definitions, open them in a multibuffer
14330 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14331 let mut locations = locations.into_iter().peekable();
14332 let mut ranges: Vec<Range<Anchor>> = Vec::new();
14333 let capability = workspace.project().read(cx).capability();
14334
14335 let excerpt_buffer = cx.new(|cx| {
14336 let mut multibuffer = MultiBuffer::new(capability);
14337 while let Some(location) = locations.next() {
14338 let buffer = location.buffer.read(cx);
14339 let mut ranges_for_buffer = Vec::new();
14340 let range = location.range.to_point(buffer);
14341 ranges_for_buffer.push(range.clone());
14342
14343 while let Some(next_location) = locations.peek() {
14344 if next_location.buffer == location.buffer {
14345 ranges_for_buffer.push(next_location.range.to_point(buffer));
14346 locations.next();
14347 } else {
14348 break;
14349 }
14350 }
14351
14352 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14353 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14354 PathKey::for_buffer(&location.buffer, cx),
14355 location.buffer.clone(),
14356 ranges_for_buffer,
14357 DEFAULT_MULTIBUFFER_CONTEXT,
14358 cx,
14359 );
14360 ranges.extend(new_ranges)
14361 }
14362
14363 multibuffer.with_title(title)
14364 });
14365
14366 let editor = cx.new(|cx| {
14367 Editor::for_multibuffer(
14368 excerpt_buffer,
14369 Some(workspace.project().clone()),
14370 window,
14371 cx,
14372 )
14373 });
14374 editor.update(cx, |editor, cx| {
14375 match multibuffer_selection_mode {
14376 MultibufferSelectionMode::First => {
14377 if let Some(first_range) = ranges.first() {
14378 editor.change_selections(None, window, cx, |selections| {
14379 selections.clear_disjoint();
14380 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14381 });
14382 }
14383 editor.highlight_background::<Self>(
14384 &ranges,
14385 |theme| theme.editor_highlighted_line_background,
14386 cx,
14387 );
14388 }
14389 MultibufferSelectionMode::All => {
14390 editor.change_selections(None, window, cx, |selections| {
14391 selections.clear_disjoint();
14392 selections.select_anchor_ranges(ranges);
14393 });
14394 }
14395 }
14396 editor.register_buffers_with_language_servers(cx);
14397 });
14398
14399 let item = Box::new(editor);
14400 let item_id = item.item_id();
14401
14402 if split {
14403 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14404 } else {
14405 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14406 let (preview_item_id, preview_item_idx) =
14407 workspace.active_pane().update(cx, |pane, _| {
14408 (pane.preview_item_id(), pane.preview_item_idx())
14409 });
14410
14411 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14412
14413 if let Some(preview_item_id) = preview_item_id {
14414 workspace.active_pane().update(cx, |pane, cx| {
14415 pane.remove_item(preview_item_id, false, false, window, cx);
14416 });
14417 }
14418 } else {
14419 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14420 }
14421 }
14422 workspace.active_pane().update(cx, |pane, cx| {
14423 pane.set_preview_item_id(Some(item_id), cx);
14424 });
14425 }
14426
14427 pub fn rename(
14428 &mut self,
14429 _: &Rename,
14430 window: &mut Window,
14431 cx: &mut Context<Self>,
14432 ) -> Option<Task<Result<()>>> {
14433 use language::ToOffset as _;
14434
14435 let provider = self.semantics_provider.clone()?;
14436 let selection = self.selections.newest_anchor().clone();
14437 let (cursor_buffer, cursor_buffer_position) = self
14438 .buffer
14439 .read(cx)
14440 .text_anchor_for_position(selection.head(), cx)?;
14441 let (tail_buffer, cursor_buffer_position_end) = self
14442 .buffer
14443 .read(cx)
14444 .text_anchor_for_position(selection.tail(), cx)?;
14445 if tail_buffer != cursor_buffer {
14446 return None;
14447 }
14448
14449 let snapshot = cursor_buffer.read(cx).snapshot();
14450 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14451 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14452 let prepare_rename = provider
14453 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14454 .unwrap_or_else(|| Task::ready(Ok(None)));
14455 drop(snapshot);
14456
14457 Some(cx.spawn_in(window, async move |this, cx| {
14458 let rename_range = if let Some(range) = prepare_rename.await? {
14459 Some(range)
14460 } else {
14461 this.update(cx, |this, cx| {
14462 let buffer = this.buffer.read(cx).snapshot(cx);
14463 let mut buffer_highlights = this
14464 .document_highlights_for_position(selection.head(), &buffer)
14465 .filter(|highlight| {
14466 highlight.start.excerpt_id == selection.head().excerpt_id
14467 && highlight.end.excerpt_id == selection.head().excerpt_id
14468 });
14469 buffer_highlights
14470 .next()
14471 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14472 })?
14473 };
14474 if let Some(rename_range) = rename_range {
14475 this.update_in(cx, |this, window, cx| {
14476 let snapshot = cursor_buffer.read(cx).snapshot();
14477 let rename_buffer_range = rename_range.to_offset(&snapshot);
14478 let cursor_offset_in_rename_range =
14479 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14480 let cursor_offset_in_rename_range_end =
14481 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14482
14483 this.take_rename(false, window, cx);
14484 let buffer = this.buffer.read(cx).read(cx);
14485 let cursor_offset = selection.head().to_offset(&buffer);
14486 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14487 let rename_end = rename_start + rename_buffer_range.len();
14488 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14489 let mut old_highlight_id = None;
14490 let old_name: Arc<str> = buffer
14491 .chunks(rename_start..rename_end, true)
14492 .map(|chunk| {
14493 if old_highlight_id.is_none() {
14494 old_highlight_id = chunk.syntax_highlight_id;
14495 }
14496 chunk.text
14497 })
14498 .collect::<String>()
14499 .into();
14500
14501 drop(buffer);
14502
14503 // Position the selection in the rename editor so that it matches the current selection.
14504 this.show_local_selections = false;
14505 let rename_editor = cx.new(|cx| {
14506 let mut editor = Editor::single_line(window, cx);
14507 editor.buffer.update(cx, |buffer, cx| {
14508 buffer.edit([(0..0, old_name.clone())], None, cx)
14509 });
14510 let rename_selection_range = match cursor_offset_in_rename_range
14511 .cmp(&cursor_offset_in_rename_range_end)
14512 {
14513 Ordering::Equal => {
14514 editor.select_all(&SelectAll, window, cx);
14515 return editor;
14516 }
14517 Ordering::Less => {
14518 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14519 }
14520 Ordering::Greater => {
14521 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14522 }
14523 };
14524 if rename_selection_range.end > old_name.len() {
14525 editor.select_all(&SelectAll, window, cx);
14526 } else {
14527 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14528 s.select_ranges([rename_selection_range]);
14529 });
14530 }
14531 editor
14532 });
14533 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14534 if e == &EditorEvent::Focused {
14535 cx.emit(EditorEvent::FocusedIn)
14536 }
14537 })
14538 .detach();
14539
14540 let write_highlights =
14541 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14542 let read_highlights =
14543 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14544 let ranges = write_highlights
14545 .iter()
14546 .flat_map(|(_, ranges)| ranges.iter())
14547 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14548 .cloned()
14549 .collect();
14550
14551 this.highlight_text::<Rename>(
14552 ranges,
14553 HighlightStyle {
14554 fade_out: Some(0.6),
14555 ..Default::default()
14556 },
14557 cx,
14558 );
14559 let rename_focus_handle = rename_editor.focus_handle(cx);
14560 window.focus(&rename_focus_handle);
14561 let block_id = this.insert_blocks(
14562 [BlockProperties {
14563 style: BlockStyle::Flex,
14564 placement: BlockPlacement::Below(range.start),
14565 height: Some(1),
14566 render: Arc::new({
14567 let rename_editor = rename_editor.clone();
14568 move |cx: &mut BlockContext| {
14569 let mut text_style = cx.editor_style.text.clone();
14570 if let Some(highlight_style) = old_highlight_id
14571 .and_then(|h| h.style(&cx.editor_style.syntax))
14572 {
14573 text_style = text_style.highlight(highlight_style);
14574 }
14575 div()
14576 .block_mouse_down()
14577 .pl(cx.anchor_x)
14578 .child(EditorElement::new(
14579 &rename_editor,
14580 EditorStyle {
14581 background: cx.theme().system().transparent,
14582 local_player: cx.editor_style.local_player,
14583 text: text_style,
14584 scrollbar_width: cx.editor_style.scrollbar_width,
14585 syntax: cx.editor_style.syntax.clone(),
14586 status: cx.editor_style.status.clone(),
14587 inlay_hints_style: HighlightStyle {
14588 font_weight: Some(FontWeight::BOLD),
14589 ..make_inlay_hints_style(cx.app)
14590 },
14591 inline_completion_styles: make_suggestion_styles(
14592 cx.app,
14593 ),
14594 ..EditorStyle::default()
14595 },
14596 ))
14597 .into_any_element()
14598 }
14599 }),
14600 priority: 0,
14601 }],
14602 Some(Autoscroll::fit()),
14603 cx,
14604 )[0];
14605 this.pending_rename = Some(RenameState {
14606 range,
14607 old_name,
14608 editor: rename_editor,
14609 block_id,
14610 });
14611 })?;
14612 }
14613
14614 Ok(())
14615 }))
14616 }
14617
14618 pub fn confirm_rename(
14619 &mut self,
14620 _: &ConfirmRename,
14621 window: &mut Window,
14622 cx: &mut Context<Self>,
14623 ) -> Option<Task<Result<()>>> {
14624 let rename = self.take_rename(false, window, cx)?;
14625 let workspace = self.workspace()?.downgrade();
14626 let (buffer, start) = self
14627 .buffer
14628 .read(cx)
14629 .text_anchor_for_position(rename.range.start, cx)?;
14630 let (end_buffer, _) = self
14631 .buffer
14632 .read(cx)
14633 .text_anchor_for_position(rename.range.end, cx)?;
14634 if buffer != end_buffer {
14635 return None;
14636 }
14637
14638 let old_name = rename.old_name;
14639 let new_name = rename.editor.read(cx).text(cx);
14640
14641 let rename = self.semantics_provider.as_ref()?.perform_rename(
14642 &buffer,
14643 start,
14644 new_name.clone(),
14645 cx,
14646 )?;
14647
14648 Some(cx.spawn_in(window, async move |editor, cx| {
14649 let project_transaction = rename.await?;
14650 Self::open_project_transaction(
14651 &editor,
14652 workspace,
14653 project_transaction,
14654 format!("Rename: {} → {}", old_name, new_name),
14655 cx,
14656 )
14657 .await?;
14658
14659 editor.update(cx, |editor, cx| {
14660 editor.refresh_document_highlights(cx);
14661 })?;
14662 Ok(())
14663 }))
14664 }
14665
14666 fn take_rename(
14667 &mut self,
14668 moving_cursor: bool,
14669 window: &mut Window,
14670 cx: &mut Context<Self>,
14671 ) -> Option<RenameState> {
14672 let rename = self.pending_rename.take()?;
14673 if rename.editor.focus_handle(cx).is_focused(window) {
14674 window.focus(&self.focus_handle);
14675 }
14676
14677 self.remove_blocks(
14678 [rename.block_id].into_iter().collect(),
14679 Some(Autoscroll::fit()),
14680 cx,
14681 );
14682 self.clear_highlights::<Rename>(cx);
14683 self.show_local_selections = true;
14684
14685 if moving_cursor {
14686 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14687 editor.selections.newest::<usize>(cx).head()
14688 });
14689
14690 // Update the selection to match the position of the selection inside
14691 // the rename editor.
14692 let snapshot = self.buffer.read(cx).read(cx);
14693 let rename_range = rename.range.to_offset(&snapshot);
14694 let cursor_in_editor = snapshot
14695 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14696 .min(rename_range.end);
14697 drop(snapshot);
14698
14699 self.change_selections(None, window, cx, |s| {
14700 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14701 });
14702 } else {
14703 self.refresh_document_highlights(cx);
14704 }
14705
14706 Some(rename)
14707 }
14708
14709 pub fn pending_rename(&self) -> Option<&RenameState> {
14710 self.pending_rename.as_ref()
14711 }
14712
14713 fn format(
14714 &mut self,
14715 _: &Format,
14716 window: &mut Window,
14717 cx: &mut Context<Self>,
14718 ) -> Option<Task<Result<()>>> {
14719 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14720
14721 let project = match &self.project {
14722 Some(project) => project.clone(),
14723 None => return None,
14724 };
14725
14726 Some(self.perform_format(
14727 project,
14728 FormatTrigger::Manual,
14729 FormatTarget::Buffers,
14730 window,
14731 cx,
14732 ))
14733 }
14734
14735 fn format_selections(
14736 &mut self,
14737 _: &FormatSelections,
14738 window: &mut Window,
14739 cx: &mut Context<Self>,
14740 ) -> Option<Task<Result<()>>> {
14741 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14742
14743 let project = match &self.project {
14744 Some(project) => project.clone(),
14745 None => return None,
14746 };
14747
14748 let ranges = self
14749 .selections
14750 .all_adjusted(cx)
14751 .into_iter()
14752 .map(|selection| selection.range())
14753 .collect_vec();
14754
14755 Some(self.perform_format(
14756 project,
14757 FormatTrigger::Manual,
14758 FormatTarget::Ranges(ranges),
14759 window,
14760 cx,
14761 ))
14762 }
14763
14764 fn perform_format(
14765 &mut self,
14766 project: Entity<Project>,
14767 trigger: FormatTrigger,
14768 target: FormatTarget,
14769 window: &mut Window,
14770 cx: &mut Context<Self>,
14771 ) -> Task<Result<()>> {
14772 let buffer = self.buffer.clone();
14773 let (buffers, target) = match target {
14774 FormatTarget::Buffers => {
14775 let mut buffers = buffer.read(cx).all_buffers();
14776 if trigger == FormatTrigger::Save {
14777 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14778 }
14779 (buffers, LspFormatTarget::Buffers)
14780 }
14781 FormatTarget::Ranges(selection_ranges) => {
14782 let multi_buffer = buffer.read(cx);
14783 let snapshot = multi_buffer.read(cx);
14784 let mut buffers = HashSet::default();
14785 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14786 BTreeMap::new();
14787 for selection_range in selection_ranges {
14788 for (buffer, buffer_range, _) in
14789 snapshot.range_to_buffer_ranges(selection_range)
14790 {
14791 let buffer_id = buffer.remote_id();
14792 let start = buffer.anchor_before(buffer_range.start);
14793 let end = buffer.anchor_after(buffer_range.end);
14794 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14795 buffer_id_to_ranges
14796 .entry(buffer_id)
14797 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14798 .or_insert_with(|| vec![start..end]);
14799 }
14800 }
14801 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14802 }
14803 };
14804
14805 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14806 let selections_prev = transaction_id_prev
14807 .and_then(|transaction_id_prev| {
14808 // default to selections as they were after the last edit, if we have them,
14809 // instead of how they are now.
14810 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14811 // will take you back to where you made the last edit, instead of staying where you scrolled
14812 self.selection_history
14813 .transaction(transaction_id_prev)
14814 .map(|t| t.0.clone())
14815 })
14816 .unwrap_or_else(|| {
14817 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14818 self.selections.disjoint_anchors()
14819 });
14820
14821 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14822 let format = project.update(cx, |project, cx| {
14823 project.format(buffers, target, true, trigger, cx)
14824 });
14825
14826 cx.spawn_in(window, async move |editor, cx| {
14827 let transaction = futures::select_biased! {
14828 transaction = format.log_err().fuse() => transaction,
14829 () = timeout => {
14830 log::warn!("timed out waiting for formatting");
14831 None
14832 }
14833 };
14834
14835 buffer
14836 .update(cx, |buffer, cx| {
14837 if let Some(transaction) = transaction {
14838 if !buffer.is_singleton() {
14839 buffer.push_transaction(&transaction.0, cx);
14840 }
14841 }
14842 cx.notify();
14843 })
14844 .ok();
14845
14846 if let Some(transaction_id_now) =
14847 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14848 {
14849 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14850 if has_new_transaction {
14851 _ = editor.update(cx, |editor, _| {
14852 editor
14853 .selection_history
14854 .insert_transaction(transaction_id_now, selections_prev);
14855 });
14856 }
14857 }
14858
14859 Ok(())
14860 })
14861 }
14862
14863 fn organize_imports(
14864 &mut self,
14865 _: &OrganizeImports,
14866 window: &mut Window,
14867 cx: &mut Context<Self>,
14868 ) -> Option<Task<Result<()>>> {
14869 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14870 let project = match &self.project {
14871 Some(project) => project.clone(),
14872 None => return None,
14873 };
14874 Some(self.perform_code_action_kind(
14875 project,
14876 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14877 window,
14878 cx,
14879 ))
14880 }
14881
14882 fn perform_code_action_kind(
14883 &mut self,
14884 project: Entity<Project>,
14885 kind: CodeActionKind,
14886 window: &mut Window,
14887 cx: &mut Context<Self>,
14888 ) -> Task<Result<()>> {
14889 let buffer = self.buffer.clone();
14890 let buffers = buffer.read(cx).all_buffers();
14891 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14892 let apply_action = project.update(cx, |project, cx| {
14893 project.apply_code_action_kind(buffers, kind, true, cx)
14894 });
14895 cx.spawn_in(window, async move |_, cx| {
14896 let transaction = futures::select_biased! {
14897 () = timeout => {
14898 log::warn!("timed out waiting for executing code action");
14899 None
14900 }
14901 transaction = apply_action.log_err().fuse() => transaction,
14902 };
14903 buffer
14904 .update(cx, |buffer, cx| {
14905 // check if we need this
14906 if let Some(transaction) = transaction {
14907 if !buffer.is_singleton() {
14908 buffer.push_transaction(&transaction.0, cx);
14909 }
14910 }
14911 cx.notify();
14912 })
14913 .ok();
14914 Ok(())
14915 })
14916 }
14917
14918 fn restart_language_server(
14919 &mut self,
14920 _: &RestartLanguageServer,
14921 _: &mut Window,
14922 cx: &mut Context<Self>,
14923 ) {
14924 if let Some(project) = self.project.clone() {
14925 self.buffer.update(cx, |multi_buffer, cx| {
14926 project.update(cx, |project, cx| {
14927 project.restart_language_servers_for_buffers(
14928 multi_buffer.all_buffers().into_iter().collect(),
14929 cx,
14930 );
14931 });
14932 })
14933 }
14934 }
14935
14936 fn stop_language_server(
14937 &mut self,
14938 _: &StopLanguageServer,
14939 _: &mut Window,
14940 cx: &mut Context<Self>,
14941 ) {
14942 if let Some(project) = self.project.clone() {
14943 self.buffer.update(cx, |multi_buffer, cx| {
14944 project.update(cx, |project, cx| {
14945 project.stop_language_servers_for_buffers(
14946 multi_buffer.all_buffers().into_iter().collect(),
14947 cx,
14948 );
14949 cx.emit(project::Event::RefreshInlayHints);
14950 });
14951 });
14952 }
14953 }
14954
14955 fn cancel_language_server_work(
14956 workspace: &mut Workspace,
14957 _: &actions::CancelLanguageServerWork,
14958 _: &mut Window,
14959 cx: &mut Context<Workspace>,
14960 ) {
14961 let project = workspace.project();
14962 let buffers = workspace
14963 .active_item(cx)
14964 .and_then(|item| item.act_as::<Editor>(cx))
14965 .map_or(HashSet::default(), |editor| {
14966 editor.read(cx).buffer.read(cx).all_buffers()
14967 });
14968 project.update(cx, |project, cx| {
14969 project.cancel_language_server_work_for_buffers(buffers, cx);
14970 });
14971 }
14972
14973 fn show_character_palette(
14974 &mut self,
14975 _: &ShowCharacterPalette,
14976 window: &mut Window,
14977 _: &mut Context<Self>,
14978 ) {
14979 window.show_character_palette();
14980 }
14981
14982 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14983 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14984 let buffer = self.buffer.read(cx).snapshot(cx);
14985 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14986 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14987 let is_valid = buffer
14988 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14989 .any(|entry| {
14990 entry.diagnostic.is_primary
14991 && !entry.range.is_empty()
14992 && entry.range.start == primary_range_start
14993 && entry.diagnostic.message == active_diagnostics.active_message
14994 });
14995
14996 if !is_valid {
14997 self.dismiss_diagnostics(cx);
14998 }
14999 }
15000 }
15001
15002 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
15003 match &self.active_diagnostics {
15004 ActiveDiagnostic::Group(group) => Some(group),
15005 _ => None,
15006 }
15007 }
15008
15009 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15010 self.dismiss_diagnostics(cx);
15011 self.active_diagnostics = ActiveDiagnostic::All;
15012 }
15013
15014 fn activate_diagnostics(
15015 &mut self,
15016 buffer_id: BufferId,
15017 diagnostic: DiagnosticEntry<usize>,
15018 window: &mut Window,
15019 cx: &mut Context<Self>,
15020 ) {
15021 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15022 return;
15023 }
15024 self.dismiss_diagnostics(cx);
15025 let snapshot = self.snapshot(window, cx);
15026 let buffer = self.buffer.read(cx).snapshot(cx);
15027 let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15028 return;
15029 };
15030
15031 let diagnostic_group = buffer
15032 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15033 .collect::<Vec<_>>();
15034
15035 let blocks =
15036 renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15037
15038 let blocks = self.display_map.update(cx, |display_map, cx| {
15039 display_map.insert_blocks(blocks, cx).into_iter().collect()
15040 });
15041 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15042 active_range: buffer.anchor_before(diagnostic.range.start)
15043 ..buffer.anchor_after(diagnostic.range.end),
15044 active_message: diagnostic.diagnostic.message.clone(),
15045 group_id: diagnostic.diagnostic.group_id,
15046 blocks,
15047 });
15048 cx.notify();
15049 }
15050
15051 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15052 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15053 return;
15054 };
15055
15056 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15057 if let ActiveDiagnostic::Group(group) = prev {
15058 self.display_map.update(cx, |display_map, cx| {
15059 display_map.remove_blocks(group.blocks, cx);
15060 });
15061 cx.notify();
15062 }
15063 }
15064
15065 /// Disable inline diagnostics rendering for this editor.
15066 pub fn disable_inline_diagnostics(&mut self) {
15067 self.inline_diagnostics_enabled = false;
15068 self.inline_diagnostics_update = Task::ready(());
15069 self.inline_diagnostics.clear();
15070 }
15071
15072 pub fn inline_diagnostics_enabled(&self) -> bool {
15073 self.inline_diagnostics_enabled
15074 }
15075
15076 pub fn show_inline_diagnostics(&self) -> bool {
15077 self.show_inline_diagnostics
15078 }
15079
15080 pub fn toggle_inline_diagnostics(
15081 &mut self,
15082 _: &ToggleInlineDiagnostics,
15083 window: &mut Window,
15084 cx: &mut Context<Editor>,
15085 ) {
15086 self.show_inline_diagnostics = !self.show_inline_diagnostics;
15087 self.refresh_inline_diagnostics(false, window, cx);
15088 }
15089
15090 fn refresh_inline_diagnostics(
15091 &mut self,
15092 debounce: bool,
15093 window: &mut Window,
15094 cx: &mut Context<Self>,
15095 ) {
15096 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15097 self.inline_diagnostics_update = Task::ready(());
15098 self.inline_diagnostics.clear();
15099 return;
15100 }
15101
15102 let debounce_ms = ProjectSettings::get_global(cx)
15103 .diagnostics
15104 .inline
15105 .update_debounce_ms;
15106 let debounce = if debounce && debounce_ms > 0 {
15107 Some(Duration::from_millis(debounce_ms))
15108 } else {
15109 None
15110 };
15111 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15112 let editor = editor.upgrade().unwrap();
15113
15114 if let Some(debounce) = debounce {
15115 cx.background_executor().timer(debounce).await;
15116 }
15117 let Some(snapshot) = editor
15118 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15119 .ok()
15120 else {
15121 return;
15122 };
15123
15124 let new_inline_diagnostics = cx
15125 .background_spawn(async move {
15126 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15127 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15128 let message = diagnostic_entry
15129 .diagnostic
15130 .message
15131 .split_once('\n')
15132 .map(|(line, _)| line)
15133 .map(SharedString::new)
15134 .unwrap_or_else(|| {
15135 SharedString::from(diagnostic_entry.diagnostic.message)
15136 });
15137 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15138 let (Ok(i) | Err(i)) = inline_diagnostics
15139 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15140 inline_diagnostics.insert(
15141 i,
15142 (
15143 start_anchor,
15144 InlineDiagnostic {
15145 message,
15146 group_id: diagnostic_entry.diagnostic.group_id,
15147 start: diagnostic_entry.range.start.to_point(&snapshot),
15148 is_primary: diagnostic_entry.diagnostic.is_primary,
15149 severity: diagnostic_entry.diagnostic.severity,
15150 },
15151 ),
15152 );
15153 }
15154 inline_diagnostics
15155 })
15156 .await;
15157
15158 editor
15159 .update(cx, |editor, cx| {
15160 editor.inline_diagnostics = new_inline_diagnostics;
15161 cx.notify();
15162 })
15163 .ok();
15164 });
15165 }
15166
15167 pub fn set_selections_from_remote(
15168 &mut self,
15169 selections: Vec<Selection<Anchor>>,
15170 pending_selection: Option<Selection<Anchor>>,
15171 window: &mut Window,
15172 cx: &mut Context<Self>,
15173 ) {
15174 let old_cursor_position = self.selections.newest_anchor().head();
15175 self.selections.change_with(cx, |s| {
15176 s.select_anchors(selections);
15177 if let Some(pending_selection) = pending_selection {
15178 s.set_pending(pending_selection, SelectMode::Character);
15179 } else {
15180 s.clear_pending();
15181 }
15182 });
15183 self.selections_did_change(false, &old_cursor_position, true, window, cx);
15184 }
15185
15186 fn push_to_selection_history(&mut self) {
15187 self.selection_history.push(SelectionHistoryEntry {
15188 selections: self.selections.disjoint_anchors(),
15189 select_next_state: self.select_next_state.clone(),
15190 select_prev_state: self.select_prev_state.clone(),
15191 add_selections_state: self.add_selections_state.clone(),
15192 });
15193 }
15194
15195 pub fn transact(
15196 &mut self,
15197 window: &mut Window,
15198 cx: &mut Context<Self>,
15199 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15200 ) -> Option<TransactionId> {
15201 self.start_transaction_at(Instant::now(), window, cx);
15202 update(self, window, cx);
15203 self.end_transaction_at(Instant::now(), cx)
15204 }
15205
15206 pub fn start_transaction_at(
15207 &mut self,
15208 now: Instant,
15209 window: &mut Window,
15210 cx: &mut Context<Self>,
15211 ) {
15212 self.end_selection(window, cx);
15213 if let Some(tx_id) = self
15214 .buffer
15215 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15216 {
15217 self.selection_history
15218 .insert_transaction(tx_id, self.selections.disjoint_anchors());
15219 cx.emit(EditorEvent::TransactionBegun {
15220 transaction_id: tx_id,
15221 })
15222 }
15223 }
15224
15225 pub fn end_transaction_at(
15226 &mut self,
15227 now: Instant,
15228 cx: &mut Context<Self>,
15229 ) -> Option<TransactionId> {
15230 if let Some(transaction_id) = self
15231 .buffer
15232 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15233 {
15234 if let Some((_, end_selections)) =
15235 self.selection_history.transaction_mut(transaction_id)
15236 {
15237 *end_selections = Some(self.selections.disjoint_anchors());
15238 } else {
15239 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15240 }
15241
15242 cx.emit(EditorEvent::Edited { transaction_id });
15243 Some(transaction_id)
15244 } else {
15245 None
15246 }
15247 }
15248
15249 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15250 if self.selection_mark_mode {
15251 self.change_selections(None, window, cx, |s| {
15252 s.move_with(|_, sel| {
15253 sel.collapse_to(sel.head(), SelectionGoal::None);
15254 });
15255 })
15256 }
15257 self.selection_mark_mode = true;
15258 cx.notify();
15259 }
15260
15261 pub fn swap_selection_ends(
15262 &mut self,
15263 _: &actions::SwapSelectionEnds,
15264 window: &mut Window,
15265 cx: &mut Context<Self>,
15266 ) {
15267 self.change_selections(None, window, cx, |s| {
15268 s.move_with(|_, sel| {
15269 if sel.start != sel.end {
15270 sel.reversed = !sel.reversed
15271 }
15272 });
15273 });
15274 self.request_autoscroll(Autoscroll::newest(), cx);
15275 cx.notify();
15276 }
15277
15278 pub fn toggle_fold(
15279 &mut self,
15280 _: &actions::ToggleFold,
15281 window: &mut Window,
15282 cx: &mut Context<Self>,
15283 ) {
15284 if self.is_singleton(cx) {
15285 let selection = self.selections.newest::<Point>(cx);
15286
15287 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15288 let range = if selection.is_empty() {
15289 let point = selection.head().to_display_point(&display_map);
15290 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15291 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15292 .to_point(&display_map);
15293 start..end
15294 } else {
15295 selection.range()
15296 };
15297 if display_map.folds_in_range(range).next().is_some() {
15298 self.unfold_lines(&Default::default(), window, cx)
15299 } else {
15300 self.fold(&Default::default(), window, cx)
15301 }
15302 } else {
15303 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15304 let buffer_ids: HashSet<_> = self
15305 .selections
15306 .disjoint_anchor_ranges()
15307 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15308 .collect();
15309
15310 let should_unfold = buffer_ids
15311 .iter()
15312 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15313
15314 for buffer_id in buffer_ids {
15315 if should_unfold {
15316 self.unfold_buffer(buffer_id, cx);
15317 } else {
15318 self.fold_buffer(buffer_id, cx);
15319 }
15320 }
15321 }
15322 }
15323
15324 pub fn toggle_fold_recursive(
15325 &mut self,
15326 _: &actions::ToggleFoldRecursive,
15327 window: &mut Window,
15328 cx: &mut Context<Self>,
15329 ) {
15330 let selection = self.selections.newest::<Point>(cx);
15331
15332 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15333 let range = if selection.is_empty() {
15334 let point = selection.head().to_display_point(&display_map);
15335 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15336 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15337 .to_point(&display_map);
15338 start..end
15339 } else {
15340 selection.range()
15341 };
15342 if display_map.folds_in_range(range).next().is_some() {
15343 self.unfold_recursive(&Default::default(), window, cx)
15344 } else {
15345 self.fold_recursive(&Default::default(), window, cx)
15346 }
15347 }
15348
15349 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15350 if self.is_singleton(cx) {
15351 let mut to_fold = Vec::new();
15352 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15353 let selections = self.selections.all_adjusted(cx);
15354
15355 for selection in selections {
15356 let range = selection.range().sorted();
15357 let buffer_start_row = range.start.row;
15358
15359 if range.start.row != range.end.row {
15360 let mut found = false;
15361 let mut row = range.start.row;
15362 while row <= range.end.row {
15363 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15364 {
15365 found = true;
15366 row = crease.range().end.row + 1;
15367 to_fold.push(crease);
15368 } else {
15369 row += 1
15370 }
15371 }
15372 if found {
15373 continue;
15374 }
15375 }
15376
15377 for row in (0..=range.start.row).rev() {
15378 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15379 if crease.range().end.row >= buffer_start_row {
15380 to_fold.push(crease);
15381 if row <= range.start.row {
15382 break;
15383 }
15384 }
15385 }
15386 }
15387 }
15388
15389 self.fold_creases(to_fold, true, window, cx);
15390 } else {
15391 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15392 let buffer_ids = self
15393 .selections
15394 .disjoint_anchor_ranges()
15395 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15396 .collect::<HashSet<_>>();
15397 for buffer_id in buffer_ids {
15398 self.fold_buffer(buffer_id, cx);
15399 }
15400 }
15401 }
15402
15403 fn fold_at_level(
15404 &mut self,
15405 fold_at: &FoldAtLevel,
15406 window: &mut Window,
15407 cx: &mut Context<Self>,
15408 ) {
15409 if !self.buffer.read(cx).is_singleton() {
15410 return;
15411 }
15412
15413 let fold_at_level = fold_at.0;
15414 let snapshot = self.buffer.read(cx).snapshot(cx);
15415 let mut to_fold = Vec::new();
15416 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15417
15418 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15419 while start_row < end_row {
15420 match self
15421 .snapshot(window, cx)
15422 .crease_for_buffer_row(MultiBufferRow(start_row))
15423 {
15424 Some(crease) => {
15425 let nested_start_row = crease.range().start.row + 1;
15426 let nested_end_row = crease.range().end.row;
15427
15428 if current_level < fold_at_level {
15429 stack.push((nested_start_row, nested_end_row, current_level + 1));
15430 } else if current_level == fold_at_level {
15431 to_fold.push(crease);
15432 }
15433
15434 start_row = nested_end_row + 1;
15435 }
15436 None => start_row += 1,
15437 }
15438 }
15439 }
15440
15441 self.fold_creases(to_fold, true, window, cx);
15442 }
15443
15444 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15445 if self.buffer.read(cx).is_singleton() {
15446 let mut fold_ranges = Vec::new();
15447 let snapshot = self.buffer.read(cx).snapshot(cx);
15448
15449 for row in 0..snapshot.max_row().0 {
15450 if let Some(foldable_range) = self
15451 .snapshot(window, cx)
15452 .crease_for_buffer_row(MultiBufferRow(row))
15453 {
15454 fold_ranges.push(foldable_range);
15455 }
15456 }
15457
15458 self.fold_creases(fold_ranges, true, window, cx);
15459 } else {
15460 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15461 editor
15462 .update_in(cx, |editor, _, cx| {
15463 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15464 editor.fold_buffer(buffer_id, cx);
15465 }
15466 })
15467 .ok();
15468 });
15469 }
15470 }
15471
15472 pub fn fold_function_bodies(
15473 &mut self,
15474 _: &actions::FoldFunctionBodies,
15475 window: &mut Window,
15476 cx: &mut Context<Self>,
15477 ) {
15478 let snapshot = self.buffer.read(cx).snapshot(cx);
15479
15480 let ranges = snapshot
15481 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15482 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15483 .collect::<Vec<_>>();
15484
15485 let creases = ranges
15486 .into_iter()
15487 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15488 .collect();
15489
15490 self.fold_creases(creases, true, window, cx);
15491 }
15492
15493 pub fn fold_recursive(
15494 &mut self,
15495 _: &actions::FoldRecursive,
15496 window: &mut Window,
15497 cx: &mut Context<Self>,
15498 ) {
15499 let mut to_fold = Vec::new();
15500 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15501 let selections = self.selections.all_adjusted(cx);
15502
15503 for selection in selections {
15504 let range = selection.range().sorted();
15505 let buffer_start_row = range.start.row;
15506
15507 if range.start.row != range.end.row {
15508 let mut found = false;
15509 for row in range.start.row..=range.end.row {
15510 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15511 found = true;
15512 to_fold.push(crease);
15513 }
15514 }
15515 if found {
15516 continue;
15517 }
15518 }
15519
15520 for row in (0..=range.start.row).rev() {
15521 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15522 if crease.range().end.row >= buffer_start_row {
15523 to_fold.push(crease);
15524 } else {
15525 break;
15526 }
15527 }
15528 }
15529 }
15530
15531 self.fold_creases(to_fold, true, window, cx);
15532 }
15533
15534 pub fn fold_at(
15535 &mut self,
15536 buffer_row: MultiBufferRow,
15537 window: &mut Window,
15538 cx: &mut Context<Self>,
15539 ) {
15540 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15541
15542 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15543 let autoscroll = self
15544 .selections
15545 .all::<Point>(cx)
15546 .iter()
15547 .any(|selection| crease.range().overlaps(&selection.range()));
15548
15549 self.fold_creases(vec![crease], autoscroll, window, cx);
15550 }
15551 }
15552
15553 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15554 if self.is_singleton(cx) {
15555 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15556 let buffer = &display_map.buffer_snapshot;
15557 let selections = self.selections.all::<Point>(cx);
15558 let ranges = selections
15559 .iter()
15560 .map(|s| {
15561 let range = s.display_range(&display_map).sorted();
15562 let mut start = range.start.to_point(&display_map);
15563 let mut end = range.end.to_point(&display_map);
15564 start.column = 0;
15565 end.column = buffer.line_len(MultiBufferRow(end.row));
15566 start..end
15567 })
15568 .collect::<Vec<_>>();
15569
15570 self.unfold_ranges(&ranges, true, true, cx);
15571 } else {
15572 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15573 let buffer_ids = self
15574 .selections
15575 .disjoint_anchor_ranges()
15576 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15577 .collect::<HashSet<_>>();
15578 for buffer_id in buffer_ids {
15579 self.unfold_buffer(buffer_id, cx);
15580 }
15581 }
15582 }
15583
15584 pub fn unfold_recursive(
15585 &mut self,
15586 _: &UnfoldRecursive,
15587 _window: &mut Window,
15588 cx: &mut Context<Self>,
15589 ) {
15590 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15591 let selections = self.selections.all::<Point>(cx);
15592 let ranges = selections
15593 .iter()
15594 .map(|s| {
15595 let mut range = s.display_range(&display_map).sorted();
15596 *range.start.column_mut() = 0;
15597 *range.end.column_mut() = display_map.line_len(range.end.row());
15598 let start = range.start.to_point(&display_map);
15599 let end = range.end.to_point(&display_map);
15600 start..end
15601 })
15602 .collect::<Vec<_>>();
15603
15604 self.unfold_ranges(&ranges, true, true, cx);
15605 }
15606
15607 pub fn unfold_at(
15608 &mut self,
15609 buffer_row: MultiBufferRow,
15610 _window: &mut Window,
15611 cx: &mut Context<Self>,
15612 ) {
15613 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15614
15615 let intersection_range = Point::new(buffer_row.0, 0)
15616 ..Point::new(
15617 buffer_row.0,
15618 display_map.buffer_snapshot.line_len(buffer_row),
15619 );
15620
15621 let autoscroll = self
15622 .selections
15623 .all::<Point>(cx)
15624 .iter()
15625 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15626
15627 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15628 }
15629
15630 pub fn unfold_all(
15631 &mut self,
15632 _: &actions::UnfoldAll,
15633 _window: &mut Window,
15634 cx: &mut Context<Self>,
15635 ) {
15636 if self.buffer.read(cx).is_singleton() {
15637 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15638 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15639 } else {
15640 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15641 editor
15642 .update(cx, |editor, cx| {
15643 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15644 editor.unfold_buffer(buffer_id, cx);
15645 }
15646 })
15647 .ok();
15648 });
15649 }
15650 }
15651
15652 pub fn fold_selected_ranges(
15653 &mut self,
15654 _: &FoldSelectedRanges,
15655 window: &mut Window,
15656 cx: &mut Context<Self>,
15657 ) {
15658 let selections = self.selections.all_adjusted(cx);
15659 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15660 let ranges = selections
15661 .into_iter()
15662 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15663 .collect::<Vec<_>>();
15664 self.fold_creases(ranges, true, window, cx);
15665 }
15666
15667 pub fn fold_ranges<T: ToOffset + Clone>(
15668 &mut self,
15669 ranges: Vec<Range<T>>,
15670 auto_scroll: bool,
15671 window: &mut Window,
15672 cx: &mut Context<Self>,
15673 ) {
15674 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15675 let ranges = ranges
15676 .into_iter()
15677 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15678 .collect::<Vec<_>>();
15679 self.fold_creases(ranges, auto_scroll, window, cx);
15680 }
15681
15682 pub fn fold_creases<T: ToOffset + Clone>(
15683 &mut self,
15684 creases: Vec<Crease<T>>,
15685 auto_scroll: bool,
15686 _window: &mut Window,
15687 cx: &mut Context<Self>,
15688 ) {
15689 if creases.is_empty() {
15690 return;
15691 }
15692
15693 let mut buffers_affected = HashSet::default();
15694 let multi_buffer = self.buffer().read(cx);
15695 for crease in &creases {
15696 if let Some((_, buffer, _)) =
15697 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15698 {
15699 buffers_affected.insert(buffer.read(cx).remote_id());
15700 };
15701 }
15702
15703 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15704
15705 if auto_scroll {
15706 self.request_autoscroll(Autoscroll::fit(), cx);
15707 }
15708
15709 cx.notify();
15710
15711 self.scrollbar_marker_state.dirty = true;
15712 self.folds_did_change(cx);
15713 }
15714
15715 /// Removes any folds whose ranges intersect any of the given ranges.
15716 pub fn unfold_ranges<T: ToOffset + Clone>(
15717 &mut self,
15718 ranges: &[Range<T>],
15719 inclusive: bool,
15720 auto_scroll: bool,
15721 cx: &mut Context<Self>,
15722 ) {
15723 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15724 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15725 });
15726 self.folds_did_change(cx);
15727 }
15728
15729 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15730 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15731 return;
15732 }
15733 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15734 self.display_map.update(cx, |display_map, cx| {
15735 display_map.fold_buffers([buffer_id], cx)
15736 });
15737 cx.emit(EditorEvent::BufferFoldToggled {
15738 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15739 folded: true,
15740 });
15741 cx.notify();
15742 }
15743
15744 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15745 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15746 return;
15747 }
15748 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15749 self.display_map.update(cx, |display_map, cx| {
15750 display_map.unfold_buffers([buffer_id], cx);
15751 });
15752 cx.emit(EditorEvent::BufferFoldToggled {
15753 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15754 folded: false,
15755 });
15756 cx.notify();
15757 }
15758
15759 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15760 self.display_map.read(cx).is_buffer_folded(buffer)
15761 }
15762
15763 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15764 self.display_map.read(cx).folded_buffers()
15765 }
15766
15767 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15768 self.display_map.update(cx, |display_map, cx| {
15769 display_map.disable_header_for_buffer(buffer_id, cx);
15770 });
15771 cx.notify();
15772 }
15773
15774 /// Removes any folds with the given ranges.
15775 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15776 &mut self,
15777 ranges: &[Range<T>],
15778 type_id: TypeId,
15779 auto_scroll: bool,
15780 cx: &mut Context<Self>,
15781 ) {
15782 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15783 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15784 });
15785 self.folds_did_change(cx);
15786 }
15787
15788 fn remove_folds_with<T: ToOffset + Clone>(
15789 &mut self,
15790 ranges: &[Range<T>],
15791 auto_scroll: bool,
15792 cx: &mut Context<Self>,
15793 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15794 ) {
15795 if ranges.is_empty() {
15796 return;
15797 }
15798
15799 let mut buffers_affected = HashSet::default();
15800 let multi_buffer = self.buffer().read(cx);
15801 for range in ranges {
15802 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15803 buffers_affected.insert(buffer.read(cx).remote_id());
15804 };
15805 }
15806
15807 self.display_map.update(cx, update);
15808
15809 if auto_scroll {
15810 self.request_autoscroll(Autoscroll::fit(), cx);
15811 }
15812
15813 cx.notify();
15814 self.scrollbar_marker_state.dirty = true;
15815 self.active_indent_guides_state.dirty = true;
15816 }
15817
15818 pub fn update_fold_widths(
15819 &mut self,
15820 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15821 cx: &mut Context<Self>,
15822 ) -> bool {
15823 self.display_map
15824 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15825 }
15826
15827 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15828 self.display_map.read(cx).fold_placeholder.clone()
15829 }
15830
15831 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15832 self.buffer.update(cx, |buffer, cx| {
15833 buffer.set_all_diff_hunks_expanded(cx);
15834 });
15835 }
15836
15837 pub fn expand_all_diff_hunks(
15838 &mut self,
15839 _: &ExpandAllDiffHunks,
15840 _window: &mut Window,
15841 cx: &mut Context<Self>,
15842 ) {
15843 self.buffer.update(cx, |buffer, cx| {
15844 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15845 });
15846 }
15847
15848 pub fn toggle_selected_diff_hunks(
15849 &mut self,
15850 _: &ToggleSelectedDiffHunks,
15851 _window: &mut Window,
15852 cx: &mut Context<Self>,
15853 ) {
15854 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15855 self.toggle_diff_hunks_in_ranges(ranges, cx);
15856 }
15857
15858 pub fn diff_hunks_in_ranges<'a>(
15859 &'a self,
15860 ranges: &'a [Range<Anchor>],
15861 buffer: &'a MultiBufferSnapshot,
15862 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15863 ranges.iter().flat_map(move |range| {
15864 let end_excerpt_id = range.end.excerpt_id;
15865 let range = range.to_point(buffer);
15866 let mut peek_end = range.end;
15867 if range.end.row < buffer.max_row().0 {
15868 peek_end = Point::new(range.end.row + 1, 0);
15869 }
15870 buffer
15871 .diff_hunks_in_range(range.start..peek_end)
15872 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15873 })
15874 }
15875
15876 pub fn has_stageable_diff_hunks_in_ranges(
15877 &self,
15878 ranges: &[Range<Anchor>],
15879 snapshot: &MultiBufferSnapshot,
15880 ) -> bool {
15881 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15882 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15883 }
15884
15885 pub fn toggle_staged_selected_diff_hunks(
15886 &mut self,
15887 _: &::git::ToggleStaged,
15888 _: &mut Window,
15889 cx: &mut Context<Self>,
15890 ) {
15891 let snapshot = self.buffer.read(cx).snapshot(cx);
15892 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15893 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15894 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15895 }
15896
15897 pub fn set_render_diff_hunk_controls(
15898 &mut self,
15899 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15900 cx: &mut Context<Self>,
15901 ) {
15902 self.render_diff_hunk_controls = render_diff_hunk_controls;
15903 cx.notify();
15904 }
15905
15906 pub fn stage_and_next(
15907 &mut self,
15908 _: &::git::StageAndNext,
15909 window: &mut Window,
15910 cx: &mut Context<Self>,
15911 ) {
15912 self.do_stage_or_unstage_and_next(true, window, cx);
15913 }
15914
15915 pub fn unstage_and_next(
15916 &mut self,
15917 _: &::git::UnstageAndNext,
15918 window: &mut Window,
15919 cx: &mut Context<Self>,
15920 ) {
15921 self.do_stage_or_unstage_and_next(false, window, cx);
15922 }
15923
15924 pub fn stage_or_unstage_diff_hunks(
15925 &mut self,
15926 stage: bool,
15927 ranges: Vec<Range<Anchor>>,
15928 cx: &mut Context<Self>,
15929 ) {
15930 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15931 cx.spawn(async move |this, cx| {
15932 task.await?;
15933 this.update(cx, |this, cx| {
15934 let snapshot = this.buffer.read(cx).snapshot(cx);
15935 let chunk_by = this
15936 .diff_hunks_in_ranges(&ranges, &snapshot)
15937 .chunk_by(|hunk| hunk.buffer_id);
15938 for (buffer_id, hunks) in &chunk_by {
15939 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15940 }
15941 })
15942 })
15943 .detach_and_log_err(cx);
15944 }
15945
15946 fn save_buffers_for_ranges_if_needed(
15947 &mut self,
15948 ranges: &[Range<Anchor>],
15949 cx: &mut Context<Editor>,
15950 ) -> Task<Result<()>> {
15951 let multibuffer = self.buffer.read(cx);
15952 let snapshot = multibuffer.read(cx);
15953 let buffer_ids: HashSet<_> = ranges
15954 .iter()
15955 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15956 .collect();
15957 drop(snapshot);
15958
15959 let mut buffers = HashSet::default();
15960 for buffer_id in buffer_ids {
15961 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15962 let buffer = buffer_entity.read(cx);
15963 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15964 {
15965 buffers.insert(buffer_entity);
15966 }
15967 }
15968 }
15969
15970 if let Some(project) = &self.project {
15971 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15972 } else {
15973 Task::ready(Ok(()))
15974 }
15975 }
15976
15977 fn do_stage_or_unstage_and_next(
15978 &mut self,
15979 stage: bool,
15980 window: &mut Window,
15981 cx: &mut Context<Self>,
15982 ) {
15983 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15984
15985 if ranges.iter().any(|range| range.start != range.end) {
15986 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15987 return;
15988 }
15989
15990 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15991 let snapshot = self.snapshot(window, cx);
15992 let position = self.selections.newest::<Point>(cx).head();
15993 let mut row = snapshot
15994 .buffer_snapshot
15995 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15996 .find(|hunk| hunk.row_range.start.0 > position.row)
15997 .map(|hunk| hunk.row_range.start);
15998
15999 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
16000 // Outside of the project diff editor, wrap around to the beginning.
16001 if !all_diff_hunks_expanded {
16002 row = row.or_else(|| {
16003 snapshot
16004 .buffer_snapshot
16005 .diff_hunks_in_range(Point::zero()..position)
16006 .find(|hunk| hunk.row_range.end.0 < position.row)
16007 .map(|hunk| hunk.row_range.start)
16008 });
16009 }
16010
16011 if let Some(row) = row {
16012 let destination = Point::new(row.0, 0);
16013 let autoscroll = Autoscroll::center();
16014
16015 self.unfold_ranges(&[destination..destination], false, false, cx);
16016 self.change_selections(Some(autoscroll), window, cx, |s| {
16017 s.select_ranges([destination..destination]);
16018 });
16019 }
16020 }
16021
16022 fn do_stage_or_unstage(
16023 &self,
16024 stage: bool,
16025 buffer_id: BufferId,
16026 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16027 cx: &mut App,
16028 ) -> Option<()> {
16029 let project = self.project.as_ref()?;
16030 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16031 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16032 let buffer_snapshot = buffer.read(cx).snapshot();
16033 let file_exists = buffer_snapshot
16034 .file()
16035 .is_some_and(|file| file.disk_state().exists());
16036 diff.update(cx, |diff, cx| {
16037 diff.stage_or_unstage_hunks(
16038 stage,
16039 &hunks
16040 .map(|hunk| buffer_diff::DiffHunk {
16041 buffer_range: hunk.buffer_range,
16042 diff_base_byte_range: hunk.diff_base_byte_range,
16043 secondary_status: hunk.secondary_status,
16044 range: Point::zero()..Point::zero(), // unused
16045 })
16046 .collect::<Vec<_>>(),
16047 &buffer_snapshot,
16048 file_exists,
16049 cx,
16050 )
16051 });
16052 None
16053 }
16054
16055 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16056 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16057 self.buffer
16058 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16059 }
16060
16061 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16062 self.buffer.update(cx, |buffer, cx| {
16063 let ranges = vec![Anchor::min()..Anchor::max()];
16064 if !buffer.all_diff_hunks_expanded()
16065 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16066 {
16067 buffer.collapse_diff_hunks(ranges, cx);
16068 true
16069 } else {
16070 false
16071 }
16072 })
16073 }
16074
16075 fn toggle_diff_hunks_in_ranges(
16076 &mut self,
16077 ranges: Vec<Range<Anchor>>,
16078 cx: &mut Context<Editor>,
16079 ) {
16080 self.buffer.update(cx, |buffer, cx| {
16081 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16082 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16083 })
16084 }
16085
16086 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16087 self.buffer.update(cx, |buffer, cx| {
16088 let snapshot = buffer.snapshot(cx);
16089 let excerpt_id = range.end.excerpt_id;
16090 let point_range = range.to_point(&snapshot);
16091 let expand = !buffer.single_hunk_is_expanded(range, cx);
16092 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16093 })
16094 }
16095
16096 pub(crate) fn apply_all_diff_hunks(
16097 &mut self,
16098 _: &ApplyAllDiffHunks,
16099 window: &mut Window,
16100 cx: &mut Context<Self>,
16101 ) {
16102 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16103
16104 let buffers = self.buffer.read(cx).all_buffers();
16105 for branch_buffer in buffers {
16106 branch_buffer.update(cx, |branch_buffer, cx| {
16107 branch_buffer.merge_into_base(Vec::new(), cx);
16108 });
16109 }
16110
16111 if let Some(project) = self.project.clone() {
16112 self.save(true, project, window, cx).detach_and_log_err(cx);
16113 }
16114 }
16115
16116 pub(crate) fn apply_selected_diff_hunks(
16117 &mut self,
16118 _: &ApplyDiffHunk,
16119 window: &mut Window,
16120 cx: &mut Context<Self>,
16121 ) {
16122 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16123 let snapshot = self.snapshot(window, cx);
16124 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16125 let mut ranges_by_buffer = HashMap::default();
16126 self.transact(window, cx, |editor, _window, cx| {
16127 for hunk in hunks {
16128 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16129 ranges_by_buffer
16130 .entry(buffer.clone())
16131 .or_insert_with(Vec::new)
16132 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16133 }
16134 }
16135
16136 for (buffer, ranges) in ranges_by_buffer {
16137 buffer.update(cx, |buffer, cx| {
16138 buffer.merge_into_base(ranges, cx);
16139 });
16140 }
16141 });
16142
16143 if let Some(project) = self.project.clone() {
16144 self.save(true, project, window, cx).detach_and_log_err(cx);
16145 }
16146 }
16147
16148 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16149 if hovered != self.gutter_hovered {
16150 self.gutter_hovered = hovered;
16151 cx.notify();
16152 }
16153 }
16154
16155 pub fn insert_blocks(
16156 &mut self,
16157 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16158 autoscroll: Option<Autoscroll>,
16159 cx: &mut Context<Self>,
16160 ) -> Vec<CustomBlockId> {
16161 let blocks = self
16162 .display_map
16163 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16164 if let Some(autoscroll) = autoscroll {
16165 self.request_autoscroll(autoscroll, cx);
16166 }
16167 cx.notify();
16168 blocks
16169 }
16170
16171 pub fn resize_blocks(
16172 &mut self,
16173 heights: HashMap<CustomBlockId, u32>,
16174 autoscroll: Option<Autoscroll>,
16175 cx: &mut Context<Self>,
16176 ) {
16177 self.display_map
16178 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16179 if let Some(autoscroll) = autoscroll {
16180 self.request_autoscroll(autoscroll, cx);
16181 }
16182 cx.notify();
16183 }
16184
16185 pub fn replace_blocks(
16186 &mut self,
16187 renderers: HashMap<CustomBlockId, RenderBlock>,
16188 autoscroll: Option<Autoscroll>,
16189 cx: &mut Context<Self>,
16190 ) {
16191 self.display_map
16192 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16193 if let Some(autoscroll) = autoscroll {
16194 self.request_autoscroll(autoscroll, cx);
16195 }
16196 cx.notify();
16197 }
16198
16199 pub fn remove_blocks(
16200 &mut self,
16201 block_ids: HashSet<CustomBlockId>,
16202 autoscroll: Option<Autoscroll>,
16203 cx: &mut Context<Self>,
16204 ) {
16205 self.display_map.update(cx, |display_map, cx| {
16206 display_map.remove_blocks(block_ids, cx)
16207 });
16208 if let Some(autoscroll) = autoscroll {
16209 self.request_autoscroll(autoscroll, cx);
16210 }
16211 cx.notify();
16212 }
16213
16214 pub fn row_for_block(
16215 &self,
16216 block_id: CustomBlockId,
16217 cx: &mut Context<Self>,
16218 ) -> Option<DisplayRow> {
16219 self.display_map
16220 .update(cx, |map, cx| map.row_for_block(block_id, cx))
16221 }
16222
16223 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16224 self.focused_block = Some(focused_block);
16225 }
16226
16227 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16228 self.focused_block.take()
16229 }
16230
16231 pub fn insert_creases(
16232 &mut self,
16233 creases: impl IntoIterator<Item = Crease<Anchor>>,
16234 cx: &mut Context<Self>,
16235 ) -> Vec<CreaseId> {
16236 self.display_map
16237 .update(cx, |map, cx| map.insert_creases(creases, cx))
16238 }
16239
16240 pub fn remove_creases(
16241 &mut self,
16242 ids: impl IntoIterator<Item = CreaseId>,
16243 cx: &mut Context<Self>,
16244 ) {
16245 self.display_map
16246 .update(cx, |map, cx| map.remove_creases(ids, cx));
16247 }
16248
16249 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16250 self.display_map
16251 .update(cx, |map, cx| map.snapshot(cx))
16252 .longest_row()
16253 }
16254
16255 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16256 self.display_map
16257 .update(cx, |map, cx| map.snapshot(cx))
16258 .max_point()
16259 }
16260
16261 pub fn text(&self, cx: &App) -> String {
16262 self.buffer.read(cx).read(cx).text()
16263 }
16264
16265 pub fn is_empty(&self, cx: &App) -> bool {
16266 self.buffer.read(cx).read(cx).is_empty()
16267 }
16268
16269 pub fn text_option(&self, cx: &App) -> Option<String> {
16270 let text = self.text(cx);
16271 let text = text.trim();
16272
16273 if text.is_empty() {
16274 return None;
16275 }
16276
16277 Some(text.to_string())
16278 }
16279
16280 pub fn set_text(
16281 &mut self,
16282 text: impl Into<Arc<str>>,
16283 window: &mut Window,
16284 cx: &mut Context<Self>,
16285 ) {
16286 self.transact(window, cx, |this, _, cx| {
16287 this.buffer
16288 .read(cx)
16289 .as_singleton()
16290 .expect("you can only call set_text on editors for singleton buffers")
16291 .update(cx, |buffer, cx| buffer.set_text(text, cx));
16292 });
16293 }
16294
16295 pub fn display_text(&self, cx: &mut App) -> String {
16296 self.display_map
16297 .update(cx, |map, cx| map.snapshot(cx))
16298 .text()
16299 }
16300
16301 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16302 let mut wrap_guides = smallvec::smallvec![];
16303
16304 if self.show_wrap_guides == Some(false) {
16305 return wrap_guides;
16306 }
16307
16308 let settings = self.buffer.read(cx).language_settings(cx);
16309 if settings.show_wrap_guides {
16310 match self.soft_wrap_mode(cx) {
16311 SoftWrap::Column(soft_wrap) => {
16312 wrap_guides.push((soft_wrap as usize, true));
16313 }
16314 SoftWrap::Bounded(soft_wrap) => {
16315 wrap_guides.push((soft_wrap as usize, true));
16316 }
16317 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16318 }
16319 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16320 }
16321
16322 wrap_guides
16323 }
16324
16325 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16326 let settings = self.buffer.read(cx).language_settings(cx);
16327 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16328 match mode {
16329 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16330 SoftWrap::None
16331 }
16332 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16333 language_settings::SoftWrap::PreferredLineLength => {
16334 SoftWrap::Column(settings.preferred_line_length)
16335 }
16336 language_settings::SoftWrap::Bounded => {
16337 SoftWrap::Bounded(settings.preferred_line_length)
16338 }
16339 }
16340 }
16341
16342 pub fn set_soft_wrap_mode(
16343 &mut self,
16344 mode: language_settings::SoftWrap,
16345
16346 cx: &mut Context<Self>,
16347 ) {
16348 self.soft_wrap_mode_override = Some(mode);
16349 cx.notify();
16350 }
16351
16352 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16353 self.hard_wrap = hard_wrap;
16354 cx.notify();
16355 }
16356
16357 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16358 self.text_style_refinement = Some(style);
16359 }
16360
16361 /// called by the Element so we know what style we were most recently rendered with.
16362 pub(crate) fn set_style(
16363 &mut self,
16364 style: EditorStyle,
16365 window: &mut Window,
16366 cx: &mut Context<Self>,
16367 ) {
16368 let rem_size = window.rem_size();
16369 self.display_map.update(cx, |map, cx| {
16370 map.set_font(
16371 style.text.font(),
16372 style.text.font_size.to_pixels(rem_size),
16373 cx,
16374 )
16375 });
16376 self.style = Some(style);
16377 }
16378
16379 pub fn style(&self) -> Option<&EditorStyle> {
16380 self.style.as_ref()
16381 }
16382
16383 // Called by the element. This method is not designed to be called outside of the editor
16384 // element's layout code because it does not notify when rewrapping is computed synchronously.
16385 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16386 self.display_map
16387 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16388 }
16389
16390 pub fn set_soft_wrap(&mut self) {
16391 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16392 }
16393
16394 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16395 if self.soft_wrap_mode_override.is_some() {
16396 self.soft_wrap_mode_override.take();
16397 } else {
16398 let soft_wrap = match self.soft_wrap_mode(cx) {
16399 SoftWrap::GitDiff => return,
16400 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16401 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16402 language_settings::SoftWrap::None
16403 }
16404 };
16405 self.soft_wrap_mode_override = Some(soft_wrap);
16406 }
16407 cx.notify();
16408 }
16409
16410 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16411 let Some(workspace) = self.workspace() else {
16412 return;
16413 };
16414 let fs = workspace.read(cx).app_state().fs.clone();
16415 let current_show = TabBarSettings::get_global(cx).show;
16416 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16417 setting.show = Some(!current_show);
16418 });
16419 }
16420
16421 pub fn toggle_indent_guides(
16422 &mut self,
16423 _: &ToggleIndentGuides,
16424 _: &mut Window,
16425 cx: &mut Context<Self>,
16426 ) {
16427 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16428 self.buffer
16429 .read(cx)
16430 .language_settings(cx)
16431 .indent_guides
16432 .enabled
16433 });
16434 self.show_indent_guides = Some(!currently_enabled);
16435 cx.notify();
16436 }
16437
16438 fn should_show_indent_guides(&self) -> Option<bool> {
16439 self.show_indent_guides
16440 }
16441
16442 pub fn toggle_line_numbers(
16443 &mut self,
16444 _: &ToggleLineNumbers,
16445 _: &mut Window,
16446 cx: &mut Context<Self>,
16447 ) {
16448 let mut editor_settings = EditorSettings::get_global(cx).clone();
16449 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16450 EditorSettings::override_global(editor_settings, cx);
16451 }
16452
16453 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16454 if let Some(show_line_numbers) = self.show_line_numbers {
16455 return show_line_numbers;
16456 }
16457 EditorSettings::get_global(cx).gutter.line_numbers
16458 }
16459
16460 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16461 self.use_relative_line_numbers
16462 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16463 }
16464
16465 pub fn toggle_relative_line_numbers(
16466 &mut self,
16467 _: &ToggleRelativeLineNumbers,
16468 _: &mut Window,
16469 cx: &mut Context<Self>,
16470 ) {
16471 let is_relative = self.should_use_relative_line_numbers(cx);
16472 self.set_relative_line_number(Some(!is_relative), cx)
16473 }
16474
16475 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16476 self.use_relative_line_numbers = is_relative;
16477 cx.notify();
16478 }
16479
16480 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16481 self.show_gutter = show_gutter;
16482 cx.notify();
16483 }
16484
16485 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16486 self.show_scrollbars = show_scrollbars;
16487 cx.notify();
16488 }
16489
16490 pub fn disable_scrolling(&mut self, cx: &mut Context<Self>) {
16491 self.disable_scrolling = true;
16492 cx.notify();
16493 }
16494
16495 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16496 self.show_line_numbers = Some(show_line_numbers);
16497 cx.notify();
16498 }
16499
16500 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16501 self.disable_expand_excerpt_buttons = true;
16502 cx.notify();
16503 }
16504
16505 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16506 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16507 cx.notify();
16508 }
16509
16510 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16511 self.show_code_actions = Some(show_code_actions);
16512 cx.notify();
16513 }
16514
16515 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16516 self.show_runnables = Some(show_runnables);
16517 cx.notify();
16518 }
16519
16520 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16521 self.show_breakpoints = Some(show_breakpoints);
16522 cx.notify();
16523 }
16524
16525 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16526 if self.display_map.read(cx).masked != masked {
16527 self.display_map.update(cx, |map, _| map.masked = masked);
16528 }
16529 cx.notify()
16530 }
16531
16532 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16533 self.show_wrap_guides = Some(show_wrap_guides);
16534 cx.notify();
16535 }
16536
16537 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16538 self.show_indent_guides = Some(show_indent_guides);
16539 cx.notify();
16540 }
16541
16542 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16543 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16544 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16545 if let Some(dir) = file.abs_path(cx).parent() {
16546 return Some(dir.to_owned());
16547 }
16548 }
16549
16550 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16551 return Some(project_path.path.to_path_buf());
16552 }
16553 }
16554
16555 None
16556 }
16557
16558 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16559 self.active_excerpt(cx)?
16560 .1
16561 .read(cx)
16562 .file()
16563 .and_then(|f| f.as_local())
16564 }
16565
16566 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16567 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16568 let buffer = buffer.read(cx);
16569 if let Some(project_path) = buffer.project_path(cx) {
16570 let project = self.project.as_ref()?.read(cx);
16571 project.absolute_path(&project_path, cx)
16572 } else {
16573 buffer
16574 .file()
16575 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16576 }
16577 })
16578 }
16579
16580 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16581 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16582 let project_path = buffer.read(cx).project_path(cx)?;
16583 let project = self.project.as_ref()?.read(cx);
16584 let entry = project.entry_for_path(&project_path, cx)?;
16585 let path = entry.path.to_path_buf();
16586 Some(path)
16587 })
16588 }
16589
16590 pub fn reveal_in_finder(
16591 &mut self,
16592 _: &RevealInFileManager,
16593 _window: &mut Window,
16594 cx: &mut Context<Self>,
16595 ) {
16596 if let Some(target) = self.target_file(cx) {
16597 cx.reveal_path(&target.abs_path(cx));
16598 }
16599 }
16600
16601 pub fn copy_path(
16602 &mut self,
16603 _: &zed_actions::workspace::CopyPath,
16604 _window: &mut Window,
16605 cx: &mut Context<Self>,
16606 ) {
16607 if let Some(path) = self.target_file_abs_path(cx) {
16608 if let Some(path) = path.to_str() {
16609 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16610 }
16611 }
16612 }
16613
16614 pub fn copy_relative_path(
16615 &mut self,
16616 _: &zed_actions::workspace::CopyRelativePath,
16617 _window: &mut Window,
16618 cx: &mut Context<Self>,
16619 ) {
16620 if let Some(path) = self.target_file_path(cx) {
16621 if let Some(path) = path.to_str() {
16622 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16623 }
16624 }
16625 }
16626
16627 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16628 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16629 buffer.read(cx).project_path(cx)
16630 } else {
16631 None
16632 }
16633 }
16634
16635 // Returns true if the editor handled a go-to-line request
16636 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16637 maybe!({
16638 let breakpoint_store = self.breakpoint_store.as_ref()?;
16639
16640 let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16641 else {
16642 self.clear_row_highlights::<ActiveDebugLine>();
16643 return None;
16644 };
16645
16646 let position = active_stack_frame.position;
16647 let buffer_id = position.buffer_id?;
16648 let snapshot = self
16649 .project
16650 .as_ref()?
16651 .read(cx)
16652 .buffer_for_id(buffer_id, cx)?
16653 .read(cx)
16654 .snapshot();
16655
16656 let mut handled = false;
16657 for (id, ExcerptRange { context, .. }) in
16658 self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16659 {
16660 if context.start.cmp(&position, &snapshot).is_ge()
16661 || context.end.cmp(&position, &snapshot).is_lt()
16662 {
16663 continue;
16664 }
16665 let snapshot = self.buffer.read(cx).snapshot(cx);
16666 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16667
16668 handled = true;
16669 self.clear_row_highlights::<ActiveDebugLine>();
16670 self.go_to_line::<ActiveDebugLine>(
16671 multibuffer_anchor,
16672 Some(cx.theme().colors().editor_debugger_active_line_background),
16673 window,
16674 cx,
16675 );
16676
16677 cx.notify();
16678 }
16679
16680 handled.then_some(())
16681 })
16682 .is_some()
16683 }
16684
16685 pub fn copy_file_name_without_extension(
16686 &mut self,
16687 _: &CopyFileNameWithoutExtension,
16688 _: &mut Window,
16689 cx: &mut Context<Self>,
16690 ) {
16691 if let Some(file) = self.target_file(cx) {
16692 if let Some(file_stem) = file.path().file_stem() {
16693 if let Some(name) = file_stem.to_str() {
16694 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16695 }
16696 }
16697 }
16698 }
16699
16700 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16701 if let Some(file) = self.target_file(cx) {
16702 if let Some(file_name) = file.path().file_name() {
16703 if let Some(name) = file_name.to_str() {
16704 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16705 }
16706 }
16707 }
16708 }
16709
16710 pub fn toggle_git_blame(
16711 &mut self,
16712 _: &::git::Blame,
16713 window: &mut Window,
16714 cx: &mut Context<Self>,
16715 ) {
16716 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16717
16718 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16719 self.start_git_blame(true, window, cx);
16720 }
16721
16722 cx.notify();
16723 }
16724
16725 pub fn toggle_git_blame_inline(
16726 &mut self,
16727 _: &ToggleGitBlameInline,
16728 window: &mut Window,
16729 cx: &mut Context<Self>,
16730 ) {
16731 self.toggle_git_blame_inline_internal(true, window, cx);
16732 cx.notify();
16733 }
16734
16735 pub fn open_git_blame_commit(
16736 &mut self,
16737 _: &OpenGitBlameCommit,
16738 window: &mut Window,
16739 cx: &mut Context<Self>,
16740 ) {
16741 self.open_git_blame_commit_internal(window, cx);
16742 }
16743
16744 fn open_git_blame_commit_internal(
16745 &mut self,
16746 window: &mut Window,
16747 cx: &mut Context<Self>,
16748 ) -> Option<()> {
16749 let blame = self.blame.as_ref()?;
16750 let snapshot = self.snapshot(window, cx);
16751 let cursor = self.selections.newest::<Point>(cx).head();
16752 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16753 let blame_entry = blame
16754 .update(cx, |blame, cx| {
16755 blame
16756 .blame_for_rows(
16757 &[RowInfo {
16758 buffer_id: Some(buffer.remote_id()),
16759 buffer_row: Some(point.row),
16760 ..Default::default()
16761 }],
16762 cx,
16763 )
16764 .next()
16765 })
16766 .flatten()?;
16767 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16768 let repo = blame.read(cx).repository(cx)?;
16769 let workspace = self.workspace()?.downgrade();
16770 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16771 None
16772 }
16773
16774 pub fn git_blame_inline_enabled(&self) -> bool {
16775 self.git_blame_inline_enabled
16776 }
16777
16778 pub fn toggle_selection_menu(
16779 &mut self,
16780 _: &ToggleSelectionMenu,
16781 _: &mut Window,
16782 cx: &mut Context<Self>,
16783 ) {
16784 self.show_selection_menu = self
16785 .show_selection_menu
16786 .map(|show_selections_menu| !show_selections_menu)
16787 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16788
16789 cx.notify();
16790 }
16791
16792 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16793 self.show_selection_menu
16794 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16795 }
16796
16797 fn start_git_blame(
16798 &mut self,
16799 user_triggered: bool,
16800 window: &mut Window,
16801 cx: &mut Context<Self>,
16802 ) {
16803 if let Some(project) = self.project.as_ref() {
16804 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16805 return;
16806 };
16807
16808 if buffer.read(cx).file().is_none() {
16809 return;
16810 }
16811
16812 let focused = self.focus_handle(cx).contains_focused(window, cx);
16813
16814 let project = project.clone();
16815 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16816 self.blame_subscription =
16817 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16818 self.blame = Some(blame);
16819 }
16820 }
16821
16822 fn toggle_git_blame_inline_internal(
16823 &mut self,
16824 user_triggered: bool,
16825 window: &mut Window,
16826 cx: &mut Context<Self>,
16827 ) {
16828 if self.git_blame_inline_enabled {
16829 self.git_blame_inline_enabled = false;
16830 self.show_git_blame_inline = false;
16831 self.show_git_blame_inline_delay_task.take();
16832 } else {
16833 self.git_blame_inline_enabled = true;
16834 self.start_git_blame_inline(user_triggered, window, cx);
16835 }
16836
16837 cx.notify();
16838 }
16839
16840 fn start_git_blame_inline(
16841 &mut self,
16842 user_triggered: bool,
16843 window: &mut Window,
16844 cx: &mut Context<Self>,
16845 ) {
16846 self.start_git_blame(user_triggered, window, cx);
16847
16848 if ProjectSettings::get_global(cx)
16849 .git
16850 .inline_blame_delay()
16851 .is_some()
16852 {
16853 self.start_inline_blame_timer(window, cx);
16854 } else {
16855 self.show_git_blame_inline = true
16856 }
16857 }
16858
16859 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16860 self.blame.as_ref()
16861 }
16862
16863 pub fn show_git_blame_gutter(&self) -> bool {
16864 self.show_git_blame_gutter
16865 }
16866
16867 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16868 self.show_git_blame_gutter && self.has_blame_entries(cx)
16869 }
16870
16871 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16872 self.show_git_blame_inline
16873 && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16874 && !self.newest_selection_head_on_empty_line(cx)
16875 && self.has_blame_entries(cx)
16876 }
16877
16878 fn has_blame_entries(&self, cx: &App) -> bool {
16879 self.blame()
16880 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16881 }
16882
16883 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16884 let cursor_anchor = self.selections.newest_anchor().head();
16885
16886 let snapshot = self.buffer.read(cx).snapshot(cx);
16887 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16888
16889 snapshot.line_len(buffer_row) == 0
16890 }
16891
16892 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16893 let buffer_and_selection = maybe!({
16894 let selection = self.selections.newest::<Point>(cx);
16895 let selection_range = selection.range();
16896
16897 let multi_buffer = self.buffer().read(cx);
16898 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16899 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16900
16901 let (buffer, range, _) = if selection.reversed {
16902 buffer_ranges.first()
16903 } else {
16904 buffer_ranges.last()
16905 }?;
16906
16907 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16908 ..text::ToPoint::to_point(&range.end, &buffer).row;
16909 Some((
16910 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16911 selection,
16912 ))
16913 });
16914
16915 let Some((buffer, selection)) = buffer_and_selection else {
16916 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16917 };
16918
16919 let Some(project) = self.project.as_ref() else {
16920 return Task::ready(Err(anyhow!("editor does not have project")));
16921 };
16922
16923 project.update(cx, |project, cx| {
16924 project.get_permalink_to_line(&buffer, selection, cx)
16925 })
16926 }
16927
16928 pub fn copy_permalink_to_line(
16929 &mut self,
16930 _: &CopyPermalinkToLine,
16931 window: &mut Window,
16932 cx: &mut Context<Self>,
16933 ) {
16934 let permalink_task = self.get_permalink_to_line(cx);
16935 let workspace = self.workspace();
16936
16937 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16938 Ok(permalink) => {
16939 cx.update(|_, cx| {
16940 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16941 })
16942 .ok();
16943 }
16944 Err(err) => {
16945 let message = format!("Failed to copy permalink: {err}");
16946
16947 Err::<(), anyhow::Error>(err).log_err();
16948
16949 if let Some(workspace) = workspace {
16950 workspace
16951 .update_in(cx, |workspace, _, cx| {
16952 struct CopyPermalinkToLine;
16953
16954 workspace.show_toast(
16955 Toast::new(
16956 NotificationId::unique::<CopyPermalinkToLine>(),
16957 message,
16958 ),
16959 cx,
16960 )
16961 })
16962 .ok();
16963 }
16964 }
16965 })
16966 .detach();
16967 }
16968
16969 pub fn copy_file_location(
16970 &mut self,
16971 _: &CopyFileLocation,
16972 _: &mut Window,
16973 cx: &mut Context<Self>,
16974 ) {
16975 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16976 if let Some(file) = self.target_file(cx) {
16977 if let Some(path) = file.path().to_str() {
16978 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16979 }
16980 }
16981 }
16982
16983 pub fn open_permalink_to_line(
16984 &mut self,
16985 _: &OpenPermalinkToLine,
16986 window: &mut Window,
16987 cx: &mut Context<Self>,
16988 ) {
16989 let permalink_task = self.get_permalink_to_line(cx);
16990 let workspace = self.workspace();
16991
16992 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16993 Ok(permalink) => {
16994 cx.update(|_, cx| {
16995 cx.open_url(permalink.as_ref());
16996 })
16997 .ok();
16998 }
16999 Err(err) => {
17000 let message = format!("Failed to open permalink: {err}");
17001
17002 Err::<(), anyhow::Error>(err).log_err();
17003
17004 if let Some(workspace) = workspace {
17005 workspace
17006 .update(cx, |workspace, cx| {
17007 struct OpenPermalinkToLine;
17008
17009 workspace.show_toast(
17010 Toast::new(
17011 NotificationId::unique::<OpenPermalinkToLine>(),
17012 message,
17013 ),
17014 cx,
17015 )
17016 })
17017 .ok();
17018 }
17019 }
17020 })
17021 .detach();
17022 }
17023
17024 pub fn insert_uuid_v4(
17025 &mut self,
17026 _: &InsertUuidV4,
17027 window: &mut Window,
17028 cx: &mut Context<Self>,
17029 ) {
17030 self.insert_uuid(UuidVersion::V4, window, cx);
17031 }
17032
17033 pub fn insert_uuid_v7(
17034 &mut self,
17035 _: &InsertUuidV7,
17036 window: &mut Window,
17037 cx: &mut Context<Self>,
17038 ) {
17039 self.insert_uuid(UuidVersion::V7, window, cx);
17040 }
17041
17042 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17043 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17044 self.transact(window, cx, |this, window, cx| {
17045 let edits = this
17046 .selections
17047 .all::<Point>(cx)
17048 .into_iter()
17049 .map(|selection| {
17050 let uuid = match version {
17051 UuidVersion::V4 => uuid::Uuid::new_v4(),
17052 UuidVersion::V7 => uuid::Uuid::now_v7(),
17053 };
17054
17055 (selection.range(), uuid.to_string())
17056 });
17057 this.edit(edits, cx);
17058 this.refresh_inline_completion(true, false, window, cx);
17059 });
17060 }
17061
17062 pub fn open_selections_in_multibuffer(
17063 &mut self,
17064 _: &OpenSelectionsInMultibuffer,
17065 window: &mut Window,
17066 cx: &mut Context<Self>,
17067 ) {
17068 let multibuffer = self.buffer.read(cx);
17069
17070 let Some(buffer) = multibuffer.as_singleton() else {
17071 return;
17072 };
17073
17074 let Some(workspace) = self.workspace() else {
17075 return;
17076 };
17077
17078 let locations = self
17079 .selections
17080 .disjoint_anchors()
17081 .iter()
17082 .map(|range| Location {
17083 buffer: buffer.clone(),
17084 range: range.start.text_anchor..range.end.text_anchor,
17085 })
17086 .collect::<Vec<_>>();
17087
17088 let title = multibuffer.title(cx).to_string();
17089
17090 cx.spawn_in(window, async move |_, cx| {
17091 workspace.update_in(cx, |workspace, window, cx| {
17092 Self::open_locations_in_multibuffer(
17093 workspace,
17094 locations,
17095 format!("Selections for '{title}'"),
17096 false,
17097 MultibufferSelectionMode::All,
17098 window,
17099 cx,
17100 );
17101 })
17102 })
17103 .detach();
17104 }
17105
17106 /// Adds a row highlight for the given range. If a row has multiple highlights, the
17107 /// last highlight added will be used.
17108 ///
17109 /// If the range ends at the beginning of a line, then that line will not be highlighted.
17110 pub fn highlight_rows<T: 'static>(
17111 &mut self,
17112 range: Range<Anchor>,
17113 color: Hsla,
17114 options: RowHighlightOptions,
17115 cx: &mut Context<Self>,
17116 ) {
17117 let snapshot = self.buffer().read(cx).snapshot(cx);
17118 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17119 let ix = row_highlights.binary_search_by(|highlight| {
17120 Ordering::Equal
17121 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17122 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17123 });
17124
17125 if let Err(mut ix) = ix {
17126 let index = post_inc(&mut self.highlight_order);
17127
17128 // If this range intersects with the preceding highlight, then merge it with
17129 // the preceding highlight. Otherwise insert a new highlight.
17130 let mut merged = false;
17131 if ix > 0 {
17132 let prev_highlight = &mut row_highlights[ix - 1];
17133 if prev_highlight
17134 .range
17135 .end
17136 .cmp(&range.start, &snapshot)
17137 .is_ge()
17138 {
17139 ix -= 1;
17140 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17141 prev_highlight.range.end = range.end;
17142 }
17143 merged = true;
17144 prev_highlight.index = index;
17145 prev_highlight.color = color;
17146 prev_highlight.options = options;
17147 }
17148 }
17149
17150 if !merged {
17151 row_highlights.insert(
17152 ix,
17153 RowHighlight {
17154 range: range.clone(),
17155 index,
17156 color,
17157 options,
17158 type_id: TypeId::of::<T>(),
17159 },
17160 );
17161 }
17162
17163 // If any of the following highlights intersect with this one, merge them.
17164 while let Some(next_highlight) = row_highlights.get(ix + 1) {
17165 let highlight = &row_highlights[ix];
17166 if next_highlight
17167 .range
17168 .start
17169 .cmp(&highlight.range.end, &snapshot)
17170 .is_le()
17171 {
17172 if next_highlight
17173 .range
17174 .end
17175 .cmp(&highlight.range.end, &snapshot)
17176 .is_gt()
17177 {
17178 row_highlights[ix].range.end = next_highlight.range.end;
17179 }
17180 row_highlights.remove(ix + 1);
17181 } else {
17182 break;
17183 }
17184 }
17185 }
17186 }
17187
17188 /// Remove any highlighted row ranges of the given type that intersect the
17189 /// given ranges.
17190 pub fn remove_highlighted_rows<T: 'static>(
17191 &mut self,
17192 ranges_to_remove: Vec<Range<Anchor>>,
17193 cx: &mut Context<Self>,
17194 ) {
17195 let snapshot = self.buffer().read(cx).snapshot(cx);
17196 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17197 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17198 row_highlights.retain(|highlight| {
17199 while let Some(range_to_remove) = ranges_to_remove.peek() {
17200 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17201 Ordering::Less | Ordering::Equal => {
17202 ranges_to_remove.next();
17203 }
17204 Ordering::Greater => {
17205 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17206 Ordering::Less | Ordering::Equal => {
17207 return false;
17208 }
17209 Ordering::Greater => break,
17210 }
17211 }
17212 }
17213 }
17214
17215 true
17216 })
17217 }
17218
17219 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17220 pub fn clear_row_highlights<T: 'static>(&mut self) {
17221 self.highlighted_rows.remove(&TypeId::of::<T>());
17222 }
17223
17224 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17225 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17226 self.highlighted_rows
17227 .get(&TypeId::of::<T>())
17228 .map_or(&[] as &[_], |vec| vec.as_slice())
17229 .iter()
17230 .map(|highlight| (highlight.range.clone(), highlight.color))
17231 }
17232
17233 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17234 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17235 /// Allows to ignore certain kinds of highlights.
17236 pub fn highlighted_display_rows(
17237 &self,
17238 window: &mut Window,
17239 cx: &mut App,
17240 ) -> BTreeMap<DisplayRow, LineHighlight> {
17241 let snapshot = self.snapshot(window, cx);
17242 let mut used_highlight_orders = HashMap::default();
17243 self.highlighted_rows
17244 .iter()
17245 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17246 .fold(
17247 BTreeMap::<DisplayRow, LineHighlight>::new(),
17248 |mut unique_rows, highlight| {
17249 let start = highlight.range.start.to_display_point(&snapshot);
17250 let end = highlight.range.end.to_display_point(&snapshot);
17251 let start_row = start.row().0;
17252 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17253 && end.column() == 0
17254 {
17255 end.row().0.saturating_sub(1)
17256 } else {
17257 end.row().0
17258 };
17259 for row in start_row..=end_row {
17260 let used_index =
17261 used_highlight_orders.entry(row).or_insert(highlight.index);
17262 if highlight.index >= *used_index {
17263 *used_index = highlight.index;
17264 unique_rows.insert(
17265 DisplayRow(row),
17266 LineHighlight {
17267 include_gutter: highlight.options.include_gutter,
17268 border: None,
17269 background: highlight.color.into(),
17270 type_id: Some(highlight.type_id),
17271 },
17272 );
17273 }
17274 }
17275 unique_rows
17276 },
17277 )
17278 }
17279
17280 pub fn highlighted_display_row_for_autoscroll(
17281 &self,
17282 snapshot: &DisplaySnapshot,
17283 ) -> Option<DisplayRow> {
17284 self.highlighted_rows
17285 .values()
17286 .flat_map(|highlighted_rows| highlighted_rows.iter())
17287 .filter_map(|highlight| {
17288 if highlight.options.autoscroll {
17289 Some(highlight.range.start.to_display_point(snapshot).row())
17290 } else {
17291 None
17292 }
17293 })
17294 .min()
17295 }
17296
17297 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17298 self.highlight_background::<SearchWithinRange>(
17299 ranges,
17300 |colors| colors.editor_document_highlight_read_background,
17301 cx,
17302 )
17303 }
17304
17305 pub fn set_breadcrumb_header(&mut self, new_header: String) {
17306 self.breadcrumb_header = Some(new_header);
17307 }
17308
17309 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17310 self.clear_background_highlights::<SearchWithinRange>(cx);
17311 }
17312
17313 pub fn highlight_background<T: 'static>(
17314 &mut self,
17315 ranges: &[Range<Anchor>],
17316 color_fetcher: fn(&ThemeColors) -> Hsla,
17317 cx: &mut Context<Self>,
17318 ) {
17319 self.background_highlights
17320 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17321 self.scrollbar_marker_state.dirty = true;
17322 cx.notify();
17323 }
17324
17325 pub fn clear_background_highlights<T: 'static>(
17326 &mut self,
17327 cx: &mut Context<Self>,
17328 ) -> Option<BackgroundHighlight> {
17329 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17330 if !text_highlights.1.is_empty() {
17331 self.scrollbar_marker_state.dirty = true;
17332 cx.notify();
17333 }
17334 Some(text_highlights)
17335 }
17336
17337 pub fn highlight_gutter<T: 'static>(
17338 &mut self,
17339 ranges: &[Range<Anchor>],
17340 color_fetcher: fn(&App) -> Hsla,
17341 cx: &mut Context<Self>,
17342 ) {
17343 self.gutter_highlights
17344 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17345 cx.notify();
17346 }
17347
17348 pub fn clear_gutter_highlights<T: 'static>(
17349 &mut self,
17350 cx: &mut Context<Self>,
17351 ) -> Option<GutterHighlight> {
17352 cx.notify();
17353 self.gutter_highlights.remove(&TypeId::of::<T>())
17354 }
17355
17356 #[cfg(feature = "test-support")]
17357 pub fn all_text_background_highlights(
17358 &self,
17359 window: &mut Window,
17360 cx: &mut Context<Self>,
17361 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17362 let snapshot = self.snapshot(window, cx);
17363 let buffer = &snapshot.buffer_snapshot;
17364 let start = buffer.anchor_before(0);
17365 let end = buffer.anchor_after(buffer.len());
17366 let theme = cx.theme().colors();
17367 self.background_highlights_in_range(start..end, &snapshot, theme)
17368 }
17369
17370 #[cfg(feature = "test-support")]
17371 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17372 let snapshot = self.buffer().read(cx).snapshot(cx);
17373
17374 let highlights = self
17375 .background_highlights
17376 .get(&TypeId::of::<items::BufferSearchHighlights>());
17377
17378 if let Some((_color, ranges)) = highlights {
17379 ranges
17380 .iter()
17381 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17382 .collect_vec()
17383 } else {
17384 vec![]
17385 }
17386 }
17387
17388 fn document_highlights_for_position<'a>(
17389 &'a self,
17390 position: Anchor,
17391 buffer: &'a MultiBufferSnapshot,
17392 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17393 let read_highlights = self
17394 .background_highlights
17395 .get(&TypeId::of::<DocumentHighlightRead>())
17396 .map(|h| &h.1);
17397 let write_highlights = self
17398 .background_highlights
17399 .get(&TypeId::of::<DocumentHighlightWrite>())
17400 .map(|h| &h.1);
17401 let left_position = position.bias_left(buffer);
17402 let right_position = position.bias_right(buffer);
17403 read_highlights
17404 .into_iter()
17405 .chain(write_highlights)
17406 .flat_map(move |ranges| {
17407 let start_ix = match ranges.binary_search_by(|probe| {
17408 let cmp = probe.end.cmp(&left_position, buffer);
17409 if cmp.is_ge() {
17410 Ordering::Greater
17411 } else {
17412 Ordering::Less
17413 }
17414 }) {
17415 Ok(i) | Err(i) => i,
17416 };
17417
17418 ranges[start_ix..]
17419 .iter()
17420 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17421 })
17422 }
17423
17424 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17425 self.background_highlights
17426 .get(&TypeId::of::<T>())
17427 .map_or(false, |(_, highlights)| !highlights.is_empty())
17428 }
17429
17430 pub fn background_highlights_in_range(
17431 &self,
17432 search_range: Range<Anchor>,
17433 display_snapshot: &DisplaySnapshot,
17434 theme: &ThemeColors,
17435 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17436 let mut results = Vec::new();
17437 for (color_fetcher, ranges) in self.background_highlights.values() {
17438 let color = color_fetcher(theme);
17439 let start_ix = match ranges.binary_search_by(|probe| {
17440 let cmp = probe
17441 .end
17442 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17443 if cmp.is_gt() {
17444 Ordering::Greater
17445 } else {
17446 Ordering::Less
17447 }
17448 }) {
17449 Ok(i) | Err(i) => i,
17450 };
17451 for range in &ranges[start_ix..] {
17452 if range
17453 .start
17454 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17455 .is_ge()
17456 {
17457 break;
17458 }
17459
17460 let start = range.start.to_display_point(display_snapshot);
17461 let end = range.end.to_display_point(display_snapshot);
17462 results.push((start..end, color))
17463 }
17464 }
17465 results
17466 }
17467
17468 pub fn background_highlight_row_ranges<T: 'static>(
17469 &self,
17470 search_range: Range<Anchor>,
17471 display_snapshot: &DisplaySnapshot,
17472 count: usize,
17473 ) -> Vec<RangeInclusive<DisplayPoint>> {
17474 let mut results = Vec::new();
17475 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17476 return vec![];
17477 };
17478
17479 let start_ix = match ranges.binary_search_by(|probe| {
17480 let cmp = probe
17481 .end
17482 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17483 if cmp.is_gt() {
17484 Ordering::Greater
17485 } else {
17486 Ordering::Less
17487 }
17488 }) {
17489 Ok(i) | Err(i) => i,
17490 };
17491 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17492 if let (Some(start_display), Some(end_display)) = (start, end) {
17493 results.push(
17494 start_display.to_display_point(display_snapshot)
17495 ..=end_display.to_display_point(display_snapshot),
17496 );
17497 }
17498 };
17499 let mut start_row: Option<Point> = None;
17500 let mut end_row: Option<Point> = None;
17501 if ranges.len() > count {
17502 return Vec::new();
17503 }
17504 for range in &ranges[start_ix..] {
17505 if range
17506 .start
17507 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17508 .is_ge()
17509 {
17510 break;
17511 }
17512 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17513 if let Some(current_row) = &end_row {
17514 if end.row == current_row.row {
17515 continue;
17516 }
17517 }
17518 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17519 if start_row.is_none() {
17520 assert_eq!(end_row, None);
17521 start_row = Some(start);
17522 end_row = Some(end);
17523 continue;
17524 }
17525 if let Some(current_end) = end_row.as_mut() {
17526 if start.row > current_end.row + 1 {
17527 push_region(start_row, end_row);
17528 start_row = Some(start);
17529 end_row = Some(end);
17530 } else {
17531 // Merge two hunks.
17532 *current_end = end;
17533 }
17534 } else {
17535 unreachable!();
17536 }
17537 }
17538 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17539 push_region(start_row, end_row);
17540 results
17541 }
17542
17543 pub fn gutter_highlights_in_range(
17544 &self,
17545 search_range: Range<Anchor>,
17546 display_snapshot: &DisplaySnapshot,
17547 cx: &App,
17548 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17549 let mut results = Vec::new();
17550 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17551 let color = color_fetcher(cx);
17552 let start_ix = match ranges.binary_search_by(|probe| {
17553 let cmp = probe
17554 .end
17555 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17556 if cmp.is_gt() {
17557 Ordering::Greater
17558 } else {
17559 Ordering::Less
17560 }
17561 }) {
17562 Ok(i) | Err(i) => i,
17563 };
17564 for range in &ranges[start_ix..] {
17565 if range
17566 .start
17567 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17568 .is_ge()
17569 {
17570 break;
17571 }
17572
17573 let start = range.start.to_display_point(display_snapshot);
17574 let end = range.end.to_display_point(display_snapshot);
17575 results.push((start..end, color))
17576 }
17577 }
17578 results
17579 }
17580
17581 /// Get the text ranges corresponding to the redaction query
17582 pub fn redacted_ranges(
17583 &self,
17584 search_range: Range<Anchor>,
17585 display_snapshot: &DisplaySnapshot,
17586 cx: &App,
17587 ) -> Vec<Range<DisplayPoint>> {
17588 display_snapshot
17589 .buffer_snapshot
17590 .redacted_ranges(search_range, |file| {
17591 if let Some(file) = file {
17592 file.is_private()
17593 && EditorSettings::get(
17594 Some(SettingsLocation {
17595 worktree_id: file.worktree_id(cx),
17596 path: file.path().as_ref(),
17597 }),
17598 cx,
17599 )
17600 .redact_private_values
17601 } else {
17602 false
17603 }
17604 })
17605 .map(|range| {
17606 range.start.to_display_point(display_snapshot)
17607 ..range.end.to_display_point(display_snapshot)
17608 })
17609 .collect()
17610 }
17611
17612 pub fn highlight_text<T: 'static>(
17613 &mut self,
17614 ranges: Vec<Range<Anchor>>,
17615 style: HighlightStyle,
17616 cx: &mut Context<Self>,
17617 ) {
17618 self.display_map.update(cx, |map, _| {
17619 map.highlight_text(TypeId::of::<T>(), ranges, style)
17620 });
17621 cx.notify();
17622 }
17623
17624 pub(crate) fn highlight_inlays<T: 'static>(
17625 &mut self,
17626 highlights: Vec<InlayHighlight>,
17627 style: HighlightStyle,
17628 cx: &mut Context<Self>,
17629 ) {
17630 self.display_map.update(cx, |map, _| {
17631 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17632 });
17633 cx.notify();
17634 }
17635
17636 pub fn text_highlights<'a, T: 'static>(
17637 &'a self,
17638 cx: &'a App,
17639 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17640 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17641 }
17642
17643 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17644 let cleared = self
17645 .display_map
17646 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17647 if cleared {
17648 cx.notify();
17649 }
17650 }
17651
17652 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17653 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17654 && self.focus_handle.is_focused(window)
17655 }
17656
17657 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17658 self.show_cursor_when_unfocused = is_enabled;
17659 cx.notify();
17660 }
17661
17662 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17663 cx.notify();
17664 }
17665
17666 fn on_debug_session_event(
17667 &mut self,
17668 _session: Entity<Session>,
17669 event: &SessionEvent,
17670 cx: &mut Context<Self>,
17671 ) {
17672 match event {
17673 SessionEvent::InvalidateInlineValue => {
17674 self.refresh_inline_values(cx);
17675 }
17676 _ => {}
17677 }
17678 }
17679
17680 fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17681 let Some(project) = self.project.clone() else {
17682 return;
17683 };
17684 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17685 return;
17686 };
17687 if !self.inline_value_cache.enabled {
17688 let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17689 self.splice_inlays(&inlays, Vec::new(), cx);
17690 return;
17691 }
17692
17693 let current_execution_position = self
17694 .highlighted_rows
17695 .get(&TypeId::of::<ActiveDebugLine>())
17696 .and_then(|lines| lines.last().map(|line| line.range.start));
17697
17698 self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17699 let snapshot = editor
17700 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17701 .ok()?;
17702
17703 let inline_values = editor
17704 .update(cx, |_, cx| {
17705 let Some(current_execution_position) = current_execution_position else {
17706 return Some(Task::ready(Ok(Vec::new())));
17707 };
17708
17709 // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17710 // anchor is in the same buffer
17711 let range =
17712 buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17713 project.inline_values(buffer, range, cx)
17714 })
17715 .ok()
17716 .flatten()?
17717 .await
17718 .context("refreshing debugger inlays")
17719 .log_err()?;
17720
17721 let (excerpt_id, buffer_id) = snapshot
17722 .excerpts()
17723 .next()
17724 .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17725 editor
17726 .update(cx, |editor, cx| {
17727 let new_inlays = inline_values
17728 .into_iter()
17729 .map(|debugger_value| {
17730 Inlay::debugger_hint(
17731 post_inc(&mut editor.next_inlay_id),
17732 Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17733 debugger_value.text(),
17734 )
17735 })
17736 .collect::<Vec<_>>();
17737 let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17738 std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17739
17740 editor.splice_inlays(&inlay_ids, new_inlays, cx);
17741 })
17742 .ok()?;
17743 Some(())
17744 });
17745 }
17746
17747 fn on_buffer_event(
17748 &mut self,
17749 multibuffer: &Entity<MultiBuffer>,
17750 event: &multi_buffer::Event,
17751 window: &mut Window,
17752 cx: &mut Context<Self>,
17753 ) {
17754 match event {
17755 multi_buffer::Event::Edited {
17756 singleton_buffer_edited,
17757 edited_buffer: buffer_edited,
17758 } => {
17759 self.scrollbar_marker_state.dirty = true;
17760 self.active_indent_guides_state.dirty = true;
17761 self.refresh_active_diagnostics(cx);
17762 self.refresh_code_actions(window, cx);
17763 self.refresh_selected_text_highlights(true, window, cx);
17764 refresh_matching_bracket_highlights(self, window, cx);
17765 if self.has_active_inline_completion() {
17766 self.update_visible_inline_completion(window, cx);
17767 }
17768 if let Some(buffer) = buffer_edited {
17769 let buffer_id = buffer.read(cx).remote_id();
17770 if !self.registered_buffers.contains_key(&buffer_id) {
17771 if let Some(project) = self.project.as_ref() {
17772 project.update(cx, |project, cx| {
17773 self.registered_buffers.insert(
17774 buffer_id,
17775 project.register_buffer_with_language_servers(&buffer, cx),
17776 );
17777 })
17778 }
17779 }
17780 }
17781 cx.emit(EditorEvent::BufferEdited);
17782 cx.emit(SearchEvent::MatchesInvalidated);
17783 if *singleton_buffer_edited {
17784 if let Some(project) = &self.project {
17785 #[allow(clippy::mutable_key_type)]
17786 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17787 multibuffer
17788 .all_buffers()
17789 .into_iter()
17790 .filter_map(|buffer| {
17791 buffer.update(cx, |buffer, cx| {
17792 let language = buffer.language()?;
17793 let should_discard = project.update(cx, |project, cx| {
17794 project.is_local()
17795 && !project.has_language_servers_for(buffer, cx)
17796 });
17797 should_discard.not().then_some(language.clone())
17798 })
17799 })
17800 .collect::<HashSet<_>>()
17801 });
17802 if !languages_affected.is_empty() {
17803 self.refresh_inlay_hints(
17804 InlayHintRefreshReason::BufferEdited(languages_affected),
17805 cx,
17806 );
17807 }
17808 }
17809 }
17810
17811 let Some(project) = &self.project else { return };
17812 let (telemetry, is_via_ssh) = {
17813 let project = project.read(cx);
17814 let telemetry = project.client().telemetry().clone();
17815 let is_via_ssh = project.is_via_ssh();
17816 (telemetry, is_via_ssh)
17817 };
17818 refresh_linked_ranges(self, window, cx);
17819 telemetry.log_edit_event("editor", is_via_ssh);
17820 }
17821 multi_buffer::Event::ExcerptsAdded {
17822 buffer,
17823 predecessor,
17824 excerpts,
17825 } => {
17826 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17827 let buffer_id = buffer.read(cx).remote_id();
17828 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17829 if let Some(project) = &self.project {
17830 get_uncommitted_diff_for_buffer(
17831 project,
17832 [buffer.clone()],
17833 self.buffer.clone(),
17834 cx,
17835 )
17836 .detach();
17837 }
17838 }
17839 cx.emit(EditorEvent::ExcerptsAdded {
17840 buffer: buffer.clone(),
17841 predecessor: *predecessor,
17842 excerpts: excerpts.clone(),
17843 });
17844 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17845 }
17846 multi_buffer::Event::ExcerptsRemoved {
17847 ids,
17848 removed_buffer_ids,
17849 } => {
17850 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17851 let buffer = self.buffer.read(cx);
17852 self.registered_buffers
17853 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17854 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17855 cx.emit(EditorEvent::ExcerptsRemoved {
17856 ids: ids.clone(),
17857 removed_buffer_ids: removed_buffer_ids.clone(),
17858 })
17859 }
17860 multi_buffer::Event::ExcerptsEdited {
17861 excerpt_ids,
17862 buffer_ids,
17863 } => {
17864 self.display_map.update(cx, |map, cx| {
17865 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17866 });
17867 cx.emit(EditorEvent::ExcerptsEdited {
17868 ids: excerpt_ids.clone(),
17869 })
17870 }
17871 multi_buffer::Event::ExcerptsExpanded { ids } => {
17872 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17873 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17874 }
17875 multi_buffer::Event::Reparsed(buffer_id) => {
17876 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17877 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17878
17879 cx.emit(EditorEvent::Reparsed(*buffer_id));
17880 }
17881 multi_buffer::Event::DiffHunksToggled => {
17882 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17883 }
17884 multi_buffer::Event::LanguageChanged(buffer_id) => {
17885 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17886 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17887 cx.emit(EditorEvent::Reparsed(*buffer_id));
17888 cx.notify();
17889 }
17890 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17891 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17892 multi_buffer::Event::FileHandleChanged
17893 | multi_buffer::Event::Reloaded
17894 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17895 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17896 multi_buffer::Event::DiagnosticsUpdated => {
17897 self.refresh_active_diagnostics(cx);
17898 self.refresh_inline_diagnostics(true, window, cx);
17899 self.scrollbar_marker_state.dirty = true;
17900 cx.notify();
17901 }
17902 _ => {}
17903 };
17904 }
17905
17906 fn on_display_map_changed(
17907 &mut self,
17908 _: Entity<DisplayMap>,
17909 _: &mut Window,
17910 cx: &mut Context<Self>,
17911 ) {
17912 cx.notify();
17913 }
17914
17915 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17916 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17917 self.update_edit_prediction_settings(cx);
17918 self.refresh_inline_completion(true, false, window, cx);
17919 self.refresh_inlay_hints(
17920 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17921 self.selections.newest_anchor().head(),
17922 &self.buffer.read(cx).snapshot(cx),
17923 cx,
17924 )),
17925 cx,
17926 );
17927
17928 let old_cursor_shape = self.cursor_shape;
17929
17930 {
17931 let editor_settings = EditorSettings::get_global(cx);
17932 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17933 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17934 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17935 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17936 }
17937
17938 if old_cursor_shape != self.cursor_shape {
17939 cx.emit(EditorEvent::CursorShapeChanged);
17940 }
17941
17942 let project_settings = ProjectSettings::get_global(cx);
17943 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17944
17945 if self.mode.is_full() {
17946 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17947 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17948 if self.show_inline_diagnostics != show_inline_diagnostics {
17949 self.show_inline_diagnostics = show_inline_diagnostics;
17950 self.refresh_inline_diagnostics(false, window, cx);
17951 }
17952
17953 if self.git_blame_inline_enabled != inline_blame_enabled {
17954 self.toggle_git_blame_inline_internal(false, window, cx);
17955 }
17956 }
17957
17958 cx.notify();
17959 }
17960
17961 pub fn set_searchable(&mut self, searchable: bool) {
17962 self.searchable = searchable;
17963 }
17964
17965 pub fn searchable(&self) -> bool {
17966 self.searchable
17967 }
17968
17969 fn open_proposed_changes_editor(
17970 &mut self,
17971 _: &OpenProposedChangesEditor,
17972 window: &mut Window,
17973 cx: &mut Context<Self>,
17974 ) {
17975 let Some(workspace) = self.workspace() else {
17976 cx.propagate();
17977 return;
17978 };
17979
17980 let selections = self.selections.all::<usize>(cx);
17981 let multi_buffer = self.buffer.read(cx);
17982 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17983 let mut new_selections_by_buffer = HashMap::default();
17984 for selection in selections {
17985 for (buffer, range, _) in
17986 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17987 {
17988 let mut range = range.to_point(buffer);
17989 range.start.column = 0;
17990 range.end.column = buffer.line_len(range.end.row);
17991 new_selections_by_buffer
17992 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17993 .or_insert(Vec::new())
17994 .push(range)
17995 }
17996 }
17997
17998 let proposed_changes_buffers = new_selections_by_buffer
17999 .into_iter()
18000 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18001 .collect::<Vec<_>>();
18002 let proposed_changes_editor = cx.new(|cx| {
18003 ProposedChangesEditor::new(
18004 "Proposed changes",
18005 proposed_changes_buffers,
18006 self.project.clone(),
18007 window,
18008 cx,
18009 )
18010 });
18011
18012 window.defer(cx, move |window, cx| {
18013 workspace.update(cx, |workspace, cx| {
18014 workspace.active_pane().update(cx, |pane, cx| {
18015 pane.add_item(
18016 Box::new(proposed_changes_editor),
18017 true,
18018 true,
18019 None,
18020 window,
18021 cx,
18022 );
18023 });
18024 });
18025 });
18026 }
18027
18028 pub fn open_excerpts_in_split(
18029 &mut self,
18030 _: &OpenExcerptsSplit,
18031 window: &mut Window,
18032 cx: &mut Context<Self>,
18033 ) {
18034 self.open_excerpts_common(None, true, window, cx)
18035 }
18036
18037 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18038 self.open_excerpts_common(None, false, window, cx)
18039 }
18040
18041 fn open_excerpts_common(
18042 &mut self,
18043 jump_data: Option<JumpData>,
18044 split: bool,
18045 window: &mut Window,
18046 cx: &mut Context<Self>,
18047 ) {
18048 let Some(workspace) = self.workspace() else {
18049 cx.propagate();
18050 return;
18051 };
18052
18053 if self.buffer.read(cx).is_singleton() {
18054 cx.propagate();
18055 return;
18056 }
18057
18058 let mut new_selections_by_buffer = HashMap::default();
18059 match &jump_data {
18060 Some(JumpData::MultiBufferPoint {
18061 excerpt_id,
18062 position,
18063 anchor,
18064 line_offset_from_top,
18065 }) => {
18066 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18067 if let Some(buffer) = multi_buffer_snapshot
18068 .buffer_id_for_excerpt(*excerpt_id)
18069 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18070 {
18071 let buffer_snapshot = buffer.read(cx).snapshot();
18072 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18073 language::ToPoint::to_point(anchor, &buffer_snapshot)
18074 } else {
18075 buffer_snapshot.clip_point(*position, Bias::Left)
18076 };
18077 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18078 new_selections_by_buffer.insert(
18079 buffer,
18080 (
18081 vec![jump_to_offset..jump_to_offset],
18082 Some(*line_offset_from_top),
18083 ),
18084 );
18085 }
18086 }
18087 Some(JumpData::MultiBufferRow {
18088 row,
18089 line_offset_from_top,
18090 }) => {
18091 let point = MultiBufferPoint::new(row.0, 0);
18092 if let Some((buffer, buffer_point, _)) =
18093 self.buffer.read(cx).point_to_buffer_point(point, cx)
18094 {
18095 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18096 new_selections_by_buffer
18097 .entry(buffer)
18098 .or_insert((Vec::new(), Some(*line_offset_from_top)))
18099 .0
18100 .push(buffer_offset..buffer_offset)
18101 }
18102 }
18103 None => {
18104 let selections = self.selections.all::<usize>(cx);
18105 let multi_buffer = self.buffer.read(cx);
18106 for selection in selections {
18107 for (snapshot, range, _, anchor) in multi_buffer
18108 .snapshot(cx)
18109 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18110 {
18111 if let Some(anchor) = anchor {
18112 // selection is in a deleted hunk
18113 let Some(buffer_id) = anchor.buffer_id else {
18114 continue;
18115 };
18116 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18117 continue;
18118 };
18119 let offset = text::ToOffset::to_offset(
18120 &anchor.text_anchor,
18121 &buffer_handle.read(cx).snapshot(),
18122 );
18123 let range = offset..offset;
18124 new_selections_by_buffer
18125 .entry(buffer_handle)
18126 .or_insert((Vec::new(), None))
18127 .0
18128 .push(range)
18129 } else {
18130 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18131 else {
18132 continue;
18133 };
18134 new_selections_by_buffer
18135 .entry(buffer_handle)
18136 .or_insert((Vec::new(), None))
18137 .0
18138 .push(range)
18139 }
18140 }
18141 }
18142 }
18143 }
18144
18145 new_selections_by_buffer
18146 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18147
18148 if new_selections_by_buffer.is_empty() {
18149 return;
18150 }
18151
18152 // We defer the pane interaction because we ourselves are a workspace item
18153 // and activating a new item causes the pane to call a method on us reentrantly,
18154 // which panics if we're on the stack.
18155 window.defer(cx, move |window, cx| {
18156 workspace.update(cx, |workspace, cx| {
18157 let pane = if split {
18158 workspace.adjacent_pane(window, cx)
18159 } else {
18160 workspace.active_pane().clone()
18161 };
18162
18163 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18164 let editor = buffer
18165 .read(cx)
18166 .file()
18167 .is_none()
18168 .then(|| {
18169 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18170 // so `workspace.open_project_item` will never find them, always opening a new editor.
18171 // Instead, we try to activate the existing editor in the pane first.
18172 let (editor, pane_item_index) =
18173 pane.read(cx).items().enumerate().find_map(|(i, item)| {
18174 let editor = item.downcast::<Editor>()?;
18175 let singleton_buffer =
18176 editor.read(cx).buffer().read(cx).as_singleton()?;
18177 if singleton_buffer == buffer {
18178 Some((editor, i))
18179 } else {
18180 None
18181 }
18182 })?;
18183 pane.update(cx, |pane, cx| {
18184 pane.activate_item(pane_item_index, true, true, window, cx)
18185 });
18186 Some(editor)
18187 })
18188 .flatten()
18189 .unwrap_or_else(|| {
18190 workspace.open_project_item::<Self>(
18191 pane.clone(),
18192 buffer,
18193 true,
18194 true,
18195 window,
18196 cx,
18197 )
18198 });
18199
18200 editor.update(cx, |editor, cx| {
18201 let autoscroll = match scroll_offset {
18202 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18203 None => Autoscroll::newest(),
18204 };
18205 let nav_history = editor.nav_history.take();
18206 editor.change_selections(Some(autoscroll), window, cx, |s| {
18207 s.select_ranges(ranges);
18208 });
18209 editor.nav_history = nav_history;
18210 });
18211 }
18212 })
18213 });
18214 }
18215
18216 // For now, don't allow opening excerpts in buffers that aren't backed by
18217 // regular project files.
18218 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18219 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18220 }
18221
18222 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18223 let snapshot = self.buffer.read(cx).read(cx);
18224 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18225 Some(
18226 ranges
18227 .iter()
18228 .map(move |range| {
18229 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18230 })
18231 .collect(),
18232 )
18233 }
18234
18235 fn selection_replacement_ranges(
18236 &self,
18237 range: Range<OffsetUtf16>,
18238 cx: &mut App,
18239 ) -> Vec<Range<OffsetUtf16>> {
18240 let selections = self.selections.all::<OffsetUtf16>(cx);
18241 let newest_selection = selections
18242 .iter()
18243 .max_by_key(|selection| selection.id)
18244 .unwrap();
18245 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18246 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18247 let snapshot = self.buffer.read(cx).read(cx);
18248 selections
18249 .into_iter()
18250 .map(|mut selection| {
18251 selection.start.0 =
18252 (selection.start.0 as isize).saturating_add(start_delta) as usize;
18253 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18254 snapshot.clip_offset_utf16(selection.start, Bias::Left)
18255 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18256 })
18257 .collect()
18258 }
18259
18260 fn report_editor_event(
18261 &self,
18262 event_type: &'static str,
18263 file_extension: Option<String>,
18264 cx: &App,
18265 ) {
18266 if cfg!(any(test, feature = "test-support")) {
18267 return;
18268 }
18269
18270 let Some(project) = &self.project else { return };
18271
18272 // If None, we are in a file without an extension
18273 let file = self
18274 .buffer
18275 .read(cx)
18276 .as_singleton()
18277 .and_then(|b| b.read(cx).file());
18278 let file_extension = file_extension.or(file
18279 .as_ref()
18280 .and_then(|file| Path::new(file.file_name(cx)).extension())
18281 .and_then(|e| e.to_str())
18282 .map(|a| a.to_string()));
18283
18284 let vim_mode = vim_enabled(cx);
18285
18286 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18287 let copilot_enabled = edit_predictions_provider
18288 == language::language_settings::EditPredictionProvider::Copilot;
18289 let copilot_enabled_for_language = self
18290 .buffer
18291 .read(cx)
18292 .language_settings(cx)
18293 .show_edit_predictions;
18294
18295 let project = project.read(cx);
18296 telemetry::event!(
18297 event_type,
18298 file_extension,
18299 vim_mode,
18300 copilot_enabled,
18301 copilot_enabled_for_language,
18302 edit_predictions_provider,
18303 is_via_ssh = project.is_via_ssh(),
18304 );
18305 }
18306
18307 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18308 /// with each line being an array of {text, highlight} objects.
18309 fn copy_highlight_json(
18310 &mut self,
18311 _: &CopyHighlightJson,
18312 window: &mut Window,
18313 cx: &mut Context<Self>,
18314 ) {
18315 #[derive(Serialize)]
18316 struct Chunk<'a> {
18317 text: String,
18318 highlight: Option<&'a str>,
18319 }
18320
18321 let snapshot = self.buffer.read(cx).snapshot(cx);
18322 let range = self
18323 .selected_text_range(false, window, cx)
18324 .and_then(|selection| {
18325 if selection.range.is_empty() {
18326 None
18327 } else {
18328 Some(selection.range)
18329 }
18330 })
18331 .unwrap_or_else(|| 0..snapshot.len());
18332
18333 let chunks = snapshot.chunks(range, true);
18334 let mut lines = Vec::new();
18335 let mut line: VecDeque<Chunk> = VecDeque::new();
18336
18337 let Some(style) = self.style.as_ref() else {
18338 return;
18339 };
18340
18341 for chunk in chunks {
18342 let highlight = chunk
18343 .syntax_highlight_id
18344 .and_then(|id| id.name(&style.syntax));
18345 let mut chunk_lines = chunk.text.split('\n').peekable();
18346 while let Some(text) = chunk_lines.next() {
18347 let mut merged_with_last_token = false;
18348 if let Some(last_token) = line.back_mut() {
18349 if last_token.highlight == highlight {
18350 last_token.text.push_str(text);
18351 merged_with_last_token = true;
18352 }
18353 }
18354
18355 if !merged_with_last_token {
18356 line.push_back(Chunk {
18357 text: text.into(),
18358 highlight,
18359 });
18360 }
18361
18362 if chunk_lines.peek().is_some() {
18363 if line.len() > 1 && line.front().unwrap().text.is_empty() {
18364 line.pop_front();
18365 }
18366 if line.len() > 1 && line.back().unwrap().text.is_empty() {
18367 line.pop_back();
18368 }
18369
18370 lines.push(mem::take(&mut line));
18371 }
18372 }
18373 }
18374
18375 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18376 return;
18377 };
18378 cx.write_to_clipboard(ClipboardItem::new_string(lines));
18379 }
18380
18381 pub fn open_context_menu(
18382 &mut self,
18383 _: &OpenContextMenu,
18384 window: &mut Window,
18385 cx: &mut Context<Self>,
18386 ) {
18387 self.request_autoscroll(Autoscroll::newest(), cx);
18388 let position = self.selections.newest_display(cx).start;
18389 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18390 }
18391
18392 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18393 &self.inlay_hint_cache
18394 }
18395
18396 pub fn replay_insert_event(
18397 &mut self,
18398 text: &str,
18399 relative_utf16_range: Option<Range<isize>>,
18400 window: &mut Window,
18401 cx: &mut Context<Self>,
18402 ) {
18403 if !self.input_enabled {
18404 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18405 return;
18406 }
18407 if let Some(relative_utf16_range) = relative_utf16_range {
18408 let selections = self.selections.all::<OffsetUtf16>(cx);
18409 self.change_selections(None, window, cx, |s| {
18410 let new_ranges = selections.into_iter().map(|range| {
18411 let start = OffsetUtf16(
18412 range
18413 .head()
18414 .0
18415 .saturating_add_signed(relative_utf16_range.start),
18416 );
18417 let end = OffsetUtf16(
18418 range
18419 .head()
18420 .0
18421 .saturating_add_signed(relative_utf16_range.end),
18422 );
18423 start..end
18424 });
18425 s.select_ranges(new_ranges);
18426 });
18427 }
18428
18429 self.handle_input(text, window, cx);
18430 }
18431
18432 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18433 let Some(provider) = self.semantics_provider.as_ref() else {
18434 return false;
18435 };
18436
18437 let mut supports = false;
18438 self.buffer().update(cx, |this, cx| {
18439 this.for_each_buffer(|buffer| {
18440 supports |= provider.supports_inlay_hints(buffer, cx);
18441 });
18442 });
18443
18444 supports
18445 }
18446
18447 pub fn is_focused(&self, window: &Window) -> bool {
18448 self.focus_handle.is_focused(window)
18449 }
18450
18451 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18452 cx.emit(EditorEvent::Focused);
18453
18454 if let Some(descendant) = self
18455 .last_focused_descendant
18456 .take()
18457 .and_then(|descendant| descendant.upgrade())
18458 {
18459 window.focus(&descendant);
18460 } else {
18461 if let Some(blame) = self.blame.as_ref() {
18462 blame.update(cx, GitBlame::focus)
18463 }
18464
18465 self.blink_manager.update(cx, BlinkManager::enable);
18466 self.show_cursor_names(window, cx);
18467 self.buffer.update(cx, |buffer, cx| {
18468 buffer.finalize_last_transaction(cx);
18469 if self.leader_peer_id.is_none() {
18470 buffer.set_active_selections(
18471 &self.selections.disjoint_anchors(),
18472 self.selections.line_mode,
18473 self.cursor_shape,
18474 cx,
18475 );
18476 }
18477 });
18478 }
18479 }
18480
18481 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18482 cx.emit(EditorEvent::FocusedIn)
18483 }
18484
18485 fn handle_focus_out(
18486 &mut self,
18487 event: FocusOutEvent,
18488 _window: &mut Window,
18489 cx: &mut Context<Self>,
18490 ) {
18491 if event.blurred != self.focus_handle {
18492 self.last_focused_descendant = Some(event.blurred);
18493 }
18494 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18495 }
18496
18497 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18498 self.blink_manager.update(cx, BlinkManager::disable);
18499 self.buffer
18500 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18501
18502 if let Some(blame) = self.blame.as_ref() {
18503 blame.update(cx, GitBlame::blur)
18504 }
18505 if !self.hover_state.focused(window, cx) {
18506 hide_hover(self, cx);
18507 }
18508 if !self
18509 .context_menu
18510 .borrow()
18511 .as_ref()
18512 .is_some_and(|context_menu| context_menu.focused(window, cx))
18513 {
18514 self.hide_context_menu(window, cx);
18515 }
18516 self.discard_inline_completion(false, cx);
18517 cx.emit(EditorEvent::Blurred);
18518 cx.notify();
18519 }
18520
18521 pub fn register_action<A: Action>(
18522 &mut self,
18523 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18524 ) -> Subscription {
18525 let id = self.next_editor_action_id.post_inc();
18526 let listener = Arc::new(listener);
18527 self.editor_actions.borrow_mut().insert(
18528 id,
18529 Box::new(move |window, _| {
18530 let listener = listener.clone();
18531 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18532 let action = action.downcast_ref().unwrap();
18533 if phase == DispatchPhase::Bubble {
18534 listener(action, window, cx)
18535 }
18536 })
18537 }),
18538 );
18539
18540 let editor_actions = self.editor_actions.clone();
18541 Subscription::new(move || {
18542 editor_actions.borrow_mut().remove(&id);
18543 })
18544 }
18545
18546 pub fn file_header_size(&self) -> u32 {
18547 FILE_HEADER_HEIGHT
18548 }
18549
18550 pub fn restore(
18551 &mut self,
18552 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18553 window: &mut Window,
18554 cx: &mut Context<Self>,
18555 ) {
18556 let workspace = self.workspace();
18557 let project = self.project.as_ref();
18558 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18559 let mut tasks = Vec::new();
18560 for (buffer_id, changes) in revert_changes {
18561 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18562 buffer.update(cx, |buffer, cx| {
18563 buffer.edit(
18564 changes
18565 .into_iter()
18566 .map(|(range, text)| (range, text.to_string())),
18567 None,
18568 cx,
18569 );
18570 });
18571
18572 if let Some(project) =
18573 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18574 {
18575 project.update(cx, |project, cx| {
18576 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18577 })
18578 }
18579 }
18580 }
18581 tasks
18582 });
18583 cx.spawn_in(window, async move |_, cx| {
18584 for (buffer, task) in save_tasks {
18585 let result = task.await;
18586 if result.is_err() {
18587 let Some(path) = buffer
18588 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18589 .ok()
18590 else {
18591 continue;
18592 };
18593 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18594 let Some(task) = cx
18595 .update_window_entity(&workspace, |workspace, window, cx| {
18596 workspace
18597 .open_path_preview(path, None, false, false, false, window, cx)
18598 })
18599 .ok()
18600 else {
18601 continue;
18602 };
18603 task.await.log_err();
18604 }
18605 }
18606 }
18607 })
18608 .detach();
18609 self.change_selections(None, window, cx, |selections| selections.refresh());
18610 }
18611
18612 pub fn to_pixel_point(
18613 &self,
18614 source: multi_buffer::Anchor,
18615 editor_snapshot: &EditorSnapshot,
18616 window: &mut Window,
18617 ) -> Option<gpui::Point<Pixels>> {
18618 let source_point = source.to_display_point(editor_snapshot);
18619 self.display_to_pixel_point(source_point, editor_snapshot, window)
18620 }
18621
18622 pub fn display_to_pixel_point(
18623 &self,
18624 source: DisplayPoint,
18625 editor_snapshot: &EditorSnapshot,
18626 window: &mut Window,
18627 ) -> Option<gpui::Point<Pixels>> {
18628 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18629 let text_layout_details = self.text_layout_details(window);
18630 let scroll_top = text_layout_details
18631 .scroll_anchor
18632 .scroll_position(editor_snapshot)
18633 .y;
18634
18635 if source.row().as_f32() < scroll_top.floor() {
18636 return None;
18637 }
18638 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18639 let source_y = line_height * (source.row().as_f32() - scroll_top);
18640 Some(gpui::Point::new(source_x, source_y))
18641 }
18642
18643 pub fn has_visible_completions_menu(&self) -> bool {
18644 !self.edit_prediction_preview_is_active()
18645 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18646 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18647 })
18648 }
18649
18650 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18651 self.addons
18652 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18653 }
18654
18655 pub fn unregister_addon<T: Addon>(&mut self) {
18656 self.addons.remove(&std::any::TypeId::of::<T>());
18657 }
18658
18659 pub fn addon<T: Addon>(&self) -> Option<&T> {
18660 let type_id = std::any::TypeId::of::<T>();
18661 self.addons
18662 .get(&type_id)
18663 .and_then(|item| item.to_any().downcast_ref::<T>())
18664 }
18665
18666 pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18667 let type_id = std::any::TypeId::of::<T>();
18668 self.addons
18669 .get_mut(&type_id)
18670 .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18671 }
18672
18673 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18674 let text_layout_details = self.text_layout_details(window);
18675 let style = &text_layout_details.editor_style;
18676 let font_id = window.text_system().resolve_font(&style.text.font());
18677 let font_size = style.text.font_size.to_pixels(window.rem_size());
18678 let line_height = style.text.line_height_in_pixels(window.rem_size());
18679 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18680
18681 gpui::Size::new(em_width, line_height)
18682 }
18683
18684 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18685 self.load_diff_task.clone()
18686 }
18687
18688 fn read_metadata_from_db(
18689 &mut self,
18690 item_id: u64,
18691 workspace_id: WorkspaceId,
18692 window: &mut Window,
18693 cx: &mut Context<Editor>,
18694 ) {
18695 if self.is_singleton(cx)
18696 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18697 {
18698 let buffer_snapshot = OnceCell::new();
18699
18700 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18701 if !folds.is_empty() {
18702 let snapshot =
18703 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18704 self.fold_ranges(
18705 folds
18706 .into_iter()
18707 .map(|(start, end)| {
18708 snapshot.clip_offset(start, Bias::Left)
18709 ..snapshot.clip_offset(end, Bias::Right)
18710 })
18711 .collect(),
18712 false,
18713 window,
18714 cx,
18715 );
18716 }
18717 }
18718
18719 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18720 if !selections.is_empty() {
18721 let snapshot =
18722 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18723 self.change_selections(None, window, cx, |s| {
18724 s.select_ranges(selections.into_iter().map(|(start, end)| {
18725 snapshot.clip_offset(start, Bias::Left)
18726 ..snapshot.clip_offset(end, Bias::Right)
18727 }));
18728 });
18729 }
18730 };
18731 }
18732
18733 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18734 }
18735}
18736
18737fn vim_enabled(cx: &App) -> bool {
18738 cx.global::<SettingsStore>()
18739 .raw_user_settings()
18740 .get("vim_mode")
18741 == Some(&serde_json::Value::Bool(true))
18742}
18743
18744// Consider user intent and default settings
18745fn choose_completion_range(
18746 completion: &Completion,
18747 intent: CompletionIntent,
18748 buffer: &Entity<Buffer>,
18749 cx: &mut Context<Editor>,
18750) -> Range<usize> {
18751 fn should_replace(
18752 completion: &Completion,
18753 insert_range: &Range<text::Anchor>,
18754 intent: CompletionIntent,
18755 completion_mode_setting: LspInsertMode,
18756 buffer: &Buffer,
18757 ) -> bool {
18758 // specific actions take precedence over settings
18759 match intent {
18760 CompletionIntent::CompleteWithInsert => return false,
18761 CompletionIntent::CompleteWithReplace => return true,
18762 CompletionIntent::Complete | CompletionIntent::Compose => {}
18763 }
18764
18765 match completion_mode_setting {
18766 LspInsertMode::Insert => false,
18767 LspInsertMode::Replace => true,
18768 LspInsertMode::ReplaceSubsequence => {
18769 let mut text_to_replace = buffer.chars_for_range(
18770 buffer.anchor_before(completion.replace_range.start)
18771 ..buffer.anchor_after(completion.replace_range.end),
18772 );
18773 let mut completion_text = completion.new_text.chars();
18774
18775 // is `text_to_replace` a subsequence of `completion_text`
18776 text_to_replace
18777 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18778 }
18779 LspInsertMode::ReplaceSuffix => {
18780 let range_after_cursor = insert_range.end..completion.replace_range.end;
18781
18782 let text_after_cursor = buffer
18783 .text_for_range(
18784 buffer.anchor_before(range_after_cursor.start)
18785 ..buffer.anchor_after(range_after_cursor.end),
18786 )
18787 .collect::<String>();
18788 completion.new_text.ends_with(&text_after_cursor)
18789 }
18790 }
18791 }
18792
18793 let buffer = buffer.read(cx);
18794
18795 if let CompletionSource::Lsp {
18796 insert_range: Some(insert_range),
18797 ..
18798 } = &completion.source
18799 {
18800 let completion_mode_setting =
18801 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18802 .completions
18803 .lsp_insert_mode;
18804
18805 if !should_replace(
18806 completion,
18807 &insert_range,
18808 intent,
18809 completion_mode_setting,
18810 buffer,
18811 ) {
18812 return insert_range.to_offset(buffer);
18813 }
18814 }
18815
18816 completion.replace_range.to_offset(buffer)
18817}
18818
18819fn insert_extra_newline_brackets(
18820 buffer: &MultiBufferSnapshot,
18821 range: Range<usize>,
18822 language: &language::LanguageScope,
18823) -> bool {
18824 let leading_whitespace_len = buffer
18825 .reversed_chars_at(range.start)
18826 .take_while(|c| c.is_whitespace() && *c != '\n')
18827 .map(|c| c.len_utf8())
18828 .sum::<usize>();
18829 let trailing_whitespace_len = buffer
18830 .chars_at(range.end)
18831 .take_while(|c| c.is_whitespace() && *c != '\n')
18832 .map(|c| c.len_utf8())
18833 .sum::<usize>();
18834 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18835
18836 language.brackets().any(|(pair, enabled)| {
18837 let pair_start = pair.start.trim_end();
18838 let pair_end = pair.end.trim_start();
18839
18840 enabled
18841 && pair.newline
18842 && buffer.contains_str_at(range.end, pair_end)
18843 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18844 })
18845}
18846
18847fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18848 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18849 [(buffer, range, _)] => (*buffer, range.clone()),
18850 _ => return false,
18851 };
18852 let pair = {
18853 let mut result: Option<BracketMatch> = None;
18854
18855 for pair in buffer
18856 .all_bracket_ranges(range.clone())
18857 .filter(move |pair| {
18858 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18859 })
18860 {
18861 let len = pair.close_range.end - pair.open_range.start;
18862
18863 if let Some(existing) = &result {
18864 let existing_len = existing.close_range.end - existing.open_range.start;
18865 if len > existing_len {
18866 continue;
18867 }
18868 }
18869
18870 result = Some(pair);
18871 }
18872
18873 result
18874 };
18875 let Some(pair) = pair else {
18876 return false;
18877 };
18878 pair.newline_only
18879 && buffer
18880 .chars_for_range(pair.open_range.end..range.start)
18881 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18882 .all(|c| c.is_whitespace() && c != '\n')
18883}
18884
18885fn get_uncommitted_diff_for_buffer(
18886 project: &Entity<Project>,
18887 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18888 buffer: Entity<MultiBuffer>,
18889 cx: &mut App,
18890) -> Task<()> {
18891 let mut tasks = Vec::new();
18892 project.update(cx, |project, cx| {
18893 for buffer in buffers {
18894 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18895 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18896 }
18897 }
18898 });
18899 cx.spawn(async move |cx| {
18900 let diffs = future::join_all(tasks).await;
18901 buffer
18902 .update(cx, |buffer, cx| {
18903 for diff in diffs.into_iter().flatten() {
18904 buffer.add_diff(diff, cx);
18905 }
18906 })
18907 .ok();
18908 })
18909}
18910
18911fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18912 let tab_size = tab_size.get() as usize;
18913 let mut width = offset;
18914
18915 for ch in text.chars() {
18916 width += if ch == '\t' {
18917 tab_size - (width % tab_size)
18918 } else {
18919 1
18920 };
18921 }
18922
18923 width - offset
18924}
18925
18926#[cfg(test)]
18927mod tests {
18928 use super::*;
18929
18930 #[test]
18931 fn test_string_size_with_expanded_tabs() {
18932 let nz = |val| NonZeroU32::new(val).unwrap();
18933 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18934 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18935 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18936 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18937 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18938 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18939 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18940 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18941 }
18942}
18943
18944/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18945struct WordBreakingTokenizer<'a> {
18946 input: &'a str,
18947}
18948
18949impl<'a> WordBreakingTokenizer<'a> {
18950 fn new(input: &'a str) -> Self {
18951 Self { input }
18952 }
18953}
18954
18955fn is_char_ideographic(ch: char) -> bool {
18956 use unicode_script::Script::*;
18957 use unicode_script::UnicodeScript;
18958 matches!(ch.script(), Han | Tangut | Yi)
18959}
18960
18961fn is_grapheme_ideographic(text: &str) -> bool {
18962 text.chars().any(is_char_ideographic)
18963}
18964
18965fn is_grapheme_whitespace(text: &str) -> bool {
18966 text.chars().any(|x| x.is_whitespace())
18967}
18968
18969fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18970 text.chars().next().map_or(false, |ch| {
18971 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18972 })
18973}
18974
18975#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18976enum WordBreakToken<'a> {
18977 Word { token: &'a str, grapheme_len: usize },
18978 InlineWhitespace { token: &'a str, grapheme_len: usize },
18979 Newline,
18980}
18981
18982impl<'a> Iterator for WordBreakingTokenizer<'a> {
18983 /// Yields a span, the count of graphemes in the token, and whether it was
18984 /// whitespace. Note that it also breaks at word boundaries.
18985 type Item = WordBreakToken<'a>;
18986
18987 fn next(&mut self) -> Option<Self::Item> {
18988 use unicode_segmentation::UnicodeSegmentation;
18989 if self.input.is_empty() {
18990 return None;
18991 }
18992
18993 let mut iter = self.input.graphemes(true).peekable();
18994 let mut offset = 0;
18995 let mut grapheme_len = 0;
18996 if let Some(first_grapheme) = iter.next() {
18997 let is_newline = first_grapheme == "\n";
18998 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18999 offset += first_grapheme.len();
19000 grapheme_len += 1;
19001 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19002 if let Some(grapheme) = iter.peek().copied() {
19003 if should_stay_with_preceding_ideograph(grapheme) {
19004 offset += grapheme.len();
19005 grapheme_len += 1;
19006 }
19007 }
19008 } else {
19009 let mut words = self.input[offset..].split_word_bound_indices().peekable();
19010 let mut next_word_bound = words.peek().copied();
19011 if next_word_bound.map_or(false, |(i, _)| i == 0) {
19012 next_word_bound = words.next();
19013 }
19014 while let Some(grapheme) = iter.peek().copied() {
19015 if next_word_bound.map_or(false, |(i, _)| i == offset) {
19016 break;
19017 };
19018 if is_grapheme_whitespace(grapheme) != is_whitespace
19019 || (grapheme == "\n") != is_newline
19020 {
19021 break;
19022 };
19023 offset += grapheme.len();
19024 grapheme_len += 1;
19025 iter.next();
19026 }
19027 }
19028 let token = &self.input[..offset];
19029 self.input = &self.input[offset..];
19030 if token == "\n" {
19031 Some(WordBreakToken::Newline)
19032 } else if is_whitespace {
19033 Some(WordBreakToken::InlineWhitespace {
19034 token,
19035 grapheme_len,
19036 })
19037 } else {
19038 Some(WordBreakToken::Word {
19039 token,
19040 grapheme_len,
19041 })
19042 }
19043 } else {
19044 None
19045 }
19046 }
19047}
19048
19049#[test]
19050fn test_word_breaking_tokenizer() {
19051 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19052 ("", &[]),
19053 (" ", &[whitespace(" ", 2)]),
19054 ("Ʒ", &[word("Ʒ", 1)]),
19055 ("Ǽ", &[word("Ǽ", 1)]),
19056 ("⋑", &[word("⋑", 1)]),
19057 ("⋑⋑", &[word("⋑⋑", 2)]),
19058 (
19059 "原理,进而",
19060 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
19061 ),
19062 (
19063 "hello world",
19064 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19065 ),
19066 (
19067 "hello, world",
19068 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19069 ),
19070 (
19071 " hello world",
19072 &[
19073 whitespace(" ", 2),
19074 word("hello", 5),
19075 whitespace(" ", 1),
19076 word("world", 5),
19077 ],
19078 ),
19079 (
19080 "这是什么 \n 钢笔",
19081 &[
19082 word("这", 1),
19083 word("是", 1),
19084 word("什", 1),
19085 word("么", 1),
19086 whitespace(" ", 1),
19087 newline(),
19088 whitespace(" ", 1),
19089 word("钢", 1),
19090 word("笔", 1),
19091 ],
19092 ),
19093 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
19094 ];
19095
19096 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19097 WordBreakToken::Word {
19098 token,
19099 grapheme_len,
19100 }
19101 }
19102
19103 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19104 WordBreakToken::InlineWhitespace {
19105 token,
19106 grapheme_len,
19107 }
19108 }
19109
19110 fn newline() -> WordBreakToken<'static> {
19111 WordBreakToken::Newline
19112 }
19113
19114 for (input, result) in tests {
19115 assert_eq!(
19116 WordBreakingTokenizer::new(input)
19117 .collect::<Vec<_>>()
19118 .as_slice(),
19119 *result,
19120 );
19121 }
19122}
19123
19124fn wrap_with_prefix(
19125 line_prefix: String,
19126 unwrapped_text: String,
19127 wrap_column: usize,
19128 tab_size: NonZeroU32,
19129 preserve_existing_whitespace: bool,
19130) -> String {
19131 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19132 let mut wrapped_text = String::new();
19133 let mut current_line = line_prefix.clone();
19134
19135 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19136 let mut current_line_len = line_prefix_len;
19137 let mut in_whitespace = false;
19138 for token in tokenizer {
19139 let have_preceding_whitespace = in_whitespace;
19140 match token {
19141 WordBreakToken::Word {
19142 token,
19143 grapheme_len,
19144 } => {
19145 in_whitespace = false;
19146 if current_line_len + grapheme_len > wrap_column
19147 && current_line_len != line_prefix_len
19148 {
19149 wrapped_text.push_str(current_line.trim_end());
19150 wrapped_text.push('\n');
19151 current_line.truncate(line_prefix.len());
19152 current_line_len = line_prefix_len;
19153 }
19154 current_line.push_str(token);
19155 current_line_len += grapheme_len;
19156 }
19157 WordBreakToken::InlineWhitespace {
19158 mut token,
19159 mut grapheme_len,
19160 } => {
19161 in_whitespace = true;
19162 if have_preceding_whitespace && !preserve_existing_whitespace {
19163 continue;
19164 }
19165 if !preserve_existing_whitespace {
19166 token = " ";
19167 grapheme_len = 1;
19168 }
19169 if current_line_len + grapheme_len > wrap_column {
19170 wrapped_text.push_str(current_line.trim_end());
19171 wrapped_text.push('\n');
19172 current_line.truncate(line_prefix.len());
19173 current_line_len = line_prefix_len;
19174 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19175 current_line.push_str(token);
19176 current_line_len += grapheme_len;
19177 }
19178 }
19179 WordBreakToken::Newline => {
19180 in_whitespace = true;
19181 if preserve_existing_whitespace {
19182 wrapped_text.push_str(current_line.trim_end());
19183 wrapped_text.push('\n');
19184 current_line.truncate(line_prefix.len());
19185 current_line_len = line_prefix_len;
19186 } else if have_preceding_whitespace {
19187 continue;
19188 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19189 {
19190 wrapped_text.push_str(current_line.trim_end());
19191 wrapped_text.push('\n');
19192 current_line.truncate(line_prefix.len());
19193 current_line_len = line_prefix_len;
19194 } else if current_line_len != line_prefix_len {
19195 current_line.push(' ');
19196 current_line_len += 1;
19197 }
19198 }
19199 }
19200 }
19201
19202 if !current_line.is_empty() {
19203 wrapped_text.push_str(¤t_line);
19204 }
19205 wrapped_text
19206}
19207
19208#[test]
19209fn test_wrap_with_prefix() {
19210 assert_eq!(
19211 wrap_with_prefix(
19212 "# ".to_string(),
19213 "abcdefg".to_string(),
19214 4,
19215 NonZeroU32::new(4).unwrap(),
19216 false,
19217 ),
19218 "# abcdefg"
19219 );
19220 assert_eq!(
19221 wrap_with_prefix(
19222 "".to_string(),
19223 "\thello world".to_string(),
19224 8,
19225 NonZeroU32::new(4).unwrap(),
19226 false,
19227 ),
19228 "hello\nworld"
19229 );
19230 assert_eq!(
19231 wrap_with_prefix(
19232 "// ".to_string(),
19233 "xx \nyy zz aa bb cc".to_string(),
19234 12,
19235 NonZeroU32::new(4).unwrap(),
19236 false,
19237 ),
19238 "// xx yy zz\n// aa bb cc"
19239 );
19240 assert_eq!(
19241 wrap_with_prefix(
19242 String::new(),
19243 "这是什么 \n 钢笔".to_string(),
19244 3,
19245 NonZeroU32::new(4).unwrap(),
19246 false,
19247 ),
19248 "这是什\n么 钢\n笔"
19249 );
19250}
19251
19252pub trait CollaborationHub {
19253 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19254 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19255 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19256}
19257
19258impl CollaborationHub for Entity<Project> {
19259 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19260 self.read(cx).collaborators()
19261 }
19262
19263 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19264 self.read(cx).user_store().read(cx).participant_indices()
19265 }
19266
19267 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19268 let this = self.read(cx);
19269 let user_ids = this.collaborators().values().map(|c| c.user_id);
19270 this.user_store().read_with(cx, |user_store, cx| {
19271 user_store.participant_names(user_ids, cx)
19272 })
19273 }
19274}
19275
19276pub trait SemanticsProvider {
19277 fn hover(
19278 &self,
19279 buffer: &Entity<Buffer>,
19280 position: text::Anchor,
19281 cx: &mut App,
19282 ) -> Option<Task<Vec<project::Hover>>>;
19283
19284 fn inline_values(
19285 &self,
19286 buffer_handle: Entity<Buffer>,
19287 range: Range<text::Anchor>,
19288 cx: &mut App,
19289 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19290
19291 fn inlay_hints(
19292 &self,
19293 buffer_handle: Entity<Buffer>,
19294 range: Range<text::Anchor>,
19295 cx: &mut App,
19296 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19297
19298 fn resolve_inlay_hint(
19299 &self,
19300 hint: InlayHint,
19301 buffer_handle: Entity<Buffer>,
19302 server_id: LanguageServerId,
19303 cx: &mut App,
19304 ) -> Option<Task<anyhow::Result<InlayHint>>>;
19305
19306 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19307
19308 fn document_highlights(
19309 &self,
19310 buffer: &Entity<Buffer>,
19311 position: text::Anchor,
19312 cx: &mut App,
19313 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19314
19315 fn definitions(
19316 &self,
19317 buffer: &Entity<Buffer>,
19318 position: text::Anchor,
19319 kind: GotoDefinitionKind,
19320 cx: &mut App,
19321 ) -> Option<Task<Result<Vec<LocationLink>>>>;
19322
19323 fn range_for_rename(
19324 &self,
19325 buffer: &Entity<Buffer>,
19326 position: text::Anchor,
19327 cx: &mut App,
19328 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19329
19330 fn perform_rename(
19331 &self,
19332 buffer: &Entity<Buffer>,
19333 position: text::Anchor,
19334 new_name: String,
19335 cx: &mut App,
19336 ) -> Option<Task<Result<ProjectTransaction>>>;
19337}
19338
19339pub trait CompletionProvider {
19340 fn completions(
19341 &self,
19342 excerpt_id: ExcerptId,
19343 buffer: &Entity<Buffer>,
19344 buffer_position: text::Anchor,
19345 trigger: CompletionContext,
19346 window: &mut Window,
19347 cx: &mut Context<Editor>,
19348 ) -> Task<Result<Option<Vec<Completion>>>>;
19349
19350 fn resolve_completions(
19351 &self,
19352 buffer: Entity<Buffer>,
19353 completion_indices: Vec<usize>,
19354 completions: Rc<RefCell<Box<[Completion]>>>,
19355 cx: &mut Context<Editor>,
19356 ) -> Task<Result<bool>>;
19357
19358 fn apply_additional_edits_for_completion(
19359 &self,
19360 _buffer: Entity<Buffer>,
19361 _completions: Rc<RefCell<Box<[Completion]>>>,
19362 _completion_index: usize,
19363 _push_to_history: bool,
19364 _cx: &mut Context<Editor>,
19365 ) -> Task<Result<Option<language::Transaction>>> {
19366 Task::ready(Ok(None))
19367 }
19368
19369 fn is_completion_trigger(
19370 &self,
19371 buffer: &Entity<Buffer>,
19372 position: language::Anchor,
19373 text: &str,
19374 trigger_in_words: bool,
19375 cx: &mut Context<Editor>,
19376 ) -> bool;
19377
19378 fn sort_completions(&self) -> bool {
19379 true
19380 }
19381
19382 fn filter_completions(&self) -> bool {
19383 true
19384 }
19385}
19386
19387pub trait CodeActionProvider {
19388 fn id(&self) -> Arc<str>;
19389
19390 fn code_actions(
19391 &self,
19392 buffer: &Entity<Buffer>,
19393 range: Range<text::Anchor>,
19394 window: &mut Window,
19395 cx: &mut App,
19396 ) -> Task<Result<Vec<CodeAction>>>;
19397
19398 fn apply_code_action(
19399 &self,
19400 buffer_handle: Entity<Buffer>,
19401 action: CodeAction,
19402 excerpt_id: ExcerptId,
19403 push_to_history: bool,
19404 window: &mut Window,
19405 cx: &mut App,
19406 ) -> Task<Result<ProjectTransaction>>;
19407}
19408
19409impl CodeActionProvider for Entity<Project> {
19410 fn id(&self) -> Arc<str> {
19411 "project".into()
19412 }
19413
19414 fn code_actions(
19415 &self,
19416 buffer: &Entity<Buffer>,
19417 range: Range<text::Anchor>,
19418 _window: &mut Window,
19419 cx: &mut App,
19420 ) -> Task<Result<Vec<CodeAction>>> {
19421 self.update(cx, |project, cx| {
19422 let code_lens = project.code_lens(buffer, range.clone(), cx);
19423 let code_actions = project.code_actions(buffer, range, None, cx);
19424 cx.background_spawn(async move {
19425 let (code_lens, code_actions) = join(code_lens, code_actions).await;
19426 Ok(code_lens
19427 .context("code lens fetch")?
19428 .into_iter()
19429 .chain(code_actions.context("code action fetch")?)
19430 .collect())
19431 })
19432 })
19433 }
19434
19435 fn apply_code_action(
19436 &self,
19437 buffer_handle: Entity<Buffer>,
19438 action: CodeAction,
19439 _excerpt_id: ExcerptId,
19440 push_to_history: bool,
19441 _window: &mut Window,
19442 cx: &mut App,
19443 ) -> Task<Result<ProjectTransaction>> {
19444 self.update(cx, |project, cx| {
19445 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19446 })
19447 }
19448}
19449
19450fn snippet_completions(
19451 project: &Project,
19452 buffer: &Entity<Buffer>,
19453 buffer_position: text::Anchor,
19454 cx: &mut App,
19455) -> Task<Result<Vec<Completion>>> {
19456 let languages = buffer.read(cx).languages_at(buffer_position);
19457 let snippet_store = project.snippets().read(cx);
19458
19459 let scopes: Vec<_> = languages
19460 .iter()
19461 .filter_map(|language| {
19462 let language_name = language.lsp_id();
19463 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19464
19465 if snippets.is_empty() {
19466 None
19467 } else {
19468 Some((language.default_scope(), snippets))
19469 }
19470 })
19471 .collect();
19472
19473 if scopes.is_empty() {
19474 return Task::ready(Ok(vec![]));
19475 }
19476
19477 let snapshot = buffer.read(cx).text_snapshot();
19478 let chars: String = snapshot
19479 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19480 .collect();
19481 let executor = cx.background_executor().clone();
19482
19483 cx.background_spawn(async move {
19484 let mut all_results: Vec<Completion> = Vec::new();
19485 for (scope, snippets) in scopes.into_iter() {
19486 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19487 let mut last_word = chars
19488 .chars()
19489 .take_while(|c| classifier.is_word(*c))
19490 .collect::<String>();
19491 last_word = last_word.chars().rev().collect();
19492
19493 if last_word.is_empty() {
19494 return Ok(vec![]);
19495 }
19496
19497 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19498 let to_lsp = |point: &text::Anchor| {
19499 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19500 point_to_lsp(end)
19501 };
19502 let lsp_end = to_lsp(&buffer_position);
19503
19504 let candidates = snippets
19505 .iter()
19506 .enumerate()
19507 .flat_map(|(ix, snippet)| {
19508 snippet
19509 .prefix
19510 .iter()
19511 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19512 })
19513 .collect::<Vec<StringMatchCandidate>>();
19514
19515 let mut matches = fuzzy::match_strings(
19516 &candidates,
19517 &last_word,
19518 last_word.chars().any(|c| c.is_uppercase()),
19519 100,
19520 &Default::default(),
19521 executor.clone(),
19522 )
19523 .await;
19524
19525 // Remove all candidates where the query's start does not match the start of any word in the candidate
19526 if let Some(query_start) = last_word.chars().next() {
19527 matches.retain(|string_match| {
19528 split_words(&string_match.string).any(|word| {
19529 // Check that the first codepoint of the word as lowercase matches the first
19530 // codepoint of the query as lowercase
19531 word.chars()
19532 .flat_map(|codepoint| codepoint.to_lowercase())
19533 .zip(query_start.to_lowercase())
19534 .all(|(word_cp, query_cp)| word_cp == query_cp)
19535 })
19536 });
19537 }
19538
19539 let matched_strings = matches
19540 .into_iter()
19541 .map(|m| m.string)
19542 .collect::<HashSet<_>>();
19543
19544 let mut result: Vec<Completion> = snippets
19545 .iter()
19546 .filter_map(|snippet| {
19547 let matching_prefix = snippet
19548 .prefix
19549 .iter()
19550 .find(|prefix| matched_strings.contains(*prefix))?;
19551 let start = as_offset - last_word.len();
19552 let start = snapshot.anchor_before(start);
19553 let range = start..buffer_position;
19554 let lsp_start = to_lsp(&start);
19555 let lsp_range = lsp::Range {
19556 start: lsp_start,
19557 end: lsp_end,
19558 };
19559 Some(Completion {
19560 replace_range: range,
19561 new_text: snippet.body.clone(),
19562 source: CompletionSource::Lsp {
19563 insert_range: None,
19564 server_id: LanguageServerId(usize::MAX),
19565 resolved: true,
19566 lsp_completion: Box::new(lsp::CompletionItem {
19567 label: snippet.prefix.first().unwrap().clone(),
19568 kind: Some(CompletionItemKind::SNIPPET),
19569 label_details: snippet.description.as_ref().map(|description| {
19570 lsp::CompletionItemLabelDetails {
19571 detail: Some(description.clone()),
19572 description: None,
19573 }
19574 }),
19575 insert_text_format: Some(InsertTextFormat::SNIPPET),
19576 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19577 lsp::InsertReplaceEdit {
19578 new_text: snippet.body.clone(),
19579 insert: lsp_range,
19580 replace: lsp_range,
19581 },
19582 )),
19583 filter_text: Some(snippet.body.clone()),
19584 sort_text: Some(char::MAX.to_string()),
19585 ..lsp::CompletionItem::default()
19586 }),
19587 lsp_defaults: None,
19588 },
19589 label: CodeLabel {
19590 text: matching_prefix.clone(),
19591 runs: Vec::new(),
19592 filter_range: 0..matching_prefix.len(),
19593 },
19594 icon_path: None,
19595 documentation: snippet.description.clone().map(|description| {
19596 CompletionDocumentation::SingleLine(description.into())
19597 }),
19598 insert_text_mode: None,
19599 confirm: None,
19600 })
19601 })
19602 .collect();
19603
19604 all_results.append(&mut result);
19605 }
19606
19607 Ok(all_results)
19608 })
19609}
19610
19611impl CompletionProvider for Entity<Project> {
19612 fn completions(
19613 &self,
19614 _excerpt_id: ExcerptId,
19615 buffer: &Entity<Buffer>,
19616 buffer_position: text::Anchor,
19617 options: CompletionContext,
19618 _window: &mut Window,
19619 cx: &mut Context<Editor>,
19620 ) -> Task<Result<Option<Vec<Completion>>>> {
19621 self.update(cx, |project, cx| {
19622 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19623 let project_completions = project.completions(buffer, buffer_position, options, cx);
19624 cx.background_spawn(async move {
19625 let snippets_completions = snippets.await?;
19626 match project_completions.await? {
19627 Some(mut completions) => {
19628 completions.extend(snippets_completions);
19629 Ok(Some(completions))
19630 }
19631 None => {
19632 if snippets_completions.is_empty() {
19633 Ok(None)
19634 } else {
19635 Ok(Some(snippets_completions))
19636 }
19637 }
19638 }
19639 })
19640 })
19641 }
19642
19643 fn resolve_completions(
19644 &self,
19645 buffer: Entity<Buffer>,
19646 completion_indices: Vec<usize>,
19647 completions: Rc<RefCell<Box<[Completion]>>>,
19648 cx: &mut Context<Editor>,
19649 ) -> Task<Result<bool>> {
19650 self.update(cx, |project, cx| {
19651 project.lsp_store().update(cx, |lsp_store, cx| {
19652 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19653 })
19654 })
19655 }
19656
19657 fn apply_additional_edits_for_completion(
19658 &self,
19659 buffer: Entity<Buffer>,
19660 completions: Rc<RefCell<Box<[Completion]>>>,
19661 completion_index: usize,
19662 push_to_history: bool,
19663 cx: &mut Context<Editor>,
19664 ) -> Task<Result<Option<language::Transaction>>> {
19665 self.update(cx, |project, cx| {
19666 project.lsp_store().update(cx, |lsp_store, cx| {
19667 lsp_store.apply_additional_edits_for_completion(
19668 buffer,
19669 completions,
19670 completion_index,
19671 push_to_history,
19672 cx,
19673 )
19674 })
19675 })
19676 }
19677
19678 fn is_completion_trigger(
19679 &self,
19680 buffer: &Entity<Buffer>,
19681 position: language::Anchor,
19682 text: &str,
19683 trigger_in_words: bool,
19684 cx: &mut Context<Editor>,
19685 ) -> bool {
19686 let mut chars = text.chars();
19687 let char = if let Some(char) = chars.next() {
19688 char
19689 } else {
19690 return false;
19691 };
19692 if chars.next().is_some() {
19693 return false;
19694 }
19695
19696 let buffer = buffer.read(cx);
19697 let snapshot = buffer.snapshot();
19698 if !snapshot.settings_at(position, cx).show_completions_on_input {
19699 return false;
19700 }
19701 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19702 if trigger_in_words && classifier.is_word(char) {
19703 return true;
19704 }
19705
19706 buffer.completion_triggers().contains(text)
19707 }
19708}
19709
19710impl SemanticsProvider for Entity<Project> {
19711 fn hover(
19712 &self,
19713 buffer: &Entity<Buffer>,
19714 position: text::Anchor,
19715 cx: &mut App,
19716 ) -> Option<Task<Vec<project::Hover>>> {
19717 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19718 }
19719
19720 fn document_highlights(
19721 &self,
19722 buffer: &Entity<Buffer>,
19723 position: text::Anchor,
19724 cx: &mut App,
19725 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19726 Some(self.update(cx, |project, cx| {
19727 project.document_highlights(buffer, position, cx)
19728 }))
19729 }
19730
19731 fn definitions(
19732 &self,
19733 buffer: &Entity<Buffer>,
19734 position: text::Anchor,
19735 kind: GotoDefinitionKind,
19736 cx: &mut App,
19737 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19738 Some(self.update(cx, |project, cx| match kind {
19739 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19740 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19741 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19742 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19743 }))
19744 }
19745
19746 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19747 // TODO: make this work for remote projects
19748 self.update(cx, |project, cx| {
19749 if project
19750 .active_debug_session(cx)
19751 .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19752 {
19753 return true;
19754 }
19755
19756 buffer.update(cx, |buffer, cx| {
19757 project.any_language_server_supports_inlay_hints(buffer, cx)
19758 })
19759 })
19760 }
19761
19762 fn inline_values(
19763 &self,
19764 buffer_handle: Entity<Buffer>,
19765 range: Range<text::Anchor>,
19766 cx: &mut App,
19767 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19768 self.update(cx, |project, cx| {
19769 let (session, active_stack_frame) = project.active_debug_session(cx)?;
19770
19771 Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19772 })
19773 }
19774
19775 fn inlay_hints(
19776 &self,
19777 buffer_handle: Entity<Buffer>,
19778 range: Range<text::Anchor>,
19779 cx: &mut App,
19780 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19781 Some(self.update(cx, |project, cx| {
19782 project.inlay_hints(buffer_handle, range, cx)
19783 }))
19784 }
19785
19786 fn resolve_inlay_hint(
19787 &self,
19788 hint: InlayHint,
19789 buffer_handle: Entity<Buffer>,
19790 server_id: LanguageServerId,
19791 cx: &mut App,
19792 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19793 Some(self.update(cx, |project, cx| {
19794 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19795 }))
19796 }
19797
19798 fn range_for_rename(
19799 &self,
19800 buffer: &Entity<Buffer>,
19801 position: text::Anchor,
19802 cx: &mut App,
19803 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19804 Some(self.update(cx, |project, cx| {
19805 let buffer = buffer.clone();
19806 let task = project.prepare_rename(buffer.clone(), position, cx);
19807 cx.spawn(async move |_, cx| {
19808 Ok(match task.await? {
19809 PrepareRenameResponse::Success(range) => Some(range),
19810 PrepareRenameResponse::InvalidPosition => None,
19811 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19812 // Fallback on using TreeSitter info to determine identifier range
19813 buffer.update(cx, |buffer, _| {
19814 let snapshot = buffer.snapshot();
19815 let (range, kind) = snapshot.surrounding_word(position);
19816 if kind != Some(CharKind::Word) {
19817 return None;
19818 }
19819 Some(
19820 snapshot.anchor_before(range.start)
19821 ..snapshot.anchor_after(range.end),
19822 )
19823 })?
19824 }
19825 })
19826 })
19827 }))
19828 }
19829
19830 fn perform_rename(
19831 &self,
19832 buffer: &Entity<Buffer>,
19833 position: text::Anchor,
19834 new_name: String,
19835 cx: &mut App,
19836 ) -> Option<Task<Result<ProjectTransaction>>> {
19837 Some(self.update(cx, |project, cx| {
19838 project.perform_rename(buffer.clone(), position, new_name, cx)
19839 }))
19840 }
19841}
19842
19843fn inlay_hint_settings(
19844 location: Anchor,
19845 snapshot: &MultiBufferSnapshot,
19846 cx: &mut Context<Editor>,
19847) -> InlayHintSettings {
19848 let file = snapshot.file_at(location);
19849 let language = snapshot.language_at(location).map(|l| l.name());
19850 language_settings(language, file, cx).inlay_hints
19851}
19852
19853fn consume_contiguous_rows(
19854 contiguous_row_selections: &mut Vec<Selection<Point>>,
19855 selection: &Selection<Point>,
19856 display_map: &DisplaySnapshot,
19857 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19858) -> (MultiBufferRow, MultiBufferRow) {
19859 contiguous_row_selections.push(selection.clone());
19860 let start_row = MultiBufferRow(selection.start.row);
19861 let mut end_row = ending_row(selection, display_map);
19862
19863 while let Some(next_selection) = selections.peek() {
19864 if next_selection.start.row <= end_row.0 {
19865 end_row = ending_row(next_selection, display_map);
19866 contiguous_row_selections.push(selections.next().unwrap().clone());
19867 } else {
19868 break;
19869 }
19870 }
19871 (start_row, end_row)
19872}
19873
19874fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19875 if next_selection.end.column > 0 || next_selection.is_empty() {
19876 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19877 } else {
19878 MultiBufferRow(next_selection.end.row)
19879 }
19880}
19881
19882impl EditorSnapshot {
19883 pub fn remote_selections_in_range<'a>(
19884 &'a self,
19885 range: &'a Range<Anchor>,
19886 collaboration_hub: &dyn CollaborationHub,
19887 cx: &'a App,
19888 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19889 let participant_names = collaboration_hub.user_names(cx);
19890 let participant_indices = collaboration_hub.user_participant_indices(cx);
19891 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19892 let collaborators_by_replica_id = collaborators_by_peer_id
19893 .iter()
19894 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19895 .collect::<HashMap<_, _>>();
19896 self.buffer_snapshot
19897 .selections_in_range(range, false)
19898 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19899 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19900 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19901 let user_name = participant_names.get(&collaborator.user_id).cloned();
19902 Some(RemoteSelection {
19903 replica_id,
19904 selection,
19905 cursor_shape,
19906 line_mode,
19907 participant_index,
19908 peer_id: collaborator.peer_id,
19909 user_name,
19910 })
19911 })
19912 }
19913
19914 pub fn hunks_for_ranges(
19915 &self,
19916 ranges: impl IntoIterator<Item = Range<Point>>,
19917 ) -> Vec<MultiBufferDiffHunk> {
19918 let mut hunks = Vec::new();
19919 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19920 HashMap::default();
19921 for query_range in ranges {
19922 let query_rows =
19923 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19924 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19925 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19926 ) {
19927 // Include deleted hunks that are adjacent to the query range, because
19928 // otherwise they would be missed.
19929 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19930 if hunk.status().is_deleted() {
19931 intersects_range |= hunk.row_range.start == query_rows.end;
19932 intersects_range |= hunk.row_range.end == query_rows.start;
19933 }
19934 if intersects_range {
19935 if !processed_buffer_rows
19936 .entry(hunk.buffer_id)
19937 .or_default()
19938 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19939 {
19940 continue;
19941 }
19942 hunks.push(hunk);
19943 }
19944 }
19945 }
19946
19947 hunks
19948 }
19949
19950 fn display_diff_hunks_for_rows<'a>(
19951 &'a self,
19952 display_rows: Range<DisplayRow>,
19953 folded_buffers: &'a HashSet<BufferId>,
19954 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19955 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19956 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19957
19958 self.buffer_snapshot
19959 .diff_hunks_in_range(buffer_start..buffer_end)
19960 .filter_map(|hunk| {
19961 if folded_buffers.contains(&hunk.buffer_id) {
19962 return None;
19963 }
19964
19965 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19966 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19967
19968 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19969 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19970
19971 let display_hunk = if hunk_display_start.column() != 0 {
19972 DisplayDiffHunk::Folded {
19973 display_row: hunk_display_start.row(),
19974 }
19975 } else {
19976 let mut end_row = hunk_display_end.row();
19977 if hunk_display_end.column() > 0 {
19978 end_row.0 += 1;
19979 }
19980 let is_created_file = hunk.is_created_file();
19981 DisplayDiffHunk::Unfolded {
19982 status: hunk.status(),
19983 diff_base_byte_range: hunk.diff_base_byte_range,
19984 display_row_range: hunk_display_start.row()..end_row,
19985 multi_buffer_range: Anchor::range_in_buffer(
19986 hunk.excerpt_id,
19987 hunk.buffer_id,
19988 hunk.buffer_range,
19989 ),
19990 is_created_file,
19991 }
19992 };
19993
19994 Some(display_hunk)
19995 })
19996 }
19997
19998 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19999 self.display_snapshot.buffer_snapshot.language_at(position)
20000 }
20001
20002 pub fn is_focused(&self) -> bool {
20003 self.is_focused
20004 }
20005
20006 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20007 self.placeholder_text.as_ref()
20008 }
20009
20010 pub fn scroll_position(&self) -> gpui::Point<f32> {
20011 self.scroll_anchor.scroll_position(&self.display_snapshot)
20012 }
20013
20014 fn gutter_dimensions(
20015 &self,
20016 font_id: FontId,
20017 font_size: Pixels,
20018 max_line_number_width: Pixels,
20019 cx: &App,
20020 ) -> Option<GutterDimensions> {
20021 if !self.show_gutter {
20022 return None;
20023 }
20024
20025 let descent = cx.text_system().descent(font_id, font_size);
20026 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20027 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20028
20029 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20030 matches!(
20031 ProjectSettings::get_global(cx).git.git_gutter,
20032 Some(GitGutterSetting::TrackedFiles)
20033 )
20034 });
20035 let gutter_settings = EditorSettings::get_global(cx).gutter;
20036 let show_line_numbers = self
20037 .show_line_numbers
20038 .unwrap_or(gutter_settings.line_numbers);
20039 let line_gutter_width = if show_line_numbers {
20040 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20041 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20042 max_line_number_width.max(min_width_for_number_on_gutter)
20043 } else {
20044 0.0.into()
20045 };
20046
20047 let show_code_actions = self
20048 .show_code_actions
20049 .unwrap_or(gutter_settings.code_actions);
20050
20051 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20052 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20053
20054 let git_blame_entries_width =
20055 self.git_blame_gutter_max_author_length
20056 .map(|max_author_length| {
20057 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20058 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20059
20060 /// The number of characters to dedicate to gaps and margins.
20061 const SPACING_WIDTH: usize = 4;
20062
20063 let max_char_count = max_author_length.min(renderer.max_author_length())
20064 + ::git::SHORT_SHA_LENGTH
20065 + MAX_RELATIVE_TIMESTAMP.len()
20066 + SPACING_WIDTH;
20067
20068 em_advance * max_char_count
20069 });
20070
20071 let is_singleton = self.buffer_snapshot.is_singleton();
20072
20073 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20074 left_padding += if !is_singleton {
20075 em_width * 4.0
20076 } else if show_code_actions || show_runnables || show_breakpoints {
20077 em_width * 3.0
20078 } else if show_git_gutter && show_line_numbers {
20079 em_width * 2.0
20080 } else if show_git_gutter || show_line_numbers {
20081 em_width
20082 } else {
20083 px(0.)
20084 };
20085
20086 let shows_folds = is_singleton && gutter_settings.folds;
20087
20088 let right_padding = if shows_folds && show_line_numbers {
20089 em_width * 4.0
20090 } else if shows_folds || (!is_singleton && show_line_numbers) {
20091 em_width * 3.0
20092 } else if show_line_numbers {
20093 em_width
20094 } else {
20095 px(0.)
20096 };
20097
20098 Some(GutterDimensions {
20099 left_padding,
20100 right_padding,
20101 width: line_gutter_width + left_padding + right_padding,
20102 margin: -descent,
20103 git_blame_entries_width,
20104 })
20105 }
20106
20107 pub fn render_crease_toggle(
20108 &self,
20109 buffer_row: MultiBufferRow,
20110 row_contains_cursor: bool,
20111 editor: Entity<Editor>,
20112 window: &mut Window,
20113 cx: &mut App,
20114 ) -> Option<AnyElement> {
20115 let folded = self.is_line_folded(buffer_row);
20116 let mut is_foldable = false;
20117
20118 if let Some(crease) = self
20119 .crease_snapshot
20120 .query_row(buffer_row, &self.buffer_snapshot)
20121 {
20122 is_foldable = true;
20123 match crease {
20124 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20125 if let Some(render_toggle) = render_toggle {
20126 let toggle_callback =
20127 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20128 if folded {
20129 editor.update(cx, |editor, cx| {
20130 editor.fold_at(buffer_row, window, cx)
20131 });
20132 } else {
20133 editor.update(cx, |editor, cx| {
20134 editor.unfold_at(buffer_row, window, cx)
20135 });
20136 }
20137 });
20138 return Some((render_toggle)(
20139 buffer_row,
20140 folded,
20141 toggle_callback,
20142 window,
20143 cx,
20144 ));
20145 }
20146 }
20147 }
20148 }
20149
20150 is_foldable |= self.starts_indent(buffer_row);
20151
20152 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20153 Some(
20154 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20155 .toggle_state(folded)
20156 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20157 if folded {
20158 this.unfold_at(buffer_row, window, cx);
20159 } else {
20160 this.fold_at(buffer_row, window, cx);
20161 }
20162 }))
20163 .into_any_element(),
20164 )
20165 } else {
20166 None
20167 }
20168 }
20169
20170 pub fn render_crease_trailer(
20171 &self,
20172 buffer_row: MultiBufferRow,
20173 window: &mut Window,
20174 cx: &mut App,
20175 ) -> Option<AnyElement> {
20176 let folded = self.is_line_folded(buffer_row);
20177 if let Crease::Inline { render_trailer, .. } = self
20178 .crease_snapshot
20179 .query_row(buffer_row, &self.buffer_snapshot)?
20180 {
20181 let render_trailer = render_trailer.as_ref()?;
20182 Some(render_trailer(buffer_row, folded, window, cx))
20183 } else {
20184 None
20185 }
20186 }
20187}
20188
20189impl Deref for EditorSnapshot {
20190 type Target = DisplaySnapshot;
20191
20192 fn deref(&self) -> &Self::Target {
20193 &self.display_snapshot
20194 }
20195}
20196
20197#[derive(Clone, Debug, PartialEq, Eq)]
20198pub enum EditorEvent {
20199 InputIgnored {
20200 text: Arc<str>,
20201 },
20202 InputHandled {
20203 utf16_range_to_replace: Option<Range<isize>>,
20204 text: Arc<str>,
20205 },
20206 ExcerptsAdded {
20207 buffer: Entity<Buffer>,
20208 predecessor: ExcerptId,
20209 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20210 },
20211 ExcerptsRemoved {
20212 ids: Vec<ExcerptId>,
20213 removed_buffer_ids: Vec<BufferId>,
20214 },
20215 BufferFoldToggled {
20216 ids: Vec<ExcerptId>,
20217 folded: bool,
20218 },
20219 ExcerptsEdited {
20220 ids: Vec<ExcerptId>,
20221 },
20222 ExcerptsExpanded {
20223 ids: Vec<ExcerptId>,
20224 },
20225 BufferEdited,
20226 Edited {
20227 transaction_id: clock::Lamport,
20228 },
20229 Reparsed(BufferId),
20230 Focused,
20231 FocusedIn,
20232 Blurred,
20233 DirtyChanged,
20234 Saved,
20235 TitleChanged,
20236 DiffBaseChanged,
20237 SelectionsChanged {
20238 local: bool,
20239 },
20240 ScrollPositionChanged {
20241 local: bool,
20242 autoscroll: bool,
20243 },
20244 Closed,
20245 TransactionUndone {
20246 transaction_id: clock::Lamport,
20247 },
20248 TransactionBegun {
20249 transaction_id: clock::Lamport,
20250 },
20251 Reloaded,
20252 CursorShapeChanged,
20253 PushedToNavHistory {
20254 anchor: Anchor,
20255 is_deactivate: bool,
20256 },
20257}
20258
20259impl EventEmitter<EditorEvent> for Editor {}
20260
20261impl Focusable for Editor {
20262 fn focus_handle(&self, _cx: &App) -> FocusHandle {
20263 self.focus_handle.clone()
20264 }
20265}
20266
20267impl Render for Editor {
20268 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20269 let settings = ThemeSettings::get_global(cx);
20270
20271 let mut text_style = match self.mode {
20272 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20273 color: cx.theme().colors().editor_foreground,
20274 font_family: settings.ui_font.family.clone(),
20275 font_features: settings.ui_font.features.clone(),
20276 font_fallbacks: settings.ui_font.fallbacks.clone(),
20277 font_size: rems(0.875).into(),
20278 font_weight: settings.ui_font.weight,
20279 line_height: relative(settings.buffer_line_height.value()),
20280 ..Default::default()
20281 },
20282 EditorMode::Full { .. } => TextStyle {
20283 color: cx.theme().colors().editor_foreground,
20284 font_family: settings.buffer_font.family.clone(),
20285 font_features: settings.buffer_font.features.clone(),
20286 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20287 font_size: settings.buffer_font_size(cx).into(),
20288 font_weight: settings.buffer_font.weight,
20289 line_height: relative(settings.buffer_line_height.value()),
20290 ..Default::default()
20291 },
20292 };
20293 if let Some(text_style_refinement) = &self.text_style_refinement {
20294 text_style.refine(text_style_refinement)
20295 }
20296
20297 let background = match self.mode {
20298 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20299 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20300 EditorMode::Full { .. } => cx.theme().colors().editor_background,
20301 };
20302
20303 EditorElement::new(
20304 &cx.entity(),
20305 EditorStyle {
20306 background,
20307 local_player: cx.theme().players().local(),
20308 text: text_style,
20309 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20310 syntax: cx.theme().syntax().clone(),
20311 status: cx.theme().status().clone(),
20312 inlay_hints_style: make_inlay_hints_style(cx),
20313 inline_completion_styles: make_suggestion_styles(cx),
20314 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20315 },
20316 )
20317 }
20318}
20319
20320impl EntityInputHandler for Editor {
20321 fn text_for_range(
20322 &mut self,
20323 range_utf16: Range<usize>,
20324 adjusted_range: &mut Option<Range<usize>>,
20325 _: &mut Window,
20326 cx: &mut Context<Self>,
20327 ) -> Option<String> {
20328 let snapshot = self.buffer.read(cx).read(cx);
20329 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20330 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20331 if (start.0..end.0) != range_utf16 {
20332 adjusted_range.replace(start.0..end.0);
20333 }
20334 Some(snapshot.text_for_range(start..end).collect())
20335 }
20336
20337 fn selected_text_range(
20338 &mut self,
20339 ignore_disabled_input: bool,
20340 _: &mut Window,
20341 cx: &mut Context<Self>,
20342 ) -> Option<UTF16Selection> {
20343 // Prevent the IME menu from appearing when holding down an alphabetic key
20344 // while input is disabled.
20345 if !ignore_disabled_input && !self.input_enabled {
20346 return None;
20347 }
20348
20349 let selection = self.selections.newest::<OffsetUtf16>(cx);
20350 let range = selection.range();
20351
20352 Some(UTF16Selection {
20353 range: range.start.0..range.end.0,
20354 reversed: selection.reversed,
20355 })
20356 }
20357
20358 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20359 let snapshot = self.buffer.read(cx).read(cx);
20360 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20361 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20362 }
20363
20364 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20365 self.clear_highlights::<InputComposition>(cx);
20366 self.ime_transaction.take();
20367 }
20368
20369 fn replace_text_in_range(
20370 &mut self,
20371 range_utf16: Option<Range<usize>>,
20372 text: &str,
20373 window: &mut Window,
20374 cx: &mut Context<Self>,
20375 ) {
20376 if !self.input_enabled {
20377 cx.emit(EditorEvent::InputIgnored { text: text.into() });
20378 return;
20379 }
20380
20381 self.transact(window, cx, |this, window, cx| {
20382 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20383 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20384 Some(this.selection_replacement_ranges(range_utf16, cx))
20385 } else {
20386 this.marked_text_ranges(cx)
20387 };
20388
20389 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20390 let newest_selection_id = this.selections.newest_anchor().id;
20391 this.selections
20392 .all::<OffsetUtf16>(cx)
20393 .iter()
20394 .zip(ranges_to_replace.iter())
20395 .find_map(|(selection, range)| {
20396 if selection.id == newest_selection_id {
20397 Some(
20398 (range.start.0 as isize - selection.head().0 as isize)
20399 ..(range.end.0 as isize - selection.head().0 as isize),
20400 )
20401 } else {
20402 None
20403 }
20404 })
20405 });
20406
20407 cx.emit(EditorEvent::InputHandled {
20408 utf16_range_to_replace: range_to_replace,
20409 text: text.into(),
20410 });
20411
20412 if let Some(new_selected_ranges) = new_selected_ranges {
20413 this.change_selections(None, window, cx, |selections| {
20414 selections.select_ranges(new_selected_ranges)
20415 });
20416 this.backspace(&Default::default(), window, cx);
20417 }
20418
20419 this.handle_input(text, window, cx);
20420 });
20421
20422 if let Some(transaction) = self.ime_transaction {
20423 self.buffer.update(cx, |buffer, cx| {
20424 buffer.group_until_transaction(transaction, cx);
20425 });
20426 }
20427
20428 self.unmark_text(window, cx);
20429 }
20430
20431 fn replace_and_mark_text_in_range(
20432 &mut self,
20433 range_utf16: Option<Range<usize>>,
20434 text: &str,
20435 new_selected_range_utf16: Option<Range<usize>>,
20436 window: &mut Window,
20437 cx: &mut Context<Self>,
20438 ) {
20439 if !self.input_enabled {
20440 return;
20441 }
20442
20443 let transaction = self.transact(window, cx, |this, window, cx| {
20444 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20445 let snapshot = this.buffer.read(cx).read(cx);
20446 if let Some(relative_range_utf16) = range_utf16.as_ref() {
20447 for marked_range in &mut marked_ranges {
20448 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20449 marked_range.start.0 += relative_range_utf16.start;
20450 marked_range.start =
20451 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20452 marked_range.end =
20453 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20454 }
20455 }
20456 Some(marked_ranges)
20457 } else if let Some(range_utf16) = range_utf16 {
20458 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20459 Some(this.selection_replacement_ranges(range_utf16, cx))
20460 } else {
20461 None
20462 };
20463
20464 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20465 let newest_selection_id = this.selections.newest_anchor().id;
20466 this.selections
20467 .all::<OffsetUtf16>(cx)
20468 .iter()
20469 .zip(ranges_to_replace.iter())
20470 .find_map(|(selection, range)| {
20471 if selection.id == newest_selection_id {
20472 Some(
20473 (range.start.0 as isize - selection.head().0 as isize)
20474 ..(range.end.0 as isize - selection.head().0 as isize),
20475 )
20476 } else {
20477 None
20478 }
20479 })
20480 });
20481
20482 cx.emit(EditorEvent::InputHandled {
20483 utf16_range_to_replace: range_to_replace,
20484 text: text.into(),
20485 });
20486
20487 if let Some(ranges) = ranges_to_replace {
20488 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20489 }
20490
20491 let marked_ranges = {
20492 let snapshot = this.buffer.read(cx).read(cx);
20493 this.selections
20494 .disjoint_anchors()
20495 .iter()
20496 .map(|selection| {
20497 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20498 })
20499 .collect::<Vec<_>>()
20500 };
20501
20502 if text.is_empty() {
20503 this.unmark_text(window, cx);
20504 } else {
20505 this.highlight_text::<InputComposition>(
20506 marked_ranges.clone(),
20507 HighlightStyle {
20508 underline: Some(UnderlineStyle {
20509 thickness: px(1.),
20510 color: None,
20511 wavy: false,
20512 }),
20513 ..Default::default()
20514 },
20515 cx,
20516 );
20517 }
20518
20519 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20520 let use_autoclose = this.use_autoclose;
20521 let use_auto_surround = this.use_auto_surround;
20522 this.set_use_autoclose(false);
20523 this.set_use_auto_surround(false);
20524 this.handle_input(text, window, cx);
20525 this.set_use_autoclose(use_autoclose);
20526 this.set_use_auto_surround(use_auto_surround);
20527
20528 if let Some(new_selected_range) = new_selected_range_utf16 {
20529 let snapshot = this.buffer.read(cx).read(cx);
20530 let new_selected_ranges = marked_ranges
20531 .into_iter()
20532 .map(|marked_range| {
20533 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20534 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20535 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20536 snapshot.clip_offset_utf16(new_start, Bias::Left)
20537 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20538 })
20539 .collect::<Vec<_>>();
20540
20541 drop(snapshot);
20542 this.change_selections(None, window, cx, |selections| {
20543 selections.select_ranges(new_selected_ranges)
20544 });
20545 }
20546 });
20547
20548 self.ime_transaction = self.ime_transaction.or(transaction);
20549 if let Some(transaction) = self.ime_transaction {
20550 self.buffer.update(cx, |buffer, cx| {
20551 buffer.group_until_transaction(transaction, cx);
20552 });
20553 }
20554
20555 if self.text_highlights::<InputComposition>(cx).is_none() {
20556 self.ime_transaction.take();
20557 }
20558 }
20559
20560 fn bounds_for_range(
20561 &mut self,
20562 range_utf16: Range<usize>,
20563 element_bounds: gpui::Bounds<Pixels>,
20564 window: &mut Window,
20565 cx: &mut Context<Self>,
20566 ) -> Option<gpui::Bounds<Pixels>> {
20567 let text_layout_details = self.text_layout_details(window);
20568 let gpui::Size {
20569 width: em_width,
20570 height: line_height,
20571 } = self.character_size(window);
20572
20573 let snapshot = self.snapshot(window, cx);
20574 let scroll_position = snapshot.scroll_position();
20575 let scroll_left = scroll_position.x * em_width;
20576
20577 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20578 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20579 + self.gutter_dimensions.width
20580 + self.gutter_dimensions.margin;
20581 let y = line_height * (start.row().as_f32() - scroll_position.y);
20582
20583 Some(Bounds {
20584 origin: element_bounds.origin + point(x, y),
20585 size: size(em_width, line_height),
20586 })
20587 }
20588
20589 fn character_index_for_point(
20590 &mut self,
20591 point: gpui::Point<Pixels>,
20592 _window: &mut Window,
20593 _cx: &mut Context<Self>,
20594 ) -> Option<usize> {
20595 let position_map = self.last_position_map.as_ref()?;
20596 if !position_map.text_hitbox.contains(&point) {
20597 return None;
20598 }
20599 let display_point = position_map.point_for_position(point).previous_valid;
20600 let anchor = position_map
20601 .snapshot
20602 .display_point_to_anchor(display_point, Bias::Left);
20603 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20604 Some(utf16_offset.0)
20605 }
20606}
20607
20608trait SelectionExt {
20609 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20610 fn spanned_rows(
20611 &self,
20612 include_end_if_at_line_start: bool,
20613 map: &DisplaySnapshot,
20614 ) -> Range<MultiBufferRow>;
20615}
20616
20617impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20618 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20619 let start = self
20620 .start
20621 .to_point(&map.buffer_snapshot)
20622 .to_display_point(map);
20623 let end = self
20624 .end
20625 .to_point(&map.buffer_snapshot)
20626 .to_display_point(map);
20627 if self.reversed {
20628 end..start
20629 } else {
20630 start..end
20631 }
20632 }
20633
20634 fn spanned_rows(
20635 &self,
20636 include_end_if_at_line_start: bool,
20637 map: &DisplaySnapshot,
20638 ) -> Range<MultiBufferRow> {
20639 let start = self.start.to_point(&map.buffer_snapshot);
20640 let mut end = self.end.to_point(&map.buffer_snapshot);
20641 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20642 end.row -= 1;
20643 }
20644
20645 let buffer_start = map.prev_line_boundary(start).0;
20646 let buffer_end = map.next_line_boundary(end).0;
20647 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20648 }
20649}
20650
20651impl<T: InvalidationRegion> InvalidationStack<T> {
20652 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20653 where
20654 S: Clone + ToOffset,
20655 {
20656 while let Some(region) = self.last() {
20657 let all_selections_inside_invalidation_ranges =
20658 if selections.len() == region.ranges().len() {
20659 selections
20660 .iter()
20661 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20662 .all(|(selection, invalidation_range)| {
20663 let head = selection.head().to_offset(buffer);
20664 invalidation_range.start <= head && invalidation_range.end >= head
20665 })
20666 } else {
20667 false
20668 };
20669
20670 if all_selections_inside_invalidation_ranges {
20671 break;
20672 } else {
20673 self.pop();
20674 }
20675 }
20676 }
20677}
20678
20679impl<T> Default for InvalidationStack<T> {
20680 fn default() -> Self {
20681 Self(Default::default())
20682 }
20683}
20684
20685impl<T> Deref for InvalidationStack<T> {
20686 type Target = Vec<T>;
20687
20688 fn deref(&self) -> &Self::Target {
20689 &self.0
20690 }
20691}
20692
20693impl<T> DerefMut for InvalidationStack<T> {
20694 fn deref_mut(&mut self) -> &mut Self::Target {
20695 &mut self.0
20696 }
20697}
20698
20699impl InvalidationRegion for SnippetState {
20700 fn ranges(&self) -> &[Range<Anchor>] {
20701 &self.ranges[self.active_index]
20702 }
20703}
20704
20705fn inline_completion_edit_text(
20706 current_snapshot: &BufferSnapshot,
20707 edits: &[(Range<Anchor>, String)],
20708 edit_preview: &EditPreview,
20709 include_deletions: bool,
20710 cx: &App,
20711) -> HighlightedText {
20712 let edits = edits
20713 .iter()
20714 .map(|(anchor, text)| {
20715 (
20716 anchor.start.text_anchor..anchor.end.text_anchor,
20717 text.clone(),
20718 )
20719 })
20720 .collect::<Vec<_>>();
20721
20722 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20723}
20724
20725pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20726 match severity {
20727 DiagnosticSeverity::ERROR => colors.error,
20728 DiagnosticSeverity::WARNING => colors.warning,
20729 DiagnosticSeverity::INFORMATION => colors.info,
20730 DiagnosticSeverity::HINT => colors.info,
20731 _ => colors.ignored,
20732 }
20733}
20734
20735pub fn styled_runs_for_code_label<'a>(
20736 label: &'a CodeLabel,
20737 syntax_theme: &'a theme::SyntaxTheme,
20738) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20739 let fade_out = HighlightStyle {
20740 fade_out: Some(0.35),
20741 ..Default::default()
20742 };
20743
20744 let mut prev_end = label.filter_range.end;
20745 label
20746 .runs
20747 .iter()
20748 .enumerate()
20749 .flat_map(move |(ix, (range, highlight_id))| {
20750 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20751 style
20752 } else {
20753 return Default::default();
20754 };
20755 let mut muted_style = style;
20756 muted_style.highlight(fade_out);
20757
20758 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20759 if range.start >= label.filter_range.end {
20760 if range.start > prev_end {
20761 runs.push((prev_end..range.start, fade_out));
20762 }
20763 runs.push((range.clone(), muted_style));
20764 } else if range.end <= label.filter_range.end {
20765 runs.push((range.clone(), style));
20766 } else {
20767 runs.push((range.start..label.filter_range.end, style));
20768 runs.push((label.filter_range.end..range.end, muted_style));
20769 }
20770 prev_end = cmp::max(prev_end, range.end);
20771
20772 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20773 runs.push((prev_end..label.text.len(), fade_out));
20774 }
20775
20776 runs
20777 })
20778}
20779
20780pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20781 let mut prev_index = 0;
20782 let mut prev_codepoint: Option<char> = None;
20783 text.char_indices()
20784 .chain([(text.len(), '\0')])
20785 .filter_map(move |(index, codepoint)| {
20786 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20787 let is_boundary = index == text.len()
20788 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20789 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20790 if is_boundary {
20791 let chunk = &text[prev_index..index];
20792 prev_index = index;
20793 Some(chunk)
20794 } else {
20795 None
20796 }
20797 })
20798}
20799
20800pub trait RangeToAnchorExt: Sized {
20801 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20802
20803 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20804 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20805 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20806 }
20807}
20808
20809impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20810 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20811 let start_offset = self.start.to_offset(snapshot);
20812 let end_offset = self.end.to_offset(snapshot);
20813 if start_offset == end_offset {
20814 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20815 } else {
20816 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20817 }
20818 }
20819}
20820
20821pub trait RowExt {
20822 fn as_f32(&self) -> f32;
20823
20824 fn next_row(&self) -> Self;
20825
20826 fn previous_row(&self) -> Self;
20827
20828 fn minus(&self, other: Self) -> u32;
20829}
20830
20831impl RowExt for DisplayRow {
20832 fn as_f32(&self) -> f32 {
20833 self.0 as f32
20834 }
20835
20836 fn next_row(&self) -> Self {
20837 Self(self.0 + 1)
20838 }
20839
20840 fn previous_row(&self) -> Self {
20841 Self(self.0.saturating_sub(1))
20842 }
20843
20844 fn minus(&self, other: Self) -> u32 {
20845 self.0 - other.0
20846 }
20847}
20848
20849impl RowExt for MultiBufferRow {
20850 fn as_f32(&self) -> f32 {
20851 self.0 as f32
20852 }
20853
20854 fn next_row(&self) -> Self {
20855 Self(self.0 + 1)
20856 }
20857
20858 fn previous_row(&self) -> Self {
20859 Self(self.0.saturating_sub(1))
20860 }
20861
20862 fn minus(&self, other: Self) -> u32 {
20863 self.0 - other.0
20864 }
20865}
20866
20867trait RowRangeExt {
20868 type Row;
20869
20870 fn len(&self) -> usize;
20871
20872 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20873}
20874
20875impl RowRangeExt for Range<MultiBufferRow> {
20876 type Row = MultiBufferRow;
20877
20878 fn len(&self) -> usize {
20879 (self.end.0 - self.start.0) as usize
20880 }
20881
20882 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20883 (self.start.0..self.end.0).map(MultiBufferRow)
20884 }
20885}
20886
20887impl RowRangeExt for Range<DisplayRow> {
20888 type Row = DisplayRow;
20889
20890 fn len(&self) -> usize {
20891 (self.end.0 - self.start.0) as usize
20892 }
20893
20894 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20895 (self.start.0..self.end.0).map(DisplayRow)
20896 }
20897}
20898
20899/// If select range has more than one line, we
20900/// just point the cursor to range.start.
20901fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20902 if range.start.row == range.end.row {
20903 range
20904 } else {
20905 range.start..range.start
20906 }
20907}
20908pub struct KillRing(ClipboardItem);
20909impl Global for KillRing {}
20910
20911const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20912
20913enum BreakpointPromptEditAction {
20914 Log,
20915 Condition,
20916 HitCondition,
20917}
20918
20919struct BreakpointPromptEditor {
20920 pub(crate) prompt: Entity<Editor>,
20921 editor: WeakEntity<Editor>,
20922 breakpoint_anchor: Anchor,
20923 breakpoint: Breakpoint,
20924 edit_action: BreakpointPromptEditAction,
20925 block_ids: HashSet<CustomBlockId>,
20926 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20927 _subscriptions: Vec<Subscription>,
20928}
20929
20930impl BreakpointPromptEditor {
20931 const MAX_LINES: u8 = 4;
20932
20933 fn new(
20934 editor: WeakEntity<Editor>,
20935 breakpoint_anchor: Anchor,
20936 breakpoint: Breakpoint,
20937 edit_action: BreakpointPromptEditAction,
20938 window: &mut Window,
20939 cx: &mut Context<Self>,
20940 ) -> Self {
20941 let base_text = match edit_action {
20942 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20943 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20944 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20945 }
20946 .map(|msg| msg.to_string())
20947 .unwrap_or_default();
20948
20949 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20950 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20951
20952 let prompt = cx.new(|cx| {
20953 let mut prompt = Editor::new(
20954 EditorMode::AutoHeight {
20955 max_lines: Self::MAX_LINES as usize,
20956 },
20957 buffer,
20958 None,
20959 window,
20960 cx,
20961 );
20962 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20963 prompt.set_show_cursor_when_unfocused(false, cx);
20964 prompt.set_placeholder_text(
20965 match edit_action {
20966 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20967 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20968 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20969 },
20970 cx,
20971 );
20972
20973 prompt
20974 });
20975
20976 Self {
20977 prompt,
20978 editor,
20979 breakpoint_anchor,
20980 breakpoint,
20981 edit_action,
20982 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20983 block_ids: Default::default(),
20984 _subscriptions: vec![],
20985 }
20986 }
20987
20988 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20989 self.block_ids.extend(block_ids)
20990 }
20991
20992 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20993 if let Some(editor) = self.editor.upgrade() {
20994 let message = self
20995 .prompt
20996 .read(cx)
20997 .buffer
20998 .read(cx)
20999 .as_singleton()
21000 .expect("A multi buffer in breakpoint prompt isn't possible")
21001 .read(cx)
21002 .as_rope()
21003 .to_string();
21004
21005 editor.update(cx, |editor, cx| {
21006 editor.edit_breakpoint_at_anchor(
21007 self.breakpoint_anchor,
21008 self.breakpoint.clone(),
21009 match self.edit_action {
21010 BreakpointPromptEditAction::Log => {
21011 BreakpointEditAction::EditLogMessage(message.into())
21012 }
21013 BreakpointPromptEditAction::Condition => {
21014 BreakpointEditAction::EditCondition(message.into())
21015 }
21016 BreakpointPromptEditAction::HitCondition => {
21017 BreakpointEditAction::EditHitCondition(message.into())
21018 }
21019 },
21020 cx,
21021 );
21022
21023 editor.remove_blocks(self.block_ids.clone(), None, cx);
21024 cx.focus_self(window);
21025 });
21026 }
21027 }
21028
21029 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21030 self.editor
21031 .update(cx, |editor, cx| {
21032 editor.remove_blocks(self.block_ids.clone(), None, cx);
21033 window.focus(&editor.focus_handle);
21034 })
21035 .log_err();
21036 }
21037
21038 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21039 let settings = ThemeSettings::get_global(cx);
21040 let text_style = TextStyle {
21041 color: if self.prompt.read(cx).read_only(cx) {
21042 cx.theme().colors().text_disabled
21043 } else {
21044 cx.theme().colors().text
21045 },
21046 font_family: settings.buffer_font.family.clone(),
21047 font_fallbacks: settings.buffer_font.fallbacks.clone(),
21048 font_size: settings.buffer_font_size(cx).into(),
21049 font_weight: settings.buffer_font.weight,
21050 line_height: relative(settings.buffer_line_height.value()),
21051 ..Default::default()
21052 };
21053 EditorElement::new(
21054 &self.prompt,
21055 EditorStyle {
21056 background: cx.theme().colors().editor_background,
21057 local_player: cx.theme().players().local(),
21058 text: text_style,
21059 ..Default::default()
21060 },
21061 )
21062 }
21063}
21064
21065impl Render for BreakpointPromptEditor {
21066 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21067 let gutter_dimensions = *self.gutter_dimensions.lock();
21068 h_flex()
21069 .key_context("Editor")
21070 .bg(cx.theme().colors().editor_background)
21071 .border_y_1()
21072 .border_color(cx.theme().status().info_border)
21073 .size_full()
21074 .py(window.line_height() / 2.5)
21075 .on_action(cx.listener(Self::confirm))
21076 .on_action(cx.listener(Self::cancel))
21077 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21078 .child(div().flex_1().child(self.render_prompt_editor(cx)))
21079 }
21080}
21081
21082impl Focusable for BreakpointPromptEditor {
21083 fn focus_handle(&self, cx: &App) -> FocusHandle {
21084 self.prompt.focus_handle(cx)
21085 }
21086}
21087
21088fn all_edits_insertions_or_deletions(
21089 edits: &Vec<(Range<Anchor>, String)>,
21090 snapshot: &MultiBufferSnapshot,
21091) -> bool {
21092 let mut all_insertions = true;
21093 let mut all_deletions = true;
21094
21095 for (range, new_text) in edits.iter() {
21096 let range_is_empty = range.to_offset(&snapshot).is_empty();
21097 let text_is_empty = new_text.is_empty();
21098
21099 if range_is_empty != text_is_empty {
21100 if range_is_empty {
21101 all_deletions = false;
21102 } else {
21103 all_insertions = false;
21104 }
21105 } else {
21106 return false;
21107 }
21108
21109 if !all_insertions && !all_deletions {
21110 return false;
21111 }
21112 }
21113 all_insertions || all_deletions
21114}
21115
21116struct MissingEditPredictionKeybindingTooltip;
21117
21118impl Render for MissingEditPredictionKeybindingTooltip {
21119 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21120 ui::tooltip_container(window, cx, |container, _, cx| {
21121 container
21122 .flex_shrink_0()
21123 .max_w_80()
21124 .min_h(rems_from_px(124.))
21125 .justify_between()
21126 .child(
21127 v_flex()
21128 .flex_1()
21129 .text_ui_sm(cx)
21130 .child(Label::new("Conflict with Accept Keybinding"))
21131 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21132 )
21133 .child(
21134 h_flex()
21135 .pb_1()
21136 .gap_1()
21137 .items_end()
21138 .w_full()
21139 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21140 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21141 }))
21142 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21143 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21144 })),
21145 )
21146 })
21147 }
21148}
21149
21150#[derive(Debug, Clone, Copy, PartialEq)]
21151pub struct LineHighlight {
21152 pub background: Background,
21153 pub border: Option<gpui::Hsla>,
21154 pub include_gutter: bool,
21155 pub type_id: Option<TypeId>,
21156}
21157
21158fn render_diff_hunk_controls(
21159 row: u32,
21160 status: &DiffHunkStatus,
21161 hunk_range: Range<Anchor>,
21162 is_created_file: bool,
21163 line_height: Pixels,
21164 editor: &Entity<Editor>,
21165 _window: &mut Window,
21166 cx: &mut App,
21167) -> AnyElement {
21168 h_flex()
21169 .h(line_height)
21170 .mr_1()
21171 .gap_1()
21172 .px_0p5()
21173 .pb_1()
21174 .border_x_1()
21175 .border_b_1()
21176 .border_color(cx.theme().colors().border_variant)
21177 .rounded_b_lg()
21178 .bg(cx.theme().colors().editor_background)
21179 .gap_1()
21180 .occlude()
21181 .shadow_md()
21182 .child(if status.has_secondary_hunk() {
21183 Button::new(("stage", row as u64), "Stage")
21184 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21185 .tooltip({
21186 let focus_handle = editor.focus_handle(cx);
21187 move |window, cx| {
21188 Tooltip::for_action_in(
21189 "Stage Hunk",
21190 &::git::ToggleStaged,
21191 &focus_handle,
21192 window,
21193 cx,
21194 )
21195 }
21196 })
21197 .on_click({
21198 let editor = editor.clone();
21199 move |_event, _window, cx| {
21200 editor.update(cx, |editor, cx| {
21201 editor.stage_or_unstage_diff_hunks(
21202 true,
21203 vec![hunk_range.start..hunk_range.start],
21204 cx,
21205 );
21206 });
21207 }
21208 })
21209 } else {
21210 Button::new(("unstage", row as u64), "Unstage")
21211 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21212 .tooltip({
21213 let focus_handle = editor.focus_handle(cx);
21214 move |window, cx| {
21215 Tooltip::for_action_in(
21216 "Unstage Hunk",
21217 &::git::ToggleStaged,
21218 &focus_handle,
21219 window,
21220 cx,
21221 )
21222 }
21223 })
21224 .on_click({
21225 let editor = editor.clone();
21226 move |_event, _window, cx| {
21227 editor.update(cx, |editor, cx| {
21228 editor.stage_or_unstage_diff_hunks(
21229 false,
21230 vec![hunk_range.start..hunk_range.start],
21231 cx,
21232 );
21233 });
21234 }
21235 })
21236 })
21237 .child(
21238 Button::new(("restore", row as u64), "Restore")
21239 .tooltip({
21240 let focus_handle = editor.focus_handle(cx);
21241 move |window, cx| {
21242 Tooltip::for_action_in(
21243 "Restore Hunk",
21244 &::git::Restore,
21245 &focus_handle,
21246 window,
21247 cx,
21248 )
21249 }
21250 })
21251 .on_click({
21252 let editor = editor.clone();
21253 move |_event, window, cx| {
21254 editor.update(cx, |editor, cx| {
21255 let snapshot = editor.snapshot(window, cx);
21256 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21257 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21258 });
21259 }
21260 })
21261 .disabled(is_created_file),
21262 )
21263 .when(
21264 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21265 |el| {
21266 el.child(
21267 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21268 .shape(IconButtonShape::Square)
21269 .icon_size(IconSize::Small)
21270 // .disabled(!has_multiple_hunks)
21271 .tooltip({
21272 let focus_handle = editor.focus_handle(cx);
21273 move |window, cx| {
21274 Tooltip::for_action_in(
21275 "Next Hunk",
21276 &GoToHunk,
21277 &focus_handle,
21278 window,
21279 cx,
21280 )
21281 }
21282 })
21283 .on_click({
21284 let editor = editor.clone();
21285 move |_event, window, cx| {
21286 editor.update(cx, |editor, cx| {
21287 let snapshot = editor.snapshot(window, cx);
21288 let position =
21289 hunk_range.end.to_point(&snapshot.buffer_snapshot);
21290 editor.go_to_hunk_before_or_after_position(
21291 &snapshot,
21292 position,
21293 Direction::Next,
21294 window,
21295 cx,
21296 );
21297 editor.expand_selected_diff_hunks(cx);
21298 });
21299 }
21300 }),
21301 )
21302 .child(
21303 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21304 .shape(IconButtonShape::Square)
21305 .icon_size(IconSize::Small)
21306 // .disabled(!has_multiple_hunks)
21307 .tooltip({
21308 let focus_handle = editor.focus_handle(cx);
21309 move |window, cx| {
21310 Tooltip::for_action_in(
21311 "Previous Hunk",
21312 &GoToPreviousHunk,
21313 &focus_handle,
21314 window,
21315 cx,
21316 )
21317 }
21318 })
21319 .on_click({
21320 let editor = editor.clone();
21321 move |_event, window, cx| {
21322 editor.update(cx, |editor, cx| {
21323 let snapshot = editor.snapshot(window, cx);
21324 let point =
21325 hunk_range.start.to_point(&snapshot.buffer_snapshot);
21326 editor.go_to_hunk_before_or_after_position(
21327 &snapshot,
21328 point,
21329 Direction::Prev,
21330 window,
21331 cx,
21332 );
21333 editor.expand_selected_diff_hunks(cx);
21334 });
21335 }
21336 }),
21337 )
21338 },
21339 )
21340 .into_any_element()
21341}