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::{AGENT_REPLICA_ID, 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 CollaboratorId, 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_expand_excerpt_buttons: bool,
875 show_line_numbers: Option<bool>,
876 use_relative_line_numbers: Option<bool>,
877 show_git_diff_gutter: Option<bool>,
878 show_code_actions: Option<bool>,
879 show_runnables: Option<bool>,
880 show_breakpoints: Option<bool>,
881 show_wrap_guides: Option<bool>,
882 show_indent_guides: Option<bool>,
883 placeholder_text: Option<Arc<str>>,
884 highlight_order: usize,
885 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
886 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
887 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
888 scrollbar_marker_state: ScrollbarMarkerState,
889 active_indent_guides_state: ActiveIndentGuidesState,
890 nav_history: Option<ItemNavHistory>,
891 context_menu: RefCell<Option<CodeContextMenu>>,
892 context_menu_options: Option<ContextMenuOptions>,
893 mouse_context_menu: Option<MouseContextMenu>,
894 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
895 inline_blame_popover: Option<InlineBlamePopover>,
896 signature_help_state: SignatureHelpState,
897 auto_signature_help: Option<bool>,
898 find_all_references_task_sources: Vec<Anchor>,
899 next_completion_id: CompletionId,
900 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
901 code_actions_task: Option<Task<Result<()>>>,
902 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
903 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
904 document_highlights_task: Option<Task<()>>,
905 linked_editing_range_task: Option<Task<Option<()>>>,
906 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
907 pending_rename: Option<RenameState>,
908 searchable: bool,
909 cursor_shape: CursorShape,
910 current_line_highlight: Option<CurrentLineHighlight>,
911 collapse_matches: bool,
912 autoindent_mode: Option<AutoindentMode>,
913 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
914 input_enabled: bool,
915 use_modal_editing: bool,
916 read_only: bool,
917 leader_id: Option<CollaboratorId>,
918 remote_id: Option<ViewId>,
919 pub hover_state: HoverState,
920 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
921 gutter_hovered: bool,
922 hovered_link_state: Option<HoveredLinkState>,
923 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
924 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
925 active_inline_completion: Option<InlineCompletionState>,
926 /// Used to prevent flickering as the user types while the menu is open
927 stale_inline_completion_in_menu: Option<InlineCompletionState>,
928 edit_prediction_settings: EditPredictionSettings,
929 inline_completions_hidden_for_vim_mode: bool,
930 show_inline_completions_override: Option<bool>,
931 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
932 edit_prediction_preview: EditPredictionPreview,
933 edit_prediction_indent_conflict: bool,
934 edit_prediction_requires_modifier_in_indent_conflict: bool,
935 inlay_hint_cache: InlayHintCache,
936 next_inlay_id: usize,
937 _subscriptions: Vec<Subscription>,
938 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
939 gutter_dimensions: GutterDimensions,
940 style: Option<EditorStyle>,
941 text_style_refinement: Option<TextStyleRefinement>,
942 next_editor_action_id: EditorActionId,
943 editor_actions:
944 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
945 use_autoclose: bool,
946 use_auto_surround: bool,
947 auto_replace_emoji_shortcode: bool,
948 jsx_tag_auto_close_enabled_in_any_buffer: bool,
949 show_git_blame_gutter: bool,
950 show_git_blame_inline: bool,
951 show_git_blame_inline_delay_task: Option<Task<()>>,
952 git_blame_inline_enabled: bool,
953 render_diff_hunk_controls: RenderDiffHunkControlsFn,
954 serialize_dirty_buffers: bool,
955 show_selection_menu: Option<bool>,
956 blame: Option<Entity<GitBlame>>,
957 blame_subscription: Option<Subscription>,
958 custom_context_menu: Option<
959 Box<
960 dyn 'static
961 + Fn(
962 &mut Self,
963 DisplayPoint,
964 &mut Window,
965 &mut Context<Self>,
966 ) -> Option<Entity<ui::ContextMenu>>,
967 >,
968 >,
969 last_bounds: Option<Bounds<Pixels>>,
970 last_position_map: Option<Rc<PositionMap>>,
971 expect_bounds_change: Option<Bounds<Pixels>>,
972 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
973 tasks_update_task: Option<Task<()>>,
974 breakpoint_store: Option<Entity<BreakpointStore>>,
975 gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
976 in_project_search: bool,
977 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
978 breadcrumb_header: Option<String>,
979 focused_block: Option<FocusedBlock>,
980 next_scroll_position: NextScrollCursorCenterTopBottom,
981 addons: HashMap<TypeId, Box<dyn Addon>>,
982 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
983 load_diff_task: Option<Shared<Task<()>>>,
984 /// Whether we are temporarily displaying a diff other than git's
985 temporary_diff_override: bool,
986 selection_mark_mode: bool,
987 toggle_fold_multiple_buffers: Task<()>,
988 _scroll_cursor_center_top_bottom_task: Task<()>,
989 serialize_selections: Task<()>,
990 serialize_folds: Task<()>,
991 mouse_cursor_hidden: bool,
992 hide_mouse_mode: HideMouseMode,
993 pub change_list: ChangeList,
994 inline_value_cache: InlineValueCache,
995}
996
997#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
998enum NextScrollCursorCenterTopBottom {
999 #[default]
1000 Center,
1001 Top,
1002 Bottom,
1003}
1004
1005impl NextScrollCursorCenterTopBottom {
1006 fn next(&self) -> Self {
1007 match self {
1008 Self::Center => Self::Top,
1009 Self::Top => Self::Bottom,
1010 Self::Bottom => Self::Center,
1011 }
1012 }
1013}
1014
1015#[derive(Clone)]
1016pub struct EditorSnapshot {
1017 pub mode: EditorMode,
1018 show_gutter: bool,
1019 show_line_numbers: Option<bool>,
1020 show_git_diff_gutter: Option<bool>,
1021 show_code_actions: Option<bool>,
1022 show_runnables: Option<bool>,
1023 show_breakpoints: Option<bool>,
1024 git_blame_gutter_max_author_length: Option<usize>,
1025 pub display_snapshot: DisplaySnapshot,
1026 pub placeholder_text: Option<Arc<str>>,
1027 is_focused: bool,
1028 scroll_anchor: ScrollAnchor,
1029 ongoing_scroll: OngoingScroll,
1030 current_line_highlight: CurrentLineHighlight,
1031 gutter_hovered: bool,
1032}
1033
1034#[derive(Default, Debug, Clone, Copy)]
1035pub struct GutterDimensions {
1036 pub left_padding: Pixels,
1037 pub right_padding: Pixels,
1038 pub width: Pixels,
1039 pub margin: Pixels,
1040 pub git_blame_entries_width: Option<Pixels>,
1041}
1042
1043impl GutterDimensions {
1044 fn default_with_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Self {
1045 Self {
1046 margin: Self::default_gutter_margin(font_id, font_size, cx),
1047 ..Default::default()
1048 }
1049 }
1050
1051 fn default_gutter_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Pixels {
1052 -cx.text_system().descent(font_id, font_size)
1053 }
1054 /// The full width of the space taken up by the gutter.
1055 pub fn full_width(&self) -> Pixels {
1056 self.margin + self.width
1057 }
1058
1059 /// The width of the space reserved for the fold indicators,
1060 /// use alongside 'justify_end' and `gutter_width` to
1061 /// right align content with the line numbers
1062 pub fn fold_area_width(&self) -> Pixels {
1063 self.margin + self.right_padding
1064 }
1065}
1066
1067#[derive(Debug)]
1068pub struct RemoteSelection {
1069 pub replica_id: ReplicaId,
1070 pub selection: Selection<Anchor>,
1071 pub cursor_shape: CursorShape,
1072 pub collaborator_id: CollaboratorId,
1073 pub line_mode: bool,
1074 pub user_name: Option<SharedString>,
1075 pub color: PlayerColor,
1076}
1077
1078#[derive(Clone, Debug)]
1079struct SelectionHistoryEntry {
1080 selections: Arc<[Selection<Anchor>]>,
1081 select_next_state: Option<SelectNextState>,
1082 select_prev_state: Option<SelectNextState>,
1083 add_selections_state: Option<AddSelectionsState>,
1084}
1085
1086enum SelectionHistoryMode {
1087 Normal,
1088 Undoing,
1089 Redoing,
1090}
1091
1092#[derive(Clone, PartialEq, Eq, Hash)]
1093struct HoveredCursor {
1094 replica_id: u16,
1095 selection_id: usize,
1096}
1097
1098impl Default for SelectionHistoryMode {
1099 fn default() -> Self {
1100 Self::Normal
1101 }
1102}
1103
1104#[derive(Default)]
1105struct SelectionHistory {
1106 #[allow(clippy::type_complexity)]
1107 selections_by_transaction:
1108 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1109 mode: SelectionHistoryMode,
1110 undo_stack: VecDeque<SelectionHistoryEntry>,
1111 redo_stack: VecDeque<SelectionHistoryEntry>,
1112}
1113
1114impl SelectionHistory {
1115 fn insert_transaction(
1116 &mut self,
1117 transaction_id: TransactionId,
1118 selections: Arc<[Selection<Anchor>]>,
1119 ) {
1120 self.selections_by_transaction
1121 .insert(transaction_id, (selections, None));
1122 }
1123
1124 #[allow(clippy::type_complexity)]
1125 fn transaction(
1126 &self,
1127 transaction_id: TransactionId,
1128 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1129 self.selections_by_transaction.get(&transaction_id)
1130 }
1131
1132 #[allow(clippy::type_complexity)]
1133 fn transaction_mut(
1134 &mut self,
1135 transaction_id: TransactionId,
1136 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1137 self.selections_by_transaction.get_mut(&transaction_id)
1138 }
1139
1140 fn push(&mut self, entry: SelectionHistoryEntry) {
1141 if !entry.selections.is_empty() {
1142 match self.mode {
1143 SelectionHistoryMode::Normal => {
1144 self.push_undo(entry);
1145 self.redo_stack.clear();
1146 }
1147 SelectionHistoryMode::Undoing => self.push_redo(entry),
1148 SelectionHistoryMode::Redoing => self.push_undo(entry),
1149 }
1150 }
1151 }
1152
1153 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1154 if self
1155 .undo_stack
1156 .back()
1157 .map_or(true, |e| e.selections != entry.selections)
1158 {
1159 self.undo_stack.push_back(entry);
1160 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1161 self.undo_stack.pop_front();
1162 }
1163 }
1164 }
1165
1166 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1167 if self
1168 .redo_stack
1169 .back()
1170 .map_or(true, |e| e.selections != entry.selections)
1171 {
1172 self.redo_stack.push_back(entry);
1173 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1174 self.redo_stack.pop_front();
1175 }
1176 }
1177 }
1178}
1179
1180#[derive(Clone, Copy)]
1181pub struct RowHighlightOptions {
1182 pub autoscroll: bool,
1183 pub include_gutter: bool,
1184}
1185
1186impl Default for RowHighlightOptions {
1187 fn default() -> Self {
1188 Self {
1189 autoscroll: Default::default(),
1190 include_gutter: true,
1191 }
1192 }
1193}
1194
1195struct RowHighlight {
1196 index: usize,
1197 range: Range<Anchor>,
1198 color: Hsla,
1199 options: RowHighlightOptions,
1200 type_id: TypeId,
1201}
1202
1203#[derive(Clone, Debug)]
1204struct AddSelectionsState {
1205 above: bool,
1206 stack: Vec<usize>,
1207}
1208
1209#[derive(Clone)]
1210struct SelectNextState {
1211 query: AhoCorasick,
1212 wordwise: bool,
1213 done: bool,
1214}
1215
1216impl std::fmt::Debug for SelectNextState {
1217 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1218 f.debug_struct(std::any::type_name::<Self>())
1219 .field("wordwise", &self.wordwise)
1220 .field("done", &self.done)
1221 .finish()
1222 }
1223}
1224
1225#[derive(Debug)]
1226struct AutocloseRegion {
1227 selection_id: usize,
1228 range: Range<Anchor>,
1229 pair: BracketPair,
1230}
1231
1232#[derive(Debug)]
1233struct SnippetState {
1234 ranges: Vec<Vec<Range<Anchor>>>,
1235 active_index: usize,
1236 choices: Vec<Option<Vec<String>>>,
1237}
1238
1239#[doc(hidden)]
1240pub struct RenameState {
1241 pub range: Range<Anchor>,
1242 pub old_name: Arc<str>,
1243 pub editor: Entity<Editor>,
1244 block_id: CustomBlockId,
1245}
1246
1247struct InvalidationStack<T>(Vec<T>);
1248
1249struct RegisteredInlineCompletionProvider {
1250 provider: Arc<dyn InlineCompletionProviderHandle>,
1251 _subscription: Subscription,
1252}
1253
1254#[derive(Debug, PartialEq, Eq)]
1255pub struct ActiveDiagnosticGroup {
1256 pub active_range: Range<Anchor>,
1257 pub active_message: String,
1258 pub group_id: usize,
1259 pub blocks: HashSet<CustomBlockId>,
1260}
1261
1262#[derive(Debug, PartialEq, Eq)]
1263#[allow(clippy::large_enum_variant)]
1264pub(crate) enum ActiveDiagnostic {
1265 None,
1266 All,
1267 Group(ActiveDiagnosticGroup),
1268}
1269
1270#[derive(Serialize, Deserialize, Clone, Debug)]
1271pub struct ClipboardSelection {
1272 /// The number of bytes in this selection.
1273 pub len: usize,
1274 /// Whether this was a full-line selection.
1275 pub is_entire_line: bool,
1276 /// The indentation of the first line when this content was originally copied.
1277 pub first_line_indent: u32,
1278}
1279
1280// selections, scroll behavior, was newest selection reversed
1281type SelectSyntaxNodeHistoryState = (
1282 Box<[Selection<usize>]>,
1283 SelectSyntaxNodeScrollBehavior,
1284 bool,
1285);
1286
1287#[derive(Default)]
1288struct SelectSyntaxNodeHistory {
1289 stack: Vec<SelectSyntaxNodeHistoryState>,
1290 // disable temporarily to allow changing selections without losing the stack
1291 pub disable_clearing: bool,
1292}
1293
1294impl SelectSyntaxNodeHistory {
1295 pub fn try_clear(&mut self) {
1296 if !self.disable_clearing {
1297 self.stack.clear();
1298 }
1299 }
1300
1301 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1302 self.stack.push(selection);
1303 }
1304
1305 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1306 self.stack.pop()
1307 }
1308}
1309
1310enum SelectSyntaxNodeScrollBehavior {
1311 CursorTop,
1312 FitSelection,
1313 CursorBottom,
1314}
1315
1316#[derive(Debug)]
1317pub(crate) struct NavigationData {
1318 cursor_anchor: Anchor,
1319 cursor_position: Point,
1320 scroll_anchor: ScrollAnchor,
1321 scroll_top_row: u32,
1322}
1323
1324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1325pub enum GotoDefinitionKind {
1326 Symbol,
1327 Declaration,
1328 Type,
1329 Implementation,
1330}
1331
1332#[derive(Debug, Clone)]
1333enum InlayHintRefreshReason {
1334 ModifiersChanged(bool),
1335 Toggle(bool),
1336 SettingsChange(InlayHintSettings),
1337 NewLinesShown,
1338 BufferEdited(HashSet<Arc<Language>>),
1339 RefreshRequested,
1340 ExcerptsRemoved(Vec<ExcerptId>),
1341}
1342
1343impl InlayHintRefreshReason {
1344 fn description(&self) -> &'static str {
1345 match self {
1346 Self::ModifiersChanged(_) => "modifiers changed",
1347 Self::Toggle(_) => "toggle",
1348 Self::SettingsChange(_) => "settings change",
1349 Self::NewLinesShown => "new lines shown",
1350 Self::BufferEdited(_) => "buffer edited",
1351 Self::RefreshRequested => "refresh requested",
1352 Self::ExcerptsRemoved(_) => "excerpts removed",
1353 }
1354 }
1355}
1356
1357pub enum FormatTarget {
1358 Buffers,
1359 Ranges(Vec<Range<MultiBufferPoint>>),
1360}
1361
1362pub(crate) struct FocusedBlock {
1363 id: BlockId,
1364 focus_handle: WeakFocusHandle,
1365}
1366
1367#[derive(Clone)]
1368enum JumpData {
1369 MultiBufferRow {
1370 row: MultiBufferRow,
1371 line_offset_from_top: u32,
1372 },
1373 MultiBufferPoint {
1374 excerpt_id: ExcerptId,
1375 position: Point,
1376 anchor: text::Anchor,
1377 line_offset_from_top: u32,
1378 },
1379}
1380
1381pub enum MultibufferSelectionMode {
1382 First,
1383 All,
1384}
1385
1386#[derive(Clone, Copy, Debug, Default)]
1387pub struct RewrapOptions {
1388 pub override_language_settings: bool,
1389 pub preserve_existing_whitespace: bool,
1390}
1391
1392impl Editor {
1393 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1394 let buffer = cx.new(|cx| Buffer::local("", cx));
1395 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1396 Self::new(
1397 EditorMode::SingleLine { auto_width: false },
1398 buffer,
1399 None,
1400 window,
1401 cx,
1402 )
1403 }
1404
1405 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1406 let buffer = cx.new(|cx| Buffer::local("", cx));
1407 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1408 Self::new(EditorMode::full(), buffer, None, window, cx)
1409 }
1410
1411 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1412 let buffer = cx.new(|cx| Buffer::local("", cx));
1413 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1414 Self::new(
1415 EditorMode::SingleLine { auto_width: true },
1416 buffer,
1417 None,
1418 window,
1419 cx,
1420 )
1421 }
1422
1423 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1424 let buffer = cx.new(|cx| Buffer::local("", cx));
1425 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1426 Self::new(
1427 EditorMode::AutoHeight { max_lines },
1428 buffer,
1429 None,
1430 window,
1431 cx,
1432 )
1433 }
1434
1435 pub fn for_buffer(
1436 buffer: Entity<Buffer>,
1437 project: Option<Entity<Project>>,
1438 window: &mut Window,
1439 cx: &mut Context<Self>,
1440 ) -> Self {
1441 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1442 Self::new(EditorMode::full(), buffer, project, window, cx)
1443 }
1444
1445 pub fn for_multibuffer(
1446 buffer: Entity<MultiBuffer>,
1447 project: Option<Entity<Project>>,
1448 window: &mut Window,
1449 cx: &mut Context<Self>,
1450 ) -> Self {
1451 Self::new(EditorMode::full(), buffer, project, window, cx)
1452 }
1453
1454 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1455 let mut clone = Self::new(
1456 self.mode,
1457 self.buffer.clone(),
1458 self.project.clone(),
1459 window,
1460 cx,
1461 );
1462 self.display_map.update(cx, |display_map, cx| {
1463 let snapshot = display_map.snapshot(cx);
1464 clone.display_map.update(cx, |display_map, cx| {
1465 display_map.set_state(&snapshot, cx);
1466 });
1467 });
1468 clone.folds_did_change(cx);
1469 clone.selections.clone_state(&self.selections);
1470 clone.scroll_manager.clone_state(&self.scroll_manager);
1471 clone.searchable = self.searchable;
1472 clone.read_only = self.read_only;
1473 clone
1474 }
1475
1476 pub fn new(
1477 mode: EditorMode,
1478 buffer: Entity<MultiBuffer>,
1479 project: Option<Entity<Project>>,
1480 window: &mut Window,
1481 cx: &mut Context<Self>,
1482 ) -> Self {
1483 let style = window.text_style();
1484 let font_size = style.font_size.to_pixels(window.rem_size());
1485 let editor = cx.entity().downgrade();
1486 let fold_placeholder = FoldPlaceholder {
1487 constrain_width: true,
1488 render: Arc::new(move |fold_id, fold_range, cx| {
1489 let editor = editor.clone();
1490 div()
1491 .id(fold_id)
1492 .bg(cx.theme().colors().ghost_element_background)
1493 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1494 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1495 .rounded_xs()
1496 .size_full()
1497 .cursor_pointer()
1498 .child("⋯")
1499 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1500 .on_click(move |_, _window, cx| {
1501 editor
1502 .update(cx, |editor, cx| {
1503 editor.unfold_ranges(
1504 &[fold_range.start..fold_range.end],
1505 true,
1506 false,
1507 cx,
1508 );
1509 cx.stop_propagation();
1510 })
1511 .ok();
1512 })
1513 .into_any()
1514 }),
1515 merge_adjacent: true,
1516 ..Default::default()
1517 };
1518 let display_map = cx.new(|cx| {
1519 DisplayMap::new(
1520 buffer.clone(),
1521 style.font(),
1522 font_size,
1523 None,
1524 FILE_HEADER_HEIGHT,
1525 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1526 fold_placeholder,
1527 cx,
1528 )
1529 });
1530
1531 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1532
1533 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1534
1535 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1536 .then(|| language_settings::SoftWrap::None);
1537
1538 let mut project_subscriptions = Vec::new();
1539 if mode.is_full() {
1540 if let Some(project) = project.as_ref() {
1541 project_subscriptions.push(cx.subscribe_in(
1542 project,
1543 window,
1544 |editor, _, event, window, cx| match event {
1545 project::Event::RefreshCodeLens => {
1546 // we always query lens with actions, without storing them, always refreshing them
1547 }
1548 project::Event::RefreshInlayHints => {
1549 editor
1550 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1551 }
1552 project::Event::SnippetEdit(id, snippet_edits) => {
1553 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1554 let focus_handle = editor.focus_handle(cx);
1555 if focus_handle.is_focused(window) {
1556 let snapshot = buffer.read(cx).snapshot();
1557 for (range, snippet) in snippet_edits {
1558 let editor_range =
1559 language::range_from_lsp(*range).to_offset(&snapshot);
1560 editor
1561 .insert_snippet(
1562 &[editor_range],
1563 snippet.clone(),
1564 window,
1565 cx,
1566 )
1567 .ok();
1568 }
1569 }
1570 }
1571 }
1572 _ => {}
1573 },
1574 ));
1575 if let Some(task_inventory) = project
1576 .read(cx)
1577 .task_store()
1578 .read(cx)
1579 .task_inventory()
1580 .cloned()
1581 {
1582 project_subscriptions.push(cx.observe_in(
1583 &task_inventory,
1584 window,
1585 |editor, _, window, cx| {
1586 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1587 },
1588 ));
1589 };
1590
1591 project_subscriptions.push(cx.subscribe_in(
1592 &project.read(cx).breakpoint_store(),
1593 window,
1594 |editor, _, event, window, cx| match event {
1595 BreakpointStoreEvent::ClearDebugLines => {
1596 editor.clear_row_highlights::<ActiveDebugLine>();
1597 editor.refresh_inline_values(cx);
1598 }
1599 BreakpointStoreEvent::SetDebugLine => {
1600 if editor.go_to_active_debug_line(window, cx) {
1601 cx.stop_propagation();
1602 }
1603
1604 editor.refresh_inline_values(cx);
1605 }
1606 _ => {}
1607 },
1608 ));
1609 }
1610 }
1611
1612 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1613
1614 let inlay_hint_settings =
1615 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1616 let focus_handle = cx.focus_handle();
1617 cx.on_focus(&focus_handle, window, Self::handle_focus)
1618 .detach();
1619 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1620 .detach();
1621 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1622 .detach();
1623 cx.on_blur(&focus_handle, window, Self::handle_blur)
1624 .detach();
1625
1626 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1627 Some(false)
1628 } else {
1629 None
1630 };
1631
1632 let breakpoint_store = match (mode, project.as_ref()) {
1633 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1634 _ => None,
1635 };
1636
1637 let mut code_action_providers = Vec::new();
1638 let mut load_uncommitted_diff = None;
1639 if let Some(project) = project.clone() {
1640 load_uncommitted_diff = Some(
1641 update_uncommitted_diff_for_buffer(
1642 cx.entity(),
1643 &project,
1644 buffer.read(cx).all_buffers(),
1645 buffer.clone(),
1646 cx,
1647 )
1648 .shared(),
1649 );
1650 code_action_providers.push(Rc::new(project) as Rc<_>);
1651 }
1652
1653 let mut this = Self {
1654 focus_handle,
1655 show_cursor_when_unfocused: false,
1656 last_focused_descendant: None,
1657 buffer: buffer.clone(),
1658 display_map: display_map.clone(),
1659 selections,
1660 scroll_manager: ScrollManager::new(cx),
1661 columnar_selection_tail: None,
1662 add_selections_state: None,
1663 select_next_state: None,
1664 select_prev_state: None,
1665 selection_history: Default::default(),
1666 autoclose_regions: Default::default(),
1667 snippet_stack: Default::default(),
1668 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1669 ime_transaction: Default::default(),
1670 active_diagnostics: ActiveDiagnostic::None,
1671 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1672 inline_diagnostics_update: Task::ready(()),
1673 inline_diagnostics: Vec::new(),
1674 soft_wrap_mode_override,
1675 hard_wrap: None,
1676 completion_provider: project.clone().map(|project| Box::new(project) as _),
1677 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1678 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1679 project,
1680 blink_manager: blink_manager.clone(),
1681 show_local_selections: true,
1682 show_scrollbars: true,
1683 mode,
1684 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1685 show_gutter: mode.is_full(),
1686 show_line_numbers: None,
1687 use_relative_line_numbers: None,
1688 disable_expand_excerpt_buttons: false,
1689 show_git_diff_gutter: None,
1690 show_code_actions: None,
1691 show_runnables: None,
1692 show_breakpoints: None,
1693 show_wrap_guides: None,
1694 show_indent_guides,
1695 placeholder_text: None,
1696 highlight_order: 0,
1697 highlighted_rows: HashMap::default(),
1698 background_highlights: Default::default(),
1699 gutter_highlights: TreeMap::default(),
1700 scrollbar_marker_state: ScrollbarMarkerState::default(),
1701 active_indent_guides_state: ActiveIndentGuidesState::default(),
1702 nav_history: None,
1703 context_menu: RefCell::new(None),
1704 context_menu_options: None,
1705 mouse_context_menu: None,
1706 completion_tasks: Default::default(),
1707 inline_blame_popover: Default::default(),
1708 signature_help_state: SignatureHelpState::default(),
1709 auto_signature_help: None,
1710 find_all_references_task_sources: Vec::new(),
1711 next_completion_id: 0,
1712 next_inlay_id: 0,
1713 code_action_providers,
1714 available_code_actions: Default::default(),
1715 code_actions_task: Default::default(),
1716 quick_selection_highlight_task: Default::default(),
1717 debounced_selection_highlight_task: Default::default(),
1718 document_highlights_task: Default::default(),
1719 linked_editing_range_task: Default::default(),
1720 pending_rename: Default::default(),
1721 searchable: true,
1722 cursor_shape: EditorSettings::get_global(cx)
1723 .cursor_shape
1724 .unwrap_or_default(),
1725 current_line_highlight: None,
1726 autoindent_mode: Some(AutoindentMode::EachLine),
1727 collapse_matches: false,
1728 workspace: None,
1729 input_enabled: true,
1730 use_modal_editing: mode.is_full(),
1731 read_only: false,
1732 use_autoclose: true,
1733 use_auto_surround: true,
1734 auto_replace_emoji_shortcode: false,
1735 jsx_tag_auto_close_enabled_in_any_buffer: false,
1736 leader_id: None,
1737 remote_id: None,
1738 hover_state: Default::default(),
1739 pending_mouse_down: None,
1740 hovered_link_state: Default::default(),
1741 edit_prediction_provider: None,
1742 active_inline_completion: None,
1743 stale_inline_completion_in_menu: None,
1744 edit_prediction_preview: EditPredictionPreview::Inactive {
1745 released_too_fast: false,
1746 },
1747 inline_diagnostics_enabled: mode.is_full(),
1748 inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
1749 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1750
1751 gutter_hovered: false,
1752 pixel_position_of_newest_cursor: None,
1753 last_bounds: None,
1754 last_position_map: None,
1755 expect_bounds_change: None,
1756 gutter_dimensions: GutterDimensions::default(),
1757 style: None,
1758 show_cursor_names: false,
1759 hovered_cursors: Default::default(),
1760 next_editor_action_id: EditorActionId::default(),
1761 editor_actions: Rc::default(),
1762 inline_completions_hidden_for_vim_mode: false,
1763 show_inline_completions_override: None,
1764 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1765 edit_prediction_settings: EditPredictionSettings::Disabled,
1766 edit_prediction_indent_conflict: false,
1767 edit_prediction_requires_modifier_in_indent_conflict: true,
1768 custom_context_menu: None,
1769 show_git_blame_gutter: false,
1770 show_git_blame_inline: false,
1771 show_selection_menu: None,
1772 show_git_blame_inline_delay_task: None,
1773 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1774 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1775 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1776 .session
1777 .restore_unsaved_buffers,
1778 blame: None,
1779 blame_subscription: None,
1780 tasks: Default::default(),
1781
1782 breakpoint_store,
1783 gutter_breakpoint_indicator: (None, None),
1784 _subscriptions: vec![
1785 cx.observe(&buffer, Self::on_buffer_changed),
1786 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1787 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1788 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1789 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1790 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1791 cx.observe_window_activation(window, |editor, window, cx| {
1792 let active = window.is_window_active();
1793 editor.blink_manager.update(cx, |blink_manager, cx| {
1794 if active {
1795 blink_manager.enable(cx);
1796 } else {
1797 blink_manager.disable(cx);
1798 }
1799 });
1800 }),
1801 ],
1802 tasks_update_task: None,
1803 linked_edit_ranges: Default::default(),
1804 in_project_search: false,
1805 previous_search_ranges: None,
1806 breadcrumb_header: None,
1807 focused_block: None,
1808 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1809 addons: HashMap::default(),
1810 registered_buffers: HashMap::default(),
1811 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1812 selection_mark_mode: false,
1813 toggle_fold_multiple_buffers: Task::ready(()),
1814 serialize_selections: Task::ready(()),
1815 serialize_folds: Task::ready(()),
1816 text_style_refinement: None,
1817 load_diff_task: load_uncommitted_diff,
1818 temporary_diff_override: false,
1819 mouse_cursor_hidden: false,
1820 hide_mouse_mode: EditorSettings::get_global(cx)
1821 .hide_mouse
1822 .unwrap_or_default(),
1823 change_list: ChangeList::new(),
1824 };
1825 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1826 this._subscriptions
1827 .push(cx.observe(breakpoints, |_, _, cx| {
1828 cx.notify();
1829 }));
1830 }
1831 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1832 this._subscriptions.extend(project_subscriptions);
1833
1834 this._subscriptions.push(cx.subscribe_in(
1835 &cx.entity(),
1836 window,
1837 |editor, _, e: &EditorEvent, window, cx| match e {
1838 EditorEvent::ScrollPositionChanged { local, .. } => {
1839 if *local {
1840 let new_anchor = editor.scroll_manager.anchor();
1841 let snapshot = editor.snapshot(window, cx);
1842 editor.update_restoration_data(cx, move |data| {
1843 data.scroll_position = (
1844 new_anchor.top_row(&snapshot.buffer_snapshot),
1845 new_anchor.offset,
1846 );
1847 });
1848 editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
1849 editor.inline_blame_popover.take();
1850 }
1851 }
1852 EditorEvent::Edited { .. } => {
1853 if !vim_enabled(cx) {
1854 let (map, selections) = editor.selections.all_adjusted_display(cx);
1855 let pop_state = editor
1856 .change_list
1857 .last()
1858 .map(|previous| {
1859 previous.len() == selections.len()
1860 && previous.iter().enumerate().all(|(ix, p)| {
1861 p.to_display_point(&map).row()
1862 == selections[ix].head().row()
1863 })
1864 })
1865 .unwrap_or(false);
1866 let new_positions = selections
1867 .into_iter()
1868 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1869 .collect();
1870 editor
1871 .change_list
1872 .push_to_change_list(pop_state, new_positions);
1873 }
1874 }
1875 _ => (),
1876 },
1877 ));
1878
1879 if let Some(dap_store) = this
1880 .project
1881 .as_ref()
1882 .map(|project| project.read(cx).dap_store())
1883 {
1884 let weak_editor = cx.weak_entity();
1885
1886 this._subscriptions
1887 .push(
1888 cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
1889 let session_entity = cx.entity();
1890 weak_editor
1891 .update(cx, |editor, cx| {
1892 editor._subscriptions.push(
1893 cx.subscribe(&session_entity, Self::on_debug_session_event),
1894 );
1895 })
1896 .ok();
1897 }),
1898 );
1899
1900 for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
1901 this._subscriptions
1902 .push(cx.subscribe(&session, Self::on_debug_session_event));
1903 }
1904 }
1905
1906 this.end_selection(window, cx);
1907 this.scroll_manager.show_scrollbars(window, cx);
1908 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1909
1910 if mode.is_full() {
1911 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1912 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1913
1914 if this.git_blame_inline_enabled {
1915 this.git_blame_inline_enabled = true;
1916 this.start_git_blame_inline(false, window, cx);
1917 }
1918
1919 this.go_to_active_debug_line(window, cx);
1920
1921 if let Some(buffer) = buffer.read(cx).as_singleton() {
1922 if let Some(project) = this.project.as_ref() {
1923 let handle = project.update(cx, |project, cx| {
1924 project.register_buffer_with_language_servers(&buffer, cx)
1925 });
1926 this.registered_buffers
1927 .insert(buffer.read(cx).remote_id(), handle);
1928 }
1929 }
1930 }
1931
1932 this.report_editor_event("Editor Opened", None, cx);
1933 this
1934 }
1935
1936 pub fn deploy_mouse_context_menu(
1937 &mut self,
1938 position: gpui::Point<Pixels>,
1939 context_menu: Entity<ContextMenu>,
1940 window: &mut Window,
1941 cx: &mut Context<Self>,
1942 ) {
1943 self.mouse_context_menu = Some(MouseContextMenu::new(
1944 self,
1945 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1946 context_menu,
1947 window,
1948 cx,
1949 ));
1950 }
1951
1952 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1953 self.mouse_context_menu
1954 .as_ref()
1955 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1956 }
1957
1958 pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1959 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1960 }
1961
1962 fn key_context_internal(
1963 &self,
1964 has_active_edit_prediction: bool,
1965 window: &Window,
1966 cx: &App,
1967 ) -> KeyContext {
1968 let mut key_context = KeyContext::new_with_defaults();
1969 key_context.add("Editor");
1970 let mode = match self.mode {
1971 EditorMode::SingleLine { .. } => "single_line",
1972 EditorMode::AutoHeight { .. } => "auto_height",
1973 EditorMode::Full { .. } => "full",
1974 };
1975
1976 if EditorSettings::jupyter_enabled(cx) {
1977 key_context.add("jupyter");
1978 }
1979
1980 key_context.set("mode", mode);
1981 if self.pending_rename.is_some() {
1982 key_context.add("renaming");
1983 }
1984
1985 match self.context_menu.borrow().as_ref() {
1986 Some(CodeContextMenu::Completions(_)) => {
1987 key_context.add("menu");
1988 key_context.add("showing_completions");
1989 }
1990 Some(CodeContextMenu::CodeActions(_)) => {
1991 key_context.add("menu");
1992 key_context.add("showing_code_actions")
1993 }
1994 None => {}
1995 }
1996
1997 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1998 if !self.focus_handle(cx).contains_focused(window, cx)
1999 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
2000 {
2001 for addon in self.addons.values() {
2002 addon.extend_key_context(&mut key_context, cx)
2003 }
2004 }
2005
2006 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
2007 if let Some(extension) = singleton_buffer
2008 .read(cx)
2009 .file()
2010 .and_then(|file| file.path().extension()?.to_str())
2011 {
2012 key_context.set("extension", extension.to_string());
2013 }
2014 } else {
2015 key_context.add("multibuffer");
2016 }
2017
2018 if has_active_edit_prediction {
2019 if self.edit_prediction_in_conflict() {
2020 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
2021 } else {
2022 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
2023 key_context.add("copilot_suggestion");
2024 }
2025 }
2026
2027 if self.selection_mark_mode {
2028 key_context.add("selection_mode");
2029 }
2030
2031 key_context
2032 }
2033
2034 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
2035 self.mouse_cursor_hidden = match origin {
2036 HideMouseCursorOrigin::TypingAction => {
2037 matches!(
2038 self.hide_mouse_mode,
2039 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
2040 )
2041 }
2042 HideMouseCursorOrigin::MovementAction => {
2043 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
2044 }
2045 };
2046 }
2047
2048 pub fn edit_prediction_in_conflict(&self) -> bool {
2049 if !self.show_edit_predictions_in_menu() {
2050 return false;
2051 }
2052
2053 let showing_completions = self
2054 .context_menu
2055 .borrow()
2056 .as_ref()
2057 .map_or(false, |context| {
2058 matches!(context, CodeContextMenu::Completions(_))
2059 });
2060
2061 showing_completions
2062 || self.edit_prediction_requires_modifier()
2063 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
2064 // bindings to insert tab characters.
2065 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
2066 }
2067
2068 pub fn accept_edit_prediction_keybind(
2069 &self,
2070 window: &Window,
2071 cx: &App,
2072 ) -> AcceptEditPredictionBinding {
2073 let key_context = self.key_context_internal(true, window, cx);
2074 let in_conflict = self.edit_prediction_in_conflict();
2075
2076 AcceptEditPredictionBinding(
2077 window
2078 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
2079 .into_iter()
2080 .filter(|binding| {
2081 !in_conflict
2082 || binding
2083 .keystrokes()
2084 .first()
2085 .map_or(false, |keystroke| keystroke.modifiers.modified())
2086 })
2087 .rev()
2088 .min_by_key(|binding| {
2089 binding
2090 .keystrokes()
2091 .first()
2092 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
2093 }),
2094 )
2095 }
2096
2097 pub fn new_file(
2098 workspace: &mut Workspace,
2099 _: &workspace::NewFile,
2100 window: &mut Window,
2101 cx: &mut Context<Workspace>,
2102 ) {
2103 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
2104 "Failed to create buffer",
2105 window,
2106 cx,
2107 |e, _, _| match e.error_code() {
2108 ErrorCode::RemoteUpgradeRequired => Some(format!(
2109 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2110 e.error_tag("required").unwrap_or("the latest version")
2111 )),
2112 _ => None,
2113 },
2114 );
2115 }
2116
2117 pub fn new_in_workspace(
2118 workspace: &mut Workspace,
2119 window: &mut Window,
2120 cx: &mut Context<Workspace>,
2121 ) -> Task<Result<Entity<Editor>>> {
2122 let project = workspace.project().clone();
2123 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2124
2125 cx.spawn_in(window, async move |workspace, cx| {
2126 let buffer = create.await?;
2127 workspace.update_in(cx, |workspace, window, cx| {
2128 let editor =
2129 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
2130 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2131 editor
2132 })
2133 })
2134 }
2135
2136 fn new_file_vertical(
2137 workspace: &mut Workspace,
2138 _: &workspace::NewFileSplitVertical,
2139 window: &mut Window,
2140 cx: &mut Context<Workspace>,
2141 ) {
2142 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
2143 }
2144
2145 fn new_file_horizontal(
2146 workspace: &mut Workspace,
2147 _: &workspace::NewFileSplitHorizontal,
2148 window: &mut Window,
2149 cx: &mut Context<Workspace>,
2150 ) {
2151 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2152 }
2153
2154 fn new_file_in_direction(
2155 workspace: &mut Workspace,
2156 direction: SplitDirection,
2157 window: &mut Window,
2158 cx: &mut Context<Workspace>,
2159 ) {
2160 let project = workspace.project().clone();
2161 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2162
2163 cx.spawn_in(window, async move |workspace, cx| {
2164 let buffer = create.await?;
2165 workspace.update_in(cx, move |workspace, window, cx| {
2166 workspace.split_item(
2167 direction,
2168 Box::new(
2169 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2170 ),
2171 window,
2172 cx,
2173 )
2174 })?;
2175 anyhow::Ok(())
2176 })
2177 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2178 match e.error_code() {
2179 ErrorCode::RemoteUpgradeRequired => Some(format!(
2180 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2181 e.error_tag("required").unwrap_or("the latest version")
2182 )),
2183 _ => None,
2184 }
2185 });
2186 }
2187
2188 pub fn leader_id(&self) -> Option<CollaboratorId> {
2189 self.leader_id
2190 }
2191
2192 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2193 &self.buffer
2194 }
2195
2196 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2197 self.workspace.as_ref()?.0.upgrade()
2198 }
2199
2200 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2201 self.buffer().read(cx).title(cx)
2202 }
2203
2204 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2205 let git_blame_gutter_max_author_length = self
2206 .render_git_blame_gutter(cx)
2207 .then(|| {
2208 if let Some(blame) = self.blame.as_ref() {
2209 let max_author_length =
2210 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2211 Some(max_author_length)
2212 } else {
2213 None
2214 }
2215 })
2216 .flatten();
2217
2218 EditorSnapshot {
2219 mode: self.mode,
2220 show_gutter: self.show_gutter,
2221 show_line_numbers: self.show_line_numbers,
2222 show_git_diff_gutter: self.show_git_diff_gutter,
2223 show_code_actions: self.show_code_actions,
2224 show_runnables: self.show_runnables,
2225 show_breakpoints: self.show_breakpoints,
2226 git_blame_gutter_max_author_length,
2227 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2228 scroll_anchor: self.scroll_manager.anchor(),
2229 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2230 placeholder_text: self.placeholder_text.clone(),
2231 is_focused: self.focus_handle.is_focused(window),
2232 current_line_highlight: self
2233 .current_line_highlight
2234 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2235 gutter_hovered: self.gutter_hovered,
2236 }
2237 }
2238
2239 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2240 self.buffer.read(cx).language_at(point, cx)
2241 }
2242
2243 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2244 self.buffer.read(cx).read(cx).file_at(point).cloned()
2245 }
2246
2247 pub fn active_excerpt(
2248 &self,
2249 cx: &App,
2250 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2251 self.buffer
2252 .read(cx)
2253 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2254 }
2255
2256 pub fn mode(&self) -> EditorMode {
2257 self.mode
2258 }
2259
2260 pub fn set_mode(&mut self, mode: EditorMode) {
2261 self.mode = mode;
2262 }
2263
2264 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2265 self.collaboration_hub.as_deref()
2266 }
2267
2268 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2269 self.collaboration_hub = Some(hub);
2270 }
2271
2272 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2273 self.in_project_search = in_project_search;
2274 }
2275
2276 pub fn set_custom_context_menu(
2277 &mut self,
2278 f: impl 'static
2279 + Fn(
2280 &mut Self,
2281 DisplayPoint,
2282 &mut Window,
2283 &mut Context<Self>,
2284 ) -> Option<Entity<ui::ContextMenu>>,
2285 ) {
2286 self.custom_context_menu = Some(Box::new(f))
2287 }
2288
2289 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2290 self.completion_provider = provider;
2291 }
2292
2293 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2294 self.semantics_provider.clone()
2295 }
2296
2297 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2298 self.semantics_provider = provider;
2299 }
2300
2301 pub fn set_edit_prediction_provider<T>(
2302 &mut self,
2303 provider: Option<Entity<T>>,
2304 window: &mut Window,
2305 cx: &mut Context<Self>,
2306 ) where
2307 T: EditPredictionProvider,
2308 {
2309 self.edit_prediction_provider =
2310 provider.map(|provider| RegisteredInlineCompletionProvider {
2311 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2312 if this.focus_handle.is_focused(window) {
2313 this.update_visible_inline_completion(window, cx);
2314 }
2315 }),
2316 provider: Arc::new(provider),
2317 });
2318 self.update_edit_prediction_settings(cx);
2319 self.refresh_inline_completion(false, false, window, cx);
2320 }
2321
2322 pub fn placeholder_text(&self) -> Option<&str> {
2323 self.placeholder_text.as_deref()
2324 }
2325
2326 pub fn set_placeholder_text(
2327 &mut self,
2328 placeholder_text: impl Into<Arc<str>>,
2329 cx: &mut Context<Self>,
2330 ) {
2331 let placeholder_text = Some(placeholder_text.into());
2332 if self.placeholder_text != placeholder_text {
2333 self.placeholder_text = placeholder_text;
2334 cx.notify();
2335 }
2336 }
2337
2338 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2339 self.cursor_shape = cursor_shape;
2340
2341 // Disrupt blink for immediate user feedback that the cursor shape has changed
2342 self.blink_manager.update(cx, BlinkManager::show_cursor);
2343
2344 cx.notify();
2345 }
2346
2347 pub fn set_current_line_highlight(
2348 &mut self,
2349 current_line_highlight: Option<CurrentLineHighlight>,
2350 ) {
2351 self.current_line_highlight = current_line_highlight;
2352 }
2353
2354 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2355 self.collapse_matches = collapse_matches;
2356 }
2357
2358 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2359 let buffers = self.buffer.read(cx).all_buffers();
2360 let Some(project) = self.project.as_ref() else {
2361 return;
2362 };
2363 project.update(cx, |project, cx| {
2364 for buffer in buffers {
2365 self.registered_buffers
2366 .entry(buffer.read(cx).remote_id())
2367 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2368 }
2369 })
2370 }
2371
2372 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2373 if self.collapse_matches {
2374 return range.start..range.start;
2375 }
2376 range.clone()
2377 }
2378
2379 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2380 if self.display_map.read(cx).clip_at_line_ends != clip {
2381 self.display_map
2382 .update(cx, |map, _| map.clip_at_line_ends = clip);
2383 }
2384 }
2385
2386 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2387 self.input_enabled = input_enabled;
2388 }
2389
2390 pub fn set_inline_completions_hidden_for_vim_mode(
2391 &mut self,
2392 hidden: bool,
2393 window: &mut Window,
2394 cx: &mut Context<Self>,
2395 ) {
2396 if hidden != self.inline_completions_hidden_for_vim_mode {
2397 self.inline_completions_hidden_for_vim_mode = hidden;
2398 if hidden {
2399 self.update_visible_inline_completion(window, cx);
2400 } else {
2401 self.refresh_inline_completion(true, false, window, cx);
2402 }
2403 }
2404 }
2405
2406 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2407 self.menu_inline_completions_policy = value;
2408 }
2409
2410 pub fn set_autoindent(&mut self, autoindent: bool) {
2411 if autoindent {
2412 self.autoindent_mode = Some(AutoindentMode::EachLine);
2413 } else {
2414 self.autoindent_mode = None;
2415 }
2416 }
2417
2418 pub fn read_only(&self, cx: &App) -> bool {
2419 self.read_only || self.buffer.read(cx).read_only()
2420 }
2421
2422 pub fn set_read_only(&mut self, read_only: bool) {
2423 self.read_only = read_only;
2424 }
2425
2426 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2427 self.use_autoclose = autoclose;
2428 }
2429
2430 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2431 self.use_auto_surround = auto_surround;
2432 }
2433
2434 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2435 self.auto_replace_emoji_shortcode = auto_replace;
2436 }
2437
2438 pub fn toggle_edit_predictions(
2439 &mut self,
2440 _: &ToggleEditPrediction,
2441 window: &mut Window,
2442 cx: &mut Context<Self>,
2443 ) {
2444 if self.show_inline_completions_override.is_some() {
2445 self.set_show_edit_predictions(None, window, cx);
2446 } else {
2447 let show_edit_predictions = !self.edit_predictions_enabled();
2448 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2449 }
2450 }
2451
2452 pub fn set_show_edit_predictions(
2453 &mut self,
2454 show_edit_predictions: Option<bool>,
2455 window: &mut Window,
2456 cx: &mut Context<Self>,
2457 ) {
2458 self.show_inline_completions_override = show_edit_predictions;
2459 self.update_edit_prediction_settings(cx);
2460
2461 if let Some(false) = show_edit_predictions {
2462 self.discard_inline_completion(false, cx);
2463 } else {
2464 self.refresh_inline_completion(false, true, window, cx);
2465 }
2466 }
2467
2468 fn inline_completions_disabled_in_scope(
2469 &self,
2470 buffer: &Entity<Buffer>,
2471 buffer_position: language::Anchor,
2472 cx: &App,
2473 ) -> bool {
2474 let snapshot = buffer.read(cx).snapshot();
2475 let settings = snapshot.settings_at(buffer_position, cx);
2476
2477 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2478 return false;
2479 };
2480
2481 scope.override_name().map_or(false, |scope_name| {
2482 settings
2483 .edit_predictions_disabled_in
2484 .iter()
2485 .any(|s| s == scope_name)
2486 })
2487 }
2488
2489 pub fn set_use_modal_editing(&mut self, to: bool) {
2490 self.use_modal_editing = to;
2491 }
2492
2493 pub fn use_modal_editing(&self) -> bool {
2494 self.use_modal_editing
2495 }
2496
2497 fn selections_did_change(
2498 &mut self,
2499 local: bool,
2500 old_cursor_position: &Anchor,
2501 show_completions: bool,
2502 window: &mut Window,
2503 cx: &mut Context<Self>,
2504 ) {
2505 window.invalidate_character_coordinates();
2506
2507 // Copy selections to primary selection buffer
2508 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2509 if local {
2510 let selections = self.selections.all::<usize>(cx);
2511 let buffer_handle = self.buffer.read(cx).read(cx);
2512
2513 let mut text = String::new();
2514 for (index, selection) in selections.iter().enumerate() {
2515 let text_for_selection = buffer_handle
2516 .text_for_range(selection.start..selection.end)
2517 .collect::<String>();
2518
2519 text.push_str(&text_for_selection);
2520 if index != selections.len() - 1 {
2521 text.push('\n');
2522 }
2523 }
2524
2525 if !text.is_empty() {
2526 cx.write_to_primary(ClipboardItem::new_string(text));
2527 }
2528 }
2529
2530 if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
2531 self.buffer.update(cx, |buffer, cx| {
2532 buffer.set_active_selections(
2533 &self.selections.disjoint_anchors(),
2534 self.selections.line_mode,
2535 self.cursor_shape,
2536 cx,
2537 )
2538 });
2539 }
2540 let display_map = self
2541 .display_map
2542 .update(cx, |display_map, cx| display_map.snapshot(cx));
2543 let buffer = &display_map.buffer_snapshot;
2544 self.add_selections_state = None;
2545 self.select_next_state = None;
2546 self.select_prev_state = None;
2547 self.select_syntax_node_history.try_clear();
2548 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2549 self.snippet_stack
2550 .invalidate(&self.selections.disjoint_anchors(), buffer);
2551 self.take_rename(false, window, cx);
2552
2553 let new_cursor_position = self.selections.newest_anchor().head();
2554
2555 self.push_to_nav_history(
2556 *old_cursor_position,
2557 Some(new_cursor_position.to_point(buffer)),
2558 false,
2559 cx,
2560 );
2561
2562 if local {
2563 let new_cursor_position = self.selections.newest_anchor().head();
2564 let mut context_menu = self.context_menu.borrow_mut();
2565 let completion_menu = match context_menu.as_ref() {
2566 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2567 _ => {
2568 *context_menu = None;
2569 None
2570 }
2571 };
2572 if let Some(buffer_id) = new_cursor_position.buffer_id {
2573 if !self.registered_buffers.contains_key(&buffer_id) {
2574 if let Some(project) = self.project.as_ref() {
2575 project.update(cx, |project, cx| {
2576 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2577 return;
2578 };
2579 self.registered_buffers.insert(
2580 buffer_id,
2581 project.register_buffer_with_language_servers(&buffer, cx),
2582 );
2583 })
2584 }
2585 }
2586 }
2587
2588 if let Some(completion_menu) = completion_menu {
2589 let cursor_position = new_cursor_position.to_offset(buffer);
2590 let (word_range, kind) =
2591 buffer.surrounding_word(completion_menu.initial_position, true);
2592 if kind == Some(CharKind::Word)
2593 && word_range.to_inclusive().contains(&cursor_position)
2594 {
2595 let mut completion_menu = completion_menu.clone();
2596 drop(context_menu);
2597
2598 let query = Self::completion_query(buffer, cursor_position);
2599 cx.spawn(async move |this, cx| {
2600 completion_menu
2601 .filter(query.as_deref(), cx.background_executor().clone())
2602 .await;
2603
2604 this.update(cx, |this, cx| {
2605 let mut context_menu = this.context_menu.borrow_mut();
2606 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2607 else {
2608 return;
2609 };
2610
2611 if menu.id > completion_menu.id {
2612 return;
2613 }
2614
2615 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2616 drop(context_menu);
2617 cx.notify();
2618 })
2619 })
2620 .detach();
2621
2622 if show_completions {
2623 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2624 }
2625 } else {
2626 drop(context_menu);
2627 self.hide_context_menu(window, cx);
2628 }
2629 } else {
2630 drop(context_menu);
2631 }
2632
2633 hide_hover(self, cx);
2634
2635 if old_cursor_position.to_display_point(&display_map).row()
2636 != new_cursor_position.to_display_point(&display_map).row()
2637 {
2638 self.available_code_actions.take();
2639 }
2640 self.refresh_code_actions(window, cx);
2641 self.refresh_document_highlights(cx);
2642 self.refresh_selected_text_highlights(false, window, cx);
2643 refresh_matching_bracket_highlights(self, window, cx);
2644 self.update_visible_inline_completion(window, cx);
2645 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2646 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2647 self.inline_blame_popover.take();
2648 if self.git_blame_inline_enabled {
2649 self.start_inline_blame_timer(window, cx);
2650 }
2651 }
2652
2653 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2654 cx.emit(EditorEvent::SelectionsChanged { local });
2655
2656 let selections = &self.selections.disjoint;
2657 if selections.len() == 1 {
2658 cx.emit(SearchEvent::ActiveMatchChanged)
2659 }
2660 if local {
2661 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2662 let inmemory_selections = selections
2663 .iter()
2664 .map(|s| {
2665 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2666 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2667 })
2668 .collect();
2669 self.update_restoration_data(cx, |data| {
2670 data.selections = inmemory_selections;
2671 });
2672
2673 if WorkspaceSettings::get(None, cx).restore_on_startup
2674 != RestoreOnStartupBehavior::None
2675 {
2676 if let Some(workspace_id) =
2677 self.workspace.as_ref().and_then(|workspace| workspace.1)
2678 {
2679 let snapshot = self.buffer().read(cx).snapshot(cx);
2680 let selections = selections.clone();
2681 let background_executor = cx.background_executor().clone();
2682 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2683 self.serialize_selections = cx.background_spawn(async move {
2684 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2685 let db_selections = selections
2686 .iter()
2687 .map(|selection| {
2688 (
2689 selection.start.to_offset(&snapshot),
2690 selection.end.to_offset(&snapshot),
2691 )
2692 })
2693 .collect();
2694
2695 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2696 .await
2697 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2698 .log_err();
2699 });
2700 }
2701 }
2702 }
2703 }
2704
2705 cx.notify();
2706 }
2707
2708 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2709 use text::ToOffset as _;
2710 use text::ToPoint as _;
2711
2712 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2713 return;
2714 }
2715
2716 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2717 return;
2718 };
2719
2720 let snapshot = singleton.read(cx).snapshot();
2721 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2722 let display_snapshot = display_map.snapshot(cx);
2723
2724 display_snapshot
2725 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2726 .map(|fold| {
2727 fold.range.start.text_anchor.to_point(&snapshot)
2728 ..fold.range.end.text_anchor.to_point(&snapshot)
2729 })
2730 .collect()
2731 });
2732 self.update_restoration_data(cx, |data| {
2733 data.folds = inmemory_folds;
2734 });
2735
2736 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2737 return;
2738 };
2739 let background_executor = cx.background_executor().clone();
2740 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2741 let db_folds = self.display_map.update(cx, |display_map, cx| {
2742 display_map
2743 .snapshot(cx)
2744 .folds_in_range(0..snapshot.len())
2745 .map(|fold| {
2746 (
2747 fold.range.start.text_anchor.to_offset(&snapshot),
2748 fold.range.end.text_anchor.to_offset(&snapshot),
2749 )
2750 })
2751 .collect()
2752 });
2753 self.serialize_folds = cx.background_spawn(async move {
2754 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2755 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2756 .await
2757 .with_context(|| {
2758 format!(
2759 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2760 )
2761 })
2762 .log_err();
2763 });
2764 }
2765
2766 pub fn sync_selections(
2767 &mut self,
2768 other: Entity<Editor>,
2769 cx: &mut Context<Self>,
2770 ) -> gpui::Subscription {
2771 let other_selections = other.read(cx).selections.disjoint.to_vec();
2772 self.selections.change_with(cx, |selections| {
2773 selections.select_anchors(other_selections);
2774 });
2775
2776 let other_subscription =
2777 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2778 EditorEvent::SelectionsChanged { local: true } => {
2779 let other_selections = other.read(cx).selections.disjoint.to_vec();
2780 if other_selections.is_empty() {
2781 return;
2782 }
2783 this.selections.change_with(cx, |selections| {
2784 selections.select_anchors(other_selections);
2785 });
2786 }
2787 _ => {}
2788 });
2789
2790 let this_subscription =
2791 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2792 EditorEvent::SelectionsChanged { local: true } => {
2793 let these_selections = this.selections.disjoint.to_vec();
2794 if these_selections.is_empty() {
2795 return;
2796 }
2797 other.update(cx, |other_editor, cx| {
2798 other_editor.selections.change_with(cx, |selections| {
2799 selections.select_anchors(these_selections);
2800 })
2801 });
2802 }
2803 _ => {}
2804 });
2805
2806 Subscription::join(other_subscription, this_subscription)
2807 }
2808
2809 pub fn change_selections<R>(
2810 &mut self,
2811 autoscroll: Option<Autoscroll>,
2812 window: &mut Window,
2813 cx: &mut Context<Self>,
2814 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2815 ) -> R {
2816 self.change_selections_inner(autoscroll, true, window, cx, change)
2817 }
2818
2819 fn change_selections_inner<R>(
2820 &mut self,
2821 autoscroll: Option<Autoscroll>,
2822 request_completions: bool,
2823 window: &mut Window,
2824 cx: &mut Context<Self>,
2825 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2826 ) -> R {
2827 let old_cursor_position = self.selections.newest_anchor().head();
2828 self.push_to_selection_history();
2829
2830 let (changed, result) = self.selections.change_with(cx, change);
2831
2832 if changed {
2833 if let Some(autoscroll) = autoscroll {
2834 self.request_autoscroll(autoscroll, cx);
2835 }
2836 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2837
2838 if self.should_open_signature_help_automatically(
2839 &old_cursor_position,
2840 self.signature_help_state.backspace_pressed(),
2841 cx,
2842 ) {
2843 self.show_signature_help(&ShowSignatureHelp, window, cx);
2844 }
2845 self.signature_help_state.set_backspace_pressed(false);
2846 }
2847
2848 result
2849 }
2850
2851 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2852 where
2853 I: IntoIterator<Item = (Range<S>, T)>,
2854 S: ToOffset,
2855 T: Into<Arc<str>>,
2856 {
2857 if self.read_only(cx) {
2858 return;
2859 }
2860
2861 self.buffer
2862 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2863 }
2864
2865 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2866 where
2867 I: IntoIterator<Item = (Range<S>, T)>,
2868 S: ToOffset,
2869 T: Into<Arc<str>>,
2870 {
2871 if self.read_only(cx) {
2872 return;
2873 }
2874
2875 self.buffer.update(cx, |buffer, cx| {
2876 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2877 });
2878 }
2879
2880 pub fn edit_with_block_indent<I, S, T>(
2881 &mut self,
2882 edits: I,
2883 original_indent_columns: Vec<Option<u32>>,
2884 cx: &mut Context<Self>,
2885 ) where
2886 I: IntoIterator<Item = (Range<S>, T)>,
2887 S: ToOffset,
2888 T: Into<Arc<str>>,
2889 {
2890 if self.read_only(cx) {
2891 return;
2892 }
2893
2894 self.buffer.update(cx, |buffer, cx| {
2895 buffer.edit(
2896 edits,
2897 Some(AutoindentMode::Block {
2898 original_indent_columns,
2899 }),
2900 cx,
2901 )
2902 });
2903 }
2904
2905 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2906 self.hide_context_menu(window, cx);
2907
2908 match phase {
2909 SelectPhase::Begin {
2910 position,
2911 add,
2912 click_count,
2913 } => self.begin_selection(position, add, click_count, window, cx),
2914 SelectPhase::BeginColumnar {
2915 position,
2916 goal_column,
2917 reset,
2918 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2919 SelectPhase::Extend {
2920 position,
2921 click_count,
2922 } => self.extend_selection(position, click_count, window, cx),
2923 SelectPhase::Update {
2924 position,
2925 goal_column,
2926 scroll_delta,
2927 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2928 SelectPhase::End => self.end_selection(window, cx),
2929 }
2930 }
2931
2932 fn extend_selection(
2933 &mut self,
2934 position: DisplayPoint,
2935 click_count: usize,
2936 window: &mut Window,
2937 cx: &mut Context<Self>,
2938 ) {
2939 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2940 let tail = self.selections.newest::<usize>(cx).tail();
2941 self.begin_selection(position, false, click_count, window, cx);
2942
2943 let position = position.to_offset(&display_map, Bias::Left);
2944 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2945
2946 let mut pending_selection = self
2947 .selections
2948 .pending_anchor()
2949 .expect("extend_selection not called with pending selection");
2950 if position >= tail {
2951 pending_selection.start = tail_anchor;
2952 } else {
2953 pending_selection.end = tail_anchor;
2954 pending_selection.reversed = true;
2955 }
2956
2957 let mut pending_mode = self.selections.pending_mode().unwrap();
2958 match &mut pending_mode {
2959 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2960 _ => {}
2961 }
2962
2963 let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
2964
2965 self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
2966 s.set_pending(pending_selection, pending_mode)
2967 });
2968 }
2969
2970 fn begin_selection(
2971 &mut self,
2972 position: DisplayPoint,
2973 add: bool,
2974 click_count: usize,
2975 window: &mut Window,
2976 cx: &mut Context<Self>,
2977 ) {
2978 if !self.focus_handle.is_focused(window) {
2979 self.last_focused_descendant = None;
2980 window.focus(&self.focus_handle);
2981 }
2982
2983 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2984 let buffer = &display_map.buffer_snapshot;
2985 let position = display_map.clip_point(position, Bias::Left);
2986
2987 let start;
2988 let end;
2989 let mode;
2990 let mut auto_scroll;
2991 match click_count {
2992 1 => {
2993 start = buffer.anchor_before(position.to_point(&display_map));
2994 end = start;
2995 mode = SelectMode::Character;
2996 auto_scroll = true;
2997 }
2998 2 => {
2999 let range = movement::surrounding_word(&display_map, position);
3000 start = buffer.anchor_before(range.start.to_point(&display_map));
3001 end = buffer.anchor_before(range.end.to_point(&display_map));
3002 mode = SelectMode::Word(start..end);
3003 auto_scroll = true;
3004 }
3005 3 => {
3006 let position = display_map
3007 .clip_point(position, Bias::Left)
3008 .to_point(&display_map);
3009 let line_start = display_map.prev_line_boundary(position).0;
3010 let next_line_start = buffer.clip_point(
3011 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3012 Bias::Left,
3013 );
3014 start = buffer.anchor_before(line_start);
3015 end = buffer.anchor_before(next_line_start);
3016 mode = SelectMode::Line(start..end);
3017 auto_scroll = true;
3018 }
3019 _ => {
3020 start = buffer.anchor_before(0);
3021 end = buffer.anchor_before(buffer.len());
3022 mode = SelectMode::All;
3023 auto_scroll = false;
3024 }
3025 }
3026 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
3027
3028 let point_to_delete: Option<usize> = {
3029 let selected_points: Vec<Selection<Point>> =
3030 self.selections.disjoint_in_range(start..end, cx);
3031
3032 if !add || click_count > 1 {
3033 None
3034 } else if !selected_points.is_empty() {
3035 Some(selected_points[0].id)
3036 } else {
3037 let clicked_point_already_selected =
3038 self.selections.disjoint.iter().find(|selection| {
3039 selection.start.to_point(buffer) == start.to_point(buffer)
3040 || selection.end.to_point(buffer) == end.to_point(buffer)
3041 });
3042
3043 clicked_point_already_selected.map(|selection| selection.id)
3044 }
3045 };
3046
3047 let selections_count = self.selections.count();
3048
3049 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
3050 if let Some(point_to_delete) = point_to_delete {
3051 s.delete(point_to_delete);
3052
3053 if selections_count == 1 {
3054 s.set_pending_anchor_range(start..end, mode);
3055 }
3056 } else {
3057 if !add {
3058 s.clear_disjoint();
3059 }
3060
3061 s.set_pending_anchor_range(start..end, mode);
3062 }
3063 });
3064 }
3065
3066 fn begin_columnar_selection(
3067 &mut self,
3068 position: DisplayPoint,
3069 goal_column: u32,
3070 reset: bool,
3071 window: &mut Window,
3072 cx: &mut Context<Self>,
3073 ) {
3074 if !self.focus_handle.is_focused(window) {
3075 self.last_focused_descendant = None;
3076 window.focus(&self.focus_handle);
3077 }
3078
3079 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3080
3081 if reset {
3082 let pointer_position = display_map
3083 .buffer_snapshot
3084 .anchor_before(position.to_point(&display_map));
3085
3086 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
3087 s.clear_disjoint();
3088 s.set_pending_anchor_range(
3089 pointer_position..pointer_position,
3090 SelectMode::Character,
3091 );
3092 });
3093 }
3094
3095 let tail = self.selections.newest::<Point>(cx).tail();
3096 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3097
3098 if !reset {
3099 self.select_columns(
3100 tail.to_display_point(&display_map),
3101 position,
3102 goal_column,
3103 &display_map,
3104 window,
3105 cx,
3106 );
3107 }
3108 }
3109
3110 fn update_selection(
3111 &mut self,
3112 position: DisplayPoint,
3113 goal_column: u32,
3114 scroll_delta: gpui::Point<f32>,
3115 window: &mut Window,
3116 cx: &mut Context<Self>,
3117 ) {
3118 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3119
3120 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3121 let tail = tail.to_display_point(&display_map);
3122 self.select_columns(tail, position, goal_column, &display_map, window, cx);
3123 } else if let Some(mut pending) = self.selections.pending_anchor() {
3124 let buffer = self.buffer.read(cx).snapshot(cx);
3125 let head;
3126 let tail;
3127 let mode = self.selections.pending_mode().unwrap();
3128 match &mode {
3129 SelectMode::Character => {
3130 head = position.to_point(&display_map);
3131 tail = pending.tail().to_point(&buffer);
3132 }
3133 SelectMode::Word(original_range) => {
3134 let original_display_range = original_range.start.to_display_point(&display_map)
3135 ..original_range.end.to_display_point(&display_map);
3136 let original_buffer_range = original_display_range.start.to_point(&display_map)
3137 ..original_display_range.end.to_point(&display_map);
3138 if movement::is_inside_word(&display_map, position)
3139 || original_display_range.contains(&position)
3140 {
3141 let word_range = movement::surrounding_word(&display_map, position);
3142 if word_range.start < original_display_range.start {
3143 head = word_range.start.to_point(&display_map);
3144 } else {
3145 head = word_range.end.to_point(&display_map);
3146 }
3147 } else {
3148 head = position.to_point(&display_map);
3149 }
3150
3151 if head <= original_buffer_range.start {
3152 tail = original_buffer_range.end;
3153 } else {
3154 tail = original_buffer_range.start;
3155 }
3156 }
3157 SelectMode::Line(original_range) => {
3158 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3159
3160 let position = display_map
3161 .clip_point(position, Bias::Left)
3162 .to_point(&display_map);
3163 let line_start = display_map.prev_line_boundary(position).0;
3164 let next_line_start = buffer.clip_point(
3165 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3166 Bias::Left,
3167 );
3168
3169 if line_start < original_range.start {
3170 head = line_start
3171 } else {
3172 head = next_line_start
3173 }
3174
3175 if head <= original_range.start {
3176 tail = original_range.end;
3177 } else {
3178 tail = original_range.start;
3179 }
3180 }
3181 SelectMode::All => {
3182 return;
3183 }
3184 };
3185
3186 if head < tail {
3187 pending.start = buffer.anchor_before(head);
3188 pending.end = buffer.anchor_before(tail);
3189 pending.reversed = true;
3190 } else {
3191 pending.start = buffer.anchor_before(tail);
3192 pending.end = buffer.anchor_before(head);
3193 pending.reversed = false;
3194 }
3195
3196 self.change_selections(None, window, cx, |s| {
3197 s.set_pending(pending, mode);
3198 });
3199 } else {
3200 log::error!("update_selection dispatched with no pending selection");
3201 return;
3202 }
3203
3204 self.apply_scroll_delta(scroll_delta, window, cx);
3205 cx.notify();
3206 }
3207
3208 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3209 self.columnar_selection_tail.take();
3210 if self.selections.pending_anchor().is_some() {
3211 let selections = self.selections.all::<usize>(cx);
3212 self.change_selections(None, window, cx, |s| {
3213 s.select(selections);
3214 s.clear_pending();
3215 });
3216 }
3217 }
3218
3219 fn select_columns(
3220 &mut self,
3221 tail: DisplayPoint,
3222 head: DisplayPoint,
3223 goal_column: u32,
3224 display_map: &DisplaySnapshot,
3225 window: &mut Window,
3226 cx: &mut Context<Self>,
3227 ) {
3228 let start_row = cmp::min(tail.row(), head.row());
3229 let end_row = cmp::max(tail.row(), head.row());
3230 let start_column = cmp::min(tail.column(), goal_column);
3231 let end_column = cmp::max(tail.column(), goal_column);
3232 let reversed = start_column < tail.column();
3233
3234 let selection_ranges = (start_row.0..=end_row.0)
3235 .map(DisplayRow)
3236 .filter_map(|row| {
3237 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3238 let start = display_map
3239 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3240 .to_point(display_map);
3241 let end = display_map
3242 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3243 .to_point(display_map);
3244 if reversed {
3245 Some(end..start)
3246 } else {
3247 Some(start..end)
3248 }
3249 } else {
3250 None
3251 }
3252 })
3253 .collect::<Vec<_>>();
3254
3255 self.change_selections(None, window, cx, |s| {
3256 s.select_ranges(selection_ranges);
3257 });
3258 cx.notify();
3259 }
3260
3261 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3262 self.selections
3263 .all_adjusted(cx)
3264 .iter()
3265 .any(|selection| !selection.is_empty())
3266 }
3267
3268 pub fn has_pending_nonempty_selection(&self) -> bool {
3269 let pending_nonempty_selection = match self.selections.pending_anchor() {
3270 Some(Selection { start, end, .. }) => start != end,
3271 None => false,
3272 };
3273
3274 pending_nonempty_selection
3275 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3276 }
3277
3278 pub fn has_pending_selection(&self) -> bool {
3279 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3280 }
3281
3282 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3283 self.selection_mark_mode = false;
3284
3285 if self.clear_expanded_diff_hunks(cx) {
3286 cx.notify();
3287 return;
3288 }
3289 if self.dismiss_menus_and_popups(true, window, cx) {
3290 return;
3291 }
3292
3293 if self.mode.is_full()
3294 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3295 {
3296 return;
3297 }
3298
3299 cx.propagate();
3300 }
3301
3302 pub fn dismiss_menus_and_popups(
3303 &mut self,
3304 is_user_requested: bool,
3305 window: &mut Window,
3306 cx: &mut Context<Self>,
3307 ) -> bool {
3308 if self.take_rename(false, window, cx).is_some() {
3309 return true;
3310 }
3311
3312 if hide_hover(self, cx) {
3313 return true;
3314 }
3315
3316 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3317 return true;
3318 }
3319
3320 if self.hide_context_menu(window, cx).is_some() {
3321 return true;
3322 }
3323
3324 if self.mouse_context_menu.take().is_some() {
3325 return true;
3326 }
3327
3328 if is_user_requested && self.discard_inline_completion(true, cx) {
3329 return true;
3330 }
3331
3332 if self.snippet_stack.pop().is_some() {
3333 return true;
3334 }
3335
3336 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3337 self.dismiss_diagnostics(cx);
3338 return true;
3339 }
3340
3341 false
3342 }
3343
3344 fn linked_editing_ranges_for(
3345 &self,
3346 selection: Range<text::Anchor>,
3347 cx: &App,
3348 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3349 if self.linked_edit_ranges.is_empty() {
3350 return None;
3351 }
3352 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3353 selection.end.buffer_id.and_then(|end_buffer_id| {
3354 if selection.start.buffer_id != Some(end_buffer_id) {
3355 return None;
3356 }
3357 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3358 let snapshot = buffer.read(cx).snapshot();
3359 self.linked_edit_ranges
3360 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3361 .map(|ranges| (ranges, snapshot, buffer))
3362 })?;
3363 use text::ToOffset as TO;
3364 // find offset from the start of current range to current cursor position
3365 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3366
3367 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3368 let start_difference = start_offset - start_byte_offset;
3369 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3370 let end_difference = end_offset - start_byte_offset;
3371 // Current range has associated linked ranges.
3372 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3373 for range in linked_ranges.iter() {
3374 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3375 let end_offset = start_offset + end_difference;
3376 let start_offset = start_offset + start_difference;
3377 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3378 continue;
3379 }
3380 if self.selections.disjoint_anchor_ranges().any(|s| {
3381 if s.start.buffer_id != selection.start.buffer_id
3382 || s.end.buffer_id != selection.end.buffer_id
3383 {
3384 return false;
3385 }
3386 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3387 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3388 }) {
3389 continue;
3390 }
3391 let start = buffer_snapshot.anchor_after(start_offset);
3392 let end = buffer_snapshot.anchor_after(end_offset);
3393 linked_edits
3394 .entry(buffer.clone())
3395 .or_default()
3396 .push(start..end);
3397 }
3398 Some(linked_edits)
3399 }
3400
3401 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3402 let text: Arc<str> = text.into();
3403
3404 if self.read_only(cx) {
3405 return;
3406 }
3407
3408 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3409
3410 let selections = self.selections.all_adjusted(cx);
3411 let mut bracket_inserted = false;
3412 let mut edits = Vec::new();
3413 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3414 let mut new_selections = Vec::with_capacity(selections.len());
3415 let mut new_autoclose_regions = Vec::new();
3416 let snapshot = self.buffer.read(cx).read(cx);
3417 let mut clear_linked_edit_ranges = false;
3418
3419 for (selection, autoclose_region) in
3420 self.selections_with_autoclose_regions(selections, &snapshot)
3421 {
3422 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3423 // Determine if the inserted text matches the opening or closing
3424 // bracket of any of this language's bracket pairs.
3425 let mut bracket_pair = None;
3426 let mut is_bracket_pair_start = false;
3427 let mut is_bracket_pair_end = false;
3428 if !text.is_empty() {
3429 let mut bracket_pair_matching_end = None;
3430 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3431 // and they are removing the character that triggered IME popup.
3432 for (pair, enabled) in scope.brackets() {
3433 if !pair.close && !pair.surround {
3434 continue;
3435 }
3436
3437 if enabled && pair.start.ends_with(text.as_ref()) {
3438 let prefix_len = pair.start.len() - text.len();
3439 let preceding_text_matches_prefix = prefix_len == 0
3440 || (selection.start.column >= (prefix_len as u32)
3441 && snapshot.contains_str_at(
3442 Point::new(
3443 selection.start.row,
3444 selection.start.column - (prefix_len as u32),
3445 ),
3446 &pair.start[..prefix_len],
3447 ));
3448 if preceding_text_matches_prefix {
3449 bracket_pair = Some(pair.clone());
3450 is_bracket_pair_start = true;
3451 break;
3452 }
3453 }
3454 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3455 {
3456 // take first bracket pair matching end, but don't break in case a later bracket
3457 // pair matches start
3458 bracket_pair_matching_end = Some(pair.clone());
3459 }
3460 }
3461 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3462 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3463 is_bracket_pair_end = true;
3464 }
3465 }
3466
3467 if let Some(bracket_pair) = bracket_pair {
3468 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3469 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3470 let auto_surround =
3471 self.use_auto_surround && snapshot_settings.use_auto_surround;
3472 if selection.is_empty() {
3473 if is_bracket_pair_start {
3474 // If the inserted text is a suffix of an opening bracket and the
3475 // selection is preceded by the rest of the opening bracket, then
3476 // insert the closing bracket.
3477 let following_text_allows_autoclose = snapshot
3478 .chars_at(selection.start)
3479 .next()
3480 .map_or(true, |c| scope.should_autoclose_before(c));
3481
3482 let preceding_text_allows_autoclose = selection.start.column == 0
3483 || snapshot.reversed_chars_at(selection.start).next().map_or(
3484 true,
3485 |c| {
3486 bracket_pair.start != bracket_pair.end
3487 || !snapshot
3488 .char_classifier_at(selection.start)
3489 .is_word(c)
3490 },
3491 );
3492
3493 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3494 && bracket_pair.start.len() == 1
3495 {
3496 let target = bracket_pair.start.chars().next().unwrap();
3497 let current_line_count = snapshot
3498 .reversed_chars_at(selection.start)
3499 .take_while(|&c| c != '\n')
3500 .filter(|&c| c == target)
3501 .count();
3502 current_line_count % 2 == 1
3503 } else {
3504 false
3505 };
3506
3507 if autoclose
3508 && bracket_pair.close
3509 && following_text_allows_autoclose
3510 && preceding_text_allows_autoclose
3511 && !is_closing_quote
3512 {
3513 let anchor = snapshot.anchor_before(selection.end);
3514 new_selections.push((selection.map(|_| anchor), text.len()));
3515 new_autoclose_regions.push((
3516 anchor,
3517 text.len(),
3518 selection.id,
3519 bracket_pair.clone(),
3520 ));
3521 edits.push((
3522 selection.range(),
3523 format!("{}{}", text, bracket_pair.end).into(),
3524 ));
3525 bracket_inserted = true;
3526 continue;
3527 }
3528 }
3529
3530 if let Some(region) = autoclose_region {
3531 // If the selection is followed by an auto-inserted closing bracket,
3532 // then don't insert that closing bracket again; just move the selection
3533 // past the closing bracket.
3534 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3535 && text.as_ref() == region.pair.end.as_str();
3536 if should_skip {
3537 let anchor = snapshot.anchor_after(selection.end);
3538 new_selections
3539 .push((selection.map(|_| anchor), region.pair.end.len()));
3540 continue;
3541 }
3542 }
3543
3544 let always_treat_brackets_as_autoclosed = snapshot
3545 .language_settings_at(selection.start, cx)
3546 .always_treat_brackets_as_autoclosed;
3547 if always_treat_brackets_as_autoclosed
3548 && is_bracket_pair_end
3549 && snapshot.contains_str_at(selection.end, text.as_ref())
3550 {
3551 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3552 // and the inserted text is a closing bracket and the selection is followed
3553 // by the closing bracket then move the selection past the closing bracket.
3554 let anchor = snapshot.anchor_after(selection.end);
3555 new_selections.push((selection.map(|_| anchor), text.len()));
3556 continue;
3557 }
3558 }
3559 // If an opening bracket is 1 character long and is typed while
3560 // text is selected, then surround that text with the bracket pair.
3561 else if auto_surround
3562 && bracket_pair.surround
3563 && is_bracket_pair_start
3564 && bracket_pair.start.chars().count() == 1
3565 {
3566 edits.push((selection.start..selection.start, text.clone()));
3567 edits.push((
3568 selection.end..selection.end,
3569 bracket_pair.end.as_str().into(),
3570 ));
3571 bracket_inserted = true;
3572 new_selections.push((
3573 Selection {
3574 id: selection.id,
3575 start: snapshot.anchor_after(selection.start),
3576 end: snapshot.anchor_before(selection.end),
3577 reversed: selection.reversed,
3578 goal: selection.goal,
3579 },
3580 0,
3581 ));
3582 continue;
3583 }
3584 }
3585 }
3586
3587 if self.auto_replace_emoji_shortcode
3588 && selection.is_empty()
3589 && text.as_ref().ends_with(':')
3590 {
3591 if let Some(possible_emoji_short_code) =
3592 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3593 {
3594 if !possible_emoji_short_code.is_empty() {
3595 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3596 let emoji_shortcode_start = Point::new(
3597 selection.start.row,
3598 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3599 );
3600
3601 // Remove shortcode from buffer
3602 edits.push((
3603 emoji_shortcode_start..selection.start,
3604 "".to_string().into(),
3605 ));
3606 new_selections.push((
3607 Selection {
3608 id: selection.id,
3609 start: snapshot.anchor_after(emoji_shortcode_start),
3610 end: snapshot.anchor_before(selection.start),
3611 reversed: selection.reversed,
3612 goal: selection.goal,
3613 },
3614 0,
3615 ));
3616
3617 // Insert emoji
3618 let selection_start_anchor = snapshot.anchor_after(selection.start);
3619 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3620 edits.push((selection.start..selection.end, emoji.to_string().into()));
3621
3622 continue;
3623 }
3624 }
3625 }
3626 }
3627
3628 // If not handling any auto-close operation, then just replace the selected
3629 // text with the given input and move the selection to the end of the
3630 // newly inserted text.
3631 let anchor = snapshot.anchor_after(selection.end);
3632 if !self.linked_edit_ranges.is_empty() {
3633 let start_anchor = snapshot.anchor_before(selection.start);
3634
3635 let is_word_char = text.chars().next().map_or(true, |char| {
3636 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3637 classifier.is_word(char)
3638 });
3639
3640 if is_word_char {
3641 if let Some(ranges) = self
3642 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3643 {
3644 for (buffer, edits) in ranges {
3645 linked_edits
3646 .entry(buffer.clone())
3647 .or_default()
3648 .extend(edits.into_iter().map(|range| (range, text.clone())));
3649 }
3650 }
3651 } else {
3652 clear_linked_edit_ranges = true;
3653 }
3654 }
3655
3656 new_selections.push((selection.map(|_| anchor), 0));
3657 edits.push((selection.start..selection.end, text.clone()));
3658 }
3659
3660 drop(snapshot);
3661
3662 self.transact(window, cx, |this, window, cx| {
3663 if clear_linked_edit_ranges {
3664 this.linked_edit_ranges.clear();
3665 }
3666 let initial_buffer_versions =
3667 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3668
3669 this.buffer.update(cx, |buffer, cx| {
3670 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3671 });
3672 for (buffer, edits) in linked_edits {
3673 buffer.update(cx, |buffer, cx| {
3674 let snapshot = buffer.snapshot();
3675 let edits = edits
3676 .into_iter()
3677 .map(|(range, text)| {
3678 use text::ToPoint as TP;
3679 let end_point = TP::to_point(&range.end, &snapshot);
3680 let start_point = TP::to_point(&range.start, &snapshot);
3681 (start_point..end_point, text)
3682 })
3683 .sorted_by_key(|(range, _)| range.start);
3684 buffer.edit(edits, None, cx);
3685 })
3686 }
3687 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3688 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3689 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3690 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3691 .zip(new_selection_deltas)
3692 .map(|(selection, delta)| Selection {
3693 id: selection.id,
3694 start: selection.start + delta,
3695 end: selection.end + delta,
3696 reversed: selection.reversed,
3697 goal: SelectionGoal::None,
3698 })
3699 .collect::<Vec<_>>();
3700
3701 let mut i = 0;
3702 for (position, delta, selection_id, pair) in new_autoclose_regions {
3703 let position = position.to_offset(&map.buffer_snapshot) + delta;
3704 let start = map.buffer_snapshot.anchor_before(position);
3705 let end = map.buffer_snapshot.anchor_after(position);
3706 while let Some(existing_state) = this.autoclose_regions.get(i) {
3707 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3708 Ordering::Less => i += 1,
3709 Ordering::Greater => break,
3710 Ordering::Equal => {
3711 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3712 Ordering::Less => i += 1,
3713 Ordering::Equal => break,
3714 Ordering::Greater => break,
3715 }
3716 }
3717 }
3718 }
3719 this.autoclose_regions.insert(
3720 i,
3721 AutocloseRegion {
3722 selection_id,
3723 range: start..end,
3724 pair,
3725 },
3726 );
3727 }
3728
3729 let had_active_inline_completion = this.has_active_inline_completion();
3730 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3731 s.select(new_selections)
3732 });
3733
3734 if !bracket_inserted {
3735 if let Some(on_type_format_task) =
3736 this.trigger_on_type_formatting(text.to_string(), window, cx)
3737 {
3738 on_type_format_task.detach_and_log_err(cx);
3739 }
3740 }
3741
3742 let editor_settings = EditorSettings::get_global(cx);
3743 if bracket_inserted
3744 && (editor_settings.auto_signature_help
3745 || editor_settings.show_signature_help_after_edits)
3746 {
3747 this.show_signature_help(&ShowSignatureHelp, window, cx);
3748 }
3749
3750 let trigger_in_words =
3751 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3752 if this.hard_wrap.is_some() {
3753 let latest: Range<Point> = this.selections.newest(cx).range();
3754 if latest.is_empty()
3755 && this
3756 .buffer()
3757 .read(cx)
3758 .snapshot(cx)
3759 .line_len(MultiBufferRow(latest.start.row))
3760 == latest.start.column
3761 {
3762 this.rewrap_impl(
3763 RewrapOptions {
3764 override_language_settings: true,
3765 preserve_existing_whitespace: true,
3766 },
3767 cx,
3768 )
3769 }
3770 }
3771 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3772 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3773 this.refresh_inline_completion(true, false, window, cx);
3774 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3775 });
3776 }
3777
3778 fn find_possible_emoji_shortcode_at_position(
3779 snapshot: &MultiBufferSnapshot,
3780 position: Point,
3781 ) -> Option<String> {
3782 let mut chars = Vec::new();
3783 let mut found_colon = false;
3784 for char in snapshot.reversed_chars_at(position).take(100) {
3785 // Found a possible emoji shortcode in the middle of the buffer
3786 if found_colon {
3787 if char.is_whitespace() {
3788 chars.reverse();
3789 return Some(chars.iter().collect());
3790 }
3791 // If the previous character is not a whitespace, we are in the middle of a word
3792 // and we only want to complete the shortcode if the word is made up of other emojis
3793 let mut containing_word = String::new();
3794 for ch in snapshot
3795 .reversed_chars_at(position)
3796 .skip(chars.len() + 1)
3797 .take(100)
3798 {
3799 if ch.is_whitespace() {
3800 break;
3801 }
3802 containing_word.push(ch);
3803 }
3804 let containing_word = containing_word.chars().rev().collect::<String>();
3805 if util::word_consists_of_emojis(containing_word.as_str()) {
3806 chars.reverse();
3807 return Some(chars.iter().collect());
3808 }
3809 }
3810
3811 if char.is_whitespace() || !char.is_ascii() {
3812 return None;
3813 }
3814 if char == ':' {
3815 found_colon = true;
3816 } else {
3817 chars.push(char);
3818 }
3819 }
3820 // Found a possible emoji shortcode at the beginning of the buffer
3821 chars.reverse();
3822 Some(chars.iter().collect())
3823 }
3824
3825 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3826 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3827 self.transact(window, cx, |this, window, cx| {
3828 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3829 let selections = this.selections.all::<usize>(cx);
3830 let multi_buffer = this.buffer.read(cx);
3831 let buffer = multi_buffer.snapshot(cx);
3832 selections
3833 .iter()
3834 .map(|selection| {
3835 let start_point = selection.start.to_point(&buffer);
3836 let mut indent =
3837 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3838 indent.len = cmp::min(indent.len, start_point.column);
3839 let start = selection.start;
3840 let end = selection.end;
3841 let selection_is_empty = start == end;
3842 let language_scope = buffer.language_scope_at(start);
3843 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3844 &language_scope
3845 {
3846 let insert_extra_newline =
3847 insert_extra_newline_brackets(&buffer, start..end, language)
3848 || insert_extra_newline_tree_sitter(&buffer, start..end);
3849
3850 // Comment extension on newline is allowed only for cursor selections
3851 let comment_delimiter = maybe!({
3852 if !selection_is_empty {
3853 return None;
3854 }
3855
3856 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3857 return None;
3858 }
3859
3860 let delimiters = language.line_comment_prefixes();
3861 let max_len_of_delimiter =
3862 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3863 let (snapshot, range) =
3864 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3865
3866 let mut index_of_first_non_whitespace = 0;
3867 let comment_candidate = snapshot
3868 .chars_for_range(range)
3869 .skip_while(|c| {
3870 let should_skip = c.is_whitespace();
3871 if should_skip {
3872 index_of_first_non_whitespace += 1;
3873 }
3874 should_skip
3875 })
3876 .take(max_len_of_delimiter)
3877 .collect::<String>();
3878 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3879 comment_candidate.starts_with(comment_prefix.as_ref())
3880 })?;
3881 let cursor_is_placed_after_comment_marker =
3882 index_of_first_non_whitespace + comment_prefix.len()
3883 <= start_point.column as usize;
3884 if cursor_is_placed_after_comment_marker {
3885 Some(comment_prefix.clone())
3886 } else {
3887 None
3888 }
3889 });
3890 (comment_delimiter, insert_extra_newline)
3891 } else {
3892 (None, false)
3893 };
3894
3895 let capacity_for_delimiter = comment_delimiter
3896 .as_deref()
3897 .map(str::len)
3898 .unwrap_or_default();
3899 let mut new_text =
3900 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3901 new_text.push('\n');
3902 new_text.extend(indent.chars());
3903 if let Some(delimiter) = &comment_delimiter {
3904 new_text.push_str(delimiter);
3905 }
3906 if insert_extra_newline {
3907 new_text = new_text.repeat(2);
3908 }
3909
3910 let anchor = buffer.anchor_after(end);
3911 let new_selection = selection.map(|_| anchor);
3912 (
3913 (start..end, new_text),
3914 (insert_extra_newline, new_selection),
3915 )
3916 })
3917 .unzip()
3918 };
3919
3920 this.edit_with_autoindent(edits, cx);
3921 let buffer = this.buffer.read(cx).snapshot(cx);
3922 let new_selections = selection_fixup_info
3923 .into_iter()
3924 .map(|(extra_newline_inserted, new_selection)| {
3925 let mut cursor = new_selection.end.to_point(&buffer);
3926 if extra_newline_inserted {
3927 cursor.row -= 1;
3928 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3929 }
3930 new_selection.map(|_| cursor)
3931 })
3932 .collect();
3933
3934 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3935 s.select(new_selections)
3936 });
3937 this.refresh_inline_completion(true, false, window, cx);
3938 });
3939 }
3940
3941 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3942 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3943
3944 let buffer = self.buffer.read(cx);
3945 let snapshot = buffer.snapshot(cx);
3946
3947 let mut edits = Vec::new();
3948 let mut rows = Vec::new();
3949
3950 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3951 let cursor = selection.head();
3952 let row = cursor.row;
3953
3954 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3955
3956 let newline = "\n".to_string();
3957 edits.push((start_of_line..start_of_line, newline));
3958
3959 rows.push(row + rows_inserted as u32);
3960 }
3961
3962 self.transact(window, cx, |editor, window, cx| {
3963 editor.edit(edits, cx);
3964
3965 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3966 let mut index = 0;
3967 s.move_cursors_with(|map, _, _| {
3968 let row = rows[index];
3969 index += 1;
3970
3971 let point = Point::new(row, 0);
3972 let boundary = map.next_line_boundary(point).1;
3973 let clipped = map.clip_point(boundary, Bias::Left);
3974
3975 (clipped, SelectionGoal::None)
3976 });
3977 });
3978
3979 let mut indent_edits = Vec::new();
3980 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3981 for row in rows {
3982 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3983 for (row, indent) in indents {
3984 if indent.len == 0 {
3985 continue;
3986 }
3987
3988 let text = match indent.kind {
3989 IndentKind::Space => " ".repeat(indent.len as usize),
3990 IndentKind::Tab => "\t".repeat(indent.len as usize),
3991 };
3992 let point = Point::new(row.0, 0);
3993 indent_edits.push((point..point, text));
3994 }
3995 }
3996 editor.edit(indent_edits, cx);
3997 });
3998 }
3999
4000 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
4001 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4002
4003 let buffer = self.buffer.read(cx);
4004 let snapshot = buffer.snapshot(cx);
4005
4006 let mut edits = Vec::new();
4007 let mut rows = Vec::new();
4008 let mut rows_inserted = 0;
4009
4010 for selection in self.selections.all_adjusted(cx) {
4011 let cursor = selection.head();
4012 let row = cursor.row;
4013
4014 let point = Point::new(row + 1, 0);
4015 let start_of_line = snapshot.clip_point(point, Bias::Left);
4016
4017 let newline = "\n".to_string();
4018 edits.push((start_of_line..start_of_line, newline));
4019
4020 rows_inserted += 1;
4021 rows.push(row + rows_inserted);
4022 }
4023
4024 self.transact(window, cx, |editor, window, cx| {
4025 editor.edit(edits, cx);
4026
4027 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4028 let mut index = 0;
4029 s.move_cursors_with(|map, _, _| {
4030 let row = rows[index];
4031 index += 1;
4032
4033 let point = Point::new(row, 0);
4034 let boundary = map.next_line_boundary(point).1;
4035 let clipped = map.clip_point(boundary, Bias::Left);
4036
4037 (clipped, SelectionGoal::None)
4038 });
4039 });
4040
4041 let mut indent_edits = Vec::new();
4042 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4043 for row in rows {
4044 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4045 for (row, indent) in indents {
4046 if indent.len == 0 {
4047 continue;
4048 }
4049
4050 let text = match indent.kind {
4051 IndentKind::Space => " ".repeat(indent.len as usize),
4052 IndentKind::Tab => "\t".repeat(indent.len as usize),
4053 };
4054 let point = Point::new(row.0, 0);
4055 indent_edits.push((point..point, text));
4056 }
4057 }
4058 editor.edit(indent_edits, cx);
4059 });
4060 }
4061
4062 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
4063 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4064 original_indent_columns: Vec::new(),
4065 });
4066 self.insert_with_autoindent_mode(text, autoindent, window, cx);
4067 }
4068
4069 fn insert_with_autoindent_mode(
4070 &mut self,
4071 text: &str,
4072 autoindent_mode: Option<AutoindentMode>,
4073 window: &mut Window,
4074 cx: &mut Context<Self>,
4075 ) {
4076 if self.read_only(cx) {
4077 return;
4078 }
4079
4080 let text: Arc<str> = text.into();
4081 self.transact(window, cx, |this, window, cx| {
4082 let old_selections = this.selections.all_adjusted(cx);
4083 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4084 let anchors = {
4085 let snapshot = buffer.read(cx);
4086 old_selections
4087 .iter()
4088 .map(|s| {
4089 let anchor = snapshot.anchor_after(s.head());
4090 s.map(|_| anchor)
4091 })
4092 .collect::<Vec<_>>()
4093 };
4094 buffer.edit(
4095 old_selections
4096 .iter()
4097 .map(|s| (s.start..s.end, text.clone())),
4098 autoindent_mode,
4099 cx,
4100 );
4101 anchors
4102 });
4103
4104 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4105 s.select_anchors(selection_anchors);
4106 });
4107
4108 cx.notify();
4109 });
4110 }
4111
4112 fn trigger_completion_on_input(
4113 &mut self,
4114 text: &str,
4115 trigger_in_words: bool,
4116 window: &mut Window,
4117 cx: &mut Context<Self>,
4118 ) {
4119 let ignore_completion_provider = self
4120 .context_menu
4121 .borrow()
4122 .as_ref()
4123 .map(|menu| match menu {
4124 CodeContextMenu::Completions(completions_menu) => {
4125 completions_menu.ignore_completion_provider
4126 }
4127 CodeContextMenu::CodeActions(_) => false,
4128 })
4129 .unwrap_or(false);
4130
4131 if ignore_completion_provider {
4132 self.show_word_completions(&ShowWordCompletions, window, cx);
4133 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
4134 self.show_completions(
4135 &ShowCompletions {
4136 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4137 },
4138 window,
4139 cx,
4140 );
4141 } else {
4142 self.hide_context_menu(window, cx);
4143 }
4144 }
4145
4146 fn is_completion_trigger(
4147 &self,
4148 text: &str,
4149 trigger_in_words: bool,
4150 cx: &mut Context<Self>,
4151 ) -> bool {
4152 let position = self.selections.newest_anchor().head();
4153 let multibuffer = self.buffer.read(cx);
4154 let Some(buffer) = position
4155 .buffer_id
4156 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4157 else {
4158 return false;
4159 };
4160
4161 if let Some(completion_provider) = &self.completion_provider {
4162 completion_provider.is_completion_trigger(
4163 &buffer,
4164 position.text_anchor,
4165 text,
4166 trigger_in_words,
4167 cx,
4168 )
4169 } else {
4170 false
4171 }
4172 }
4173
4174 /// If any empty selections is touching the start of its innermost containing autoclose
4175 /// region, expand it to select the brackets.
4176 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4177 let selections = self.selections.all::<usize>(cx);
4178 let buffer = self.buffer.read(cx).read(cx);
4179 let new_selections = self
4180 .selections_with_autoclose_regions(selections, &buffer)
4181 .map(|(mut selection, region)| {
4182 if !selection.is_empty() {
4183 return selection;
4184 }
4185
4186 if let Some(region) = region {
4187 let mut range = region.range.to_offset(&buffer);
4188 if selection.start == range.start && range.start >= region.pair.start.len() {
4189 range.start -= region.pair.start.len();
4190 if buffer.contains_str_at(range.start, ®ion.pair.start)
4191 && buffer.contains_str_at(range.end, ®ion.pair.end)
4192 {
4193 range.end += region.pair.end.len();
4194 selection.start = range.start;
4195 selection.end = range.end;
4196
4197 return selection;
4198 }
4199 }
4200 }
4201
4202 let always_treat_brackets_as_autoclosed = buffer
4203 .language_settings_at(selection.start, cx)
4204 .always_treat_brackets_as_autoclosed;
4205
4206 if !always_treat_brackets_as_autoclosed {
4207 return selection;
4208 }
4209
4210 if let Some(scope) = buffer.language_scope_at(selection.start) {
4211 for (pair, enabled) in scope.brackets() {
4212 if !enabled || !pair.close {
4213 continue;
4214 }
4215
4216 if buffer.contains_str_at(selection.start, &pair.end) {
4217 let pair_start_len = pair.start.len();
4218 if buffer.contains_str_at(
4219 selection.start.saturating_sub(pair_start_len),
4220 &pair.start,
4221 ) {
4222 selection.start -= pair_start_len;
4223 selection.end += pair.end.len();
4224
4225 return selection;
4226 }
4227 }
4228 }
4229 }
4230
4231 selection
4232 })
4233 .collect();
4234
4235 drop(buffer);
4236 self.change_selections(None, window, cx, |selections| {
4237 selections.select(new_selections)
4238 });
4239 }
4240
4241 /// Iterate the given selections, and for each one, find the smallest surrounding
4242 /// autoclose region. This uses the ordering of the selections and the autoclose
4243 /// regions to avoid repeated comparisons.
4244 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4245 &'a self,
4246 selections: impl IntoIterator<Item = Selection<D>>,
4247 buffer: &'a MultiBufferSnapshot,
4248 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4249 let mut i = 0;
4250 let mut regions = self.autoclose_regions.as_slice();
4251 selections.into_iter().map(move |selection| {
4252 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4253
4254 let mut enclosing = None;
4255 while let Some(pair_state) = regions.get(i) {
4256 if pair_state.range.end.to_offset(buffer) < range.start {
4257 regions = ®ions[i + 1..];
4258 i = 0;
4259 } else if pair_state.range.start.to_offset(buffer) > range.end {
4260 break;
4261 } else {
4262 if pair_state.selection_id == selection.id {
4263 enclosing = Some(pair_state);
4264 }
4265 i += 1;
4266 }
4267 }
4268
4269 (selection, enclosing)
4270 })
4271 }
4272
4273 /// Remove any autoclose regions that no longer contain their selection.
4274 fn invalidate_autoclose_regions(
4275 &mut self,
4276 mut selections: &[Selection<Anchor>],
4277 buffer: &MultiBufferSnapshot,
4278 ) {
4279 self.autoclose_regions.retain(|state| {
4280 let mut i = 0;
4281 while let Some(selection) = selections.get(i) {
4282 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4283 selections = &selections[1..];
4284 continue;
4285 }
4286 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4287 break;
4288 }
4289 if selection.id == state.selection_id {
4290 return true;
4291 } else {
4292 i += 1;
4293 }
4294 }
4295 false
4296 });
4297 }
4298
4299 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4300 let offset = position.to_offset(buffer);
4301 let (word_range, kind) = buffer.surrounding_word(offset, true);
4302 if offset > word_range.start && kind == Some(CharKind::Word) {
4303 Some(
4304 buffer
4305 .text_for_range(word_range.start..offset)
4306 .collect::<String>(),
4307 )
4308 } else {
4309 None
4310 }
4311 }
4312
4313 pub fn toggle_inline_values(
4314 &mut self,
4315 _: &ToggleInlineValues,
4316 _: &mut Window,
4317 cx: &mut Context<Self>,
4318 ) {
4319 self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
4320
4321 self.refresh_inline_values(cx);
4322 }
4323
4324 pub fn toggle_inlay_hints(
4325 &mut self,
4326 _: &ToggleInlayHints,
4327 _: &mut Window,
4328 cx: &mut Context<Self>,
4329 ) {
4330 self.refresh_inlay_hints(
4331 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4332 cx,
4333 );
4334 }
4335
4336 pub fn inlay_hints_enabled(&self) -> bool {
4337 self.inlay_hint_cache.enabled
4338 }
4339
4340 pub fn inline_values_enabled(&self) -> bool {
4341 self.inline_value_cache.enabled
4342 }
4343
4344 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4345 if self.semantics_provider.is_none() || !self.mode.is_full() {
4346 return;
4347 }
4348
4349 let reason_description = reason.description();
4350 let ignore_debounce = matches!(
4351 reason,
4352 InlayHintRefreshReason::SettingsChange(_)
4353 | InlayHintRefreshReason::Toggle(_)
4354 | InlayHintRefreshReason::ExcerptsRemoved(_)
4355 | InlayHintRefreshReason::ModifiersChanged(_)
4356 );
4357 let (invalidate_cache, required_languages) = match reason {
4358 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4359 match self.inlay_hint_cache.modifiers_override(enabled) {
4360 Some(enabled) => {
4361 if enabled {
4362 (InvalidationStrategy::RefreshRequested, None)
4363 } else {
4364 self.splice_inlays(
4365 &self
4366 .visible_inlay_hints(cx)
4367 .iter()
4368 .map(|inlay| inlay.id)
4369 .collect::<Vec<InlayId>>(),
4370 Vec::new(),
4371 cx,
4372 );
4373 return;
4374 }
4375 }
4376 None => return,
4377 }
4378 }
4379 InlayHintRefreshReason::Toggle(enabled) => {
4380 if self.inlay_hint_cache.toggle(enabled) {
4381 if enabled {
4382 (InvalidationStrategy::RefreshRequested, None)
4383 } else {
4384 self.splice_inlays(
4385 &self
4386 .visible_inlay_hints(cx)
4387 .iter()
4388 .map(|inlay| inlay.id)
4389 .collect::<Vec<InlayId>>(),
4390 Vec::new(),
4391 cx,
4392 );
4393 return;
4394 }
4395 } else {
4396 return;
4397 }
4398 }
4399 InlayHintRefreshReason::SettingsChange(new_settings) => {
4400 match self.inlay_hint_cache.update_settings(
4401 &self.buffer,
4402 new_settings,
4403 self.visible_inlay_hints(cx),
4404 cx,
4405 ) {
4406 ControlFlow::Break(Some(InlaySplice {
4407 to_remove,
4408 to_insert,
4409 })) => {
4410 self.splice_inlays(&to_remove, to_insert, cx);
4411 return;
4412 }
4413 ControlFlow::Break(None) => return,
4414 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4415 }
4416 }
4417 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4418 if let Some(InlaySplice {
4419 to_remove,
4420 to_insert,
4421 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4422 {
4423 self.splice_inlays(&to_remove, to_insert, cx);
4424 }
4425 self.display_map.update(cx, |display_map, _| {
4426 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4427 });
4428 return;
4429 }
4430 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4431 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4432 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4433 }
4434 InlayHintRefreshReason::RefreshRequested => {
4435 (InvalidationStrategy::RefreshRequested, None)
4436 }
4437 };
4438
4439 if let Some(InlaySplice {
4440 to_remove,
4441 to_insert,
4442 }) = self.inlay_hint_cache.spawn_hint_refresh(
4443 reason_description,
4444 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4445 invalidate_cache,
4446 ignore_debounce,
4447 cx,
4448 ) {
4449 self.splice_inlays(&to_remove, to_insert, cx);
4450 }
4451 }
4452
4453 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4454 self.display_map
4455 .read(cx)
4456 .current_inlays()
4457 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4458 .cloned()
4459 .collect()
4460 }
4461
4462 pub fn excerpts_for_inlay_hints_query(
4463 &self,
4464 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4465 cx: &mut Context<Editor>,
4466 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4467 let Some(project) = self.project.as_ref() else {
4468 return HashMap::default();
4469 };
4470 let project = project.read(cx);
4471 let multi_buffer = self.buffer().read(cx);
4472 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4473 let multi_buffer_visible_start = self
4474 .scroll_manager
4475 .anchor()
4476 .anchor
4477 .to_point(&multi_buffer_snapshot);
4478 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4479 multi_buffer_visible_start
4480 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4481 Bias::Left,
4482 );
4483 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4484 multi_buffer_snapshot
4485 .range_to_buffer_ranges(multi_buffer_visible_range)
4486 .into_iter()
4487 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4488 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4489 let buffer_file = project::File::from_dyn(buffer.file())?;
4490 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4491 let worktree_entry = buffer_worktree
4492 .read(cx)
4493 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4494 if worktree_entry.is_ignored {
4495 return None;
4496 }
4497
4498 let language = buffer.language()?;
4499 if let Some(restrict_to_languages) = restrict_to_languages {
4500 if !restrict_to_languages.contains(language) {
4501 return None;
4502 }
4503 }
4504 Some((
4505 excerpt_id,
4506 (
4507 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4508 buffer.version().clone(),
4509 excerpt_visible_range,
4510 ),
4511 ))
4512 })
4513 .collect()
4514 }
4515
4516 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4517 TextLayoutDetails {
4518 text_system: window.text_system().clone(),
4519 editor_style: self.style.clone().unwrap(),
4520 rem_size: window.rem_size(),
4521 scroll_anchor: self.scroll_manager.anchor(),
4522 visible_rows: self.visible_line_count(),
4523 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4524 }
4525 }
4526
4527 pub fn splice_inlays(
4528 &self,
4529 to_remove: &[InlayId],
4530 to_insert: Vec<Inlay>,
4531 cx: &mut Context<Self>,
4532 ) {
4533 self.display_map.update(cx, |display_map, cx| {
4534 display_map.splice_inlays(to_remove, to_insert, cx)
4535 });
4536 cx.notify();
4537 }
4538
4539 fn trigger_on_type_formatting(
4540 &self,
4541 input: String,
4542 window: &mut Window,
4543 cx: &mut Context<Self>,
4544 ) -> Option<Task<Result<()>>> {
4545 if input.len() != 1 {
4546 return None;
4547 }
4548
4549 let project = self.project.as_ref()?;
4550 let position = self.selections.newest_anchor().head();
4551 let (buffer, buffer_position) = self
4552 .buffer
4553 .read(cx)
4554 .text_anchor_for_position(position, cx)?;
4555
4556 let settings = language_settings::language_settings(
4557 buffer
4558 .read(cx)
4559 .language_at(buffer_position)
4560 .map(|l| l.name()),
4561 buffer.read(cx).file(),
4562 cx,
4563 );
4564 if !settings.use_on_type_format {
4565 return None;
4566 }
4567
4568 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4569 // hence we do LSP request & edit on host side only — add formats to host's history.
4570 let push_to_lsp_host_history = true;
4571 // If this is not the host, append its history with new edits.
4572 let push_to_client_history = project.read(cx).is_via_collab();
4573
4574 let on_type_formatting = project.update(cx, |project, cx| {
4575 project.on_type_format(
4576 buffer.clone(),
4577 buffer_position,
4578 input,
4579 push_to_lsp_host_history,
4580 cx,
4581 )
4582 });
4583 Some(cx.spawn_in(window, async move |editor, cx| {
4584 if let Some(transaction) = on_type_formatting.await? {
4585 if push_to_client_history {
4586 buffer
4587 .update(cx, |buffer, _| {
4588 buffer.push_transaction(transaction, Instant::now());
4589 buffer.finalize_last_transaction();
4590 })
4591 .ok();
4592 }
4593 editor.update(cx, |editor, cx| {
4594 editor.refresh_document_highlights(cx);
4595 })?;
4596 }
4597 Ok(())
4598 }))
4599 }
4600
4601 pub fn show_word_completions(
4602 &mut self,
4603 _: &ShowWordCompletions,
4604 window: &mut Window,
4605 cx: &mut Context<Self>,
4606 ) {
4607 self.open_completions_menu(true, None, window, cx);
4608 }
4609
4610 pub fn show_completions(
4611 &mut self,
4612 options: &ShowCompletions,
4613 window: &mut Window,
4614 cx: &mut Context<Self>,
4615 ) {
4616 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4617 }
4618
4619 fn open_completions_menu(
4620 &mut self,
4621 ignore_completion_provider: bool,
4622 trigger: Option<&str>,
4623 window: &mut Window,
4624 cx: &mut Context<Self>,
4625 ) {
4626 if self.pending_rename.is_some() {
4627 return;
4628 }
4629 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4630 return;
4631 }
4632
4633 let position = self.selections.newest_anchor().head();
4634 if position.diff_base_anchor.is_some() {
4635 return;
4636 }
4637 let (buffer, buffer_position) =
4638 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4639 output
4640 } else {
4641 return;
4642 };
4643 let buffer_snapshot = buffer.read(cx).snapshot();
4644 let show_completion_documentation = buffer_snapshot
4645 .settings_at(buffer_position, cx)
4646 .show_completion_documentation;
4647
4648 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4649
4650 let trigger_kind = match trigger {
4651 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4652 CompletionTriggerKind::TRIGGER_CHARACTER
4653 }
4654 _ => CompletionTriggerKind::INVOKED,
4655 };
4656 let completion_context = CompletionContext {
4657 trigger_character: trigger.and_then(|trigger| {
4658 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4659 Some(String::from(trigger))
4660 } else {
4661 None
4662 }
4663 }),
4664 trigger_kind,
4665 };
4666
4667 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4668 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4669 let word_to_exclude = buffer_snapshot
4670 .text_for_range(old_range.clone())
4671 .collect::<String>();
4672 (
4673 buffer_snapshot.anchor_before(old_range.start)
4674 ..buffer_snapshot.anchor_after(old_range.end),
4675 Some(word_to_exclude),
4676 )
4677 } else {
4678 (buffer_position..buffer_position, None)
4679 };
4680
4681 let completion_settings = language_settings(
4682 buffer_snapshot
4683 .language_at(buffer_position)
4684 .map(|language| language.name()),
4685 buffer_snapshot.file(),
4686 cx,
4687 )
4688 .completions;
4689
4690 // The document can be large, so stay in reasonable bounds when searching for words,
4691 // otherwise completion pop-up might be slow to appear.
4692 const WORD_LOOKUP_ROWS: u32 = 5_000;
4693 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4694 let min_word_search = buffer_snapshot.clip_point(
4695 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4696 Bias::Left,
4697 );
4698 let max_word_search = buffer_snapshot.clip_point(
4699 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4700 Bias::Right,
4701 );
4702 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4703 ..buffer_snapshot.point_to_offset(max_word_search);
4704
4705 let provider = self
4706 .completion_provider
4707 .as_ref()
4708 .filter(|_| !ignore_completion_provider);
4709 let skip_digits = query
4710 .as_ref()
4711 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4712
4713 let (mut words, provided_completions) = match provider {
4714 Some(provider) => {
4715 let completions = provider.completions(
4716 position.excerpt_id,
4717 &buffer,
4718 buffer_position,
4719 completion_context,
4720 window,
4721 cx,
4722 );
4723
4724 let words = match completion_settings.words {
4725 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4726 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4727 .background_spawn(async move {
4728 buffer_snapshot.words_in_range(WordsQuery {
4729 fuzzy_contents: None,
4730 range: word_search_range,
4731 skip_digits,
4732 })
4733 }),
4734 };
4735
4736 (words, completions)
4737 }
4738 None => (
4739 cx.background_spawn(async move {
4740 buffer_snapshot.words_in_range(WordsQuery {
4741 fuzzy_contents: None,
4742 range: word_search_range,
4743 skip_digits,
4744 })
4745 }),
4746 Task::ready(Ok(None)),
4747 ),
4748 };
4749
4750 let sort_completions = provider
4751 .as_ref()
4752 .map_or(false, |provider| provider.sort_completions());
4753
4754 let filter_completions = provider
4755 .as_ref()
4756 .map_or(true, |provider| provider.filter_completions());
4757
4758 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
4759
4760 let id = post_inc(&mut self.next_completion_id);
4761 let task = cx.spawn_in(window, async move |editor, cx| {
4762 async move {
4763 editor.update(cx, |this, _| {
4764 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4765 })?;
4766
4767 let mut completions = Vec::new();
4768 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4769 completions.extend(provided_completions);
4770 if completion_settings.words == WordsCompletionMode::Fallback {
4771 words = Task::ready(BTreeMap::default());
4772 }
4773 }
4774
4775 let mut words = words.await;
4776 if let Some(word_to_exclude) = &word_to_exclude {
4777 words.remove(word_to_exclude);
4778 }
4779 for lsp_completion in &completions {
4780 words.remove(&lsp_completion.new_text);
4781 }
4782 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4783 replace_range: old_range.clone(),
4784 new_text: word.clone(),
4785 label: CodeLabel::plain(word, None),
4786 icon_path: None,
4787 documentation: None,
4788 source: CompletionSource::BufferWord {
4789 word_range,
4790 resolved: false,
4791 },
4792 insert_text_mode: Some(InsertTextMode::AS_IS),
4793 confirm: None,
4794 }));
4795
4796 let menu = if completions.is_empty() {
4797 None
4798 } else {
4799 let mut menu = CompletionsMenu::new(
4800 id,
4801 sort_completions,
4802 show_completion_documentation,
4803 ignore_completion_provider,
4804 position,
4805 buffer.clone(),
4806 completions.into(),
4807 snippet_sort_order,
4808 );
4809
4810 menu.filter(
4811 if filter_completions {
4812 query.as_deref()
4813 } else {
4814 None
4815 },
4816 cx.background_executor().clone(),
4817 )
4818 .await;
4819
4820 menu.visible().then_some(menu)
4821 };
4822
4823 editor.update_in(cx, |editor, window, cx| {
4824 match editor.context_menu.borrow().as_ref() {
4825 None => {}
4826 Some(CodeContextMenu::Completions(prev_menu)) => {
4827 if prev_menu.id > id {
4828 return;
4829 }
4830 }
4831 _ => return,
4832 }
4833
4834 if editor.focus_handle.is_focused(window) && menu.is_some() {
4835 let mut menu = menu.unwrap();
4836 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4837
4838 *editor.context_menu.borrow_mut() =
4839 Some(CodeContextMenu::Completions(menu));
4840
4841 if editor.show_edit_predictions_in_menu() {
4842 editor.update_visible_inline_completion(window, cx);
4843 } else {
4844 editor.discard_inline_completion(false, cx);
4845 }
4846
4847 cx.notify();
4848 } else if editor.completion_tasks.len() <= 1 {
4849 // If there are no more completion tasks and the last menu was
4850 // empty, we should hide it.
4851 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4852 // If it was already hidden and we don't show inline
4853 // completions in the menu, we should also show the
4854 // inline-completion when available.
4855 if was_hidden && editor.show_edit_predictions_in_menu() {
4856 editor.update_visible_inline_completion(window, cx);
4857 }
4858 }
4859 })?;
4860
4861 anyhow::Ok(())
4862 }
4863 .log_err()
4864 .await
4865 });
4866
4867 self.completion_tasks.push((id, task));
4868 }
4869
4870 #[cfg(feature = "test-support")]
4871 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4872 let menu = self.context_menu.borrow();
4873 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4874 let completions = menu.completions.borrow();
4875 Some(completions.to_vec())
4876 } else {
4877 None
4878 }
4879 }
4880
4881 pub fn confirm_completion(
4882 &mut self,
4883 action: &ConfirmCompletion,
4884 window: &mut Window,
4885 cx: &mut Context<Self>,
4886 ) -> Option<Task<Result<()>>> {
4887 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4888 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4889 }
4890
4891 pub fn confirm_completion_insert(
4892 &mut self,
4893 _: &ConfirmCompletionInsert,
4894 window: &mut Window,
4895 cx: &mut Context<Self>,
4896 ) -> Option<Task<Result<()>>> {
4897 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4898 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4899 }
4900
4901 pub fn confirm_completion_replace(
4902 &mut self,
4903 _: &ConfirmCompletionReplace,
4904 window: &mut Window,
4905 cx: &mut Context<Self>,
4906 ) -> Option<Task<Result<()>>> {
4907 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4908 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4909 }
4910
4911 pub fn compose_completion(
4912 &mut self,
4913 action: &ComposeCompletion,
4914 window: &mut Window,
4915 cx: &mut Context<Self>,
4916 ) -> Option<Task<Result<()>>> {
4917 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4918 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4919 }
4920
4921 fn do_completion(
4922 &mut self,
4923 item_ix: Option<usize>,
4924 intent: CompletionIntent,
4925 window: &mut Window,
4926 cx: &mut Context<Editor>,
4927 ) -> Option<Task<Result<()>>> {
4928 use language::ToOffset as _;
4929
4930 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4931 else {
4932 return None;
4933 };
4934
4935 let candidate_id = {
4936 let entries = completions_menu.entries.borrow();
4937 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4938 if self.show_edit_predictions_in_menu() {
4939 self.discard_inline_completion(true, cx);
4940 }
4941 mat.candidate_id
4942 };
4943
4944 let buffer_handle = completions_menu.buffer;
4945 let completion = completions_menu
4946 .completions
4947 .borrow()
4948 .get(candidate_id)?
4949 .clone();
4950 cx.stop_propagation();
4951
4952 let snippet;
4953 let new_text;
4954 if completion.is_snippet() {
4955 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4956 new_text = snippet.as_ref().unwrap().text.clone();
4957 } else {
4958 snippet = None;
4959 new_text = completion.new_text.clone();
4960 };
4961
4962 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4963 let buffer = buffer_handle.read(cx);
4964 let snapshot = self.buffer.read(cx).snapshot(cx);
4965 let replace_range_multibuffer = {
4966 let excerpt = snapshot
4967 .excerpt_containing(self.selections.newest_anchor().range())
4968 .unwrap();
4969 let multibuffer_anchor = snapshot
4970 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4971 .unwrap()
4972 ..snapshot
4973 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4974 .unwrap();
4975 multibuffer_anchor.start.to_offset(&snapshot)
4976 ..multibuffer_anchor.end.to_offset(&snapshot)
4977 };
4978 let newest_anchor = self.selections.newest_anchor();
4979 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4980 return None;
4981 }
4982
4983 let old_text = buffer
4984 .text_for_range(replace_range.clone())
4985 .collect::<String>();
4986 let lookbehind = newest_anchor
4987 .start
4988 .text_anchor
4989 .to_offset(buffer)
4990 .saturating_sub(replace_range.start);
4991 let lookahead = replace_range
4992 .end
4993 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4994 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4995 let suffix = &old_text[lookbehind.min(old_text.len())..];
4996
4997 let selections = self.selections.all::<usize>(cx);
4998 let mut ranges = Vec::new();
4999 let mut linked_edits = HashMap::<_, Vec<_>>::default();
5000
5001 for selection in &selections {
5002 let range = if selection.id == newest_anchor.id {
5003 replace_range_multibuffer.clone()
5004 } else {
5005 let mut range = selection.range();
5006
5007 // if prefix is present, don't duplicate it
5008 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
5009 range.start = range.start.saturating_sub(lookbehind);
5010
5011 // if suffix is also present, mimic the newest cursor and replace it
5012 if selection.id != newest_anchor.id
5013 && snapshot.contains_str_at(range.end, suffix)
5014 {
5015 range.end += lookahead;
5016 }
5017 }
5018 range
5019 };
5020
5021 ranges.push(range.clone());
5022
5023 if !self.linked_edit_ranges.is_empty() {
5024 let start_anchor = snapshot.anchor_before(range.start);
5025 let end_anchor = snapshot.anchor_after(range.end);
5026 if let Some(ranges) = self
5027 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
5028 {
5029 for (buffer, edits) in ranges {
5030 linked_edits
5031 .entry(buffer.clone())
5032 .or_default()
5033 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
5034 }
5035 }
5036 }
5037 }
5038
5039 cx.emit(EditorEvent::InputHandled {
5040 utf16_range_to_replace: None,
5041 text: new_text.clone().into(),
5042 });
5043
5044 self.transact(window, cx, |this, window, cx| {
5045 if let Some(mut snippet) = snippet {
5046 snippet.text = new_text.to_string();
5047 this.insert_snippet(&ranges, snippet, window, cx).log_err();
5048 } else {
5049 this.buffer.update(cx, |buffer, cx| {
5050 let auto_indent = match completion.insert_text_mode {
5051 Some(InsertTextMode::AS_IS) => None,
5052 _ => this.autoindent_mode.clone(),
5053 };
5054 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
5055 buffer.edit(edits, auto_indent, cx);
5056 });
5057 }
5058 for (buffer, edits) in linked_edits {
5059 buffer.update(cx, |buffer, cx| {
5060 let snapshot = buffer.snapshot();
5061 let edits = edits
5062 .into_iter()
5063 .map(|(range, text)| {
5064 use text::ToPoint as TP;
5065 let end_point = TP::to_point(&range.end, &snapshot);
5066 let start_point = TP::to_point(&range.start, &snapshot);
5067 (start_point..end_point, text)
5068 })
5069 .sorted_by_key(|(range, _)| range.start);
5070 buffer.edit(edits, None, cx);
5071 })
5072 }
5073
5074 this.refresh_inline_completion(true, false, window, cx);
5075 });
5076
5077 let show_new_completions_on_confirm = completion
5078 .confirm
5079 .as_ref()
5080 .map_or(false, |confirm| confirm(intent, window, cx));
5081 if show_new_completions_on_confirm {
5082 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
5083 }
5084
5085 let provider = self.completion_provider.as_ref()?;
5086 drop(completion);
5087 let apply_edits = provider.apply_additional_edits_for_completion(
5088 buffer_handle,
5089 completions_menu.completions.clone(),
5090 candidate_id,
5091 true,
5092 cx,
5093 );
5094
5095 let editor_settings = EditorSettings::get_global(cx);
5096 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
5097 // After the code completion is finished, users often want to know what signatures are needed.
5098 // so we should automatically call signature_help
5099 self.show_signature_help(&ShowSignatureHelp, window, cx);
5100 }
5101
5102 Some(cx.foreground_executor().spawn(async move {
5103 apply_edits.await?;
5104 Ok(())
5105 }))
5106 }
5107
5108 pub fn toggle_code_actions(
5109 &mut self,
5110 action: &ToggleCodeActions,
5111 window: &mut Window,
5112 cx: &mut Context<Self>,
5113 ) {
5114 let quick_launch = action.quick_launch;
5115 let mut context_menu = self.context_menu.borrow_mut();
5116 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
5117 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
5118 // Toggle if we're selecting the same one
5119 *context_menu = None;
5120 cx.notify();
5121 return;
5122 } else {
5123 // Otherwise, clear it and start a new one
5124 *context_menu = None;
5125 cx.notify();
5126 }
5127 }
5128 drop(context_menu);
5129 let snapshot = self.snapshot(window, cx);
5130 let deployed_from_indicator = action.deployed_from_indicator;
5131 let mut task = self.code_actions_task.take();
5132 let action = action.clone();
5133 cx.spawn_in(window, async move |editor, cx| {
5134 while let Some(prev_task) = task {
5135 prev_task.await.log_err();
5136 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
5137 }
5138
5139 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
5140 if editor.focus_handle.is_focused(window) {
5141 let multibuffer_point = action
5142 .deployed_from_indicator
5143 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
5144 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
5145 let (buffer, buffer_row) = snapshot
5146 .buffer_snapshot
5147 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
5148 .and_then(|(buffer_snapshot, range)| {
5149 editor
5150 .buffer
5151 .read(cx)
5152 .buffer(buffer_snapshot.remote_id())
5153 .map(|buffer| (buffer, range.start.row))
5154 })?;
5155 let (_, code_actions) = editor
5156 .available_code_actions
5157 .clone()
5158 .and_then(|(location, code_actions)| {
5159 let snapshot = location.buffer.read(cx).snapshot();
5160 let point_range = location.range.to_point(&snapshot);
5161 let point_range = point_range.start.row..=point_range.end.row;
5162 if point_range.contains(&buffer_row) {
5163 Some((location, code_actions))
5164 } else {
5165 None
5166 }
5167 })
5168 .unzip();
5169 let buffer_id = buffer.read(cx).remote_id();
5170 let tasks = editor
5171 .tasks
5172 .get(&(buffer_id, buffer_row))
5173 .map(|t| Arc::new(t.to_owned()));
5174 if tasks.is_none() && code_actions.is_none() {
5175 return None;
5176 }
5177
5178 editor.completion_tasks.clear();
5179 editor.discard_inline_completion(false, cx);
5180 let task_context =
5181 tasks
5182 .as_ref()
5183 .zip(editor.project.clone())
5184 .map(|(tasks, project)| {
5185 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5186 });
5187
5188 Some(cx.spawn_in(window, async move |editor, cx| {
5189 let task_context = match task_context {
5190 Some(task_context) => task_context.await,
5191 None => None,
5192 };
5193 let resolved_tasks =
5194 tasks
5195 .zip(task_context.clone())
5196 .map(|(tasks, task_context)| ResolvedTasks {
5197 templates: tasks.resolve(&task_context).collect(),
5198 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5199 multibuffer_point.row,
5200 tasks.column,
5201 )),
5202 });
5203 let spawn_straight_away = quick_launch
5204 && resolved_tasks
5205 .as_ref()
5206 .map_or(false, |tasks| tasks.templates.len() == 1)
5207 && code_actions
5208 .as_ref()
5209 .map_or(true, |actions| actions.is_empty());
5210 let debug_scenarios = editor.update(cx, |editor, cx| {
5211 if cx.has_flag::<DebuggerFeatureFlag>() {
5212 maybe!({
5213 let project = editor.project.as_ref()?;
5214 let dap_store = project.read(cx).dap_store();
5215 let mut scenarios = vec![];
5216 let resolved_tasks = resolved_tasks.as_ref()?;
5217 let buffer = buffer.read(cx);
5218 let language = buffer.language()?;
5219 let file = buffer.file();
5220 let debug_adapter =
5221 language_settings(language.name().into(), file, cx)
5222 .debuggers
5223 .first()
5224 .map(SharedString::from)
5225 .or_else(|| {
5226 language
5227 .config()
5228 .debuggers
5229 .first()
5230 .map(SharedString::from)
5231 })?;
5232
5233 dap_store.update(cx, |this, cx| {
5234 for (_, task) in &resolved_tasks.templates {
5235 if let Some(scenario) = this
5236 .debug_scenario_for_build_task(
5237 task.original_task().clone(),
5238 debug_adapter.clone(),
5239 cx,
5240 )
5241 {
5242 scenarios.push(scenario);
5243 }
5244 }
5245 });
5246 Some(scenarios)
5247 })
5248 .unwrap_or_default()
5249 } else {
5250 vec![]
5251 }
5252 })?;
5253 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5254 *editor.context_menu.borrow_mut() =
5255 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5256 buffer,
5257 actions: CodeActionContents::new(
5258 resolved_tasks,
5259 code_actions,
5260 debug_scenarios,
5261 task_context.unwrap_or_default(),
5262 ),
5263 selected_item: Default::default(),
5264 scroll_handle: UniformListScrollHandle::default(),
5265 deployed_from_indicator,
5266 }));
5267 if spawn_straight_away {
5268 if let Some(task) = editor.confirm_code_action(
5269 &ConfirmCodeAction { item_ix: Some(0) },
5270 window,
5271 cx,
5272 ) {
5273 cx.notify();
5274 return task;
5275 }
5276 }
5277 cx.notify();
5278 Task::ready(Ok(()))
5279 }) {
5280 task.await
5281 } else {
5282 Ok(())
5283 }
5284 }))
5285 } else {
5286 Some(Task::ready(Ok(())))
5287 }
5288 })?;
5289 if let Some(task) = spawned_test_task {
5290 task.await?;
5291 }
5292
5293 Ok::<_, anyhow::Error>(())
5294 })
5295 .detach_and_log_err(cx);
5296 }
5297
5298 pub fn confirm_code_action(
5299 &mut self,
5300 action: &ConfirmCodeAction,
5301 window: &mut Window,
5302 cx: &mut Context<Self>,
5303 ) -> Option<Task<Result<()>>> {
5304 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5305
5306 let actions_menu =
5307 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5308 menu
5309 } else {
5310 return None;
5311 };
5312
5313 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5314 let action = actions_menu.actions.get(action_ix)?;
5315 let title = action.label();
5316 let buffer = actions_menu.buffer;
5317 let workspace = self.workspace()?;
5318
5319 match action {
5320 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5321 workspace.update(cx, |workspace, cx| {
5322 workspace.schedule_resolved_task(
5323 task_source_kind,
5324 resolved_task,
5325 false,
5326 window,
5327 cx,
5328 );
5329
5330 Some(Task::ready(Ok(())))
5331 })
5332 }
5333 CodeActionsItem::CodeAction {
5334 excerpt_id,
5335 action,
5336 provider,
5337 } => {
5338 let apply_code_action =
5339 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5340 let workspace = workspace.downgrade();
5341 Some(cx.spawn_in(window, async move |editor, cx| {
5342 let project_transaction = apply_code_action.await?;
5343 Self::open_project_transaction(
5344 &editor,
5345 workspace,
5346 project_transaction,
5347 title,
5348 cx,
5349 )
5350 .await
5351 }))
5352 }
5353 CodeActionsItem::DebugScenario(scenario) => {
5354 let context = actions_menu.actions.context.clone();
5355
5356 workspace.update(cx, |workspace, cx| {
5357 workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
5358 });
5359 Some(Task::ready(Ok(())))
5360 }
5361 }
5362 }
5363
5364 pub async fn open_project_transaction(
5365 this: &WeakEntity<Editor>,
5366 workspace: WeakEntity<Workspace>,
5367 transaction: ProjectTransaction,
5368 title: String,
5369 cx: &mut AsyncWindowContext,
5370 ) -> Result<()> {
5371 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5372 cx.update(|_, cx| {
5373 entries.sort_unstable_by_key(|(buffer, _)| {
5374 buffer.read(cx).file().map(|f| f.path().clone())
5375 });
5376 })?;
5377
5378 // If the project transaction's edits are all contained within this editor, then
5379 // avoid opening a new editor to display them.
5380
5381 if let Some((buffer, transaction)) = entries.first() {
5382 if entries.len() == 1 {
5383 let excerpt = this.update(cx, |editor, cx| {
5384 editor
5385 .buffer()
5386 .read(cx)
5387 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5388 })?;
5389 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5390 if excerpted_buffer == *buffer {
5391 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5392 let excerpt_range = excerpt_range.to_offset(buffer);
5393 buffer
5394 .edited_ranges_for_transaction::<usize>(transaction)
5395 .all(|range| {
5396 excerpt_range.start <= range.start
5397 && excerpt_range.end >= range.end
5398 })
5399 })?;
5400
5401 if all_edits_within_excerpt {
5402 return Ok(());
5403 }
5404 }
5405 }
5406 }
5407 } else {
5408 return Ok(());
5409 }
5410
5411 let mut ranges_to_highlight = Vec::new();
5412 let excerpt_buffer = cx.new(|cx| {
5413 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5414 for (buffer_handle, transaction) in &entries {
5415 let edited_ranges = buffer_handle
5416 .read(cx)
5417 .edited_ranges_for_transaction::<Point>(transaction)
5418 .collect::<Vec<_>>();
5419 let (ranges, _) = multibuffer.set_excerpts_for_path(
5420 PathKey::for_buffer(buffer_handle, cx),
5421 buffer_handle.clone(),
5422 edited_ranges,
5423 DEFAULT_MULTIBUFFER_CONTEXT,
5424 cx,
5425 );
5426
5427 ranges_to_highlight.extend(ranges);
5428 }
5429 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5430 multibuffer
5431 })?;
5432
5433 workspace.update_in(cx, |workspace, window, cx| {
5434 let project = workspace.project().clone();
5435 let editor =
5436 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5437 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5438 editor.update(cx, |editor, cx| {
5439 editor.highlight_background::<Self>(
5440 &ranges_to_highlight,
5441 |theme| theme.editor_highlighted_line_background,
5442 cx,
5443 );
5444 });
5445 })?;
5446
5447 Ok(())
5448 }
5449
5450 pub fn clear_code_action_providers(&mut self) {
5451 self.code_action_providers.clear();
5452 self.available_code_actions.take();
5453 }
5454
5455 pub fn add_code_action_provider(
5456 &mut self,
5457 provider: Rc<dyn CodeActionProvider>,
5458 window: &mut Window,
5459 cx: &mut Context<Self>,
5460 ) {
5461 if self
5462 .code_action_providers
5463 .iter()
5464 .any(|existing_provider| existing_provider.id() == provider.id())
5465 {
5466 return;
5467 }
5468
5469 self.code_action_providers.push(provider);
5470 self.refresh_code_actions(window, cx);
5471 }
5472
5473 pub fn remove_code_action_provider(
5474 &mut self,
5475 id: Arc<str>,
5476 window: &mut Window,
5477 cx: &mut Context<Self>,
5478 ) {
5479 self.code_action_providers
5480 .retain(|provider| provider.id() != id);
5481 self.refresh_code_actions(window, cx);
5482 }
5483
5484 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5485 let newest_selection = self.selections.newest_anchor().clone();
5486 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5487 let buffer = self.buffer.read(cx);
5488 if newest_selection.head().diff_base_anchor.is_some() {
5489 return None;
5490 }
5491 let (start_buffer, start) =
5492 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5493 let (end_buffer, end) =
5494 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5495 if start_buffer != end_buffer {
5496 return None;
5497 }
5498
5499 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5500 cx.background_executor()
5501 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5502 .await;
5503
5504 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5505 let providers = this.code_action_providers.clone();
5506 let tasks = this
5507 .code_action_providers
5508 .iter()
5509 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5510 .collect::<Vec<_>>();
5511 (providers, tasks)
5512 })?;
5513
5514 let mut actions = Vec::new();
5515 for (provider, provider_actions) in
5516 providers.into_iter().zip(future::join_all(tasks).await)
5517 {
5518 if let Some(provider_actions) = provider_actions.log_err() {
5519 actions.extend(provider_actions.into_iter().map(|action| {
5520 AvailableCodeAction {
5521 excerpt_id: newest_selection.start.excerpt_id,
5522 action,
5523 provider: provider.clone(),
5524 }
5525 }));
5526 }
5527 }
5528
5529 this.update(cx, |this, cx| {
5530 this.available_code_actions = if actions.is_empty() {
5531 None
5532 } else {
5533 Some((
5534 Location {
5535 buffer: start_buffer,
5536 range: start..end,
5537 },
5538 actions.into(),
5539 ))
5540 };
5541 cx.notify();
5542 })
5543 }));
5544 None
5545 }
5546
5547 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5548 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5549 self.show_git_blame_inline = false;
5550
5551 self.show_git_blame_inline_delay_task =
5552 Some(cx.spawn_in(window, async move |this, cx| {
5553 cx.background_executor().timer(delay).await;
5554
5555 this.update(cx, |this, cx| {
5556 this.show_git_blame_inline = true;
5557 cx.notify();
5558 })
5559 .log_err();
5560 }));
5561 }
5562 }
5563
5564 fn show_blame_popover(
5565 &mut self,
5566 blame_entry: &BlameEntry,
5567 position: gpui::Point<Pixels>,
5568 cx: &mut Context<Self>,
5569 ) {
5570 if let Some(state) = &mut self.inline_blame_popover {
5571 state.hide_task.take();
5572 cx.notify();
5573 } else {
5574 let delay = EditorSettings::get_global(cx).hover_popover_delay;
5575 let show_task = cx.spawn(async move |editor, cx| {
5576 cx.background_executor()
5577 .timer(std::time::Duration::from_millis(delay))
5578 .await;
5579 editor
5580 .update(cx, |editor, cx| {
5581 if let Some(state) = &mut editor.inline_blame_popover {
5582 state.show_task = None;
5583 cx.notify();
5584 }
5585 })
5586 .ok();
5587 });
5588 let Some(blame) = self.blame.as_ref() else {
5589 return;
5590 };
5591 let blame = blame.read(cx);
5592 let details = blame.details_for_entry(&blame_entry);
5593 let markdown = cx.new(|cx| {
5594 Markdown::new(
5595 details
5596 .as_ref()
5597 .map(|message| message.message.clone())
5598 .unwrap_or_default(),
5599 None,
5600 None,
5601 cx,
5602 )
5603 });
5604 self.inline_blame_popover = Some(InlineBlamePopover {
5605 position,
5606 show_task: Some(show_task),
5607 hide_task: None,
5608 popover_bounds: None,
5609 popover_state: InlineBlamePopoverState {
5610 scroll_handle: ScrollHandle::new(),
5611 commit_message: details,
5612 markdown,
5613 },
5614 });
5615 }
5616 }
5617
5618 fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
5619 if let Some(state) = &mut self.inline_blame_popover {
5620 if state.show_task.is_some() {
5621 self.inline_blame_popover.take();
5622 cx.notify();
5623 } else {
5624 let hide_task = cx.spawn(async move |editor, cx| {
5625 cx.background_executor()
5626 .timer(std::time::Duration::from_millis(100))
5627 .await;
5628 editor
5629 .update(cx, |editor, cx| {
5630 editor.inline_blame_popover.take();
5631 cx.notify();
5632 })
5633 .ok();
5634 });
5635 state.hide_task = Some(hide_task);
5636 }
5637 }
5638 }
5639
5640 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5641 if self.pending_rename.is_some() {
5642 return None;
5643 }
5644
5645 let provider = self.semantics_provider.clone()?;
5646 let buffer = self.buffer.read(cx);
5647 let newest_selection = self.selections.newest_anchor().clone();
5648 let cursor_position = newest_selection.head();
5649 let (cursor_buffer, cursor_buffer_position) =
5650 buffer.text_anchor_for_position(cursor_position, cx)?;
5651 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5652 if cursor_buffer != tail_buffer {
5653 return None;
5654 }
5655 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5656 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5657 cx.background_executor()
5658 .timer(Duration::from_millis(debounce))
5659 .await;
5660
5661 let highlights = if let Some(highlights) = cx
5662 .update(|cx| {
5663 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5664 })
5665 .ok()
5666 .flatten()
5667 {
5668 highlights.await.log_err()
5669 } else {
5670 None
5671 };
5672
5673 if let Some(highlights) = highlights {
5674 this.update(cx, |this, cx| {
5675 if this.pending_rename.is_some() {
5676 return;
5677 }
5678
5679 let buffer_id = cursor_position.buffer_id;
5680 let buffer = this.buffer.read(cx);
5681 if !buffer
5682 .text_anchor_for_position(cursor_position, cx)
5683 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5684 {
5685 return;
5686 }
5687
5688 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5689 let mut write_ranges = Vec::new();
5690 let mut read_ranges = Vec::new();
5691 for highlight in highlights {
5692 for (excerpt_id, excerpt_range) in
5693 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5694 {
5695 let start = highlight
5696 .range
5697 .start
5698 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5699 let end = highlight
5700 .range
5701 .end
5702 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5703 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5704 continue;
5705 }
5706
5707 let range = Anchor {
5708 buffer_id,
5709 excerpt_id,
5710 text_anchor: start,
5711 diff_base_anchor: None,
5712 }..Anchor {
5713 buffer_id,
5714 excerpt_id,
5715 text_anchor: end,
5716 diff_base_anchor: None,
5717 };
5718 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5719 write_ranges.push(range);
5720 } else {
5721 read_ranges.push(range);
5722 }
5723 }
5724 }
5725
5726 this.highlight_background::<DocumentHighlightRead>(
5727 &read_ranges,
5728 |theme| theme.editor_document_highlight_read_background,
5729 cx,
5730 );
5731 this.highlight_background::<DocumentHighlightWrite>(
5732 &write_ranges,
5733 |theme| theme.editor_document_highlight_write_background,
5734 cx,
5735 );
5736 cx.notify();
5737 })
5738 .log_err();
5739 }
5740 }));
5741 None
5742 }
5743
5744 fn prepare_highlight_query_from_selection(
5745 &mut self,
5746 cx: &mut Context<Editor>,
5747 ) -> Option<(String, Range<Anchor>)> {
5748 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5749 return None;
5750 }
5751 if !EditorSettings::get_global(cx).selection_highlight {
5752 return None;
5753 }
5754 if self.selections.count() != 1 || self.selections.line_mode {
5755 return None;
5756 }
5757 let selection = self.selections.newest::<Point>(cx);
5758 if selection.is_empty() || selection.start.row != selection.end.row {
5759 return None;
5760 }
5761 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5762 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5763 let query = multi_buffer_snapshot
5764 .text_for_range(selection_anchor_range.clone())
5765 .collect::<String>();
5766 if query.trim().is_empty() {
5767 return None;
5768 }
5769 Some((query, selection_anchor_range))
5770 }
5771
5772 fn update_selection_occurrence_highlights(
5773 &mut self,
5774 query_text: String,
5775 query_range: Range<Anchor>,
5776 multi_buffer_range_to_query: Range<Point>,
5777 use_debounce: bool,
5778 window: &mut Window,
5779 cx: &mut Context<Editor>,
5780 ) -> Task<()> {
5781 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5782 cx.spawn_in(window, async move |editor, cx| {
5783 if use_debounce {
5784 cx.background_executor()
5785 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5786 .await;
5787 }
5788 let match_task = cx.background_spawn(async move {
5789 let buffer_ranges = multi_buffer_snapshot
5790 .range_to_buffer_ranges(multi_buffer_range_to_query)
5791 .into_iter()
5792 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5793 let mut match_ranges = Vec::new();
5794 let Ok(regex) = project::search::SearchQuery::text(
5795 query_text.clone(),
5796 false,
5797 false,
5798 false,
5799 Default::default(),
5800 Default::default(),
5801 false,
5802 None,
5803 ) else {
5804 return Vec::default();
5805 };
5806 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5807 match_ranges.extend(
5808 regex
5809 .search(&buffer_snapshot, Some(search_range.clone()))
5810 .await
5811 .into_iter()
5812 .filter_map(|match_range| {
5813 let match_start = buffer_snapshot
5814 .anchor_after(search_range.start + match_range.start);
5815 let match_end = buffer_snapshot
5816 .anchor_before(search_range.start + match_range.end);
5817 let match_anchor_range = Anchor::range_in_buffer(
5818 excerpt_id,
5819 buffer_snapshot.remote_id(),
5820 match_start..match_end,
5821 );
5822 (match_anchor_range != query_range).then_some(match_anchor_range)
5823 }),
5824 );
5825 }
5826 match_ranges
5827 });
5828 let match_ranges = match_task.await;
5829 editor
5830 .update_in(cx, |editor, _, cx| {
5831 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5832 if !match_ranges.is_empty() {
5833 editor.highlight_background::<SelectedTextHighlight>(
5834 &match_ranges,
5835 |theme| theme.editor_document_highlight_bracket_background,
5836 cx,
5837 )
5838 }
5839 })
5840 .log_err();
5841 })
5842 }
5843
5844 fn refresh_selected_text_highlights(
5845 &mut self,
5846 on_buffer_edit: bool,
5847 window: &mut Window,
5848 cx: &mut Context<Editor>,
5849 ) {
5850 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5851 else {
5852 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5853 self.quick_selection_highlight_task.take();
5854 self.debounced_selection_highlight_task.take();
5855 return;
5856 };
5857 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5858 if on_buffer_edit
5859 || self
5860 .quick_selection_highlight_task
5861 .as_ref()
5862 .map_or(true, |(prev_anchor_range, _)| {
5863 prev_anchor_range != &query_range
5864 })
5865 {
5866 let multi_buffer_visible_start = self
5867 .scroll_manager
5868 .anchor()
5869 .anchor
5870 .to_point(&multi_buffer_snapshot);
5871 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5872 multi_buffer_visible_start
5873 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5874 Bias::Left,
5875 );
5876 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5877 self.quick_selection_highlight_task = Some((
5878 query_range.clone(),
5879 self.update_selection_occurrence_highlights(
5880 query_text.clone(),
5881 query_range.clone(),
5882 multi_buffer_visible_range,
5883 false,
5884 window,
5885 cx,
5886 ),
5887 ));
5888 }
5889 if on_buffer_edit
5890 || self
5891 .debounced_selection_highlight_task
5892 .as_ref()
5893 .map_or(true, |(prev_anchor_range, _)| {
5894 prev_anchor_range != &query_range
5895 })
5896 {
5897 let multi_buffer_start = multi_buffer_snapshot
5898 .anchor_before(0)
5899 .to_point(&multi_buffer_snapshot);
5900 let multi_buffer_end = multi_buffer_snapshot
5901 .anchor_after(multi_buffer_snapshot.len())
5902 .to_point(&multi_buffer_snapshot);
5903 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5904 self.debounced_selection_highlight_task = Some((
5905 query_range.clone(),
5906 self.update_selection_occurrence_highlights(
5907 query_text,
5908 query_range,
5909 multi_buffer_full_range,
5910 true,
5911 window,
5912 cx,
5913 ),
5914 ));
5915 }
5916 }
5917
5918 pub fn refresh_inline_completion(
5919 &mut self,
5920 debounce: bool,
5921 user_requested: bool,
5922 window: &mut Window,
5923 cx: &mut Context<Self>,
5924 ) -> Option<()> {
5925 let provider = self.edit_prediction_provider()?;
5926 let cursor = self.selections.newest_anchor().head();
5927 let (buffer, cursor_buffer_position) =
5928 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5929
5930 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5931 self.discard_inline_completion(false, cx);
5932 return None;
5933 }
5934
5935 if !user_requested
5936 && (!self.should_show_edit_predictions()
5937 || !self.is_focused(window)
5938 || buffer.read(cx).is_empty())
5939 {
5940 self.discard_inline_completion(false, cx);
5941 return None;
5942 }
5943
5944 self.update_visible_inline_completion(window, cx);
5945 provider.refresh(
5946 self.project.clone(),
5947 buffer,
5948 cursor_buffer_position,
5949 debounce,
5950 cx,
5951 );
5952 Some(())
5953 }
5954
5955 fn show_edit_predictions_in_menu(&self) -> bool {
5956 match self.edit_prediction_settings {
5957 EditPredictionSettings::Disabled => false,
5958 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5959 }
5960 }
5961
5962 pub fn edit_predictions_enabled(&self) -> bool {
5963 match self.edit_prediction_settings {
5964 EditPredictionSettings::Disabled => false,
5965 EditPredictionSettings::Enabled { .. } => true,
5966 }
5967 }
5968
5969 fn edit_prediction_requires_modifier(&self) -> bool {
5970 match self.edit_prediction_settings {
5971 EditPredictionSettings::Disabled => false,
5972 EditPredictionSettings::Enabled {
5973 preview_requires_modifier,
5974 ..
5975 } => preview_requires_modifier,
5976 }
5977 }
5978
5979 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5980 if self.edit_prediction_provider.is_none() {
5981 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5982 } else {
5983 let selection = self.selections.newest_anchor();
5984 let cursor = selection.head();
5985
5986 if let Some((buffer, cursor_buffer_position)) =
5987 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5988 {
5989 self.edit_prediction_settings =
5990 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5991 }
5992 }
5993 }
5994
5995 fn edit_prediction_settings_at_position(
5996 &self,
5997 buffer: &Entity<Buffer>,
5998 buffer_position: language::Anchor,
5999 cx: &App,
6000 ) -> EditPredictionSettings {
6001 if !self.mode.is_full()
6002 || !self.show_inline_completions_override.unwrap_or(true)
6003 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
6004 {
6005 return EditPredictionSettings::Disabled;
6006 }
6007
6008 let buffer = buffer.read(cx);
6009
6010 let file = buffer.file();
6011
6012 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
6013 return EditPredictionSettings::Disabled;
6014 };
6015
6016 let by_provider = matches!(
6017 self.menu_inline_completions_policy,
6018 MenuInlineCompletionsPolicy::ByProvider
6019 );
6020
6021 let show_in_menu = by_provider
6022 && self
6023 .edit_prediction_provider
6024 .as_ref()
6025 .map_or(false, |provider| {
6026 provider.provider.show_completions_in_menu()
6027 });
6028
6029 let preview_requires_modifier =
6030 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
6031
6032 EditPredictionSettings::Enabled {
6033 show_in_menu,
6034 preview_requires_modifier,
6035 }
6036 }
6037
6038 fn should_show_edit_predictions(&self) -> bool {
6039 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
6040 }
6041
6042 pub fn edit_prediction_preview_is_active(&self) -> bool {
6043 matches!(
6044 self.edit_prediction_preview,
6045 EditPredictionPreview::Active { .. }
6046 )
6047 }
6048
6049 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
6050 let cursor = self.selections.newest_anchor().head();
6051 if let Some((buffer, cursor_position)) =
6052 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
6053 {
6054 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
6055 } else {
6056 false
6057 }
6058 }
6059
6060 fn edit_predictions_enabled_in_buffer(
6061 &self,
6062 buffer: &Entity<Buffer>,
6063 buffer_position: language::Anchor,
6064 cx: &App,
6065 ) -> bool {
6066 maybe!({
6067 if self.read_only(cx) {
6068 return Some(false);
6069 }
6070 let provider = self.edit_prediction_provider()?;
6071 if !provider.is_enabled(&buffer, buffer_position, cx) {
6072 return Some(false);
6073 }
6074 let buffer = buffer.read(cx);
6075 let Some(file) = buffer.file() else {
6076 return Some(true);
6077 };
6078 let settings = all_language_settings(Some(file), cx);
6079 Some(settings.edit_predictions_enabled_for_file(file, cx))
6080 })
6081 .unwrap_or(false)
6082 }
6083
6084 fn cycle_inline_completion(
6085 &mut self,
6086 direction: Direction,
6087 window: &mut Window,
6088 cx: &mut Context<Self>,
6089 ) -> Option<()> {
6090 let provider = self.edit_prediction_provider()?;
6091 let cursor = self.selections.newest_anchor().head();
6092 let (buffer, cursor_buffer_position) =
6093 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6094 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
6095 return None;
6096 }
6097
6098 provider.cycle(buffer, cursor_buffer_position, direction, cx);
6099 self.update_visible_inline_completion(window, cx);
6100
6101 Some(())
6102 }
6103
6104 pub fn show_inline_completion(
6105 &mut self,
6106 _: &ShowEditPrediction,
6107 window: &mut Window,
6108 cx: &mut Context<Self>,
6109 ) {
6110 if !self.has_active_inline_completion() {
6111 self.refresh_inline_completion(false, true, window, cx);
6112 return;
6113 }
6114
6115 self.update_visible_inline_completion(window, cx);
6116 }
6117
6118 pub fn display_cursor_names(
6119 &mut self,
6120 _: &DisplayCursorNames,
6121 window: &mut Window,
6122 cx: &mut Context<Self>,
6123 ) {
6124 self.show_cursor_names(window, cx);
6125 }
6126
6127 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6128 self.show_cursor_names = true;
6129 cx.notify();
6130 cx.spawn_in(window, async move |this, cx| {
6131 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
6132 this.update(cx, |this, cx| {
6133 this.show_cursor_names = false;
6134 cx.notify()
6135 })
6136 .ok()
6137 })
6138 .detach();
6139 }
6140
6141 pub fn next_edit_prediction(
6142 &mut self,
6143 _: &NextEditPrediction,
6144 window: &mut Window,
6145 cx: &mut Context<Self>,
6146 ) {
6147 if self.has_active_inline_completion() {
6148 self.cycle_inline_completion(Direction::Next, window, cx);
6149 } else {
6150 let is_copilot_disabled = self
6151 .refresh_inline_completion(false, true, window, cx)
6152 .is_none();
6153 if is_copilot_disabled {
6154 cx.propagate();
6155 }
6156 }
6157 }
6158
6159 pub fn previous_edit_prediction(
6160 &mut self,
6161 _: &PreviousEditPrediction,
6162 window: &mut Window,
6163 cx: &mut Context<Self>,
6164 ) {
6165 if self.has_active_inline_completion() {
6166 self.cycle_inline_completion(Direction::Prev, window, cx);
6167 } else {
6168 let is_copilot_disabled = self
6169 .refresh_inline_completion(false, true, window, cx)
6170 .is_none();
6171 if is_copilot_disabled {
6172 cx.propagate();
6173 }
6174 }
6175 }
6176
6177 pub fn accept_edit_prediction(
6178 &mut self,
6179 _: &AcceptEditPrediction,
6180 window: &mut Window,
6181 cx: &mut Context<Self>,
6182 ) {
6183 if self.show_edit_predictions_in_menu() {
6184 self.hide_context_menu(window, cx);
6185 }
6186
6187 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6188 return;
6189 };
6190
6191 self.report_inline_completion_event(
6192 active_inline_completion.completion_id.clone(),
6193 true,
6194 cx,
6195 );
6196
6197 match &active_inline_completion.completion {
6198 InlineCompletion::Move { target, .. } => {
6199 let target = *target;
6200
6201 if let Some(position_map) = &self.last_position_map {
6202 if position_map
6203 .visible_row_range
6204 .contains(&target.to_display_point(&position_map.snapshot).row())
6205 || !self.edit_prediction_requires_modifier()
6206 {
6207 self.unfold_ranges(&[target..target], true, false, cx);
6208 // Note that this is also done in vim's handler of the Tab action.
6209 self.change_selections(
6210 Some(Autoscroll::newest()),
6211 window,
6212 cx,
6213 |selections| {
6214 selections.select_anchor_ranges([target..target]);
6215 },
6216 );
6217 self.clear_row_highlights::<EditPredictionPreview>();
6218
6219 self.edit_prediction_preview
6220 .set_previous_scroll_position(None);
6221 } else {
6222 self.edit_prediction_preview
6223 .set_previous_scroll_position(Some(
6224 position_map.snapshot.scroll_anchor,
6225 ));
6226
6227 self.highlight_rows::<EditPredictionPreview>(
6228 target..target,
6229 cx.theme().colors().editor_highlighted_line_background,
6230 RowHighlightOptions {
6231 autoscroll: true,
6232 ..Default::default()
6233 },
6234 cx,
6235 );
6236 self.request_autoscroll(Autoscroll::fit(), cx);
6237 }
6238 }
6239 }
6240 InlineCompletion::Edit { edits, .. } => {
6241 if let Some(provider) = self.edit_prediction_provider() {
6242 provider.accept(cx);
6243 }
6244
6245 let snapshot = self.buffer.read(cx).snapshot(cx);
6246 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
6247
6248 self.buffer.update(cx, |buffer, cx| {
6249 buffer.edit(edits.iter().cloned(), None, cx)
6250 });
6251
6252 self.change_selections(None, window, cx, |s| {
6253 s.select_anchor_ranges([last_edit_end..last_edit_end])
6254 });
6255
6256 self.update_visible_inline_completion(window, cx);
6257 if self.active_inline_completion.is_none() {
6258 self.refresh_inline_completion(true, true, window, cx);
6259 }
6260
6261 cx.notify();
6262 }
6263 }
6264
6265 self.edit_prediction_requires_modifier_in_indent_conflict = false;
6266 }
6267
6268 pub fn accept_partial_inline_completion(
6269 &mut self,
6270 _: &AcceptPartialEditPrediction,
6271 window: &mut Window,
6272 cx: &mut Context<Self>,
6273 ) {
6274 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6275 return;
6276 };
6277 if self.selections.count() != 1 {
6278 return;
6279 }
6280
6281 self.report_inline_completion_event(
6282 active_inline_completion.completion_id.clone(),
6283 true,
6284 cx,
6285 );
6286
6287 match &active_inline_completion.completion {
6288 InlineCompletion::Move { target, .. } => {
6289 let target = *target;
6290 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6291 selections.select_anchor_ranges([target..target]);
6292 });
6293 }
6294 InlineCompletion::Edit { edits, .. } => {
6295 // Find an insertion that starts at the cursor position.
6296 let snapshot = self.buffer.read(cx).snapshot(cx);
6297 let cursor_offset = self.selections.newest::<usize>(cx).head();
6298 let insertion = edits.iter().find_map(|(range, text)| {
6299 let range = range.to_offset(&snapshot);
6300 if range.is_empty() && range.start == cursor_offset {
6301 Some(text)
6302 } else {
6303 None
6304 }
6305 });
6306
6307 if let Some(text) = insertion {
6308 let mut partial_completion = text
6309 .chars()
6310 .by_ref()
6311 .take_while(|c| c.is_alphabetic())
6312 .collect::<String>();
6313 if partial_completion.is_empty() {
6314 partial_completion = text
6315 .chars()
6316 .by_ref()
6317 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6318 .collect::<String>();
6319 }
6320
6321 cx.emit(EditorEvent::InputHandled {
6322 utf16_range_to_replace: None,
6323 text: partial_completion.clone().into(),
6324 });
6325
6326 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6327
6328 self.refresh_inline_completion(true, true, window, cx);
6329 cx.notify();
6330 } else {
6331 self.accept_edit_prediction(&Default::default(), window, cx);
6332 }
6333 }
6334 }
6335 }
6336
6337 fn discard_inline_completion(
6338 &mut self,
6339 should_report_inline_completion_event: bool,
6340 cx: &mut Context<Self>,
6341 ) -> bool {
6342 if should_report_inline_completion_event {
6343 let completion_id = self
6344 .active_inline_completion
6345 .as_ref()
6346 .and_then(|active_completion| active_completion.completion_id.clone());
6347
6348 self.report_inline_completion_event(completion_id, false, cx);
6349 }
6350
6351 if let Some(provider) = self.edit_prediction_provider() {
6352 provider.discard(cx);
6353 }
6354
6355 self.take_active_inline_completion(cx)
6356 }
6357
6358 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6359 let Some(provider) = self.edit_prediction_provider() else {
6360 return;
6361 };
6362
6363 let Some((_, buffer, _)) = self
6364 .buffer
6365 .read(cx)
6366 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6367 else {
6368 return;
6369 };
6370
6371 let extension = buffer
6372 .read(cx)
6373 .file()
6374 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6375
6376 let event_type = match accepted {
6377 true => "Edit Prediction Accepted",
6378 false => "Edit Prediction Discarded",
6379 };
6380 telemetry::event!(
6381 event_type,
6382 provider = provider.name(),
6383 prediction_id = id,
6384 suggestion_accepted = accepted,
6385 file_extension = extension,
6386 );
6387 }
6388
6389 pub fn has_active_inline_completion(&self) -> bool {
6390 self.active_inline_completion.is_some()
6391 }
6392
6393 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6394 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6395 return false;
6396 };
6397
6398 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6399 self.clear_highlights::<InlineCompletionHighlight>(cx);
6400 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6401 true
6402 }
6403
6404 /// Returns true when we're displaying the edit prediction popover below the cursor
6405 /// like we are not previewing and the LSP autocomplete menu is visible
6406 /// or we are in `when_holding_modifier` mode.
6407 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6408 if self.edit_prediction_preview_is_active()
6409 || !self.show_edit_predictions_in_menu()
6410 || !self.edit_predictions_enabled()
6411 {
6412 return false;
6413 }
6414
6415 if self.has_visible_completions_menu() {
6416 return true;
6417 }
6418
6419 has_completion && self.edit_prediction_requires_modifier()
6420 }
6421
6422 fn handle_modifiers_changed(
6423 &mut self,
6424 modifiers: Modifiers,
6425 position_map: &PositionMap,
6426 window: &mut Window,
6427 cx: &mut Context<Self>,
6428 ) {
6429 if self.show_edit_predictions_in_menu() {
6430 self.update_edit_prediction_preview(&modifiers, window, cx);
6431 }
6432
6433 self.update_selection_mode(&modifiers, position_map, window, cx);
6434
6435 let mouse_position = window.mouse_position();
6436 if !position_map.text_hitbox.is_hovered(window) {
6437 return;
6438 }
6439
6440 self.update_hovered_link(
6441 position_map.point_for_position(mouse_position),
6442 &position_map.snapshot,
6443 modifiers,
6444 window,
6445 cx,
6446 )
6447 }
6448
6449 fn update_selection_mode(
6450 &mut self,
6451 modifiers: &Modifiers,
6452 position_map: &PositionMap,
6453 window: &mut Window,
6454 cx: &mut Context<Self>,
6455 ) {
6456 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6457 return;
6458 }
6459
6460 let mouse_position = window.mouse_position();
6461 let point_for_position = position_map.point_for_position(mouse_position);
6462 let position = point_for_position.previous_valid;
6463
6464 self.select(
6465 SelectPhase::BeginColumnar {
6466 position,
6467 reset: false,
6468 goal_column: point_for_position.exact_unclipped.column(),
6469 },
6470 window,
6471 cx,
6472 );
6473 }
6474
6475 fn update_edit_prediction_preview(
6476 &mut self,
6477 modifiers: &Modifiers,
6478 window: &mut Window,
6479 cx: &mut Context<Self>,
6480 ) {
6481 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6482 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6483 return;
6484 };
6485
6486 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6487 if matches!(
6488 self.edit_prediction_preview,
6489 EditPredictionPreview::Inactive { .. }
6490 ) {
6491 self.edit_prediction_preview = EditPredictionPreview::Active {
6492 previous_scroll_position: None,
6493 since: Instant::now(),
6494 };
6495
6496 self.update_visible_inline_completion(window, cx);
6497 cx.notify();
6498 }
6499 } else if let EditPredictionPreview::Active {
6500 previous_scroll_position,
6501 since,
6502 } = self.edit_prediction_preview
6503 {
6504 if let (Some(previous_scroll_position), Some(position_map)) =
6505 (previous_scroll_position, self.last_position_map.as_ref())
6506 {
6507 self.set_scroll_position(
6508 previous_scroll_position
6509 .scroll_position(&position_map.snapshot.display_snapshot),
6510 window,
6511 cx,
6512 );
6513 }
6514
6515 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6516 released_too_fast: since.elapsed() < Duration::from_millis(200),
6517 };
6518 self.clear_row_highlights::<EditPredictionPreview>();
6519 self.update_visible_inline_completion(window, cx);
6520 cx.notify();
6521 }
6522 }
6523
6524 fn update_visible_inline_completion(
6525 &mut self,
6526 _window: &mut Window,
6527 cx: &mut Context<Self>,
6528 ) -> Option<()> {
6529 let selection = self.selections.newest_anchor();
6530 let cursor = selection.head();
6531 let multibuffer = self.buffer.read(cx).snapshot(cx);
6532 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6533 let excerpt_id = cursor.excerpt_id;
6534
6535 let show_in_menu = self.show_edit_predictions_in_menu();
6536 let completions_menu_has_precedence = !show_in_menu
6537 && (self.context_menu.borrow().is_some()
6538 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6539
6540 if completions_menu_has_precedence
6541 || !offset_selection.is_empty()
6542 || self
6543 .active_inline_completion
6544 .as_ref()
6545 .map_or(false, |completion| {
6546 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6547 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6548 !invalidation_range.contains(&offset_selection.head())
6549 })
6550 {
6551 self.discard_inline_completion(false, cx);
6552 return None;
6553 }
6554
6555 self.take_active_inline_completion(cx);
6556 let Some(provider) = self.edit_prediction_provider() else {
6557 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6558 return None;
6559 };
6560
6561 let (buffer, cursor_buffer_position) =
6562 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6563
6564 self.edit_prediction_settings =
6565 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6566
6567 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6568
6569 if self.edit_prediction_indent_conflict {
6570 let cursor_point = cursor.to_point(&multibuffer);
6571
6572 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6573
6574 if let Some((_, indent)) = indents.iter().next() {
6575 if indent.len == cursor_point.column {
6576 self.edit_prediction_indent_conflict = false;
6577 }
6578 }
6579 }
6580
6581 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6582 let edits = inline_completion
6583 .edits
6584 .into_iter()
6585 .flat_map(|(range, new_text)| {
6586 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6587 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6588 Some((start..end, new_text))
6589 })
6590 .collect::<Vec<_>>();
6591 if edits.is_empty() {
6592 return None;
6593 }
6594
6595 let first_edit_start = edits.first().unwrap().0.start;
6596 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6597 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6598
6599 let last_edit_end = edits.last().unwrap().0.end;
6600 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6601 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6602
6603 let cursor_row = cursor.to_point(&multibuffer).row;
6604
6605 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6606
6607 let mut inlay_ids = Vec::new();
6608 let invalidation_row_range;
6609 let move_invalidation_row_range = if cursor_row < edit_start_row {
6610 Some(cursor_row..edit_end_row)
6611 } else if cursor_row > edit_end_row {
6612 Some(edit_start_row..cursor_row)
6613 } else {
6614 None
6615 };
6616 let is_move =
6617 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6618 let completion = if is_move {
6619 invalidation_row_range =
6620 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6621 let target = first_edit_start;
6622 InlineCompletion::Move { target, snapshot }
6623 } else {
6624 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6625 && !self.inline_completions_hidden_for_vim_mode;
6626
6627 if show_completions_in_buffer {
6628 if edits
6629 .iter()
6630 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6631 {
6632 let mut inlays = Vec::new();
6633 for (range, new_text) in &edits {
6634 let inlay = Inlay::inline_completion(
6635 post_inc(&mut self.next_inlay_id),
6636 range.start,
6637 new_text.as_str(),
6638 );
6639 inlay_ids.push(inlay.id);
6640 inlays.push(inlay);
6641 }
6642
6643 self.splice_inlays(&[], inlays, cx);
6644 } else {
6645 let background_color = cx.theme().status().deleted_background;
6646 self.highlight_text::<InlineCompletionHighlight>(
6647 edits.iter().map(|(range, _)| range.clone()).collect(),
6648 HighlightStyle {
6649 background_color: Some(background_color),
6650 ..Default::default()
6651 },
6652 cx,
6653 );
6654 }
6655 }
6656
6657 invalidation_row_range = edit_start_row..edit_end_row;
6658
6659 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6660 if provider.show_tab_accept_marker() {
6661 EditDisplayMode::TabAccept
6662 } else {
6663 EditDisplayMode::Inline
6664 }
6665 } else {
6666 EditDisplayMode::DiffPopover
6667 };
6668
6669 InlineCompletion::Edit {
6670 edits,
6671 edit_preview: inline_completion.edit_preview,
6672 display_mode,
6673 snapshot,
6674 }
6675 };
6676
6677 let invalidation_range = multibuffer
6678 .anchor_before(Point::new(invalidation_row_range.start, 0))
6679 ..multibuffer.anchor_after(Point::new(
6680 invalidation_row_range.end,
6681 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6682 ));
6683
6684 self.stale_inline_completion_in_menu = None;
6685 self.active_inline_completion = Some(InlineCompletionState {
6686 inlay_ids,
6687 completion,
6688 completion_id: inline_completion.id,
6689 invalidation_range,
6690 });
6691
6692 cx.notify();
6693
6694 Some(())
6695 }
6696
6697 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6698 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6699 }
6700
6701 fn render_code_actions_indicator(
6702 &self,
6703 _style: &EditorStyle,
6704 row: DisplayRow,
6705 is_active: bool,
6706 breakpoint: Option<&(Anchor, Breakpoint)>,
6707 cx: &mut Context<Self>,
6708 ) -> Option<IconButton> {
6709 let color = Color::Muted;
6710 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6711 let show_tooltip = !self.context_menu_visible();
6712
6713 if self.available_code_actions.is_some() {
6714 Some(
6715 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6716 .shape(ui::IconButtonShape::Square)
6717 .icon_size(IconSize::XSmall)
6718 .icon_color(color)
6719 .toggle_state(is_active)
6720 .when(show_tooltip, |this| {
6721 this.tooltip({
6722 let focus_handle = self.focus_handle.clone();
6723 move |window, cx| {
6724 Tooltip::for_action_in(
6725 "Toggle Code Actions",
6726 &ToggleCodeActions {
6727 deployed_from_indicator: None,
6728 quick_launch: false,
6729 },
6730 &focus_handle,
6731 window,
6732 cx,
6733 )
6734 }
6735 })
6736 })
6737 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
6738 let quick_launch = e.down.button == MouseButton::Left;
6739 window.focus(&editor.focus_handle(cx));
6740 editor.toggle_code_actions(
6741 &ToggleCodeActions {
6742 deployed_from_indicator: Some(row),
6743 quick_launch,
6744 },
6745 window,
6746 cx,
6747 );
6748 }))
6749 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6750 editor.set_breakpoint_context_menu(
6751 row,
6752 position,
6753 event.down.position,
6754 window,
6755 cx,
6756 );
6757 })),
6758 )
6759 } else {
6760 None
6761 }
6762 }
6763
6764 fn clear_tasks(&mut self) {
6765 self.tasks.clear()
6766 }
6767
6768 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6769 if self.tasks.insert(key, value).is_some() {
6770 // This case should hopefully be rare, but just in case...
6771 log::error!(
6772 "multiple different run targets found on a single line, only the last target will be rendered"
6773 )
6774 }
6775 }
6776
6777 /// Get all display points of breakpoints that will be rendered within editor
6778 ///
6779 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6780 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6781 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6782 fn active_breakpoints(
6783 &self,
6784 range: Range<DisplayRow>,
6785 window: &mut Window,
6786 cx: &mut Context<Self>,
6787 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6788 let mut breakpoint_display_points = HashMap::default();
6789
6790 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6791 return breakpoint_display_points;
6792 };
6793
6794 let snapshot = self.snapshot(window, cx);
6795
6796 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6797 let Some(project) = self.project.as_ref() else {
6798 return breakpoint_display_points;
6799 };
6800
6801 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6802 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6803
6804 for (buffer_snapshot, range, excerpt_id) in
6805 multi_buffer_snapshot.range_to_buffer_ranges(range)
6806 {
6807 let Some(buffer) = project.read_with(cx, |this, cx| {
6808 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6809 }) else {
6810 continue;
6811 };
6812 let breakpoints = breakpoint_store.read(cx).breakpoints(
6813 &buffer,
6814 Some(
6815 buffer_snapshot.anchor_before(range.start)
6816 ..buffer_snapshot.anchor_after(range.end),
6817 ),
6818 buffer_snapshot,
6819 cx,
6820 );
6821 for (anchor, breakpoint) in breakpoints {
6822 let multi_buffer_anchor =
6823 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6824 let position = multi_buffer_anchor
6825 .to_point(&multi_buffer_snapshot)
6826 .to_display_point(&snapshot);
6827
6828 breakpoint_display_points
6829 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6830 }
6831 }
6832
6833 breakpoint_display_points
6834 }
6835
6836 fn breakpoint_context_menu(
6837 &self,
6838 anchor: Anchor,
6839 window: &mut Window,
6840 cx: &mut Context<Self>,
6841 ) -> Entity<ui::ContextMenu> {
6842 let weak_editor = cx.weak_entity();
6843 let focus_handle = self.focus_handle(cx);
6844
6845 let row = self
6846 .buffer
6847 .read(cx)
6848 .snapshot(cx)
6849 .summary_for_anchor::<Point>(&anchor)
6850 .row;
6851
6852 let breakpoint = self
6853 .breakpoint_at_row(row, window, cx)
6854 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6855
6856 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6857 "Edit Log Breakpoint"
6858 } else {
6859 "Set Log Breakpoint"
6860 };
6861
6862 let condition_breakpoint_msg = if breakpoint
6863 .as_ref()
6864 .is_some_and(|bp| bp.1.condition.is_some())
6865 {
6866 "Edit Condition Breakpoint"
6867 } else {
6868 "Set Condition Breakpoint"
6869 };
6870
6871 let hit_condition_breakpoint_msg = if breakpoint
6872 .as_ref()
6873 .is_some_and(|bp| bp.1.hit_condition.is_some())
6874 {
6875 "Edit Hit Condition Breakpoint"
6876 } else {
6877 "Set Hit Condition Breakpoint"
6878 };
6879
6880 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6881 "Unset Breakpoint"
6882 } else {
6883 "Set Breakpoint"
6884 };
6885
6886 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6887 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6888
6889 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6890 BreakpointState::Enabled => Some("Disable"),
6891 BreakpointState::Disabled => Some("Enable"),
6892 });
6893
6894 let (anchor, breakpoint) =
6895 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6896
6897 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6898 menu.on_blur_subscription(Subscription::new(|| {}))
6899 .context(focus_handle)
6900 .when(run_to_cursor, |this| {
6901 let weak_editor = weak_editor.clone();
6902 this.entry("Run to cursor", None, move |window, cx| {
6903 weak_editor
6904 .update(cx, |editor, cx| {
6905 editor.change_selections(None, window, cx, |s| {
6906 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6907 });
6908 })
6909 .ok();
6910
6911 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6912 })
6913 .separator()
6914 })
6915 .when_some(toggle_state_msg, |this, msg| {
6916 this.entry(msg, None, {
6917 let weak_editor = weak_editor.clone();
6918 let breakpoint = breakpoint.clone();
6919 move |_window, cx| {
6920 weak_editor
6921 .update(cx, |this, cx| {
6922 this.edit_breakpoint_at_anchor(
6923 anchor,
6924 breakpoint.as_ref().clone(),
6925 BreakpointEditAction::InvertState,
6926 cx,
6927 );
6928 })
6929 .log_err();
6930 }
6931 })
6932 })
6933 .entry(set_breakpoint_msg, None, {
6934 let weak_editor = weak_editor.clone();
6935 let breakpoint = breakpoint.clone();
6936 move |_window, cx| {
6937 weak_editor
6938 .update(cx, |this, cx| {
6939 this.edit_breakpoint_at_anchor(
6940 anchor,
6941 breakpoint.as_ref().clone(),
6942 BreakpointEditAction::Toggle,
6943 cx,
6944 );
6945 })
6946 .log_err();
6947 }
6948 })
6949 .entry(log_breakpoint_msg, None, {
6950 let breakpoint = breakpoint.clone();
6951 let weak_editor = weak_editor.clone();
6952 move |window, cx| {
6953 weak_editor
6954 .update(cx, |this, cx| {
6955 this.add_edit_breakpoint_block(
6956 anchor,
6957 breakpoint.as_ref(),
6958 BreakpointPromptEditAction::Log,
6959 window,
6960 cx,
6961 );
6962 })
6963 .log_err();
6964 }
6965 })
6966 .entry(condition_breakpoint_msg, None, {
6967 let breakpoint = breakpoint.clone();
6968 let weak_editor = weak_editor.clone();
6969 move |window, cx| {
6970 weak_editor
6971 .update(cx, |this, cx| {
6972 this.add_edit_breakpoint_block(
6973 anchor,
6974 breakpoint.as_ref(),
6975 BreakpointPromptEditAction::Condition,
6976 window,
6977 cx,
6978 );
6979 })
6980 .log_err();
6981 }
6982 })
6983 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6984 weak_editor
6985 .update(cx, |this, cx| {
6986 this.add_edit_breakpoint_block(
6987 anchor,
6988 breakpoint.as_ref(),
6989 BreakpointPromptEditAction::HitCondition,
6990 window,
6991 cx,
6992 );
6993 })
6994 .log_err();
6995 })
6996 })
6997 }
6998
6999 fn render_breakpoint(
7000 &self,
7001 position: Anchor,
7002 row: DisplayRow,
7003 breakpoint: &Breakpoint,
7004 cx: &mut Context<Self>,
7005 ) -> IconButton {
7006 // Is it a breakpoint that shows up when hovering over gutter?
7007 let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
7008 (false, false),
7009 |PhantomBreakpointIndicator {
7010 is_active,
7011 display_row,
7012 collides_with_existing_breakpoint,
7013 }| {
7014 (
7015 is_active && display_row == row,
7016 collides_with_existing_breakpoint,
7017 )
7018 },
7019 );
7020
7021 let (color, icon) = {
7022 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
7023 (false, false) => ui::IconName::DebugBreakpoint,
7024 (true, false) => ui::IconName::DebugLogBreakpoint,
7025 (false, true) => ui::IconName::DebugDisabledBreakpoint,
7026 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
7027 };
7028
7029 let color = if is_phantom {
7030 Color::Hint
7031 } else {
7032 Color::Debugger
7033 };
7034
7035 (color, icon)
7036 };
7037
7038 let breakpoint = Arc::from(breakpoint.clone());
7039
7040 let alt_as_text = gpui::Keystroke {
7041 modifiers: Modifiers::secondary_key(),
7042 ..Default::default()
7043 };
7044 let primary_action_text = if breakpoint.is_disabled() {
7045 "enable"
7046 } else if is_phantom && !collides_with_existing {
7047 "set"
7048 } else {
7049 "unset"
7050 };
7051 let mut primary_text = format!("Click to {primary_action_text}");
7052 if collides_with_existing && !breakpoint.is_disabled() {
7053 use std::fmt::Write;
7054 write!(primary_text, ", {alt_as_text}-click to disable").ok();
7055 }
7056 let primary_text = SharedString::from(primary_text);
7057 let focus_handle = self.focus_handle.clone();
7058 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
7059 .icon_size(IconSize::XSmall)
7060 .size(ui::ButtonSize::None)
7061 .icon_color(color)
7062 .style(ButtonStyle::Transparent)
7063 .on_click(cx.listener({
7064 let breakpoint = breakpoint.clone();
7065
7066 move |editor, event: &ClickEvent, window, cx| {
7067 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
7068 BreakpointEditAction::InvertState
7069 } else {
7070 BreakpointEditAction::Toggle
7071 };
7072
7073 window.focus(&editor.focus_handle(cx));
7074 editor.edit_breakpoint_at_anchor(
7075 position,
7076 breakpoint.as_ref().clone(),
7077 edit_action,
7078 cx,
7079 );
7080 }
7081 }))
7082 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7083 editor.set_breakpoint_context_menu(
7084 row,
7085 Some(position),
7086 event.down.position,
7087 window,
7088 cx,
7089 );
7090 }))
7091 .tooltip(move |window, cx| {
7092 Tooltip::with_meta_in(
7093 primary_text.clone(),
7094 None,
7095 "Right-click for more options",
7096 &focus_handle,
7097 window,
7098 cx,
7099 )
7100 })
7101 }
7102
7103 fn build_tasks_context(
7104 project: &Entity<Project>,
7105 buffer: &Entity<Buffer>,
7106 buffer_row: u32,
7107 tasks: &Arc<RunnableTasks>,
7108 cx: &mut Context<Self>,
7109 ) -> Task<Option<task::TaskContext>> {
7110 let position = Point::new(buffer_row, tasks.column);
7111 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
7112 let location = Location {
7113 buffer: buffer.clone(),
7114 range: range_start..range_start,
7115 };
7116 // Fill in the environmental variables from the tree-sitter captures
7117 let mut captured_task_variables = TaskVariables::default();
7118 for (capture_name, value) in tasks.extra_variables.clone() {
7119 captured_task_variables.insert(
7120 task::VariableName::Custom(capture_name.into()),
7121 value.clone(),
7122 );
7123 }
7124 project.update(cx, |project, cx| {
7125 project.task_store().update(cx, |task_store, cx| {
7126 task_store.task_context_for_location(captured_task_variables, location, cx)
7127 })
7128 })
7129 }
7130
7131 pub fn spawn_nearest_task(
7132 &mut self,
7133 action: &SpawnNearestTask,
7134 window: &mut Window,
7135 cx: &mut Context<Self>,
7136 ) {
7137 let Some((workspace, _)) = self.workspace.clone() else {
7138 return;
7139 };
7140 let Some(project) = self.project.clone() else {
7141 return;
7142 };
7143
7144 // Try to find a closest, enclosing node using tree-sitter that has a
7145 // task
7146 let Some((buffer, buffer_row, tasks)) = self
7147 .find_enclosing_node_task(cx)
7148 // Or find the task that's closest in row-distance.
7149 .or_else(|| self.find_closest_task(cx))
7150 else {
7151 return;
7152 };
7153
7154 let reveal_strategy = action.reveal;
7155 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
7156 cx.spawn_in(window, async move |_, cx| {
7157 let context = task_context.await?;
7158 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
7159
7160 let resolved = &mut resolved_task.resolved;
7161 resolved.reveal = reveal_strategy;
7162
7163 workspace
7164 .update_in(cx, |workspace, window, cx| {
7165 workspace.schedule_resolved_task(
7166 task_source_kind,
7167 resolved_task,
7168 false,
7169 window,
7170 cx,
7171 );
7172 })
7173 .ok()
7174 })
7175 .detach();
7176 }
7177
7178 fn find_closest_task(
7179 &mut self,
7180 cx: &mut Context<Self>,
7181 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7182 let cursor_row = self.selections.newest_adjusted(cx).head().row;
7183
7184 let ((buffer_id, row), tasks) = self
7185 .tasks
7186 .iter()
7187 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
7188
7189 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
7190 let tasks = Arc::new(tasks.to_owned());
7191 Some((buffer, *row, tasks))
7192 }
7193
7194 fn find_enclosing_node_task(
7195 &mut self,
7196 cx: &mut Context<Self>,
7197 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7198 let snapshot = self.buffer.read(cx).snapshot(cx);
7199 let offset = self.selections.newest::<usize>(cx).head();
7200 let excerpt = snapshot.excerpt_containing(offset..offset)?;
7201 let buffer_id = excerpt.buffer().remote_id();
7202
7203 let layer = excerpt.buffer().syntax_layer_at(offset)?;
7204 let mut cursor = layer.node().walk();
7205
7206 while cursor.goto_first_child_for_byte(offset).is_some() {
7207 if cursor.node().end_byte() == offset {
7208 cursor.goto_next_sibling();
7209 }
7210 }
7211
7212 // Ascend to the smallest ancestor that contains the range and has a task.
7213 loop {
7214 let node = cursor.node();
7215 let node_range = node.byte_range();
7216 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
7217
7218 // Check if this node contains our offset
7219 if node_range.start <= offset && node_range.end >= offset {
7220 // If it contains offset, check for task
7221 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
7222 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
7223 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
7224 }
7225 }
7226
7227 if !cursor.goto_parent() {
7228 break;
7229 }
7230 }
7231 None
7232 }
7233
7234 fn render_run_indicator(
7235 &self,
7236 _style: &EditorStyle,
7237 is_active: bool,
7238 row: DisplayRow,
7239 breakpoint: Option<(Anchor, Breakpoint)>,
7240 cx: &mut Context<Self>,
7241 ) -> IconButton {
7242 let color = Color::Muted;
7243 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
7244
7245 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
7246 .shape(ui::IconButtonShape::Square)
7247 .icon_size(IconSize::XSmall)
7248 .icon_color(color)
7249 .toggle_state(is_active)
7250 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
7251 let quick_launch = e.down.button == MouseButton::Left;
7252 window.focus(&editor.focus_handle(cx));
7253 editor.toggle_code_actions(
7254 &ToggleCodeActions {
7255 deployed_from_indicator: Some(row),
7256 quick_launch,
7257 },
7258 window,
7259 cx,
7260 );
7261 }))
7262 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7263 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
7264 }))
7265 }
7266
7267 pub fn context_menu_visible(&self) -> bool {
7268 !self.edit_prediction_preview_is_active()
7269 && self
7270 .context_menu
7271 .borrow()
7272 .as_ref()
7273 .map_or(false, |menu| menu.visible())
7274 }
7275
7276 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
7277 self.context_menu
7278 .borrow()
7279 .as_ref()
7280 .map(|menu| menu.origin())
7281 }
7282
7283 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
7284 self.context_menu_options = Some(options);
7285 }
7286
7287 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
7288 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
7289
7290 fn render_edit_prediction_popover(
7291 &mut self,
7292 text_bounds: &Bounds<Pixels>,
7293 content_origin: gpui::Point<Pixels>,
7294 editor_snapshot: &EditorSnapshot,
7295 visible_row_range: Range<DisplayRow>,
7296 scroll_top: f32,
7297 scroll_bottom: f32,
7298 line_layouts: &[LineWithInvisibles],
7299 line_height: Pixels,
7300 scroll_pixel_position: gpui::Point<Pixels>,
7301 newest_selection_head: Option<DisplayPoint>,
7302 editor_width: Pixels,
7303 style: &EditorStyle,
7304 window: &mut Window,
7305 cx: &mut App,
7306 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7307 let active_inline_completion = self.active_inline_completion.as_ref()?;
7308
7309 if self.edit_prediction_visible_in_cursor_popover(true) {
7310 return None;
7311 }
7312
7313 match &active_inline_completion.completion {
7314 InlineCompletion::Move { target, .. } => {
7315 let target_display_point = target.to_display_point(editor_snapshot);
7316
7317 if self.edit_prediction_requires_modifier() {
7318 if !self.edit_prediction_preview_is_active() {
7319 return None;
7320 }
7321
7322 self.render_edit_prediction_modifier_jump_popover(
7323 text_bounds,
7324 content_origin,
7325 visible_row_range,
7326 line_layouts,
7327 line_height,
7328 scroll_pixel_position,
7329 newest_selection_head,
7330 target_display_point,
7331 window,
7332 cx,
7333 )
7334 } else {
7335 self.render_edit_prediction_eager_jump_popover(
7336 text_bounds,
7337 content_origin,
7338 editor_snapshot,
7339 visible_row_range,
7340 scroll_top,
7341 scroll_bottom,
7342 line_height,
7343 scroll_pixel_position,
7344 target_display_point,
7345 editor_width,
7346 window,
7347 cx,
7348 )
7349 }
7350 }
7351 InlineCompletion::Edit {
7352 display_mode: EditDisplayMode::Inline,
7353 ..
7354 } => None,
7355 InlineCompletion::Edit {
7356 display_mode: EditDisplayMode::TabAccept,
7357 edits,
7358 ..
7359 } => {
7360 let range = &edits.first()?.0;
7361 let target_display_point = range.end.to_display_point(editor_snapshot);
7362
7363 self.render_edit_prediction_end_of_line_popover(
7364 "Accept",
7365 editor_snapshot,
7366 visible_row_range,
7367 target_display_point,
7368 line_height,
7369 scroll_pixel_position,
7370 content_origin,
7371 editor_width,
7372 window,
7373 cx,
7374 )
7375 }
7376 InlineCompletion::Edit {
7377 edits,
7378 edit_preview,
7379 display_mode: EditDisplayMode::DiffPopover,
7380 snapshot,
7381 } => self.render_edit_prediction_diff_popover(
7382 text_bounds,
7383 content_origin,
7384 editor_snapshot,
7385 visible_row_range,
7386 line_layouts,
7387 line_height,
7388 scroll_pixel_position,
7389 newest_selection_head,
7390 editor_width,
7391 style,
7392 edits,
7393 edit_preview,
7394 snapshot,
7395 window,
7396 cx,
7397 ),
7398 }
7399 }
7400
7401 fn render_edit_prediction_modifier_jump_popover(
7402 &mut self,
7403 text_bounds: &Bounds<Pixels>,
7404 content_origin: gpui::Point<Pixels>,
7405 visible_row_range: Range<DisplayRow>,
7406 line_layouts: &[LineWithInvisibles],
7407 line_height: Pixels,
7408 scroll_pixel_position: gpui::Point<Pixels>,
7409 newest_selection_head: Option<DisplayPoint>,
7410 target_display_point: DisplayPoint,
7411 window: &mut Window,
7412 cx: &mut App,
7413 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7414 let scrolled_content_origin =
7415 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7416
7417 const SCROLL_PADDING_Y: Pixels = px(12.);
7418
7419 if target_display_point.row() < visible_row_range.start {
7420 return self.render_edit_prediction_scroll_popover(
7421 |_| SCROLL_PADDING_Y,
7422 IconName::ArrowUp,
7423 visible_row_range,
7424 line_layouts,
7425 newest_selection_head,
7426 scrolled_content_origin,
7427 window,
7428 cx,
7429 );
7430 } else if target_display_point.row() >= visible_row_range.end {
7431 return self.render_edit_prediction_scroll_popover(
7432 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7433 IconName::ArrowDown,
7434 visible_row_range,
7435 line_layouts,
7436 newest_selection_head,
7437 scrolled_content_origin,
7438 window,
7439 cx,
7440 );
7441 }
7442
7443 const POLE_WIDTH: Pixels = px(2.);
7444
7445 let line_layout =
7446 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7447 let target_column = target_display_point.column() as usize;
7448
7449 let target_x = line_layout.x_for_index(target_column);
7450 let target_y =
7451 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7452
7453 let flag_on_right = target_x < text_bounds.size.width / 2.;
7454
7455 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7456 border_color.l += 0.001;
7457
7458 let mut element = v_flex()
7459 .items_end()
7460 .when(flag_on_right, |el| el.items_start())
7461 .child(if flag_on_right {
7462 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7463 .rounded_bl(px(0.))
7464 .rounded_tl(px(0.))
7465 .border_l_2()
7466 .border_color(border_color)
7467 } else {
7468 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7469 .rounded_br(px(0.))
7470 .rounded_tr(px(0.))
7471 .border_r_2()
7472 .border_color(border_color)
7473 })
7474 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7475 .into_any();
7476
7477 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7478
7479 let mut origin = scrolled_content_origin + point(target_x, target_y)
7480 - point(
7481 if flag_on_right {
7482 POLE_WIDTH
7483 } else {
7484 size.width - POLE_WIDTH
7485 },
7486 size.height - line_height,
7487 );
7488
7489 origin.x = origin.x.max(content_origin.x);
7490
7491 element.prepaint_at(origin, window, cx);
7492
7493 Some((element, origin))
7494 }
7495
7496 fn render_edit_prediction_scroll_popover(
7497 &mut self,
7498 to_y: impl Fn(Size<Pixels>) -> Pixels,
7499 scroll_icon: IconName,
7500 visible_row_range: Range<DisplayRow>,
7501 line_layouts: &[LineWithInvisibles],
7502 newest_selection_head: Option<DisplayPoint>,
7503 scrolled_content_origin: gpui::Point<Pixels>,
7504 window: &mut Window,
7505 cx: &mut App,
7506 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7507 let mut element = self
7508 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7509 .into_any();
7510
7511 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7512
7513 let cursor = newest_selection_head?;
7514 let cursor_row_layout =
7515 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7516 let cursor_column = cursor.column() as usize;
7517
7518 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7519
7520 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7521
7522 element.prepaint_at(origin, window, cx);
7523 Some((element, origin))
7524 }
7525
7526 fn render_edit_prediction_eager_jump_popover(
7527 &mut self,
7528 text_bounds: &Bounds<Pixels>,
7529 content_origin: gpui::Point<Pixels>,
7530 editor_snapshot: &EditorSnapshot,
7531 visible_row_range: Range<DisplayRow>,
7532 scroll_top: f32,
7533 scroll_bottom: f32,
7534 line_height: Pixels,
7535 scroll_pixel_position: gpui::Point<Pixels>,
7536 target_display_point: DisplayPoint,
7537 editor_width: Pixels,
7538 window: &mut Window,
7539 cx: &mut App,
7540 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7541 if target_display_point.row().as_f32() < scroll_top {
7542 let mut element = self
7543 .render_edit_prediction_line_popover(
7544 "Jump to Edit",
7545 Some(IconName::ArrowUp),
7546 window,
7547 cx,
7548 )?
7549 .into_any();
7550
7551 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7552 let offset = point(
7553 (text_bounds.size.width - size.width) / 2.,
7554 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7555 );
7556
7557 let origin = text_bounds.origin + offset;
7558 element.prepaint_at(origin, window, cx);
7559 Some((element, origin))
7560 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7561 let mut element = self
7562 .render_edit_prediction_line_popover(
7563 "Jump to Edit",
7564 Some(IconName::ArrowDown),
7565 window,
7566 cx,
7567 )?
7568 .into_any();
7569
7570 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7571 let offset = point(
7572 (text_bounds.size.width - size.width) / 2.,
7573 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7574 );
7575
7576 let origin = text_bounds.origin + offset;
7577 element.prepaint_at(origin, window, cx);
7578 Some((element, origin))
7579 } else {
7580 self.render_edit_prediction_end_of_line_popover(
7581 "Jump to Edit",
7582 editor_snapshot,
7583 visible_row_range,
7584 target_display_point,
7585 line_height,
7586 scroll_pixel_position,
7587 content_origin,
7588 editor_width,
7589 window,
7590 cx,
7591 )
7592 }
7593 }
7594
7595 fn render_edit_prediction_end_of_line_popover(
7596 self: &mut Editor,
7597 label: &'static str,
7598 editor_snapshot: &EditorSnapshot,
7599 visible_row_range: Range<DisplayRow>,
7600 target_display_point: DisplayPoint,
7601 line_height: Pixels,
7602 scroll_pixel_position: gpui::Point<Pixels>,
7603 content_origin: gpui::Point<Pixels>,
7604 editor_width: Pixels,
7605 window: &mut Window,
7606 cx: &mut App,
7607 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7608 let target_line_end = DisplayPoint::new(
7609 target_display_point.row(),
7610 editor_snapshot.line_len(target_display_point.row()),
7611 );
7612
7613 let mut element = self
7614 .render_edit_prediction_line_popover(label, None, window, cx)?
7615 .into_any();
7616
7617 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7618
7619 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7620
7621 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7622 let mut origin = start_point
7623 + line_origin
7624 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7625 origin.x = origin.x.max(content_origin.x);
7626
7627 let max_x = content_origin.x + editor_width - size.width;
7628
7629 if origin.x > max_x {
7630 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7631
7632 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7633 origin.y += offset;
7634 IconName::ArrowUp
7635 } else {
7636 origin.y -= offset;
7637 IconName::ArrowDown
7638 };
7639
7640 element = self
7641 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7642 .into_any();
7643
7644 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7645
7646 origin.x = content_origin.x + editor_width - size.width - px(2.);
7647 }
7648
7649 element.prepaint_at(origin, window, cx);
7650 Some((element, origin))
7651 }
7652
7653 fn render_edit_prediction_diff_popover(
7654 self: &Editor,
7655 text_bounds: &Bounds<Pixels>,
7656 content_origin: gpui::Point<Pixels>,
7657 editor_snapshot: &EditorSnapshot,
7658 visible_row_range: Range<DisplayRow>,
7659 line_layouts: &[LineWithInvisibles],
7660 line_height: Pixels,
7661 scroll_pixel_position: gpui::Point<Pixels>,
7662 newest_selection_head: Option<DisplayPoint>,
7663 editor_width: Pixels,
7664 style: &EditorStyle,
7665 edits: &Vec<(Range<Anchor>, String)>,
7666 edit_preview: &Option<language::EditPreview>,
7667 snapshot: &language::BufferSnapshot,
7668 window: &mut Window,
7669 cx: &mut App,
7670 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7671 let edit_start = edits
7672 .first()
7673 .unwrap()
7674 .0
7675 .start
7676 .to_display_point(editor_snapshot);
7677 let edit_end = edits
7678 .last()
7679 .unwrap()
7680 .0
7681 .end
7682 .to_display_point(editor_snapshot);
7683
7684 let is_visible = visible_row_range.contains(&edit_start.row())
7685 || visible_row_range.contains(&edit_end.row());
7686 if !is_visible {
7687 return None;
7688 }
7689
7690 let highlighted_edits =
7691 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7692
7693 let styled_text = highlighted_edits.to_styled_text(&style.text);
7694 let line_count = highlighted_edits.text.lines().count();
7695
7696 const BORDER_WIDTH: Pixels = px(1.);
7697
7698 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7699 let has_keybind = keybind.is_some();
7700
7701 let mut element = h_flex()
7702 .items_start()
7703 .child(
7704 h_flex()
7705 .bg(cx.theme().colors().editor_background)
7706 .border(BORDER_WIDTH)
7707 .shadow_sm()
7708 .border_color(cx.theme().colors().border)
7709 .rounded_l_lg()
7710 .when(line_count > 1, |el| el.rounded_br_lg())
7711 .pr_1()
7712 .child(styled_text),
7713 )
7714 .child(
7715 h_flex()
7716 .h(line_height + BORDER_WIDTH * 2.)
7717 .px_1p5()
7718 .gap_1()
7719 // Workaround: For some reason, there's a gap if we don't do this
7720 .ml(-BORDER_WIDTH)
7721 .shadow(smallvec![gpui::BoxShadow {
7722 color: gpui::black().opacity(0.05),
7723 offset: point(px(1.), px(1.)),
7724 blur_radius: px(2.),
7725 spread_radius: px(0.),
7726 }])
7727 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7728 .border(BORDER_WIDTH)
7729 .border_color(cx.theme().colors().border)
7730 .rounded_r_lg()
7731 .id("edit_prediction_diff_popover_keybind")
7732 .when(!has_keybind, |el| {
7733 let status_colors = cx.theme().status();
7734
7735 el.bg(status_colors.error_background)
7736 .border_color(status_colors.error.opacity(0.6))
7737 .child(Icon::new(IconName::Info).color(Color::Error))
7738 .cursor_default()
7739 .hoverable_tooltip(move |_window, cx| {
7740 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7741 })
7742 })
7743 .children(keybind),
7744 )
7745 .into_any();
7746
7747 let longest_row =
7748 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7749 let longest_line_width = if visible_row_range.contains(&longest_row) {
7750 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7751 } else {
7752 layout_line(
7753 longest_row,
7754 editor_snapshot,
7755 style,
7756 editor_width,
7757 |_| false,
7758 window,
7759 cx,
7760 )
7761 .width
7762 };
7763
7764 let viewport_bounds =
7765 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7766 right: -EditorElement::SCROLLBAR_WIDTH,
7767 ..Default::default()
7768 });
7769
7770 let x_after_longest =
7771 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7772 - scroll_pixel_position.x;
7773
7774 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7775
7776 // Fully visible if it can be displayed within the window (allow overlapping other
7777 // panes). However, this is only allowed if the popover starts within text_bounds.
7778 let can_position_to_the_right = x_after_longest < text_bounds.right()
7779 && x_after_longest + element_bounds.width < viewport_bounds.right();
7780
7781 let mut origin = if can_position_to_the_right {
7782 point(
7783 x_after_longest,
7784 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7785 - scroll_pixel_position.y,
7786 )
7787 } else {
7788 let cursor_row = newest_selection_head.map(|head| head.row());
7789 let above_edit = edit_start
7790 .row()
7791 .0
7792 .checked_sub(line_count as u32)
7793 .map(DisplayRow);
7794 let below_edit = Some(edit_end.row() + 1);
7795 let above_cursor =
7796 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7797 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7798
7799 // Place the edit popover adjacent to the edit if there is a location
7800 // available that is onscreen and does not obscure the cursor. Otherwise,
7801 // place it adjacent to the cursor.
7802 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7803 .into_iter()
7804 .flatten()
7805 .find(|&start_row| {
7806 let end_row = start_row + line_count as u32;
7807 visible_row_range.contains(&start_row)
7808 && visible_row_range.contains(&end_row)
7809 && cursor_row.map_or(true, |cursor_row| {
7810 !((start_row..end_row).contains(&cursor_row))
7811 })
7812 })?;
7813
7814 content_origin
7815 + point(
7816 -scroll_pixel_position.x,
7817 row_target.as_f32() * line_height - scroll_pixel_position.y,
7818 )
7819 };
7820
7821 origin.x -= BORDER_WIDTH;
7822
7823 window.defer_draw(element, origin, 1);
7824
7825 // Do not return an element, since it will already be drawn due to defer_draw.
7826 None
7827 }
7828
7829 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7830 px(30.)
7831 }
7832
7833 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7834 if self.read_only(cx) {
7835 cx.theme().players().read_only()
7836 } else {
7837 self.style.as_ref().unwrap().local_player
7838 }
7839 }
7840
7841 fn render_edit_prediction_accept_keybind(
7842 &self,
7843 window: &mut Window,
7844 cx: &App,
7845 ) -> Option<AnyElement> {
7846 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7847 let accept_keystroke = accept_binding.keystroke()?;
7848
7849 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7850
7851 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7852 Color::Accent
7853 } else {
7854 Color::Muted
7855 };
7856
7857 h_flex()
7858 .px_0p5()
7859 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7860 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7861 .text_size(TextSize::XSmall.rems(cx))
7862 .child(h_flex().children(ui::render_modifiers(
7863 &accept_keystroke.modifiers,
7864 PlatformStyle::platform(),
7865 Some(modifiers_color),
7866 Some(IconSize::XSmall.rems().into()),
7867 true,
7868 )))
7869 .when(is_platform_style_mac, |parent| {
7870 parent.child(accept_keystroke.key.clone())
7871 })
7872 .when(!is_platform_style_mac, |parent| {
7873 parent.child(
7874 Key::new(
7875 util::capitalize(&accept_keystroke.key),
7876 Some(Color::Default),
7877 )
7878 .size(Some(IconSize::XSmall.rems().into())),
7879 )
7880 })
7881 .into_any()
7882 .into()
7883 }
7884
7885 fn render_edit_prediction_line_popover(
7886 &self,
7887 label: impl Into<SharedString>,
7888 icon: Option<IconName>,
7889 window: &mut Window,
7890 cx: &App,
7891 ) -> Option<Stateful<Div>> {
7892 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7893
7894 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7895 let has_keybind = keybind.is_some();
7896
7897 let result = h_flex()
7898 .id("ep-line-popover")
7899 .py_0p5()
7900 .pl_1()
7901 .pr(padding_right)
7902 .gap_1()
7903 .rounded_md()
7904 .border_1()
7905 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7906 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7907 .shadow_sm()
7908 .when(!has_keybind, |el| {
7909 let status_colors = cx.theme().status();
7910
7911 el.bg(status_colors.error_background)
7912 .border_color(status_colors.error.opacity(0.6))
7913 .pl_2()
7914 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7915 .cursor_default()
7916 .hoverable_tooltip(move |_window, cx| {
7917 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7918 })
7919 })
7920 .children(keybind)
7921 .child(
7922 Label::new(label)
7923 .size(LabelSize::Small)
7924 .when(!has_keybind, |el| {
7925 el.color(cx.theme().status().error.into()).strikethrough()
7926 }),
7927 )
7928 .when(!has_keybind, |el| {
7929 el.child(
7930 h_flex().ml_1().child(
7931 Icon::new(IconName::Info)
7932 .size(IconSize::Small)
7933 .color(cx.theme().status().error.into()),
7934 ),
7935 )
7936 })
7937 .when_some(icon, |element, icon| {
7938 element.child(
7939 div()
7940 .mt(px(1.5))
7941 .child(Icon::new(icon).size(IconSize::Small)),
7942 )
7943 });
7944
7945 Some(result)
7946 }
7947
7948 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7949 let accent_color = cx.theme().colors().text_accent;
7950 let editor_bg_color = cx.theme().colors().editor_background;
7951 editor_bg_color.blend(accent_color.opacity(0.1))
7952 }
7953
7954 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7955 let accent_color = cx.theme().colors().text_accent;
7956 let editor_bg_color = cx.theme().colors().editor_background;
7957 editor_bg_color.blend(accent_color.opacity(0.6))
7958 }
7959
7960 fn render_edit_prediction_cursor_popover(
7961 &self,
7962 min_width: Pixels,
7963 max_width: Pixels,
7964 cursor_point: Point,
7965 style: &EditorStyle,
7966 accept_keystroke: Option<&gpui::Keystroke>,
7967 _window: &Window,
7968 cx: &mut Context<Editor>,
7969 ) -> Option<AnyElement> {
7970 let provider = self.edit_prediction_provider.as_ref()?;
7971
7972 if provider.provider.needs_terms_acceptance(cx) {
7973 return Some(
7974 h_flex()
7975 .min_w(min_width)
7976 .flex_1()
7977 .px_2()
7978 .py_1()
7979 .gap_3()
7980 .elevation_2(cx)
7981 .hover(|style| style.bg(cx.theme().colors().element_hover))
7982 .id("accept-terms")
7983 .cursor_pointer()
7984 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7985 .on_click(cx.listener(|this, _event, window, cx| {
7986 cx.stop_propagation();
7987 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7988 window.dispatch_action(
7989 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7990 cx,
7991 );
7992 }))
7993 .child(
7994 h_flex()
7995 .flex_1()
7996 .gap_2()
7997 .child(Icon::new(IconName::ZedPredict))
7998 .child(Label::new("Accept Terms of Service"))
7999 .child(div().w_full())
8000 .child(
8001 Icon::new(IconName::ArrowUpRight)
8002 .color(Color::Muted)
8003 .size(IconSize::Small),
8004 )
8005 .into_any_element(),
8006 )
8007 .into_any(),
8008 );
8009 }
8010
8011 let is_refreshing = provider.provider.is_refreshing(cx);
8012
8013 fn pending_completion_container() -> Div {
8014 h_flex()
8015 .h_full()
8016 .flex_1()
8017 .gap_2()
8018 .child(Icon::new(IconName::ZedPredict))
8019 }
8020
8021 let completion = match &self.active_inline_completion {
8022 Some(prediction) => {
8023 if !self.has_visible_completions_menu() {
8024 const RADIUS: Pixels = px(6.);
8025 const BORDER_WIDTH: Pixels = px(1.);
8026
8027 return Some(
8028 h_flex()
8029 .elevation_2(cx)
8030 .border(BORDER_WIDTH)
8031 .border_color(cx.theme().colors().border)
8032 .when(accept_keystroke.is_none(), |el| {
8033 el.border_color(cx.theme().status().error)
8034 })
8035 .rounded(RADIUS)
8036 .rounded_tl(px(0.))
8037 .overflow_hidden()
8038 .child(div().px_1p5().child(match &prediction.completion {
8039 InlineCompletion::Move { target, snapshot } => {
8040 use text::ToPoint as _;
8041 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
8042 {
8043 Icon::new(IconName::ZedPredictDown)
8044 } else {
8045 Icon::new(IconName::ZedPredictUp)
8046 }
8047 }
8048 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
8049 }))
8050 .child(
8051 h_flex()
8052 .gap_1()
8053 .py_1()
8054 .px_2()
8055 .rounded_r(RADIUS - BORDER_WIDTH)
8056 .border_l_1()
8057 .border_color(cx.theme().colors().border)
8058 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8059 .when(self.edit_prediction_preview.released_too_fast(), |el| {
8060 el.child(
8061 Label::new("Hold")
8062 .size(LabelSize::Small)
8063 .when(accept_keystroke.is_none(), |el| {
8064 el.strikethrough()
8065 })
8066 .line_height_style(LineHeightStyle::UiLabel),
8067 )
8068 })
8069 .id("edit_prediction_cursor_popover_keybind")
8070 .when(accept_keystroke.is_none(), |el| {
8071 let status_colors = cx.theme().status();
8072
8073 el.bg(status_colors.error_background)
8074 .border_color(status_colors.error.opacity(0.6))
8075 .child(Icon::new(IconName::Info).color(Color::Error))
8076 .cursor_default()
8077 .hoverable_tooltip(move |_window, cx| {
8078 cx.new(|_| MissingEditPredictionKeybindingTooltip)
8079 .into()
8080 })
8081 })
8082 .when_some(
8083 accept_keystroke.as_ref(),
8084 |el, accept_keystroke| {
8085 el.child(h_flex().children(ui::render_modifiers(
8086 &accept_keystroke.modifiers,
8087 PlatformStyle::platform(),
8088 Some(Color::Default),
8089 Some(IconSize::XSmall.rems().into()),
8090 false,
8091 )))
8092 },
8093 ),
8094 )
8095 .into_any(),
8096 );
8097 }
8098
8099 self.render_edit_prediction_cursor_popover_preview(
8100 prediction,
8101 cursor_point,
8102 style,
8103 cx,
8104 )?
8105 }
8106
8107 None if is_refreshing => match &self.stale_inline_completion_in_menu {
8108 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
8109 stale_completion,
8110 cursor_point,
8111 style,
8112 cx,
8113 )?,
8114
8115 None => {
8116 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
8117 }
8118 },
8119
8120 None => pending_completion_container().child(Label::new("No Prediction")),
8121 };
8122
8123 let completion = if is_refreshing {
8124 completion
8125 .with_animation(
8126 "loading-completion",
8127 Animation::new(Duration::from_secs(2))
8128 .repeat()
8129 .with_easing(pulsating_between(0.4, 0.8)),
8130 |label, delta| label.opacity(delta),
8131 )
8132 .into_any_element()
8133 } else {
8134 completion.into_any_element()
8135 };
8136
8137 let has_completion = self.active_inline_completion.is_some();
8138
8139 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
8140 Some(
8141 h_flex()
8142 .min_w(min_width)
8143 .max_w(max_width)
8144 .flex_1()
8145 .elevation_2(cx)
8146 .border_color(cx.theme().colors().border)
8147 .child(
8148 div()
8149 .flex_1()
8150 .py_1()
8151 .px_2()
8152 .overflow_hidden()
8153 .child(completion),
8154 )
8155 .when_some(accept_keystroke, |el, accept_keystroke| {
8156 if !accept_keystroke.modifiers.modified() {
8157 return el;
8158 }
8159
8160 el.child(
8161 h_flex()
8162 .h_full()
8163 .border_l_1()
8164 .rounded_r_lg()
8165 .border_color(cx.theme().colors().border)
8166 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8167 .gap_1()
8168 .py_1()
8169 .px_2()
8170 .child(
8171 h_flex()
8172 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8173 .when(is_platform_style_mac, |parent| parent.gap_1())
8174 .child(h_flex().children(ui::render_modifiers(
8175 &accept_keystroke.modifiers,
8176 PlatformStyle::platform(),
8177 Some(if !has_completion {
8178 Color::Muted
8179 } else {
8180 Color::Default
8181 }),
8182 None,
8183 false,
8184 ))),
8185 )
8186 .child(Label::new("Preview").into_any_element())
8187 .opacity(if has_completion { 1.0 } else { 0.4 }),
8188 )
8189 })
8190 .into_any(),
8191 )
8192 }
8193
8194 fn render_edit_prediction_cursor_popover_preview(
8195 &self,
8196 completion: &InlineCompletionState,
8197 cursor_point: Point,
8198 style: &EditorStyle,
8199 cx: &mut Context<Editor>,
8200 ) -> Option<Div> {
8201 use text::ToPoint as _;
8202
8203 fn render_relative_row_jump(
8204 prefix: impl Into<String>,
8205 current_row: u32,
8206 target_row: u32,
8207 ) -> Div {
8208 let (row_diff, arrow) = if target_row < current_row {
8209 (current_row - target_row, IconName::ArrowUp)
8210 } else {
8211 (target_row - current_row, IconName::ArrowDown)
8212 };
8213
8214 h_flex()
8215 .child(
8216 Label::new(format!("{}{}", prefix.into(), row_diff))
8217 .color(Color::Muted)
8218 .size(LabelSize::Small),
8219 )
8220 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
8221 }
8222
8223 match &completion.completion {
8224 InlineCompletion::Move {
8225 target, snapshot, ..
8226 } => Some(
8227 h_flex()
8228 .px_2()
8229 .gap_2()
8230 .flex_1()
8231 .child(
8232 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
8233 Icon::new(IconName::ZedPredictDown)
8234 } else {
8235 Icon::new(IconName::ZedPredictUp)
8236 },
8237 )
8238 .child(Label::new("Jump to Edit")),
8239 ),
8240
8241 InlineCompletion::Edit {
8242 edits,
8243 edit_preview,
8244 snapshot,
8245 display_mode: _,
8246 } => {
8247 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
8248
8249 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
8250 &snapshot,
8251 &edits,
8252 edit_preview.as_ref()?,
8253 true,
8254 cx,
8255 )
8256 .first_line_preview();
8257
8258 let styled_text = gpui::StyledText::new(highlighted_edits.text)
8259 .with_default_highlights(&style.text, highlighted_edits.highlights);
8260
8261 let preview = h_flex()
8262 .gap_1()
8263 .min_w_16()
8264 .child(styled_text)
8265 .when(has_more_lines, |parent| parent.child("…"));
8266
8267 let left = if first_edit_row != cursor_point.row {
8268 render_relative_row_jump("", cursor_point.row, first_edit_row)
8269 .into_any_element()
8270 } else {
8271 Icon::new(IconName::ZedPredict).into_any_element()
8272 };
8273
8274 Some(
8275 h_flex()
8276 .h_full()
8277 .flex_1()
8278 .gap_2()
8279 .pr_1()
8280 .overflow_x_hidden()
8281 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8282 .child(left)
8283 .child(preview),
8284 )
8285 }
8286 }
8287 }
8288
8289 fn render_context_menu(
8290 &self,
8291 style: &EditorStyle,
8292 max_height_in_lines: u32,
8293 window: &mut Window,
8294 cx: &mut Context<Editor>,
8295 ) -> Option<AnyElement> {
8296 let menu = self.context_menu.borrow();
8297 let menu = menu.as_ref()?;
8298 if !menu.visible() {
8299 return None;
8300 };
8301 Some(menu.render(style, max_height_in_lines, window, cx))
8302 }
8303
8304 fn render_context_menu_aside(
8305 &mut self,
8306 max_size: Size<Pixels>,
8307 window: &mut Window,
8308 cx: &mut Context<Editor>,
8309 ) -> Option<AnyElement> {
8310 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
8311 if menu.visible() {
8312 menu.render_aside(self, max_size, window, cx)
8313 } else {
8314 None
8315 }
8316 })
8317 }
8318
8319 fn hide_context_menu(
8320 &mut self,
8321 window: &mut Window,
8322 cx: &mut Context<Self>,
8323 ) -> Option<CodeContextMenu> {
8324 cx.notify();
8325 self.completion_tasks.clear();
8326 let context_menu = self.context_menu.borrow_mut().take();
8327 self.stale_inline_completion_in_menu.take();
8328 self.update_visible_inline_completion(window, cx);
8329 context_menu
8330 }
8331
8332 fn show_snippet_choices(
8333 &mut self,
8334 choices: &Vec<String>,
8335 selection: Range<Anchor>,
8336 cx: &mut Context<Self>,
8337 ) {
8338 if selection.start.buffer_id.is_none() {
8339 return;
8340 }
8341 let buffer_id = selection.start.buffer_id.unwrap();
8342 let buffer = self.buffer().read(cx).buffer(buffer_id);
8343 let id = post_inc(&mut self.next_completion_id);
8344 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
8345
8346 if let Some(buffer) = buffer {
8347 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8348 CompletionsMenu::new_snippet_choices(
8349 id,
8350 true,
8351 choices,
8352 selection,
8353 buffer,
8354 snippet_sort_order,
8355 ),
8356 ));
8357 }
8358 }
8359
8360 pub fn insert_snippet(
8361 &mut self,
8362 insertion_ranges: &[Range<usize>],
8363 snippet: Snippet,
8364 window: &mut Window,
8365 cx: &mut Context<Self>,
8366 ) -> Result<()> {
8367 struct Tabstop<T> {
8368 is_end_tabstop: bool,
8369 ranges: Vec<Range<T>>,
8370 choices: Option<Vec<String>>,
8371 }
8372
8373 let tabstops = self.buffer.update(cx, |buffer, cx| {
8374 let snippet_text: Arc<str> = snippet.text.clone().into();
8375 let edits = insertion_ranges
8376 .iter()
8377 .cloned()
8378 .map(|range| (range, snippet_text.clone()));
8379 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8380
8381 let snapshot = &*buffer.read(cx);
8382 let snippet = &snippet;
8383 snippet
8384 .tabstops
8385 .iter()
8386 .map(|tabstop| {
8387 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8388 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8389 });
8390 let mut tabstop_ranges = tabstop
8391 .ranges
8392 .iter()
8393 .flat_map(|tabstop_range| {
8394 let mut delta = 0_isize;
8395 insertion_ranges.iter().map(move |insertion_range| {
8396 let insertion_start = insertion_range.start as isize + delta;
8397 delta +=
8398 snippet.text.len() as isize - insertion_range.len() as isize;
8399
8400 let start = ((insertion_start + tabstop_range.start) as usize)
8401 .min(snapshot.len());
8402 let end = ((insertion_start + tabstop_range.end) as usize)
8403 .min(snapshot.len());
8404 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8405 })
8406 })
8407 .collect::<Vec<_>>();
8408 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8409
8410 Tabstop {
8411 is_end_tabstop,
8412 ranges: tabstop_ranges,
8413 choices: tabstop.choices.clone(),
8414 }
8415 })
8416 .collect::<Vec<_>>()
8417 });
8418 if let Some(tabstop) = tabstops.first() {
8419 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8420 s.select_ranges(tabstop.ranges.iter().cloned());
8421 });
8422
8423 if let Some(choices) = &tabstop.choices {
8424 if let Some(selection) = tabstop.ranges.first() {
8425 self.show_snippet_choices(choices, selection.clone(), cx)
8426 }
8427 }
8428
8429 // If we're already at the last tabstop and it's at the end of the snippet,
8430 // we're done, we don't need to keep the state around.
8431 if !tabstop.is_end_tabstop {
8432 let choices = tabstops
8433 .iter()
8434 .map(|tabstop| tabstop.choices.clone())
8435 .collect();
8436
8437 let ranges = tabstops
8438 .into_iter()
8439 .map(|tabstop| tabstop.ranges)
8440 .collect::<Vec<_>>();
8441
8442 self.snippet_stack.push(SnippetState {
8443 active_index: 0,
8444 ranges,
8445 choices,
8446 });
8447 }
8448
8449 // Check whether the just-entered snippet ends with an auto-closable bracket.
8450 if self.autoclose_regions.is_empty() {
8451 let snapshot = self.buffer.read(cx).snapshot(cx);
8452 for selection in &mut self.selections.all::<Point>(cx) {
8453 let selection_head = selection.head();
8454 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8455 continue;
8456 };
8457
8458 let mut bracket_pair = None;
8459 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8460 let prev_chars = snapshot
8461 .reversed_chars_at(selection_head)
8462 .collect::<String>();
8463 for (pair, enabled) in scope.brackets() {
8464 if enabled
8465 && pair.close
8466 && prev_chars.starts_with(pair.start.as_str())
8467 && next_chars.starts_with(pair.end.as_str())
8468 {
8469 bracket_pair = Some(pair.clone());
8470 break;
8471 }
8472 }
8473 if let Some(pair) = bracket_pair {
8474 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8475 let autoclose_enabled =
8476 self.use_autoclose && snapshot_settings.use_autoclose;
8477 if autoclose_enabled {
8478 let start = snapshot.anchor_after(selection_head);
8479 let end = snapshot.anchor_after(selection_head);
8480 self.autoclose_regions.push(AutocloseRegion {
8481 selection_id: selection.id,
8482 range: start..end,
8483 pair,
8484 });
8485 }
8486 }
8487 }
8488 }
8489 }
8490 Ok(())
8491 }
8492
8493 pub fn move_to_next_snippet_tabstop(
8494 &mut self,
8495 window: &mut Window,
8496 cx: &mut Context<Self>,
8497 ) -> bool {
8498 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8499 }
8500
8501 pub fn move_to_prev_snippet_tabstop(
8502 &mut self,
8503 window: &mut Window,
8504 cx: &mut Context<Self>,
8505 ) -> bool {
8506 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8507 }
8508
8509 pub fn move_to_snippet_tabstop(
8510 &mut self,
8511 bias: Bias,
8512 window: &mut Window,
8513 cx: &mut Context<Self>,
8514 ) -> bool {
8515 if let Some(mut snippet) = self.snippet_stack.pop() {
8516 match bias {
8517 Bias::Left => {
8518 if snippet.active_index > 0 {
8519 snippet.active_index -= 1;
8520 } else {
8521 self.snippet_stack.push(snippet);
8522 return false;
8523 }
8524 }
8525 Bias::Right => {
8526 if snippet.active_index + 1 < snippet.ranges.len() {
8527 snippet.active_index += 1;
8528 } else {
8529 self.snippet_stack.push(snippet);
8530 return false;
8531 }
8532 }
8533 }
8534 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8535 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8536 s.select_anchor_ranges(current_ranges.iter().cloned())
8537 });
8538
8539 if let Some(choices) = &snippet.choices[snippet.active_index] {
8540 if let Some(selection) = current_ranges.first() {
8541 self.show_snippet_choices(&choices, selection.clone(), cx);
8542 }
8543 }
8544
8545 // If snippet state is not at the last tabstop, push it back on the stack
8546 if snippet.active_index + 1 < snippet.ranges.len() {
8547 self.snippet_stack.push(snippet);
8548 }
8549 return true;
8550 }
8551 }
8552
8553 false
8554 }
8555
8556 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8557 self.transact(window, cx, |this, window, cx| {
8558 this.select_all(&SelectAll, window, cx);
8559 this.insert("", window, cx);
8560 });
8561 }
8562
8563 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8564 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8565 self.transact(window, cx, |this, window, cx| {
8566 this.select_autoclose_pair(window, cx);
8567 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8568 if !this.linked_edit_ranges.is_empty() {
8569 let selections = this.selections.all::<MultiBufferPoint>(cx);
8570 let snapshot = this.buffer.read(cx).snapshot(cx);
8571
8572 for selection in selections.iter() {
8573 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8574 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8575 if selection_start.buffer_id != selection_end.buffer_id {
8576 continue;
8577 }
8578 if let Some(ranges) =
8579 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8580 {
8581 for (buffer, entries) in ranges {
8582 linked_ranges.entry(buffer).or_default().extend(entries);
8583 }
8584 }
8585 }
8586 }
8587
8588 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8589 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8590 for selection in &mut selections {
8591 if selection.is_empty() {
8592 let old_head = selection.head();
8593 let mut new_head =
8594 movement::left(&display_map, old_head.to_display_point(&display_map))
8595 .to_point(&display_map);
8596 if let Some((buffer, line_buffer_range)) = display_map
8597 .buffer_snapshot
8598 .buffer_line_for_row(MultiBufferRow(old_head.row))
8599 {
8600 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8601 let indent_len = match indent_size.kind {
8602 IndentKind::Space => {
8603 buffer.settings_at(line_buffer_range.start, cx).tab_size
8604 }
8605 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8606 };
8607 if old_head.column <= indent_size.len && old_head.column > 0 {
8608 let indent_len = indent_len.get();
8609 new_head = cmp::min(
8610 new_head,
8611 MultiBufferPoint::new(
8612 old_head.row,
8613 ((old_head.column - 1) / indent_len) * indent_len,
8614 ),
8615 );
8616 }
8617 }
8618
8619 selection.set_head(new_head, SelectionGoal::None);
8620 }
8621 }
8622
8623 this.signature_help_state.set_backspace_pressed(true);
8624 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8625 s.select(selections)
8626 });
8627 this.insert("", window, cx);
8628 let empty_str: Arc<str> = Arc::from("");
8629 for (buffer, edits) in linked_ranges {
8630 let snapshot = buffer.read(cx).snapshot();
8631 use text::ToPoint as TP;
8632
8633 let edits = edits
8634 .into_iter()
8635 .map(|range| {
8636 let end_point = TP::to_point(&range.end, &snapshot);
8637 let mut start_point = TP::to_point(&range.start, &snapshot);
8638
8639 if end_point == start_point {
8640 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8641 .saturating_sub(1);
8642 start_point =
8643 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8644 };
8645
8646 (start_point..end_point, empty_str.clone())
8647 })
8648 .sorted_by_key(|(range, _)| range.start)
8649 .collect::<Vec<_>>();
8650 buffer.update(cx, |this, cx| {
8651 this.edit(edits, None, cx);
8652 })
8653 }
8654 this.refresh_inline_completion(true, false, window, cx);
8655 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8656 });
8657 }
8658
8659 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8660 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8661 self.transact(window, cx, |this, window, cx| {
8662 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8663 s.move_with(|map, selection| {
8664 if selection.is_empty() {
8665 let cursor = movement::right(map, selection.head());
8666 selection.end = cursor;
8667 selection.reversed = true;
8668 selection.goal = SelectionGoal::None;
8669 }
8670 })
8671 });
8672 this.insert("", window, cx);
8673 this.refresh_inline_completion(true, false, window, cx);
8674 });
8675 }
8676
8677 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8678 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8679 if self.move_to_prev_snippet_tabstop(window, cx) {
8680 return;
8681 }
8682 self.outdent(&Outdent, window, cx);
8683 }
8684
8685 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8686 if self.move_to_next_snippet_tabstop(window, cx) {
8687 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8688 return;
8689 }
8690 if self.read_only(cx) {
8691 return;
8692 }
8693 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8694 let mut selections = self.selections.all_adjusted(cx);
8695 let buffer = self.buffer.read(cx);
8696 let snapshot = buffer.snapshot(cx);
8697 let rows_iter = selections.iter().map(|s| s.head().row);
8698 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8699
8700 let has_some_cursor_in_whitespace = selections
8701 .iter()
8702 .filter(|selection| selection.is_empty())
8703 .any(|selection| {
8704 let cursor = selection.head();
8705 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8706 cursor.column < current_indent.len
8707 });
8708
8709 let mut edits = Vec::new();
8710 let mut prev_edited_row = 0;
8711 let mut row_delta = 0;
8712 for selection in &mut selections {
8713 if selection.start.row != prev_edited_row {
8714 row_delta = 0;
8715 }
8716 prev_edited_row = selection.end.row;
8717
8718 // If the selection is non-empty, then increase the indentation of the selected lines.
8719 if !selection.is_empty() {
8720 row_delta =
8721 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8722 continue;
8723 }
8724
8725 // If the selection is empty and the cursor is in the leading whitespace before the
8726 // suggested indentation, then auto-indent the line.
8727 let cursor = selection.head();
8728 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8729 if let Some(suggested_indent) =
8730 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8731 {
8732 // If there exist any empty selection in the leading whitespace, then skip
8733 // indent for selections at the boundary.
8734 if has_some_cursor_in_whitespace
8735 && cursor.column == current_indent.len
8736 && current_indent.len == suggested_indent.len
8737 {
8738 continue;
8739 }
8740
8741 if cursor.column < suggested_indent.len
8742 && cursor.column <= current_indent.len
8743 && current_indent.len <= suggested_indent.len
8744 {
8745 selection.start = Point::new(cursor.row, suggested_indent.len);
8746 selection.end = selection.start;
8747 if row_delta == 0 {
8748 edits.extend(Buffer::edit_for_indent_size_adjustment(
8749 cursor.row,
8750 current_indent,
8751 suggested_indent,
8752 ));
8753 row_delta = suggested_indent.len - current_indent.len;
8754 }
8755 continue;
8756 }
8757 }
8758
8759 // Otherwise, insert a hard or soft tab.
8760 let settings = buffer.language_settings_at(cursor, cx);
8761 let tab_size = if settings.hard_tabs {
8762 IndentSize::tab()
8763 } else {
8764 let tab_size = settings.tab_size.get();
8765 let indent_remainder = snapshot
8766 .text_for_range(Point::new(cursor.row, 0)..cursor)
8767 .flat_map(str::chars)
8768 .fold(row_delta % tab_size, |counter: u32, c| {
8769 if c == '\t' {
8770 0
8771 } else {
8772 (counter + 1) % tab_size
8773 }
8774 });
8775
8776 let chars_to_next_tab_stop = tab_size - indent_remainder;
8777 IndentSize::spaces(chars_to_next_tab_stop)
8778 };
8779 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8780 selection.end = selection.start;
8781 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8782 row_delta += tab_size.len;
8783 }
8784
8785 self.transact(window, cx, |this, window, cx| {
8786 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8787 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8788 s.select(selections)
8789 });
8790 this.refresh_inline_completion(true, false, window, cx);
8791 });
8792 }
8793
8794 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8795 if self.read_only(cx) {
8796 return;
8797 }
8798 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8799 let mut selections = self.selections.all::<Point>(cx);
8800 let mut prev_edited_row = 0;
8801 let mut row_delta = 0;
8802 let mut edits = Vec::new();
8803 let buffer = self.buffer.read(cx);
8804 let snapshot = buffer.snapshot(cx);
8805 for selection in &mut selections {
8806 if selection.start.row != prev_edited_row {
8807 row_delta = 0;
8808 }
8809 prev_edited_row = selection.end.row;
8810
8811 row_delta =
8812 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8813 }
8814
8815 self.transact(window, cx, |this, window, cx| {
8816 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8817 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8818 s.select(selections)
8819 });
8820 });
8821 }
8822
8823 fn indent_selection(
8824 buffer: &MultiBuffer,
8825 snapshot: &MultiBufferSnapshot,
8826 selection: &mut Selection<Point>,
8827 edits: &mut Vec<(Range<Point>, String)>,
8828 delta_for_start_row: u32,
8829 cx: &App,
8830 ) -> u32 {
8831 let settings = buffer.language_settings_at(selection.start, cx);
8832 let tab_size = settings.tab_size.get();
8833 let indent_kind = if settings.hard_tabs {
8834 IndentKind::Tab
8835 } else {
8836 IndentKind::Space
8837 };
8838 let mut start_row = selection.start.row;
8839 let mut end_row = selection.end.row + 1;
8840
8841 // If a selection ends at the beginning of a line, don't indent
8842 // that last line.
8843 if selection.end.column == 0 && selection.end.row > selection.start.row {
8844 end_row -= 1;
8845 }
8846
8847 // Avoid re-indenting a row that has already been indented by a
8848 // previous selection, but still update this selection's column
8849 // to reflect that indentation.
8850 if delta_for_start_row > 0 {
8851 start_row += 1;
8852 selection.start.column += delta_for_start_row;
8853 if selection.end.row == selection.start.row {
8854 selection.end.column += delta_for_start_row;
8855 }
8856 }
8857
8858 let mut delta_for_end_row = 0;
8859 let has_multiple_rows = start_row + 1 != end_row;
8860 for row in start_row..end_row {
8861 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8862 let indent_delta = match (current_indent.kind, indent_kind) {
8863 (IndentKind::Space, IndentKind::Space) => {
8864 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8865 IndentSize::spaces(columns_to_next_tab_stop)
8866 }
8867 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8868 (_, IndentKind::Tab) => IndentSize::tab(),
8869 };
8870
8871 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8872 0
8873 } else {
8874 selection.start.column
8875 };
8876 let row_start = Point::new(row, start);
8877 edits.push((
8878 row_start..row_start,
8879 indent_delta.chars().collect::<String>(),
8880 ));
8881
8882 // Update this selection's endpoints to reflect the indentation.
8883 if row == selection.start.row {
8884 selection.start.column += indent_delta.len;
8885 }
8886 if row == selection.end.row {
8887 selection.end.column += indent_delta.len;
8888 delta_for_end_row = indent_delta.len;
8889 }
8890 }
8891
8892 if selection.start.row == selection.end.row {
8893 delta_for_start_row + delta_for_end_row
8894 } else {
8895 delta_for_end_row
8896 }
8897 }
8898
8899 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8900 if self.read_only(cx) {
8901 return;
8902 }
8903 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8904 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8905 let selections = self.selections.all::<Point>(cx);
8906 let mut deletion_ranges = Vec::new();
8907 let mut last_outdent = None;
8908 {
8909 let buffer = self.buffer.read(cx);
8910 let snapshot = buffer.snapshot(cx);
8911 for selection in &selections {
8912 let settings = buffer.language_settings_at(selection.start, cx);
8913 let tab_size = settings.tab_size.get();
8914 let mut rows = selection.spanned_rows(false, &display_map);
8915
8916 // Avoid re-outdenting a row that has already been outdented by a
8917 // previous selection.
8918 if let Some(last_row) = last_outdent {
8919 if last_row == rows.start {
8920 rows.start = rows.start.next_row();
8921 }
8922 }
8923 let has_multiple_rows = rows.len() > 1;
8924 for row in rows.iter_rows() {
8925 let indent_size = snapshot.indent_size_for_line(row);
8926 if indent_size.len > 0 {
8927 let deletion_len = match indent_size.kind {
8928 IndentKind::Space => {
8929 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8930 if columns_to_prev_tab_stop == 0 {
8931 tab_size
8932 } else {
8933 columns_to_prev_tab_stop
8934 }
8935 }
8936 IndentKind::Tab => 1,
8937 };
8938 let start = if has_multiple_rows
8939 || deletion_len > selection.start.column
8940 || indent_size.len < selection.start.column
8941 {
8942 0
8943 } else {
8944 selection.start.column - deletion_len
8945 };
8946 deletion_ranges.push(
8947 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8948 );
8949 last_outdent = Some(row);
8950 }
8951 }
8952 }
8953 }
8954
8955 self.transact(window, cx, |this, window, cx| {
8956 this.buffer.update(cx, |buffer, cx| {
8957 let empty_str: Arc<str> = Arc::default();
8958 buffer.edit(
8959 deletion_ranges
8960 .into_iter()
8961 .map(|range| (range, empty_str.clone())),
8962 None,
8963 cx,
8964 );
8965 });
8966 let selections = this.selections.all::<usize>(cx);
8967 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8968 s.select(selections)
8969 });
8970 });
8971 }
8972
8973 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8974 if self.read_only(cx) {
8975 return;
8976 }
8977 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8978 let selections = self
8979 .selections
8980 .all::<usize>(cx)
8981 .into_iter()
8982 .map(|s| s.range());
8983
8984 self.transact(window, cx, |this, window, cx| {
8985 this.buffer.update(cx, |buffer, cx| {
8986 buffer.autoindent_ranges(selections, cx);
8987 });
8988 let selections = this.selections.all::<usize>(cx);
8989 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8990 s.select(selections)
8991 });
8992 });
8993 }
8994
8995 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8996 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8997 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8998 let selections = self.selections.all::<Point>(cx);
8999
9000 let mut new_cursors = Vec::new();
9001 let mut edit_ranges = Vec::new();
9002 let mut selections = selections.iter().peekable();
9003 while let Some(selection) = selections.next() {
9004 let mut rows = selection.spanned_rows(false, &display_map);
9005 let goal_display_column = selection.head().to_display_point(&display_map).column();
9006
9007 // Accumulate contiguous regions of rows that we want to delete.
9008 while let Some(next_selection) = selections.peek() {
9009 let next_rows = next_selection.spanned_rows(false, &display_map);
9010 if next_rows.start <= rows.end {
9011 rows.end = next_rows.end;
9012 selections.next().unwrap();
9013 } else {
9014 break;
9015 }
9016 }
9017
9018 let buffer = &display_map.buffer_snapshot;
9019 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
9020 let edit_end;
9021 let cursor_buffer_row;
9022 if buffer.max_point().row >= rows.end.0 {
9023 // If there's a line after the range, delete the \n from the end of the row range
9024 // and position the cursor on the next line.
9025 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
9026 cursor_buffer_row = rows.end;
9027 } else {
9028 // If there isn't a line after the range, delete the \n from the line before the
9029 // start of the row range and position the cursor there.
9030 edit_start = edit_start.saturating_sub(1);
9031 edit_end = buffer.len();
9032 cursor_buffer_row = rows.start.previous_row();
9033 }
9034
9035 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
9036 *cursor.column_mut() =
9037 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
9038
9039 new_cursors.push((
9040 selection.id,
9041 buffer.anchor_after(cursor.to_point(&display_map)),
9042 ));
9043 edit_ranges.push(edit_start..edit_end);
9044 }
9045
9046 self.transact(window, cx, |this, window, cx| {
9047 let buffer = this.buffer.update(cx, |buffer, cx| {
9048 let empty_str: Arc<str> = Arc::default();
9049 buffer.edit(
9050 edit_ranges
9051 .into_iter()
9052 .map(|range| (range, empty_str.clone())),
9053 None,
9054 cx,
9055 );
9056 buffer.snapshot(cx)
9057 });
9058 let new_selections = new_cursors
9059 .into_iter()
9060 .map(|(id, cursor)| {
9061 let cursor = cursor.to_point(&buffer);
9062 Selection {
9063 id,
9064 start: cursor,
9065 end: cursor,
9066 reversed: false,
9067 goal: SelectionGoal::None,
9068 }
9069 })
9070 .collect();
9071
9072 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9073 s.select(new_selections);
9074 });
9075 });
9076 }
9077
9078 pub fn join_lines_impl(
9079 &mut self,
9080 insert_whitespace: bool,
9081 window: &mut Window,
9082 cx: &mut Context<Self>,
9083 ) {
9084 if self.read_only(cx) {
9085 return;
9086 }
9087 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
9088 for selection in self.selections.all::<Point>(cx) {
9089 let start = MultiBufferRow(selection.start.row);
9090 // Treat single line selections as if they include the next line. Otherwise this action
9091 // would do nothing for single line selections individual cursors.
9092 let end = if selection.start.row == selection.end.row {
9093 MultiBufferRow(selection.start.row + 1)
9094 } else {
9095 MultiBufferRow(selection.end.row)
9096 };
9097
9098 if let Some(last_row_range) = row_ranges.last_mut() {
9099 if start <= last_row_range.end {
9100 last_row_range.end = end;
9101 continue;
9102 }
9103 }
9104 row_ranges.push(start..end);
9105 }
9106
9107 let snapshot = self.buffer.read(cx).snapshot(cx);
9108 let mut cursor_positions = Vec::new();
9109 for row_range in &row_ranges {
9110 let anchor = snapshot.anchor_before(Point::new(
9111 row_range.end.previous_row().0,
9112 snapshot.line_len(row_range.end.previous_row()),
9113 ));
9114 cursor_positions.push(anchor..anchor);
9115 }
9116
9117 self.transact(window, cx, |this, window, cx| {
9118 for row_range in row_ranges.into_iter().rev() {
9119 for row in row_range.iter_rows().rev() {
9120 let end_of_line = Point::new(row.0, snapshot.line_len(row));
9121 let next_line_row = row.next_row();
9122 let indent = snapshot.indent_size_for_line(next_line_row);
9123 let start_of_next_line = Point::new(next_line_row.0, indent.len);
9124
9125 let replace =
9126 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
9127 " "
9128 } else {
9129 ""
9130 };
9131
9132 this.buffer.update(cx, |buffer, cx| {
9133 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
9134 });
9135 }
9136 }
9137
9138 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9139 s.select_anchor_ranges(cursor_positions)
9140 });
9141 });
9142 }
9143
9144 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
9145 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9146 self.join_lines_impl(true, window, cx);
9147 }
9148
9149 pub fn sort_lines_case_sensitive(
9150 &mut self,
9151 _: &SortLinesCaseSensitive,
9152 window: &mut Window,
9153 cx: &mut Context<Self>,
9154 ) {
9155 self.manipulate_lines(window, cx, |lines| lines.sort())
9156 }
9157
9158 pub fn sort_lines_case_insensitive(
9159 &mut self,
9160 _: &SortLinesCaseInsensitive,
9161 window: &mut Window,
9162 cx: &mut Context<Self>,
9163 ) {
9164 self.manipulate_lines(window, cx, |lines| {
9165 lines.sort_by_key(|line| line.to_lowercase())
9166 })
9167 }
9168
9169 pub fn unique_lines_case_insensitive(
9170 &mut self,
9171 _: &UniqueLinesCaseInsensitive,
9172 window: &mut Window,
9173 cx: &mut Context<Self>,
9174 ) {
9175 self.manipulate_lines(window, cx, |lines| {
9176 let mut seen = HashSet::default();
9177 lines.retain(|line| seen.insert(line.to_lowercase()));
9178 })
9179 }
9180
9181 pub fn unique_lines_case_sensitive(
9182 &mut self,
9183 _: &UniqueLinesCaseSensitive,
9184 window: &mut Window,
9185 cx: &mut Context<Self>,
9186 ) {
9187 self.manipulate_lines(window, cx, |lines| {
9188 let mut seen = HashSet::default();
9189 lines.retain(|line| seen.insert(*line));
9190 })
9191 }
9192
9193 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
9194 let Some(project) = self.project.clone() else {
9195 return;
9196 };
9197 self.reload(project, window, cx)
9198 .detach_and_notify_err(window, cx);
9199 }
9200
9201 pub fn restore_file(
9202 &mut self,
9203 _: &::git::RestoreFile,
9204 window: &mut Window,
9205 cx: &mut Context<Self>,
9206 ) {
9207 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9208 let mut buffer_ids = HashSet::default();
9209 let snapshot = self.buffer().read(cx).snapshot(cx);
9210 for selection in self.selections.all::<usize>(cx) {
9211 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
9212 }
9213
9214 let buffer = self.buffer().read(cx);
9215 let ranges = buffer_ids
9216 .into_iter()
9217 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
9218 .collect::<Vec<_>>();
9219
9220 self.restore_hunks_in_ranges(ranges, window, cx);
9221 }
9222
9223 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
9224 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9225 let selections = self
9226 .selections
9227 .all(cx)
9228 .into_iter()
9229 .map(|s| s.range())
9230 .collect();
9231 self.restore_hunks_in_ranges(selections, window, cx);
9232 }
9233
9234 pub fn restore_hunks_in_ranges(
9235 &mut self,
9236 ranges: Vec<Range<Point>>,
9237 window: &mut Window,
9238 cx: &mut Context<Editor>,
9239 ) {
9240 let mut revert_changes = HashMap::default();
9241 let chunk_by = self
9242 .snapshot(window, cx)
9243 .hunks_for_ranges(ranges)
9244 .into_iter()
9245 .chunk_by(|hunk| hunk.buffer_id);
9246 for (buffer_id, hunks) in &chunk_by {
9247 let hunks = hunks.collect::<Vec<_>>();
9248 for hunk in &hunks {
9249 self.prepare_restore_change(&mut revert_changes, hunk, cx);
9250 }
9251 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
9252 }
9253 drop(chunk_by);
9254 if !revert_changes.is_empty() {
9255 self.transact(window, cx, |editor, window, cx| {
9256 editor.restore(revert_changes, window, cx);
9257 });
9258 }
9259 }
9260
9261 pub fn open_active_item_in_terminal(
9262 &mut self,
9263 _: &OpenInTerminal,
9264 window: &mut Window,
9265 cx: &mut Context<Self>,
9266 ) {
9267 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
9268 let project_path = buffer.read(cx).project_path(cx)?;
9269 let project = self.project.as_ref()?.read(cx);
9270 let entry = project.entry_for_path(&project_path, cx)?;
9271 let parent = match &entry.canonical_path {
9272 Some(canonical_path) => canonical_path.to_path_buf(),
9273 None => project.absolute_path(&project_path, cx)?,
9274 }
9275 .parent()?
9276 .to_path_buf();
9277 Some(parent)
9278 }) {
9279 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
9280 }
9281 }
9282
9283 fn set_breakpoint_context_menu(
9284 &mut self,
9285 display_row: DisplayRow,
9286 position: Option<Anchor>,
9287 clicked_point: gpui::Point<Pixels>,
9288 window: &mut Window,
9289 cx: &mut Context<Self>,
9290 ) {
9291 if !cx.has_flag::<DebuggerFeatureFlag>() {
9292 return;
9293 }
9294 let source = self
9295 .buffer
9296 .read(cx)
9297 .snapshot(cx)
9298 .anchor_before(Point::new(display_row.0, 0u32));
9299
9300 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
9301
9302 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
9303 self,
9304 source,
9305 clicked_point,
9306 context_menu,
9307 window,
9308 cx,
9309 );
9310 }
9311
9312 fn add_edit_breakpoint_block(
9313 &mut self,
9314 anchor: Anchor,
9315 breakpoint: &Breakpoint,
9316 edit_action: BreakpointPromptEditAction,
9317 window: &mut Window,
9318 cx: &mut Context<Self>,
9319 ) {
9320 let weak_editor = cx.weak_entity();
9321 let bp_prompt = cx.new(|cx| {
9322 BreakpointPromptEditor::new(
9323 weak_editor,
9324 anchor,
9325 breakpoint.clone(),
9326 edit_action,
9327 window,
9328 cx,
9329 )
9330 });
9331
9332 let height = bp_prompt.update(cx, |this, cx| {
9333 this.prompt
9334 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
9335 });
9336 let cloned_prompt = bp_prompt.clone();
9337 let blocks = vec![BlockProperties {
9338 style: BlockStyle::Sticky,
9339 placement: BlockPlacement::Above(anchor),
9340 height: Some(height),
9341 render: Arc::new(move |cx| {
9342 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
9343 cloned_prompt.clone().into_any_element()
9344 }),
9345 priority: 0,
9346 }];
9347
9348 let focus_handle = bp_prompt.focus_handle(cx);
9349 window.focus(&focus_handle);
9350
9351 let block_ids = self.insert_blocks(blocks, None, cx);
9352 bp_prompt.update(cx, |prompt, _| {
9353 prompt.add_block_ids(block_ids);
9354 });
9355 }
9356
9357 pub(crate) fn breakpoint_at_row(
9358 &self,
9359 row: u32,
9360 window: &mut Window,
9361 cx: &mut Context<Self>,
9362 ) -> Option<(Anchor, Breakpoint)> {
9363 let snapshot = self.snapshot(window, cx);
9364 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9365
9366 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9367 }
9368
9369 pub(crate) fn breakpoint_at_anchor(
9370 &self,
9371 breakpoint_position: Anchor,
9372 snapshot: &EditorSnapshot,
9373 cx: &mut Context<Self>,
9374 ) -> Option<(Anchor, Breakpoint)> {
9375 let project = self.project.clone()?;
9376
9377 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9378 snapshot
9379 .buffer_snapshot
9380 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9381 })?;
9382
9383 let enclosing_excerpt = breakpoint_position.excerpt_id;
9384 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9385 let buffer_snapshot = buffer.read(cx).snapshot();
9386
9387 let row = buffer_snapshot
9388 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9389 .row;
9390
9391 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9392 let anchor_end = snapshot
9393 .buffer_snapshot
9394 .anchor_after(Point::new(row, line_len));
9395
9396 let bp = self
9397 .breakpoint_store
9398 .as_ref()?
9399 .read_with(cx, |breakpoint_store, cx| {
9400 breakpoint_store
9401 .breakpoints(
9402 &buffer,
9403 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9404 &buffer_snapshot,
9405 cx,
9406 )
9407 .next()
9408 .and_then(|(anchor, bp)| {
9409 let breakpoint_row = buffer_snapshot
9410 .summary_for_anchor::<text::PointUtf16>(anchor)
9411 .row;
9412
9413 if breakpoint_row == row {
9414 snapshot
9415 .buffer_snapshot
9416 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9417 .map(|anchor| (anchor, bp.clone()))
9418 } else {
9419 None
9420 }
9421 })
9422 });
9423 bp
9424 }
9425
9426 pub fn edit_log_breakpoint(
9427 &mut self,
9428 _: &EditLogBreakpoint,
9429 window: &mut Window,
9430 cx: &mut Context<Self>,
9431 ) {
9432 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9433 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9434 message: None,
9435 state: BreakpointState::Enabled,
9436 condition: None,
9437 hit_condition: None,
9438 });
9439
9440 self.add_edit_breakpoint_block(
9441 anchor,
9442 &breakpoint,
9443 BreakpointPromptEditAction::Log,
9444 window,
9445 cx,
9446 );
9447 }
9448 }
9449
9450 fn breakpoints_at_cursors(
9451 &self,
9452 window: &mut Window,
9453 cx: &mut Context<Self>,
9454 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9455 let snapshot = self.snapshot(window, cx);
9456 let cursors = self
9457 .selections
9458 .disjoint_anchors()
9459 .into_iter()
9460 .map(|selection| {
9461 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9462
9463 let breakpoint_position = self
9464 .breakpoint_at_row(cursor_position.row, window, cx)
9465 .map(|bp| bp.0)
9466 .unwrap_or_else(|| {
9467 snapshot
9468 .display_snapshot
9469 .buffer_snapshot
9470 .anchor_after(Point::new(cursor_position.row, 0))
9471 });
9472
9473 let breakpoint = self
9474 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9475 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9476
9477 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9478 })
9479 // 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.
9480 .collect::<HashMap<Anchor, _>>();
9481
9482 cursors.into_iter().collect()
9483 }
9484
9485 pub fn enable_breakpoint(
9486 &mut self,
9487 _: &crate::actions::EnableBreakpoint,
9488 window: &mut Window,
9489 cx: &mut Context<Self>,
9490 ) {
9491 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9492 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9493 continue;
9494 };
9495 self.edit_breakpoint_at_anchor(
9496 anchor,
9497 breakpoint,
9498 BreakpointEditAction::InvertState,
9499 cx,
9500 );
9501 }
9502 }
9503
9504 pub fn disable_breakpoint(
9505 &mut self,
9506 _: &crate::actions::DisableBreakpoint,
9507 window: &mut Window,
9508 cx: &mut Context<Self>,
9509 ) {
9510 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9511 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9512 continue;
9513 };
9514 self.edit_breakpoint_at_anchor(
9515 anchor,
9516 breakpoint,
9517 BreakpointEditAction::InvertState,
9518 cx,
9519 );
9520 }
9521 }
9522
9523 pub fn toggle_breakpoint(
9524 &mut self,
9525 _: &crate::actions::ToggleBreakpoint,
9526 window: &mut Window,
9527 cx: &mut Context<Self>,
9528 ) {
9529 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9530 if let Some(breakpoint) = breakpoint {
9531 self.edit_breakpoint_at_anchor(
9532 anchor,
9533 breakpoint,
9534 BreakpointEditAction::Toggle,
9535 cx,
9536 );
9537 } else {
9538 self.edit_breakpoint_at_anchor(
9539 anchor,
9540 Breakpoint::new_standard(),
9541 BreakpointEditAction::Toggle,
9542 cx,
9543 );
9544 }
9545 }
9546 }
9547
9548 pub fn edit_breakpoint_at_anchor(
9549 &mut self,
9550 breakpoint_position: Anchor,
9551 breakpoint: Breakpoint,
9552 edit_action: BreakpointEditAction,
9553 cx: &mut Context<Self>,
9554 ) {
9555 let Some(breakpoint_store) = &self.breakpoint_store else {
9556 return;
9557 };
9558
9559 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9560 if breakpoint_position == Anchor::min() {
9561 self.buffer()
9562 .read(cx)
9563 .excerpt_buffer_ids()
9564 .into_iter()
9565 .next()
9566 } else {
9567 None
9568 }
9569 }) else {
9570 return;
9571 };
9572
9573 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9574 return;
9575 };
9576
9577 breakpoint_store.update(cx, |breakpoint_store, cx| {
9578 breakpoint_store.toggle_breakpoint(
9579 buffer,
9580 (breakpoint_position.text_anchor, breakpoint),
9581 edit_action,
9582 cx,
9583 );
9584 });
9585
9586 cx.notify();
9587 }
9588
9589 #[cfg(any(test, feature = "test-support"))]
9590 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9591 self.breakpoint_store.clone()
9592 }
9593
9594 pub fn prepare_restore_change(
9595 &self,
9596 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9597 hunk: &MultiBufferDiffHunk,
9598 cx: &mut App,
9599 ) -> Option<()> {
9600 if hunk.is_created_file() {
9601 return None;
9602 }
9603 let buffer = self.buffer.read(cx);
9604 let diff = buffer.diff_for(hunk.buffer_id)?;
9605 let buffer = buffer.buffer(hunk.buffer_id)?;
9606 let buffer = buffer.read(cx);
9607 let original_text = diff
9608 .read(cx)
9609 .base_text()
9610 .as_rope()
9611 .slice(hunk.diff_base_byte_range.clone());
9612 let buffer_snapshot = buffer.snapshot();
9613 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9614 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9615 probe
9616 .0
9617 .start
9618 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9619 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9620 }) {
9621 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9622 Some(())
9623 } else {
9624 None
9625 }
9626 }
9627
9628 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9629 self.manipulate_lines(window, cx, |lines| lines.reverse())
9630 }
9631
9632 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9633 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9634 }
9635
9636 fn manipulate_lines<Fn>(
9637 &mut self,
9638 window: &mut Window,
9639 cx: &mut Context<Self>,
9640 mut callback: Fn,
9641 ) where
9642 Fn: FnMut(&mut Vec<&str>),
9643 {
9644 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9645
9646 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9647 let buffer = self.buffer.read(cx).snapshot(cx);
9648
9649 let mut edits = Vec::new();
9650
9651 let selections = self.selections.all::<Point>(cx);
9652 let mut selections = selections.iter().peekable();
9653 let mut contiguous_row_selections = Vec::new();
9654 let mut new_selections = Vec::new();
9655 let mut added_lines = 0;
9656 let mut removed_lines = 0;
9657
9658 while let Some(selection) = selections.next() {
9659 let (start_row, end_row) = consume_contiguous_rows(
9660 &mut contiguous_row_selections,
9661 selection,
9662 &display_map,
9663 &mut selections,
9664 );
9665
9666 let start_point = Point::new(start_row.0, 0);
9667 let end_point = Point::new(
9668 end_row.previous_row().0,
9669 buffer.line_len(end_row.previous_row()),
9670 );
9671 let text = buffer
9672 .text_for_range(start_point..end_point)
9673 .collect::<String>();
9674
9675 let mut lines = text.split('\n').collect_vec();
9676
9677 let lines_before = lines.len();
9678 callback(&mut lines);
9679 let lines_after = lines.len();
9680
9681 edits.push((start_point..end_point, lines.join("\n")));
9682
9683 // Selections must change based on added and removed line count
9684 let start_row =
9685 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9686 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9687 new_selections.push(Selection {
9688 id: selection.id,
9689 start: start_row,
9690 end: end_row,
9691 goal: SelectionGoal::None,
9692 reversed: selection.reversed,
9693 });
9694
9695 if lines_after > lines_before {
9696 added_lines += lines_after - lines_before;
9697 } else if lines_before > lines_after {
9698 removed_lines += lines_before - lines_after;
9699 }
9700 }
9701
9702 self.transact(window, cx, |this, window, cx| {
9703 let buffer = this.buffer.update(cx, |buffer, cx| {
9704 buffer.edit(edits, None, cx);
9705 buffer.snapshot(cx)
9706 });
9707
9708 // Recalculate offsets on newly edited buffer
9709 let new_selections = new_selections
9710 .iter()
9711 .map(|s| {
9712 let start_point = Point::new(s.start.0, 0);
9713 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9714 Selection {
9715 id: s.id,
9716 start: buffer.point_to_offset(start_point),
9717 end: buffer.point_to_offset(end_point),
9718 goal: s.goal,
9719 reversed: s.reversed,
9720 }
9721 })
9722 .collect();
9723
9724 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9725 s.select(new_selections);
9726 });
9727
9728 this.request_autoscroll(Autoscroll::fit(), cx);
9729 });
9730 }
9731
9732 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9733 self.manipulate_text(window, cx, |text| {
9734 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9735 if has_upper_case_characters {
9736 text.to_lowercase()
9737 } else {
9738 text.to_uppercase()
9739 }
9740 })
9741 }
9742
9743 pub fn convert_to_upper_case(
9744 &mut self,
9745 _: &ConvertToUpperCase,
9746 window: &mut Window,
9747 cx: &mut Context<Self>,
9748 ) {
9749 self.manipulate_text(window, cx, |text| text.to_uppercase())
9750 }
9751
9752 pub fn convert_to_lower_case(
9753 &mut self,
9754 _: &ConvertToLowerCase,
9755 window: &mut Window,
9756 cx: &mut Context<Self>,
9757 ) {
9758 self.manipulate_text(window, cx, |text| text.to_lowercase())
9759 }
9760
9761 pub fn convert_to_title_case(
9762 &mut self,
9763 _: &ConvertToTitleCase,
9764 window: &mut Window,
9765 cx: &mut Context<Self>,
9766 ) {
9767 self.manipulate_text(window, cx, |text| {
9768 text.split('\n')
9769 .map(|line| line.to_case(Case::Title))
9770 .join("\n")
9771 })
9772 }
9773
9774 pub fn convert_to_snake_case(
9775 &mut self,
9776 _: &ConvertToSnakeCase,
9777 window: &mut Window,
9778 cx: &mut Context<Self>,
9779 ) {
9780 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9781 }
9782
9783 pub fn convert_to_kebab_case(
9784 &mut self,
9785 _: &ConvertToKebabCase,
9786 window: &mut Window,
9787 cx: &mut Context<Self>,
9788 ) {
9789 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9790 }
9791
9792 pub fn convert_to_upper_camel_case(
9793 &mut self,
9794 _: &ConvertToUpperCamelCase,
9795 window: &mut Window,
9796 cx: &mut Context<Self>,
9797 ) {
9798 self.manipulate_text(window, cx, |text| {
9799 text.split('\n')
9800 .map(|line| line.to_case(Case::UpperCamel))
9801 .join("\n")
9802 })
9803 }
9804
9805 pub fn convert_to_lower_camel_case(
9806 &mut self,
9807 _: &ConvertToLowerCamelCase,
9808 window: &mut Window,
9809 cx: &mut Context<Self>,
9810 ) {
9811 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9812 }
9813
9814 pub fn convert_to_opposite_case(
9815 &mut self,
9816 _: &ConvertToOppositeCase,
9817 window: &mut Window,
9818 cx: &mut Context<Self>,
9819 ) {
9820 self.manipulate_text(window, cx, |text| {
9821 text.chars()
9822 .fold(String::with_capacity(text.len()), |mut t, c| {
9823 if c.is_uppercase() {
9824 t.extend(c.to_lowercase());
9825 } else {
9826 t.extend(c.to_uppercase());
9827 }
9828 t
9829 })
9830 })
9831 }
9832
9833 pub fn convert_to_rot13(
9834 &mut self,
9835 _: &ConvertToRot13,
9836 window: &mut Window,
9837 cx: &mut Context<Self>,
9838 ) {
9839 self.manipulate_text(window, cx, |text| {
9840 text.chars()
9841 .map(|c| match c {
9842 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9843 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9844 _ => c,
9845 })
9846 .collect()
9847 })
9848 }
9849
9850 pub fn convert_to_rot47(
9851 &mut self,
9852 _: &ConvertToRot47,
9853 window: &mut Window,
9854 cx: &mut Context<Self>,
9855 ) {
9856 self.manipulate_text(window, cx, |text| {
9857 text.chars()
9858 .map(|c| {
9859 let code_point = c as u32;
9860 if code_point >= 33 && code_point <= 126 {
9861 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9862 }
9863 c
9864 })
9865 .collect()
9866 })
9867 }
9868
9869 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9870 where
9871 Fn: FnMut(&str) -> String,
9872 {
9873 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9874 let buffer = self.buffer.read(cx).snapshot(cx);
9875
9876 let mut new_selections = Vec::new();
9877 let mut edits = Vec::new();
9878 let mut selection_adjustment = 0i32;
9879
9880 for selection in self.selections.all::<usize>(cx) {
9881 let selection_is_empty = selection.is_empty();
9882
9883 let (start, end) = if selection_is_empty {
9884 let word_range = movement::surrounding_word(
9885 &display_map,
9886 selection.start.to_display_point(&display_map),
9887 );
9888 let start = word_range.start.to_offset(&display_map, Bias::Left);
9889 let end = word_range.end.to_offset(&display_map, Bias::Left);
9890 (start, end)
9891 } else {
9892 (selection.start, selection.end)
9893 };
9894
9895 let text = buffer.text_for_range(start..end).collect::<String>();
9896 let old_length = text.len() as i32;
9897 let text = callback(&text);
9898
9899 new_selections.push(Selection {
9900 start: (start as i32 - selection_adjustment) as usize,
9901 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9902 goal: SelectionGoal::None,
9903 ..selection
9904 });
9905
9906 selection_adjustment += old_length - text.len() as i32;
9907
9908 edits.push((start..end, text));
9909 }
9910
9911 self.transact(window, cx, |this, window, cx| {
9912 this.buffer.update(cx, |buffer, cx| {
9913 buffer.edit(edits, None, cx);
9914 });
9915
9916 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9917 s.select(new_selections);
9918 });
9919
9920 this.request_autoscroll(Autoscroll::fit(), cx);
9921 });
9922 }
9923
9924 pub fn duplicate(
9925 &mut self,
9926 upwards: bool,
9927 whole_lines: bool,
9928 window: &mut Window,
9929 cx: &mut Context<Self>,
9930 ) {
9931 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9932
9933 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9934 let buffer = &display_map.buffer_snapshot;
9935 let selections = self.selections.all::<Point>(cx);
9936
9937 let mut edits = Vec::new();
9938 let mut selections_iter = selections.iter().peekable();
9939 while let Some(selection) = selections_iter.next() {
9940 let mut rows = selection.spanned_rows(false, &display_map);
9941 // duplicate line-wise
9942 if whole_lines || selection.start == selection.end {
9943 // Avoid duplicating the same lines twice.
9944 while let Some(next_selection) = selections_iter.peek() {
9945 let next_rows = next_selection.spanned_rows(false, &display_map);
9946 if next_rows.start < rows.end {
9947 rows.end = next_rows.end;
9948 selections_iter.next().unwrap();
9949 } else {
9950 break;
9951 }
9952 }
9953
9954 // Copy the text from the selected row region and splice it either at the start
9955 // or end of the region.
9956 let start = Point::new(rows.start.0, 0);
9957 let end = Point::new(
9958 rows.end.previous_row().0,
9959 buffer.line_len(rows.end.previous_row()),
9960 );
9961 let text = buffer
9962 .text_for_range(start..end)
9963 .chain(Some("\n"))
9964 .collect::<String>();
9965 let insert_location = if upwards {
9966 Point::new(rows.end.0, 0)
9967 } else {
9968 start
9969 };
9970 edits.push((insert_location..insert_location, text));
9971 } else {
9972 // duplicate character-wise
9973 let start = selection.start;
9974 let end = selection.end;
9975 let text = buffer.text_for_range(start..end).collect::<String>();
9976 edits.push((selection.end..selection.end, text));
9977 }
9978 }
9979
9980 self.transact(window, cx, |this, _, cx| {
9981 this.buffer.update(cx, |buffer, cx| {
9982 buffer.edit(edits, None, cx);
9983 });
9984
9985 this.request_autoscroll(Autoscroll::fit(), cx);
9986 });
9987 }
9988
9989 pub fn duplicate_line_up(
9990 &mut self,
9991 _: &DuplicateLineUp,
9992 window: &mut Window,
9993 cx: &mut Context<Self>,
9994 ) {
9995 self.duplicate(true, true, window, cx);
9996 }
9997
9998 pub fn duplicate_line_down(
9999 &mut self,
10000 _: &DuplicateLineDown,
10001 window: &mut Window,
10002 cx: &mut Context<Self>,
10003 ) {
10004 self.duplicate(false, true, window, cx);
10005 }
10006
10007 pub fn duplicate_selection(
10008 &mut self,
10009 _: &DuplicateSelection,
10010 window: &mut Window,
10011 cx: &mut Context<Self>,
10012 ) {
10013 self.duplicate(false, false, window, cx);
10014 }
10015
10016 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10017 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10018
10019 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10020 let buffer = self.buffer.read(cx).snapshot(cx);
10021
10022 let mut edits = Vec::new();
10023 let mut unfold_ranges = Vec::new();
10024 let mut refold_creases = Vec::new();
10025
10026 let selections = self.selections.all::<Point>(cx);
10027 let mut selections = selections.iter().peekable();
10028 let mut contiguous_row_selections = Vec::new();
10029 let mut new_selections = Vec::new();
10030
10031 while let Some(selection) = selections.next() {
10032 // Find all the selections that span a contiguous row range
10033 let (start_row, end_row) = consume_contiguous_rows(
10034 &mut contiguous_row_selections,
10035 selection,
10036 &display_map,
10037 &mut selections,
10038 );
10039
10040 // Move the text spanned by the row range to be before the line preceding the row range
10041 if start_row.0 > 0 {
10042 let range_to_move = Point::new(
10043 start_row.previous_row().0,
10044 buffer.line_len(start_row.previous_row()),
10045 )
10046 ..Point::new(
10047 end_row.previous_row().0,
10048 buffer.line_len(end_row.previous_row()),
10049 );
10050 let insertion_point = display_map
10051 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10052 .0;
10053
10054 // Don't move lines across excerpts
10055 if buffer
10056 .excerpt_containing(insertion_point..range_to_move.end)
10057 .is_some()
10058 {
10059 let text = buffer
10060 .text_for_range(range_to_move.clone())
10061 .flat_map(|s| s.chars())
10062 .skip(1)
10063 .chain(['\n'])
10064 .collect::<String>();
10065
10066 edits.push((
10067 buffer.anchor_after(range_to_move.start)
10068 ..buffer.anchor_before(range_to_move.end),
10069 String::new(),
10070 ));
10071 let insertion_anchor = buffer.anchor_after(insertion_point);
10072 edits.push((insertion_anchor..insertion_anchor, text));
10073
10074 let row_delta = range_to_move.start.row - insertion_point.row + 1;
10075
10076 // Move selections up
10077 new_selections.extend(contiguous_row_selections.drain(..).map(
10078 |mut selection| {
10079 selection.start.row -= row_delta;
10080 selection.end.row -= row_delta;
10081 selection
10082 },
10083 ));
10084
10085 // Move folds up
10086 unfold_ranges.push(range_to_move.clone());
10087 for fold in display_map.folds_in_range(
10088 buffer.anchor_before(range_to_move.start)
10089 ..buffer.anchor_after(range_to_move.end),
10090 ) {
10091 let mut start = fold.range.start.to_point(&buffer);
10092 let mut end = fold.range.end.to_point(&buffer);
10093 start.row -= row_delta;
10094 end.row -= row_delta;
10095 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10096 }
10097 }
10098 }
10099
10100 // If we didn't move line(s), preserve the existing selections
10101 new_selections.append(&mut contiguous_row_selections);
10102 }
10103
10104 self.transact(window, cx, |this, window, cx| {
10105 this.unfold_ranges(&unfold_ranges, true, true, cx);
10106 this.buffer.update(cx, |buffer, cx| {
10107 for (range, text) in edits {
10108 buffer.edit([(range, text)], None, cx);
10109 }
10110 });
10111 this.fold_creases(refold_creases, true, window, cx);
10112 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10113 s.select(new_selections);
10114 })
10115 });
10116 }
10117
10118 pub fn move_line_down(
10119 &mut self,
10120 _: &MoveLineDown,
10121 window: &mut Window,
10122 cx: &mut Context<Self>,
10123 ) {
10124 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10125
10126 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10127 let buffer = self.buffer.read(cx).snapshot(cx);
10128
10129 let mut edits = Vec::new();
10130 let mut unfold_ranges = Vec::new();
10131 let mut refold_creases = Vec::new();
10132
10133 let selections = self.selections.all::<Point>(cx);
10134 let mut selections = selections.iter().peekable();
10135 let mut contiguous_row_selections = Vec::new();
10136 let mut new_selections = Vec::new();
10137
10138 while let Some(selection) = selections.next() {
10139 // Find all the selections that span a contiguous row range
10140 let (start_row, end_row) = consume_contiguous_rows(
10141 &mut contiguous_row_selections,
10142 selection,
10143 &display_map,
10144 &mut selections,
10145 );
10146
10147 // Move the text spanned by the row range to be after the last line of the row range
10148 if end_row.0 <= buffer.max_point().row {
10149 let range_to_move =
10150 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10151 let insertion_point = display_map
10152 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10153 .0;
10154
10155 // Don't move lines across excerpt boundaries
10156 if buffer
10157 .excerpt_containing(range_to_move.start..insertion_point)
10158 .is_some()
10159 {
10160 let mut text = String::from("\n");
10161 text.extend(buffer.text_for_range(range_to_move.clone()));
10162 text.pop(); // Drop trailing newline
10163 edits.push((
10164 buffer.anchor_after(range_to_move.start)
10165 ..buffer.anchor_before(range_to_move.end),
10166 String::new(),
10167 ));
10168 let insertion_anchor = buffer.anchor_after(insertion_point);
10169 edits.push((insertion_anchor..insertion_anchor, text));
10170
10171 let row_delta = insertion_point.row - range_to_move.end.row + 1;
10172
10173 // Move selections down
10174 new_selections.extend(contiguous_row_selections.drain(..).map(
10175 |mut selection| {
10176 selection.start.row += row_delta;
10177 selection.end.row += row_delta;
10178 selection
10179 },
10180 ));
10181
10182 // Move folds down
10183 unfold_ranges.push(range_to_move.clone());
10184 for fold in display_map.folds_in_range(
10185 buffer.anchor_before(range_to_move.start)
10186 ..buffer.anchor_after(range_to_move.end),
10187 ) {
10188 let mut start = fold.range.start.to_point(&buffer);
10189 let mut end = fold.range.end.to_point(&buffer);
10190 start.row += row_delta;
10191 end.row += row_delta;
10192 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10193 }
10194 }
10195 }
10196
10197 // If we didn't move line(s), preserve the existing selections
10198 new_selections.append(&mut contiguous_row_selections);
10199 }
10200
10201 self.transact(window, cx, |this, window, cx| {
10202 this.unfold_ranges(&unfold_ranges, true, true, cx);
10203 this.buffer.update(cx, |buffer, cx| {
10204 for (range, text) in edits {
10205 buffer.edit([(range, text)], None, cx);
10206 }
10207 });
10208 this.fold_creases(refold_creases, true, window, cx);
10209 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10210 s.select(new_selections)
10211 });
10212 });
10213 }
10214
10215 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10216 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10217 let text_layout_details = &self.text_layout_details(window);
10218 self.transact(window, cx, |this, window, cx| {
10219 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10220 let mut edits: Vec<(Range<usize>, String)> = Default::default();
10221 s.move_with(|display_map, selection| {
10222 if !selection.is_empty() {
10223 return;
10224 }
10225
10226 let mut head = selection.head();
10227 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10228 if head.column() == display_map.line_len(head.row()) {
10229 transpose_offset = display_map
10230 .buffer_snapshot
10231 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10232 }
10233
10234 if transpose_offset == 0 {
10235 return;
10236 }
10237
10238 *head.column_mut() += 1;
10239 head = display_map.clip_point(head, Bias::Right);
10240 let goal = SelectionGoal::HorizontalPosition(
10241 display_map
10242 .x_for_display_point(head, text_layout_details)
10243 .into(),
10244 );
10245 selection.collapse_to(head, goal);
10246
10247 let transpose_start = display_map
10248 .buffer_snapshot
10249 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10250 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10251 let transpose_end = display_map
10252 .buffer_snapshot
10253 .clip_offset(transpose_offset + 1, Bias::Right);
10254 if let Some(ch) =
10255 display_map.buffer_snapshot.chars_at(transpose_start).next()
10256 {
10257 edits.push((transpose_start..transpose_offset, String::new()));
10258 edits.push((transpose_end..transpose_end, ch.to_string()));
10259 }
10260 }
10261 });
10262 edits
10263 });
10264 this.buffer
10265 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10266 let selections = this.selections.all::<usize>(cx);
10267 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10268 s.select(selections);
10269 });
10270 });
10271 }
10272
10273 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10274 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10275 self.rewrap_impl(RewrapOptions::default(), cx)
10276 }
10277
10278 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10279 let buffer = self.buffer.read(cx).snapshot(cx);
10280 let selections = self.selections.all::<Point>(cx);
10281 let mut selections = selections.iter().peekable();
10282
10283 let mut edits = Vec::new();
10284 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10285
10286 while let Some(selection) = selections.next() {
10287 let mut start_row = selection.start.row;
10288 let mut end_row = selection.end.row;
10289
10290 // Skip selections that overlap with a range that has already been rewrapped.
10291 let selection_range = start_row..end_row;
10292 if rewrapped_row_ranges
10293 .iter()
10294 .any(|range| range.overlaps(&selection_range))
10295 {
10296 continue;
10297 }
10298
10299 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10300
10301 // Since not all lines in the selection may be at the same indent
10302 // level, choose the indent size that is the most common between all
10303 // of the lines.
10304 //
10305 // If there is a tie, we use the deepest indent.
10306 let (indent_size, indent_end) = {
10307 let mut indent_size_occurrences = HashMap::default();
10308 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10309
10310 for row in start_row..=end_row {
10311 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10312 rows_by_indent_size.entry(indent).or_default().push(row);
10313 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10314 }
10315
10316 let indent_size = indent_size_occurrences
10317 .into_iter()
10318 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10319 .map(|(indent, _)| indent)
10320 .unwrap_or_default();
10321 let row = rows_by_indent_size[&indent_size][0];
10322 let indent_end = Point::new(row, indent_size.len);
10323
10324 (indent_size, indent_end)
10325 };
10326
10327 let mut line_prefix = indent_size.chars().collect::<String>();
10328
10329 let mut inside_comment = false;
10330 if let Some(comment_prefix) =
10331 buffer
10332 .language_scope_at(selection.head())
10333 .and_then(|language| {
10334 language
10335 .line_comment_prefixes()
10336 .iter()
10337 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10338 .cloned()
10339 })
10340 {
10341 line_prefix.push_str(&comment_prefix);
10342 inside_comment = true;
10343 }
10344
10345 let language_settings = buffer.language_settings_at(selection.head(), cx);
10346 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10347 RewrapBehavior::InComments => inside_comment,
10348 RewrapBehavior::InSelections => !selection.is_empty(),
10349 RewrapBehavior::Anywhere => true,
10350 };
10351
10352 let should_rewrap = options.override_language_settings
10353 || allow_rewrap_based_on_language
10354 || self.hard_wrap.is_some();
10355 if !should_rewrap {
10356 continue;
10357 }
10358
10359 if selection.is_empty() {
10360 'expand_upwards: while start_row > 0 {
10361 let prev_row = start_row - 1;
10362 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10363 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10364 {
10365 start_row = prev_row;
10366 } else {
10367 break 'expand_upwards;
10368 }
10369 }
10370
10371 'expand_downwards: while end_row < buffer.max_point().row {
10372 let next_row = end_row + 1;
10373 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10374 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10375 {
10376 end_row = next_row;
10377 } else {
10378 break 'expand_downwards;
10379 }
10380 }
10381 }
10382
10383 let start = Point::new(start_row, 0);
10384 let start_offset = start.to_offset(&buffer);
10385 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10386 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10387 let Some(lines_without_prefixes) = selection_text
10388 .lines()
10389 .map(|line| {
10390 line.strip_prefix(&line_prefix)
10391 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10392 .ok_or_else(|| {
10393 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10394 })
10395 })
10396 .collect::<Result<Vec<_>, _>>()
10397 .log_err()
10398 else {
10399 continue;
10400 };
10401
10402 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10403 buffer
10404 .language_settings_at(Point::new(start_row, 0), cx)
10405 .preferred_line_length as usize
10406 });
10407 let wrapped_text = wrap_with_prefix(
10408 line_prefix,
10409 lines_without_prefixes.join("\n"),
10410 wrap_column,
10411 tab_size,
10412 options.preserve_existing_whitespace,
10413 );
10414
10415 // TODO: should always use char-based diff while still supporting cursor behavior that
10416 // matches vim.
10417 let mut diff_options = DiffOptions::default();
10418 if options.override_language_settings {
10419 diff_options.max_word_diff_len = 0;
10420 diff_options.max_word_diff_line_count = 0;
10421 } else {
10422 diff_options.max_word_diff_len = usize::MAX;
10423 diff_options.max_word_diff_line_count = usize::MAX;
10424 }
10425
10426 for (old_range, new_text) in
10427 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10428 {
10429 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10430 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10431 edits.push((edit_start..edit_end, new_text));
10432 }
10433
10434 rewrapped_row_ranges.push(start_row..=end_row);
10435 }
10436
10437 self.buffer
10438 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10439 }
10440
10441 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10442 let mut text = String::new();
10443 let buffer = self.buffer.read(cx).snapshot(cx);
10444 let mut selections = self.selections.all::<Point>(cx);
10445 let mut clipboard_selections = Vec::with_capacity(selections.len());
10446 {
10447 let max_point = buffer.max_point();
10448 let mut is_first = true;
10449 for selection in &mut selections {
10450 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10451 if is_entire_line {
10452 selection.start = Point::new(selection.start.row, 0);
10453 if !selection.is_empty() && selection.end.column == 0 {
10454 selection.end = cmp::min(max_point, selection.end);
10455 } else {
10456 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10457 }
10458 selection.goal = SelectionGoal::None;
10459 }
10460 if is_first {
10461 is_first = false;
10462 } else {
10463 text += "\n";
10464 }
10465 let mut len = 0;
10466 for chunk in buffer.text_for_range(selection.start..selection.end) {
10467 text.push_str(chunk);
10468 len += chunk.len();
10469 }
10470 clipboard_selections.push(ClipboardSelection {
10471 len,
10472 is_entire_line,
10473 first_line_indent: buffer
10474 .indent_size_for_line(MultiBufferRow(selection.start.row))
10475 .len,
10476 });
10477 }
10478 }
10479
10480 self.transact(window, cx, |this, window, cx| {
10481 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10482 s.select(selections);
10483 });
10484 this.insert("", window, cx);
10485 });
10486 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10487 }
10488
10489 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10490 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10491 let item = self.cut_common(window, cx);
10492 cx.write_to_clipboard(item);
10493 }
10494
10495 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10496 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10497 self.change_selections(None, window, cx, |s| {
10498 s.move_with(|snapshot, sel| {
10499 if sel.is_empty() {
10500 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10501 }
10502 });
10503 });
10504 let item = self.cut_common(window, cx);
10505 cx.set_global(KillRing(item))
10506 }
10507
10508 pub fn kill_ring_yank(
10509 &mut self,
10510 _: &KillRingYank,
10511 window: &mut Window,
10512 cx: &mut Context<Self>,
10513 ) {
10514 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10515 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10516 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10517 (kill_ring.text().to_string(), kill_ring.metadata_json())
10518 } else {
10519 return;
10520 }
10521 } else {
10522 return;
10523 };
10524 self.do_paste(&text, metadata, false, window, cx);
10525 }
10526
10527 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10528 self.do_copy(true, cx);
10529 }
10530
10531 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10532 self.do_copy(false, cx);
10533 }
10534
10535 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10536 let selections = self.selections.all::<Point>(cx);
10537 let buffer = self.buffer.read(cx).read(cx);
10538 let mut text = String::new();
10539
10540 let mut clipboard_selections = Vec::with_capacity(selections.len());
10541 {
10542 let max_point = buffer.max_point();
10543 let mut is_first = true;
10544 for selection in &selections {
10545 let mut start = selection.start;
10546 let mut end = selection.end;
10547 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10548 if is_entire_line {
10549 start = Point::new(start.row, 0);
10550 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10551 }
10552
10553 let mut trimmed_selections = Vec::new();
10554 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10555 let row = MultiBufferRow(start.row);
10556 let first_indent = buffer.indent_size_for_line(row);
10557 if first_indent.len == 0 || start.column > first_indent.len {
10558 trimmed_selections.push(start..end);
10559 } else {
10560 trimmed_selections.push(
10561 Point::new(row.0, first_indent.len)
10562 ..Point::new(row.0, buffer.line_len(row)),
10563 );
10564 for row in start.row + 1..=end.row {
10565 let mut line_len = buffer.line_len(MultiBufferRow(row));
10566 if row == end.row {
10567 line_len = end.column;
10568 }
10569 if line_len == 0 {
10570 trimmed_selections
10571 .push(Point::new(row, 0)..Point::new(row, line_len));
10572 continue;
10573 }
10574 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10575 if row_indent_size.len >= first_indent.len {
10576 trimmed_selections.push(
10577 Point::new(row, first_indent.len)..Point::new(row, line_len),
10578 );
10579 } else {
10580 trimmed_selections.clear();
10581 trimmed_selections.push(start..end);
10582 break;
10583 }
10584 }
10585 }
10586 } else {
10587 trimmed_selections.push(start..end);
10588 }
10589
10590 for trimmed_range in trimmed_selections {
10591 if is_first {
10592 is_first = false;
10593 } else {
10594 text += "\n";
10595 }
10596 let mut len = 0;
10597 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10598 text.push_str(chunk);
10599 len += chunk.len();
10600 }
10601 clipboard_selections.push(ClipboardSelection {
10602 len,
10603 is_entire_line,
10604 first_line_indent: buffer
10605 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10606 .len,
10607 });
10608 }
10609 }
10610 }
10611
10612 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10613 text,
10614 clipboard_selections,
10615 ));
10616 }
10617
10618 pub fn do_paste(
10619 &mut self,
10620 text: &String,
10621 clipboard_selections: Option<Vec<ClipboardSelection>>,
10622 handle_entire_lines: bool,
10623 window: &mut Window,
10624 cx: &mut Context<Self>,
10625 ) {
10626 if self.read_only(cx) {
10627 return;
10628 }
10629
10630 let clipboard_text = Cow::Borrowed(text);
10631
10632 self.transact(window, cx, |this, window, cx| {
10633 if let Some(mut clipboard_selections) = clipboard_selections {
10634 let old_selections = this.selections.all::<usize>(cx);
10635 let all_selections_were_entire_line =
10636 clipboard_selections.iter().all(|s| s.is_entire_line);
10637 let first_selection_indent_column =
10638 clipboard_selections.first().map(|s| s.first_line_indent);
10639 if clipboard_selections.len() != old_selections.len() {
10640 clipboard_selections.drain(..);
10641 }
10642 let cursor_offset = this.selections.last::<usize>(cx).head();
10643 let mut auto_indent_on_paste = true;
10644
10645 this.buffer.update(cx, |buffer, cx| {
10646 let snapshot = buffer.read(cx);
10647 auto_indent_on_paste = snapshot
10648 .language_settings_at(cursor_offset, cx)
10649 .auto_indent_on_paste;
10650
10651 let mut start_offset = 0;
10652 let mut edits = Vec::new();
10653 let mut original_indent_columns = Vec::new();
10654 for (ix, selection) in old_selections.iter().enumerate() {
10655 let to_insert;
10656 let entire_line;
10657 let original_indent_column;
10658 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10659 let end_offset = start_offset + clipboard_selection.len;
10660 to_insert = &clipboard_text[start_offset..end_offset];
10661 entire_line = clipboard_selection.is_entire_line;
10662 start_offset = end_offset + 1;
10663 original_indent_column = Some(clipboard_selection.first_line_indent);
10664 } else {
10665 to_insert = clipboard_text.as_str();
10666 entire_line = all_selections_were_entire_line;
10667 original_indent_column = first_selection_indent_column
10668 }
10669
10670 // If the corresponding selection was empty when this slice of the
10671 // clipboard text was written, then the entire line containing the
10672 // selection was copied. If this selection is also currently empty,
10673 // then paste the line before the current line of the buffer.
10674 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10675 let column = selection.start.to_point(&snapshot).column as usize;
10676 let line_start = selection.start - column;
10677 line_start..line_start
10678 } else {
10679 selection.range()
10680 };
10681
10682 edits.push((range, to_insert));
10683 original_indent_columns.push(original_indent_column);
10684 }
10685 drop(snapshot);
10686
10687 buffer.edit(
10688 edits,
10689 if auto_indent_on_paste {
10690 Some(AutoindentMode::Block {
10691 original_indent_columns,
10692 })
10693 } else {
10694 None
10695 },
10696 cx,
10697 );
10698 });
10699
10700 let selections = this.selections.all::<usize>(cx);
10701 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10702 s.select(selections)
10703 });
10704 } else {
10705 this.insert(&clipboard_text, window, cx);
10706 }
10707 });
10708 }
10709
10710 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10711 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10712 if let Some(item) = cx.read_from_clipboard() {
10713 let entries = item.entries();
10714
10715 match entries.first() {
10716 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10717 // of all the pasted entries.
10718 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10719 .do_paste(
10720 clipboard_string.text(),
10721 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10722 true,
10723 window,
10724 cx,
10725 ),
10726 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10727 }
10728 }
10729 }
10730
10731 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10732 if self.read_only(cx) {
10733 return;
10734 }
10735
10736 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10737
10738 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10739 if let Some((selections, _)) =
10740 self.selection_history.transaction(transaction_id).cloned()
10741 {
10742 self.change_selections(None, window, cx, |s| {
10743 s.select_anchors(selections.to_vec());
10744 });
10745 } else {
10746 log::error!(
10747 "No entry in selection_history found for undo. \
10748 This may correspond to a bug where undo does not update the selection. \
10749 If this is occurring, please add details to \
10750 https://github.com/zed-industries/zed/issues/22692"
10751 );
10752 }
10753 self.request_autoscroll(Autoscroll::fit(), cx);
10754 self.unmark_text(window, cx);
10755 self.refresh_inline_completion(true, false, window, cx);
10756 cx.emit(EditorEvent::Edited { transaction_id });
10757 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10758 }
10759 }
10760
10761 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10762 if self.read_only(cx) {
10763 return;
10764 }
10765
10766 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10767
10768 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10769 if let Some((_, Some(selections))) =
10770 self.selection_history.transaction(transaction_id).cloned()
10771 {
10772 self.change_selections(None, window, cx, |s| {
10773 s.select_anchors(selections.to_vec());
10774 });
10775 } else {
10776 log::error!(
10777 "No entry in selection_history found for redo. \
10778 This may correspond to a bug where undo does not update the selection. \
10779 If this is occurring, please add details to \
10780 https://github.com/zed-industries/zed/issues/22692"
10781 );
10782 }
10783 self.request_autoscroll(Autoscroll::fit(), cx);
10784 self.unmark_text(window, cx);
10785 self.refresh_inline_completion(true, false, window, cx);
10786 cx.emit(EditorEvent::Edited { transaction_id });
10787 }
10788 }
10789
10790 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10791 self.buffer
10792 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10793 }
10794
10795 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10796 self.buffer
10797 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10798 }
10799
10800 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10801 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10802 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10803 s.move_with(|map, selection| {
10804 let cursor = if selection.is_empty() {
10805 movement::left(map, selection.start)
10806 } else {
10807 selection.start
10808 };
10809 selection.collapse_to(cursor, SelectionGoal::None);
10810 });
10811 })
10812 }
10813
10814 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10815 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10816 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10817 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10818 })
10819 }
10820
10821 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10822 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10823 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10824 s.move_with(|map, selection| {
10825 let cursor = if selection.is_empty() {
10826 movement::right(map, selection.end)
10827 } else {
10828 selection.end
10829 };
10830 selection.collapse_to(cursor, SelectionGoal::None)
10831 });
10832 })
10833 }
10834
10835 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10836 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10837 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10838 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10839 })
10840 }
10841
10842 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10843 if self.take_rename(true, window, cx).is_some() {
10844 return;
10845 }
10846
10847 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10848 cx.propagate();
10849 return;
10850 }
10851
10852 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10853
10854 let text_layout_details = &self.text_layout_details(window);
10855 let selection_count = self.selections.count();
10856 let first_selection = self.selections.first_anchor();
10857
10858 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10859 s.move_with(|map, selection| {
10860 if !selection.is_empty() {
10861 selection.goal = SelectionGoal::None;
10862 }
10863 let (cursor, goal) = movement::up(
10864 map,
10865 selection.start,
10866 selection.goal,
10867 false,
10868 text_layout_details,
10869 );
10870 selection.collapse_to(cursor, goal);
10871 });
10872 });
10873
10874 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10875 {
10876 cx.propagate();
10877 }
10878 }
10879
10880 pub fn move_up_by_lines(
10881 &mut self,
10882 action: &MoveUpByLines,
10883 window: &mut Window,
10884 cx: &mut Context<Self>,
10885 ) {
10886 if self.take_rename(true, window, cx).is_some() {
10887 return;
10888 }
10889
10890 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10891 cx.propagate();
10892 return;
10893 }
10894
10895 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10896
10897 let text_layout_details = &self.text_layout_details(window);
10898
10899 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10900 s.move_with(|map, selection| {
10901 if !selection.is_empty() {
10902 selection.goal = SelectionGoal::None;
10903 }
10904 let (cursor, goal) = movement::up_by_rows(
10905 map,
10906 selection.start,
10907 action.lines,
10908 selection.goal,
10909 false,
10910 text_layout_details,
10911 );
10912 selection.collapse_to(cursor, goal);
10913 });
10914 })
10915 }
10916
10917 pub fn move_down_by_lines(
10918 &mut self,
10919 action: &MoveDownByLines,
10920 window: &mut Window,
10921 cx: &mut Context<Self>,
10922 ) {
10923 if self.take_rename(true, window, cx).is_some() {
10924 return;
10925 }
10926
10927 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10928 cx.propagate();
10929 return;
10930 }
10931
10932 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10933
10934 let text_layout_details = &self.text_layout_details(window);
10935
10936 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10937 s.move_with(|map, selection| {
10938 if !selection.is_empty() {
10939 selection.goal = SelectionGoal::None;
10940 }
10941 let (cursor, goal) = movement::down_by_rows(
10942 map,
10943 selection.start,
10944 action.lines,
10945 selection.goal,
10946 false,
10947 text_layout_details,
10948 );
10949 selection.collapse_to(cursor, goal);
10950 });
10951 })
10952 }
10953
10954 pub fn select_down_by_lines(
10955 &mut self,
10956 action: &SelectDownByLines,
10957 window: &mut Window,
10958 cx: &mut Context<Self>,
10959 ) {
10960 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10961 let text_layout_details = &self.text_layout_details(window);
10962 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10963 s.move_heads_with(|map, head, goal| {
10964 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10965 })
10966 })
10967 }
10968
10969 pub fn select_up_by_lines(
10970 &mut self,
10971 action: &SelectUpByLines,
10972 window: &mut Window,
10973 cx: &mut Context<Self>,
10974 ) {
10975 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10976 let text_layout_details = &self.text_layout_details(window);
10977 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10978 s.move_heads_with(|map, head, goal| {
10979 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10980 })
10981 })
10982 }
10983
10984 pub fn select_page_up(
10985 &mut self,
10986 _: &SelectPageUp,
10987 window: &mut Window,
10988 cx: &mut Context<Self>,
10989 ) {
10990 let Some(row_count) = self.visible_row_count() else {
10991 return;
10992 };
10993
10994 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10995
10996 let text_layout_details = &self.text_layout_details(window);
10997
10998 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10999 s.move_heads_with(|map, head, goal| {
11000 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
11001 })
11002 })
11003 }
11004
11005 pub fn move_page_up(
11006 &mut self,
11007 action: &MovePageUp,
11008 window: &mut Window,
11009 cx: &mut Context<Self>,
11010 ) {
11011 if self.take_rename(true, window, cx).is_some() {
11012 return;
11013 }
11014
11015 if self
11016 .context_menu
11017 .borrow_mut()
11018 .as_mut()
11019 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11020 .unwrap_or(false)
11021 {
11022 return;
11023 }
11024
11025 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11026 cx.propagate();
11027 return;
11028 }
11029
11030 let Some(row_count) = self.visible_row_count() else {
11031 return;
11032 };
11033
11034 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11035
11036 let autoscroll = if action.center_cursor {
11037 Autoscroll::center()
11038 } else {
11039 Autoscroll::fit()
11040 };
11041
11042 let text_layout_details = &self.text_layout_details(window);
11043
11044 self.change_selections(Some(autoscroll), window, cx, |s| {
11045 s.move_with(|map, selection| {
11046 if !selection.is_empty() {
11047 selection.goal = SelectionGoal::None;
11048 }
11049 let (cursor, goal) = movement::up_by_rows(
11050 map,
11051 selection.end,
11052 row_count,
11053 selection.goal,
11054 false,
11055 text_layout_details,
11056 );
11057 selection.collapse_to(cursor, goal);
11058 });
11059 });
11060 }
11061
11062 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11063 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11064 let text_layout_details = &self.text_layout_details(window);
11065 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11066 s.move_heads_with(|map, head, goal| {
11067 movement::up(map, head, goal, false, text_layout_details)
11068 })
11069 })
11070 }
11071
11072 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11073 self.take_rename(true, window, cx);
11074
11075 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11076 cx.propagate();
11077 return;
11078 }
11079
11080 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11081
11082 let text_layout_details = &self.text_layout_details(window);
11083 let selection_count = self.selections.count();
11084 let first_selection = self.selections.first_anchor();
11085
11086 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11087 s.move_with(|map, selection| {
11088 if !selection.is_empty() {
11089 selection.goal = SelectionGoal::None;
11090 }
11091 let (cursor, goal) = movement::down(
11092 map,
11093 selection.end,
11094 selection.goal,
11095 false,
11096 text_layout_details,
11097 );
11098 selection.collapse_to(cursor, goal);
11099 });
11100 });
11101
11102 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11103 {
11104 cx.propagate();
11105 }
11106 }
11107
11108 pub fn select_page_down(
11109 &mut self,
11110 _: &SelectPageDown,
11111 window: &mut Window,
11112 cx: &mut Context<Self>,
11113 ) {
11114 let Some(row_count) = self.visible_row_count() else {
11115 return;
11116 };
11117
11118 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11119
11120 let text_layout_details = &self.text_layout_details(window);
11121
11122 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11123 s.move_heads_with(|map, head, goal| {
11124 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11125 })
11126 })
11127 }
11128
11129 pub fn move_page_down(
11130 &mut self,
11131 action: &MovePageDown,
11132 window: &mut Window,
11133 cx: &mut Context<Self>,
11134 ) {
11135 if self.take_rename(true, window, cx).is_some() {
11136 return;
11137 }
11138
11139 if self
11140 .context_menu
11141 .borrow_mut()
11142 .as_mut()
11143 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11144 .unwrap_or(false)
11145 {
11146 return;
11147 }
11148
11149 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11150 cx.propagate();
11151 return;
11152 }
11153
11154 let Some(row_count) = self.visible_row_count() else {
11155 return;
11156 };
11157
11158 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11159
11160 let autoscroll = if action.center_cursor {
11161 Autoscroll::center()
11162 } else {
11163 Autoscroll::fit()
11164 };
11165
11166 let text_layout_details = &self.text_layout_details(window);
11167 self.change_selections(Some(autoscroll), window, cx, |s| {
11168 s.move_with(|map, selection| {
11169 if !selection.is_empty() {
11170 selection.goal = SelectionGoal::None;
11171 }
11172 let (cursor, goal) = movement::down_by_rows(
11173 map,
11174 selection.end,
11175 row_count,
11176 selection.goal,
11177 false,
11178 text_layout_details,
11179 );
11180 selection.collapse_to(cursor, goal);
11181 });
11182 });
11183 }
11184
11185 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11186 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11187 let text_layout_details = &self.text_layout_details(window);
11188 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11189 s.move_heads_with(|map, head, goal| {
11190 movement::down(map, head, goal, false, text_layout_details)
11191 })
11192 });
11193 }
11194
11195 pub fn context_menu_first(
11196 &mut self,
11197 _: &ContextMenuFirst,
11198 _window: &mut Window,
11199 cx: &mut Context<Self>,
11200 ) {
11201 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11202 context_menu.select_first(self.completion_provider.as_deref(), cx);
11203 }
11204 }
11205
11206 pub fn context_menu_prev(
11207 &mut self,
11208 _: &ContextMenuPrevious,
11209 _window: &mut Window,
11210 cx: &mut Context<Self>,
11211 ) {
11212 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11213 context_menu.select_prev(self.completion_provider.as_deref(), cx);
11214 }
11215 }
11216
11217 pub fn context_menu_next(
11218 &mut self,
11219 _: &ContextMenuNext,
11220 _window: &mut Window,
11221 cx: &mut Context<Self>,
11222 ) {
11223 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11224 context_menu.select_next(self.completion_provider.as_deref(), cx);
11225 }
11226 }
11227
11228 pub fn context_menu_last(
11229 &mut self,
11230 _: &ContextMenuLast,
11231 _window: &mut Window,
11232 cx: &mut Context<Self>,
11233 ) {
11234 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11235 context_menu.select_last(self.completion_provider.as_deref(), cx);
11236 }
11237 }
11238
11239 pub fn move_to_previous_word_start(
11240 &mut self,
11241 _: &MoveToPreviousWordStart,
11242 window: &mut Window,
11243 cx: &mut Context<Self>,
11244 ) {
11245 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11246 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11247 s.move_cursors_with(|map, head, _| {
11248 (
11249 movement::previous_word_start(map, head),
11250 SelectionGoal::None,
11251 )
11252 });
11253 })
11254 }
11255
11256 pub fn move_to_previous_subword_start(
11257 &mut self,
11258 _: &MoveToPreviousSubwordStart,
11259 window: &mut Window,
11260 cx: &mut Context<Self>,
11261 ) {
11262 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11263 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11264 s.move_cursors_with(|map, head, _| {
11265 (
11266 movement::previous_subword_start(map, head),
11267 SelectionGoal::None,
11268 )
11269 });
11270 })
11271 }
11272
11273 pub fn select_to_previous_word_start(
11274 &mut self,
11275 _: &SelectToPreviousWordStart,
11276 window: &mut Window,
11277 cx: &mut Context<Self>,
11278 ) {
11279 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11280 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11281 s.move_heads_with(|map, head, _| {
11282 (
11283 movement::previous_word_start(map, head),
11284 SelectionGoal::None,
11285 )
11286 });
11287 })
11288 }
11289
11290 pub fn select_to_previous_subword_start(
11291 &mut self,
11292 _: &SelectToPreviousSubwordStart,
11293 window: &mut Window,
11294 cx: &mut Context<Self>,
11295 ) {
11296 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11297 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11298 s.move_heads_with(|map, head, _| {
11299 (
11300 movement::previous_subword_start(map, head),
11301 SelectionGoal::None,
11302 )
11303 });
11304 })
11305 }
11306
11307 pub fn delete_to_previous_word_start(
11308 &mut self,
11309 action: &DeleteToPreviousWordStart,
11310 window: &mut Window,
11311 cx: &mut Context<Self>,
11312 ) {
11313 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11314 self.transact(window, cx, |this, window, cx| {
11315 this.select_autoclose_pair(window, cx);
11316 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11317 s.move_with(|map, selection| {
11318 if selection.is_empty() {
11319 let cursor = if action.ignore_newlines {
11320 movement::previous_word_start(map, selection.head())
11321 } else {
11322 movement::previous_word_start_or_newline(map, selection.head())
11323 };
11324 selection.set_head(cursor, SelectionGoal::None);
11325 }
11326 });
11327 });
11328 this.insert("", window, cx);
11329 });
11330 }
11331
11332 pub fn delete_to_previous_subword_start(
11333 &mut self,
11334 _: &DeleteToPreviousSubwordStart,
11335 window: &mut Window,
11336 cx: &mut Context<Self>,
11337 ) {
11338 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11339 self.transact(window, cx, |this, window, cx| {
11340 this.select_autoclose_pair(window, cx);
11341 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11342 s.move_with(|map, selection| {
11343 if selection.is_empty() {
11344 let cursor = movement::previous_subword_start(map, selection.head());
11345 selection.set_head(cursor, SelectionGoal::None);
11346 }
11347 });
11348 });
11349 this.insert("", window, cx);
11350 });
11351 }
11352
11353 pub fn move_to_next_word_end(
11354 &mut self,
11355 _: &MoveToNextWordEnd,
11356 window: &mut Window,
11357 cx: &mut Context<Self>,
11358 ) {
11359 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11360 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11361 s.move_cursors_with(|map, head, _| {
11362 (movement::next_word_end(map, head), SelectionGoal::None)
11363 });
11364 })
11365 }
11366
11367 pub fn move_to_next_subword_end(
11368 &mut self,
11369 _: &MoveToNextSubwordEnd,
11370 window: &mut Window,
11371 cx: &mut Context<Self>,
11372 ) {
11373 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11374 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11375 s.move_cursors_with(|map, head, _| {
11376 (movement::next_subword_end(map, head), SelectionGoal::None)
11377 });
11378 })
11379 }
11380
11381 pub fn select_to_next_word_end(
11382 &mut self,
11383 _: &SelectToNextWordEnd,
11384 window: &mut Window,
11385 cx: &mut Context<Self>,
11386 ) {
11387 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11388 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11389 s.move_heads_with(|map, head, _| {
11390 (movement::next_word_end(map, head), SelectionGoal::None)
11391 });
11392 })
11393 }
11394
11395 pub fn select_to_next_subword_end(
11396 &mut self,
11397 _: &SelectToNextSubwordEnd,
11398 window: &mut Window,
11399 cx: &mut Context<Self>,
11400 ) {
11401 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11402 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11403 s.move_heads_with(|map, head, _| {
11404 (movement::next_subword_end(map, head), SelectionGoal::None)
11405 });
11406 })
11407 }
11408
11409 pub fn delete_to_next_word_end(
11410 &mut self,
11411 action: &DeleteToNextWordEnd,
11412 window: &mut Window,
11413 cx: &mut Context<Self>,
11414 ) {
11415 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11416 self.transact(window, cx, |this, window, cx| {
11417 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11418 s.move_with(|map, selection| {
11419 if selection.is_empty() {
11420 let cursor = if action.ignore_newlines {
11421 movement::next_word_end(map, selection.head())
11422 } else {
11423 movement::next_word_end_or_newline(map, selection.head())
11424 };
11425 selection.set_head(cursor, SelectionGoal::None);
11426 }
11427 });
11428 });
11429 this.insert("", window, cx);
11430 });
11431 }
11432
11433 pub fn delete_to_next_subword_end(
11434 &mut self,
11435 _: &DeleteToNextSubwordEnd,
11436 window: &mut Window,
11437 cx: &mut Context<Self>,
11438 ) {
11439 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11440 self.transact(window, cx, |this, window, cx| {
11441 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11442 s.move_with(|map, selection| {
11443 if selection.is_empty() {
11444 let cursor = movement::next_subword_end(map, selection.head());
11445 selection.set_head(cursor, SelectionGoal::None);
11446 }
11447 });
11448 });
11449 this.insert("", window, cx);
11450 });
11451 }
11452
11453 pub fn move_to_beginning_of_line(
11454 &mut self,
11455 action: &MoveToBeginningOfLine,
11456 window: &mut Window,
11457 cx: &mut Context<Self>,
11458 ) {
11459 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11460 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11461 s.move_cursors_with(|map, head, _| {
11462 (
11463 movement::indented_line_beginning(
11464 map,
11465 head,
11466 action.stop_at_soft_wraps,
11467 action.stop_at_indent,
11468 ),
11469 SelectionGoal::None,
11470 )
11471 });
11472 })
11473 }
11474
11475 pub fn select_to_beginning_of_line(
11476 &mut self,
11477 action: &SelectToBeginningOfLine,
11478 window: &mut Window,
11479 cx: &mut Context<Self>,
11480 ) {
11481 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11482 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11483 s.move_heads_with(|map, head, _| {
11484 (
11485 movement::indented_line_beginning(
11486 map,
11487 head,
11488 action.stop_at_soft_wraps,
11489 action.stop_at_indent,
11490 ),
11491 SelectionGoal::None,
11492 )
11493 });
11494 });
11495 }
11496
11497 pub fn delete_to_beginning_of_line(
11498 &mut self,
11499 action: &DeleteToBeginningOfLine,
11500 window: &mut Window,
11501 cx: &mut Context<Self>,
11502 ) {
11503 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11504 self.transact(window, cx, |this, window, cx| {
11505 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11506 s.move_with(|_, selection| {
11507 selection.reversed = true;
11508 });
11509 });
11510
11511 this.select_to_beginning_of_line(
11512 &SelectToBeginningOfLine {
11513 stop_at_soft_wraps: false,
11514 stop_at_indent: action.stop_at_indent,
11515 },
11516 window,
11517 cx,
11518 );
11519 this.backspace(&Backspace, window, cx);
11520 });
11521 }
11522
11523 pub fn move_to_end_of_line(
11524 &mut self,
11525 action: &MoveToEndOfLine,
11526 window: &mut Window,
11527 cx: &mut Context<Self>,
11528 ) {
11529 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11530 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11531 s.move_cursors_with(|map, head, _| {
11532 (
11533 movement::line_end(map, head, action.stop_at_soft_wraps),
11534 SelectionGoal::None,
11535 )
11536 });
11537 })
11538 }
11539
11540 pub fn select_to_end_of_line(
11541 &mut self,
11542 action: &SelectToEndOfLine,
11543 window: &mut Window,
11544 cx: &mut Context<Self>,
11545 ) {
11546 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11547 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11548 s.move_heads_with(|map, head, _| {
11549 (
11550 movement::line_end(map, head, action.stop_at_soft_wraps),
11551 SelectionGoal::None,
11552 )
11553 });
11554 })
11555 }
11556
11557 pub fn delete_to_end_of_line(
11558 &mut self,
11559 _: &DeleteToEndOfLine,
11560 window: &mut Window,
11561 cx: &mut Context<Self>,
11562 ) {
11563 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11564 self.transact(window, cx, |this, window, cx| {
11565 this.select_to_end_of_line(
11566 &SelectToEndOfLine {
11567 stop_at_soft_wraps: false,
11568 },
11569 window,
11570 cx,
11571 );
11572 this.delete(&Delete, window, cx);
11573 });
11574 }
11575
11576 pub fn cut_to_end_of_line(
11577 &mut self,
11578 _: &CutToEndOfLine,
11579 window: &mut Window,
11580 cx: &mut Context<Self>,
11581 ) {
11582 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11583 self.transact(window, cx, |this, window, cx| {
11584 this.select_to_end_of_line(
11585 &SelectToEndOfLine {
11586 stop_at_soft_wraps: false,
11587 },
11588 window,
11589 cx,
11590 );
11591 this.cut(&Cut, window, cx);
11592 });
11593 }
11594
11595 pub fn move_to_start_of_paragraph(
11596 &mut self,
11597 _: &MoveToStartOfParagraph,
11598 window: &mut Window,
11599 cx: &mut Context<Self>,
11600 ) {
11601 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11602 cx.propagate();
11603 return;
11604 }
11605 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11606 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11607 s.move_with(|map, selection| {
11608 selection.collapse_to(
11609 movement::start_of_paragraph(map, selection.head(), 1),
11610 SelectionGoal::None,
11611 )
11612 });
11613 })
11614 }
11615
11616 pub fn move_to_end_of_paragraph(
11617 &mut self,
11618 _: &MoveToEndOfParagraph,
11619 window: &mut Window,
11620 cx: &mut Context<Self>,
11621 ) {
11622 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11623 cx.propagate();
11624 return;
11625 }
11626 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11627 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11628 s.move_with(|map, selection| {
11629 selection.collapse_to(
11630 movement::end_of_paragraph(map, selection.head(), 1),
11631 SelectionGoal::None,
11632 )
11633 });
11634 })
11635 }
11636
11637 pub fn select_to_start_of_paragraph(
11638 &mut self,
11639 _: &SelectToStartOfParagraph,
11640 window: &mut Window,
11641 cx: &mut Context<Self>,
11642 ) {
11643 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11644 cx.propagate();
11645 return;
11646 }
11647 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11648 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11649 s.move_heads_with(|map, head, _| {
11650 (
11651 movement::start_of_paragraph(map, head, 1),
11652 SelectionGoal::None,
11653 )
11654 });
11655 })
11656 }
11657
11658 pub fn select_to_end_of_paragraph(
11659 &mut self,
11660 _: &SelectToEndOfParagraph,
11661 window: &mut Window,
11662 cx: &mut Context<Self>,
11663 ) {
11664 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11665 cx.propagate();
11666 return;
11667 }
11668 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11669 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11670 s.move_heads_with(|map, head, _| {
11671 (
11672 movement::end_of_paragraph(map, head, 1),
11673 SelectionGoal::None,
11674 )
11675 });
11676 })
11677 }
11678
11679 pub fn move_to_start_of_excerpt(
11680 &mut self,
11681 _: &MoveToStartOfExcerpt,
11682 window: &mut Window,
11683 cx: &mut Context<Self>,
11684 ) {
11685 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11686 cx.propagate();
11687 return;
11688 }
11689 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11690 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11691 s.move_with(|map, selection| {
11692 selection.collapse_to(
11693 movement::start_of_excerpt(
11694 map,
11695 selection.head(),
11696 workspace::searchable::Direction::Prev,
11697 ),
11698 SelectionGoal::None,
11699 )
11700 });
11701 })
11702 }
11703
11704 pub fn move_to_start_of_next_excerpt(
11705 &mut self,
11706 _: &MoveToStartOfNextExcerpt,
11707 window: &mut Window,
11708 cx: &mut Context<Self>,
11709 ) {
11710 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11711 cx.propagate();
11712 return;
11713 }
11714
11715 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11716 s.move_with(|map, selection| {
11717 selection.collapse_to(
11718 movement::start_of_excerpt(
11719 map,
11720 selection.head(),
11721 workspace::searchable::Direction::Next,
11722 ),
11723 SelectionGoal::None,
11724 )
11725 });
11726 })
11727 }
11728
11729 pub fn move_to_end_of_excerpt(
11730 &mut self,
11731 _: &MoveToEndOfExcerpt,
11732 window: &mut Window,
11733 cx: &mut Context<Self>,
11734 ) {
11735 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11736 cx.propagate();
11737 return;
11738 }
11739 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11740 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11741 s.move_with(|map, selection| {
11742 selection.collapse_to(
11743 movement::end_of_excerpt(
11744 map,
11745 selection.head(),
11746 workspace::searchable::Direction::Next,
11747 ),
11748 SelectionGoal::None,
11749 )
11750 });
11751 })
11752 }
11753
11754 pub fn move_to_end_of_previous_excerpt(
11755 &mut self,
11756 _: &MoveToEndOfPreviousExcerpt,
11757 window: &mut Window,
11758 cx: &mut Context<Self>,
11759 ) {
11760 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11761 cx.propagate();
11762 return;
11763 }
11764 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11765 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11766 s.move_with(|map, selection| {
11767 selection.collapse_to(
11768 movement::end_of_excerpt(
11769 map,
11770 selection.head(),
11771 workspace::searchable::Direction::Prev,
11772 ),
11773 SelectionGoal::None,
11774 )
11775 });
11776 })
11777 }
11778
11779 pub fn select_to_start_of_excerpt(
11780 &mut self,
11781 _: &SelectToStartOfExcerpt,
11782 window: &mut Window,
11783 cx: &mut Context<Self>,
11784 ) {
11785 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11786 cx.propagate();
11787 return;
11788 }
11789 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11790 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11791 s.move_heads_with(|map, head, _| {
11792 (
11793 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11794 SelectionGoal::None,
11795 )
11796 });
11797 })
11798 }
11799
11800 pub fn select_to_start_of_next_excerpt(
11801 &mut self,
11802 _: &SelectToStartOfNextExcerpt,
11803 window: &mut Window,
11804 cx: &mut Context<Self>,
11805 ) {
11806 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11807 cx.propagate();
11808 return;
11809 }
11810 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11811 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11812 s.move_heads_with(|map, head, _| {
11813 (
11814 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11815 SelectionGoal::None,
11816 )
11817 });
11818 })
11819 }
11820
11821 pub fn select_to_end_of_excerpt(
11822 &mut self,
11823 _: &SelectToEndOfExcerpt,
11824 window: &mut Window,
11825 cx: &mut Context<Self>,
11826 ) {
11827 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11828 cx.propagate();
11829 return;
11830 }
11831 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11832 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11833 s.move_heads_with(|map, head, _| {
11834 (
11835 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11836 SelectionGoal::None,
11837 )
11838 });
11839 })
11840 }
11841
11842 pub fn select_to_end_of_previous_excerpt(
11843 &mut self,
11844 _: &SelectToEndOfPreviousExcerpt,
11845 window: &mut Window,
11846 cx: &mut Context<Self>,
11847 ) {
11848 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11849 cx.propagate();
11850 return;
11851 }
11852 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11853 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11854 s.move_heads_with(|map, head, _| {
11855 (
11856 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11857 SelectionGoal::None,
11858 )
11859 });
11860 })
11861 }
11862
11863 pub fn move_to_beginning(
11864 &mut self,
11865 _: &MoveToBeginning,
11866 window: &mut Window,
11867 cx: &mut Context<Self>,
11868 ) {
11869 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11870 cx.propagate();
11871 return;
11872 }
11873 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11874 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11875 s.select_ranges(vec![0..0]);
11876 });
11877 }
11878
11879 pub fn select_to_beginning(
11880 &mut self,
11881 _: &SelectToBeginning,
11882 window: &mut Window,
11883 cx: &mut Context<Self>,
11884 ) {
11885 let mut selection = self.selections.last::<Point>(cx);
11886 selection.set_head(Point::zero(), SelectionGoal::None);
11887 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11888 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11889 s.select(vec![selection]);
11890 });
11891 }
11892
11893 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11894 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11895 cx.propagate();
11896 return;
11897 }
11898 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11899 let cursor = self.buffer.read(cx).read(cx).len();
11900 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11901 s.select_ranges(vec![cursor..cursor])
11902 });
11903 }
11904
11905 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11906 self.nav_history = nav_history;
11907 }
11908
11909 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11910 self.nav_history.as_ref()
11911 }
11912
11913 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11914 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11915 }
11916
11917 fn push_to_nav_history(
11918 &mut self,
11919 cursor_anchor: Anchor,
11920 new_position: Option<Point>,
11921 is_deactivate: bool,
11922 cx: &mut Context<Self>,
11923 ) {
11924 if let Some(nav_history) = self.nav_history.as_mut() {
11925 let buffer = self.buffer.read(cx).read(cx);
11926 let cursor_position = cursor_anchor.to_point(&buffer);
11927 let scroll_state = self.scroll_manager.anchor();
11928 let scroll_top_row = scroll_state.top_row(&buffer);
11929 drop(buffer);
11930
11931 if let Some(new_position) = new_position {
11932 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11933 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11934 return;
11935 }
11936 }
11937
11938 nav_history.push(
11939 Some(NavigationData {
11940 cursor_anchor,
11941 cursor_position,
11942 scroll_anchor: scroll_state,
11943 scroll_top_row,
11944 }),
11945 cx,
11946 );
11947 cx.emit(EditorEvent::PushedToNavHistory {
11948 anchor: cursor_anchor,
11949 is_deactivate,
11950 })
11951 }
11952 }
11953
11954 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11955 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11956 let buffer = self.buffer.read(cx).snapshot(cx);
11957 let mut selection = self.selections.first::<usize>(cx);
11958 selection.set_head(buffer.len(), SelectionGoal::None);
11959 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11960 s.select(vec![selection]);
11961 });
11962 }
11963
11964 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11965 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11966 let end = self.buffer.read(cx).read(cx).len();
11967 self.change_selections(None, window, cx, |s| {
11968 s.select_ranges(vec![0..end]);
11969 });
11970 }
11971
11972 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11973 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11974 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11975 let mut selections = self.selections.all::<Point>(cx);
11976 let max_point = display_map.buffer_snapshot.max_point();
11977 for selection in &mut selections {
11978 let rows = selection.spanned_rows(true, &display_map);
11979 selection.start = Point::new(rows.start.0, 0);
11980 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11981 selection.reversed = false;
11982 }
11983 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11984 s.select(selections);
11985 });
11986 }
11987
11988 pub fn split_selection_into_lines(
11989 &mut self,
11990 _: &SplitSelectionIntoLines,
11991 window: &mut Window,
11992 cx: &mut Context<Self>,
11993 ) {
11994 let selections = self
11995 .selections
11996 .all::<Point>(cx)
11997 .into_iter()
11998 .map(|selection| selection.start..selection.end)
11999 .collect::<Vec<_>>();
12000 self.unfold_ranges(&selections, true, true, cx);
12001
12002 let mut new_selection_ranges = Vec::new();
12003 {
12004 let buffer = self.buffer.read(cx).read(cx);
12005 for selection in selections {
12006 for row in selection.start.row..selection.end.row {
12007 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
12008 new_selection_ranges.push(cursor..cursor);
12009 }
12010
12011 let is_multiline_selection = selection.start.row != selection.end.row;
12012 // Don't insert last one if it's a multi-line selection ending at the start of a line,
12013 // so this action feels more ergonomic when paired with other selection operations
12014 let should_skip_last = is_multiline_selection && selection.end.column == 0;
12015 if !should_skip_last {
12016 new_selection_ranges.push(selection.end..selection.end);
12017 }
12018 }
12019 }
12020 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12021 s.select_ranges(new_selection_ranges);
12022 });
12023 }
12024
12025 pub fn add_selection_above(
12026 &mut self,
12027 _: &AddSelectionAbove,
12028 window: &mut Window,
12029 cx: &mut Context<Self>,
12030 ) {
12031 self.add_selection(true, window, cx);
12032 }
12033
12034 pub fn add_selection_below(
12035 &mut self,
12036 _: &AddSelectionBelow,
12037 window: &mut Window,
12038 cx: &mut Context<Self>,
12039 ) {
12040 self.add_selection(false, window, cx);
12041 }
12042
12043 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12044 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12045
12046 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12047 let mut selections = self.selections.all::<Point>(cx);
12048 let text_layout_details = self.text_layout_details(window);
12049 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12050 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12051 let range = oldest_selection.display_range(&display_map).sorted();
12052
12053 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12054 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12055 let positions = start_x.min(end_x)..start_x.max(end_x);
12056
12057 selections.clear();
12058 let mut stack = Vec::new();
12059 for row in range.start.row().0..=range.end.row().0 {
12060 if let Some(selection) = self.selections.build_columnar_selection(
12061 &display_map,
12062 DisplayRow(row),
12063 &positions,
12064 oldest_selection.reversed,
12065 &text_layout_details,
12066 ) {
12067 stack.push(selection.id);
12068 selections.push(selection);
12069 }
12070 }
12071
12072 if above {
12073 stack.reverse();
12074 }
12075
12076 AddSelectionsState { above, stack }
12077 });
12078
12079 let last_added_selection = *state.stack.last().unwrap();
12080 let mut new_selections = Vec::new();
12081 if above == state.above {
12082 let end_row = if above {
12083 DisplayRow(0)
12084 } else {
12085 display_map.max_point().row()
12086 };
12087
12088 'outer: for selection in selections {
12089 if selection.id == last_added_selection {
12090 let range = selection.display_range(&display_map).sorted();
12091 debug_assert_eq!(range.start.row(), range.end.row());
12092 let mut row = range.start.row();
12093 let positions =
12094 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12095 px(start)..px(end)
12096 } else {
12097 let start_x =
12098 display_map.x_for_display_point(range.start, &text_layout_details);
12099 let end_x =
12100 display_map.x_for_display_point(range.end, &text_layout_details);
12101 start_x.min(end_x)..start_x.max(end_x)
12102 };
12103
12104 while row != end_row {
12105 if above {
12106 row.0 -= 1;
12107 } else {
12108 row.0 += 1;
12109 }
12110
12111 if let Some(new_selection) = self.selections.build_columnar_selection(
12112 &display_map,
12113 row,
12114 &positions,
12115 selection.reversed,
12116 &text_layout_details,
12117 ) {
12118 state.stack.push(new_selection.id);
12119 if above {
12120 new_selections.push(new_selection);
12121 new_selections.push(selection);
12122 } else {
12123 new_selections.push(selection);
12124 new_selections.push(new_selection);
12125 }
12126
12127 continue 'outer;
12128 }
12129 }
12130 }
12131
12132 new_selections.push(selection);
12133 }
12134 } else {
12135 new_selections = selections;
12136 new_selections.retain(|s| s.id != last_added_selection);
12137 state.stack.pop();
12138 }
12139
12140 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12141 s.select(new_selections);
12142 });
12143 if state.stack.len() > 1 {
12144 self.add_selections_state = Some(state);
12145 }
12146 }
12147
12148 fn select_match_ranges(
12149 &mut self,
12150 range: Range<usize>,
12151 reversed: bool,
12152 replace_newest: bool,
12153 auto_scroll: Option<Autoscroll>,
12154 window: &mut Window,
12155 cx: &mut Context<Editor>,
12156 ) {
12157 self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12158 self.change_selections(auto_scroll, window, cx, |s| {
12159 if replace_newest {
12160 s.delete(s.newest_anchor().id);
12161 }
12162 if reversed {
12163 s.insert_range(range.end..range.start);
12164 } else {
12165 s.insert_range(range);
12166 }
12167 });
12168 }
12169
12170 pub fn select_next_match_internal(
12171 &mut self,
12172 display_map: &DisplaySnapshot,
12173 replace_newest: bool,
12174 autoscroll: Option<Autoscroll>,
12175 window: &mut Window,
12176 cx: &mut Context<Self>,
12177 ) -> Result<()> {
12178 let buffer = &display_map.buffer_snapshot;
12179 let mut selections = self.selections.all::<usize>(cx);
12180 if let Some(mut select_next_state) = self.select_next_state.take() {
12181 let query = &select_next_state.query;
12182 if !select_next_state.done {
12183 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12184 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12185 let mut next_selected_range = None;
12186
12187 let bytes_after_last_selection =
12188 buffer.bytes_in_range(last_selection.end..buffer.len());
12189 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12190 let query_matches = query
12191 .stream_find_iter(bytes_after_last_selection)
12192 .map(|result| (last_selection.end, result))
12193 .chain(
12194 query
12195 .stream_find_iter(bytes_before_first_selection)
12196 .map(|result| (0, result)),
12197 );
12198
12199 for (start_offset, query_match) in query_matches {
12200 let query_match = query_match.unwrap(); // can only fail due to I/O
12201 let offset_range =
12202 start_offset + query_match.start()..start_offset + query_match.end();
12203 let display_range = offset_range.start.to_display_point(display_map)
12204 ..offset_range.end.to_display_point(display_map);
12205
12206 if !select_next_state.wordwise
12207 || (!movement::is_inside_word(display_map, display_range.start)
12208 && !movement::is_inside_word(display_map, display_range.end))
12209 {
12210 // TODO: This is n^2, because we might check all the selections
12211 if !selections
12212 .iter()
12213 .any(|selection| selection.range().overlaps(&offset_range))
12214 {
12215 next_selected_range = Some(offset_range);
12216 break;
12217 }
12218 }
12219 }
12220
12221 if let Some(next_selected_range) = next_selected_range {
12222 self.select_match_ranges(
12223 next_selected_range,
12224 last_selection.reversed,
12225 replace_newest,
12226 autoscroll,
12227 window,
12228 cx,
12229 );
12230 } else {
12231 select_next_state.done = true;
12232 }
12233 }
12234
12235 self.select_next_state = Some(select_next_state);
12236 } else {
12237 let mut only_carets = true;
12238 let mut same_text_selected = true;
12239 let mut selected_text = None;
12240
12241 let mut selections_iter = selections.iter().peekable();
12242 while let Some(selection) = selections_iter.next() {
12243 if selection.start != selection.end {
12244 only_carets = false;
12245 }
12246
12247 if same_text_selected {
12248 if selected_text.is_none() {
12249 selected_text =
12250 Some(buffer.text_for_range(selection.range()).collect::<String>());
12251 }
12252
12253 if let Some(next_selection) = selections_iter.peek() {
12254 if next_selection.range().len() == selection.range().len() {
12255 let next_selected_text = buffer
12256 .text_for_range(next_selection.range())
12257 .collect::<String>();
12258 if Some(next_selected_text) != selected_text {
12259 same_text_selected = false;
12260 selected_text = None;
12261 }
12262 } else {
12263 same_text_selected = false;
12264 selected_text = None;
12265 }
12266 }
12267 }
12268 }
12269
12270 if only_carets {
12271 for selection in &mut selections {
12272 let word_range = movement::surrounding_word(
12273 display_map,
12274 selection.start.to_display_point(display_map),
12275 );
12276 selection.start = word_range.start.to_offset(display_map, Bias::Left);
12277 selection.end = word_range.end.to_offset(display_map, Bias::Left);
12278 selection.goal = SelectionGoal::None;
12279 selection.reversed = false;
12280 self.select_match_ranges(
12281 selection.start..selection.end,
12282 selection.reversed,
12283 replace_newest,
12284 autoscroll,
12285 window,
12286 cx,
12287 );
12288 }
12289
12290 if selections.len() == 1 {
12291 let selection = selections
12292 .last()
12293 .expect("ensured that there's only one selection");
12294 let query = buffer
12295 .text_for_range(selection.start..selection.end)
12296 .collect::<String>();
12297 let is_empty = query.is_empty();
12298 let select_state = SelectNextState {
12299 query: AhoCorasick::new(&[query])?,
12300 wordwise: true,
12301 done: is_empty,
12302 };
12303 self.select_next_state = Some(select_state);
12304 } else {
12305 self.select_next_state = None;
12306 }
12307 } else if let Some(selected_text) = selected_text {
12308 self.select_next_state = Some(SelectNextState {
12309 query: AhoCorasick::new(&[selected_text])?,
12310 wordwise: false,
12311 done: false,
12312 });
12313 self.select_next_match_internal(
12314 display_map,
12315 replace_newest,
12316 autoscroll,
12317 window,
12318 cx,
12319 )?;
12320 }
12321 }
12322 Ok(())
12323 }
12324
12325 pub fn select_all_matches(
12326 &mut self,
12327 _action: &SelectAllMatches,
12328 window: &mut Window,
12329 cx: &mut Context<Self>,
12330 ) -> Result<()> {
12331 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12332
12333 self.push_to_selection_history();
12334 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12335
12336 self.select_next_match_internal(&display_map, false, None, window, cx)?;
12337 let Some(select_next_state) = self.select_next_state.as_mut() else {
12338 return Ok(());
12339 };
12340 if select_next_state.done {
12341 return Ok(());
12342 }
12343
12344 let mut new_selections = Vec::new();
12345
12346 let reversed = self.selections.oldest::<usize>(cx).reversed;
12347 let buffer = &display_map.buffer_snapshot;
12348 let query_matches = select_next_state
12349 .query
12350 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12351
12352 for query_match in query_matches.into_iter() {
12353 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12354 let offset_range = if reversed {
12355 query_match.end()..query_match.start()
12356 } else {
12357 query_match.start()..query_match.end()
12358 };
12359 let display_range = offset_range.start.to_display_point(&display_map)
12360 ..offset_range.end.to_display_point(&display_map);
12361
12362 if !select_next_state.wordwise
12363 || (!movement::is_inside_word(&display_map, display_range.start)
12364 && !movement::is_inside_word(&display_map, display_range.end))
12365 {
12366 new_selections.push(offset_range.start..offset_range.end);
12367 }
12368 }
12369
12370 select_next_state.done = true;
12371 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12372 self.change_selections(None, window, cx, |selections| {
12373 selections.select_ranges(new_selections)
12374 });
12375
12376 Ok(())
12377 }
12378
12379 pub fn select_next(
12380 &mut self,
12381 action: &SelectNext,
12382 window: &mut Window,
12383 cx: &mut Context<Self>,
12384 ) -> Result<()> {
12385 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12386 self.push_to_selection_history();
12387 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12388 self.select_next_match_internal(
12389 &display_map,
12390 action.replace_newest,
12391 Some(Autoscroll::newest()),
12392 window,
12393 cx,
12394 )?;
12395 Ok(())
12396 }
12397
12398 pub fn select_previous(
12399 &mut self,
12400 action: &SelectPrevious,
12401 window: &mut Window,
12402 cx: &mut Context<Self>,
12403 ) -> Result<()> {
12404 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12405 self.push_to_selection_history();
12406 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12407 let buffer = &display_map.buffer_snapshot;
12408 let mut selections = self.selections.all::<usize>(cx);
12409 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12410 let query = &select_prev_state.query;
12411 if !select_prev_state.done {
12412 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12413 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12414 let mut next_selected_range = None;
12415 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12416 let bytes_before_last_selection =
12417 buffer.reversed_bytes_in_range(0..last_selection.start);
12418 let bytes_after_first_selection =
12419 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12420 let query_matches = query
12421 .stream_find_iter(bytes_before_last_selection)
12422 .map(|result| (last_selection.start, result))
12423 .chain(
12424 query
12425 .stream_find_iter(bytes_after_first_selection)
12426 .map(|result| (buffer.len(), result)),
12427 );
12428 for (end_offset, query_match) in query_matches {
12429 let query_match = query_match.unwrap(); // can only fail due to I/O
12430 let offset_range =
12431 end_offset - query_match.end()..end_offset - query_match.start();
12432 let display_range = offset_range.start.to_display_point(&display_map)
12433 ..offset_range.end.to_display_point(&display_map);
12434
12435 if !select_prev_state.wordwise
12436 || (!movement::is_inside_word(&display_map, display_range.start)
12437 && !movement::is_inside_word(&display_map, display_range.end))
12438 {
12439 next_selected_range = Some(offset_range);
12440 break;
12441 }
12442 }
12443
12444 if let Some(next_selected_range) = next_selected_range {
12445 self.select_match_ranges(
12446 next_selected_range,
12447 last_selection.reversed,
12448 action.replace_newest,
12449 Some(Autoscroll::newest()),
12450 window,
12451 cx,
12452 );
12453 } else {
12454 select_prev_state.done = true;
12455 }
12456 }
12457
12458 self.select_prev_state = Some(select_prev_state);
12459 } else {
12460 let mut only_carets = true;
12461 let mut same_text_selected = true;
12462 let mut selected_text = None;
12463
12464 let mut selections_iter = selections.iter().peekable();
12465 while let Some(selection) = selections_iter.next() {
12466 if selection.start != selection.end {
12467 only_carets = false;
12468 }
12469
12470 if same_text_selected {
12471 if selected_text.is_none() {
12472 selected_text =
12473 Some(buffer.text_for_range(selection.range()).collect::<String>());
12474 }
12475
12476 if let Some(next_selection) = selections_iter.peek() {
12477 if next_selection.range().len() == selection.range().len() {
12478 let next_selected_text = buffer
12479 .text_for_range(next_selection.range())
12480 .collect::<String>();
12481 if Some(next_selected_text) != selected_text {
12482 same_text_selected = false;
12483 selected_text = None;
12484 }
12485 } else {
12486 same_text_selected = false;
12487 selected_text = None;
12488 }
12489 }
12490 }
12491 }
12492
12493 if only_carets {
12494 for selection in &mut selections {
12495 let word_range = movement::surrounding_word(
12496 &display_map,
12497 selection.start.to_display_point(&display_map),
12498 );
12499 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12500 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12501 selection.goal = SelectionGoal::None;
12502 selection.reversed = false;
12503 self.select_match_ranges(
12504 selection.start..selection.end,
12505 selection.reversed,
12506 action.replace_newest,
12507 Some(Autoscroll::newest()),
12508 window,
12509 cx,
12510 );
12511 }
12512 if selections.len() == 1 {
12513 let selection = selections
12514 .last()
12515 .expect("ensured that there's only one selection");
12516 let query = buffer
12517 .text_for_range(selection.start..selection.end)
12518 .collect::<String>();
12519 let is_empty = query.is_empty();
12520 let select_state = SelectNextState {
12521 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12522 wordwise: true,
12523 done: is_empty,
12524 };
12525 self.select_prev_state = Some(select_state);
12526 } else {
12527 self.select_prev_state = None;
12528 }
12529 } else if let Some(selected_text) = selected_text {
12530 self.select_prev_state = Some(SelectNextState {
12531 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12532 wordwise: false,
12533 done: false,
12534 });
12535 self.select_previous(action, window, cx)?;
12536 }
12537 }
12538 Ok(())
12539 }
12540
12541 pub fn find_next_match(
12542 &mut self,
12543 _: &FindNextMatch,
12544 window: &mut Window,
12545 cx: &mut Context<Self>,
12546 ) -> Result<()> {
12547 let selections = self.selections.disjoint_anchors();
12548 match selections.first() {
12549 Some(first) if selections.len() >= 2 => {
12550 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12551 s.select_ranges([first.range()]);
12552 });
12553 }
12554 _ => self.select_next(
12555 &SelectNext {
12556 replace_newest: true,
12557 },
12558 window,
12559 cx,
12560 )?,
12561 }
12562 Ok(())
12563 }
12564
12565 pub fn find_previous_match(
12566 &mut self,
12567 _: &FindPreviousMatch,
12568 window: &mut Window,
12569 cx: &mut Context<Self>,
12570 ) -> Result<()> {
12571 let selections = self.selections.disjoint_anchors();
12572 match selections.last() {
12573 Some(last) if selections.len() >= 2 => {
12574 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12575 s.select_ranges([last.range()]);
12576 });
12577 }
12578 _ => self.select_previous(
12579 &SelectPrevious {
12580 replace_newest: true,
12581 },
12582 window,
12583 cx,
12584 )?,
12585 }
12586 Ok(())
12587 }
12588
12589 pub fn toggle_comments(
12590 &mut self,
12591 action: &ToggleComments,
12592 window: &mut Window,
12593 cx: &mut Context<Self>,
12594 ) {
12595 if self.read_only(cx) {
12596 return;
12597 }
12598 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12599 let text_layout_details = &self.text_layout_details(window);
12600 self.transact(window, cx, |this, window, cx| {
12601 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12602 let mut edits = Vec::new();
12603 let mut selection_edit_ranges = Vec::new();
12604 let mut last_toggled_row = None;
12605 let snapshot = this.buffer.read(cx).read(cx);
12606 let empty_str: Arc<str> = Arc::default();
12607 let mut suffixes_inserted = Vec::new();
12608 let ignore_indent = action.ignore_indent;
12609
12610 fn comment_prefix_range(
12611 snapshot: &MultiBufferSnapshot,
12612 row: MultiBufferRow,
12613 comment_prefix: &str,
12614 comment_prefix_whitespace: &str,
12615 ignore_indent: bool,
12616 ) -> Range<Point> {
12617 let indent_size = if ignore_indent {
12618 0
12619 } else {
12620 snapshot.indent_size_for_line(row).len
12621 };
12622
12623 let start = Point::new(row.0, indent_size);
12624
12625 let mut line_bytes = snapshot
12626 .bytes_in_range(start..snapshot.max_point())
12627 .flatten()
12628 .copied();
12629
12630 // If this line currently begins with the line comment prefix, then record
12631 // the range containing the prefix.
12632 if line_bytes
12633 .by_ref()
12634 .take(comment_prefix.len())
12635 .eq(comment_prefix.bytes())
12636 {
12637 // Include any whitespace that matches the comment prefix.
12638 let matching_whitespace_len = line_bytes
12639 .zip(comment_prefix_whitespace.bytes())
12640 .take_while(|(a, b)| a == b)
12641 .count() as u32;
12642 let end = Point::new(
12643 start.row,
12644 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12645 );
12646 start..end
12647 } else {
12648 start..start
12649 }
12650 }
12651
12652 fn comment_suffix_range(
12653 snapshot: &MultiBufferSnapshot,
12654 row: MultiBufferRow,
12655 comment_suffix: &str,
12656 comment_suffix_has_leading_space: bool,
12657 ) -> Range<Point> {
12658 let end = Point::new(row.0, snapshot.line_len(row));
12659 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12660
12661 let mut line_end_bytes = snapshot
12662 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12663 .flatten()
12664 .copied();
12665
12666 let leading_space_len = if suffix_start_column > 0
12667 && line_end_bytes.next() == Some(b' ')
12668 && comment_suffix_has_leading_space
12669 {
12670 1
12671 } else {
12672 0
12673 };
12674
12675 // If this line currently begins with the line comment prefix, then record
12676 // the range containing the prefix.
12677 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12678 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12679 start..end
12680 } else {
12681 end..end
12682 }
12683 }
12684
12685 // TODO: Handle selections that cross excerpts
12686 for selection in &mut selections {
12687 let start_column = snapshot
12688 .indent_size_for_line(MultiBufferRow(selection.start.row))
12689 .len;
12690 let language = if let Some(language) =
12691 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12692 {
12693 language
12694 } else {
12695 continue;
12696 };
12697
12698 selection_edit_ranges.clear();
12699
12700 // If multiple selections contain a given row, avoid processing that
12701 // row more than once.
12702 let mut start_row = MultiBufferRow(selection.start.row);
12703 if last_toggled_row == Some(start_row) {
12704 start_row = start_row.next_row();
12705 }
12706 let end_row =
12707 if selection.end.row > selection.start.row && selection.end.column == 0 {
12708 MultiBufferRow(selection.end.row - 1)
12709 } else {
12710 MultiBufferRow(selection.end.row)
12711 };
12712 last_toggled_row = Some(end_row);
12713
12714 if start_row > end_row {
12715 continue;
12716 }
12717
12718 // If the language has line comments, toggle those.
12719 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12720
12721 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12722 if ignore_indent {
12723 full_comment_prefixes = full_comment_prefixes
12724 .into_iter()
12725 .map(|s| Arc::from(s.trim_end()))
12726 .collect();
12727 }
12728
12729 if !full_comment_prefixes.is_empty() {
12730 let first_prefix = full_comment_prefixes
12731 .first()
12732 .expect("prefixes is non-empty");
12733 let prefix_trimmed_lengths = full_comment_prefixes
12734 .iter()
12735 .map(|p| p.trim_end_matches(' ').len())
12736 .collect::<SmallVec<[usize; 4]>>();
12737
12738 let mut all_selection_lines_are_comments = true;
12739
12740 for row in start_row.0..=end_row.0 {
12741 let row = MultiBufferRow(row);
12742 if start_row < end_row && snapshot.is_line_blank(row) {
12743 continue;
12744 }
12745
12746 let prefix_range = full_comment_prefixes
12747 .iter()
12748 .zip(prefix_trimmed_lengths.iter().copied())
12749 .map(|(prefix, trimmed_prefix_len)| {
12750 comment_prefix_range(
12751 snapshot.deref(),
12752 row,
12753 &prefix[..trimmed_prefix_len],
12754 &prefix[trimmed_prefix_len..],
12755 ignore_indent,
12756 )
12757 })
12758 .max_by_key(|range| range.end.column - range.start.column)
12759 .expect("prefixes is non-empty");
12760
12761 if prefix_range.is_empty() {
12762 all_selection_lines_are_comments = false;
12763 }
12764
12765 selection_edit_ranges.push(prefix_range);
12766 }
12767
12768 if all_selection_lines_are_comments {
12769 edits.extend(
12770 selection_edit_ranges
12771 .iter()
12772 .cloned()
12773 .map(|range| (range, empty_str.clone())),
12774 );
12775 } else {
12776 let min_column = selection_edit_ranges
12777 .iter()
12778 .map(|range| range.start.column)
12779 .min()
12780 .unwrap_or(0);
12781 edits.extend(selection_edit_ranges.iter().map(|range| {
12782 let position = Point::new(range.start.row, min_column);
12783 (position..position, first_prefix.clone())
12784 }));
12785 }
12786 } else if let Some((full_comment_prefix, comment_suffix)) =
12787 language.block_comment_delimiters()
12788 {
12789 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12790 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12791 let prefix_range = comment_prefix_range(
12792 snapshot.deref(),
12793 start_row,
12794 comment_prefix,
12795 comment_prefix_whitespace,
12796 ignore_indent,
12797 );
12798 let suffix_range = comment_suffix_range(
12799 snapshot.deref(),
12800 end_row,
12801 comment_suffix.trim_start_matches(' '),
12802 comment_suffix.starts_with(' '),
12803 );
12804
12805 if prefix_range.is_empty() || suffix_range.is_empty() {
12806 edits.push((
12807 prefix_range.start..prefix_range.start,
12808 full_comment_prefix.clone(),
12809 ));
12810 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12811 suffixes_inserted.push((end_row, comment_suffix.len()));
12812 } else {
12813 edits.push((prefix_range, empty_str.clone()));
12814 edits.push((suffix_range, empty_str.clone()));
12815 }
12816 } else {
12817 continue;
12818 }
12819 }
12820
12821 drop(snapshot);
12822 this.buffer.update(cx, |buffer, cx| {
12823 buffer.edit(edits, None, cx);
12824 });
12825
12826 // Adjust selections so that they end before any comment suffixes that
12827 // were inserted.
12828 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12829 let mut selections = this.selections.all::<Point>(cx);
12830 let snapshot = this.buffer.read(cx).read(cx);
12831 for selection in &mut selections {
12832 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12833 match row.cmp(&MultiBufferRow(selection.end.row)) {
12834 Ordering::Less => {
12835 suffixes_inserted.next();
12836 continue;
12837 }
12838 Ordering::Greater => break,
12839 Ordering::Equal => {
12840 if selection.end.column == snapshot.line_len(row) {
12841 if selection.is_empty() {
12842 selection.start.column -= suffix_len as u32;
12843 }
12844 selection.end.column -= suffix_len as u32;
12845 }
12846 break;
12847 }
12848 }
12849 }
12850 }
12851
12852 drop(snapshot);
12853 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12854 s.select(selections)
12855 });
12856
12857 let selections = this.selections.all::<Point>(cx);
12858 let selections_on_single_row = selections.windows(2).all(|selections| {
12859 selections[0].start.row == selections[1].start.row
12860 && selections[0].end.row == selections[1].end.row
12861 && selections[0].start.row == selections[0].end.row
12862 });
12863 let selections_selecting = selections
12864 .iter()
12865 .any(|selection| selection.start != selection.end);
12866 let advance_downwards = action.advance_downwards
12867 && selections_on_single_row
12868 && !selections_selecting
12869 && !matches!(this.mode, EditorMode::SingleLine { .. });
12870
12871 if advance_downwards {
12872 let snapshot = this.buffer.read(cx).snapshot(cx);
12873
12874 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12875 s.move_cursors_with(|display_snapshot, display_point, _| {
12876 let mut point = display_point.to_point(display_snapshot);
12877 point.row += 1;
12878 point = snapshot.clip_point(point, Bias::Left);
12879 let display_point = point.to_display_point(display_snapshot);
12880 let goal = SelectionGoal::HorizontalPosition(
12881 display_snapshot
12882 .x_for_display_point(display_point, text_layout_details)
12883 .into(),
12884 );
12885 (display_point, goal)
12886 })
12887 });
12888 }
12889 });
12890 }
12891
12892 pub fn select_enclosing_symbol(
12893 &mut self,
12894 _: &SelectEnclosingSymbol,
12895 window: &mut Window,
12896 cx: &mut Context<Self>,
12897 ) {
12898 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12899
12900 let buffer = self.buffer.read(cx).snapshot(cx);
12901 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12902
12903 fn update_selection(
12904 selection: &Selection<usize>,
12905 buffer_snap: &MultiBufferSnapshot,
12906 ) -> Option<Selection<usize>> {
12907 let cursor = selection.head();
12908 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12909 for symbol in symbols.iter().rev() {
12910 let start = symbol.range.start.to_offset(buffer_snap);
12911 let end = symbol.range.end.to_offset(buffer_snap);
12912 let new_range = start..end;
12913 if start < selection.start || end > selection.end {
12914 return Some(Selection {
12915 id: selection.id,
12916 start: new_range.start,
12917 end: new_range.end,
12918 goal: SelectionGoal::None,
12919 reversed: selection.reversed,
12920 });
12921 }
12922 }
12923 None
12924 }
12925
12926 let mut selected_larger_symbol = false;
12927 let new_selections = old_selections
12928 .iter()
12929 .map(|selection| match update_selection(selection, &buffer) {
12930 Some(new_selection) => {
12931 if new_selection.range() != selection.range() {
12932 selected_larger_symbol = true;
12933 }
12934 new_selection
12935 }
12936 None => selection.clone(),
12937 })
12938 .collect::<Vec<_>>();
12939
12940 if selected_larger_symbol {
12941 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12942 s.select(new_selections);
12943 });
12944 }
12945 }
12946
12947 pub fn select_larger_syntax_node(
12948 &mut self,
12949 _: &SelectLargerSyntaxNode,
12950 window: &mut Window,
12951 cx: &mut Context<Self>,
12952 ) {
12953 let Some(visible_row_count) = self.visible_row_count() else {
12954 return;
12955 };
12956 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12957 if old_selections.is_empty() {
12958 return;
12959 }
12960
12961 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12962
12963 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12964 let buffer = self.buffer.read(cx).snapshot(cx);
12965
12966 let mut selected_larger_node = false;
12967 let mut new_selections = old_selections
12968 .iter()
12969 .map(|selection| {
12970 let old_range = selection.start..selection.end;
12971
12972 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12973 // manually select word at selection
12974 if ["string_content", "inline"].contains(&node.kind()) {
12975 let word_range = {
12976 let display_point = buffer
12977 .offset_to_point(old_range.start)
12978 .to_display_point(&display_map);
12979 let Range { start, end } =
12980 movement::surrounding_word(&display_map, display_point);
12981 start.to_point(&display_map).to_offset(&buffer)
12982 ..end.to_point(&display_map).to_offset(&buffer)
12983 };
12984 // ignore if word is already selected
12985 if !word_range.is_empty() && old_range != word_range {
12986 let last_word_range = {
12987 let display_point = buffer
12988 .offset_to_point(old_range.end)
12989 .to_display_point(&display_map);
12990 let Range { start, end } =
12991 movement::surrounding_word(&display_map, display_point);
12992 start.to_point(&display_map).to_offset(&buffer)
12993 ..end.to_point(&display_map).to_offset(&buffer)
12994 };
12995 // only select word if start and end point belongs to same word
12996 if word_range == last_word_range {
12997 selected_larger_node = true;
12998 return Selection {
12999 id: selection.id,
13000 start: word_range.start,
13001 end: word_range.end,
13002 goal: SelectionGoal::None,
13003 reversed: selection.reversed,
13004 };
13005 }
13006 }
13007 }
13008 }
13009
13010 let mut new_range = old_range.clone();
13011 while let Some((_node, containing_range)) =
13012 buffer.syntax_ancestor(new_range.clone())
13013 {
13014 new_range = match containing_range {
13015 MultiOrSingleBufferOffsetRange::Single(_) => break,
13016 MultiOrSingleBufferOffsetRange::Multi(range) => range,
13017 };
13018 if !display_map.intersects_fold(new_range.start)
13019 && !display_map.intersects_fold(new_range.end)
13020 {
13021 break;
13022 }
13023 }
13024
13025 selected_larger_node |= new_range != old_range;
13026 Selection {
13027 id: selection.id,
13028 start: new_range.start,
13029 end: new_range.end,
13030 goal: SelectionGoal::None,
13031 reversed: selection.reversed,
13032 }
13033 })
13034 .collect::<Vec<_>>();
13035
13036 if !selected_larger_node {
13037 return; // don't put this call in the history
13038 }
13039
13040 // scroll based on transformation done to the last selection created by the user
13041 let (last_old, last_new) = old_selections
13042 .last()
13043 .zip(new_selections.last().cloned())
13044 .expect("old_selections isn't empty");
13045
13046 // revert selection
13047 let is_selection_reversed = {
13048 let should_newest_selection_be_reversed = last_old.start != last_new.start;
13049 new_selections.last_mut().expect("checked above").reversed =
13050 should_newest_selection_be_reversed;
13051 should_newest_selection_be_reversed
13052 };
13053
13054 if selected_larger_node {
13055 self.select_syntax_node_history.disable_clearing = true;
13056 self.change_selections(None, window, cx, |s| {
13057 s.select(new_selections.clone());
13058 });
13059 self.select_syntax_node_history.disable_clearing = false;
13060 }
13061
13062 let start_row = last_new.start.to_display_point(&display_map).row().0;
13063 let end_row = last_new.end.to_display_point(&display_map).row().0;
13064 let selection_height = end_row - start_row + 1;
13065 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13066
13067 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13068 let scroll_behavior = if fits_on_the_screen {
13069 self.request_autoscroll(Autoscroll::fit(), cx);
13070 SelectSyntaxNodeScrollBehavior::FitSelection
13071 } else if is_selection_reversed {
13072 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13073 SelectSyntaxNodeScrollBehavior::CursorTop
13074 } else {
13075 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13076 SelectSyntaxNodeScrollBehavior::CursorBottom
13077 };
13078
13079 self.select_syntax_node_history.push((
13080 old_selections,
13081 scroll_behavior,
13082 is_selection_reversed,
13083 ));
13084 }
13085
13086 pub fn select_smaller_syntax_node(
13087 &mut self,
13088 _: &SelectSmallerSyntaxNode,
13089 window: &mut Window,
13090 cx: &mut Context<Self>,
13091 ) {
13092 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13093
13094 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13095 self.select_syntax_node_history.pop()
13096 {
13097 if let Some(selection) = selections.last_mut() {
13098 selection.reversed = is_selection_reversed;
13099 }
13100
13101 self.select_syntax_node_history.disable_clearing = true;
13102 self.change_selections(None, window, cx, |s| {
13103 s.select(selections.to_vec());
13104 });
13105 self.select_syntax_node_history.disable_clearing = false;
13106
13107 match scroll_behavior {
13108 SelectSyntaxNodeScrollBehavior::CursorTop => {
13109 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13110 }
13111 SelectSyntaxNodeScrollBehavior::FitSelection => {
13112 self.request_autoscroll(Autoscroll::fit(), cx);
13113 }
13114 SelectSyntaxNodeScrollBehavior::CursorBottom => {
13115 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13116 }
13117 }
13118 }
13119 }
13120
13121 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13122 if !EditorSettings::get_global(cx).gutter.runnables {
13123 self.clear_tasks();
13124 return Task::ready(());
13125 }
13126 let project = self.project.as_ref().map(Entity::downgrade);
13127 let task_sources = self.lsp_task_sources(cx);
13128 cx.spawn_in(window, async move |editor, cx| {
13129 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13130 let Some(project) = project.and_then(|p| p.upgrade()) else {
13131 return;
13132 };
13133 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13134 this.display_map.update(cx, |map, cx| map.snapshot(cx))
13135 }) else {
13136 return;
13137 };
13138
13139 let hide_runnables = project
13140 .update(cx, |project, cx| {
13141 // Do not display any test indicators in non-dev server remote projects.
13142 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13143 })
13144 .unwrap_or(true);
13145 if hide_runnables {
13146 return;
13147 }
13148 let new_rows =
13149 cx.background_spawn({
13150 let snapshot = display_snapshot.clone();
13151 async move {
13152 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13153 }
13154 })
13155 .await;
13156 let Ok(lsp_tasks) =
13157 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13158 else {
13159 return;
13160 };
13161 let lsp_tasks = lsp_tasks.await;
13162
13163 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13164 lsp_tasks
13165 .into_iter()
13166 .flat_map(|(kind, tasks)| {
13167 tasks.into_iter().filter_map(move |(location, task)| {
13168 Some((kind.clone(), location?, task))
13169 })
13170 })
13171 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13172 let buffer = location.target.buffer;
13173 let buffer_snapshot = buffer.read(cx).snapshot();
13174 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13175 |(excerpt_id, snapshot, _)| {
13176 if snapshot.remote_id() == buffer_snapshot.remote_id() {
13177 display_snapshot
13178 .buffer_snapshot
13179 .anchor_in_excerpt(excerpt_id, location.target.range.start)
13180 } else {
13181 None
13182 }
13183 },
13184 );
13185 if let Some(offset) = offset {
13186 let task_buffer_range =
13187 location.target.range.to_point(&buffer_snapshot);
13188 let context_buffer_range =
13189 task_buffer_range.to_offset(&buffer_snapshot);
13190 let context_range = BufferOffset(context_buffer_range.start)
13191 ..BufferOffset(context_buffer_range.end);
13192
13193 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13194 .or_insert_with(|| RunnableTasks {
13195 templates: Vec::new(),
13196 offset,
13197 column: task_buffer_range.start.column,
13198 extra_variables: HashMap::default(),
13199 context_range,
13200 })
13201 .templates
13202 .push((kind, task.original_task().clone()));
13203 }
13204
13205 acc
13206 })
13207 }) else {
13208 return;
13209 };
13210
13211 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13212 editor
13213 .update(cx, |editor, _| {
13214 editor.clear_tasks();
13215 for (key, mut value) in rows {
13216 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13217 value.templates.extend(lsp_tasks.templates);
13218 }
13219
13220 editor.insert_tasks(key, value);
13221 }
13222 for (key, value) in lsp_tasks_by_rows {
13223 editor.insert_tasks(key, value);
13224 }
13225 })
13226 .ok();
13227 })
13228 }
13229 fn fetch_runnable_ranges(
13230 snapshot: &DisplaySnapshot,
13231 range: Range<Anchor>,
13232 ) -> Vec<language::RunnableRange> {
13233 snapshot.buffer_snapshot.runnable_ranges(range).collect()
13234 }
13235
13236 fn runnable_rows(
13237 project: Entity<Project>,
13238 snapshot: DisplaySnapshot,
13239 runnable_ranges: Vec<RunnableRange>,
13240 mut cx: AsyncWindowContext,
13241 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13242 runnable_ranges
13243 .into_iter()
13244 .filter_map(|mut runnable| {
13245 let tasks = cx
13246 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13247 .ok()?;
13248 if tasks.is_empty() {
13249 return None;
13250 }
13251
13252 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13253
13254 let row = snapshot
13255 .buffer_snapshot
13256 .buffer_line_for_row(MultiBufferRow(point.row))?
13257 .1
13258 .start
13259 .row;
13260
13261 let context_range =
13262 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13263 Some((
13264 (runnable.buffer_id, row),
13265 RunnableTasks {
13266 templates: tasks,
13267 offset: snapshot
13268 .buffer_snapshot
13269 .anchor_before(runnable.run_range.start),
13270 context_range,
13271 column: point.column,
13272 extra_variables: runnable.extra_captures,
13273 },
13274 ))
13275 })
13276 .collect()
13277 }
13278
13279 fn templates_with_tags(
13280 project: &Entity<Project>,
13281 runnable: &mut Runnable,
13282 cx: &mut App,
13283 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13284 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13285 let (worktree_id, file) = project
13286 .buffer_for_id(runnable.buffer, cx)
13287 .and_then(|buffer| buffer.read(cx).file())
13288 .map(|file| (file.worktree_id(cx), file.clone()))
13289 .unzip();
13290
13291 (
13292 project.task_store().read(cx).task_inventory().cloned(),
13293 worktree_id,
13294 file,
13295 )
13296 });
13297
13298 let mut templates_with_tags = mem::take(&mut runnable.tags)
13299 .into_iter()
13300 .flat_map(|RunnableTag(tag)| {
13301 inventory
13302 .as_ref()
13303 .into_iter()
13304 .flat_map(|inventory| {
13305 inventory.read(cx).list_tasks(
13306 file.clone(),
13307 Some(runnable.language.clone()),
13308 worktree_id,
13309 cx,
13310 )
13311 })
13312 .filter(move |(_, template)| {
13313 template.tags.iter().any(|source_tag| source_tag == &tag)
13314 })
13315 })
13316 .sorted_by_key(|(kind, _)| kind.to_owned())
13317 .collect::<Vec<_>>();
13318 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13319 // Strongest source wins; if we have worktree tag binding, prefer that to
13320 // global and language bindings;
13321 // if we have a global binding, prefer that to language binding.
13322 let first_mismatch = templates_with_tags
13323 .iter()
13324 .position(|(tag_source, _)| tag_source != leading_tag_source);
13325 if let Some(index) = first_mismatch {
13326 templates_with_tags.truncate(index);
13327 }
13328 }
13329
13330 templates_with_tags
13331 }
13332
13333 pub fn move_to_enclosing_bracket(
13334 &mut self,
13335 _: &MoveToEnclosingBracket,
13336 window: &mut Window,
13337 cx: &mut Context<Self>,
13338 ) {
13339 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13340 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13341 s.move_offsets_with(|snapshot, selection| {
13342 let Some(enclosing_bracket_ranges) =
13343 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13344 else {
13345 return;
13346 };
13347
13348 let mut best_length = usize::MAX;
13349 let mut best_inside = false;
13350 let mut best_in_bracket_range = false;
13351 let mut best_destination = None;
13352 for (open, close) in enclosing_bracket_ranges {
13353 let close = close.to_inclusive();
13354 let length = close.end() - open.start;
13355 let inside = selection.start >= open.end && selection.end <= *close.start();
13356 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13357 || close.contains(&selection.head());
13358
13359 // If best is next to a bracket and current isn't, skip
13360 if !in_bracket_range && best_in_bracket_range {
13361 continue;
13362 }
13363
13364 // Prefer smaller lengths unless best is inside and current isn't
13365 if length > best_length && (best_inside || !inside) {
13366 continue;
13367 }
13368
13369 best_length = length;
13370 best_inside = inside;
13371 best_in_bracket_range = in_bracket_range;
13372 best_destination = Some(
13373 if close.contains(&selection.start) && close.contains(&selection.end) {
13374 if inside { open.end } else { open.start }
13375 } else if inside {
13376 *close.start()
13377 } else {
13378 *close.end()
13379 },
13380 );
13381 }
13382
13383 if let Some(destination) = best_destination {
13384 selection.collapse_to(destination, SelectionGoal::None);
13385 }
13386 })
13387 });
13388 }
13389
13390 pub fn undo_selection(
13391 &mut self,
13392 _: &UndoSelection,
13393 window: &mut Window,
13394 cx: &mut Context<Self>,
13395 ) {
13396 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13397 self.end_selection(window, cx);
13398 self.selection_history.mode = SelectionHistoryMode::Undoing;
13399 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13400 self.change_selections(None, window, cx, |s| {
13401 s.select_anchors(entry.selections.to_vec())
13402 });
13403 self.select_next_state = entry.select_next_state;
13404 self.select_prev_state = entry.select_prev_state;
13405 self.add_selections_state = entry.add_selections_state;
13406 self.request_autoscroll(Autoscroll::newest(), cx);
13407 }
13408 self.selection_history.mode = SelectionHistoryMode::Normal;
13409 }
13410
13411 pub fn redo_selection(
13412 &mut self,
13413 _: &RedoSelection,
13414 window: &mut Window,
13415 cx: &mut Context<Self>,
13416 ) {
13417 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13418 self.end_selection(window, cx);
13419 self.selection_history.mode = SelectionHistoryMode::Redoing;
13420 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13421 self.change_selections(None, window, cx, |s| {
13422 s.select_anchors(entry.selections.to_vec())
13423 });
13424 self.select_next_state = entry.select_next_state;
13425 self.select_prev_state = entry.select_prev_state;
13426 self.add_selections_state = entry.add_selections_state;
13427 self.request_autoscroll(Autoscroll::newest(), cx);
13428 }
13429 self.selection_history.mode = SelectionHistoryMode::Normal;
13430 }
13431
13432 pub fn expand_excerpts(
13433 &mut self,
13434 action: &ExpandExcerpts,
13435 _: &mut Window,
13436 cx: &mut Context<Self>,
13437 ) {
13438 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13439 }
13440
13441 pub fn expand_excerpts_down(
13442 &mut self,
13443 action: &ExpandExcerptsDown,
13444 _: &mut Window,
13445 cx: &mut Context<Self>,
13446 ) {
13447 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13448 }
13449
13450 pub fn expand_excerpts_up(
13451 &mut self,
13452 action: &ExpandExcerptsUp,
13453 _: &mut Window,
13454 cx: &mut Context<Self>,
13455 ) {
13456 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13457 }
13458
13459 pub fn expand_excerpts_for_direction(
13460 &mut self,
13461 lines: u32,
13462 direction: ExpandExcerptDirection,
13463
13464 cx: &mut Context<Self>,
13465 ) {
13466 let selections = self.selections.disjoint_anchors();
13467
13468 let lines = if lines == 0 {
13469 EditorSettings::get_global(cx).expand_excerpt_lines
13470 } else {
13471 lines
13472 };
13473
13474 self.buffer.update(cx, |buffer, cx| {
13475 let snapshot = buffer.snapshot(cx);
13476 let mut excerpt_ids = selections
13477 .iter()
13478 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13479 .collect::<Vec<_>>();
13480 excerpt_ids.sort();
13481 excerpt_ids.dedup();
13482 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13483 })
13484 }
13485
13486 pub fn expand_excerpt(
13487 &mut self,
13488 excerpt: ExcerptId,
13489 direction: ExpandExcerptDirection,
13490 window: &mut Window,
13491 cx: &mut Context<Self>,
13492 ) {
13493 let current_scroll_position = self.scroll_position(cx);
13494 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13495 let mut should_scroll_up = false;
13496
13497 if direction == ExpandExcerptDirection::Down {
13498 let multi_buffer = self.buffer.read(cx);
13499 let snapshot = multi_buffer.snapshot(cx);
13500 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13501 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13502 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13503 let buffer_snapshot = buffer.read(cx).snapshot();
13504 let excerpt_end_row =
13505 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13506 let last_row = buffer_snapshot.max_point().row;
13507 let lines_below = last_row.saturating_sub(excerpt_end_row);
13508 should_scroll_up = lines_below >= lines_to_expand;
13509 }
13510 }
13511 }
13512 }
13513
13514 self.buffer.update(cx, |buffer, cx| {
13515 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13516 });
13517
13518 if should_scroll_up {
13519 let new_scroll_position =
13520 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13521 self.set_scroll_position(new_scroll_position, window, cx);
13522 }
13523 }
13524
13525 pub fn go_to_singleton_buffer_point(
13526 &mut self,
13527 point: Point,
13528 window: &mut Window,
13529 cx: &mut Context<Self>,
13530 ) {
13531 self.go_to_singleton_buffer_range(point..point, window, cx);
13532 }
13533
13534 pub fn go_to_singleton_buffer_range(
13535 &mut self,
13536 range: Range<Point>,
13537 window: &mut Window,
13538 cx: &mut Context<Self>,
13539 ) {
13540 let multibuffer = self.buffer().read(cx);
13541 let Some(buffer) = multibuffer.as_singleton() else {
13542 return;
13543 };
13544 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13545 return;
13546 };
13547 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13548 return;
13549 };
13550 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13551 s.select_anchor_ranges([start..end])
13552 });
13553 }
13554
13555 pub fn go_to_diagnostic(
13556 &mut self,
13557 _: &GoToDiagnostic,
13558 window: &mut Window,
13559 cx: &mut Context<Self>,
13560 ) {
13561 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13562 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13563 }
13564
13565 pub fn go_to_prev_diagnostic(
13566 &mut self,
13567 _: &GoToPreviousDiagnostic,
13568 window: &mut Window,
13569 cx: &mut Context<Self>,
13570 ) {
13571 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13572 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13573 }
13574
13575 pub fn go_to_diagnostic_impl(
13576 &mut self,
13577 direction: Direction,
13578 window: &mut Window,
13579 cx: &mut Context<Self>,
13580 ) {
13581 let buffer = self.buffer.read(cx).snapshot(cx);
13582 let selection = self.selections.newest::<usize>(cx);
13583
13584 let mut active_group_id = None;
13585 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13586 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13587 active_group_id = Some(active_group.group_id);
13588 }
13589 }
13590
13591 fn filtered(
13592 snapshot: EditorSnapshot,
13593 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13594 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13595 diagnostics
13596 .filter(|entry| entry.range.start != entry.range.end)
13597 .filter(|entry| !entry.diagnostic.is_unnecessary)
13598 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13599 }
13600
13601 let snapshot = self.snapshot(window, cx);
13602 let before = filtered(
13603 snapshot.clone(),
13604 buffer
13605 .diagnostics_in_range(0..selection.start)
13606 .filter(|entry| entry.range.start <= selection.start),
13607 );
13608 let after = filtered(
13609 snapshot,
13610 buffer
13611 .diagnostics_in_range(selection.start..buffer.len())
13612 .filter(|entry| entry.range.start >= selection.start),
13613 );
13614
13615 let mut found: Option<DiagnosticEntry<usize>> = None;
13616 if direction == Direction::Prev {
13617 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13618 {
13619 for diagnostic in prev_diagnostics.into_iter().rev() {
13620 if diagnostic.range.start != selection.start
13621 || active_group_id
13622 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13623 {
13624 found = Some(diagnostic);
13625 break 'outer;
13626 }
13627 }
13628 }
13629 } else {
13630 for diagnostic in after.chain(before) {
13631 if diagnostic.range.start != selection.start
13632 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13633 {
13634 found = Some(diagnostic);
13635 break;
13636 }
13637 }
13638 }
13639 let Some(next_diagnostic) = found else {
13640 return;
13641 };
13642
13643 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13644 return;
13645 };
13646 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13647 s.select_ranges(vec![
13648 next_diagnostic.range.start..next_diagnostic.range.start,
13649 ])
13650 });
13651 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13652 self.refresh_inline_completion(false, true, window, cx);
13653 }
13654
13655 pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13656 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13657 let snapshot = self.snapshot(window, cx);
13658 let selection = self.selections.newest::<Point>(cx);
13659 self.go_to_hunk_before_or_after_position(
13660 &snapshot,
13661 selection.head(),
13662 Direction::Next,
13663 window,
13664 cx,
13665 );
13666 }
13667
13668 pub fn go_to_hunk_before_or_after_position(
13669 &mut self,
13670 snapshot: &EditorSnapshot,
13671 position: Point,
13672 direction: Direction,
13673 window: &mut Window,
13674 cx: &mut Context<Editor>,
13675 ) {
13676 let row = if direction == Direction::Next {
13677 self.hunk_after_position(snapshot, position)
13678 .map(|hunk| hunk.row_range.start)
13679 } else {
13680 self.hunk_before_position(snapshot, position)
13681 };
13682
13683 if let Some(row) = row {
13684 let destination = Point::new(row.0, 0);
13685 let autoscroll = Autoscroll::center();
13686
13687 self.unfold_ranges(&[destination..destination], false, false, cx);
13688 self.change_selections(Some(autoscroll), window, cx, |s| {
13689 s.select_ranges([destination..destination]);
13690 });
13691 }
13692 }
13693
13694 fn hunk_after_position(
13695 &mut self,
13696 snapshot: &EditorSnapshot,
13697 position: Point,
13698 ) -> Option<MultiBufferDiffHunk> {
13699 snapshot
13700 .buffer_snapshot
13701 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13702 .find(|hunk| hunk.row_range.start.0 > position.row)
13703 .or_else(|| {
13704 snapshot
13705 .buffer_snapshot
13706 .diff_hunks_in_range(Point::zero()..position)
13707 .find(|hunk| hunk.row_range.end.0 < position.row)
13708 })
13709 }
13710
13711 fn go_to_prev_hunk(
13712 &mut self,
13713 _: &GoToPreviousHunk,
13714 window: &mut Window,
13715 cx: &mut Context<Self>,
13716 ) {
13717 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13718 let snapshot = self.snapshot(window, cx);
13719 let selection = self.selections.newest::<Point>(cx);
13720 self.go_to_hunk_before_or_after_position(
13721 &snapshot,
13722 selection.head(),
13723 Direction::Prev,
13724 window,
13725 cx,
13726 );
13727 }
13728
13729 fn hunk_before_position(
13730 &mut self,
13731 snapshot: &EditorSnapshot,
13732 position: Point,
13733 ) -> Option<MultiBufferRow> {
13734 snapshot
13735 .buffer_snapshot
13736 .diff_hunk_before(position)
13737 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13738 }
13739
13740 fn go_to_next_change(
13741 &mut self,
13742 _: &GoToNextChange,
13743 window: &mut Window,
13744 cx: &mut Context<Self>,
13745 ) {
13746 if let Some(selections) = self
13747 .change_list
13748 .next_change(1, Direction::Next)
13749 .map(|s| s.to_vec())
13750 {
13751 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13752 let map = s.display_map();
13753 s.select_display_ranges(selections.iter().map(|a| {
13754 let point = a.to_display_point(&map);
13755 point..point
13756 }))
13757 })
13758 }
13759 }
13760
13761 fn go_to_previous_change(
13762 &mut self,
13763 _: &GoToPreviousChange,
13764 window: &mut Window,
13765 cx: &mut Context<Self>,
13766 ) {
13767 if let Some(selections) = self
13768 .change_list
13769 .next_change(1, Direction::Prev)
13770 .map(|s| s.to_vec())
13771 {
13772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13773 let map = s.display_map();
13774 s.select_display_ranges(selections.iter().map(|a| {
13775 let point = a.to_display_point(&map);
13776 point..point
13777 }))
13778 })
13779 }
13780 }
13781
13782 fn go_to_line<T: 'static>(
13783 &mut self,
13784 position: Anchor,
13785 highlight_color: Option<Hsla>,
13786 window: &mut Window,
13787 cx: &mut Context<Self>,
13788 ) {
13789 let snapshot = self.snapshot(window, cx).display_snapshot;
13790 let position = position.to_point(&snapshot.buffer_snapshot);
13791 let start = snapshot
13792 .buffer_snapshot
13793 .clip_point(Point::new(position.row, 0), Bias::Left);
13794 let end = start + Point::new(1, 0);
13795 let start = snapshot.buffer_snapshot.anchor_before(start);
13796 let end = snapshot.buffer_snapshot.anchor_before(end);
13797
13798 self.highlight_rows::<T>(
13799 start..end,
13800 highlight_color
13801 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13802 Default::default(),
13803 cx,
13804 );
13805 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13806 }
13807
13808 pub fn go_to_definition(
13809 &mut self,
13810 _: &GoToDefinition,
13811 window: &mut Window,
13812 cx: &mut Context<Self>,
13813 ) -> Task<Result<Navigated>> {
13814 let definition =
13815 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13816 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13817 cx.spawn_in(window, async move |editor, cx| {
13818 if definition.await? == Navigated::Yes {
13819 return Ok(Navigated::Yes);
13820 }
13821 match fallback_strategy {
13822 GoToDefinitionFallback::None => Ok(Navigated::No),
13823 GoToDefinitionFallback::FindAllReferences => {
13824 match editor.update_in(cx, |editor, window, cx| {
13825 editor.find_all_references(&FindAllReferences, window, cx)
13826 })? {
13827 Some(references) => references.await,
13828 None => Ok(Navigated::No),
13829 }
13830 }
13831 }
13832 })
13833 }
13834
13835 pub fn go_to_declaration(
13836 &mut self,
13837 _: &GoToDeclaration,
13838 window: &mut Window,
13839 cx: &mut Context<Self>,
13840 ) -> Task<Result<Navigated>> {
13841 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13842 }
13843
13844 pub fn go_to_declaration_split(
13845 &mut self,
13846 _: &GoToDeclaration,
13847 window: &mut Window,
13848 cx: &mut Context<Self>,
13849 ) -> Task<Result<Navigated>> {
13850 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13851 }
13852
13853 pub fn go_to_implementation(
13854 &mut self,
13855 _: &GoToImplementation,
13856 window: &mut Window,
13857 cx: &mut Context<Self>,
13858 ) -> Task<Result<Navigated>> {
13859 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13860 }
13861
13862 pub fn go_to_implementation_split(
13863 &mut self,
13864 _: &GoToImplementationSplit,
13865 window: &mut Window,
13866 cx: &mut Context<Self>,
13867 ) -> Task<Result<Navigated>> {
13868 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13869 }
13870
13871 pub fn go_to_type_definition(
13872 &mut self,
13873 _: &GoToTypeDefinition,
13874 window: &mut Window,
13875 cx: &mut Context<Self>,
13876 ) -> Task<Result<Navigated>> {
13877 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13878 }
13879
13880 pub fn go_to_definition_split(
13881 &mut self,
13882 _: &GoToDefinitionSplit,
13883 window: &mut Window,
13884 cx: &mut Context<Self>,
13885 ) -> Task<Result<Navigated>> {
13886 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13887 }
13888
13889 pub fn go_to_type_definition_split(
13890 &mut self,
13891 _: &GoToTypeDefinitionSplit,
13892 window: &mut Window,
13893 cx: &mut Context<Self>,
13894 ) -> Task<Result<Navigated>> {
13895 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13896 }
13897
13898 fn go_to_definition_of_kind(
13899 &mut self,
13900 kind: GotoDefinitionKind,
13901 split: bool,
13902 window: &mut Window,
13903 cx: &mut Context<Self>,
13904 ) -> Task<Result<Navigated>> {
13905 let Some(provider) = self.semantics_provider.clone() else {
13906 return Task::ready(Ok(Navigated::No));
13907 };
13908 let head = self.selections.newest::<usize>(cx).head();
13909 let buffer = self.buffer.read(cx);
13910 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13911 text_anchor
13912 } else {
13913 return Task::ready(Ok(Navigated::No));
13914 };
13915
13916 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13917 return Task::ready(Ok(Navigated::No));
13918 };
13919
13920 cx.spawn_in(window, async move |editor, cx| {
13921 let definitions = definitions.await?;
13922 let navigated = editor
13923 .update_in(cx, |editor, window, cx| {
13924 editor.navigate_to_hover_links(
13925 Some(kind),
13926 definitions
13927 .into_iter()
13928 .filter(|location| {
13929 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13930 })
13931 .map(HoverLink::Text)
13932 .collect::<Vec<_>>(),
13933 split,
13934 window,
13935 cx,
13936 )
13937 })?
13938 .await?;
13939 anyhow::Ok(navigated)
13940 })
13941 }
13942
13943 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13944 let selection = self.selections.newest_anchor();
13945 let head = selection.head();
13946 let tail = selection.tail();
13947
13948 let Some((buffer, start_position)) =
13949 self.buffer.read(cx).text_anchor_for_position(head, cx)
13950 else {
13951 return;
13952 };
13953
13954 let end_position = if head != tail {
13955 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13956 return;
13957 };
13958 Some(pos)
13959 } else {
13960 None
13961 };
13962
13963 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13964 let url = if let Some(end_pos) = end_position {
13965 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13966 } else {
13967 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13968 };
13969
13970 if let Some(url) = url {
13971 editor.update(cx, |_, cx| {
13972 cx.open_url(&url);
13973 })
13974 } else {
13975 Ok(())
13976 }
13977 });
13978
13979 url_finder.detach();
13980 }
13981
13982 pub fn open_selected_filename(
13983 &mut self,
13984 _: &OpenSelectedFilename,
13985 window: &mut Window,
13986 cx: &mut Context<Self>,
13987 ) {
13988 let Some(workspace) = self.workspace() else {
13989 return;
13990 };
13991
13992 let position = self.selections.newest_anchor().head();
13993
13994 let Some((buffer, buffer_position)) =
13995 self.buffer.read(cx).text_anchor_for_position(position, cx)
13996 else {
13997 return;
13998 };
13999
14000 let project = self.project.clone();
14001
14002 cx.spawn_in(window, async move |_, cx| {
14003 let result = find_file(&buffer, project, buffer_position, cx).await;
14004
14005 if let Some((_, path)) = result {
14006 workspace
14007 .update_in(cx, |workspace, window, cx| {
14008 workspace.open_resolved_path(path, window, cx)
14009 })?
14010 .await?;
14011 }
14012 anyhow::Ok(())
14013 })
14014 .detach();
14015 }
14016
14017 pub(crate) fn navigate_to_hover_links(
14018 &mut self,
14019 kind: Option<GotoDefinitionKind>,
14020 mut definitions: Vec<HoverLink>,
14021 split: bool,
14022 window: &mut Window,
14023 cx: &mut Context<Editor>,
14024 ) -> Task<Result<Navigated>> {
14025 // If there is one definition, just open it directly
14026 if definitions.len() == 1 {
14027 let definition = definitions.pop().unwrap();
14028
14029 enum TargetTaskResult {
14030 Location(Option<Location>),
14031 AlreadyNavigated,
14032 }
14033
14034 let target_task = match definition {
14035 HoverLink::Text(link) => {
14036 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14037 }
14038 HoverLink::InlayHint(lsp_location, server_id) => {
14039 let computation =
14040 self.compute_target_location(lsp_location, server_id, window, cx);
14041 cx.background_spawn(async move {
14042 let location = computation.await?;
14043 Ok(TargetTaskResult::Location(location))
14044 })
14045 }
14046 HoverLink::Url(url) => {
14047 cx.open_url(&url);
14048 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14049 }
14050 HoverLink::File(path) => {
14051 if let Some(workspace) = self.workspace() {
14052 cx.spawn_in(window, async move |_, cx| {
14053 workspace
14054 .update_in(cx, |workspace, window, cx| {
14055 workspace.open_resolved_path(path, window, cx)
14056 })?
14057 .await
14058 .map(|_| TargetTaskResult::AlreadyNavigated)
14059 })
14060 } else {
14061 Task::ready(Ok(TargetTaskResult::Location(None)))
14062 }
14063 }
14064 };
14065 cx.spawn_in(window, async move |editor, cx| {
14066 let target = match target_task.await.context("target resolution task")? {
14067 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14068 TargetTaskResult::Location(None) => return Ok(Navigated::No),
14069 TargetTaskResult::Location(Some(target)) => target,
14070 };
14071
14072 editor.update_in(cx, |editor, window, cx| {
14073 let Some(workspace) = editor.workspace() else {
14074 return Navigated::No;
14075 };
14076 let pane = workspace.read(cx).active_pane().clone();
14077
14078 let range = target.range.to_point(target.buffer.read(cx));
14079 let range = editor.range_for_match(&range);
14080 let range = collapse_multiline_range(range);
14081
14082 if !split
14083 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14084 {
14085 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14086 } else {
14087 window.defer(cx, move |window, cx| {
14088 let target_editor: Entity<Self> =
14089 workspace.update(cx, |workspace, cx| {
14090 let pane = if split {
14091 workspace.adjacent_pane(window, cx)
14092 } else {
14093 workspace.active_pane().clone()
14094 };
14095
14096 workspace.open_project_item(
14097 pane,
14098 target.buffer.clone(),
14099 true,
14100 true,
14101 window,
14102 cx,
14103 )
14104 });
14105 target_editor.update(cx, |target_editor, cx| {
14106 // When selecting a definition in a different buffer, disable the nav history
14107 // to avoid creating a history entry at the previous cursor location.
14108 pane.update(cx, |pane, _| pane.disable_history());
14109 target_editor.go_to_singleton_buffer_range(range, window, cx);
14110 pane.update(cx, |pane, _| pane.enable_history());
14111 });
14112 });
14113 }
14114 Navigated::Yes
14115 })
14116 })
14117 } else if !definitions.is_empty() {
14118 cx.spawn_in(window, async move |editor, cx| {
14119 let (title, location_tasks, workspace) = editor
14120 .update_in(cx, |editor, window, cx| {
14121 let tab_kind = match kind {
14122 Some(GotoDefinitionKind::Implementation) => "Implementations",
14123 _ => "Definitions",
14124 };
14125 let title = definitions
14126 .iter()
14127 .find_map(|definition| match definition {
14128 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14129 let buffer = origin.buffer.read(cx);
14130 format!(
14131 "{} for {}",
14132 tab_kind,
14133 buffer
14134 .text_for_range(origin.range.clone())
14135 .collect::<String>()
14136 )
14137 }),
14138 HoverLink::InlayHint(_, _) => None,
14139 HoverLink::Url(_) => None,
14140 HoverLink::File(_) => None,
14141 })
14142 .unwrap_or(tab_kind.to_string());
14143 let location_tasks = definitions
14144 .into_iter()
14145 .map(|definition| match definition {
14146 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14147 HoverLink::InlayHint(lsp_location, server_id) => editor
14148 .compute_target_location(lsp_location, server_id, window, cx),
14149 HoverLink::Url(_) => Task::ready(Ok(None)),
14150 HoverLink::File(_) => Task::ready(Ok(None)),
14151 })
14152 .collect::<Vec<_>>();
14153 (title, location_tasks, editor.workspace().clone())
14154 })
14155 .context("location tasks preparation")?;
14156
14157 let locations = future::join_all(location_tasks)
14158 .await
14159 .into_iter()
14160 .filter_map(|location| location.transpose())
14161 .collect::<Result<_>>()
14162 .context("location tasks")?;
14163
14164 let Some(workspace) = workspace else {
14165 return Ok(Navigated::No);
14166 };
14167 let opened = workspace
14168 .update_in(cx, |workspace, window, cx| {
14169 Self::open_locations_in_multibuffer(
14170 workspace,
14171 locations,
14172 title,
14173 split,
14174 MultibufferSelectionMode::First,
14175 window,
14176 cx,
14177 )
14178 })
14179 .ok();
14180
14181 anyhow::Ok(Navigated::from_bool(opened.is_some()))
14182 })
14183 } else {
14184 Task::ready(Ok(Navigated::No))
14185 }
14186 }
14187
14188 fn compute_target_location(
14189 &self,
14190 lsp_location: lsp::Location,
14191 server_id: LanguageServerId,
14192 window: &mut Window,
14193 cx: &mut Context<Self>,
14194 ) -> Task<anyhow::Result<Option<Location>>> {
14195 let Some(project) = self.project.clone() else {
14196 return Task::ready(Ok(None));
14197 };
14198
14199 cx.spawn_in(window, async move |editor, cx| {
14200 let location_task = editor.update(cx, |_, cx| {
14201 project.update(cx, |project, cx| {
14202 let language_server_name = project
14203 .language_server_statuses(cx)
14204 .find(|(id, _)| server_id == *id)
14205 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14206 language_server_name.map(|language_server_name| {
14207 project.open_local_buffer_via_lsp(
14208 lsp_location.uri.clone(),
14209 server_id,
14210 language_server_name,
14211 cx,
14212 )
14213 })
14214 })
14215 })?;
14216 let location = match location_task {
14217 Some(task) => Some({
14218 let target_buffer_handle = task.await.context("open local buffer")?;
14219 let range = target_buffer_handle.update(cx, |target_buffer, _| {
14220 let target_start = target_buffer
14221 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14222 let target_end = target_buffer
14223 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14224 target_buffer.anchor_after(target_start)
14225 ..target_buffer.anchor_before(target_end)
14226 })?;
14227 Location {
14228 buffer: target_buffer_handle,
14229 range,
14230 }
14231 }),
14232 None => None,
14233 };
14234 Ok(location)
14235 })
14236 }
14237
14238 pub fn find_all_references(
14239 &mut self,
14240 _: &FindAllReferences,
14241 window: &mut Window,
14242 cx: &mut Context<Self>,
14243 ) -> Option<Task<Result<Navigated>>> {
14244 let selection = self.selections.newest::<usize>(cx);
14245 let multi_buffer = self.buffer.read(cx);
14246 let head = selection.head();
14247
14248 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14249 let head_anchor = multi_buffer_snapshot.anchor_at(
14250 head,
14251 if head < selection.tail() {
14252 Bias::Right
14253 } else {
14254 Bias::Left
14255 },
14256 );
14257
14258 match self
14259 .find_all_references_task_sources
14260 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14261 {
14262 Ok(_) => {
14263 log::info!(
14264 "Ignoring repeated FindAllReferences invocation with the position of already running task"
14265 );
14266 return None;
14267 }
14268 Err(i) => {
14269 self.find_all_references_task_sources.insert(i, head_anchor);
14270 }
14271 }
14272
14273 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14274 let workspace = self.workspace()?;
14275 let project = workspace.read(cx).project().clone();
14276 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14277 Some(cx.spawn_in(window, async move |editor, cx| {
14278 let _cleanup = cx.on_drop(&editor, move |editor, _| {
14279 if let Ok(i) = editor
14280 .find_all_references_task_sources
14281 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14282 {
14283 editor.find_all_references_task_sources.remove(i);
14284 }
14285 });
14286
14287 let locations = references.await?;
14288 if locations.is_empty() {
14289 return anyhow::Ok(Navigated::No);
14290 }
14291
14292 workspace.update_in(cx, |workspace, window, cx| {
14293 let title = locations
14294 .first()
14295 .as_ref()
14296 .map(|location| {
14297 let buffer = location.buffer.read(cx);
14298 format!(
14299 "References to `{}`",
14300 buffer
14301 .text_for_range(location.range.clone())
14302 .collect::<String>()
14303 )
14304 })
14305 .unwrap();
14306 Self::open_locations_in_multibuffer(
14307 workspace,
14308 locations,
14309 title,
14310 false,
14311 MultibufferSelectionMode::First,
14312 window,
14313 cx,
14314 );
14315 Navigated::Yes
14316 })
14317 }))
14318 }
14319
14320 /// Opens a multibuffer with the given project locations in it
14321 pub fn open_locations_in_multibuffer(
14322 workspace: &mut Workspace,
14323 mut locations: Vec<Location>,
14324 title: String,
14325 split: bool,
14326 multibuffer_selection_mode: MultibufferSelectionMode,
14327 window: &mut Window,
14328 cx: &mut Context<Workspace>,
14329 ) {
14330 // If there are multiple definitions, open them in a multibuffer
14331 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14332 let mut locations = locations.into_iter().peekable();
14333 let mut ranges: Vec<Range<Anchor>> = Vec::new();
14334 let capability = workspace.project().read(cx).capability();
14335
14336 let excerpt_buffer = cx.new(|cx| {
14337 let mut multibuffer = MultiBuffer::new(capability);
14338 while let Some(location) = locations.next() {
14339 let buffer = location.buffer.read(cx);
14340 let mut ranges_for_buffer = Vec::new();
14341 let range = location.range.to_point(buffer);
14342 ranges_for_buffer.push(range.clone());
14343
14344 while let Some(next_location) = locations.peek() {
14345 if next_location.buffer == location.buffer {
14346 ranges_for_buffer.push(next_location.range.to_point(buffer));
14347 locations.next();
14348 } else {
14349 break;
14350 }
14351 }
14352
14353 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14354 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14355 PathKey::for_buffer(&location.buffer, cx),
14356 location.buffer.clone(),
14357 ranges_for_buffer,
14358 DEFAULT_MULTIBUFFER_CONTEXT,
14359 cx,
14360 );
14361 ranges.extend(new_ranges)
14362 }
14363
14364 multibuffer.with_title(title)
14365 });
14366
14367 let editor = cx.new(|cx| {
14368 Editor::for_multibuffer(
14369 excerpt_buffer,
14370 Some(workspace.project().clone()),
14371 window,
14372 cx,
14373 )
14374 });
14375 editor.update(cx, |editor, cx| {
14376 match multibuffer_selection_mode {
14377 MultibufferSelectionMode::First => {
14378 if let Some(first_range) = ranges.first() {
14379 editor.change_selections(None, window, cx, |selections| {
14380 selections.clear_disjoint();
14381 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14382 });
14383 }
14384 editor.highlight_background::<Self>(
14385 &ranges,
14386 |theme| theme.editor_highlighted_line_background,
14387 cx,
14388 );
14389 }
14390 MultibufferSelectionMode::All => {
14391 editor.change_selections(None, window, cx, |selections| {
14392 selections.clear_disjoint();
14393 selections.select_anchor_ranges(ranges);
14394 });
14395 }
14396 }
14397 editor.register_buffers_with_language_servers(cx);
14398 });
14399
14400 let item = Box::new(editor);
14401 let item_id = item.item_id();
14402
14403 if split {
14404 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14405 } else {
14406 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14407 let (preview_item_id, preview_item_idx) =
14408 workspace.active_pane().update(cx, |pane, _| {
14409 (pane.preview_item_id(), pane.preview_item_idx())
14410 });
14411
14412 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14413
14414 if let Some(preview_item_id) = preview_item_id {
14415 workspace.active_pane().update(cx, |pane, cx| {
14416 pane.remove_item(preview_item_id, false, false, window, cx);
14417 });
14418 }
14419 } else {
14420 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14421 }
14422 }
14423 workspace.active_pane().update(cx, |pane, cx| {
14424 pane.set_preview_item_id(Some(item_id), cx);
14425 });
14426 }
14427
14428 pub fn rename(
14429 &mut self,
14430 _: &Rename,
14431 window: &mut Window,
14432 cx: &mut Context<Self>,
14433 ) -> Option<Task<Result<()>>> {
14434 use language::ToOffset as _;
14435
14436 let provider = self.semantics_provider.clone()?;
14437 let selection = self.selections.newest_anchor().clone();
14438 let (cursor_buffer, cursor_buffer_position) = self
14439 .buffer
14440 .read(cx)
14441 .text_anchor_for_position(selection.head(), cx)?;
14442 let (tail_buffer, cursor_buffer_position_end) = self
14443 .buffer
14444 .read(cx)
14445 .text_anchor_for_position(selection.tail(), cx)?;
14446 if tail_buffer != cursor_buffer {
14447 return None;
14448 }
14449
14450 let snapshot = cursor_buffer.read(cx).snapshot();
14451 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14452 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14453 let prepare_rename = provider
14454 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14455 .unwrap_or_else(|| Task::ready(Ok(None)));
14456 drop(snapshot);
14457
14458 Some(cx.spawn_in(window, async move |this, cx| {
14459 let rename_range = if let Some(range) = prepare_rename.await? {
14460 Some(range)
14461 } else {
14462 this.update(cx, |this, cx| {
14463 let buffer = this.buffer.read(cx).snapshot(cx);
14464 let mut buffer_highlights = this
14465 .document_highlights_for_position(selection.head(), &buffer)
14466 .filter(|highlight| {
14467 highlight.start.excerpt_id == selection.head().excerpt_id
14468 && highlight.end.excerpt_id == selection.head().excerpt_id
14469 });
14470 buffer_highlights
14471 .next()
14472 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14473 })?
14474 };
14475 if let Some(rename_range) = rename_range {
14476 this.update_in(cx, |this, window, cx| {
14477 let snapshot = cursor_buffer.read(cx).snapshot();
14478 let rename_buffer_range = rename_range.to_offset(&snapshot);
14479 let cursor_offset_in_rename_range =
14480 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14481 let cursor_offset_in_rename_range_end =
14482 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14483
14484 this.take_rename(false, window, cx);
14485 let buffer = this.buffer.read(cx).read(cx);
14486 let cursor_offset = selection.head().to_offset(&buffer);
14487 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14488 let rename_end = rename_start + rename_buffer_range.len();
14489 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14490 let mut old_highlight_id = None;
14491 let old_name: Arc<str> = buffer
14492 .chunks(rename_start..rename_end, true)
14493 .map(|chunk| {
14494 if old_highlight_id.is_none() {
14495 old_highlight_id = chunk.syntax_highlight_id;
14496 }
14497 chunk.text
14498 })
14499 .collect::<String>()
14500 .into();
14501
14502 drop(buffer);
14503
14504 // Position the selection in the rename editor so that it matches the current selection.
14505 this.show_local_selections = false;
14506 let rename_editor = cx.new(|cx| {
14507 let mut editor = Editor::single_line(window, cx);
14508 editor.buffer.update(cx, |buffer, cx| {
14509 buffer.edit([(0..0, old_name.clone())], None, cx)
14510 });
14511 let rename_selection_range = match cursor_offset_in_rename_range
14512 .cmp(&cursor_offset_in_rename_range_end)
14513 {
14514 Ordering::Equal => {
14515 editor.select_all(&SelectAll, window, cx);
14516 return editor;
14517 }
14518 Ordering::Less => {
14519 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14520 }
14521 Ordering::Greater => {
14522 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14523 }
14524 };
14525 if rename_selection_range.end > old_name.len() {
14526 editor.select_all(&SelectAll, window, cx);
14527 } else {
14528 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14529 s.select_ranges([rename_selection_range]);
14530 });
14531 }
14532 editor
14533 });
14534 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14535 if e == &EditorEvent::Focused {
14536 cx.emit(EditorEvent::FocusedIn)
14537 }
14538 })
14539 .detach();
14540
14541 let write_highlights =
14542 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14543 let read_highlights =
14544 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14545 let ranges = write_highlights
14546 .iter()
14547 .flat_map(|(_, ranges)| ranges.iter())
14548 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14549 .cloned()
14550 .collect();
14551
14552 this.highlight_text::<Rename>(
14553 ranges,
14554 HighlightStyle {
14555 fade_out: Some(0.6),
14556 ..Default::default()
14557 },
14558 cx,
14559 );
14560 let rename_focus_handle = rename_editor.focus_handle(cx);
14561 window.focus(&rename_focus_handle);
14562 let block_id = this.insert_blocks(
14563 [BlockProperties {
14564 style: BlockStyle::Flex,
14565 placement: BlockPlacement::Below(range.start),
14566 height: Some(1),
14567 render: Arc::new({
14568 let rename_editor = rename_editor.clone();
14569 move |cx: &mut BlockContext| {
14570 let mut text_style = cx.editor_style.text.clone();
14571 if let Some(highlight_style) = old_highlight_id
14572 .and_then(|h| h.style(&cx.editor_style.syntax))
14573 {
14574 text_style = text_style.highlight(highlight_style);
14575 }
14576 div()
14577 .block_mouse_down()
14578 .pl(cx.anchor_x)
14579 .child(EditorElement::new(
14580 &rename_editor,
14581 EditorStyle {
14582 background: cx.theme().system().transparent,
14583 local_player: cx.editor_style.local_player,
14584 text: text_style,
14585 scrollbar_width: cx.editor_style.scrollbar_width,
14586 syntax: cx.editor_style.syntax.clone(),
14587 status: cx.editor_style.status.clone(),
14588 inlay_hints_style: HighlightStyle {
14589 font_weight: Some(FontWeight::BOLD),
14590 ..make_inlay_hints_style(cx.app)
14591 },
14592 inline_completion_styles: make_suggestion_styles(
14593 cx.app,
14594 ),
14595 ..EditorStyle::default()
14596 },
14597 ))
14598 .into_any_element()
14599 }
14600 }),
14601 priority: 0,
14602 }],
14603 Some(Autoscroll::fit()),
14604 cx,
14605 )[0];
14606 this.pending_rename = Some(RenameState {
14607 range,
14608 old_name,
14609 editor: rename_editor,
14610 block_id,
14611 });
14612 })?;
14613 }
14614
14615 Ok(())
14616 }))
14617 }
14618
14619 pub fn confirm_rename(
14620 &mut self,
14621 _: &ConfirmRename,
14622 window: &mut Window,
14623 cx: &mut Context<Self>,
14624 ) -> Option<Task<Result<()>>> {
14625 let rename = self.take_rename(false, window, cx)?;
14626 let workspace = self.workspace()?.downgrade();
14627 let (buffer, start) = self
14628 .buffer
14629 .read(cx)
14630 .text_anchor_for_position(rename.range.start, cx)?;
14631 let (end_buffer, _) = self
14632 .buffer
14633 .read(cx)
14634 .text_anchor_for_position(rename.range.end, cx)?;
14635 if buffer != end_buffer {
14636 return None;
14637 }
14638
14639 let old_name = rename.old_name;
14640 let new_name = rename.editor.read(cx).text(cx);
14641
14642 let rename = self.semantics_provider.as_ref()?.perform_rename(
14643 &buffer,
14644 start,
14645 new_name.clone(),
14646 cx,
14647 )?;
14648
14649 Some(cx.spawn_in(window, async move |editor, cx| {
14650 let project_transaction = rename.await?;
14651 Self::open_project_transaction(
14652 &editor,
14653 workspace,
14654 project_transaction,
14655 format!("Rename: {} → {}", old_name, new_name),
14656 cx,
14657 )
14658 .await?;
14659
14660 editor.update(cx, |editor, cx| {
14661 editor.refresh_document_highlights(cx);
14662 })?;
14663 Ok(())
14664 }))
14665 }
14666
14667 fn take_rename(
14668 &mut self,
14669 moving_cursor: bool,
14670 window: &mut Window,
14671 cx: &mut Context<Self>,
14672 ) -> Option<RenameState> {
14673 let rename = self.pending_rename.take()?;
14674 if rename.editor.focus_handle(cx).is_focused(window) {
14675 window.focus(&self.focus_handle);
14676 }
14677
14678 self.remove_blocks(
14679 [rename.block_id].into_iter().collect(),
14680 Some(Autoscroll::fit()),
14681 cx,
14682 );
14683 self.clear_highlights::<Rename>(cx);
14684 self.show_local_selections = true;
14685
14686 if moving_cursor {
14687 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14688 editor.selections.newest::<usize>(cx).head()
14689 });
14690
14691 // Update the selection to match the position of the selection inside
14692 // the rename editor.
14693 let snapshot = self.buffer.read(cx).read(cx);
14694 let rename_range = rename.range.to_offset(&snapshot);
14695 let cursor_in_editor = snapshot
14696 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14697 .min(rename_range.end);
14698 drop(snapshot);
14699
14700 self.change_selections(None, window, cx, |s| {
14701 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14702 });
14703 } else {
14704 self.refresh_document_highlights(cx);
14705 }
14706
14707 Some(rename)
14708 }
14709
14710 pub fn pending_rename(&self) -> Option<&RenameState> {
14711 self.pending_rename.as_ref()
14712 }
14713
14714 fn format(
14715 &mut self,
14716 _: &Format,
14717 window: &mut Window,
14718 cx: &mut Context<Self>,
14719 ) -> Option<Task<Result<()>>> {
14720 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14721
14722 let project = match &self.project {
14723 Some(project) => project.clone(),
14724 None => return None,
14725 };
14726
14727 Some(self.perform_format(
14728 project,
14729 FormatTrigger::Manual,
14730 FormatTarget::Buffers,
14731 window,
14732 cx,
14733 ))
14734 }
14735
14736 fn format_selections(
14737 &mut self,
14738 _: &FormatSelections,
14739 window: &mut Window,
14740 cx: &mut Context<Self>,
14741 ) -> Option<Task<Result<()>>> {
14742 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14743
14744 let project = match &self.project {
14745 Some(project) => project.clone(),
14746 None => return None,
14747 };
14748
14749 let ranges = self
14750 .selections
14751 .all_adjusted(cx)
14752 .into_iter()
14753 .map(|selection| selection.range())
14754 .collect_vec();
14755
14756 Some(self.perform_format(
14757 project,
14758 FormatTrigger::Manual,
14759 FormatTarget::Ranges(ranges),
14760 window,
14761 cx,
14762 ))
14763 }
14764
14765 fn perform_format(
14766 &mut self,
14767 project: Entity<Project>,
14768 trigger: FormatTrigger,
14769 target: FormatTarget,
14770 window: &mut Window,
14771 cx: &mut Context<Self>,
14772 ) -> Task<Result<()>> {
14773 let buffer = self.buffer.clone();
14774 let (buffers, target) = match target {
14775 FormatTarget::Buffers => {
14776 let mut buffers = buffer.read(cx).all_buffers();
14777 if trigger == FormatTrigger::Save {
14778 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14779 }
14780 (buffers, LspFormatTarget::Buffers)
14781 }
14782 FormatTarget::Ranges(selection_ranges) => {
14783 let multi_buffer = buffer.read(cx);
14784 let snapshot = multi_buffer.read(cx);
14785 let mut buffers = HashSet::default();
14786 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14787 BTreeMap::new();
14788 for selection_range in selection_ranges {
14789 for (buffer, buffer_range, _) in
14790 snapshot.range_to_buffer_ranges(selection_range)
14791 {
14792 let buffer_id = buffer.remote_id();
14793 let start = buffer.anchor_before(buffer_range.start);
14794 let end = buffer.anchor_after(buffer_range.end);
14795 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14796 buffer_id_to_ranges
14797 .entry(buffer_id)
14798 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14799 .or_insert_with(|| vec![start..end]);
14800 }
14801 }
14802 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14803 }
14804 };
14805
14806 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14807 let selections_prev = transaction_id_prev
14808 .and_then(|transaction_id_prev| {
14809 // default to selections as they were after the last edit, if we have them,
14810 // instead of how they are now.
14811 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14812 // will take you back to where you made the last edit, instead of staying where you scrolled
14813 self.selection_history
14814 .transaction(transaction_id_prev)
14815 .map(|t| t.0.clone())
14816 })
14817 .unwrap_or_else(|| {
14818 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14819 self.selections.disjoint_anchors()
14820 });
14821
14822 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14823 let format = project.update(cx, |project, cx| {
14824 project.format(buffers, target, true, trigger, cx)
14825 });
14826
14827 cx.spawn_in(window, async move |editor, cx| {
14828 let transaction = futures::select_biased! {
14829 transaction = format.log_err().fuse() => transaction,
14830 () = timeout => {
14831 log::warn!("timed out waiting for formatting");
14832 None
14833 }
14834 };
14835
14836 buffer
14837 .update(cx, |buffer, cx| {
14838 if let Some(transaction) = transaction {
14839 if !buffer.is_singleton() {
14840 buffer.push_transaction(&transaction.0, cx);
14841 }
14842 }
14843 cx.notify();
14844 })
14845 .ok();
14846
14847 if let Some(transaction_id_now) =
14848 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14849 {
14850 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14851 if has_new_transaction {
14852 _ = editor.update(cx, |editor, _| {
14853 editor
14854 .selection_history
14855 .insert_transaction(transaction_id_now, selections_prev);
14856 });
14857 }
14858 }
14859
14860 Ok(())
14861 })
14862 }
14863
14864 fn organize_imports(
14865 &mut self,
14866 _: &OrganizeImports,
14867 window: &mut Window,
14868 cx: &mut Context<Self>,
14869 ) -> Option<Task<Result<()>>> {
14870 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14871 let project = match &self.project {
14872 Some(project) => project.clone(),
14873 None => return None,
14874 };
14875 Some(self.perform_code_action_kind(
14876 project,
14877 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14878 window,
14879 cx,
14880 ))
14881 }
14882
14883 fn perform_code_action_kind(
14884 &mut self,
14885 project: Entity<Project>,
14886 kind: CodeActionKind,
14887 window: &mut Window,
14888 cx: &mut Context<Self>,
14889 ) -> Task<Result<()>> {
14890 let buffer = self.buffer.clone();
14891 let buffers = buffer.read(cx).all_buffers();
14892 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14893 let apply_action = project.update(cx, |project, cx| {
14894 project.apply_code_action_kind(buffers, kind, true, cx)
14895 });
14896 cx.spawn_in(window, async move |_, cx| {
14897 let transaction = futures::select_biased! {
14898 () = timeout => {
14899 log::warn!("timed out waiting for executing code action");
14900 None
14901 }
14902 transaction = apply_action.log_err().fuse() => transaction,
14903 };
14904 buffer
14905 .update(cx, |buffer, cx| {
14906 // check if we need this
14907 if let Some(transaction) = transaction {
14908 if !buffer.is_singleton() {
14909 buffer.push_transaction(&transaction.0, cx);
14910 }
14911 }
14912 cx.notify();
14913 })
14914 .ok();
14915 Ok(())
14916 })
14917 }
14918
14919 fn restart_language_server(
14920 &mut self,
14921 _: &RestartLanguageServer,
14922 _: &mut Window,
14923 cx: &mut Context<Self>,
14924 ) {
14925 if let Some(project) = self.project.clone() {
14926 self.buffer.update(cx, |multi_buffer, cx| {
14927 project.update(cx, |project, cx| {
14928 project.restart_language_servers_for_buffers(
14929 multi_buffer.all_buffers().into_iter().collect(),
14930 cx,
14931 );
14932 });
14933 })
14934 }
14935 }
14936
14937 fn stop_language_server(
14938 &mut self,
14939 _: &StopLanguageServer,
14940 _: &mut Window,
14941 cx: &mut Context<Self>,
14942 ) {
14943 if let Some(project) = self.project.clone() {
14944 self.buffer.update(cx, |multi_buffer, cx| {
14945 project.update(cx, |project, cx| {
14946 project.stop_language_servers_for_buffers(
14947 multi_buffer.all_buffers().into_iter().collect(),
14948 cx,
14949 );
14950 cx.emit(project::Event::RefreshInlayHints);
14951 });
14952 });
14953 }
14954 }
14955
14956 fn cancel_language_server_work(
14957 workspace: &mut Workspace,
14958 _: &actions::CancelLanguageServerWork,
14959 _: &mut Window,
14960 cx: &mut Context<Workspace>,
14961 ) {
14962 let project = workspace.project();
14963 let buffers = workspace
14964 .active_item(cx)
14965 .and_then(|item| item.act_as::<Editor>(cx))
14966 .map_or(HashSet::default(), |editor| {
14967 editor.read(cx).buffer.read(cx).all_buffers()
14968 });
14969 project.update(cx, |project, cx| {
14970 project.cancel_language_server_work_for_buffers(buffers, cx);
14971 });
14972 }
14973
14974 fn show_character_palette(
14975 &mut self,
14976 _: &ShowCharacterPalette,
14977 window: &mut Window,
14978 _: &mut Context<Self>,
14979 ) {
14980 window.show_character_palette();
14981 }
14982
14983 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14984 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14985 let buffer = self.buffer.read(cx).snapshot(cx);
14986 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14987 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14988 let is_valid = buffer
14989 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14990 .any(|entry| {
14991 entry.diagnostic.is_primary
14992 && !entry.range.is_empty()
14993 && entry.range.start == primary_range_start
14994 && entry.diagnostic.message == active_diagnostics.active_message
14995 });
14996
14997 if !is_valid {
14998 self.dismiss_diagnostics(cx);
14999 }
15000 }
15001 }
15002
15003 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
15004 match &self.active_diagnostics {
15005 ActiveDiagnostic::Group(group) => Some(group),
15006 _ => None,
15007 }
15008 }
15009
15010 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15011 self.dismiss_diagnostics(cx);
15012 self.active_diagnostics = ActiveDiagnostic::All;
15013 }
15014
15015 fn activate_diagnostics(
15016 &mut self,
15017 buffer_id: BufferId,
15018 diagnostic: DiagnosticEntry<usize>,
15019 window: &mut Window,
15020 cx: &mut Context<Self>,
15021 ) {
15022 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15023 return;
15024 }
15025 self.dismiss_diagnostics(cx);
15026 let snapshot = self.snapshot(window, cx);
15027 let buffer = self.buffer.read(cx).snapshot(cx);
15028 let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15029 return;
15030 };
15031
15032 let diagnostic_group = buffer
15033 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15034 .collect::<Vec<_>>();
15035
15036 let blocks =
15037 renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15038
15039 let blocks = self.display_map.update(cx, |display_map, cx| {
15040 display_map.insert_blocks(blocks, cx).into_iter().collect()
15041 });
15042 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15043 active_range: buffer.anchor_before(diagnostic.range.start)
15044 ..buffer.anchor_after(diagnostic.range.end),
15045 active_message: diagnostic.diagnostic.message.clone(),
15046 group_id: diagnostic.diagnostic.group_id,
15047 blocks,
15048 });
15049 cx.notify();
15050 }
15051
15052 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15053 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15054 return;
15055 };
15056
15057 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15058 if let ActiveDiagnostic::Group(group) = prev {
15059 self.display_map.update(cx, |display_map, cx| {
15060 display_map.remove_blocks(group.blocks, cx);
15061 });
15062 cx.notify();
15063 }
15064 }
15065
15066 /// Disable inline diagnostics rendering for this editor.
15067 pub fn disable_inline_diagnostics(&mut self) {
15068 self.inline_diagnostics_enabled = false;
15069 self.inline_diagnostics_update = Task::ready(());
15070 self.inline_diagnostics.clear();
15071 }
15072
15073 pub fn inline_diagnostics_enabled(&self) -> bool {
15074 self.inline_diagnostics_enabled
15075 }
15076
15077 pub fn show_inline_diagnostics(&self) -> bool {
15078 self.show_inline_diagnostics
15079 }
15080
15081 pub fn toggle_inline_diagnostics(
15082 &mut self,
15083 _: &ToggleInlineDiagnostics,
15084 window: &mut Window,
15085 cx: &mut Context<Editor>,
15086 ) {
15087 self.show_inline_diagnostics = !self.show_inline_diagnostics;
15088 self.refresh_inline_diagnostics(false, window, cx);
15089 }
15090
15091 fn refresh_inline_diagnostics(
15092 &mut self,
15093 debounce: bool,
15094 window: &mut Window,
15095 cx: &mut Context<Self>,
15096 ) {
15097 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
15098 self.inline_diagnostics_update = Task::ready(());
15099 self.inline_diagnostics.clear();
15100 return;
15101 }
15102
15103 let debounce_ms = ProjectSettings::get_global(cx)
15104 .diagnostics
15105 .inline
15106 .update_debounce_ms;
15107 let debounce = if debounce && debounce_ms > 0 {
15108 Some(Duration::from_millis(debounce_ms))
15109 } else {
15110 None
15111 };
15112 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15113 let editor = editor.upgrade().unwrap();
15114
15115 if let Some(debounce) = debounce {
15116 cx.background_executor().timer(debounce).await;
15117 }
15118 let Some(snapshot) = editor
15119 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15120 .ok()
15121 else {
15122 return;
15123 };
15124
15125 let new_inline_diagnostics = cx
15126 .background_spawn(async move {
15127 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15128 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15129 let message = diagnostic_entry
15130 .diagnostic
15131 .message
15132 .split_once('\n')
15133 .map(|(line, _)| line)
15134 .map(SharedString::new)
15135 .unwrap_or_else(|| {
15136 SharedString::from(diagnostic_entry.diagnostic.message)
15137 });
15138 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15139 let (Ok(i) | Err(i)) = inline_diagnostics
15140 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15141 inline_diagnostics.insert(
15142 i,
15143 (
15144 start_anchor,
15145 InlineDiagnostic {
15146 message,
15147 group_id: diagnostic_entry.diagnostic.group_id,
15148 start: diagnostic_entry.range.start.to_point(&snapshot),
15149 is_primary: diagnostic_entry.diagnostic.is_primary,
15150 severity: diagnostic_entry.diagnostic.severity,
15151 },
15152 ),
15153 );
15154 }
15155 inline_diagnostics
15156 })
15157 .await;
15158
15159 editor
15160 .update(cx, |editor, cx| {
15161 editor.inline_diagnostics = new_inline_diagnostics;
15162 cx.notify();
15163 })
15164 .ok();
15165 });
15166 }
15167
15168 pub fn set_selections_from_remote(
15169 &mut self,
15170 selections: Vec<Selection<Anchor>>,
15171 pending_selection: Option<Selection<Anchor>>,
15172 window: &mut Window,
15173 cx: &mut Context<Self>,
15174 ) {
15175 let old_cursor_position = self.selections.newest_anchor().head();
15176 self.selections.change_with(cx, |s| {
15177 s.select_anchors(selections);
15178 if let Some(pending_selection) = pending_selection {
15179 s.set_pending(pending_selection, SelectMode::Character);
15180 } else {
15181 s.clear_pending();
15182 }
15183 });
15184 self.selections_did_change(false, &old_cursor_position, true, window, cx);
15185 }
15186
15187 fn push_to_selection_history(&mut self) {
15188 self.selection_history.push(SelectionHistoryEntry {
15189 selections: self.selections.disjoint_anchors(),
15190 select_next_state: self.select_next_state.clone(),
15191 select_prev_state: self.select_prev_state.clone(),
15192 add_selections_state: self.add_selections_state.clone(),
15193 });
15194 }
15195
15196 pub fn transact(
15197 &mut self,
15198 window: &mut Window,
15199 cx: &mut Context<Self>,
15200 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15201 ) -> Option<TransactionId> {
15202 self.start_transaction_at(Instant::now(), window, cx);
15203 update(self, window, cx);
15204 self.end_transaction_at(Instant::now(), cx)
15205 }
15206
15207 pub fn start_transaction_at(
15208 &mut self,
15209 now: Instant,
15210 window: &mut Window,
15211 cx: &mut Context<Self>,
15212 ) {
15213 self.end_selection(window, cx);
15214 if let Some(tx_id) = self
15215 .buffer
15216 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15217 {
15218 self.selection_history
15219 .insert_transaction(tx_id, self.selections.disjoint_anchors());
15220 cx.emit(EditorEvent::TransactionBegun {
15221 transaction_id: tx_id,
15222 })
15223 }
15224 }
15225
15226 pub fn end_transaction_at(
15227 &mut self,
15228 now: Instant,
15229 cx: &mut Context<Self>,
15230 ) -> Option<TransactionId> {
15231 if let Some(transaction_id) = self
15232 .buffer
15233 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15234 {
15235 if let Some((_, end_selections)) =
15236 self.selection_history.transaction_mut(transaction_id)
15237 {
15238 *end_selections = Some(self.selections.disjoint_anchors());
15239 } else {
15240 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15241 }
15242
15243 cx.emit(EditorEvent::Edited { transaction_id });
15244 Some(transaction_id)
15245 } else {
15246 None
15247 }
15248 }
15249
15250 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15251 if self.selection_mark_mode {
15252 self.change_selections(None, window, cx, |s| {
15253 s.move_with(|_, sel| {
15254 sel.collapse_to(sel.head(), SelectionGoal::None);
15255 });
15256 })
15257 }
15258 self.selection_mark_mode = true;
15259 cx.notify();
15260 }
15261
15262 pub fn swap_selection_ends(
15263 &mut self,
15264 _: &actions::SwapSelectionEnds,
15265 window: &mut Window,
15266 cx: &mut Context<Self>,
15267 ) {
15268 self.change_selections(None, window, cx, |s| {
15269 s.move_with(|_, sel| {
15270 if sel.start != sel.end {
15271 sel.reversed = !sel.reversed
15272 }
15273 });
15274 });
15275 self.request_autoscroll(Autoscroll::newest(), cx);
15276 cx.notify();
15277 }
15278
15279 pub fn toggle_fold(
15280 &mut self,
15281 _: &actions::ToggleFold,
15282 window: &mut Window,
15283 cx: &mut Context<Self>,
15284 ) {
15285 if self.is_singleton(cx) {
15286 let selection = self.selections.newest::<Point>(cx);
15287
15288 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15289 let range = if selection.is_empty() {
15290 let point = selection.head().to_display_point(&display_map);
15291 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15292 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15293 .to_point(&display_map);
15294 start..end
15295 } else {
15296 selection.range()
15297 };
15298 if display_map.folds_in_range(range).next().is_some() {
15299 self.unfold_lines(&Default::default(), window, cx)
15300 } else {
15301 self.fold(&Default::default(), window, cx)
15302 }
15303 } else {
15304 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15305 let buffer_ids: HashSet<_> = self
15306 .selections
15307 .disjoint_anchor_ranges()
15308 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15309 .collect();
15310
15311 let should_unfold = buffer_ids
15312 .iter()
15313 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15314
15315 for buffer_id in buffer_ids {
15316 if should_unfold {
15317 self.unfold_buffer(buffer_id, cx);
15318 } else {
15319 self.fold_buffer(buffer_id, cx);
15320 }
15321 }
15322 }
15323 }
15324
15325 pub fn toggle_fold_recursive(
15326 &mut self,
15327 _: &actions::ToggleFoldRecursive,
15328 window: &mut Window,
15329 cx: &mut Context<Self>,
15330 ) {
15331 let selection = self.selections.newest::<Point>(cx);
15332
15333 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15334 let range = if selection.is_empty() {
15335 let point = selection.head().to_display_point(&display_map);
15336 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15337 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15338 .to_point(&display_map);
15339 start..end
15340 } else {
15341 selection.range()
15342 };
15343 if display_map.folds_in_range(range).next().is_some() {
15344 self.unfold_recursive(&Default::default(), window, cx)
15345 } else {
15346 self.fold_recursive(&Default::default(), window, cx)
15347 }
15348 }
15349
15350 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15351 if self.is_singleton(cx) {
15352 let mut to_fold = Vec::new();
15353 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15354 let selections = self.selections.all_adjusted(cx);
15355
15356 for selection in selections {
15357 let range = selection.range().sorted();
15358 let buffer_start_row = range.start.row;
15359
15360 if range.start.row != range.end.row {
15361 let mut found = false;
15362 let mut row = range.start.row;
15363 while row <= range.end.row {
15364 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15365 {
15366 found = true;
15367 row = crease.range().end.row + 1;
15368 to_fold.push(crease);
15369 } else {
15370 row += 1
15371 }
15372 }
15373 if found {
15374 continue;
15375 }
15376 }
15377
15378 for row in (0..=range.start.row).rev() {
15379 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15380 if crease.range().end.row >= buffer_start_row {
15381 to_fold.push(crease);
15382 if row <= range.start.row {
15383 break;
15384 }
15385 }
15386 }
15387 }
15388 }
15389
15390 self.fold_creases(to_fold, true, window, cx);
15391 } else {
15392 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15393 let buffer_ids = self
15394 .selections
15395 .disjoint_anchor_ranges()
15396 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15397 .collect::<HashSet<_>>();
15398 for buffer_id in buffer_ids {
15399 self.fold_buffer(buffer_id, cx);
15400 }
15401 }
15402 }
15403
15404 fn fold_at_level(
15405 &mut self,
15406 fold_at: &FoldAtLevel,
15407 window: &mut Window,
15408 cx: &mut Context<Self>,
15409 ) {
15410 if !self.buffer.read(cx).is_singleton() {
15411 return;
15412 }
15413
15414 let fold_at_level = fold_at.0;
15415 let snapshot = self.buffer.read(cx).snapshot(cx);
15416 let mut to_fold = Vec::new();
15417 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15418
15419 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15420 while start_row < end_row {
15421 match self
15422 .snapshot(window, cx)
15423 .crease_for_buffer_row(MultiBufferRow(start_row))
15424 {
15425 Some(crease) => {
15426 let nested_start_row = crease.range().start.row + 1;
15427 let nested_end_row = crease.range().end.row;
15428
15429 if current_level < fold_at_level {
15430 stack.push((nested_start_row, nested_end_row, current_level + 1));
15431 } else if current_level == fold_at_level {
15432 to_fold.push(crease);
15433 }
15434
15435 start_row = nested_end_row + 1;
15436 }
15437 None => start_row += 1,
15438 }
15439 }
15440 }
15441
15442 self.fold_creases(to_fold, true, window, cx);
15443 }
15444
15445 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15446 if self.buffer.read(cx).is_singleton() {
15447 let mut fold_ranges = Vec::new();
15448 let snapshot = self.buffer.read(cx).snapshot(cx);
15449
15450 for row in 0..snapshot.max_row().0 {
15451 if let Some(foldable_range) = self
15452 .snapshot(window, cx)
15453 .crease_for_buffer_row(MultiBufferRow(row))
15454 {
15455 fold_ranges.push(foldable_range);
15456 }
15457 }
15458
15459 self.fold_creases(fold_ranges, true, window, cx);
15460 } else {
15461 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15462 editor
15463 .update_in(cx, |editor, _, cx| {
15464 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15465 editor.fold_buffer(buffer_id, cx);
15466 }
15467 })
15468 .ok();
15469 });
15470 }
15471 }
15472
15473 pub fn fold_function_bodies(
15474 &mut self,
15475 _: &actions::FoldFunctionBodies,
15476 window: &mut Window,
15477 cx: &mut Context<Self>,
15478 ) {
15479 let snapshot = self.buffer.read(cx).snapshot(cx);
15480
15481 let ranges = snapshot
15482 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15483 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15484 .collect::<Vec<_>>();
15485
15486 let creases = ranges
15487 .into_iter()
15488 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15489 .collect();
15490
15491 self.fold_creases(creases, true, window, cx);
15492 }
15493
15494 pub fn fold_recursive(
15495 &mut self,
15496 _: &actions::FoldRecursive,
15497 window: &mut Window,
15498 cx: &mut Context<Self>,
15499 ) {
15500 let mut to_fold = Vec::new();
15501 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15502 let selections = self.selections.all_adjusted(cx);
15503
15504 for selection in selections {
15505 let range = selection.range().sorted();
15506 let buffer_start_row = range.start.row;
15507
15508 if range.start.row != range.end.row {
15509 let mut found = false;
15510 for row in range.start.row..=range.end.row {
15511 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15512 found = true;
15513 to_fold.push(crease);
15514 }
15515 }
15516 if found {
15517 continue;
15518 }
15519 }
15520
15521 for row in (0..=range.start.row).rev() {
15522 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15523 if crease.range().end.row >= buffer_start_row {
15524 to_fold.push(crease);
15525 } else {
15526 break;
15527 }
15528 }
15529 }
15530 }
15531
15532 self.fold_creases(to_fold, true, window, cx);
15533 }
15534
15535 pub fn fold_at(
15536 &mut self,
15537 buffer_row: MultiBufferRow,
15538 window: &mut Window,
15539 cx: &mut Context<Self>,
15540 ) {
15541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15542
15543 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15544 let autoscroll = self
15545 .selections
15546 .all::<Point>(cx)
15547 .iter()
15548 .any(|selection| crease.range().overlaps(&selection.range()));
15549
15550 self.fold_creases(vec![crease], autoscroll, window, cx);
15551 }
15552 }
15553
15554 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15555 if self.is_singleton(cx) {
15556 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15557 let buffer = &display_map.buffer_snapshot;
15558 let selections = self.selections.all::<Point>(cx);
15559 let ranges = selections
15560 .iter()
15561 .map(|s| {
15562 let range = s.display_range(&display_map).sorted();
15563 let mut start = range.start.to_point(&display_map);
15564 let mut end = range.end.to_point(&display_map);
15565 start.column = 0;
15566 end.column = buffer.line_len(MultiBufferRow(end.row));
15567 start..end
15568 })
15569 .collect::<Vec<_>>();
15570
15571 self.unfold_ranges(&ranges, true, true, cx);
15572 } else {
15573 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15574 let buffer_ids = self
15575 .selections
15576 .disjoint_anchor_ranges()
15577 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15578 .collect::<HashSet<_>>();
15579 for buffer_id in buffer_ids {
15580 self.unfold_buffer(buffer_id, cx);
15581 }
15582 }
15583 }
15584
15585 pub fn unfold_recursive(
15586 &mut self,
15587 _: &UnfoldRecursive,
15588 _window: &mut Window,
15589 cx: &mut Context<Self>,
15590 ) {
15591 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15592 let selections = self.selections.all::<Point>(cx);
15593 let ranges = selections
15594 .iter()
15595 .map(|s| {
15596 let mut range = s.display_range(&display_map).sorted();
15597 *range.start.column_mut() = 0;
15598 *range.end.column_mut() = display_map.line_len(range.end.row());
15599 let start = range.start.to_point(&display_map);
15600 let end = range.end.to_point(&display_map);
15601 start..end
15602 })
15603 .collect::<Vec<_>>();
15604
15605 self.unfold_ranges(&ranges, true, true, cx);
15606 }
15607
15608 pub fn unfold_at(
15609 &mut self,
15610 buffer_row: MultiBufferRow,
15611 _window: &mut Window,
15612 cx: &mut Context<Self>,
15613 ) {
15614 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15615
15616 let intersection_range = Point::new(buffer_row.0, 0)
15617 ..Point::new(
15618 buffer_row.0,
15619 display_map.buffer_snapshot.line_len(buffer_row),
15620 );
15621
15622 let autoscroll = self
15623 .selections
15624 .all::<Point>(cx)
15625 .iter()
15626 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15627
15628 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15629 }
15630
15631 pub fn unfold_all(
15632 &mut self,
15633 _: &actions::UnfoldAll,
15634 _window: &mut Window,
15635 cx: &mut Context<Self>,
15636 ) {
15637 if self.buffer.read(cx).is_singleton() {
15638 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15639 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15640 } else {
15641 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15642 editor
15643 .update(cx, |editor, cx| {
15644 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15645 editor.unfold_buffer(buffer_id, cx);
15646 }
15647 })
15648 .ok();
15649 });
15650 }
15651 }
15652
15653 pub fn fold_selected_ranges(
15654 &mut self,
15655 _: &FoldSelectedRanges,
15656 window: &mut Window,
15657 cx: &mut Context<Self>,
15658 ) {
15659 let selections = self.selections.all_adjusted(cx);
15660 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15661 let ranges = selections
15662 .into_iter()
15663 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15664 .collect::<Vec<_>>();
15665 self.fold_creases(ranges, true, window, cx);
15666 }
15667
15668 pub fn fold_ranges<T: ToOffset + Clone>(
15669 &mut self,
15670 ranges: Vec<Range<T>>,
15671 auto_scroll: bool,
15672 window: &mut Window,
15673 cx: &mut Context<Self>,
15674 ) {
15675 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15676 let ranges = ranges
15677 .into_iter()
15678 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15679 .collect::<Vec<_>>();
15680 self.fold_creases(ranges, auto_scroll, window, cx);
15681 }
15682
15683 pub fn fold_creases<T: ToOffset + Clone>(
15684 &mut self,
15685 creases: Vec<Crease<T>>,
15686 auto_scroll: bool,
15687 _window: &mut Window,
15688 cx: &mut Context<Self>,
15689 ) {
15690 if creases.is_empty() {
15691 return;
15692 }
15693
15694 let mut buffers_affected = HashSet::default();
15695 let multi_buffer = self.buffer().read(cx);
15696 for crease in &creases {
15697 if let Some((_, buffer, _)) =
15698 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15699 {
15700 buffers_affected.insert(buffer.read(cx).remote_id());
15701 };
15702 }
15703
15704 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15705
15706 if auto_scroll {
15707 self.request_autoscroll(Autoscroll::fit(), cx);
15708 }
15709
15710 cx.notify();
15711
15712 self.scrollbar_marker_state.dirty = true;
15713 self.folds_did_change(cx);
15714 }
15715
15716 /// Removes any folds whose ranges intersect any of the given ranges.
15717 pub fn unfold_ranges<T: ToOffset + Clone>(
15718 &mut self,
15719 ranges: &[Range<T>],
15720 inclusive: bool,
15721 auto_scroll: bool,
15722 cx: &mut Context<Self>,
15723 ) {
15724 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15725 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15726 });
15727 self.folds_did_change(cx);
15728 }
15729
15730 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15731 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15732 return;
15733 }
15734 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15735 self.display_map.update(cx, |display_map, cx| {
15736 display_map.fold_buffers([buffer_id], cx)
15737 });
15738 cx.emit(EditorEvent::BufferFoldToggled {
15739 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15740 folded: true,
15741 });
15742 cx.notify();
15743 }
15744
15745 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15746 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15747 return;
15748 }
15749 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15750 self.display_map.update(cx, |display_map, cx| {
15751 display_map.unfold_buffers([buffer_id], cx);
15752 });
15753 cx.emit(EditorEvent::BufferFoldToggled {
15754 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15755 folded: false,
15756 });
15757 cx.notify();
15758 }
15759
15760 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15761 self.display_map.read(cx).is_buffer_folded(buffer)
15762 }
15763
15764 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15765 self.display_map.read(cx).folded_buffers()
15766 }
15767
15768 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15769 self.display_map.update(cx, |display_map, cx| {
15770 display_map.disable_header_for_buffer(buffer_id, cx);
15771 });
15772 cx.notify();
15773 }
15774
15775 /// Removes any folds with the given ranges.
15776 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15777 &mut self,
15778 ranges: &[Range<T>],
15779 type_id: TypeId,
15780 auto_scroll: bool,
15781 cx: &mut Context<Self>,
15782 ) {
15783 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15784 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15785 });
15786 self.folds_did_change(cx);
15787 }
15788
15789 fn remove_folds_with<T: ToOffset + Clone>(
15790 &mut self,
15791 ranges: &[Range<T>],
15792 auto_scroll: bool,
15793 cx: &mut Context<Self>,
15794 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15795 ) {
15796 if ranges.is_empty() {
15797 return;
15798 }
15799
15800 let mut buffers_affected = HashSet::default();
15801 let multi_buffer = self.buffer().read(cx);
15802 for range in ranges {
15803 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15804 buffers_affected.insert(buffer.read(cx).remote_id());
15805 };
15806 }
15807
15808 self.display_map.update(cx, update);
15809
15810 if auto_scroll {
15811 self.request_autoscroll(Autoscroll::fit(), cx);
15812 }
15813
15814 cx.notify();
15815 self.scrollbar_marker_state.dirty = true;
15816 self.active_indent_guides_state.dirty = true;
15817 }
15818
15819 pub fn update_fold_widths(
15820 &mut self,
15821 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15822 cx: &mut Context<Self>,
15823 ) -> bool {
15824 self.display_map
15825 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15826 }
15827
15828 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15829 self.display_map.read(cx).fold_placeholder.clone()
15830 }
15831
15832 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15833 self.buffer.update(cx, |buffer, cx| {
15834 buffer.set_all_diff_hunks_expanded(cx);
15835 });
15836 }
15837
15838 pub fn expand_all_diff_hunks(
15839 &mut self,
15840 _: &ExpandAllDiffHunks,
15841 _window: &mut Window,
15842 cx: &mut Context<Self>,
15843 ) {
15844 self.buffer.update(cx, |buffer, cx| {
15845 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15846 });
15847 }
15848
15849 pub fn toggle_selected_diff_hunks(
15850 &mut self,
15851 _: &ToggleSelectedDiffHunks,
15852 _window: &mut Window,
15853 cx: &mut Context<Self>,
15854 ) {
15855 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15856 self.toggle_diff_hunks_in_ranges(ranges, cx);
15857 }
15858
15859 pub fn diff_hunks_in_ranges<'a>(
15860 &'a self,
15861 ranges: &'a [Range<Anchor>],
15862 buffer: &'a MultiBufferSnapshot,
15863 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15864 ranges.iter().flat_map(move |range| {
15865 let end_excerpt_id = range.end.excerpt_id;
15866 let range = range.to_point(buffer);
15867 let mut peek_end = range.end;
15868 if range.end.row < buffer.max_row().0 {
15869 peek_end = Point::new(range.end.row + 1, 0);
15870 }
15871 buffer
15872 .diff_hunks_in_range(range.start..peek_end)
15873 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15874 })
15875 }
15876
15877 pub fn has_stageable_diff_hunks_in_ranges(
15878 &self,
15879 ranges: &[Range<Anchor>],
15880 snapshot: &MultiBufferSnapshot,
15881 ) -> bool {
15882 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15883 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15884 }
15885
15886 pub fn toggle_staged_selected_diff_hunks(
15887 &mut self,
15888 _: &::git::ToggleStaged,
15889 _: &mut Window,
15890 cx: &mut Context<Self>,
15891 ) {
15892 let snapshot = self.buffer.read(cx).snapshot(cx);
15893 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15894 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15895 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15896 }
15897
15898 pub fn set_render_diff_hunk_controls(
15899 &mut self,
15900 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15901 cx: &mut Context<Self>,
15902 ) {
15903 self.render_diff_hunk_controls = render_diff_hunk_controls;
15904 cx.notify();
15905 }
15906
15907 pub fn stage_and_next(
15908 &mut self,
15909 _: &::git::StageAndNext,
15910 window: &mut Window,
15911 cx: &mut Context<Self>,
15912 ) {
15913 self.do_stage_or_unstage_and_next(true, window, cx);
15914 }
15915
15916 pub fn unstage_and_next(
15917 &mut self,
15918 _: &::git::UnstageAndNext,
15919 window: &mut Window,
15920 cx: &mut Context<Self>,
15921 ) {
15922 self.do_stage_or_unstage_and_next(false, window, cx);
15923 }
15924
15925 pub fn stage_or_unstage_diff_hunks(
15926 &mut self,
15927 stage: bool,
15928 ranges: Vec<Range<Anchor>>,
15929 cx: &mut Context<Self>,
15930 ) {
15931 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15932 cx.spawn(async move |this, cx| {
15933 task.await?;
15934 this.update(cx, |this, cx| {
15935 let snapshot = this.buffer.read(cx).snapshot(cx);
15936 let chunk_by = this
15937 .diff_hunks_in_ranges(&ranges, &snapshot)
15938 .chunk_by(|hunk| hunk.buffer_id);
15939 for (buffer_id, hunks) in &chunk_by {
15940 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15941 }
15942 })
15943 })
15944 .detach_and_log_err(cx);
15945 }
15946
15947 fn save_buffers_for_ranges_if_needed(
15948 &mut self,
15949 ranges: &[Range<Anchor>],
15950 cx: &mut Context<Editor>,
15951 ) -> Task<Result<()>> {
15952 let multibuffer = self.buffer.read(cx);
15953 let snapshot = multibuffer.read(cx);
15954 let buffer_ids: HashSet<_> = ranges
15955 .iter()
15956 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15957 .collect();
15958 drop(snapshot);
15959
15960 let mut buffers = HashSet::default();
15961 for buffer_id in buffer_ids {
15962 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15963 let buffer = buffer_entity.read(cx);
15964 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15965 {
15966 buffers.insert(buffer_entity);
15967 }
15968 }
15969 }
15970
15971 if let Some(project) = &self.project {
15972 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15973 } else {
15974 Task::ready(Ok(()))
15975 }
15976 }
15977
15978 fn do_stage_or_unstage_and_next(
15979 &mut self,
15980 stage: bool,
15981 window: &mut Window,
15982 cx: &mut Context<Self>,
15983 ) {
15984 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15985
15986 if ranges.iter().any(|range| range.start != range.end) {
15987 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15988 return;
15989 }
15990
15991 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15992 let snapshot = self.snapshot(window, cx);
15993 let position = self.selections.newest::<Point>(cx).head();
15994 let mut row = snapshot
15995 .buffer_snapshot
15996 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15997 .find(|hunk| hunk.row_range.start.0 > position.row)
15998 .map(|hunk| hunk.row_range.start);
15999
16000 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
16001 // Outside of the project diff editor, wrap around to the beginning.
16002 if !all_diff_hunks_expanded {
16003 row = row.or_else(|| {
16004 snapshot
16005 .buffer_snapshot
16006 .diff_hunks_in_range(Point::zero()..position)
16007 .find(|hunk| hunk.row_range.end.0 < position.row)
16008 .map(|hunk| hunk.row_range.start)
16009 });
16010 }
16011
16012 if let Some(row) = row {
16013 let destination = Point::new(row.0, 0);
16014 let autoscroll = Autoscroll::center();
16015
16016 self.unfold_ranges(&[destination..destination], false, false, cx);
16017 self.change_selections(Some(autoscroll), window, cx, |s| {
16018 s.select_ranges([destination..destination]);
16019 });
16020 }
16021 }
16022
16023 fn do_stage_or_unstage(
16024 &self,
16025 stage: bool,
16026 buffer_id: BufferId,
16027 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16028 cx: &mut App,
16029 ) -> Option<()> {
16030 let project = self.project.as_ref()?;
16031 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16032 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16033 let buffer_snapshot = buffer.read(cx).snapshot();
16034 let file_exists = buffer_snapshot
16035 .file()
16036 .is_some_and(|file| file.disk_state().exists());
16037 diff.update(cx, |diff, cx| {
16038 diff.stage_or_unstage_hunks(
16039 stage,
16040 &hunks
16041 .map(|hunk| buffer_diff::DiffHunk {
16042 buffer_range: hunk.buffer_range,
16043 diff_base_byte_range: hunk.diff_base_byte_range,
16044 secondary_status: hunk.secondary_status,
16045 range: Point::zero()..Point::zero(), // unused
16046 })
16047 .collect::<Vec<_>>(),
16048 &buffer_snapshot,
16049 file_exists,
16050 cx,
16051 )
16052 });
16053 None
16054 }
16055
16056 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16057 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16058 self.buffer
16059 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16060 }
16061
16062 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16063 self.buffer.update(cx, |buffer, cx| {
16064 let ranges = vec![Anchor::min()..Anchor::max()];
16065 if !buffer.all_diff_hunks_expanded()
16066 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16067 {
16068 buffer.collapse_diff_hunks(ranges, cx);
16069 true
16070 } else {
16071 false
16072 }
16073 })
16074 }
16075
16076 fn toggle_diff_hunks_in_ranges(
16077 &mut self,
16078 ranges: Vec<Range<Anchor>>,
16079 cx: &mut Context<Editor>,
16080 ) {
16081 self.buffer.update(cx, |buffer, cx| {
16082 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16083 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16084 })
16085 }
16086
16087 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16088 self.buffer.update(cx, |buffer, cx| {
16089 let snapshot = buffer.snapshot(cx);
16090 let excerpt_id = range.end.excerpt_id;
16091 let point_range = range.to_point(&snapshot);
16092 let expand = !buffer.single_hunk_is_expanded(range, cx);
16093 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16094 })
16095 }
16096
16097 pub(crate) fn apply_all_diff_hunks(
16098 &mut self,
16099 _: &ApplyAllDiffHunks,
16100 window: &mut Window,
16101 cx: &mut Context<Self>,
16102 ) {
16103 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16104
16105 let buffers = self.buffer.read(cx).all_buffers();
16106 for branch_buffer in buffers {
16107 branch_buffer.update(cx, |branch_buffer, cx| {
16108 branch_buffer.merge_into_base(Vec::new(), cx);
16109 });
16110 }
16111
16112 if let Some(project) = self.project.clone() {
16113 self.save(true, project, window, cx).detach_and_log_err(cx);
16114 }
16115 }
16116
16117 pub(crate) fn apply_selected_diff_hunks(
16118 &mut self,
16119 _: &ApplyDiffHunk,
16120 window: &mut Window,
16121 cx: &mut Context<Self>,
16122 ) {
16123 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16124 let snapshot = self.snapshot(window, cx);
16125 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16126 let mut ranges_by_buffer = HashMap::default();
16127 self.transact(window, cx, |editor, _window, cx| {
16128 for hunk in hunks {
16129 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16130 ranges_by_buffer
16131 .entry(buffer.clone())
16132 .or_insert_with(Vec::new)
16133 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16134 }
16135 }
16136
16137 for (buffer, ranges) in ranges_by_buffer {
16138 buffer.update(cx, |buffer, cx| {
16139 buffer.merge_into_base(ranges, cx);
16140 });
16141 }
16142 });
16143
16144 if let Some(project) = self.project.clone() {
16145 self.save(true, project, window, cx).detach_and_log_err(cx);
16146 }
16147 }
16148
16149 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16150 if hovered != self.gutter_hovered {
16151 self.gutter_hovered = hovered;
16152 cx.notify();
16153 }
16154 }
16155
16156 pub fn insert_blocks(
16157 &mut self,
16158 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16159 autoscroll: Option<Autoscroll>,
16160 cx: &mut Context<Self>,
16161 ) -> Vec<CustomBlockId> {
16162 let blocks = self
16163 .display_map
16164 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16165 if let Some(autoscroll) = autoscroll {
16166 self.request_autoscroll(autoscroll, cx);
16167 }
16168 cx.notify();
16169 blocks
16170 }
16171
16172 pub fn resize_blocks(
16173 &mut self,
16174 heights: HashMap<CustomBlockId, u32>,
16175 autoscroll: Option<Autoscroll>,
16176 cx: &mut Context<Self>,
16177 ) {
16178 self.display_map
16179 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16180 if let Some(autoscroll) = autoscroll {
16181 self.request_autoscroll(autoscroll, cx);
16182 }
16183 cx.notify();
16184 }
16185
16186 pub fn replace_blocks(
16187 &mut self,
16188 renderers: HashMap<CustomBlockId, RenderBlock>,
16189 autoscroll: Option<Autoscroll>,
16190 cx: &mut Context<Self>,
16191 ) {
16192 self.display_map
16193 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16194 if let Some(autoscroll) = autoscroll {
16195 self.request_autoscroll(autoscroll, cx);
16196 }
16197 cx.notify();
16198 }
16199
16200 pub fn remove_blocks(
16201 &mut self,
16202 block_ids: HashSet<CustomBlockId>,
16203 autoscroll: Option<Autoscroll>,
16204 cx: &mut Context<Self>,
16205 ) {
16206 self.display_map.update(cx, |display_map, cx| {
16207 display_map.remove_blocks(block_ids, cx)
16208 });
16209 if let Some(autoscroll) = autoscroll {
16210 self.request_autoscroll(autoscroll, cx);
16211 }
16212 cx.notify();
16213 }
16214
16215 pub fn row_for_block(
16216 &self,
16217 block_id: CustomBlockId,
16218 cx: &mut Context<Self>,
16219 ) -> Option<DisplayRow> {
16220 self.display_map
16221 .update(cx, |map, cx| map.row_for_block(block_id, cx))
16222 }
16223
16224 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16225 self.focused_block = Some(focused_block);
16226 }
16227
16228 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16229 self.focused_block.take()
16230 }
16231
16232 pub fn insert_creases(
16233 &mut self,
16234 creases: impl IntoIterator<Item = Crease<Anchor>>,
16235 cx: &mut Context<Self>,
16236 ) -> Vec<CreaseId> {
16237 self.display_map
16238 .update(cx, |map, cx| map.insert_creases(creases, cx))
16239 }
16240
16241 pub fn remove_creases(
16242 &mut self,
16243 ids: impl IntoIterator<Item = CreaseId>,
16244 cx: &mut Context<Self>,
16245 ) -> Vec<(CreaseId, Range<Anchor>)> {
16246 self.display_map
16247 .update(cx, |map, cx| map.remove_creases(ids, cx))
16248 }
16249
16250 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16251 self.display_map
16252 .update(cx, |map, cx| map.snapshot(cx))
16253 .longest_row()
16254 }
16255
16256 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16257 self.display_map
16258 .update(cx, |map, cx| map.snapshot(cx))
16259 .max_point()
16260 }
16261
16262 pub fn text(&self, cx: &App) -> String {
16263 self.buffer.read(cx).read(cx).text()
16264 }
16265
16266 pub fn is_empty(&self, cx: &App) -> bool {
16267 self.buffer.read(cx).read(cx).is_empty()
16268 }
16269
16270 pub fn text_option(&self, cx: &App) -> Option<String> {
16271 let text = self.text(cx);
16272 let text = text.trim();
16273
16274 if text.is_empty() {
16275 return None;
16276 }
16277
16278 Some(text.to_string())
16279 }
16280
16281 pub fn set_text(
16282 &mut self,
16283 text: impl Into<Arc<str>>,
16284 window: &mut Window,
16285 cx: &mut Context<Self>,
16286 ) {
16287 self.transact(window, cx, |this, _, cx| {
16288 this.buffer
16289 .read(cx)
16290 .as_singleton()
16291 .expect("you can only call set_text on editors for singleton buffers")
16292 .update(cx, |buffer, cx| buffer.set_text(text, cx));
16293 });
16294 }
16295
16296 pub fn display_text(&self, cx: &mut App) -> String {
16297 self.display_map
16298 .update(cx, |map, cx| map.snapshot(cx))
16299 .text()
16300 }
16301
16302 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16303 let mut wrap_guides = smallvec::smallvec![];
16304
16305 if self.show_wrap_guides == Some(false) {
16306 return wrap_guides;
16307 }
16308
16309 let settings = self.buffer.read(cx).language_settings(cx);
16310 if settings.show_wrap_guides {
16311 match self.soft_wrap_mode(cx) {
16312 SoftWrap::Column(soft_wrap) => {
16313 wrap_guides.push((soft_wrap as usize, true));
16314 }
16315 SoftWrap::Bounded(soft_wrap) => {
16316 wrap_guides.push((soft_wrap as usize, true));
16317 }
16318 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16319 }
16320 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16321 }
16322
16323 wrap_guides
16324 }
16325
16326 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16327 let settings = self.buffer.read(cx).language_settings(cx);
16328 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16329 match mode {
16330 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16331 SoftWrap::None
16332 }
16333 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16334 language_settings::SoftWrap::PreferredLineLength => {
16335 SoftWrap::Column(settings.preferred_line_length)
16336 }
16337 language_settings::SoftWrap::Bounded => {
16338 SoftWrap::Bounded(settings.preferred_line_length)
16339 }
16340 }
16341 }
16342
16343 pub fn set_soft_wrap_mode(
16344 &mut self,
16345 mode: language_settings::SoftWrap,
16346
16347 cx: &mut Context<Self>,
16348 ) {
16349 self.soft_wrap_mode_override = Some(mode);
16350 cx.notify();
16351 }
16352
16353 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16354 self.hard_wrap = hard_wrap;
16355 cx.notify();
16356 }
16357
16358 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16359 self.text_style_refinement = Some(style);
16360 }
16361
16362 /// called by the Element so we know what style we were most recently rendered with.
16363 pub(crate) fn set_style(
16364 &mut self,
16365 style: EditorStyle,
16366 window: &mut Window,
16367 cx: &mut Context<Self>,
16368 ) {
16369 let rem_size = window.rem_size();
16370 self.display_map.update(cx, |map, cx| {
16371 map.set_font(
16372 style.text.font(),
16373 style.text.font_size.to_pixels(rem_size),
16374 cx,
16375 )
16376 });
16377 self.style = Some(style);
16378 }
16379
16380 pub fn style(&self) -> Option<&EditorStyle> {
16381 self.style.as_ref()
16382 }
16383
16384 // Called by the element. This method is not designed to be called outside of the editor
16385 // element's layout code because it does not notify when rewrapping is computed synchronously.
16386 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16387 self.display_map
16388 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16389 }
16390
16391 pub fn set_soft_wrap(&mut self) {
16392 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16393 }
16394
16395 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16396 if self.soft_wrap_mode_override.is_some() {
16397 self.soft_wrap_mode_override.take();
16398 } else {
16399 let soft_wrap = match self.soft_wrap_mode(cx) {
16400 SoftWrap::GitDiff => return,
16401 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16402 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16403 language_settings::SoftWrap::None
16404 }
16405 };
16406 self.soft_wrap_mode_override = Some(soft_wrap);
16407 }
16408 cx.notify();
16409 }
16410
16411 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16412 let Some(workspace) = self.workspace() else {
16413 return;
16414 };
16415 let fs = workspace.read(cx).app_state().fs.clone();
16416 let current_show = TabBarSettings::get_global(cx).show;
16417 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16418 setting.show = Some(!current_show);
16419 });
16420 }
16421
16422 pub fn toggle_indent_guides(
16423 &mut self,
16424 _: &ToggleIndentGuides,
16425 _: &mut Window,
16426 cx: &mut Context<Self>,
16427 ) {
16428 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16429 self.buffer
16430 .read(cx)
16431 .language_settings(cx)
16432 .indent_guides
16433 .enabled
16434 });
16435 self.show_indent_guides = Some(!currently_enabled);
16436 cx.notify();
16437 }
16438
16439 fn should_show_indent_guides(&self) -> Option<bool> {
16440 self.show_indent_guides
16441 }
16442
16443 pub fn toggle_line_numbers(
16444 &mut self,
16445 _: &ToggleLineNumbers,
16446 _: &mut Window,
16447 cx: &mut Context<Self>,
16448 ) {
16449 let mut editor_settings = EditorSettings::get_global(cx).clone();
16450 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16451 EditorSettings::override_global(editor_settings, cx);
16452 }
16453
16454 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16455 if let Some(show_line_numbers) = self.show_line_numbers {
16456 return show_line_numbers;
16457 }
16458 EditorSettings::get_global(cx).gutter.line_numbers
16459 }
16460
16461 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16462 self.use_relative_line_numbers
16463 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16464 }
16465
16466 pub fn toggle_relative_line_numbers(
16467 &mut self,
16468 _: &ToggleRelativeLineNumbers,
16469 _: &mut Window,
16470 cx: &mut Context<Self>,
16471 ) {
16472 let is_relative = self.should_use_relative_line_numbers(cx);
16473 self.set_relative_line_number(Some(!is_relative), cx)
16474 }
16475
16476 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16477 self.use_relative_line_numbers = is_relative;
16478 cx.notify();
16479 }
16480
16481 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16482 self.show_gutter = show_gutter;
16483 cx.notify();
16484 }
16485
16486 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16487 self.show_scrollbars = show_scrollbars;
16488 cx.notify();
16489 }
16490
16491 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16492 self.show_line_numbers = Some(show_line_numbers);
16493 cx.notify();
16494 }
16495
16496 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16497 self.disable_expand_excerpt_buttons = true;
16498 cx.notify();
16499 }
16500
16501 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16502 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16503 cx.notify();
16504 }
16505
16506 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16507 self.show_code_actions = Some(show_code_actions);
16508 cx.notify();
16509 }
16510
16511 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16512 self.show_runnables = Some(show_runnables);
16513 cx.notify();
16514 }
16515
16516 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16517 self.show_breakpoints = Some(show_breakpoints);
16518 cx.notify();
16519 }
16520
16521 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16522 if self.display_map.read(cx).masked != masked {
16523 self.display_map.update(cx, |map, _| map.masked = masked);
16524 }
16525 cx.notify()
16526 }
16527
16528 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16529 self.show_wrap_guides = Some(show_wrap_guides);
16530 cx.notify();
16531 }
16532
16533 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16534 self.show_indent_guides = Some(show_indent_guides);
16535 cx.notify();
16536 }
16537
16538 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16539 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16540 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16541 if let Some(dir) = file.abs_path(cx).parent() {
16542 return Some(dir.to_owned());
16543 }
16544 }
16545
16546 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16547 return Some(project_path.path.to_path_buf());
16548 }
16549 }
16550
16551 None
16552 }
16553
16554 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16555 self.active_excerpt(cx)?
16556 .1
16557 .read(cx)
16558 .file()
16559 .and_then(|f| f.as_local())
16560 }
16561
16562 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16563 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16564 let buffer = buffer.read(cx);
16565 if let Some(project_path) = buffer.project_path(cx) {
16566 let project = self.project.as_ref()?.read(cx);
16567 project.absolute_path(&project_path, cx)
16568 } else {
16569 buffer
16570 .file()
16571 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16572 }
16573 })
16574 }
16575
16576 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16577 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16578 let project_path = buffer.read(cx).project_path(cx)?;
16579 let project = self.project.as_ref()?.read(cx);
16580 let entry = project.entry_for_path(&project_path, cx)?;
16581 let path = entry.path.to_path_buf();
16582 Some(path)
16583 })
16584 }
16585
16586 pub fn reveal_in_finder(
16587 &mut self,
16588 _: &RevealInFileManager,
16589 _window: &mut Window,
16590 cx: &mut Context<Self>,
16591 ) {
16592 if let Some(target) = self.target_file(cx) {
16593 cx.reveal_path(&target.abs_path(cx));
16594 }
16595 }
16596
16597 pub fn copy_path(
16598 &mut self,
16599 _: &zed_actions::workspace::CopyPath,
16600 _window: &mut Window,
16601 cx: &mut Context<Self>,
16602 ) {
16603 if let Some(path) = self.target_file_abs_path(cx) {
16604 if let Some(path) = path.to_str() {
16605 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16606 }
16607 }
16608 }
16609
16610 pub fn copy_relative_path(
16611 &mut self,
16612 _: &zed_actions::workspace::CopyRelativePath,
16613 _window: &mut Window,
16614 cx: &mut Context<Self>,
16615 ) {
16616 if let Some(path) = self.target_file_path(cx) {
16617 if let Some(path) = path.to_str() {
16618 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16619 }
16620 }
16621 }
16622
16623 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16624 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16625 buffer.read(cx).project_path(cx)
16626 } else {
16627 None
16628 }
16629 }
16630
16631 // Returns true if the editor handled a go-to-line request
16632 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16633 maybe!({
16634 let breakpoint_store = self.breakpoint_store.as_ref()?;
16635
16636 let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16637 else {
16638 self.clear_row_highlights::<ActiveDebugLine>();
16639 return None;
16640 };
16641
16642 let position = active_stack_frame.position;
16643 let buffer_id = position.buffer_id?;
16644 let snapshot = self
16645 .project
16646 .as_ref()?
16647 .read(cx)
16648 .buffer_for_id(buffer_id, cx)?
16649 .read(cx)
16650 .snapshot();
16651
16652 let mut handled = false;
16653 for (id, ExcerptRange { context, .. }) in
16654 self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16655 {
16656 if context.start.cmp(&position, &snapshot).is_ge()
16657 || context.end.cmp(&position, &snapshot).is_lt()
16658 {
16659 continue;
16660 }
16661 let snapshot = self.buffer.read(cx).snapshot(cx);
16662 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16663
16664 handled = true;
16665 self.clear_row_highlights::<ActiveDebugLine>();
16666 self.go_to_line::<ActiveDebugLine>(
16667 multibuffer_anchor,
16668 Some(cx.theme().colors().editor_debugger_active_line_background),
16669 window,
16670 cx,
16671 );
16672
16673 cx.notify();
16674 }
16675
16676 handled.then_some(())
16677 })
16678 .is_some()
16679 }
16680
16681 pub fn copy_file_name_without_extension(
16682 &mut self,
16683 _: &CopyFileNameWithoutExtension,
16684 _: &mut Window,
16685 cx: &mut Context<Self>,
16686 ) {
16687 if let Some(file) = self.target_file(cx) {
16688 if let Some(file_stem) = file.path().file_stem() {
16689 if let Some(name) = file_stem.to_str() {
16690 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16691 }
16692 }
16693 }
16694 }
16695
16696 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16697 if let Some(file) = self.target_file(cx) {
16698 if let Some(file_name) = file.path().file_name() {
16699 if let Some(name) = file_name.to_str() {
16700 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16701 }
16702 }
16703 }
16704 }
16705
16706 pub fn toggle_git_blame(
16707 &mut self,
16708 _: &::git::Blame,
16709 window: &mut Window,
16710 cx: &mut Context<Self>,
16711 ) {
16712 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16713
16714 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16715 self.start_git_blame(true, window, cx);
16716 }
16717
16718 cx.notify();
16719 }
16720
16721 pub fn toggle_git_blame_inline(
16722 &mut self,
16723 _: &ToggleGitBlameInline,
16724 window: &mut Window,
16725 cx: &mut Context<Self>,
16726 ) {
16727 self.toggle_git_blame_inline_internal(true, window, cx);
16728 cx.notify();
16729 }
16730
16731 pub fn open_git_blame_commit(
16732 &mut self,
16733 _: &OpenGitBlameCommit,
16734 window: &mut Window,
16735 cx: &mut Context<Self>,
16736 ) {
16737 self.open_git_blame_commit_internal(window, cx);
16738 }
16739
16740 fn open_git_blame_commit_internal(
16741 &mut self,
16742 window: &mut Window,
16743 cx: &mut Context<Self>,
16744 ) -> Option<()> {
16745 let blame = self.blame.as_ref()?;
16746 let snapshot = self.snapshot(window, cx);
16747 let cursor = self.selections.newest::<Point>(cx).head();
16748 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16749 let blame_entry = blame
16750 .update(cx, |blame, cx| {
16751 blame
16752 .blame_for_rows(
16753 &[RowInfo {
16754 buffer_id: Some(buffer.remote_id()),
16755 buffer_row: Some(point.row),
16756 ..Default::default()
16757 }],
16758 cx,
16759 )
16760 .next()
16761 })
16762 .flatten()?;
16763 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16764 let repo = blame.read(cx).repository(cx)?;
16765 let workspace = self.workspace()?.downgrade();
16766 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16767 None
16768 }
16769
16770 pub fn git_blame_inline_enabled(&self) -> bool {
16771 self.git_blame_inline_enabled
16772 }
16773
16774 pub fn toggle_selection_menu(
16775 &mut self,
16776 _: &ToggleSelectionMenu,
16777 _: &mut Window,
16778 cx: &mut Context<Self>,
16779 ) {
16780 self.show_selection_menu = self
16781 .show_selection_menu
16782 .map(|show_selections_menu| !show_selections_menu)
16783 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16784
16785 cx.notify();
16786 }
16787
16788 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16789 self.show_selection_menu
16790 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16791 }
16792
16793 fn start_git_blame(
16794 &mut self,
16795 user_triggered: bool,
16796 window: &mut Window,
16797 cx: &mut Context<Self>,
16798 ) {
16799 if let Some(project) = self.project.as_ref() {
16800 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16801 return;
16802 };
16803
16804 if buffer.read(cx).file().is_none() {
16805 return;
16806 }
16807
16808 let focused = self.focus_handle(cx).contains_focused(window, cx);
16809
16810 let project = project.clone();
16811 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16812 self.blame_subscription =
16813 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16814 self.blame = Some(blame);
16815 }
16816 }
16817
16818 fn toggle_git_blame_inline_internal(
16819 &mut self,
16820 user_triggered: bool,
16821 window: &mut Window,
16822 cx: &mut Context<Self>,
16823 ) {
16824 if self.git_blame_inline_enabled {
16825 self.git_blame_inline_enabled = false;
16826 self.show_git_blame_inline = false;
16827 self.show_git_blame_inline_delay_task.take();
16828 } else {
16829 self.git_blame_inline_enabled = true;
16830 self.start_git_blame_inline(user_triggered, window, cx);
16831 }
16832
16833 cx.notify();
16834 }
16835
16836 fn start_git_blame_inline(
16837 &mut self,
16838 user_triggered: bool,
16839 window: &mut Window,
16840 cx: &mut Context<Self>,
16841 ) {
16842 self.start_git_blame(user_triggered, window, cx);
16843
16844 if ProjectSettings::get_global(cx)
16845 .git
16846 .inline_blame_delay()
16847 .is_some()
16848 {
16849 self.start_inline_blame_timer(window, cx);
16850 } else {
16851 self.show_git_blame_inline = true
16852 }
16853 }
16854
16855 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16856 self.blame.as_ref()
16857 }
16858
16859 pub fn show_git_blame_gutter(&self) -> bool {
16860 self.show_git_blame_gutter
16861 }
16862
16863 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16864 self.show_git_blame_gutter && self.has_blame_entries(cx)
16865 }
16866
16867 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16868 self.show_git_blame_inline
16869 && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16870 && !self.newest_selection_head_on_empty_line(cx)
16871 && self.has_blame_entries(cx)
16872 }
16873
16874 fn has_blame_entries(&self, cx: &App) -> bool {
16875 self.blame()
16876 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16877 }
16878
16879 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16880 let cursor_anchor = self.selections.newest_anchor().head();
16881
16882 let snapshot = self.buffer.read(cx).snapshot(cx);
16883 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16884
16885 snapshot.line_len(buffer_row) == 0
16886 }
16887
16888 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16889 let buffer_and_selection = maybe!({
16890 let selection = self.selections.newest::<Point>(cx);
16891 let selection_range = selection.range();
16892
16893 let multi_buffer = self.buffer().read(cx);
16894 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16895 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16896
16897 let (buffer, range, _) = if selection.reversed {
16898 buffer_ranges.first()
16899 } else {
16900 buffer_ranges.last()
16901 }?;
16902
16903 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16904 ..text::ToPoint::to_point(&range.end, &buffer).row;
16905 Some((
16906 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16907 selection,
16908 ))
16909 });
16910
16911 let Some((buffer, selection)) = buffer_and_selection else {
16912 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16913 };
16914
16915 let Some(project) = self.project.as_ref() else {
16916 return Task::ready(Err(anyhow!("editor does not have project")));
16917 };
16918
16919 project.update(cx, |project, cx| {
16920 project.get_permalink_to_line(&buffer, selection, cx)
16921 })
16922 }
16923
16924 pub fn copy_permalink_to_line(
16925 &mut self,
16926 _: &CopyPermalinkToLine,
16927 window: &mut Window,
16928 cx: &mut Context<Self>,
16929 ) {
16930 let permalink_task = self.get_permalink_to_line(cx);
16931 let workspace = self.workspace();
16932
16933 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16934 Ok(permalink) => {
16935 cx.update(|_, cx| {
16936 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16937 })
16938 .ok();
16939 }
16940 Err(err) => {
16941 let message = format!("Failed to copy permalink: {err}");
16942
16943 Err::<(), anyhow::Error>(err).log_err();
16944
16945 if let Some(workspace) = workspace {
16946 workspace
16947 .update_in(cx, |workspace, _, cx| {
16948 struct CopyPermalinkToLine;
16949
16950 workspace.show_toast(
16951 Toast::new(
16952 NotificationId::unique::<CopyPermalinkToLine>(),
16953 message,
16954 ),
16955 cx,
16956 )
16957 })
16958 .ok();
16959 }
16960 }
16961 })
16962 .detach();
16963 }
16964
16965 pub fn copy_file_location(
16966 &mut self,
16967 _: &CopyFileLocation,
16968 _: &mut Window,
16969 cx: &mut Context<Self>,
16970 ) {
16971 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16972 if let Some(file) = self.target_file(cx) {
16973 if let Some(path) = file.path().to_str() {
16974 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16975 }
16976 }
16977 }
16978
16979 pub fn open_permalink_to_line(
16980 &mut self,
16981 _: &OpenPermalinkToLine,
16982 window: &mut Window,
16983 cx: &mut Context<Self>,
16984 ) {
16985 let permalink_task = self.get_permalink_to_line(cx);
16986 let workspace = self.workspace();
16987
16988 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16989 Ok(permalink) => {
16990 cx.update(|_, cx| {
16991 cx.open_url(permalink.as_ref());
16992 })
16993 .ok();
16994 }
16995 Err(err) => {
16996 let message = format!("Failed to open permalink: {err}");
16997
16998 Err::<(), anyhow::Error>(err).log_err();
16999
17000 if let Some(workspace) = workspace {
17001 workspace
17002 .update(cx, |workspace, cx| {
17003 struct OpenPermalinkToLine;
17004
17005 workspace.show_toast(
17006 Toast::new(
17007 NotificationId::unique::<OpenPermalinkToLine>(),
17008 message,
17009 ),
17010 cx,
17011 )
17012 })
17013 .ok();
17014 }
17015 }
17016 })
17017 .detach();
17018 }
17019
17020 pub fn insert_uuid_v4(
17021 &mut self,
17022 _: &InsertUuidV4,
17023 window: &mut Window,
17024 cx: &mut Context<Self>,
17025 ) {
17026 self.insert_uuid(UuidVersion::V4, window, cx);
17027 }
17028
17029 pub fn insert_uuid_v7(
17030 &mut self,
17031 _: &InsertUuidV7,
17032 window: &mut Window,
17033 cx: &mut Context<Self>,
17034 ) {
17035 self.insert_uuid(UuidVersion::V7, window, cx);
17036 }
17037
17038 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17039 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17040 self.transact(window, cx, |this, window, cx| {
17041 let edits = this
17042 .selections
17043 .all::<Point>(cx)
17044 .into_iter()
17045 .map(|selection| {
17046 let uuid = match version {
17047 UuidVersion::V4 => uuid::Uuid::new_v4(),
17048 UuidVersion::V7 => uuid::Uuid::now_v7(),
17049 };
17050
17051 (selection.range(), uuid.to_string())
17052 });
17053 this.edit(edits, cx);
17054 this.refresh_inline_completion(true, false, window, cx);
17055 });
17056 }
17057
17058 pub fn open_selections_in_multibuffer(
17059 &mut self,
17060 _: &OpenSelectionsInMultibuffer,
17061 window: &mut Window,
17062 cx: &mut Context<Self>,
17063 ) {
17064 let multibuffer = self.buffer.read(cx);
17065
17066 let Some(buffer) = multibuffer.as_singleton() else {
17067 return;
17068 };
17069
17070 let Some(workspace) = self.workspace() else {
17071 return;
17072 };
17073
17074 let locations = self
17075 .selections
17076 .disjoint_anchors()
17077 .iter()
17078 .map(|range| Location {
17079 buffer: buffer.clone(),
17080 range: range.start.text_anchor..range.end.text_anchor,
17081 })
17082 .collect::<Vec<_>>();
17083
17084 let title = multibuffer.title(cx).to_string();
17085
17086 cx.spawn_in(window, async move |_, cx| {
17087 workspace.update_in(cx, |workspace, window, cx| {
17088 Self::open_locations_in_multibuffer(
17089 workspace,
17090 locations,
17091 format!("Selections for '{title}'"),
17092 false,
17093 MultibufferSelectionMode::All,
17094 window,
17095 cx,
17096 );
17097 })
17098 })
17099 .detach();
17100 }
17101
17102 /// Adds a row highlight for the given range. If a row has multiple highlights, the
17103 /// last highlight added will be used.
17104 ///
17105 /// If the range ends at the beginning of a line, then that line will not be highlighted.
17106 pub fn highlight_rows<T: 'static>(
17107 &mut self,
17108 range: Range<Anchor>,
17109 color: Hsla,
17110 options: RowHighlightOptions,
17111 cx: &mut Context<Self>,
17112 ) {
17113 let snapshot = self.buffer().read(cx).snapshot(cx);
17114 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17115 let ix = row_highlights.binary_search_by(|highlight| {
17116 Ordering::Equal
17117 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17118 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17119 });
17120
17121 if let Err(mut ix) = ix {
17122 let index = post_inc(&mut self.highlight_order);
17123
17124 // If this range intersects with the preceding highlight, then merge it with
17125 // the preceding highlight. Otherwise insert a new highlight.
17126 let mut merged = false;
17127 if ix > 0 {
17128 let prev_highlight = &mut row_highlights[ix - 1];
17129 if prev_highlight
17130 .range
17131 .end
17132 .cmp(&range.start, &snapshot)
17133 .is_ge()
17134 {
17135 ix -= 1;
17136 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17137 prev_highlight.range.end = range.end;
17138 }
17139 merged = true;
17140 prev_highlight.index = index;
17141 prev_highlight.color = color;
17142 prev_highlight.options = options;
17143 }
17144 }
17145
17146 if !merged {
17147 row_highlights.insert(
17148 ix,
17149 RowHighlight {
17150 range: range.clone(),
17151 index,
17152 color,
17153 options,
17154 type_id: TypeId::of::<T>(),
17155 },
17156 );
17157 }
17158
17159 // If any of the following highlights intersect with this one, merge them.
17160 while let Some(next_highlight) = row_highlights.get(ix + 1) {
17161 let highlight = &row_highlights[ix];
17162 if next_highlight
17163 .range
17164 .start
17165 .cmp(&highlight.range.end, &snapshot)
17166 .is_le()
17167 {
17168 if next_highlight
17169 .range
17170 .end
17171 .cmp(&highlight.range.end, &snapshot)
17172 .is_gt()
17173 {
17174 row_highlights[ix].range.end = next_highlight.range.end;
17175 }
17176 row_highlights.remove(ix + 1);
17177 } else {
17178 break;
17179 }
17180 }
17181 }
17182 }
17183
17184 /// Remove any highlighted row ranges of the given type that intersect the
17185 /// given ranges.
17186 pub fn remove_highlighted_rows<T: 'static>(
17187 &mut self,
17188 ranges_to_remove: Vec<Range<Anchor>>,
17189 cx: &mut Context<Self>,
17190 ) {
17191 let snapshot = self.buffer().read(cx).snapshot(cx);
17192 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17193 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17194 row_highlights.retain(|highlight| {
17195 while let Some(range_to_remove) = ranges_to_remove.peek() {
17196 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17197 Ordering::Less | Ordering::Equal => {
17198 ranges_to_remove.next();
17199 }
17200 Ordering::Greater => {
17201 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17202 Ordering::Less | Ordering::Equal => {
17203 return false;
17204 }
17205 Ordering::Greater => break,
17206 }
17207 }
17208 }
17209 }
17210
17211 true
17212 })
17213 }
17214
17215 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17216 pub fn clear_row_highlights<T: 'static>(&mut self) {
17217 self.highlighted_rows.remove(&TypeId::of::<T>());
17218 }
17219
17220 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17221 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17222 self.highlighted_rows
17223 .get(&TypeId::of::<T>())
17224 .map_or(&[] as &[_], |vec| vec.as_slice())
17225 .iter()
17226 .map(|highlight| (highlight.range.clone(), highlight.color))
17227 }
17228
17229 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17230 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17231 /// Allows to ignore certain kinds of highlights.
17232 pub fn highlighted_display_rows(
17233 &self,
17234 window: &mut Window,
17235 cx: &mut App,
17236 ) -> BTreeMap<DisplayRow, LineHighlight> {
17237 let snapshot = self.snapshot(window, cx);
17238 let mut used_highlight_orders = HashMap::default();
17239 self.highlighted_rows
17240 .iter()
17241 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17242 .fold(
17243 BTreeMap::<DisplayRow, LineHighlight>::new(),
17244 |mut unique_rows, highlight| {
17245 let start = highlight.range.start.to_display_point(&snapshot);
17246 let end = highlight.range.end.to_display_point(&snapshot);
17247 let start_row = start.row().0;
17248 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17249 && end.column() == 0
17250 {
17251 end.row().0.saturating_sub(1)
17252 } else {
17253 end.row().0
17254 };
17255 for row in start_row..=end_row {
17256 let used_index =
17257 used_highlight_orders.entry(row).or_insert(highlight.index);
17258 if highlight.index >= *used_index {
17259 *used_index = highlight.index;
17260 unique_rows.insert(
17261 DisplayRow(row),
17262 LineHighlight {
17263 include_gutter: highlight.options.include_gutter,
17264 border: None,
17265 background: highlight.color.into(),
17266 type_id: Some(highlight.type_id),
17267 },
17268 );
17269 }
17270 }
17271 unique_rows
17272 },
17273 )
17274 }
17275
17276 pub fn highlighted_display_row_for_autoscroll(
17277 &self,
17278 snapshot: &DisplaySnapshot,
17279 ) -> Option<DisplayRow> {
17280 self.highlighted_rows
17281 .values()
17282 .flat_map(|highlighted_rows| highlighted_rows.iter())
17283 .filter_map(|highlight| {
17284 if highlight.options.autoscroll {
17285 Some(highlight.range.start.to_display_point(snapshot).row())
17286 } else {
17287 None
17288 }
17289 })
17290 .min()
17291 }
17292
17293 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17294 self.highlight_background::<SearchWithinRange>(
17295 ranges,
17296 |colors| colors.editor_document_highlight_read_background,
17297 cx,
17298 )
17299 }
17300
17301 pub fn set_breadcrumb_header(&mut self, new_header: String) {
17302 self.breadcrumb_header = Some(new_header);
17303 }
17304
17305 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17306 self.clear_background_highlights::<SearchWithinRange>(cx);
17307 }
17308
17309 pub fn highlight_background<T: 'static>(
17310 &mut self,
17311 ranges: &[Range<Anchor>],
17312 color_fetcher: fn(&ThemeColors) -> Hsla,
17313 cx: &mut Context<Self>,
17314 ) {
17315 self.background_highlights
17316 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17317 self.scrollbar_marker_state.dirty = true;
17318 cx.notify();
17319 }
17320
17321 pub fn clear_background_highlights<T: 'static>(
17322 &mut self,
17323 cx: &mut Context<Self>,
17324 ) -> Option<BackgroundHighlight> {
17325 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17326 if !text_highlights.1.is_empty() {
17327 self.scrollbar_marker_state.dirty = true;
17328 cx.notify();
17329 }
17330 Some(text_highlights)
17331 }
17332
17333 pub fn highlight_gutter<T: 'static>(
17334 &mut self,
17335 ranges: &[Range<Anchor>],
17336 color_fetcher: fn(&App) -> Hsla,
17337 cx: &mut Context<Self>,
17338 ) {
17339 self.gutter_highlights
17340 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17341 cx.notify();
17342 }
17343
17344 pub fn clear_gutter_highlights<T: 'static>(
17345 &mut self,
17346 cx: &mut Context<Self>,
17347 ) -> Option<GutterHighlight> {
17348 cx.notify();
17349 self.gutter_highlights.remove(&TypeId::of::<T>())
17350 }
17351
17352 #[cfg(feature = "test-support")]
17353 pub fn all_text_background_highlights(
17354 &self,
17355 window: &mut Window,
17356 cx: &mut Context<Self>,
17357 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17358 let snapshot = self.snapshot(window, cx);
17359 let buffer = &snapshot.buffer_snapshot;
17360 let start = buffer.anchor_before(0);
17361 let end = buffer.anchor_after(buffer.len());
17362 let theme = cx.theme().colors();
17363 self.background_highlights_in_range(start..end, &snapshot, theme)
17364 }
17365
17366 #[cfg(feature = "test-support")]
17367 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17368 let snapshot = self.buffer().read(cx).snapshot(cx);
17369
17370 let highlights = self
17371 .background_highlights
17372 .get(&TypeId::of::<items::BufferSearchHighlights>());
17373
17374 if let Some((_color, ranges)) = highlights {
17375 ranges
17376 .iter()
17377 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17378 .collect_vec()
17379 } else {
17380 vec![]
17381 }
17382 }
17383
17384 fn document_highlights_for_position<'a>(
17385 &'a self,
17386 position: Anchor,
17387 buffer: &'a MultiBufferSnapshot,
17388 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17389 let read_highlights = self
17390 .background_highlights
17391 .get(&TypeId::of::<DocumentHighlightRead>())
17392 .map(|h| &h.1);
17393 let write_highlights = self
17394 .background_highlights
17395 .get(&TypeId::of::<DocumentHighlightWrite>())
17396 .map(|h| &h.1);
17397 let left_position = position.bias_left(buffer);
17398 let right_position = position.bias_right(buffer);
17399 read_highlights
17400 .into_iter()
17401 .chain(write_highlights)
17402 .flat_map(move |ranges| {
17403 let start_ix = match ranges.binary_search_by(|probe| {
17404 let cmp = probe.end.cmp(&left_position, buffer);
17405 if cmp.is_ge() {
17406 Ordering::Greater
17407 } else {
17408 Ordering::Less
17409 }
17410 }) {
17411 Ok(i) | Err(i) => i,
17412 };
17413
17414 ranges[start_ix..]
17415 .iter()
17416 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17417 })
17418 }
17419
17420 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17421 self.background_highlights
17422 .get(&TypeId::of::<T>())
17423 .map_or(false, |(_, highlights)| !highlights.is_empty())
17424 }
17425
17426 pub fn background_highlights_in_range(
17427 &self,
17428 search_range: Range<Anchor>,
17429 display_snapshot: &DisplaySnapshot,
17430 theme: &ThemeColors,
17431 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17432 let mut results = Vec::new();
17433 for (color_fetcher, ranges) in self.background_highlights.values() {
17434 let color = color_fetcher(theme);
17435 let start_ix = match ranges.binary_search_by(|probe| {
17436 let cmp = probe
17437 .end
17438 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17439 if cmp.is_gt() {
17440 Ordering::Greater
17441 } else {
17442 Ordering::Less
17443 }
17444 }) {
17445 Ok(i) | Err(i) => i,
17446 };
17447 for range in &ranges[start_ix..] {
17448 if range
17449 .start
17450 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17451 .is_ge()
17452 {
17453 break;
17454 }
17455
17456 let start = range.start.to_display_point(display_snapshot);
17457 let end = range.end.to_display_point(display_snapshot);
17458 results.push((start..end, color))
17459 }
17460 }
17461 results
17462 }
17463
17464 pub fn background_highlight_row_ranges<T: 'static>(
17465 &self,
17466 search_range: Range<Anchor>,
17467 display_snapshot: &DisplaySnapshot,
17468 count: usize,
17469 ) -> Vec<RangeInclusive<DisplayPoint>> {
17470 let mut results = Vec::new();
17471 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17472 return vec![];
17473 };
17474
17475 let start_ix = match ranges.binary_search_by(|probe| {
17476 let cmp = probe
17477 .end
17478 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17479 if cmp.is_gt() {
17480 Ordering::Greater
17481 } else {
17482 Ordering::Less
17483 }
17484 }) {
17485 Ok(i) | Err(i) => i,
17486 };
17487 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17488 if let (Some(start_display), Some(end_display)) = (start, end) {
17489 results.push(
17490 start_display.to_display_point(display_snapshot)
17491 ..=end_display.to_display_point(display_snapshot),
17492 );
17493 }
17494 };
17495 let mut start_row: Option<Point> = None;
17496 let mut end_row: Option<Point> = None;
17497 if ranges.len() > count {
17498 return Vec::new();
17499 }
17500 for range in &ranges[start_ix..] {
17501 if range
17502 .start
17503 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17504 .is_ge()
17505 {
17506 break;
17507 }
17508 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17509 if let Some(current_row) = &end_row {
17510 if end.row == current_row.row {
17511 continue;
17512 }
17513 }
17514 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17515 if start_row.is_none() {
17516 assert_eq!(end_row, None);
17517 start_row = Some(start);
17518 end_row = Some(end);
17519 continue;
17520 }
17521 if let Some(current_end) = end_row.as_mut() {
17522 if start.row > current_end.row + 1 {
17523 push_region(start_row, end_row);
17524 start_row = Some(start);
17525 end_row = Some(end);
17526 } else {
17527 // Merge two hunks.
17528 *current_end = end;
17529 }
17530 } else {
17531 unreachable!();
17532 }
17533 }
17534 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17535 push_region(start_row, end_row);
17536 results
17537 }
17538
17539 pub fn gutter_highlights_in_range(
17540 &self,
17541 search_range: Range<Anchor>,
17542 display_snapshot: &DisplaySnapshot,
17543 cx: &App,
17544 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17545 let mut results = Vec::new();
17546 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17547 let color = color_fetcher(cx);
17548 let start_ix = match ranges.binary_search_by(|probe| {
17549 let cmp = probe
17550 .end
17551 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17552 if cmp.is_gt() {
17553 Ordering::Greater
17554 } else {
17555 Ordering::Less
17556 }
17557 }) {
17558 Ok(i) | Err(i) => i,
17559 };
17560 for range in &ranges[start_ix..] {
17561 if range
17562 .start
17563 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17564 .is_ge()
17565 {
17566 break;
17567 }
17568
17569 let start = range.start.to_display_point(display_snapshot);
17570 let end = range.end.to_display_point(display_snapshot);
17571 results.push((start..end, color))
17572 }
17573 }
17574 results
17575 }
17576
17577 /// Get the text ranges corresponding to the redaction query
17578 pub fn redacted_ranges(
17579 &self,
17580 search_range: Range<Anchor>,
17581 display_snapshot: &DisplaySnapshot,
17582 cx: &App,
17583 ) -> Vec<Range<DisplayPoint>> {
17584 display_snapshot
17585 .buffer_snapshot
17586 .redacted_ranges(search_range, |file| {
17587 if let Some(file) = file {
17588 file.is_private()
17589 && EditorSettings::get(
17590 Some(SettingsLocation {
17591 worktree_id: file.worktree_id(cx),
17592 path: file.path().as_ref(),
17593 }),
17594 cx,
17595 )
17596 .redact_private_values
17597 } else {
17598 false
17599 }
17600 })
17601 .map(|range| {
17602 range.start.to_display_point(display_snapshot)
17603 ..range.end.to_display_point(display_snapshot)
17604 })
17605 .collect()
17606 }
17607
17608 pub fn highlight_text<T: 'static>(
17609 &mut self,
17610 ranges: Vec<Range<Anchor>>,
17611 style: HighlightStyle,
17612 cx: &mut Context<Self>,
17613 ) {
17614 self.display_map.update(cx, |map, _| {
17615 map.highlight_text(TypeId::of::<T>(), ranges, style)
17616 });
17617 cx.notify();
17618 }
17619
17620 pub(crate) fn highlight_inlays<T: 'static>(
17621 &mut self,
17622 highlights: Vec<InlayHighlight>,
17623 style: HighlightStyle,
17624 cx: &mut Context<Self>,
17625 ) {
17626 self.display_map.update(cx, |map, _| {
17627 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17628 });
17629 cx.notify();
17630 }
17631
17632 pub fn text_highlights<'a, T: 'static>(
17633 &'a self,
17634 cx: &'a App,
17635 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17636 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17637 }
17638
17639 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17640 let cleared = self
17641 .display_map
17642 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17643 if cleared {
17644 cx.notify();
17645 }
17646 }
17647
17648 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17649 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17650 && self.focus_handle.is_focused(window)
17651 }
17652
17653 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17654 self.show_cursor_when_unfocused = is_enabled;
17655 cx.notify();
17656 }
17657
17658 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17659 cx.notify();
17660 }
17661
17662 fn on_debug_session_event(
17663 &mut self,
17664 _session: Entity<Session>,
17665 event: &SessionEvent,
17666 cx: &mut Context<Self>,
17667 ) {
17668 match event {
17669 SessionEvent::InvalidateInlineValue => {
17670 self.refresh_inline_values(cx);
17671 }
17672 _ => {}
17673 }
17674 }
17675
17676 fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17677 let Some(project) = self.project.clone() else {
17678 return;
17679 };
17680 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17681 return;
17682 };
17683 if !self.inline_value_cache.enabled {
17684 let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17685 self.splice_inlays(&inlays, Vec::new(), cx);
17686 return;
17687 }
17688
17689 let current_execution_position = self
17690 .highlighted_rows
17691 .get(&TypeId::of::<ActiveDebugLine>())
17692 .and_then(|lines| lines.last().map(|line| line.range.start));
17693
17694 self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17695 let snapshot = editor
17696 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17697 .ok()?;
17698
17699 let inline_values = editor
17700 .update(cx, |_, cx| {
17701 let Some(current_execution_position) = current_execution_position else {
17702 return Some(Task::ready(Ok(Vec::new())));
17703 };
17704
17705 // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17706 // anchor is in the same buffer
17707 let range =
17708 buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17709 project.inline_values(buffer, range, cx)
17710 })
17711 .ok()
17712 .flatten()?
17713 .await
17714 .context("refreshing debugger inlays")
17715 .log_err()?;
17716
17717 let (excerpt_id, buffer_id) = snapshot
17718 .excerpts()
17719 .next()
17720 .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17721 editor
17722 .update(cx, |editor, cx| {
17723 let new_inlays = inline_values
17724 .into_iter()
17725 .map(|debugger_value| {
17726 Inlay::debugger_hint(
17727 post_inc(&mut editor.next_inlay_id),
17728 Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17729 debugger_value.text(),
17730 )
17731 })
17732 .collect::<Vec<_>>();
17733 let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17734 std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17735
17736 editor.splice_inlays(&inlay_ids, new_inlays, cx);
17737 })
17738 .ok()?;
17739 Some(())
17740 });
17741 }
17742
17743 fn on_buffer_event(
17744 &mut self,
17745 multibuffer: &Entity<MultiBuffer>,
17746 event: &multi_buffer::Event,
17747 window: &mut Window,
17748 cx: &mut Context<Self>,
17749 ) {
17750 match event {
17751 multi_buffer::Event::Edited {
17752 singleton_buffer_edited,
17753 edited_buffer: buffer_edited,
17754 } => {
17755 self.scrollbar_marker_state.dirty = true;
17756 self.active_indent_guides_state.dirty = true;
17757 self.refresh_active_diagnostics(cx);
17758 self.refresh_code_actions(window, cx);
17759 self.refresh_selected_text_highlights(true, window, cx);
17760 refresh_matching_bracket_highlights(self, window, cx);
17761 if self.has_active_inline_completion() {
17762 self.update_visible_inline_completion(window, cx);
17763 }
17764 if let Some(buffer) = buffer_edited {
17765 let buffer_id = buffer.read(cx).remote_id();
17766 if !self.registered_buffers.contains_key(&buffer_id) {
17767 if let Some(project) = self.project.as_ref() {
17768 project.update(cx, |project, cx| {
17769 self.registered_buffers.insert(
17770 buffer_id,
17771 project.register_buffer_with_language_servers(&buffer, cx),
17772 );
17773 })
17774 }
17775 }
17776 }
17777 cx.emit(EditorEvent::BufferEdited);
17778 cx.emit(SearchEvent::MatchesInvalidated);
17779 if *singleton_buffer_edited {
17780 if let Some(project) = &self.project {
17781 #[allow(clippy::mutable_key_type)]
17782 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17783 multibuffer
17784 .all_buffers()
17785 .into_iter()
17786 .filter_map(|buffer| {
17787 buffer.update(cx, |buffer, cx| {
17788 let language = buffer.language()?;
17789 let should_discard = project.update(cx, |project, cx| {
17790 project.is_local()
17791 && !project.has_language_servers_for(buffer, cx)
17792 });
17793 should_discard.not().then_some(language.clone())
17794 })
17795 })
17796 .collect::<HashSet<_>>()
17797 });
17798 if !languages_affected.is_empty() {
17799 self.refresh_inlay_hints(
17800 InlayHintRefreshReason::BufferEdited(languages_affected),
17801 cx,
17802 );
17803 }
17804 }
17805 }
17806
17807 let Some(project) = &self.project else { return };
17808 let (telemetry, is_via_ssh) = {
17809 let project = project.read(cx);
17810 let telemetry = project.client().telemetry().clone();
17811 let is_via_ssh = project.is_via_ssh();
17812 (telemetry, is_via_ssh)
17813 };
17814 refresh_linked_ranges(self, window, cx);
17815 telemetry.log_edit_event("editor", is_via_ssh);
17816 }
17817 multi_buffer::Event::ExcerptsAdded {
17818 buffer,
17819 predecessor,
17820 excerpts,
17821 } => {
17822 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17823 let buffer_id = buffer.read(cx).remote_id();
17824 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17825 if let Some(project) = &self.project {
17826 update_uncommitted_diff_for_buffer(
17827 cx.entity(),
17828 project,
17829 [buffer.clone()],
17830 self.buffer.clone(),
17831 cx,
17832 )
17833 .detach();
17834 }
17835 }
17836 cx.emit(EditorEvent::ExcerptsAdded {
17837 buffer: buffer.clone(),
17838 predecessor: *predecessor,
17839 excerpts: excerpts.clone(),
17840 });
17841 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17842 }
17843 multi_buffer::Event::ExcerptsRemoved {
17844 ids,
17845 removed_buffer_ids,
17846 } => {
17847 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17848 let buffer = self.buffer.read(cx);
17849 self.registered_buffers
17850 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17851 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17852 cx.emit(EditorEvent::ExcerptsRemoved {
17853 ids: ids.clone(),
17854 removed_buffer_ids: removed_buffer_ids.clone(),
17855 })
17856 }
17857 multi_buffer::Event::ExcerptsEdited {
17858 excerpt_ids,
17859 buffer_ids,
17860 } => {
17861 self.display_map.update(cx, |map, cx| {
17862 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17863 });
17864 cx.emit(EditorEvent::ExcerptsEdited {
17865 ids: excerpt_ids.clone(),
17866 })
17867 }
17868 multi_buffer::Event::ExcerptsExpanded { ids } => {
17869 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17870 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17871 }
17872 multi_buffer::Event::Reparsed(buffer_id) => {
17873 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17874 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17875
17876 cx.emit(EditorEvent::Reparsed(*buffer_id));
17877 }
17878 multi_buffer::Event::DiffHunksToggled => {
17879 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17880 }
17881 multi_buffer::Event::LanguageChanged(buffer_id) => {
17882 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17883 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17884 cx.emit(EditorEvent::Reparsed(*buffer_id));
17885 cx.notify();
17886 }
17887 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17888 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17889 multi_buffer::Event::FileHandleChanged
17890 | multi_buffer::Event::Reloaded
17891 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17892 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17893 multi_buffer::Event::DiagnosticsUpdated => {
17894 self.refresh_active_diagnostics(cx);
17895 self.refresh_inline_diagnostics(true, window, cx);
17896 self.scrollbar_marker_state.dirty = true;
17897 cx.notify();
17898 }
17899 _ => {}
17900 };
17901 }
17902
17903 pub fn start_temporary_diff_override(&mut self) {
17904 self.load_diff_task.take();
17905 self.temporary_diff_override = true;
17906 }
17907
17908 pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
17909 self.temporary_diff_override = false;
17910 self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
17911 self.buffer.update(cx, |buffer, cx| {
17912 buffer.set_all_diff_hunks_collapsed(cx);
17913 });
17914
17915 if let Some(project) = self.project.clone() {
17916 self.load_diff_task = Some(
17917 update_uncommitted_diff_for_buffer(
17918 cx.entity(),
17919 &project,
17920 self.buffer.read(cx).all_buffers(),
17921 self.buffer.clone(),
17922 cx,
17923 )
17924 .shared(),
17925 );
17926 }
17927 }
17928
17929 fn on_display_map_changed(
17930 &mut self,
17931 _: Entity<DisplayMap>,
17932 _: &mut Window,
17933 cx: &mut Context<Self>,
17934 ) {
17935 cx.notify();
17936 }
17937
17938 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17939 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17940 self.update_edit_prediction_settings(cx);
17941 self.refresh_inline_completion(true, false, window, cx);
17942 self.refresh_inlay_hints(
17943 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17944 self.selections.newest_anchor().head(),
17945 &self.buffer.read(cx).snapshot(cx),
17946 cx,
17947 )),
17948 cx,
17949 );
17950
17951 let old_cursor_shape = self.cursor_shape;
17952
17953 {
17954 let editor_settings = EditorSettings::get_global(cx);
17955 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17956 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17957 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17958 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17959 }
17960
17961 if old_cursor_shape != self.cursor_shape {
17962 cx.emit(EditorEvent::CursorShapeChanged);
17963 }
17964
17965 let project_settings = ProjectSettings::get_global(cx);
17966 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17967
17968 if self.mode.is_full() {
17969 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17970 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17971 if self.show_inline_diagnostics != show_inline_diagnostics {
17972 self.show_inline_diagnostics = show_inline_diagnostics;
17973 self.refresh_inline_diagnostics(false, window, cx);
17974 }
17975
17976 if self.git_blame_inline_enabled != inline_blame_enabled {
17977 self.toggle_git_blame_inline_internal(false, window, cx);
17978 }
17979 }
17980
17981 cx.notify();
17982 }
17983
17984 pub fn set_searchable(&mut self, searchable: bool) {
17985 self.searchable = searchable;
17986 }
17987
17988 pub fn searchable(&self) -> bool {
17989 self.searchable
17990 }
17991
17992 fn open_proposed_changes_editor(
17993 &mut self,
17994 _: &OpenProposedChangesEditor,
17995 window: &mut Window,
17996 cx: &mut Context<Self>,
17997 ) {
17998 let Some(workspace) = self.workspace() else {
17999 cx.propagate();
18000 return;
18001 };
18002
18003 let selections = self.selections.all::<usize>(cx);
18004 let multi_buffer = self.buffer.read(cx);
18005 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
18006 let mut new_selections_by_buffer = HashMap::default();
18007 for selection in selections {
18008 for (buffer, range, _) in
18009 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18010 {
18011 let mut range = range.to_point(buffer);
18012 range.start.column = 0;
18013 range.end.column = buffer.line_len(range.end.row);
18014 new_selections_by_buffer
18015 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18016 .or_insert(Vec::new())
18017 .push(range)
18018 }
18019 }
18020
18021 let proposed_changes_buffers = new_selections_by_buffer
18022 .into_iter()
18023 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18024 .collect::<Vec<_>>();
18025 let proposed_changes_editor = cx.new(|cx| {
18026 ProposedChangesEditor::new(
18027 "Proposed changes",
18028 proposed_changes_buffers,
18029 self.project.clone(),
18030 window,
18031 cx,
18032 )
18033 });
18034
18035 window.defer(cx, move |window, cx| {
18036 workspace.update(cx, |workspace, cx| {
18037 workspace.active_pane().update(cx, |pane, cx| {
18038 pane.add_item(
18039 Box::new(proposed_changes_editor),
18040 true,
18041 true,
18042 None,
18043 window,
18044 cx,
18045 );
18046 });
18047 });
18048 });
18049 }
18050
18051 pub fn open_excerpts_in_split(
18052 &mut self,
18053 _: &OpenExcerptsSplit,
18054 window: &mut Window,
18055 cx: &mut Context<Self>,
18056 ) {
18057 self.open_excerpts_common(None, true, window, cx)
18058 }
18059
18060 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18061 self.open_excerpts_common(None, false, window, cx)
18062 }
18063
18064 fn open_excerpts_common(
18065 &mut self,
18066 jump_data: Option<JumpData>,
18067 split: bool,
18068 window: &mut Window,
18069 cx: &mut Context<Self>,
18070 ) {
18071 let Some(workspace) = self.workspace() else {
18072 cx.propagate();
18073 return;
18074 };
18075
18076 if self.buffer.read(cx).is_singleton() {
18077 cx.propagate();
18078 return;
18079 }
18080
18081 let mut new_selections_by_buffer = HashMap::default();
18082 match &jump_data {
18083 Some(JumpData::MultiBufferPoint {
18084 excerpt_id,
18085 position,
18086 anchor,
18087 line_offset_from_top,
18088 }) => {
18089 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18090 if let Some(buffer) = multi_buffer_snapshot
18091 .buffer_id_for_excerpt(*excerpt_id)
18092 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18093 {
18094 let buffer_snapshot = buffer.read(cx).snapshot();
18095 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18096 language::ToPoint::to_point(anchor, &buffer_snapshot)
18097 } else {
18098 buffer_snapshot.clip_point(*position, Bias::Left)
18099 };
18100 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18101 new_selections_by_buffer.insert(
18102 buffer,
18103 (
18104 vec![jump_to_offset..jump_to_offset],
18105 Some(*line_offset_from_top),
18106 ),
18107 );
18108 }
18109 }
18110 Some(JumpData::MultiBufferRow {
18111 row,
18112 line_offset_from_top,
18113 }) => {
18114 let point = MultiBufferPoint::new(row.0, 0);
18115 if let Some((buffer, buffer_point, _)) =
18116 self.buffer.read(cx).point_to_buffer_point(point, cx)
18117 {
18118 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18119 new_selections_by_buffer
18120 .entry(buffer)
18121 .or_insert((Vec::new(), Some(*line_offset_from_top)))
18122 .0
18123 .push(buffer_offset..buffer_offset)
18124 }
18125 }
18126 None => {
18127 let selections = self.selections.all::<usize>(cx);
18128 let multi_buffer = self.buffer.read(cx);
18129 for selection in selections {
18130 for (snapshot, range, _, anchor) in multi_buffer
18131 .snapshot(cx)
18132 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18133 {
18134 if let Some(anchor) = anchor {
18135 // selection is in a deleted hunk
18136 let Some(buffer_id) = anchor.buffer_id else {
18137 continue;
18138 };
18139 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18140 continue;
18141 };
18142 let offset = text::ToOffset::to_offset(
18143 &anchor.text_anchor,
18144 &buffer_handle.read(cx).snapshot(),
18145 );
18146 let range = offset..offset;
18147 new_selections_by_buffer
18148 .entry(buffer_handle)
18149 .or_insert((Vec::new(), None))
18150 .0
18151 .push(range)
18152 } else {
18153 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18154 else {
18155 continue;
18156 };
18157 new_selections_by_buffer
18158 .entry(buffer_handle)
18159 .or_insert((Vec::new(), None))
18160 .0
18161 .push(range)
18162 }
18163 }
18164 }
18165 }
18166 }
18167
18168 new_selections_by_buffer
18169 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18170
18171 if new_selections_by_buffer.is_empty() {
18172 return;
18173 }
18174
18175 // We defer the pane interaction because we ourselves are a workspace item
18176 // and activating a new item causes the pane to call a method on us reentrantly,
18177 // which panics if we're on the stack.
18178 window.defer(cx, move |window, cx| {
18179 workspace.update(cx, |workspace, cx| {
18180 let pane = if split {
18181 workspace.adjacent_pane(window, cx)
18182 } else {
18183 workspace.active_pane().clone()
18184 };
18185
18186 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18187 let editor = buffer
18188 .read(cx)
18189 .file()
18190 .is_none()
18191 .then(|| {
18192 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18193 // so `workspace.open_project_item` will never find them, always opening a new editor.
18194 // Instead, we try to activate the existing editor in the pane first.
18195 let (editor, pane_item_index) =
18196 pane.read(cx).items().enumerate().find_map(|(i, item)| {
18197 let editor = item.downcast::<Editor>()?;
18198 let singleton_buffer =
18199 editor.read(cx).buffer().read(cx).as_singleton()?;
18200 if singleton_buffer == buffer {
18201 Some((editor, i))
18202 } else {
18203 None
18204 }
18205 })?;
18206 pane.update(cx, |pane, cx| {
18207 pane.activate_item(pane_item_index, true, true, window, cx)
18208 });
18209 Some(editor)
18210 })
18211 .flatten()
18212 .unwrap_or_else(|| {
18213 workspace.open_project_item::<Self>(
18214 pane.clone(),
18215 buffer,
18216 true,
18217 true,
18218 window,
18219 cx,
18220 )
18221 });
18222
18223 editor.update(cx, |editor, cx| {
18224 let autoscroll = match scroll_offset {
18225 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18226 None => Autoscroll::newest(),
18227 };
18228 let nav_history = editor.nav_history.take();
18229 editor.change_selections(Some(autoscroll), window, cx, |s| {
18230 s.select_ranges(ranges);
18231 });
18232 editor.nav_history = nav_history;
18233 });
18234 }
18235 })
18236 });
18237 }
18238
18239 // For now, don't allow opening excerpts in buffers that aren't backed by
18240 // regular project files.
18241 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18242 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18243 }
18244
18245 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18246 let snapshot = self.buffer.read(cx).read(cx);
18247 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18248 Some(
18249 ranges
18250 .iter()
18251 .map(move |range| {
18252 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18253 })
18254 .collect(),
18255 )
18256 }
18257
18258 fn selection_replacement_ranges(
18259 &self,
18260 range: Range<OffsetUtf16>,
18261 cx: &mut App,
18262 ) -> Vec<Range<OffsetUtf16>> {
18263 let selections = self.selections.all::<OffsetUtf16>(cx);
18264 let newest_selection = selections
18265 .iter()
18266 .max_by_key(|selection| selection.id)
18267 .unwrap();
18268 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18269 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18270 let snapshot = self.buffer.read(cx).read(cx);
18271 selections
18272 .into_iter()
18273 .map(|mut selection| {
18274 selection.start.0 =
18275 (selection.start.0 as isize).saturating_add(start_delta) as usize;
18276 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18277 snapshot.clip_offset_utf16(selection.start, Bias::Left)
18278 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18279 })
18280 .collect()
18281 }
18282
18283 fn report_editor_event(
18284 &self,
18285 event_type: &'static str,
18286 file_extension: Option<String>,
18287 cx: &App,
18288 ) {
18289 if cfg!(any(test, feature = "test-support")) {
18290 return;
18291 }
18292
18293 let Some(project) = &self.project else { return };
18294
18295 // If None, we are in a file without an extension
18296 let file = self
18297 .buffer
18298 .read(cx)
18299 .as_singleton()
18300 .and_then(|b| b.read(cx).file());
18301 let file_extension = file_extension.or(file
18302 .as_ref()
18303 .and_then(|file| Path::new(file.file_name(cx)).extension())
18304 .and_then(|e| e.to_str())
18305 .map(|a| a.to_string()));
18306
18307 let vim_mode = vim_enabled(cx);
18308
18309 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18310 let copilot_enabled = edit_predictions_provider
18311 == language::language_settings::EditPredictionProvider::Copilot;
18312 let copilot_enabled_for_language = self
18313 .buffer
18314 .read(cx)
18315 .language_settings(cx)
18316 .show_edit_predictions;
18317
18318 let project = project.read(cx);
18319 telemetry::event!(
18320 event_type,
18321 file_extension,
18322 vim_mode,
18323 copilot_enabled,
18324 copilot_enabled_for_language,
18325 edit_predictions_provider,
18326 is_via_ssh = project.is_via_ssh(),
18327 );
18328 }
18329
18330 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18331 /// with each line being an array of {text, highlight} objects.
18332 fn copy_highlight_json(
18333 &mut self,
18334 _: &CopyHighlightJson,
18335 window: &mut Window,
18336 cx: &mut Context<Self>,
18337 ) {
18338 #[derive(Serialize)]
18339 struct Chunk<'a> {
18340 text: String,
18341 highlight: Option<&'a str>,
18342 }
18343
18344 let snapshot = self.buffer.read(cx).snapshot(cx);
18345 let range = self
18346 .selected_text_range(false, window, cx)
18347 .and_then(|selection| {
18348 if selection.range.is_empty() {
18349 None
18350 } else {
18351 Some(selection.range)
18352 }
18353 })
18354 .unwrap_or_else(|| 0..snapshot.len());
18355
18356 let chunks = snapshot.chunks(range, true);
18357 let mut lines = Vec::new();
18358 let mut line: VecDeque<Chunk> = VecDeque::new();
18359
18360 let Some(style) = self.style.as_ref() else {
18361 return;
18362 };
18363
18364 for chunk in chunks {
18365 let highlight = chunk
18366 .syntax_highlight_id
18367 .and_then(|id| id.name(&style.syntax));
18368 let mut chunk_lines = chunk.text.split('\n').peekable();
18369 while let Some(text) = chunk_lines.next() {
18370 let mut merged_with_last_token = false;
18371 if let Some(last_token) = line.back_mut() {
18372 if last_token.highlight == highlight {
18373 last_token.text.push_str(text);
18374 merged_with_last_token = true;
18375 }
18376 }
18377
18378 if !merged_with_last_token {
18379 line.push_back(Chunk {
18380 text: text.into(),
18381 highlight,
18382 });
18383 }
18384
18385 if chunk_lines.peek().is_some() {
18386 if line.len() > 1 && line.front().unwrap().text.is_empty() {
18387 line.pop_front();
18388 }
18389 if line.len() > 1 && line.back().unwrap().text.is_empty() {
18390 line.pop_back();
18391 }
18392
18393 lines.push(mem::take(&mut line));
18394 }
18395 }
18396 }
18397
18398 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18399 return;
18400 };
18401 cx.write_to_clipboard(ClipboardItem::new_string(lines));
18402 }
18403
18404 pub fn open_context_menu(
18405 &mut self,
18406 _: &OpenContextMenu,
18407 window: &mut Window,
18408 cx: &mut Context<Self>,
18409 ) {
18410 self.request_autoscroll(Autoscroll::newest(), cx);
18411 let position = self.selections.newest_display(cx).start;
18412 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18413 }
18414
18415 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18416 &self.inlay_hint_cache
18417 }
18418
18419 pub fn replay_insert_event(
18420 &mut self,
18421 text: &str,
18422 relative_utf16_range: Option<Range<isize>>,
18423 window: &mut Window,
18424 cx: &mut Context<Self>,
18425 ) {
18426 if !self.input_enabled {
18427 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18428 return;
18429 }
18430 if let Some(relative_utf16_range) = relative_utf16_range {
18431 let selections = self.selections.all::<OffsetUtf16>(cx);
18432 self.change_selections(None, window, cx, |s| {
18433 let new_ranges = selections.into_iter().map(|range| {
18434 let start = OffsetUtf16(
18435 range
18436 .head()
18437 .0
18438 .saturating_add_signed(relative_utf16_range.start),
18439 );
18440 let end = OffsetUtf16(
18441 range
18442 .head()
18443 .0
18444 .saturating_add_signed(relative_utf16_range.end),
18445 );
18446 start..end
18447 });
18448 s.select_ranges(new_ranges);
18449 });
18450 }
18451
18452 self.handle_input(text, window, cx);
18453 }
18454
18455 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18456 let Some(provider) = self.semantics_provider.as_ref() else {
18457 return false;
18458 };
18459
18460 let mut supports = false;
18461 self.buffer().update(cx, |this, cx| {
18462 this.for_each_buffer(|buffer| {
18463 supports |= provider.supports_inlay_hints(buffer, cx);
18464 });
18465 });
18466
18467 supports
18468 }
18469
18470 pub fn is_focused(&self, window: &Window) -> bool {
18471 self.focus_handle.is_focused(window)
18472 }
18473
18474 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18475 cx.emit(EditorEvent::Focused);
18476
18477 if let Some(descendant) = self
18478 .last_focused_descendant
18479 .take()
18480 .and_then(|descendant| descendant.upgrade())
18481 {
18482 window.focus(&descendant);
18483 } else {
18484 if let Some(blame) = self.blame.as_ref() {
18485 blame.update(cx, GitBlame::focus)
18486 }
18487
18488 self.blink_manager.update(cx, BlinkManager::enable);
18489 self.show_cursor_names(window, cx);
18490 self.buffer.update(cx, |buffer, cx| {
18491 buffer.finalize_last_transaction(cx);
18492 if self.leader_id.is_none() {
18493 buffer.set_active_selections(
18494 &self.selections.disjoint_anchors(),
18495 self.selections.line_mode,
18496 self.cursor_shape,
18497 cx,
18498 );
18499 }
18500 });
18501 }
18502 }
18503
18504 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18505 cx.emit(EditorEvent::FocusedIn)
18506 }
18507
18508 fn handle_focus_out(
18509 &mut self,
18510 event: FocusOutEvent,
18511 _window: &mut Window,
18512 cx: &mut Context<Self>,
18513 ) {
18514 if event.blurred != self.focus_handle {
18515 self.last_focused_descendant = Some(event.blurred);
18516 }
18517 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18518 }
18519
18520 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18521 self.blink_manager.update(cx, BlinkManager::disable);
18522 self.buffer
18523 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18524
18525 if let Some(blame) = self.blame.as_ref() {
18526 blame.update(cx, GitBlame::blur)
18527 }
18528 if !self.hover_state.focused(window, cx) {
18529 hide_hover(self, cx);
18530 }
18531 if !self
18532 .context_menu
18533 .borrow()
18534 .as_ref()
18535 .is_some_and(|context_menu| context_menu.focused(window, cx))
18536 {
18537 self.hide_context_menu(window, cx);
18538 }
18539 self.discard_inline_completion(false, cx);
18540 cx.emit(EditorEvent::Blurred);
18541 cx.notify();
18542 }
18543
18544 pub fn register_action<A: Action>(
18545 &mut self,
18546 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18547 ) -> Subscription {
18548 let id = self.next_editor_action_id.post_inc();
18549 let listener = Arc::new(listener);
18550 self.editor_actions.borrow_mut().insert(
18551 id,
18552 Box::new(move |window, _| {
18553 let listener = listener.clone();
18554 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18555 let action = action.downcast_ref().unwrap();
18556 if phase == DispatchPhase::Bubble {
18557 listener(action, window, cx)
18558 }
18559 })
18560 }),
18561 );
18562
18563 let editor_actions = self.editor_actions.clone();
18564 Subscription::new(move || {
18565 editor_actions.borrow_mut().remove(&id);
18566 })
18567 }
18568
18569 pub fn file_header_size(&self) -> u32 {
18570 FILE_HEADER_HEIGHT
18571 }
18572
18573 pub fn restore(
18574 &mut self,
18575 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18576 window: &mut Window,
18577 cx: &mut Context<Self>,
18578 ) {
18579 let workspace = self.workspace();
18580 let project = self.project.as_ref();
18581 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18582 let mut tasks = Vec::new();
18583 for (buffer_id, changes) in revert_changes {
18584 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18585 buffer.update(cx, |buffer, cx| {
18586 buffer.edit(
18587 changes
18588 .into_iter()
18589 .map(|(range, text)| (range, text.to_string())),
18590 None,
18591 cx,
18592 );
18593 });
18594
18595 if let Some(project) =
18596 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18597 {
18598 project.update(cx, |project, cx| {
18599 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18600 })
18601 }
18602 }
18603 }
18604 tasks
18605 });
18606 cx.spawn_in(window, async move |_, cx| {
18607 for (buffer, task) in save_tasks {
18608 let result = task.await;
18609 if result.is_err() {
18610 let Some(path) = buffer
18611 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18612 .ok()
18613 else {
18614 continue;
18615 };
18616 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18617 let Some(task) = cx
18618 .update_window_entity(&workspace, |workspace, window, cx| {
18619 workspace
18620 .open_path_preview(path, None, false, false, false, window, cx)
18621 })
18622 .ok()
18623 else {
18624 continue;
18625 };
18626 task.await.log_err();
18627 }
18628 }
18629 }
18630 })
18631 .detach();
18632 self.change_selections(None, window, cx, |selections| selections.refresh());
18633 }
18634
18635 pub fn to_pixel_point(
18636 &self,
18637 source: multi_buffer::Anchor,
18638 editor_snapshot: &EditorSnapshot,
18639 window: &mut Window,
18640 ) -> Option<gpui::Point<Pixels>> {
18641 let source_point = source.to_display_point(editor_snapshot);
18642 self.display_to_pixel_point(source_point, editor_snapshot, window)
18643 }
18644
18645 pub fn display_to_pixel_point(
18646 &self,
18647 source: DisplayPoint,
18648 editor_snapshot: &EditorSnapshot,
18649 window: &mut Window,
18650 ) -> Option<gpui::Point<Pixels>> {
18651 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18652 let text_layout_details = self.text_layout_details(window);
18653 let scroll_top = text_layout_details
18654 .scroll_anchor
18655 .scroll_position(editor_snapshot)
18656 .y;
18657
18658 if source.row().as_f32() < scroll_top.floor() {
18659 return None;
18660 }
18661 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18662 let source_y = line_height * (source.row().as_f32() - scroll_top);
18663 Some(gpui::Point::new(source_x, source_y))
18664 }
18665
18666 pub fn has_visible_completions_menu(&self) -> bool {
18667 !self.edit_prediction_preview_is_active()
18668 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18669 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18670 })
18671 }
18672
18673 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18674 self.addons
18675 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18676 }
18677
18678 pub fn unregister_addon<T: Addon>(&mut self) {
18679 self.addons.remove(&std::any::TypeId::of::<T>());
18680 }
18681
18682 pub fn addon<T: Addon>(&self) -> Option<&T> {
18683 let type_id = std::any::TypeId::of::<T>();
18684 self.addons
18685 .get(&type_id)
18686 .and_then(|item| item.to_any().downcast_ref::<T>())
18687 }
18688
18689 pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18690 let type_id = std::any::TypeId::of::<T>();
18691 self.addons
18692 .get_mut(&type_id)
18693 .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18694 }
18695
18696 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18697 let text_layout_details = self.text_layout_details(window);
18698 let style = &text_layout_details.editor_style;
18699 let font_id = window.text_system().resolve_font(&style.text.font());
18700 let font_size = style.text.font_size.to_pixels(window.rem_size());
18701 let line_height = style.text.line_height_in_pixels(window.rem_size());
18702 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18703
18704 gpui::Size::new(em_width, line_height)
18705 }
18706
18707 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18708 self.load_diff_task.clone()
18709 }
18710
18711 fn read_metadata_from_db(
18712 &mut self,
18713 item_id: u64,
18714 workspace_id: WorkspaceId,
18715 window: &mut Window,
18716 cx: &mut Context<Editor>,
18717 ) {
18718 if self.is_singleton(cx)
18719 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18720 {
18721 let buffer_snapshot = OnceCell::new();
18722
18723 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18724 if !folds.is_empty() {
18725 let snapshot =
18726 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18727 self.fold_ranges(
18728 folds
18729 .into_iter()
18730 .map(|(start, end)| {
18731 snapshot.clip_offset(start, Bias::Left)
18732 ..snapshot.clip_offset(end, Bias::Right)
18733 })
18734 .collect(),
18735 false,
18736 window,
18737 cx,
18738 );
18739 }
18740 }
18741
18742 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18743 if !selections.is_empty() {
18744 let snapshot =
18745 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18746 self.change_selections(None, window, cx, |s| {
18747 s.select_ranges(selections.into_iter().map(|(start, end)| {
18748 snapshot.clip_offset(start, Bias::Left)
18749 ..snapshot.clip_offset(end, Bias::Right)
18750 }));
18751 });
18752 }
18753 };
18754 }
18755
18756 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18757 }
18758}
18759
18760fn vim_enabled(cx: &App) -> bool {
18761 cx.global::<SettingsStore>()
18762 .raw_user_settings()
18763 .get("vim_mode")
18764 == Some(&serde_json::Value::Bool(true))
18765}
18766
18767// Consider user intent and default settings
18768fn choose_completion_range(
18769 completion: &Completion,
18770 intent: CompletionIntent,
18771 buffer: &Entity<Buffer>,
18772 cx: &mut Context<Editor>,
18773) -> Range<usize> {
18774 fn should_replace(
18775 completion: &Completion,
18776 insert_range: &Range<text::Anchor>,
18777 intent: CompletionIntent,
18778 completion_mode_setting: LspInsertMode,
18779 buffer: &Buffer,
18780 ) -> bool {
18781 // specific actions take precedence over settings
18782 match intent {
18783 CompletionIntent::CompleteWithInsert => return false,
18784 CompletionIntent::CompleteWithReplace => return true,
18785 CompletionIntent::Complete | CompletionIntent::Compose => {}
18786 }
18787
18788 match completion_mode_setting {
18789 LspInsertMode::Insert => false,
18790 LspInsertMode::Replace => true,
18791 LspInsertMode::ReplaceSubsequence => {
18792 let mut text_to_replace = buffer.chars_for_range(
18793 buffer.anchor_before(completion.replace_range.start)
18794 ..buffer.anchor_after(completion.replace_range.end),
18795 );
18796 let mut completion_text = completion.new_text.chars();
18797
18798 // is `text_to_replace` a subsequence of `completion_text`
18799 text_to_replace
18800 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18801 }
18802 LspInsertMode::ReplaceSuffix => {
18803 let range_after_cursor = insert_range.end..completion.replace_range.end;
18804
18805 let text_after_cursor = buffer
18806 .text_for_range(
18807 buffer.anchor_before(range_after_cursor.start)
18808 ..buffer.anchor_after(range_after_cursor.end),
18809 )
18810 .collect::<String>();
18811 completion.new_text.ends_with(&text_after_cursor)
18812 }
18813 }
18814 }
18815
18816 let buffer = buffer.read(cx);
18817
18818 if let CompletionSource::Lsp {
18819 insert_range: Some(insert_range),
18820 ..
18821 } = &completion.source
18822 {
18823 let completion_mode_setting =
18824 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18825 .completions
18826 .lsp_insert_mode;
18827
18828 if !should_replace(
18829 completion,
18830 &insert_range,
18831 intent,
18832 completion_mode_setting,
18833 buffer,
18834 ) {
18835 return insert_range.to_offset(buffer);
18836 }
18837 }
18838
18839 completion.replace_range.to_offset(buffer)
18840}
18841
18842fn insert_extra_newline_brackets(
18843 buffer: &MultiBufferSnapshot,
18844 range: Range<usize>,
18845 language: &language::LanguageScope,
18846) -> bool {
18847 let leading_whitespace_len = buffer
18848 .reversed_chars_at(range.start)
18849 .take_while(|c| c.is_whitespace() && *c != '\n')
18850 .map(|c| c.len_utf8())
18851 .sum::<usize>();
18852 let trailing_whitespace_len = buffer
18853 .chars_at(range.end)
18854 .take_while(|c| c.is_whitespace() && *c != '\n')
18855 .map(|c| c.len_utf8())
18856 .sum::<usize>();
18857 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18858
18859 language.brackets().any(|(pair, enabled)| {
18860 let pair_start = pair.start.trim_end();
18861 let pair_end = pair.end.trim_start();
18862
18863 enabled
18864 && pair.newline
18865 && buffer.contains_str_at(range.end, pair_end)
18866 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18867 })
18868}
18869
18870fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18871 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18872 [(buffer, range, _)] => (*buffer, range.clone()),
18873 _ => return false,
18874 };
18875 let pair = {
18876 let mut result: Option<BracketMatch> = None;
18877
18878 for pair in buffer
18879 .all_bracket_ranges(range.clone())
18880 .filter(move |pair| {
18881 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18882 })
18883 {
18884 let len = pair.close_range.end - pair.open_range.start;
18885
18886 if let Some(existing) = &result {
18887 let existing_len = existing.close_range.end - existing.open_range.start;
18888 if len > existing_len {
18889 continue;
18890 }
18891 }
18892
18893 result = Some(pair);
18894 }
18895
18896 result
18897 };
18898 let Some(pair) = pair else {
18899 return false;
18900 };
18901 pair.newline_only
18902 && buffer
18903 .chars_for_range(pair.open_range.end..range.start)
18904 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18905 .all(|c| c.is_whitespace() && c != '\n')
18906}
18907
18908fn update_uncommitted_diff_for_buffer(
18909 editor: Entity<Editor>,
18910 project: &Entity<Project>,
18911 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18912 buffer: Entity<MultiBuffer>,
18913 cx: &mut App,
18914) -> Task<()> {
18915 let mut tasks = Vec::new();
18916 project.update(cx, |project, cx| {
18917 for buffer in buffers {
18918 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18919 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18920 }
18921 }
18922 });
18923 cx.spawn(async move |cx| {
18924 let diffs = future::join_all(tasks).await;
18925 if editor
18926 .read_with(cx, |editor, _cx| editor.temporary_diff_override)
18927 .unwrap_or(false)
18928 {
18929 return;
18930 }
18931
18932 buffer
18933 .update(cx, |buffer, cx| {
18934 for diff in diffs.into_iter().flatten() {
18935 buffer.add_diff(diff, cx);
18936 }
18937 })
18938 .ok();
18939 })
18940}
18941
18942fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18943 let tab_size = tab_size.get() as usize;
18944 let mut width = offset;
18945
18946 for ch in text.chars() {
18947 width += if ch == '\t' {
18948 tab_size - (width % tab_size)
18949 } else {
18950 1
18951 };
18952 }
18953
18954 width - offset
18955}
18956
18957#[cfg(test)]
18958mod tests {
18959 use super::*;
18960
18961 #[test]
18962 fn test_string_size_with_expanded_tabs() {
18963 let nz = |val| NonZeroU32::new(val).unwrap();
18964 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18965 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18966 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18967 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18968 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18969 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18970 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18971 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18972 }
18973}
18974
18975/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18976struct WordBreakingTokenizer<'a> {
18977 input: &'a str,
18978}
18979
18980impl<'a> WordBreakingTokenizer<'a> {
18981 fn new(input: &'a str) -> Self {
18982 Self { input }
18983 }
18984}
18985
18986fn is_char_ideographic(ch: char) -> bool {
18987 use unicode_script::Script::*;
18988 use unicode_script::UnicodeScript;
18989 matches!(ch.script(), Han | Tangut | Yi)
18990}
18991
18992fn is_grapheme_ideographic(text: &str) -> bool {
18993 text.chars().any(is_char_ideographic)
18994}
18995
18996fn is_grapheme_whitespace(text: &str) -> bool {
18997 text.chars().any(|x| x.is_whitespace())
18998}
18999
19000fn should_stay_with_preceding_ideograph(text: &str) -> bool {
19001 text.chars().next().map_or(false, |ch| {
19002 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
19003 })
19004}
19005
19006#[derive(PartialEq, Eq, Debug, Clone, Copy)]
19007enum WordBreakToken<'a> {
19008 Word { token: &'a str, grapheme_len: usize },
19009 InlineWhitespace { token: &'a str, grapheme_len: usize },
19010 Newline,
19011}
19012
19013impl<'a> Iterator for WordBreakingTokenizer<'a> {
19014 /// Yields a span, the count of graphemes in the token, and whether it was
19015 /// whitespace. Note that it also breaks at word boundaries.
19016 type Item = WordBreakToken<'a>;
19017
19018 fn next(&mut self) -> Option<Self::Item> {
19019 use unicode_segmentation::UnicodeSegmentation;
19020 if self.input.is_empty() {
19021 return None;
19022 }
19023
19024 let mut iter = self.input.graphemes(true).peekable();
19025 let mut offset = 0;
19026 let mut grapheme_len = 0;
19027 if let Some(first_grapheme) = iter.next() {
19028 let is_newline = first_grapheme == "\n";
19029 let is_whitespace = is_grapheme_whitespace(first_grapheme);
19030 offset += first_grapheme.len();
19031 grapheme_len += 1;
19032 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19033 if let Some(grapheme) = iter.peek().copied() {
19034 if should_stay_with_preceding_ideograph(grapheme) {
19035 offset += grapheme.len();
19036 grapheme_len += 1;
19037 }
19038 }
19039 } else {
19040 let mut words = self.input[offset..].split_word_bound_indices().peekable();
19041 let mut next_word_bound = words.peek().copied();
19042 if next_word_bound.map_or(false, |(i, _)| i == 0) {
19043 next_word_bound = words.next();
19044 }
19045 while let Some(grapheme) = iter.peek().copied() {
19046 if next_word_bound.map_or(false, |(i, _)| i == offset) {
19047 break;
19048 };
19049 if is_grapheme_whitespace(grapheme) != is_whitespace
19050 || (grapheme == "\n") != is_newline
19051 {
19052 break;
19053 };
19054 offset += grapheme.len();
19055 grapheme_len += 1;
19056 iter.next();
19057 }
19058 }
19059 let token = &self.input[..offset];
19060 self.input = &self.input[offset..];
19061 if token == "\n" {
19062 Some(WordBreakToken::Newline)
19063 } else if is_whitespace {
19064 Some(WordBreakToken::InlineWhitespace {
19065 token,
19066 grapheme_len,
19067 })
19068 } else {
19069 Some(WordBreakToken::Word {
19070 token,
19071 grapheme_len,
19072 })
19073 }
19074 } else {
19075 None
19076 }
19077 }
19078}
19079
19080#[test]
19081fn test_word_breaking_tokenizer() {
19082 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19083 ("", &[]),
19084 (" ", &[whitespace(" ", 2)]),
19085 ("Ʒ", &[word("Ʒ", 1)]),
19086 ("Ǽ", &[word("Ǽ", 1)]),
19087 ("⋑", &[word("⋑", 1)]),
19088 ("⋑⋑", &[word("⋑⋑", 2)]),
19089 (
19090 "原理,进而",
19091 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
19092 ),
19093 (
19094 "hello world",
19095 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19096 ),
19097 (
19098 "hello, world",
19099 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19100 ),
19101 (
19102 " hello world",
19103 &[
19104 whitespace(" ", 2),
19105 word("hello", 5),
19106 whitespace(" ", 1),
19107 word("world", 5),
19108 ],
19109 ),
19110 (
19111 "这是什么 \n 钢笔",
19112 &[
19113 word("这", 1),
19114 word("是", 1),
19115 word("什", 1),
19116 word("么", 1),
19117 whitespace(" ", 1),
19118 newline(),
19119 whitespace(" ", 1),
19120 word("钢", 1),
19121 word("笔", 1),
19122 ],
19123 ),
19124 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
19125 ];
19126
19127 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19128 WordBreakToken::Word {
19129 token,
19130 grapheme_len,
19131 }
19132 }
19133
19134 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19135 WordBreakToken::InlineWhitespace {
19136 token,
19137 grapheme_len,
19138 }
19139 }
19140
19141 fn newline() -> WordBreakToken<'static> {
19142 WordBreakToken::Newline
19143 }
19144
19145 for (input, result) in tests {
19146 assert_eq!(
19147 WordBreakingTokenizer::new(input)
19148 .collect::<Vec<_>>()
19149 .as_slice(),
19150 *result,
19151 );
19152 }
19153}
19154
19155fn wrap_with_prefix(
19156 line_prefix: String,
19157 unwrapped_text: String,
19158 wrap_column: usize,
19159 tab_size: NonZeroU32,
19160 preserve_existing_whitespace: bool,
19161) -> String {
19162 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19163 let mut wrapped_text = String::new();
19164 let mut current_line = line_prefix.clone();
19165
19166 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19167 let mut current_line_len = line_prefix_len;
19168 let mut in_whitespace = false;
19169 for token in tokenizer {
19170 let have_preceding_whitespace = in_whitespace;
19171 match token {
19172 WordBreakToken::Word {
19173 token,
19174 grapheme_len,
19175 } => {
19176 in_whitespace = false;
19177 if current_line_len + grapheme_len > wrap_column
19178 && current_line_len != line_prefix_len
19179 {
19180 wrapped_text.push_str(current_line.trim_end());
19181 wrapped_text.push('\n');
19182 current_line.truncate(line_prefix.len());
19183 current_line_len = line_prefix_len;
19184 }
19185 current_line.push_str(token);
19186 current_line_len += grapheme_len;
19187 }
19188 WordBreakToken::InlineWhitespace {
19189 mut token,
19190 mut grapheme_len,
19191 } => {
19192 in_whitespace = true;
19193 if have_preceding_whitespace && !preserve_existing_whitespace {
19194 continue;
19195 }
19196 if !preserve_existing_whitespace {
19197 token = " ";
19198 grapheme_len = 1;
19199 }
19200 if current_line_len + grapheme_len > wrap_column {
19201 wrapped_text.push_str(current_line.trim_end());
19202 wrapped_text.push('\n');
19203 current_line.truncate(line_prefix.len());
19204 current_line_len = line_prefix_len;
19205 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19206 current_line.push_str(token);
19207 current_line_len += grapheme_len;
19208 }
19209 }
19210 WordBreakToken::Newline => {
19211 in_whitespace = true;
19212 if preserve_existing_whitespace {
19213 wrapped_text.push_str(current_line.trim_end());
19214 wrapped_text.push('\n');
19215 current_line.truncate(line_prefix.len());
19216 current_line_len = line_prefix_len;
19217 } else if have_preceding_whitespace {
19218 continue;
19219 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19220 {
19221 wrapped_text.push_str(current_line.trim_end());
19222 wrapped_text.push('\n');
19223 current_line.truncate(line_prefix.len());
19224 current_line_len = line_prefix_len;
19225 } else if current_line_len != line_prefix_len {
19226 current_line.push(' ');
19227 current_line_len += 1;
19228 }
19229 }
19230 }
19231 }
19232
19233 if !current_line.is_empty() {
19234 wrapped_text.push_str(¤t_line);
19235 }
19236 wrapped_text
19237}
19238
19239#[test]
19240fn test_wrap_with_prefix() {
19241 assert_eq!(
19242 wrap_with_prefix(
19243 "# ".to_string(),
19244 "abcdefg".to_string(),
19245 4,
19246 NonZeroU32::new(4).unwrap(),
19247 false,
19248 ),
19249 "# abcdefg"
19250 );
19251 assert_eq!(
19252 wrap_with_prefix(
19253 "".to_string(),
19254 "\thello world".to_string(),
19255 8,
19256 NonZeroU32::new(4).unwrap(),
19257 false,
19258 ),
19259 "hello\nworld"
19260 );
19261 assert_eq!(
19262 wrap_with_prefix(
19263 "// ".to_string(),
19264 "xx \nyy zz aa bb cc".to_string(),
19265 12,
19266 NonZeroU32::new(4).unwrap(),
19267 false,
19268 ),
19269 "// xx yy zz\n// aa bb cc"
19270 );
19271 assert_eq!(
19272 wrap_with_prefix(
19273 String::new(),
19274 "这是什么 \n 钢笔".to_string(),
19275 3,
19276 NonZeroU32::new(4).unwrap(),
19277 false,
19278 ),
19279 "这是什\n么 钢\n笔"
19280 );
19281}
19282
19283pub trait CollaborationHub {
19284 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19285 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19286 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19287}
19288
19289impl CollaborationHub for Entity<Project> {
19290 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19291 self.read(cx).collaborators()
19292 }
19293
19294 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19295 self.read(cx).user_store().read(cx).participant_indices()
19296 }
19297
19298 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19299 let this = self.read(cx);
19300 let user_ids = this.collaborators().values().map(|c| c.user_id);
19301 this.user_store().read_with(cx, |user_store, cx| {
19302 user_store.participant_names(user_ids, cx)
19303 })
19304 }
19305}
19306
19307pub trait SemanticsProvider {
19308 fn hover(
19309 &self,
19310 buffer: &Entity<Buffer>,
19311 position: text::Anchor,
19312 cx: &mut App,
19313 ) -> Option<Task<Vec<project::Hover>>>;
19314
19315 fn inline_values(
19316 &self,
19317 buffer_handle: Entity<Buffer>,
19318 range: Range<text::Anchor>,
19319 cx: &mut App,
19320 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19321
19322 fn inlay_hints(
19323 &self,
19324 buffer_handle: Entity<Buffer>,
19325 range: Range<text::Anchor>,
19326 cx: &mut App,
19327 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19328
19329 fn resolve_inlay_hint(
19330 &self,
19331 hint: InlayHint,
19332 buffer_handle: Entity<Buffer>,
19333 server_id: LanguageServerId,
19334 cx: &mut App,
19335 ) -> Option<Task<anyhow::Result<InlayHint>>>;
19336
19337 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19338
19339 fn document_highlights(
19340 &self,
19341 buffer: &Entity<Buffer>,
19342 position: text::Anchor,
19343 cx: &mut App,
19344 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19345
19346 fn definitions(
19347 &self,
19348 buffer: &Entity<Buffer>,
19349 position: text::Anchor,
19350 kind: GotoDefinitionKind,
19351 cx: &mut App,
19352 ) -> Option<Task<Result<Vec<LocationLink>>>>;
19353
19354 fn range_for_rename(
19355 &self,
19356 buffer: &Entity<Buffer>,
19357 position: text::Anchor,
19358 cx: &mut App,
19359 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19360
19361 fn perform_rename(
19362 &self,
19363 buffer: &Entity<Buffer>,
19364 position: text::Anchor,
19365 new_name: String,
19366 cx: &mut App,
19367 ) -> Option<Task<Result<ProjectTransaction>>>;
19368}
19369
19370pub trait CompletionProvider {
19371 fn completions(
19372 &self,
19373 excerpt_id: ExcerptId,
19374 buffer: &Entity<Buffer>,
19375 buffer_position: text::Anchor,
19376 trigger: CompletionContext,
19377 window: &mut Window,
19378 cx: &mut Context<Editor>,
19379 ) -> Task<Result<Option<Vec<Completion>>>>;
19380
19381 fn resolve_completions(
19382 &self,
19383 buffer: Entity<Buffer>,
19384 completion_indices: Vec<usize>,
19385 completions: Rc<RefCell<Box<[Completion]>>>,
19386 cx: &mut Context<Editor>,
19387 ) -> Task<Result<bool>>;
19388
19389 fn apply_additional_edits_for_completion(
19390 &self,
19391 _buffer: Entity<Buffer>,
19392 _completions: Rc<RefCell<Box<[Completion]>>>,
19393 _completion_index: usize,
19394 _push_to_history: bool,
19395 _cx: &mut Context<Editor>,
19396 ) -> Task<Result<Option<language::Transaction>>> {
19397 Task::ready(Ok(None))
19398 }
19399
19400 fn is_completion_trigger(
19401 &self,
19402 buffer: &Entity<Buffer>,
19403 position: language::Anchor,
19404 text: &str,
19405 trigger_in_words: bool,
19406 cx: &mut Context<Editor>,
19407 ) -> bool;
19408
19409 fn sort_completions(&self) -> bool {
19410 true
19411 }
19412
19413 fn filter_completions(&self) -> bool {
19414 true
19415 }
19416}
19417
19418pub trait CodeActionProvider {
19419 fn id(&self) -> Arc<str>;
19420
19421 fn code_actions(
19422 &self,
19423 buffer: &Entity<Buffer>,
19424 range: Range<text::Anchor>,
19425 window: &mut Window,
19426 cx: &mut App,
19427 ) -> Task<Result<Vec<CodeAction>>>;
19428
19429 fn apply_code_action(
19430 &self,
19431 buffer_handle: Entity<Buffer>,
19432 action: CodeAction,
19433 excerpt_id: ExcerptId,
19434 push_to_history: bool,
19435 window: &mut Window,
19436 cx: &mut App,
19437 ) -> Task<Result<ProjectTransaction>>;
19438}
19439
19440impl CodeActionProvider for Entity<Project> {
19441 fn id(&self) -> Arc<str> {
19442 "project".into()
19443 }
19444
19445 fn code_actions(
19446 &self,
19447 buffer: &Entity<Buffer>,
19448 range: Range<text::Anchor>,
19449 _window: &mut Window,
19450 cx: &mut App,
19451 ) -> Task<Result<Vec<CodeAction>>> {
19452 self.update(cx, |project, cx| {
19453 let code_lens = project.code_lens(buffer, range.clone(), cx);
19454 let code_actions = project.code_actions(buffer, range, None, cx);
19455 cx.background_spawn(async move {
19456 let (code_lens, code_actions) = join(code_lens, code_actions).await;
19457 Ok(code_lens
19458 .context("code lens fetch")?
19459 .into_iter()
19460 .chain(code_actions.context("code action fetch")?)
19461 .collect())
19462 })
19463 })
19464 }
19465
19466 fn apply_code_action(
19467 &self,
19468 buffer_handle: Entity<Buffer>,
19469 action: CodeAction,
19470 _excerpt_id: ExcerptId,
19471 push_to_history: bool,
19472 _window: &mut Window,
19473 cx: &mut App,
19474 ) -> Task<Result<ProjectTransaction>> {
19475 self.update(cx, |project, cx| {
19476 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19477 })
19478 }
19479}
19480
19481fn snippet_completions(
19482 project: &Project,
19483 buffer: &Entity<Buffer>,
19484 buffer_position: text::Anchor,
19485 cx: &mut App,
19486) -> Task<Result<Vec<Completion>>> {
19487 let languages = buffer.read(cx).languages_at(buffer_position);
19488 let snippet_store = project.snippets().read(cx);
19489
19490 let scopes: Vec<_> = languages
19491 .iter()
19492 .filter_map(|language| {
19493 let language_name = language.lsp_id();
19494 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19495
19496 if snippets.is_empty() {
19497 None
19498 } else {
19499 Some((language.default_scope(), snippets))
19500 }
19501 })
19502 .collect();
19503
19504 if scopes.is_empty() {
19505 return Task::ready(Ok(vec![]));
19506 }
19507
19508 let snapshot = buffer.read(cx).text_snapshot();
19509 let chars: String = snapshot
19510 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19511 .collect();
19512 let executor = cx.background_executor().clone();
19513
19514 cx.background_spawn(async move {
19515 let mut all_results: Vec<Completion> = Vec::new();
19516 for (scope, snippets) in scopes.into_iter() {
19517 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19518 let mut last_word = chars
19519 .chars()
19520 .take_while(|c| classifier.is_word(*c))
19521 .collect::<String>();
19522 last_word = last_word.chars().rev().collect();
19523
19524 if last_word.is_empty() {
19525 return Ok(vec![]);
19526 }
19527
19528 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19529 let to_lsp = |point: &text::Anchor| {
19530 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19531 point_to_lsp(end)
19532 };
19533 let lsp_end = to_lsp(&buffer_position);
19534
19535 let candidates = snippets
19536 .iter()
19537 .enumerate()
19538 .flat_map(|(ix, snippet)| {
19539 snippet
19540 .prefix
19541 .iter()
19542 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19543 })
19544 .collect::<Vec<StringMatchCandidate>>();
19545
19546 let mut matches = fuzzy::match_strings(
19547 &candidates,
19548 &last_word,
19549 last_word.chars().any(|c| c.is_uppercase()),
19550 100,
19551 &Default::default(),
19552 executor.clone(),
19553 )
19554 .await;
19555
19556 // Remove all candidates where the query's start does not match the start of any word in the candidate
19557 if let Some(query_start) = last_word.chars().next() {
19558 matches.retain(|string_match| {
19559 split_words(&string_match.string).any(|word| {
19560 // Check that the first codepoint of the word as lowercase matches the first
19561 // codepoint of the query as lowercase
19562 word.chars()
19563 .flat_map(|codepoint| codepoint.to_lowercase())
19564 .zip(query_start.to_lowercase())
19565 .all(|(word_cp, query_cp)| word_cp == query_cp)
19566 })
19567 });
19568 }
19569
19570 let matched_strings = matches
19571 .into_iter()
19572 .map(|m| m.string)
19573 .collect::<HashSet<_>>();
19574
19575 let mut result: Vec<Completion> = snippets
19576 .iter()
19577 .filter_map(|snippet| {
19578 let matching_prefix = snippet
19579 .prefix
19580 .iter()
19581 .find(|prefix| matched_strings.contains(*prefix))?;
19582 let start = as_offset - last_word.len();
19583 let start = snapshot.anchor_before(start);
19584 let range = start..buffer_position;
19585 let lsp_start = to_lsp(&start);
19586 let lsp_range = lsp::Range {
19587 start: lsp_start,
19588 end: lsp_end,
19589 };
19590 Some(Completion {
19591 replace_range: range,
19592 new_text: snippet.body.clone(),
19593 source: CompletionSource::Lsp {
19594 insert_range: None,
19595 server_id: LanguageServerId(usize::MAX),
19596 resolved: true,
19597 lsp_completion: Box::new(lsp::CompletionItem {
19598 label: snippet.prefix.first().unwrap().clone(),
19599 kind: Some(CompletionItemKind::SNIPPET),
19600 label_details: snippet.description.as_ref().map(|description| {
19601 lsp::CompletionItemLabelDetails {
19602 detail: Some(description.clone()),
19603 description: None,
19604 }
19605 }),
19606 insert_text_format: Some(InsertTextFormat::SNIPPET),
19607 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19608 lsp::InsertReplaceEdit {
19609 new_text: snippet.body.clone(),
19610 insert: lsp_range,
19611 replace: lsp_range,
19612 },
19613 )),
19614 filter_text: Some(snippet.body.clone()),
19615 sort_text: Some(char::MAX.to_string()),
19616 ..lsp::CompletionItem::default()
19617 }),
19618 lsp_defaults: None,
19619 },
19620 label: CodeLabel {
19621 text: matching_prefix.clone(),
19622 runs: Vec::new(),
19623 filter_range: 0..matching_prefix.len(),
19624 },
19625 icon_path: None,
19626 documentation: snippet.description.clone().map(|description| {
19627 CompletionDocumentation::SingleLine(description.into())
19628 }),
19629 insert_text_mode: None,
19630 confirm: None,
19631 })
19632 })
19633 .collect();
19634
19635 all_results.append(&mut result);
19636 }
19637
19638 Ok(all_results)
19639 })
19640}
19641
19642impl CompletionProvider for Entity<Project> {
19643 fn completions(
19644 &self,
19645 _excerpt_id: ExcerptId,
19646 buffer: &Entity<Buffer>,
19647 buffer_position: text::Anchor,
19648 options: CompletionContext,
19649 _window: &mut Window,
19650 cx: &mut Context<Editor>,
19651 ) -> Task<Result<Option<Vec<Completion>>>> {
19652 self.update(cx, |project, cx| {
19653 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19654 let project_completions = project.completions(buffer, buffer_position, options, cx);
19655 cx.background_spawn(async move {
19656 let snippets_completions = snippets.await?;
19657 match project_completions.await? {
19658 Some(mut completions) => {
19659 completions.extend(snippets_completions);
19660 Ok(Some(completions))
19661 }
19662 None => {
19663 if snippets_completions.is_empty() {
19664 Ok(None)
19665 } else {
19666 Ok(Some(snippets_completions))
19667 }
19668 }
19669 }
19670 })
19671 })
19672 }
19673
19674 fn resolve_completions(
19675 &self,
19676 buffer: Entity<Buffer>,
19677 completion_indices: Vec<usize>,
19678 completions: Rc<RefCell<Box<[Completion]>>>,
19679 cx: &mut Context<Editor>,
19680 ) -> Task<Result<bool>> {
19681 self.update(cx, |project, cx| {
19682 project.lsp_store().update(cx, |lsp_store, cx| {
19683 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19684 })
19685 })
19686 }
19687
19688 fn apply_additional_edits_for_completion(
19689 &self,
19690 buffer: Entity<Buffer>,
19691 completions: Rc<RefCell<Box<[Completion]>>>,
19692 completion_index: usize,
19693 push_to_history: bool,
19694 cx: &mut Context<Editor>,
19695 ) -> Task<Result<Option<language::Transaction>>> {
19696 self.update(cx, |project, cx| {
19697 project.lsp_store().update(cx, |lsp_store, cx| {
19698 lsp_store.apply_additional_edits_for_completion(
19699 buffer,
19700 completions,
19701 completion_index,
19702 push_to_history,
19703 cx,
19704 )
19705 })
19706 })
19707 }
19708
19709 fn is_completion_trigger(
19710 &self,
19711 buffer: &Entity<Buffer>,
19712 position: language::Anchor,
19713 text: &str,
19714 trigger_in_words: bool,
19715 cx: &mut Context<Editor>,
19716 ) -> bool {
19717 let mut chars = text.chars();
19718 let char = if let Some(char) = chars.next() {
19719 char
19720 } else {
19721 return false;
19722 };
19723 if chars.next().is_some() {
19724 return false;
19725 }
19726
19727 let buffer = buffer.read(cx);
19728 let snapshot = buffer.snapshot();
19729 if !snapshot.settings_at(position, cx).show_completions_on_input {
19730 return false;
19731 }
19732 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19733 if trigger_in_words && classifier.is_word(char) {
19734 return true;
19735 }
19736
19737 buffer.completion_triggers().contains(text)
19738 }
19739}
19740
19741impl SemanticsProvider for Entity<Project> {
19742 fn hover(
19743 &self,
19744 buffer: &Entity<Buffer>,
19745 position: text::Anchor,
19746 cx: &mut App,
19747 ) -> Option<Task<Vec<project::Hover>>> {
19748 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19749 }
19750
19751 fn document_highlights(
19752 &self,
19753 buffer: &Entity<Buffer>,
19754 position: text::Anchor,
19755 cx: &mut App,
19756 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19757 Some(self.update(cx, |project, cx| {
19758 project.document_highlights(buffer, position, cx)
19759 }))
19760 }
19761
19762 fn definitions(
19763 &self,
19764 buffer: &Entity<Buffer>,
19765 position: text::Anchor,
19766 kind: GotoDefinitionKind,
19767 cx: &mut App,
19768 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19769 Some(self.update(cx, |project, cx| match kind {
19770 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19771 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19772 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19773 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19774 }))
19775 }
19776
19777 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19778 // TODO: make this work for remote projects
19779 self.update(cx, |project, cx| {
19780 if project
19781 .active_debug_session(cx)
19782 .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19783 {
19784 return true;
19785 }
19786
19787 buffer.update(cx, |buffer, cx| {
19788 project.any_language_server_supports_inlay_hints(buffer, cx)
19789 })
19790 })
19791 }
19792
19793 fn inline_values(
19794 &self,
19795 buffer_handle: Entity<Buffer>,
19796 range: Range<text::Anchor>,
19797 cx: &mut App,
19798 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19799 self.update(cx, |project, cx| {
19800 let (session, active_stack_frame) = project.active_debug_session(cx)?;
19801
19802 Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19803 })
19804 }
19805
19806 fn inlay_hints(
19807 &self,
19808 buffer_handle: Entity<Buffer>,
19809 range: Range<text::Anchor>,
19810 cx: &mut App,
19811 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19812 Some(self.update(cx, |project, cx| {
19813 project.inlay_hints(buffer_handle, range, cx)
19814 }))
19815 }
19816
19817 fn resolve_inlay_hint(
19818 &self,
19819 hint: InlayHint,
19820 buffer_handle: Entity<Buffer>,
19821 server_id: LanguageServerId,
19822 cx: &mut App,
19823 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19824 Some(self.update(cx, |project, cx| {
19825 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19826 }))
19827 }
19828
19829 fn range_for_rename(
19830 &self,
19831 buffer: &Entity<Buffer>,
19832 position: text::Anchor,
19833 cx: &mut App,
19834 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19835 Some(self.update(cx, |project, cx| {
19836 let buffer = buffer.clone();
19837 let task = project.prepare_rename(buffer.clone(), position, cx);
19838 cx.spawn(async move |_, cx| {
19839 Ok(match task.await? {
19840 PrepareRenameResponse::Success(range) => Some(range),
19841 PrepareRenameResponse::InvalidPosition => None,
19842 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19843 // Fallback on using TreeSitter info to determine identifier range
19844 buffer.update(cx, |buffer, _| {
19845 let snapshot = buffer.snapshot();
19846 let (range, kind) = snapshot.surrounding_word(position);
19847 if kind != Some(CharKind::Word) {
19848 return None;
19849 }
19850 Some(
19851 snapshot.anchor_before(range.start)
19852 ..snapshot.anchor_after(range.end),
19853 )
19854 })?
19855 }
19856 })
19857 })
19858 }))
19859 }
19860
19861 fn perform_rename(
19862 &self,
19863 buffer: &Entity<Buffer>,
19864 position: text::Anchor,
19865 new_name: String,
19866 cx: &mut App,
19867 ) -> Option<Task<Result<ProjectTransaction>>> {
19868 Some(self.update(cx, |project, cx| {
19869 project.perform_rename(buffer.clone(), position, new_name, cx)
19870 }))
19871 }
19872}
19873
19874fn inlay_hint_settings(
19875 location: Anchor,
19876 snapshot: &MultiBufferSnapshot,
19877 cx: &mut Context<Editor>,
19878) -> InlayHintSettings {
19879 let file = snapshot.file_at(location);
19880 let language = snapshot.language_at(location).map(|l| l.name());
19881 language_settings(language, file, cx).inlay_hints
19882}
19883
19884fn consume_contiguous_rows(
19885 contiguous_row_selections: &mut Vec<Selection<Point>>,
19886 selection: &Selection<Point>,
19887 display_map: &DisplaySnapshot,
19888 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19889) -> (MultiBufferRow, MultiBufferRow) {
19890 contiguous_row_selections.push(selection.clone());
19891 let start_row = MultiBufferRow(selection.start.row);
19892 let mut end_row = ending_row(selection, display_map);
19893
19894 while let Some(next_selection) = selections.peek() {
19895 if next_selection.start.row <= end_row.0 {
19896 end_row = ending_row(next_selection, display_map);
19897 contiguous_row_selections.push(selections.next().unwrap().clone());
19898 } else {
19899 break;
19900 }
19901 }
19902 (start_row, end_row)
19903}
19904
19905fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19906 if next_selection.end.column > 0 || next_selection.is_empty() {
19907 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19908 } else {
19909 MultiBufferRow(next_selection.end.row)
19910 }
19911}
19912
19913impl EditorSnapshot {
19914 pub fn remote_selections_in_range<'a>(
19915 &'a self,
19916 range: &'a Range<Anchor>,
19917 collaboration_hub: &dyn CollaborationHub,
19918 cx: &'a App,
19919 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19920 let participant_names = collaboration_hub.user_names(cx);
19921 let participant_indices = collaboration_hub.user_participant_indices(cx);
19922 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19923 let collaborators_by_replica_id = collaborators_by_peer_id
19924 .iter()
19925 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19926 .collect::<HashMap<_, _>>();
19927 self.buffer_snapshot
19928 .selections_in_range(range, false)
19929 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19930 if replica_id == AGENT_REPLICA_ID {
19931 Some(RemoteSelection {
19932 replica_id,
19933 selection,
19934 cursor_shape,
19935 line_mode,
19936 collaborator_id: CollaboratorId::Agent,
19937 user_name: Some("Agent".into()),
19938 color: cx.theme().players().agent(),
19939 })
19940 } else {
19941 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19942 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19943 let user_name = participant_names.get(&collaborator.user_id).cloned();
19944 Some(RemoteSelection {
19945 replica_id,
19946 selection,
19947 cursor_shape,
19948 line_mode,
19949 collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
19950 user_name,
19951 color: if let Some(index) = participant_index {
19952 cx.theme().players().color_for_participant(index.0)
19953 } else {
19954 cx.theme().players().absent()
19955 },
19956 })
19957 }
19958 })
19959 }
19960
19961 pub fn hunks_for_ranges(
19962 &self,
19963 ranges: impl IntoIterator<Item = Range<Point>>,
19964 ) -> Vec<MultiBufferDiffHunk> {
19965 let mut hunks = Vec::new();
19966 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19967 HashMap::default();
19968 for query_range in ranges {
19969 let query_rows =
19970 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19971 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19972 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19973 ) {
19974 // Include deleted hunks that are adjacent to the query range, because
19975 // otherwise they would be missed.
19976 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19977 if hunk.status().is_deleted() {
19978 intersects_range |= hunk.row_range.start == query_rows.end;
19979 intersects_range |= hunk.row_range.end == query_rows.start;
19980 }
19981 if intersects_range {
19982 if !processed_buffer_rows
19983 .entry(hunk.buffer_id)
19984 .or_default()
19985 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19986 {
19987 continue;
19988 }
19989 hunks.push(hunk);
19990 }
19991 }
19992 }
19993
19994 hunks
19995 }
19996
19997 fn display_diff_hunks_for_rows<'a>(
19998 &'a self,
19999 display_rows: Range<DisplayRow>,
20000 folded_buffers: &'a HashSet<BufferId>,
20001 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
20002 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
20003 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
20004
20005 self.buffer_snapshot
20006 .diff_hunks_in_range(buffer_start..buffer_end)
20007 .filter_map(|hunk| {
20008 if folded_buffers.contains(&hunk.buffer_id) {
20009 return None;
20010 }
20011
20012 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20013 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20014
20015 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20016 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20017
20018 let display_hunk = if hunk_display_start.column() != 0 {
20019 DisplayDiffHunk::Folded {
20020 display_row: hunk_display_start.row(),
20021 }
20022 } else {
20023 let mut end_row = hunk_display_end.row();
20024 if hunk_display_end.column() > 0 {
20025 end_row.0 += 1;
20026 }
20027 let is_created_file = hunk.is_created_file();
20028 DisplayDiffHunk::Unfolded {
20029 status: hunk.status(),
20030 diff_base_byte_range: hunk.diff_base_byte_range,
20031 display_row_range: hunk_display_start.row()..end_row,
20032 multi_buffer_range: Anchor::range_in_buffer(
20033 hunk.excerpt_id,
20034 hunk.buffer_id,
20035 hunk.buffer_range,
20036 ),
20037 is_created_file,
20038 }
20039 };
20040
20041 Some(display_hunk)
20042 })
20043 }
20044
20045 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20046 self.display_snapshot.buffer_snapshot.language_at(position)
20047 }
20048
20049 pub fn is_focused(&self) -> bool {
20050 self.is_focused
20051 }
20052
20053 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20054 self.placeholder_text.as_ref()
20055 }
20056
20057 pub fn scroll_position(&self) -> gpui::Point<f32> {
20058 self.scroll_anchor.scroll_position(&self.display_snapshot)
20059 }
20060
20061 fn gutter_dimensions(
20062 &self,
20063 font_id: FontId,
20064 font_size: Pixels,
20065 max_line_number_width: Pixels,
20066 cx: &App,
20067 ) -> Option<GutterDimensions> {
20068 if !self.show_gutter {
20069 return None;
20070 }
20071
20072 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20073 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20074
20075 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20076 matches!(
20077 ProjectSettings::get_global(cx).git.git_gutter,
20078 Some(GitGutterSetting::TrackedFiles)
20079 )
20080 });
20081 let gutter_settings = EditorSettings::get_global(cx).gutter;
20082 let show_line_numbers = self
20083 .show_line_numbers
20084 .unwrap_or(gutter_settings.line_numbers);
20085 let line_gutter_width = if show_line_numbers {
20086 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20087 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20088 max_line_number_width.max(min_width_for_number_on_gutter)
20089 } else {
20090 0.0.into()
20091 };
20092
20093 let show_code_actions = self
20094 .show_code_actions
20095 .unwrap_or(gutter_settings.code_actions);
20096
20097 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20098 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20099
20100 let git_blame_entries_width =
20101 self.git_blame_gutter_max_author_length
20102 .map(|max_author_length| {
20103 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20104 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20105
20106 /// The number of characters to dedicate to gaps and margins.
20107 const SPACING_WIDTH: usize = 4;
20108
20109 let max_char_count = max_author_length.min(renderer.max_author_length())
20110 + ::git::SHORT_SHA_LENGTH
20111 + MAX_RELATIVE_TIMESTAMP.len()
20112 + SPACING_WIDTH;
20113
20114 em_advance * max_char_count
20115 });
20116
20117 let is_singleton = self.buffer_snapshot.is_singleton();
20118
20119 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20120 left_padding += if !is_singleton {
20121 em_width * 4.0
20122 } else if show_code_actions || show_runnables || show_breakpoints {
20123 em_width * 3.0
20124 } else if show_git_gutter && show_line_numbers {
20125 em_width * 2.0
20126 } else if show_git_gutter || show_line_numbers {
20127 em_width
20128 } else {
20129 px(0.)
20130 };
20131
20132 let shows_folds = is_singleton && gutter_settings.folds;
20133
20134 let right_padding = if shows_folds && show_line_numbers {
20135 em_width * 4.0
20136 } else if shows_folds || (!is_singleton && show_line_numbers) {
20137 em_width * 3.0
20138 } else if show_line_numbers {
20139 em_width
20140 } else {
20141 px(0.)
20142 };
20143
20144 Some(GutterDimensions {
20145 left_padding,
20146 right_padding,
20147 width: line_gutter_width + left_padding + right_padding,
20148 margin: GutterDimensions::default_gutter_margin(font_id, font_size, cx),
20149 git_blame_entries_width,
20150 })
20151 }
20152
20153 pub fn render_crease_toggle(
20154 &self,
20155 buffer_row: MultiBufferRow,
20156 row_contains_cursor: bool,
20157 editor: Entity<Editor>,
20158 window: &mut Window,
20159 cx: &mut App,
20160 ) -> Option<AnyElement> {
20161 let folded = self.is_line_folded(buffer_row);
20162 let mut is_foldable = false;
20163
20164 if let Some(crease) = self
20165 .crease_snapshot
20166 .query_row(buffer_row, &self.buffer_snapshot)
20167 {
20168 is_foldable = true;
20169 match crease {
20170 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20171 if let Some(render_toggle) = render_toggle {
20172 let toggle_callback =
20173 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20174 if folded {
20175 editor.update(cx, |editor, cx| {
20176 editor.fold_at(buffer_row, window, cx)
20177 });
20178 } else {
20179 editor.update(cx, |editor, cx| {
20180 editor.unfold_at(buffer_row, window, cx)
20181 });
20182 }
20183 });
20184 return Some((render_toggle)(
20185 buffer_row,
20186 folded,
20187 toggle_callback,
20188 window,
20189 cx,
20190 ));
20191 }
20192 }
20193 }
20194 }
20195
20196 is_foldable |= self.starts_indent(buffer_row);
20197
20198 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20199 Some(
20200 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20201 .toggle_state(folded)
20202 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20203 if folded {
20204 this.unfold_at(buffer_row, window, cx);
20205 } else {
20206 this.fold_at(buffer_row, window, cx);
20207 }
20208 }))
20209 .into_any_element(),
20210 )
20211 } else {
20212 None
20213 }
20214 }
20215
20216 pub fn render_crease_trailer(
20217 &self,
20218 buffer_row: MultiBufferRow,
20219 window: &mut Window,
20220 cx: &mut App,
20221 ) -> Option<AnyElement> {
20222 let folded = self.is_line_folded(buffer_row);
20223 if let Crease::Inline { render_trailer, .. } = self
20224 .crease_snapshot
20225 .query_row(buffer_row, &self.buffer_snapshot)?
20226 {
20227 let render_trailer = render_trailer.as_ref()?;
20228 Some(render_trailer(buffer_row, folded, window, cx))
20229 } else {
20230 None
20231 }
20232 }
20233}
20234
20235impl Deref for EditorSnapshot {
20236 type Target = DisplaySnapshot;
20237
20238 fn deref(&self) -> &Self::Target {
20239 &self.display_snapshot
20240 }
20241}
20242
20243#[derive(Clone, Debug, PartialEq, Eq)]
20244pub enum EditorEvent {
20245 InputIgnored {
20246 text: Arc<str>,
20247 },
20248 InputHandled {
20249 utf16_range_to_replace: Option<Range<isize>>,
20250 text: Arc<str>,
20251 },
20252 ExcerptsAdded {
20253 buffer: Entity<Buffer>,
20254 predecessor: ExcerptId,
20255 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20256 },
20257 ExcerptsRemoved {
20258 ids: Vec<ExcerptId>,
20259 removed_buffer_ids: Vec<BufferId>,
20260 },
20261 BufferFoldToggled {
20262 ids: Vec<ExcerptId>,
20263 folded: bool,
20264 },
20265 ExcerptsEdited {
20266 ids: Vec<ExcerptId>,
20267 },
20268 ExcerptsExpanded {
20269 ids: Vec<ExcerptId>,
20270 },
20271 BufferEdited,
20272 Edited {
20273 transaction_id: clock::Lamport,
20274 },
20275 Reparsed(BufferId),
20276 Focused,
20277 FocusedIn,
20278 Blurred,
20279 DirtyChanged,
20280 Saved,
20281 TitleChanged,
20282 DiffBaseChanged,
20283 SelectionsChanged {
20284 local: bool,
20285 },
20286 ScrollPositionChanged {
20287 local: bool,
20288 autoscroll: bool,
20289 },
20290 Closed,
20291 TransactionUndone {
20292 transaction_id: clock::Lamport,
20293 },
20294 TransactionBegun {
20295 transaction_id: clock::Lamport,
20296 },
20297 Reloaded,
20298 CursorShapeChanged,
20299 PushedToNavHistory {
20300 anchor: Anchor,
20301 is_deactivate: bool,
20302 },
20303}
20304
20305impl EventEmitter<EditorEvent> for Editor {}
20306
20307impl Focusable for Editor {
20308 fn focus_handle(&self, _cx: &App) -> FocusHandle {
20309 self.focus_handle.clone()
20310 }
20311}
20312
20313impl Render for Editor {
20314 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20315 let settings = ThemeSettings::get_global(cx);
20316
20317 let mut text_style = match self.mode {
20318 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20319 color: cx.theme().colors().editor_foreground,
20320 font_family: settings.ui_font.family.clone(),
20321 font_features: settings.ui_font.features.clone(),
20322 font_fallbacks: settings.ui_font.fallbacks.clone(),
20323 font_size: rems(0.875).into(),
20324 font_weight: settings.ui_font.weight,
20325 line_height: relative(settings.buffer_line_height.value()),
20326 ..Default::default()
20327 },
20328 EditorMode::Full { .. } => TextStyle {
20329 color: cx.theme().colors().editor_foreground,
20330 font_family: settings.buffer_font.family.clone(),
20331 font_features: settings.buffer_font.features.clone(),
20332 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20333 font_size: settings.buffer_font_size(cx).into(),
20334 font_weight: settings.buffer_font.weight,
20335 line_height: relative(settings.buffer_line_height.value()),
20336 ..Default::default()
20337 },
20338 };
20339 if let Some(text_style_refinement) = &self.text_style_refinement {
20340 text_style.refine(text_style_refinement)
20341 }
20342
20343 let background = match self.mode {
20344 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20345 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20346 EditorMode::Full { .. } => cx.theme().colors().editor_background,
20347 };
20348
20349 EditorElement::new(
20350 &cx.entity(),
20351 EditorStyle {
20352 background,
20353 local_player: cx.theme().players().local(),
20354 text: text_style,
20355 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20356 syntax: cx.theme().syntax().clone(),
20357 status: cx.theme().status().clone(),
20358 inlay_hints_style: make_inlay_hints_style(cx),
20359 inline_completion_styles: make_suggestion_styles(cx),
20360 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20361 },
20362 )
20363 }
20364}
20365
20366impl EntityInputHandler for Editor {
20367 fn text_for_range(
20368 &mut self,
20369 range_utf16: Range<usize>,
20370 adjusted_range: &mut Option<Range<usize>>,
20371 _: &mut Window,
20372 cx: &mut Context<Self>,
20373 ) -> Option<String> {
20374 let snapshot = self.buffer.read(cx).read(cx);
20375 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20376 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20377 if (start.0..end.0) != range_utf16 {
20378 adjusted_range.replace(start.0..end.0);
20379 }
20380 Some(snapshot.text_for_range(start..end).collect())
20381 }
20382
20383 fn selected_text_range(
20384 &mut self,
20385 ignore_disabled_input: bool,
20386 _: &mut Window,
20387 cx: &mut Context<Self>,
20388 ) -> Option<UTF16Selection> {
20389 // Prevent the IME menu from appearing when holding down an alphabetic key
20390 // while input is disabled.
20391 if !ignore_disabled_input && !self.input_enabled {
20392 return None;
20393 }
20394
20395 let selection = self.selections.newest::<OffsetUtf16>(cx);
20396 let range = selection.range();
20397
20398 Some(UTF16Selection {
20399 range: range.start.0..range.end.0,
20400 reversed: selection.reversed,
20401 })
20402 }
20403
20404 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20405 let snapshot = self.buffer.read(cx).read(cx);
20406 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20407 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20408 }
20409
20410 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20411 self.clear_highlights::<InputComposition>(cx);
20412 self.ime_transaction.take();
20413 }
20414
20415 fn replace_text_in_range(
20416 &mut self,
20417 range_utf16: Option<Range<usize>>,
20418 text: &str,
20419 window: &mut Window,
20420 cx: &mut Context<Self>,
20421 ) {
20422 if !self.input_enabled {
20423 cx.emit(EditorEvent::InputIgnored { text: text.into() });
20424 return;
20425 }
20426
20427 self.transact(window, cx, |this, window, cx| {
20428 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20429 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20430 Some(this.selection_replacement_ranges(range_utf16, cx))
20431 } else {
20432 this.marked_text_ranges(cx)
20433 };
20434
20435 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20436 let newest_selection_id = this.selections.newest_anchor().id;
20437 this.selections
20438 .all::<OffsetUtf16>(cx)
20439 .iter()
20440 .zip(ranges_to_replace.iter())
20441 .find_map(|(selection, range)| {
20442 if selection.id == newest_selection_id {
20443 Some(
20444 (range.start.0 as isize - selection.head().0 as isize)
20445 ..(range.end.0 as isize - selection.head().0 as isize),
20446 )
20447 } else {
20448 None
20449 }
20450 })
20451 });
20452
20453 cx.emit(EditorEvent::InputHandled {
20454 utf16_range_to_replace: range_to_replace,
20455 text: text.into(),
20456 });
20457
20458 if let Some(new_selected_ranges) = new_selected_ranges {
20459 this.change_selections(None, window, cx, |selections| {
20460 selections.select_ranges(new_selected_ranges)
20461 });
20462 this.backspace(&Default::default(), window, cx);
20463 }
20464
20465 this.handle_input(text, window, cx);
20466 });
20467
20468 if let Some(transaction) = self.ime_transaction {
20469 self.buffer.update(cx, |buffer, cx| {
20470 buffer.group_until_transaction(transaction, cx);
20471 });
20472 }
20473
20474 self.unmark_text(window, cx);
20475 }
20476
20477 fn replace_and_mark_text_in_range(
20478 &mut self,
20479 range_utf16: Option<Range<usize>>,
20480 text: &str,
20481 new_selected_range_utf16: Option<Range<usize>>,
20482 window: &mut Window,
20483 cx: &mut Context<Self>,
20484 ) {
20485 if !self.input_enabled {
20486 return;
20487 }
20488
20489 let transaction = self.transact(window, cx, |this, window, cx| {
20490 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20491 let snapshot = this.buffer.read(cx).read(cx);
20492 if let Some(relative_range_utf16) = range_utf16.as_ref() {
20493 for marked_range in &mut marked_ranges {
20494 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20495 marked_range.start.0 += relative_range_utf16.start;
20496 marked_range.start =
20497 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20498 marked_range.end =
20499 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20500 }
20501 }
20502 Some(marked_ranges)
20503 } else if let Some(range_utf16) = range_utf16 {
20504 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20505 Some(this.selection_replacement_ranges(range_utf16, cx))
20506 } else {
20507 None
20508 };
20509
20510 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20511 let newest_selection_id = this.selections.newest_anchor().id;
20512 this.selections
20513 .all::<OffsetUtf16>(cx)
20514 .iter()
20515 .zip(ranges_to_replace.iter())
20516 .find_map(|(selection, range)| {
20517 if selection.id == newest_selection_id {
20518 Some(
20519 (range.start.0 as isize - selection.head().0 as isize)
20520 ..(range.end.0 as isize - selection.head().0 as isize),
20521 )
20522 } else {
20523 None
20524 }
20525 })
20526 });
20527
20528 cx.emit(EditorEvent::InputHandled {
20529 utf16_range_to_replace: range_to_replace,
20530 text: text.into(),
20531 });
20532
20533 if let Some(ranges) = ranges_to_replace {
20534 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20535 }
20536
20537 let marked_ranges = {
20538 let snapshot = this.buffer.read(cx).read(cx);
20539 this.selections
20540 .disjoint_anchors()
20541 .iter()
20542 .map(|selection| {
20543 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20544 })
20545 .collect::<Vec<_>>()
20546 };
20547
20548 if text.is_empty() {
20549 this.unmark_text(window, cx);
20550 } else {
20551 this.highlight_text::<InputComposition>(
20552 marked_ranges.clone(),
20553 HighlightStyle {
20554 underline: Some(UnderlineStyle {
20555 thickness: px(1.),
20556 color: None,
20557 wavy: false,
20558 }),
20559 ..Default::default()
20560 },
20561 cx,
20562 );
20563 }
20564
20565 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20566 let use_autoclose = this.use_autoclose;
20567 let use_auto_surround = this.use_auto_surround;
20568 this.set_use_autoclose(false);
20569 this.set_use_auto_surround(false);
20570 this.handle_input(text, window, cx);
20571 this.set_use_autoclose(use_autoclose);
20572 this.set_use_auto_surround(use_auto_surround);
20573
20574 if let Some(new_selected_range) = new_selected_range_utf16 {
20575 let snapshot = this.buffer.read(cx).read(cx);
20576 let new_selected_ranges = marked_ranges
20577 .into_iter()
20578 .map(|marked_range| {
20579 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20580 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20581 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20582 snapshot.clip_offset_utf16(new_start, Bias::Left)
20583 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20584 })
20585 .collect::<Vec<_>>();
20586
20587 drop(snapshot);
20588 this.change_selections(None, window, cx, |selections| {
20589 selections.select_ranges(new_selected_ranges)
20590 });
20591 }
20592 });
20593
20594 self.ime_transaction = self.ime_transaction.or(transaction);
20595 if let Some(transaction) = self.ime_transaction {
20596 self.buffer.update(cx, |buffer, cx| {
20597 buffer.group_until_transaction(transaction, cx);
20598 });
20599 }
20600
20601 if self.text_highlights::<InputComposition>(cx).is_none() {
20602 self.ime_transaction.take();
20603 }
20604 }
20605
20606 fn bounds_for_range(
20607 &mut self,
20608 range_utf16: Range<usize>,
20609 element_bounds: gpui::Bounds<Pixels>,
20610 window: &mut Window,
20611 cx: &mut Context<Self>,
20612 ) -> Option<gpui::Bounds<Pixels>> {
20613 let text_layout_details = self.text_layout_details(window);
20614 let gpui::Size {
20615 width: em_width,
20616 height: line_height,
20617 } = self.character_size(window);
20618
20619 let snapshot = self.snapshot(window, cx);
20620 let scroll_position = snapshot.scroll_position();
20621 let scroll_left = scroll_position.x * em_width;
20622
20623 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20624 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20625 + self.gutter_dimensions.width
20626 + self.gutter_dimensions.margin;
20627 let y = line_height * (start.row().as_f32() - scroll_position.y);
20628
20629 Some(Bounds {
20630 origin: element_bounds.origin + point(x, y),
20631 size: size(em_width, line_height),
20632 })
20633 }
20634
20635 fn character_index_for_point(
20636 &mut self,
20637 point: gpui::Point<Pixels>,
20638 _window: &mut Window,
20639 _cx: &mut Context<Self>,
20640 ) -> Option<usize> {
20641 let position_map = self.last_position_map.as_ref()?;
20642 if !position_map.text_hitbox.contains(&point) {
20643 return None;
20644 }
20645 let display_point = position_map.point_for_position(point).previous_valid;
20646 let anchor = position_map
20647 .snapshot
20648 .display_point_to_anchor(display_point, Bias::Left);
20649 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20650 Some(utf16_offset.0)
20651 }
20652}
20653
20654trait SelectionExt {
20655 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20656 fn spanned_rows(
20657 &self,
20658 include_end_if_at_line_start: bool,
20659 map: &DisplaySnapshot,
20660 ) -> Range<MultiBufferRow>;
20661}
20662
20663impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20664 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20665 let start = self
20666 .start
20667 .to_point(&map.buffer_snapshot)
20668 .to_display_point(map);
20669 let end = self
20670 .end
20671 .to_point(&map.buffer_snapshot)
20672 .to_display_point(map);
20673 if self.reversed {
20674 end..start
20675 } else {
20676 start..end
20677 }
20678 }
20679
20680 fn spanned_rows(
20681 &self,
20682 include_end_if_at_line_start: bool,
20683 map: &DisplaySnapshot,
20684 ) -> Range<MultiBufferRow> {
20685 let start = self.start.to_point(&map.buffer_snapshot);
20686 let mut end = self.end.to_point(&map.buffer_snapshot);
20687 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20688 end.row -= 1;
20689 }
20690
20691 let buffer_start = map.prev_line_boundary(start).0;
20692 let buffer_end = map.next_line_boundary(end).0;
20693 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20694 }
20695}
20696
20697impl<T: InvalidationRegion> InvalidationStack<T> {
20698 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20699 where
20700 S: Clone + ToOffset,
20701 {
20702 while let Some(region) = self.last() {
20703 let all_selections_inside_invalidation_ranges =
20704 if selections.len() == region.ranges().len() {
20705 selections
20706 .iter()
20707 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20708 .all(|(selection, invalidation_range)| {
20709 let head = selection.head().to_offset(buffer);
20710 invalidation_range.start <= head && invalidation_range.end >= head
20711 })
20712 } else {
20713 false
20714 };
20715
20716 if all_selections_inside_invalidation_ranges {
20717 break;
20718 } else {
20719 self.pop();
20720 }
20721 }
20722 }
20723}
20724
20725impl<T> Default for InvalidationStack<T> {
20726 fn default() -> Self {
20727 Self(Default::default())
20728 }
20729}
20730
20731impl<T> Deref for InvalidationStack<T> {
20732 type Target = Vec<T>;
20733
20734 fn deref(&self) -> &Self::Target {
20735 &self.0
20736 }
20737}
20738
20739impl<T> DerefMut for InvalidationStack<T> {
20740 fn deref_mut(&mut self) -> &mut Self::Target {
20741 &mut self.0
20742 }
20743}
20744
20745impl InvalidationRegion for SnippetState {
20746 fn ranges(&self) -> &[Range<Anchor>] {
20747 &self.ranges[self.active_index]
20748 }
20749}
20750
20751fn inline_completion_edit_text(
20752 current_snapshot: &BufferSnapshot,
20753 edits: &[(Range<Anchor>, String)],
20754 edit_preview: &EditPreview,
20755 include_deletions: bool,
20756 cx: &App,
20757) -> HighlightedText {
20758 let edits = edits
20759 .iter()
20760 .map(|(anchor, text)| {
20761 (
20762 anchor.start.text_anchor..anchor.end.text_anchor,
20763 text.clone(),
20764 )
20765 })
20766 .collect::<Vec<_>>();
20767
20768 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20769}
20770
20771pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20772 match severity {
20773 DiagnosticSeverity::ERROR => colors.error,
20774 DiagnosticSeverity::WARNING => colors.warning,
20775 DiagnosticSeverity::INFORMATION => colors.info,
20776 DiagnosticSeverity::HINT => colors.info,
20777 _ => colors.ignored,
20778 }
20779}
20780
20781pub fn styled_runs_for_code_label<'a>(
20782 label: &'a CodeLabel,
20783 syntax_theme: &'a theme::SyntaxTheme,
20784) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20785 let fade_out = HighlightStyle {
20786 fade_out: Some(0.35),
20787 ..Default::default()
20788 };
20789
20790 let mut prev_end = label.filter_range.end;
20791 label
20792 .runs
20793 .iter()
20794 .enumerate()
20795 .flat_map(move |(ix, (range, highlight_id))| {
20796 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20797 style
20798 } else {
20799 return Default::default();
20800 };
20801 let mut muted_style = style;
20802 muted_style.highlight(fade_out);
20803
20804 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20805 if range.start >= label.filter_range.end {
20806 if range.start > prev_end {
20807 runs.push((prev_end..range.start, fade_out));
20808 }
20809 runs.push((range.clone(), muted_style));
20810 } else if range.end <= label.filter_range.end {
20811 runs.push((range.clone(), style));
20812 } else {
20813 runs.push((range.start..label.filter_range.end, style));
20814 runs.push((label.filter_range.end..range.end, muted_style));
20815 }
20816 prev_end = cmp::max(prev_end, range.end);
20817
20818 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20819 runs.push((prev_end..label.text.len(), fade_out));
20820 }
20821
20822 runs
20823 })
20824}
20825
20826pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20827 let mut prev_index = 0;
20828 let mut prev_codepoint: Option<char> = None;
20829 text.char_indices()
20830 .chain([(text.len(), '\0')])
20831 .filter_map(move |(index, codepoint)| {
20832 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20833 let is_boundary = index == text.len()
20834 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20835 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20836 if is_boundary {
20837 let chunk = &text[prev_index..index];
20838 prev_index = index;
20839 Some(chunk)
20840 } else {
20841 None
20842 }
20843 })
20844}
20845
20846pub trait RangeToAnchorExt: Sized {
20847 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20848
20849 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20850 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20851 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20852 }
20853}
20854
20855impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20856 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20857 let start_offset = self.start.to_offset(snapshot);
20858 let end_offset = self.end.to_offset(snapshot);
20859 if start_offset == end_offset {
20860 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20861 } else {
20862 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20863 }
20864 }
20865}
20866
20867pub trait RowExt {
20868 fn as_f32(&self) -> f32;
20869
20870 fn next_row(&self) -> Self;
20871
20872 fn previous_row(&self) -> Self;
20873
20874 fn minus(&self, other: Self) -> u32;
20875}
20876
20877impl RowExt for DisplayRow {
20878 fn as_f32(&self) -> f32 {
20879 self.0 as f32
20880 }
20881
20882 fn next_row(&self) -> Self {
20883 Self(self.0 + 1)
20884 }
20885
20886 fn previous_row(&self) -> Self {
20887 Self(self.0.saturating_sub(1))
20888 }
20889
20890 fn minus(&self, other: Self) -> u32 {
20891 self.0 - other.0
20892 }
20893}
20894
20895impl RowExt for MultiBufferRow {
20896 fn as_f32(&self) -> f32 {
20897 self.0 as f32
20898 }
20899
20900 fn next_row(&self) -> Self {
20901 Self(self.0 + 1)
20902 }
20903
20904 fn previous_row(&self) -> Self {
20905 Self(self.0.saturating_sub(1))
20906 }
20907
20908 fn minus(&self, other: Self) -> u32 {
20909 self.0 - other.0
20910 }
20911}
20912
20913trait RowRangeExt {
20914 type Row;
20915
20916 fn len(&self) -> usize;
20917
20918 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20919}
20920
20921impl RowRangeExt for Range<MultiBufferRow> {
20922 type Row = MultiBufferRow;
20923
20924 fn len(&self) -> usize {
20925 (self.end.0 - self.start.0) as usize
20926 }
20927
20928 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20929 (self.start.0..self.end.0).map(MultiBufferRow)
20930 }
20931}
20932
20933impl RowRangeExt for Range<DisplayRow> {
20934 type Row = DisplayRow;
20935
20936 fn len(&self) -> usize {
20937 (self.end.0 - self.start.0) as usize
20938 }
20939
20940 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20941 (self.start.0..self.end.0).map(DisplayRow)
20942 }
20943}
20944
20945/// If select range has more than one line, we
20946/// just point the cursor to range.start.
20947fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20948 if range.start.row == range.end.row {
20949 range
20950 } else {
20951 range.start..range.start
20952 }
20953}
20954pub struct KillRing(ClipboardItem);
20955impl Global for KillRing {}
20956
20957const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20958
20959enum BreakpointPromptEditAction {
20960 Log,
20961 Condition,
20962 HitCondition,
20963}
20964
20965struct BreakpointPromptEditor {
20966 pub(crate) prompt: Entity<Editor>,
20967 editor: WeakEntity<Editor>,
20968 breakpoint_anchor: Anchor,
20969 breakpoint: Breakpoint,
20970 edit_action: BreakpointPromptEditAction,
20971 block_ids: HashSet<CustomBlockId>,
20972 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20973 _subscriptions: Vec<Subscription>,
20974}
20975
20976impl BreakpointPromptEditor {
20977 const MAX_LINES: u8 = 4;
20978
20979 fn new(
20980 editor: WeakEntity<Editor>,
20981 breakpoint_anchor: Anchor,
20982 breakpoint: Breakpoint,
20983 edit_action: BreakpointPromptEditAction,
20984 window: &mut Window,
20985 cx: &mut Context<Self>,
20986 ) -> Self {
20987 let base_text = match edit_action {
20988 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20989 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20990 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20991 }
20992 .map(|msg| msg.to_string())
20993 .unwrap_or_default();
20994
20995 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20996 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20997
20998 let prompt = cx.new(|cx| {
20999 let mut prompt = Editor::new(
21000 EditorMode::AutoHeight {
21001 max_lines: Self::MAX_LINES as usize,
21002 },
21003 buffer,
21004 None,
21005 window,
21006 cx,
21007 );
21008 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21009 prompt.set_show_cursor_when_unfocused(false, cx);
21010 prompt.set_placeholder_text(
21011 match edit_action {
21012 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21013 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21014 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21015 },
21016 cx,
21017 );
21018
21019 prompt
21020 });
21021
21022 Self {
21023 prompt,
21024 editor,
21025 breakpoint_anchor,
21026 breakpoint,
21027 edit_action,
21028 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
21029 block_ids: Default::default(),
21030 _subscriptions: vec![],
21031 }
21032 }
21033
21034 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21035 self.block_ids.extend(block_ids)
21036 }
21037
21038 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21039 if let Some(editor) = self.editor.upgrade() {
21040 let message = self
21041 .prompt
21042 .read(cx)
21043 .buffer
21044 .read(cx)
21045 .as_singleton()
21046 .expect("A multi buffer in breakpoint prompt isn't possible")
21047 .read(cx)
21048 .as_rope()
21049 .to_string();
21050
21051 editor.update(cx, |editor, cx| {
21052 editor.edit_breakpoint_at_anchor(
21053 self.breakpoint_anchor,
21054 self.breakpoint.clone(),
21055 match self.edit_action {
21056 BreakpointPromptEditAction::Log => {
21057 BreakpointEditAction::EditLogMessage(message.into())
21058 }
21059 BreakpointPromptEditAction::Condition => {
21060 BreakpointEditAction::EditCondition(message.into())
21061 }
21062 BreakpointPromptEditAction::HitCondition => {
21063 BreakpointEditAction::EditHitCondition(message.into())
21064 }
21065 },
21066 cx,
21067 );
21068
21069 editor.remove_blocks(self.block_ids.clone(), None, cx);
21070 cx.focus_self(window);
21071 });
21072 }
21073 }
21074
21075 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21076 self.editor
21077 .update(cx, |editor, cx| {
21078 editor.remove_blocks(self.block_ids.clone(), None, cx);
21079 window.focus(&editor.focus_handle);
21080 })
21081 .log_err();
21082 }
21083
21084 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21085 let settings = ThemeSettings::get_global(cx);
21086 let text_style = TextStyle {
21087 color: if self.prompt.read(cx).read_only(cx) {
21088 cx.theme().colors().text_disabled
21089 } else {
21090 cx.theme().colors().text
21091 },
21092 font_family: settings.buffer_font.family.clone(),
21093 font_fallbacks: settings.buffer_font.fallbacks.clone(),
21094 font_size: settings.buffer_font_size(cx).into(),
21095 font_weight: settings.buffer_font.weight,
21096 line_height: relative(settings.buffer_line_height.value()),
21097 ..Default::default()
21098 };
21099 EditorElement::new(
21100 &self.prompt,
21101 EditorStyle {
21102 background: cx.theme().colors().editor_background,
21103 local_player: cx.theme().players().local(),
21104 text: text_style,
21105 ..Default::default()
21106 },
21107 )
21108 }
21109}
21110
21111impl Render for BreakpointPromptEditor {
21112 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21113 let gutter_dimensions = *self.gutter_dimensions.lock();
21114 h_flex()
21115 .key_context("Editor")
21116 .bg(cx.theme().colors().editor_background)
21117 .border_y_1()
21118 .border_color(cx.theme().status().info_border)
21119 .size_full()
21120 .py(window.line_height() / 2.5)
21121 .on_action(cx.listener(Self::confirm))
21122 .on_action(cx.listener(Self::cancel))
21123 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21124 .child(div().flex_1().child(self.render_prompt_editor(cx)))
21125 }
21126}
21127
21128impl Focusable for BreakpointPromptEditor {
21129 fn focus_handle(&self, cx: &App) -> FocusHandle {
21130 self.prompt.focus_handle(cx)
21131 }
21132}
21133
21134fn all_edits_insertions_or_deletions(
21135 edits: &Vec<(Range<Anchor>, String)>,
21136 snapshot: &MultiBufferSnapshot,
21137) -> bool {
21138 let mut all_insertions = true;
21139 let mut all_deletions = true;
21140
21141 for (range, new_text) in edits.iter() {
21142 let range_is_empty = range.to_offset(&snapshot).is_empty();
21143 let text_is_empty = new_text.is_empty();
21144
21145 if range_is_empty != text_is_empty {
21146 if range_is_empty {
21147 all_deletions = false;
21148 } else {
21149 all_insertions = false;
21150 }
21151 } else {
21152 return false;
21153 }
21154
21155 if !all_insertions && !all_deletions {
21156 return false;
21157 }
21158 }
21159 all_insertions || all_deletions
21160}
21161
21162struct MissingEditPredictionKeybindingTooltip;
21163
21164impl Render for MissingEditPredictionKeybindingTooltip {
21165 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21166 ui::tooltip_container(window, cx, |container, _, cx| {
21167 container
21168 .flex_shrink_0()
21169 .max_w_80()
21170 .min_h(rems_from_px(124.))
21171 .justify_between()
21172 .child(
21173 v_flex()
21174 .flex_1()
21175 .text_ui_sm(cx)
21176 .child(Label::new("Conflict with Accept Keybinding"))
21177 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21178 )
21179 .child(
21180 h_flex()
21181 .pb_1()
21182 .gap_1()
21183 .items_end()
21184 .w_full()
21185 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21186 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21187 }))
21188 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21189 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21190 })),
21191 )
21192 })
21193 }
21194}
21195
21196#[derive(Debug, Clone, Copy, PartialEq)]
21197pub struct LineHighlight {
21198 pub background: Background,
21199 pub border: Option<gpui::Hsla>,
21200 pub include_gutter: bool,
21201 pub type_id: Option<TypeId>,
21202}
21203
21204fn render_diff_hunk_controls(
21205 row: u32,
21206 status: &DiffHunkStatus,
21207 hunk_range: Range<Anchor>,
21208 is_created_file: bool,
21209 line_height: Pixels,
21210 editor: &Entity<Editor>,
21211 _window: &mut Window,
21212 cx: &mut App,
21213) -> AnyElement {
21214 h_flex()
21215 .h(line_height)
21216 .mr_1()
21217 .gap_1()
21218 .px_0p5()
21219 .pb_1()
21220 .border_x_1()
21221 .border_b_1()
21222 .border_color(cx.theme().colors().border_variant)
21223 .rounded_b_lg()
21224 .bg(cx.theme().colors().editor_background)
21225 .gap_1()
21226 .occlude()
21227 .shadow_md()
21228 .child(if status.has_secondary_hunk() {
21229 Button::new(("stage", row as u64), "Stage")
21230 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21231 .tooltip({
21232 let focus_handle = editor.focus_handle(cx);
21233 move |window, cx| {
21234 Tooltip::for_action_in(
21235 "Stage Hunk",
21236 &::git::ToggleStaged,
21237 &focus_handle,
21238 window,
21239 cx,
21240 )
21241 }
21242 })
21243 .on_click({
21244 let editor = editor.clone();
21245 move |_event, _window, cx| {
21246 editor.update(cx, |editor, cx| {
21247 editor.stage_or_unstage_diff_hunks(
21248 true,
21249 vec![hunk_range.start..hunk_range.start],
21250 cx,
21251 );
21252 });
21253 }
21254 })
21255 } else {
21256 Button::new(("unstage", row as u64), "Unstage")
21257 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21258 .tooltip({
21259 let focus_handle = editor.focus_handle(cx);
21260 move |window, cx| {
21261 Tooltip::for_action_in(
21262 "Unstage Hunk",
21263 &::git::ToggleStaged,
21264 &focus_handle,
21265 window,
21266 cx,
21267 )
21268 }
21269 })
21270 .on_click({
21271 let editor = editor.clone();
21272 move |_event, _window, cx| {
21273 editor.update(cx, |editor, cx| {
21274 editor.stage_or_unstage_diff_hunks(
21275 false,
21276 vec![hunk_range.start..hunk_range.start],
21277 cx,
21278 );
21279 });
21280 }
21281 })
21282 })
21283 .child(
21284 Button::new(("restore", row as u64), "Restore")
21285 .tooltip({
21286 let focus_handle = editor.focus_handle(cx);
21287 move |window, cx| {
21288 Tooltip::for_action_in(
21289 "Restore Hunk",
21290 &::git::Restore,
21291 &focus_handle,
21292 window,
21293 cx,
21294 )
21295 }
21296 })
21297 .on_click({
21298 let editor = editor.clone();
21299 move |_event, window, cx| {
21300 editor.update(cx, |editor, cx| {
21301 let snapshot = editor.snapshot(window, cx);
21302 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21303 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21304 });
21305 }
21306 })
21307 .disabled(is_created_file),
21308 )
21309 .when(
21310 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21311 |el| {
21312 el.child(
21313 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21314 .shape(IconButtonShape::Square)
21315 .icon_size(IconSize::Small)
21316 // .disabled(!has_multiple_hunks)
21317 .tooltip({
21318 let focus_handle = editor.focus_handle(cx);
21319 move |window, cx| {
21320 Tooltip::for_action_in(
21321 "Next Hunk",
21322 &GoToHunk,
21323 &focus_handle,
21324 window,
21325 cx,
21326 )
21327 }
21328 })
21329 .on_click({
21330 let editor = editor.clone();
21331 move |_event, window, cx| {
21332 editor.update(cx, |editor, cx| {
21333 let snapshot = editor.snapshot(window, cx);
21334 let position =
21335 hunk_range.end.to_point(&snapshot.buffer_snapshot);
21336 editor.go_to_hunk_before_or_after_position(
21337 &snapshot,
21338 position,
21339 Direction::Next,
21340 window,
21341 cx,
21342 );
21343 editor.expand_selected_diff_hunks(cx);
21344 });
21345 }
21346 }),
21347 )
21348 .child(
21349 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21350 .shape(IconButtonShape::Square)
21351 .icon_size(IconSize::Small)
21352 // .disabled(!has_multiple_hunks)
21353 .tooltip({
21354 let focus_handle = editor.focus_handle(cx);
21355 move |window, cx| {
21356 Tooltip::for_action_in(
21357 "Previous Hunk",
21358 &GoToPreviousHunk,
21359 &focus_handle,
21360 window,
21361 cx,
21362 )
21363 }
21364 })
21365 .on_click({
21366 let editor = editor.clone();
21367 move |_event, window, cx| {
21368 editor.update(cx, |editor, cx| {
21369 let snapshot = editor.snapshot(window, cx);
21370 let point =
21371 hunk_range.start.to_point(&snapshot.buffer_snapshot);
21372 editor.go_to_hunk_before_or_after_position(
21373 &snapshot,
21374 point,
21375 Direction::Prev,
21376 window,
21377 cx,
21378 );
21379 editor.expand_selected_diff_hunks(cx);
21380 });
21381 }
21382 }),
21383 )
21384 },
21385 )
21386 .into_any_element()
21387}