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};
64pub use editor_settings::{
65 CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
66 ShowScrollbar,
67};
68use editor_settings::{GoToDefinitionFallback, Minimap as MinimapSettings};
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;
234pub(crate) const MINIMAP_FONT_SIZE: AbsoluteLength = AbsoluteLength::Pixels(px(2.));
235
236pub type RenderDiffHunkControlsFn = Arc<
237 dyn Fn(
238 u32,
239 &DiffHunkStatus,
240 Range<Anchor>,
241 bool,
242 Pixels,
243 &Entity<Editor>,
244 &mut Window,
245 &mut App,
246 ) -> AnyElement,
247>;
248
249const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
250 alt: true,
251 shift: true,
252 control: false,
253 platform: false,
254 function: false,
255};
256
257struct InlineValueCache {
258 enabled: bool,
259 inlays: Vec<InlayId>,
260 refresh_task: Task<Option<()>>,
261}
262
263impl InlineValueCache {
264 fn new(enabled: bool) -> Self {
265 Self {
266 enabled,
267 inlays: Vec::new(),
268 refresh_task: Task::ready(None),
269 }
270 }
271}
272
273#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
274pub enum InlayId {
275 InlineCompletion(usize),
276 Hint(usize),
277 DebuggerValue(usize),
278}
279
280impl InlayId {
281 fn id(&self) -> usize {
282 match self {
283 Self::InlineCompletion(id) => *id,
284 Self::Hint(id) => *id,
285 Self::DebuggerValue(id) => *id,
286 }
287 }
288}
289
290pub enum ActiveDebugLine {}
291enum DocumentHighlightRead {}
292enum DocumentHighlightWrite {}
293enum InputComposition {}
294enum SelectedTextHighlight {}
295
296pub enum ConflictsOuter {}
297pub enum ConflictsOurs {}
298pub enum ConflictsTheirs {}
299pub enum ConflictsOursMarker {}
300pub enum ConflictsTheirsMarker {}
301
302#[derive(Debug, Copy, Clone, PartialEq, Eq)]
303pub enum Navigated {
304 Yes,
305 No,
306}
307
308impl Navigated {
309 pub fn from_bool(yes: bool) -> Navigated {
310 if yes { Navigated::Yes } else { Navigated::No }
311 }
312}
313
314#[derive(Debug, Clone, PartialEq, Eq)]
315enum DisplayDiffHunk {
316 Folded {
317 display_row: DisplayRow,
318 },
319 Unfolded {
320 is_created_file: bool,
321 diff_base_byte_range: Range<usize>,
322 display_row_range: Range<DisplayRow>,
323 multi_buffer_range: Range<Anchor>,
324 status: DiffHunkStatus,
325 },
326}
327
328pub enum HideMouseCursorOrigin {
329 TypingAction,
330 MovementAction,
331}
332
333pub fn init_settings(cx: &mut App) {
334 EditorSettings::register(cx);
335}
336
337pub fn init(cx: &mut App) {
338 init_settings(cx);
339
340 cx.set_global(GlobalBlameRenderer(Arc::new(())));
341
342 workspace::register_project_item::<Editor>(cx);
343 workspace::FollowableViewRegistry::register::<Editor>(cx);
344 workspace::register_serializable_item::<Editor>(cx);
345
346 cx.observe_new(
347 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
348 workspace.register_action(Editor::new_file);
349 workspace.register_action(Editor::new_file_vertical);
350 workspace.register_action(Editor::new_file_horizontal);
351 workspace.register_action(Editor::cancel_language_server_work);
352 },
353 )
354 .detach();
355
356 cx.on_action(move |_: &workspace::NewFile, cx| {
357 let app_state = workspace::AppState::global(cx);
358 if let Some(app_state) = app_state.upgrade() {
359 workspace::open_new(
360 Default::default(),
361 app_state,
362 cx,
363 |workspace, window, cx| {
364 Editor::new_file(workspace, &Default::default(), window, cx)
365 },
366 )
367 .detach();
368 }
369 });
370 cx.on_action(move |_: &workspace::NewWindow, cx| {
371 let app_state = workspace::AppState::global(cx);
372 if let Some(app_state) = app_state.upgrade() {
373 workspace::open_new(
374 Default::default(),
375 app_state,
376 cx,
377 |workspace, window, cx| {
378 cx.activate(true);
379 Editor::new_file(workspace, &Default::default(), window, cx)
380 },
381 )
382 .detach();
383 }
384 });
385}
386
387pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
388 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
389}
390
391pub trait DiagnosticRenderer {
392 fn render_group(
393 &self,
394 diagnostic_group: Vec<DiagnosticEntry<Point>>,
395 buffer_id: BufferId,
396 snapshot: EditorSnapshot,
397 editor: WeakEntity<Editor>,
398 cx: &mut App,
399 ) -> Vec<BlockProperties<Anchor>>;
400
401 fn render_hover(
402 &self,
403 diagnostic_group: Vec<DiagnosticEntry<Point>>,
404 range: Range<Point>,
405 buffer_id: BufferId,
406 cx: &mut App,
407 ) -> Option<Entity<markdown::Markdown>>;
408
409 fn open_link(
410 &self,
411 editor: &mut Editor,
412 link: SharedString,
413 window: &mut Window,
414 cx: &mut Context<Editor>,
415 );
416}
417
418pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
419
420impl GlobalDiagnosticRenderer {
421 fn global(cx: &App) -> Option<Arc<dyn DiagnosticRenderer>> {
422 cx.try_global::<Self>().map(|g| g.0.clone())
423 }
424}
425
426impl gpui::Global for GlobalDiagnosticRenderer {}
427pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
428 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
429}
430
431pub struct SearchWithinRange;
432
433trait InvalidationRegion {
434 fn ranges(&self) -> &[Range<Anchor>];
435}
436
437#[derive(Clone, Debug, PartialEq)]
438pub enum SelectPhase {
439 Begin {
440 position: DisplayPoint,
441 add: bool,
442 click_count: usize,
443 },
444 BeginColumnar {
445 position: DisplayPoint,
446 reset: bool,
447 goal_column: u32,
448 },
449 Extend {
450 position: DisplayPoint,
451 click_count: usize,
452 },
453 Update {
454 position: DisplayPoint,
455 goal_column: u32,
456 scroll_delta: gpui::Point<f32>,
457 },
458 End,
459}
460
461#[derive(Clone, Debug)]
462pub enum SelectMode {
463 Character,
464 Word(Range<Anchor>),
465 Line(Range<Anchor>),
466 All,
467}
468
469#[derive(Clone, PartialEq, Eq, Debug)]
470pub enum EditorMode {
471 SingleLine {
472 auto_width: bool,
473 },
474 AutoHeight {
475 max_lines: usize,
476 },
477 Full {
478 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
479 scale_ui_elements_with_buffer_font_size: bool,
480 /// When set to `true`, the editor will render a background for the active line.
481 show_active_line_background: bool,
482 /// When set to `true`, the editor's height will be determined by its content.
483 sized_by_content: bool,
484 },
485 Minimap {
486 parent: WeakEntity<Editor>,
487 },
488}
489
490impl EditorMode {
491 pub fn full() -> Self {
492 Self::Full {
493 scale_ui_elements_with_buffer_font_size: true,
494 show_active_line_background: true,
495 sized_by_content: false,
496 }
497 }
498
499 pub fn is_full(&self) -> bool {
500 matches!(self, Self::Full { .. })
501 }
502
503 fn is_minimap(&self) -> bool {
504 matches!(self, Self::Minimap { .. })
505 }
506}
507
508#[derive(Copy, Clone, Debug)]
509pub enum SoftWrap {
510 /// Prefer not to wrap at all.
511 ///
512 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
513 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
514 GitDiff,
515 /// Prefer a single line generally, unless an overly long line is encountered.
516 None,
517 /// Soft wrap lines that exceed the editor width.
518 EditorWidth,
519 /// Soft wrap lines at the preferred line length.
520 Column(u32),
521 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
522 Bounded(u32),
523}
524
525#[derive(Clone)]
526pub struct EditorStyle {
527 pub background: Hsla,
528 pub local_player: PlayerColor,
529 pub text: TextStyle,
530 pub scrollbar_width: Pixels,
531 pub syntax: Arc<SyntaxTheme>,
532 pub status: StatusColors,
533 pub inlay_hints_style: HighlightStyle,
534 pub inline_completion_styles: InlineCompletionStyles,
535 pub unnecessary_code_fade: f32,
536 pub show_underlines: bool,
537}
538
539impl Default for EditorStyle {
540 fn default() -> Self {
541 Self {
542 background: Hsla::default(),
543 local_player: PlayerColor::default(),
544 text: TextStyle::default(),
545 scrollbar_width: Pixels::default(),
546 syntax: Default::default(),
547 // HACK: Status colors don't have a real default.
548 // We should look into removing the status colors from the editor
549 // style and retrieve them directly from the theme.
550 status: StatusColors::dark(),
551 inlay_hints_style: HighlightStyle::default(),
552 inline_completion_styles: InlineCompletionStyles {
553 insertion: HighlightStyle::default(),
554 whitespace: HighlightStyle::default(),
555 },
556 unnecessary_code_fade: Default::default(),
557 show_underlines: true,
558 }
559 }
560}
561
562pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
563 let show_background = language_settings::language_settings(None, None, cx)
564 .inlay_hints
565 .show_background;
566
567 HighlightStyle {
568 color: Some(cx.theme().status().hint),
569 background_color: show_background.then(|| cx.theme().status().hint_background),
570 ..HighlightStyle::default()
571 }
572}
573
574pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
575 InlineCompletionStyles {
576 insertion: HighlightStyle {
577 color: Some(cx.theme().status().predictive),
578 ..HighlightStyle::default()
579 },
580 whitespace: HighlightStyle {
581 background_color: Some(cx.theme().status().created_background),
582 ..HighlightStyle::default()
583 },
584 }
585}
586
587type CompletionId = usize;
588
589pub(crate) enum EditDisplayMode {
590 TabAccept,
591 DiffPopover,
592 Inline,
593}
594
595enum InlineCompletion {
596 Edit {
597 edits: Vec<(Range<Anchor>, String)>,
598 edit_preview: Option<EditPreview>,
599 display_mode: EditDisplayMode,
600 snapshot: BufferSnapshot,
601 },
602 Move {
603 target: Anchor,
604 snapshot: BufferSnapshot,
605 },
606}
607
608struct InlineCompletionState {
609 inlay_ids: Vec<InlayId>,
610 completion: InlineCompletion,
611 completion_id: Option<SharedString>,
612 invalidation_range: Range<Anchor>,
613}
614
615enum EditPredictionSettings {
616 Disabled,
617 Enabled {
618 show_in_menu: bool,
619 preview_requires_modifier: bool,
620 },
621}
622
623enum InlineCompletionHighlight {}
624
625#[derive(Debug, Clone)]
626struct InlineDiagnostic {
627 message: SharedString,
628 group_id: usize,
629 is_primary: bool,
630 start: Point,
631 severity: DiagnosticSeverity,
632}
633
634pub enum MenuInlineCompletionsPolicy {
635 Never,
636 ByProvider,
637}
638
639pub enum EditPredictionPreview {
640 /// Modifier is not pressed
641 Inactive { released_too_fast: bool },
642 /// Modifier pressed
643 Active {
644 since: Instant,
645 previous_scroll_position: Option<ScrollAnchor>,
646 },
647}
648
649impl EditPredictionPreview {
650 pub fn released_too_fast(&self) -> bool {
651 match self {
652 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
653 EditPredictionPreview::Active { .. } => false,
654 }
655 }
656
657 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
658 if let EditPredictionPreview::Active {
659 previous_scroll_position,
660 ..
661 } = self
662 {
663 *previous_scroll_position = scroll_position;
664 }
665 }
666}
667
668pub struct ContextMenuOptions {
669 pub min_entries_visible: usize,
670 pub max_entries_visible: usize,
671 pub placement: Option<ContextMenuPlacement>,
672}
673
674#[derive(Debug, Clone, PartialEq, Eq)]
675pub enum ContextMenuPlacement {
676 Above,
677 Below,
678}
679
680#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
681struct EditorActionId(usize);
682
683impl EditorActionId {
684 pub fn post_inc(&mut self) -> Self {
685 let answer = self.0;
686
687 *self = Self(answer + 1);
688
689 Self(answer)
690 }
691}
692
693// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
694// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
695
696type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
697type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
698
699#[derive(Default)]
700struct ScrollbarMarkerState {
701 scrollbar_size: Size<Pixels>,
702 dirty: bool,
703 markers: Arc<[PaintQuad]>,
704 pending_refresh: Option<Task<Result<()>>>,
705}
706
707impl ScrollbarMarkerState {
708 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
709 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
710 }
711}
712
713#[derive(Clone, Debug)]
714struct RunnableTasks {
715 templates: Vec<(TaskSourceKind, TaskTemplate)>,
716 offset: multi_buffer::Anchor,
717 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
718 column: u32,
719 // Values of all named captures, including those starting with '_'
720 extra_variables: HashMap<String, String>,
721 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
722 context_range: Range<BufferOffset>,
723}
724
725impl RunnableTasks {
726 fn resolve<'a>(
727 &'a self,
728 cx: &'a task::TaskContext,
729 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
730 self.templates.iter().filter_map(|(kind, template)| {
731 template
732 .resolve_task(&kind.to_id_base(), cx)
733 .map(|task| (kind.clone(), task))
734 })
735 }
736}
737
738#[derive(Clone)]
739struct ResolvedTasks {
740 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
741 position: Anchor,
742}
743
744#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
745struct BufferOffset(usize);
746
747// Addons allow storing per-editor state in other crates (e.g. Vim)
748pub trait Addon: 'static {
749 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
750
751 fn render_buffer_header_controls(
752 &self,
753 _: &ExcerptInfo,
754 _: &Window,
755 _: &App,
756 ) -> Option<AnyElement> {
757 None
758 }
759
760 fn to_any(&self) -> &dyn std::any::Any;
761
762 fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
763 None
764 }
765}
766
767/// A set of caret positions, registered when the editor was edited.
768pub struct ChangeList {
769 changes: Vec<Vec<Anchor>>,
770 /// Currently "selected" change.
771 position: Option<usize>,
772}
773
774impl ChangeList {
775 pub fn new() -> Self {
776 Self {
777 changes: Vec::new(),
778 position: None,
779 }
780 }
781
782 /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
783 /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
784 pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
785 if self.changes.is_empty() {
786 return None;
787 }
788
789 let prev = self.position.unwrap_or(self.changes.len());
790 let next = if direction == Direction::Prev {
791 prev.saturating_sub(count)
792 } else {
793 (prev + count).min(self.changes.len() - 1)
794 };
795 self.position = Some(next);
796 self.changes.get(next).map(|anchors| anchors.as_slice())
797 }
798
799 /// Adds a new change to the list, resetting the change list position.
800 pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
801 self.position.take();
802 if pop_state {
803 self.changes.pop();
804 }
805 self.changes.push(new_positions.clone());
806 }
807
808 pub fn last(&self) -> Option<&[Anchor]> {
809 self.changes.last().map(|anchors| anchors.as_slice())
810 }
811}
812
813#[derive(Clone)]
814struct InlineBlamePopoverState {
815 scroll_handle: ScrollHandle,
816 commit_message: Option<ParsedCommitMessage>,
817 markdown: Entity<Markdown>,
818}
819
820struct InlineBlamePopover {
821 position: gpui::Point<Pixels>,
822 show_task: Option<Task<()>>,
823 hide_task: Option<Task<()>>,
824 popover_bounds: Option<Bounds<Pixels>>,
825 popover_state: InlineBlamePopoverState,
826}
827
828/// Represents a breakpoint indicator that shows up when hovering over lines in the gutter that don't have
829/// a breakpoint on them.
830#[derive(Clone, Copy, Debug)]
831struct PhantomBreakpointIndicator {
832 display_row: DisplayRow,
833 /// There's a small debounce between hovering over the line and showing the indicator.
834 /// We don't want to show the indicator when moving the mouse from editor to e.g. project panel.
835 is_active: bool,
836 collides_with_existing_breakpoint: bool,
837}
838/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
839///
840/// See the [module level documentation](self) for more information.
841pub struct Editor {
842 focus_handle: FocusHandle,
843 last_focused_descendant: Option<WeakFocusHandle>,
844 /// The text buffer being edited
845 buffer: Entity<MultiBuffer>,
846 /// Map of how text in the buffer should be displayed.
847 /// Handles soft wraps, folds, fake inlay text insertions, etc.
848 pub display_map: Entity<DisplayMap>,
849 pub selections: SelectionsCollection,
850 pub scroll_manager: ScrollManager,
851 /// When inline assist editors are linked, they all render cursors because
852 /// typing enters text into each of them, even the ones that aren't focused.
853 pub(crate) show_cursor_when_unfocused: bool,
854 columnar_selection_tail: Option<Anchor>,
855 add_selections_state: Option<AddSelectionsState>,
856 select_next_state: Option<SelectNextState>,
857 select_prev_state: Option<SelectNextState>,
858 selection_history: SelectionHistory,
859 autoclose_regions: Vec<AutocloseRegion>,
860 snippet_stack: InvalidationStack<SnippetState>,
861 select_syntax_node_history: SelectSyntaxNodeHistory,
862 ime_transaction: Option<TransactionId>,
863 active_diagnostics: ActiveDiagnostic,
864 show_inline_diagnostics: bool,
865 inline_diagnostics_update: Task<()>,
866 inline_diagnostics_enabled: bool,
867 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
868 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
869 hard_wrap: Option<usize>,
870
871 // TODO: make this a access method
872 pub project: Option<Entity<Project>>,
873 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
874 completion_provider: Option<Box<dyn CompletionProvider>>,
875 collaboration_hub: Option<Box<dyn CollaborationHub>>,
876 blink_manager: Entity<BlinkManager>,
877 show_cursor_names: bool,
878 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
879 pub show_local_selections: bool,
880 mode: EditorMode,
881 show_breadcrumbs: bool,
882 show_gutter: bool,
883 show_scrollbars: bool,
884 show_minimap: bool,
885 disable_expand_excerpt_buttons: bool,
886 show_line_numbers: Option<bool>,
887 use_relative_line_numbers: Option<bool>,
888 show_git_diff_gutter: Option<bool>,
889 show_code_actions: Option<bool>,
890 show_runnables: Option<bool>,
891 show_breakpoints: Option<bool>,
892 show_wrap_guides: Option<bool>,
893 show_indent_guides: Option<bool>,
894 placeholder_text: Option<Arc<str>>,
895 highlight_order: usize,
896 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
897 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
898 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
899 scrollbar_marker_state: ScrollbarMarkerState,
900 active_indent_guides_state: ActiveIndentGuidesState,
901 nav_history: Option<ItemNavHistory>,
902 context_menu: RefCell<Option<CodeContextMenu>>,
903 context_menu_options: Option<ContextMenuOptions>,
904 mouse_context_menu: Option<MouseContextMenu>,
905 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
906 inline_blame_popover: Option<InlineBlamePopover>,
907 signature_help_state: SignatureHelpState,
908 auto_signature_help: Option<bool>,
909 find_all_references_task_sources: Vec<Anchor>,
910 next_completion_id: CompletionId,
911 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
912 code_actions_task: Option<Task<Result<()>>>,
913 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
914 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
915 document_highlights_task: Option<Task<()>>,
916 linked_editing_range_task: Option<Task<Option<()>>>,
917 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
918 pending_rename: Option<RenameState>,
919 searchable: bool,
920 cursor_shape: CursorShape,
921 current_line_highlight: Option<CurrentLineHighlight>,
922 collapse_matches: bool,
923 autoindent_mode: Option<AutoindentMode>,
924 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
925 input_enabled: bool,
926 use_modal_editing: bool,
927 read_only: bool,
928 leader_id: Option<CollaboratorId>,
929 remote_id: Option<ViewId>,
930 pub hover_state: HoverState,
931 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
932 gutter_hovered: bool,
933 hovered_link_state: Option<HoveredLinkState>,
934 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
935 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
936 active_inline_completion: Option<InlineCompletionState>,
937 /// Used to prevent flickering as the user types while the menu is open
938 stale_inline_completion_in_menu: Option<InlineCompletionState>,
939 edit_prediction_settings: EditPredictionSettings,
940 inline_completions_hidden_for_vim_mode: bool,
941 show_inline_completions_override: Option<bool>,
942 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
943 edit_prediction_preview: EditPredictionPreview,
944 edit_prediction_indent_conflict: bool,
945 edit_prediction_requires_modifier_in_indent_conflict: bool,
946 inlay_hint_cache: InlayHintCache,
947 next_inlay_id: usize,
948 _subscriptions: Vec<Subscription>,
949 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
950 gutter_dimensions: GutterDimensions,
951 style: Option<EditorStyle>,
952 text_style_refinement: Option<TextStyleRefinement>,
953 next_editor_action_id: EditorActionId,
954 editor_actions:
955 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
956 use_autoclose: bool,
957 use_auto_surround: bool,
958 auto_replace_emoji_shortcode: bool,
959 jsx_tag_auto_close_enabled_in_any_buffer: bool,
960 show_git_blame_gutter: bool,
961 show_git_blame_inline: bool,
962 show_git_blame_inline_delay_task: Option<Task<()>>,
963 git_blame_inline_enabled: bool,
964 render_diff_hunk_controls: RenderDiffHunkControlsFn,
965 serialize_dirty_buffers: bool,
966 show_selection_menu: Option<bool>,
967 blame: Option<Entity<GitBlame>>,
968 blame_subscription: Option<Subscription>,
969 custom_context_menu: Option<
970 Box<
971 dyn 'static
972 + Fn(
973 &mut Self,
974 DisplayPoint,
975 &mut Window,
976 &mut Context<Self>,
977 ) -> Option<Entity<ui::ContextMenu>>,
978 >,
979 >,
980 last_bounds: Option<Bounds<Pixels>>,
981 last_position_map: Option<Rc<PositionMap>>,
982 expect_bounds_change: Option<Bounds<Pixels>>,
983 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
984 tasks_update_task: Option<Task<()>>,
985 breakpoint_store: Option<Entity<BreakpointStore>>,
986 gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
987 in_project_search: bool,
988 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
989 breadcrumb_header: Option<String>,
990 focused_block: Option<FocusedBlock>,
991 next_scroll_position: NextScrollCursorCenterTopBottom,
992 addons: HashMap<TypeId, Box<dyn Addon>>,
993 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
994 load_diff_task: Option<Shared<Task<()>>>,
995 /// Whether we are temporarily displaying a diff other than git's
996 temporary_diff_override: bool,
997 selection_mark_mode: bool,
998 toggle_fold_multiple_buffers: Task<()>,
999 _scroll_cursor_center_top_bottom_task: Task<()>,
1000 serialize_selections: Task<()>,
1001 serialize_folds: Task<()>,
1002 mouse_cursor_hidden: bool,
1003 minimap: Option<Entity<Self>>,
1004 hide_mouse_mode: HideMouseMode,
1005 pub change_list: ChangeList,
1006 inline_value_cache: InlineValueCache,
1007}
1008
1009#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
1010enum NextScrollCursorCenterTopBottom {
1011 #[default]
1012 Center,
1013 Top,
1014 Bottom,
1015}
1016
1017impl NextScrollCursorCenterTopBottom {
1018 fn next(&self) -> Self {
1019 match self {
1020 Self::Center => Self::Top,
1021 Self::Top => Self::Bottom,
1022 Self::Bottom => Self::Center,
1023 }
1024 }
1025}
1026
1027#[derive(Clone)]
1028pub struct EditorSnapshot {
1029 pub mode: EditorMode,
1030 show_gutter: bool,
1031 show_line_numbers: Option<bool>,
1032 show_git_diff_gutter: Option<bool>,
1033 show_runnables: Option<bool>,
1034 show_breakpoints: Option<bool>,
1035 git_blame_gutter_max_author_length: Option<usize>,
1036 pub display_snapshot: DisplaySnapshot,
1037 pub placeholder_text: Option<Arc<str>>,
1038 is_focused: bool,
1039 scroll_anchor: ScrollAnchor,
1040 ongoing_scroll: OngoingScroll,
1041 current_line_highlight: CurrentLineHighlight,
1042 gutter_hovered: bool,
1043}
1044
1045#[derive(Default, Debug, Clone, Copy)]
1046pub struct GutterDimensions {
1047 pub left_padding: Pixels,
1048 pub right_padding: Pixels,
1049 pub width: Pixels,
1050 pub margin: Pixels,
1051 pub git_blame_entries_width: Option<Pixels>,
1052}
1053
1054impl GutterDimensions {
1055 fn default_with_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Self {
1056 Self {
1057 margin: Self::default_gutter_margin(font_id, font_size, cx),
1058 ..Default::default()
1059 }
1060 }
1061
1062 fn default_gutter_margin(font_id: FontId, font_size: Pixels, cx: &App) -> Pixels {
1063 -cx.text_system().descent(font_id, font_size)
1064 }
1065 /// The full width of the space taken up by the gutter.
1066 pub fn full_width(&self) -> Pixels {
1067 self.margin + self.width
1068 }
1069
1070 /// The width of the space reserved for the fold indicators,
1071 /// use alongside 'justify_end' and `gutter_width` to
1072 /// right align content with the line numbers
1073 pub fn fold_area_width(&self) -> Pixels {
1074 self.margin + self.right_padding
1075 }
1076}
1077
1078#[derive(Debug)]
1079pub struct RemoteSelection {
1080 pub replica_id: ReplicaId,
1081 pub selection: Selection<Anchor>,
1082 pub cursor_shape: CursorShape,
1083 pub collaborator_id: CollaboratorId,
1084 pub line_mode: bool,
1085 pub user_name: Option<SharedString>,
1086 pub color: PlayerColor,
1087}
1088
1089#[derive(Clone, Debug)]
1090struct SelectionHistoryEntry {
1091 selections: Arc<[Selection<Anchor>]>,
1092 select_next_state: Option<SelectNextState>,
1093 select_prev_state: Option<SelectNextState>,
1094 add_selections_state: Option<AddSelectionsState>,
1095}
1096
1097enum SelectionHistoryMode {
1098 Normal,
1099 Undoing,
1100 Redoing,
1101}
1102
1103#[derive(Clone, PartialEq, Eq, Hash)]
1104struct HoveredCursor {
1105 replica_id: u16,
1106 selection_id: usize,
1107}
1108
1109impl Default for SelectionHistoryMode {
1110 fn default() -> Self {
1111 Self::Normal
1112 }
1113}
1114
1115#[derive(Default)]
1116struct SelectionHistory {
1117 #[allow(clippy::type_complexity)]
1118 selections_by_transaction:
1119 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1120 mode: SelectionHistoryMode,
1121 undo_stack: VecDeque<SelectionHistoryEntry>,
1122 redo_stack: VecDeque<SelectionHistoryEntry>,
1123}
1124
1125impl SelectionHistory {
1126 fn insert_transaction(
1127 &mut self,
1128 transaction_id: TransactionId,
1129 selections: Arc<[Selection<Anchor>]>,
1130 ) {
1131 self.selections_by_transaction
1132 .insert(transaction_id, (selections, None));
1133 }
1134
1135 #[allow(clippy::type_complexity)]
1136 fn transaction(
1137 &self,
1138 transaction_id: TransactionId,
1139 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1140 self.selections_by_transaction.get(&transaction_id)
1141 }
1142
1143 #[allow(clippy::type_complexity)]
1144 fn transaction_mut(
1145 &mut self,
1146 transaction_id: TransactionId,
1147 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1148 self.selections_by_transaction.get_mut(&transaction_id)
1149 }
1150
1151 fn push(&mut self, entry: SelectionHistoryEntry) {
1152 if !entry.selections.is_empty() {
1153 match self.mode {
1154 SelectionHistoryMode::Normal => {
1155 self.push_undo(entry);
1156 self.redo_stack.clear();
1157 }
1158 SelectionHistoryMode::Undoing => self.push_redo(entry),
1159 SelectionHistoryMode::Redoing => self.push_undo(entry),
1160 }
1161 }
1162 }
1163
1164 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1165 if self
1166 .undo_stack
1167 .back()
1168 .map_or(true, |e| e.selections != entry.selections)
1169 {
1170 self.undo_stack.push_back(entry);
1171 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1172 self.undo_stack.pop_front();
1173 }
1174 }
1175 }
1176
1177 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1178 if self
1179 .redo_stack
1180 .back()
1181 .map_or(true, |e| e.selections != entry.selections)
1182 {
1183 self.redo_stack.push_back(entry);
1184 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1185 self.redo_stack.pop_front();
1186 }
1187 }
1188 }
1189}
1190
1191#[derive(Clone, Copy)]
1192pub struct RowHighlightOptions {
1193 pub autoscroll: bool,
1194 pub include_gutter: bool,
1195}
1196
1197impl Default for RowHighlightOptions {
1198 fn default() -> Self {
1199 Self {
1200 autoscroll: Default::default(),
1201 include_gutter: true,
1202 }
1203 }
1204}
1205
1206struct RowHighlight {
1207 index: usize,
1208 range: Range<Anchor>,
1209 color: Hsla,
1210 options: RowHighlightOptions,
1211 type_id: TypeId,
1212}
1213
1214#[derive(Clone, Debug)]
1215struct AddSelectionsState {
1216 above: bool,
1217 stack: Vec<usize>,
1218}
1219
1220#[derive(Clone)]
1221struct SelectNextState {
1222 query: AhoCorasick,
1223 wordwise: bool,
1224 done: bool,
1225}
1226
1227impl std::fmt::Debug for SelectNextState {
1228 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1229 f.debug_struct(std::any::type_name::<Self>())
1230 .field("wordwise", &self.wordwise)
1231 .field("done", &self.done)
1232 .finish()
1233 }
1234}
1235
1236#[derive(Debug)]
1237struct AutocloseRegion {
1238 selection_id: usize,
1239 range: Range<Anchor>,
1240 pair: BracketPair,
1241}
1242
1243#[derive(Debug)]
1244struct SnippetState {
1245 ranges: Vec<Vec<Range<Anchor>>>,
1246 active_index: usize,
1247 choices: Vec<Option<Vec<String>>>,
1248}
1249
1250#[doc(hidden)]
1251pub struct RenameState {
1252 pub range: Range<Anchor>,
1253 pub old_name: Arc<str>,
1254 pub editor: Entity<Editor>,
1255 block_id: CustomBlockId,
1256}
1257
1258struct InvalidationStack<T>(Vec<T>);
1259
1260struct RegisteredInlineCompletionProvider {
1261 provider: Arc<dyn InlineCompletionProviderHandle>,
1262 _subscription: Subscription,
1263}
1264
1265#[derive(Debug, PartialEq, Eq)]
1266pub struct ActiveDiagnosticGroup {
1267 pub active_range: Range<Anchor>,
1268 pub active_message: String,
1269 pub group_id: usize,
1270 pub blocks: HashSet<CustomBlockId>,
1271}
1272
1273#[derive(Debug, PartialEq, Eq)]
1274#[allow(clippy::large_enum_variant)]
1275pub(crate) enum ActiveDiagnostic {
1276 None,
1277 All,
1278 Group(ActiveDiagnosticGroup),
1279}
1280
1281#[derive(Serialize, Deserialize, Clone, Debug)]
1282pub struct ClipboardSelection {
1283 /// The number of bytes in this selection.
1284 pub len: usize,
1285 /// Whether this was a full-line selection.
1286 pub is_entire_line: bool,
1287 /// The indentation of the first line when this content was originally copied.
1288 pub first_line_indent: u32,
1289}
1290
1291// selections, scroll behavior, was newest selection reversed
1292type SelectSyntaxNodeHistoryState = (
1293 Box<[Selection<usize>]>,
1294 SelectSyntaxNodeScrollBehavior,
1295 bool,
1296);
1297
1298#[derive(Default)]
1299struct SelectSyntaxNodeHistory {
1300 stack: Vec<SelectSyntaxNodeHistoryState>,
1301 // disable temporarily to allow changing selections without losing the stack
1302 pub disable_clearing: bool,
1303}
1304
1305impl SelectSyntaxNodeHistory {
1306 pub fn try_clear(&mut self) {
1307 if !self.disable_clearing {
1308 self.stack.clear();
1309 }
1310 }
1311
1312 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1313 self.stack.push(selection);
1314 }
1315
1316 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1317 self.stack.pop()
1318 }
1319}
1320
1321enum SelectSyntaxNodeScrollBehavior {
1322 CursorTop,
1323 FitSelection,
1324 CursorBottom,
1325}
1326
1327#[derive(Debug)]
1328pub(crate) struct NavigationData {
1329 cursor_anchor: Anchor,
1330 cursor_position: Point,
1331 scroll_anchor: ScrollAnchor,
1332 scroll_top_row: u32,
1333}
1334
1335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1336pub enum GotoDefinitionKind {
1337 Symbol,
1338 Declaration,
1339 Type,
1340 Implementation,
1341}
1342
1343#[derive(Debug, Clone)]
1344enum InlayHintRefreshReason {
1345 ModifiersChanged(bool),
1346 Toggle(bool),
1347 SettingsChange(InlayHintSettings),
1348 NewLinesShown,
1349 BufferEdited(HashSet<Arc<Language>>),
1350 RefreshRequested,
1351 ExcerptsRemoved(Vec<ExcerptId>),
1352}
1353
1354impl InlayHintRefreshReason {
1355 fn description(&self) -> &'static str {
1356 match self {
1357 Self::ModifiersChanged(_) => "modifiers changed",
1358 Self::Toggle(_) => "toggle",
1359 Self::SettingsChange(_) => "settings change",
1360 Self::NewLinesShown => "new lines shown",
1361 Self::BufferEdited(_) => "buffer edited",
1362 Self::RefreshRequested => "refresh requested",
1363 Self::ExcerptsRemoved(_) => "excerpts removed",
1364 }
1365 }
1366}
1367
1368pub enum FormatTarget {
1369 Buffers,
1370 Ranges(Vec<Range<MultiBufferPoint>>),
1371}
1372
1373pub(crate) struct FocusedBlock {
1374 id: BlockId,
1375 focus_handle: WeakFocusHandle,
1376}
1377
1378#[derive(Clone)]
1379enum JumpData {
1380 MultiBufferRow {
1381 row: MultiBufferRow,
1382 line_offset_from_top: u32,
1383 },
1384 MultiBufferPoint {
1385 excerpt_id: ExcerptId,
1386 position: Point,
1387 anchor: text::Anchor,
1388 line_offset_from_top: u32,
1389 },
1390}
1391
1392pub enum MultibufferSelectionMode {
1393 First,
1394 All,
1395}
1396
1397#[derive(Clone, Copy, Debug, Default)]
1398pub struct RewrapOptions {
1399 pub override_language_settings: bool,
1400 pub preserve_existing_whitespace: bool,
1401}
1402
1403impl Editor {
1404 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1405 let buffer = cx.new(|cx| Buffer::local("", cx));
1406 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1407 Self::new(
1408 EditorMode::SingleLine { auto_width: false },
1409 buffer,
1410 None,
1411 window,
1412 cx,
1413 )
1414 }
1415
1416 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1417 let buffer = cx.new(|cx| Buffer::local("", cx));
1418 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1419 Self::new(EditorMode::full(), buffer, None, window, cx)
1420 }
1421
1422 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1423 let buffer = cx.new(|cx| Buffer::local("", cx));
1424 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1425 Self::new(
1426 EditorMode::SingleLine { auto_width: true },
1427 buffer,
1428 None,
1429 window,
1430 cx,
1431 )
1432 }
1433
1434 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1435 let buffer = cx.new(|cx| Buffer::local("", cx));
1436 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1437 Self::new(
1438 EditorMode::AutoHeight { max_lines },
1439 buffer,
1440 None,
1441 window,
1442 cx,
1443 )
1444 }
1445
1446 pub fn for_buffer(
1447 buffer: Entity<Buffer>,
1448 project: Option<Entity<Project>>,
1449 window: &mut Window,
1450 cx: &mut Context<Self>,
1451 ) -> Self {
1452 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1453 Self::new(EditorMode::full(), buffer, project, window, cx)
1454 }
1455
1456 pub fn for_multibuffer(
1457 buffer: Entity<MultiBuffer>,
1458 project: Option<Entity<Project>>,
1459 window: &mut Window,
1460 cx: &mut Context<Self>,
1461 ) -> Self {
1462 Self::new(EditorMode::full(), buffer, project, window, cx)
1463 }
1464
1465 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1466 let mut clone = Self::new(
1467 self.mode.clone(),
1468 self.buffer.clone(),
1469 self.project.clone(),
1470 window,
1471 cx,
1472 );
1473 self.display_map.update(cx, |display_map, cx| {
1474 let snapshot = display_map.snapshot(cx);
1475 clone.display_map.update(cx, |display_map, cx| {
1476 display_map.set_state(&snapshot, cx);
1477 });
1478 });
1479 clone.folds_did_change(cx);
1480 clone.selections.clone_state(&self.selections);
1481 clone.scroll_manager.clone_state(&self.scroll_manager);
1482 clone.searchable = self.searchable;
1483 clone.read_only = self.read_only;
1484 clone
1485 }
1486
1487 pub fn new(
1488 mode: EditorMode,
1489 buffer: Entity<MultiBuffer>,
1490 project: Option<Entity<Project>>,
1491 window: &mut Window,
1492 cx: &mut Context<Self>,
1493 ) -> Self {
1494 Editor::new_internal(mode, buffer, project, None, window, cx)
1495 }
1496
1497 fn new_internal(
1498 mode: EditorMode,
1499 buffer: Entity<MultiBuffer>,
1500 project: Option<Entity<Project>>,
1501 display_map: Option<Entity<DisplayMap>>,
1502 window: &mut Window,
1503 cx: &mut Context<Self>,
1504 ) -> Self {
1505 debug_assert!(
1506 display_map.is_none() || mode.is_minimap(),
1507 "Providing a display map for a new editor is only intended for the minimap and might have unindended side effects otherwise!"
1508 );
1509 let style = window.text_style();
1510 let font_size = style.font_size.to_pixels(window.rem_size());
1511 let editor = cx.entity().downgrade();
1512 let fold_placeholder = FoldPlaceholder {
1513 constrain_width: true,
1514 render: Arc::new(move |fold_id, fold_range, cx| {
1515 let editor = editor.clone();
1516 div()
1517 .id(fold_id)
1518 .bg(cx.theme().colors().ghost_element_background)
1519 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1520 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1521 .rounded_xs()
1522 .size_full()
1523 .cursor_pointer()
1524 .child("⋯")
1525 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1526 .on_click(move |_, _window, cx| {
1527 editor
1528 .update(cx, |editor, cx| {
1529 editor.unfold_ranges(
1530 &[fold_range.start..fold_range.end],
1531 true,
1532 false,
1533 cx,
1534 );
1535 cx.stop_propagation();
1536 })
1537 .ok();
1538 })
1539 .into_any()
1540 }),
1541 merge_adjacent: true,
1542 ..Default::default()
1543 };
1544 let display_map = display_map.unwrap_or_else(|| {
1545 cx.new(|cx| {
1546 DisplayMap::new(
1547 buffer.clone(),
1548 style.font(),
1549 font_size,
1550 None,
1551 FILE_HEADER_HEIGHT,
1552 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1553 fold_placeholder,
1554 cx,
1555 )
1556 })
1557 });
1558
1559 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1560
1561 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1562
1563 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1564 .then(|| language_settings::SoftWrap::None);
1565
1566 let mut project_subscriptions = Vec::new();
1567 if mode.is_full() {
1568 if let Some(project) = project.as_ref() {
1569 project_subscriptions.push(cx.subscribe_in(
1570 project,
1571 window,
1572 |editor, _, event, window, cx| match event {
1573 project::Event::RefreshCodeLens => {
1574 // we always query lens with actions, without storing them, always refreshing them
1575 }
1576 project::Event::RefreshInlayHints => {
1577 editor
1578 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1579 }
1580 project::Event::SnippetEdit(id, snippet_edits) => {
1581 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1582 let focus_handle = editor.focus_handle(cx);
1583 if focus_handle.is_focused(window) {
1584 let snapshot = buffer.read(cx).snapshot();
1585 for (range, snippet) in snippet_edits {
1586 let editor_range =
1587 language::range_from_lsp(*range).to_offset(&snapshot);
1588 editor
1589 .insert_snippet(
1590 &[editor_range],
1591 snippet.clone(),
1592 window,
1593 cx,
1594 )
1595 .ok();
1596 }
1597 }
1598 }
1599 }
1600 _ => {}
1601 },
1602 ));
1603 if let Some(task_inventory) = project
1604 .read(cx)
1605 .task_store()
1606 .read(cx)
1607 .task_inventory()
1608 .cloned()
1609 {
1610 project_subscriptions.push(cx.observe_in(
1611 &task_inventory,
1612 window,
1613 |editor, _, window, cx| {
1614 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1615 },
1616 ));
1617 };
1618
1619 project_subscriptions.push(cx.subscribe_in(
1620 &project.read(cx).breakpoint_store(),
1621 window,
1622 |editor, _, event, window, cx| match event {
1623 BreakpointStoreEvent::ClearDebugLines => {
1624 editor.clear_row_highlights::<ActiveDebugLine>();
1625 editor.refresh_inline_values(cx);
1626 }
1627 BreakpointStoreEvent::SetDebugLine => {
1628 if editor.go_to_active_debug_line(window, cx) {
1629 cx.stop_propagation();
1630 }
1631
1632 editor.refresh_inline_values(cx);
1633 }
1634 _ => {}
1635 },
1636 ));
1637 }
1638 }
1639
1640 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1641
1642 let inlay_hint_settings =
1643 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1644 let focus_handle = cx.focus_handle();
1645 cx.on_focus(&focus_handle, window, Self::handle_focus)
1646 .detach();
1647 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1648 .detach();
1649 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1650 .detach();
1651 cx.on_blur(&focus_handle, window, Self::handle_blur)
1652 .detach();
1653
1654 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1655 Some(false)
1656 } else {
1657 None
1658 };
1659
1660 let breakpoint_store = match (&mode, project.as_ref()) {
1661 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1662 _ => None,
1663 };
1664
1665 let mut code_action_providers = Vec::new();
1666 let mut load_uncommitted_diff = None;
1667 if let Some(project) = project.clone() {
1668 load_uncommitted_diff = Some(
1669 update_uncommitted_diff_for_buffer(
1670 cx.entity(),
1671 &project,
1672 buffer.read(cx).all_buffers(),
1673 buffer.clone(),
1674 cx,
1675 )
1676 .shared(),
1677 );
1678 code_action_providers.push(Rc::new(project) as Rc<_>);
1679 }
1680
1681 let full_mode = mode.is_full();
1682
1683 let mut this = Self {
1684 focus_handle,
1685 show_cursor_when_unfocused: false,
1686 last_focused_descendant: None,
1687 buffer: buffer.clone(),
1688 display_map: display_map.clone(),
1689 selections,
1690 scroll_manager: ScrollManager::new(cx),
1691 columnar_selection_tail: None,
1692 add_selections_state: None,
1693 select_next_state: None,
1694 select_prev_state: None,
1695 selection_history: Default::default(),
1696 autoclose_regions: Default::default(),
1697 snippet_stack: Default::default(),
1698 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1699 ime_transaction: Default::default(),
1700 active_diagnostics: ActiveDiagnostic::None,
1701 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1702 inline_diagnostics_update: Task::ready(()),
1703 inline_diagnostics: Vec::new(),
1704 soft_wrap_mode_override,
1705 hard_wrap: None,
1706 completion_provider: project.clone().map(|project| Box::new(project) as _),
1707 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1708 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1709 project,
1710 blink_manager: blink_manager.clone(),
1711 show_local_selections: true,
1712 show_scrollbars: full_mode,
1713 show_minimap: full_mode,
1714 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1715 show_gutter: mode.is_full(),
1716 show_line_numbers: None,
1717 use_relative_line_numbers: None,
1718 disable_expand_excerpt_buttons: false,
1719 show_git_diff_gutter: None,
1720 show_code_actions: None,
1721 show_runnables: None,
1722 show_breakpoints: None,
1723 show_wrap_guides: None,
1724 show_indent_guides,
1725 placeholder_text: None,
1726 highlight_order: 0,
1727 highlighted_rows: HashMap::default(),
1728 background_highlights: Default::default(),
1729 gutter_highlights: TreeMap::default(),
1730 scrollbar_marker_state: ScrollbarMarkerState::default(),
1731 active_indent_guides_state: ActiveIndentGuidesState::default(),
1732 nav_history: None,
1733 context_menu: RefCell::new(None),
1734 context_menu_options: None,
1735 mouse_context_menu: None,
1736 completion_tasks: Default::default(),
1737 inline_blame_popover: Default::default(),
1738 signature_help_state: SignatureHelpState::default(),
1739 auto_signature_help: None,
1740 find_all_references_task_sources: Vec::new(),
1741 next_completion_id: 0,
1742 next_inlay_id: 0,
1743 code_action_providers,
1744 available_code_actions: Default::default(),
1745 code_actions_task: Default::default(),
1746 quick_selection_highlight_task: Default::default(),
1747 debounced_selection_highlight_task: Default::default(),
1748 document_highlights_task: Default::default(),
1749 linked_editing_range_task: Default::default(),
1750 pending_rename: Default::default(),
1751 searchable: true,
1752 cursor_shape: EditorSettings::get_global(cx)
1753 .cursor_shape
1754 .unwrap_or_default(),
1755 current_line_highlight: None,
1756 autoindent_mode: Some(AutoindentMode::EachLine),
1757 collapse_matches: false,
1758 workspace: None,
1759 input_enabled: true,
1760 use_modal_editing: mode.is_full(),
1761 read_only: mode.is_minimap(),
1762 use_autoclose: true,
1763 use_auto_surround: true,
1764 auto_replace_emoji_shortcode: false,
1765 jsx_tag_auto_close_enabled_in_any_buffer: false,
1766 leader_id: None,
1767 remote_id: None,
1768 hover_state: Default::default(),
1769 pending_mouse_down: None,
1770 hovered_link_state: Default::default(),
1771 edit_prediction_provider: None,
1772 active_inline_completion: None,
1773 stale_inline_completion_in_menu: None,
1774 edit_prediction_preview: EditPredictionPreview::Inactive {
1775 released_too_fast: false,
1776 },
1777 inline_diagnostics_enabled: mode.is_full(),
1778 inline_value_cache: InlineValueCache::new(inlay_hint_settings.show_value_hints),
1779 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1780
1781 gutter_hovered: false,
1782 pixel_position_of_newest_cursor: None,
1783 last_bounds: None,
1784 last_position_map: None,
1785 expect_bounds_change: None,
1786 gutter_dimensions: GutterDimensions::default(),
1787 style: None,
1788 show_cursor_names: false,
1789 hovered_cursors: Default::default(),
1790 next_editor_action_id: EditorActionId::default(),
1791 editor_actions: Rc::default(),
1792 inline_completions_hidden_for_vim_mode: false,
1793 show_inline_completions_override: None,
1794 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1795 edit_prediction_settings: EditPredictionSettings::Disabled,
1796 edit_prediction_indent_conflict: false,
1797 edit_prediction_requires_modifier_in_indent_conflict: true,
1798 custom_context_menu: None,
1799 show_git_blame_gutter: false,
1800 show_git_blame_inline: false,
1801 show_selection_menu: None,
1802 show_git_blame_inline_delay_task: None,
1803 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1804 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1805 serialize_dirty_buffers: !mode.is_minimap()
1806 && ProjectSettings::get_global(cx)
1807 .session
1808 .restore_unsaved_buffers,
1809 blame: None,
1810 blame_subscription: None,
1811 tasks: Default::default(),
1812
1813 breakpoint_store,
1814 gutter_breakpoint_indicator: (None, None),
1815 _subscriptions: vec![
1816 cx.observe(&buffer, Self::on_buffer_changed),
1817 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1818 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1819 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1820 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1821 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1822 cx.observe_window_activation(window, |editor, window, cx| {
1823 let active = window.is_window_active();
1824 editor.blink_manager.update(cx, |blink_manager, cx| {
1825 if active {
1826 blink_manager.enable(cx);
1827 } else {
1828 blink_manager.disable(cx);
1829 }
1830 });
1831 }),
1832 ],
1833 tasks_update_task: None,
1834 linked_edit_ranges: Default::default(),
1835 in_project_search: false,
1836 previous_search_ranges: None,
1837 breadcrumb_header: None,
1838 focused_block: None,
1839 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1840 addons: HashMap::default(),
1841 registered_buffers: HashMap::default(),
1842 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1843 selection_mark_mode: false,
1844 toggle_fold_multiple_buffers: Task::ready(()),
1845 serialize_selections: Task::ready(()),
1846 serialize_folds: Task::ready(()),
1847 text_style_refinement: None,
1848 load_diff_task: load_uncommitted_diff,
1849 temporary_diff_override: false,
1850 mouse_cursor_hidden: false,
1851 minimap: None,
1852 hide_mouse_mode: EditorSettings::get_global(cx)
1853 .hide_mouse
1854 .unwrap_or_default(),
1855 change_list: ChangeList::new(),
1856 mode,
1857 };
1858 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1859 this._subscriptions
1860 .push(cx.observe(breakpoints, |_, _, cx| {
1861 cx.notify();
1862 }));
1863 }
1864 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1865 this._subscriptions.extend(project_subscriptions);
1866
1867 this._subscriptions.push(cx.subscribe_in(
1868 &cx.entity(),
1869 window,
1870 |editor, _, e: &EditorEvent, window, cx| match e {
1871 EditorEvent::ScrollPositionChanged { local, .. } => {
1872 if *local {
1873 let new_anchor = editor.scroll_manager.anchor();
1874 let snapshot = editor.snapshot(window, cx);
1875 editor.update_restoration_data(cx, move |data| {
1876 data.scroll_position = (
1877 new_anchor.top_row(&snapshot.buffer_snapshot),
1878 new_anchor.offset,
1879 );
1880 });
1881 editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
1882 editor.inline_blame_popover.take();
1883 }
1884 }
1885 EditorEvent::Edited { .. } => {
1886 if !vim_enabled(cx) {
1887 let (map, selections) = editor.selections.all_adjusted_display(cx);
1888 let pop_state = editor
1889 .change_list
1890 .last()
1891 .map(|previous| {
1892 previous.len() == selections.len()
1893 && previous.iter().enumerate().all(|(ix, p)| {
1894 p.to_display_point(&map).row()
1895 == selections[ix].head().row()
1896 })
1897 })
1898 .unwrap_or(false);
1899 let new_positions = selections
1900 .into_iter()
1901 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1902 .collect();
1903 editor
1904 .change_list
1905 .push_to_change_list(pop_state, new_positions);
1906 }
1907 }
1908 _ => (),
1909 },
1910 ));
1911
1912 if let Some(dap_store) = this
1913 .project
1914 .as_ref()
1915 .map(|project| project.read(cx).dap_store())
1916 {
1917 let weak_editor = cx.weak_entity();
1918
1919 this._subscriptions
1920 .push(
1921 cx.observe_new::<project::debugger::session::Session>(move |_, _, cx| {
1922 let session_entity = cx.entity();
1923 weak_editor
1924 .update(cx, |editor, cx| {
1925 editor._subscriptions.push(
1926 cx.subscribe(&session_entity, Self::on_debug_session_event),
1927 );
1928 })
1929 .ok();
1930 }),
1931 );
1932
1933 for session in dap_store.read(cx).sessions().cloned().collect::<Vec<_>>() {
1934 this._subscriptions
1935 .push(cx.subscribe(&session, Self::on_debug_session_event));
1936 }
1937 }
1938
1939 this.end_selection(window, cx);
1940 this.scroll_manager.show_scrollbars(window, cx);
1941 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1942
1943 if full_mode {
1944 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1945 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1946
1947 if this.git_blame_inline_enabled {
1948 this.start_git_blame_inline(false, window, cx);
1949 }
1950
1951 this.go_to_active_debug_line(window, cx);
1952
1953 if let Some(buffer) = buffer.read(cx).as_singleton() {
1954 if let Some(project) = this.project.as_ref() {
1955 let handle = project.update(cx, |project, cx| {
1956 project.register_buffer_with_language_servers(&buffer, cx)
1957 });
1958 this.registered_buffers
1959 .insert(buffer.read(cx).remote_id(), handle);
1960 }
1961 }
1962
1963 this.minimap = this.create_minimap(EditorSettings::get_global(cx).minimap, window, cx);
1964 }
1965
1966 this.report_editor_event("Editor Opened", None, cx);
1967 this
1968 }
1969
1970 pub fn deploy_mouse_context_menu(
1971 &mut self,
1972 position: gpui::Point<Pixels>,
1973 context_menu: Entity<ContextMenu>,
1974 window: &mut Window,
1975 cx: &mut Context<Self>,
1976 ) {
1977 self.mouse_context_menu = Some(MouseContextMenu::new(
1978 self,
1979 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1980 context_menu,
1981 window,
1982 cx,
1983 ));
1984 }
1985
1986 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1987 self.mouse_context_menu
1988 .as_ref()
1989 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1990 }
1991
1992 pub fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1993 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1994 }
1995
1996 fn key_context_internal(
1997 &self,
1998 has_active_edit_prediction: bool,
1999 window: &Window,
2000 cx: &App,
2001 ) -> KeyContext {
2002 let mut key_context = KeyContext::new_with_defaults();
2003 key_context.add("Editor");
2004 let mode = match self.mode {
2005 EditorMode::SingleLine { .. } => "single_line",
2006 EditorMode::AutoHeight { .. } => "auto_height",
2007 EditorMode::Minimap { .. } => "minimap",
2008 EditorMode::Full { .. } => "full",
2009 };
2010
2011 if EditorSettings::jupyter_enabled(cx) {
2012 key_context.add("jupyter");
2013 }
2014
2015 key_context.set("mode", mode);
2016 if self.pending_rename.is_some() {
2017 key_context.add("renaming");
2018 }
2019
2020 match self.context_menu.borrow().as_ref() {
2021 Some(CodeContextMenu::Completions(_)) => {
2022 key_context.add("menu");
2023 key_context.add("showing_completions");
2024 }
2025 Some(CodeContextMenu::CodeActions(_)) => {
2026 key_context.add("menu");
2027 key_context.add("showing_code_actions")
2028 }
2029 None => {}
2030 }
2031
2032 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2033 if !self.focus_handle(cx).contains_focused(window, cx)
2034 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
2035 {
2036 for addon in self.addons.values() {
2037 addon.extend_key_context(&mut key_context, cx)
2038 }
2039 }
2040
2041 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
2042 if let Some(extension) = singleton_buffer
2043 .read(cx)
2044 .file()
2045 .and_then(|file| file.path().extension()?.to_str())
2046 {
2047 key_context.set("extension", extension.to_string());
2048 }
2049 } else {
2050 key_context.add("multibuffer");
2051 }
2052
2053 if has_active_edit_prediction {
2054 if self.edit_prediction_in_conflict() {
2055 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
2056 } else {
2057 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
2058 key_context.add("copilot_suggestion");
2059 }
2060 }
2061
2062 if self.selection_mark_mode {
2063 key_context.add("selection_mode");
2064 }
2065
2066 key_context
2067 }
2068
2069 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
2070 self.mouse_cursor_hidden = match origin {
2071 HideMouseCursorOrigin::TypingAction => {
2072 matches!(
2073 self.hide_mouse_mode,
2074 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
2075 )
2076 }
2077 HideMouseCursorOrigin::MovementAction => {
2078 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
2079 }
2080 };
2081 }
2082
2083 pub fn edit_prediction_in_conflict(&self) -> bool {
2084 if !self.show_edit_predictions_in_menu() {
2085 return false;
2086 }
2087
2088 let showing_completions = self
2089 .context_menu
2090 .borrow()
2091 .as_ref()
2092 .map_or(false, |context| {
2093 matches!(context, CodeContextMenu::Completions(_))
2094 });
2095
2096 showing_completions
2097 || self.edit_prediction_requires_modifier()
2098 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
2099 // bindings to insert tab characters.
2100 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
2101 }
2102
2103 pub fn accept_edit_prediction_keybind(
2104 &self,
2105 window: &Window,
2106 cx: &App,
2107 ) -> AcceptEditPredictionBinding {
2108 let key_context = self.key_context_internal(true, window, cx);
2109 let in_conflict = self.edit_prediction_in_conflict();
2110
2111 AcceptEditPredictionBinding(
2112 window
2113 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
2114 .into_iter()
2115 .filter(|binding| {
2116 !in_conflict
2117 || binding
2118 .keystrokes()
2119 .first()
2120 .map_or(false, |keystroke| keystroke.modifiers.modified())
2121 })
2122 .rev()
2123 .min_by_key(|binding| {
2124 binding
2125 .keystrokes()
2126 .first()
2127 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
2128 }),
2129 )
2130 }
2131
2132 pub fn new_file(
2133 workspace: &mut Workspace,
2134 _: &workspace::NewFile,
2135 window: &mut Window,
2136 cx: &mut Context<Workspace>,
2137 ) {
2138 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
2139 "Failed to create buffer",
2140 window,
2141 cx,
2142 |e, _, _| match e.error_code() {
2143 ErrorCode::RemoteUpgradeRequired => Some(format!(
2144 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2145 e.error_tag("required").unwrap_or("the latest version")
2146 )),
2147 _ => None,
2148 },
2149 );
2150 }
2151
2152 pub fn new_in_workspace(
2153 workspace: &mut Workspace,
2154 window: &mut Window,
2155 cx: &mut Context<Workspace>,
2156 ) -> Task<Result<Entity<Editor>>> {
2157 let project = workspace.project().clone();
2158 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2159
2160 cx.spawn_in(window, async move |workspace, cx| {
2161 let buffer = create.await?;
2162 workspace.update_in(cx, |workspace, window, cx| {
2163 let editor =
2164 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
2165 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2166 editor
2167 })
2168 })
2169 }
2170
2171 fn new_file_vertical(
2172 workspace: &mut Workspace,
2173 _: &workspace::NewFileSplitVertical,
2174 window: &mut Window,
2175 cx: &mut Context<Workspace>,
2176 ) {
2177 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
2178 }
2179
2180 fn new_file_horizontal(
2181 workspace: &mut Workspace,
2182 _: &workspace::NewFileSplitHorizontal,
2183 window: &mut Window,
2184 cx: &mut Context<Workspace>,
2185 ) {
2186 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2187 }
2188
2189 fn new_file_in_direction(
2190 workspace: &mut Workspace,
2191 direction: SplitDirection,
2192 window: &mut Window,
2193 cx: &mut Context<Workspace>,
2194 ) {
2195 let project = workspace.project().clone();
2196 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2197
2198 cx.spawn_in(window, async move |workspace, cx| {
2199 let buffer = create.await?;
2200 workspace.update_in(cx, move |workspace, window, cx| {
2201 workspace.split_item(
2202 direction,
2203 Box::new(
2204 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2205 ),
2206 window,
2207 cx,
2208 )
2209 })?;
2210 anyhow::Ok(())
2211 })
2212 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2213 match e.error_code() {
2214 ErrorCode::RemoteUpgradeRequired => Some(format!(
2215 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2216 e.error_tag("required").unwrap_or("the latest version")
2217 )),
2218 _ => None,
2219 }
2220 });
2221 }
2222
2223 pub fn leader_id(&self) -> Option<CollaboratorId> {
2224 self.leader_id
2225 }
2226
2227 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2228 &self.buffer
2229 }
2230
2231 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2232 self.workspace.as_ref()?.0.upgrade()
2233 }
2234
2235 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2236 self.buffer().read(cx).title(cx)
2237 }
2238
2239 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2240 let git_blame_gutter_max_author_length = self
2241 .render_git_blame_gutter(cx)
2242 .then(|| {
2243 if let Some(blame) = self.blame.as_ref() {
2244 let max_author_length =
2245 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2246 Some(max_author_length)
2247 } else {
2248 None
2249 }
2250 })
2251 .flatten();
2252
2253 EditorSnapshot {
2254 mode: self.mode.clone(),
2255 show_gutter: self.show_gutter,
2256 show_line_numbers: self.show_line_numbers,
2257 show_git_diff_gutter: self.show_git_diff_gutter,
2258 show_runnables: self.show_runnables,
2259 show_breakpoints: self.show_breakpoints,
2260 git_blame_gutter_max_author_length,
2261 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2262 scroll_anchor: self.scroll_manager.anchor(),
2263 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2264 placeholder_text: self.placeholder_text.clone(),
2265 is_focused: self.focus_handle.is_focused(window),
2266 current_line_highlight: self
2267 .current_line_highlight
2268 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2269 gutter_hovered: self.gutter_hovered,
2270 }
2271 }
2272
2273 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2274 self.buffer.read(cx).language_at(point, cx)
2275 }
2276
2277 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2278 self.buffer.read(cx).read(cx).file_at(point).cloned()
2279 }
2280
2281 pub fn active_excerpt(
2282 &self,
2283 cx: &App,
2284 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2285 self.buffer
2286 .read(cx)
2287 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2288 }
2289
2290 pub fn mode(&self) -> &EditorMode {
2291 &self.mode
2292 }
2293
2294 pub fn set_mode(&mut self, mode: EditorMode) {
2295 self.mode = mode;
2296 }
2297
2298 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2299 self.collaboration_hub.as_deref()
2300 }
2301
2302 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2303 self.collaboration_hub = Some(hub);
2304 }
2305
2306 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2307 self.in_project_search = in_project_search;
2308 }
2309
2310 pub fn set_custom_context_menu(
2311 &mut self,
2312 f: impl 'static
2313 + Fn(
2314 &mut Self,
2315 DisplayPoint,
2316 &mut Window,
2317 &mut Context<Self>,
2318 ) -> Option<Entity<ui::ContextMenu>>,
2319 ) {
2320 self.custom_context_menu = Some(Box::new(f))
2321 }
2322
2323 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2324 self.completion_provider = provider;
2325 }
2326
2327 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2328 self.semantics_provider.clone()
2329 }
2330
2331 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2332 self.semantics_provider = provider;
2333 }
2334
2335 pub fn set_edit_prediction_provider<T>(
2336 &mut self,
2337 provider: Option<Entity<T>>,
2338 window: &mut Window,
2339 cx: &mut Context<Self>,
2340 ) where
2341 T: EditPredictionProvider,
2342 {
2343 self.edit_prediction_provider =
2344 provider.map(|provider| RegisteredInlineCompletionProvider {
2345 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2346 if this.focus_handle.is_focused(window) {
2347 this.update_visible_inline_completion(window, cx);
2348 }
2349 }),
2350 provider: Arc::new(provider),
2351 });
2352 self.update_edit_prediction_settings(cx);
2353 self.refresh_inline_completion(false, false, window, cx);
2354 }
2355
2356 pub fn placeholder_text(&self) -> Option<&str> {
2357 self.placeholder_text.as_deref()
2358 }
2359
2360 pub fn set_placeholder_text(
2361 &mut self,
2362 placeholder_text: impl Into<Arc<str>>,
2363 cx: &mut Context<Self>,
2364 ) {
2365 let placeholder_text = Some(placeholder_text.into());
2366 if self.placeholder_text != placeholder_text {
2367 self.placeholder_text = placeholder_text;
2368 cx.notify();
2369 }
2370 }
2371
2372 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2373 self.cursor_shape = cursor_shape;
2374
2375 // Disrupt blink for immediate user feedback that the cursor shape has changed
2376 self.blink_manager.update(cx, BlinkManager::show_cursor);
2377
2378 cx.notify();
2379 }
2380
2381 pub fn set_current_line_highlight(
2382 &mut self,
2383 current_line_highlight: Option<CurrentLineHighlight>,
2384 ) {
2385 self.current_line_highlight = current_line_highlight;
2386 }
2387
2388 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2389 self.collapse_matches = collapse_matches;
2390 }
2391
2392 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2393 let buffers = self.buffer.read(cx).all_buffers();
2394 let Some(project) = self.project.as_ref() else {
2395 return;
2396 };
2397 project.update(cx, |project, cx| {
2398 for buffer in buffers {
2399 self.registered_buffers
2400 .entry(buffer.read(cx).remote_id())
2401 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2402 }
2403 })
2404 }
2405
2406 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2407 if self.collapse_matches {
2408 return range.start..range.start;
2409 }
2410 range.clone()
2411 }
2412
2413 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2414 if self.display_map.read(cx).clip_at_line_ends != clip {
2415 self.display_map
2416 .update(cx, |map, _| map.clip_at_line_ends = clip);
2417 }
2418 }
2419
2420 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2421 self.input_enabled = input_enabled;
2422 }
2423
2424 pub fn set_inline_completions_hidden_for_vim_mode(
2425 &mut self,
2426 hidden: bool,
2427 window: &mut Window,
2428 cx: &mut Context<Self>,
2429 ) {
2430 if hidden != self.inline_completions_hidden_for_vim_mode {
2431 self.inline_completions_hidden_for_vim_mode = hidden;
2432 if hidden {
2433 self.update_visible_inline_completion(window, cx);
2434 } else {
2435 self.refresh_inline_completion(true, false, window, cx);
2436 }
2437 }
2438 }
2439
2440 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2441 self.menu_inline_completions_policy = value;
2442 }
2443
2444 pub fn set_autoindent(&mut self, autoindent: bool) {
2445 if autoindent {
2446 self.autoindent_mode = Some(AutoindentMode::EachLine);
2447 } else {
2448 self.autoindent_mode = None;
2449 }
2450 }
2451
2452 pub fn read_only(&self, cx: &App) -> bool {
2453 self.read_only || self.buffer.read(cx).read_only()
2454 }
2455
2456 pub fn set_read_only(&mut self, read_only: bool) {
2457 self.read_only = read_only;
2458 }
2459
2460 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2461 self.use_autoclose = autoclose;
2462 }
2463
2464 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2465 self.use_auto_surround = auto_surround;
2466 }
2467
2468 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2469 self.auto_replace_emoji_shortcode = auto_replace;
2470 }
2471
2472 pub fn toggle_edit_predictions(
2473 &mut self,
2474 _: &ToggleEditPrediction,
2475 window: &mut Window,
2476 cx: &mut Context<Self>,
2477 ) {
2478 if self.show_inline_completions_override.is_some() {
2479 self.set_show_edit_predictions(None, window, cx);
2480 } else {
2481 let show_edit_predictions = !self.edit_predictions_enabled();
2482 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2483 }
2484 }
2485
2486 pub fn set_show_edit_predictions(
2487 &mut self,
2488 show_edit_predictions: Option<bool>,
2489 window: &mut Window,
2490 cx: &mut Context<Self>,
2491 ) {
2492 self.show_inline_completions_override = show_edit_predictions;
2493 self.update_edit_prediction_settings(cx);
2494
2495 if let Some(false) = show_edit_predictions {
2496 self.discard_inline_completion(false, cx);
2497 } else {
2498 self.refresh_inline_completion(false, true, window, cx);
2499 }
2500 }
2501
2502 fn inline_completions_disabled_in_scope(
2503 &self,
2504 buffer: &Entity<Buffer>,
2505 buffer_position: language::Anchor,
2506 cx: &App,
2507 ) -> bool {
2508 let snapshot = buffer.read(cx).snapshot();
2509 let settings = snapshot.settings_at(buffer_position, cx);
2510
2511 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2512 return false;
2513 };
2514
2515 scope.override_name().map_or(false, |scope_name| {
2516 settings
2517 .edit_predictions_disabled_in
2518 .iter()
2519 .any(|s| s == scope_name)
2520 })
2521 }
2522
2523 pub fn set_use_modal_editing(&mut self, to: bool) {
2524 self.use_modal_editing = to;
2525 }
2526
2527 pub fn use_modal_editing(&self) -> bool {
2528 self.use_modal_editing
2529 }
2530
2531 fn selections_did_change(
2532 &mut self,
2533 local: bool,
2534 old_cursor_position: &Anchor,
2535 show_completions: bool,
2536 window: &mut Window,
2537 cx: &mut Context<Self>,
2538 ) {
2539 window.invalidate_character_coordinates();
2540
2541 // Copy selections to primary selection buffer
2542 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2543 if local {
2544 let selections = self.selections.all::<usize>(cx);
2545 let buffer_handle = self.buffer.read(cx).read(cx);
2546
2547 let mut text = String::new();
2548 for (index, selection) in selections.iter().enumerate() {
2549 let text_for_selection = buffer_handle
2550 .text_for_range(selection.start..selection.end)
2551 .collect::<String>();
2552
2553 text.push_str(&text_for_selection);
2554 if index != selections.len() - 1 {
2555 text.push('\n');
2556 }
2557 }
2558
2559 if !text.is_empty() {
2560 cx.write_to_primary(ClipboardItem::new_string(text));
2561 }
2562 }
2563
2564 if self.focus_handle.is_focused(window) && self.leader_id.is_none() {
2565 self.buffer.update(cx, |buffer, cx| {
2566 buffer.set_active_selections(
2567 &self.selections.disjoint_anchors(),
2568 self.selections.line_mode,
2569 self.cursor_shape,
2570 cx,
2571 )
2572 });
2573 }
2574 let display_map = self
2575 .display_map
2576 .update(cx, |display_map, cx| display_map.snapshot(cx));
2577 let buffer = &display_map.buffer_snapshot;
2578 self.add_selections_state = None;
2579 self.select_next_state = None;
2580 self.select_prev_state = None;
2581 self.select_syntax_node_history.try_clear();
2582 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2583 self.snippet_stack
2584 .invalidate(&self.selections.disjoint_anchors(), buffer);
2585 self.take_rename(false, window, cx);
2586
2587 let new_cursor_position = self.selections.newest_anchor().head();
2588
2589 self.push_to_nav_history(
2590 *old_cursor_position,
2591 Some(new_cursor_position.to_point(buffer)),
2592 false,
2593 cx,
2594 );
2595
2596 if local {
2597 let new_cursor_position = self.selections.newest_anchor().head();
2598 let mut context_menu = self.context_menu.borrow_mut();
2599 let completion_menu = match context_menu.as_ref() {
2600 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2601 _ => {
2602 *context_menu = None;
2603 None
2604 }
2605 };
2606 if let Some(buffer_id) = new_cursor_position.buffer_id {
2607 if !self.registered_buffers.contains_key(&buffer_id) {
2608 if let Some(project) = self.project.as_ref() {
2609 project.update(cx, |project, cx| {
2610 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2611 return;
2612 };
2613 self.registered_buffers.insert(
2614 buffer_id,
2615 project.register_buffer_with_language_servers(&buffer, cx),
2616 );
2617 })
2618 }
2619 }
2620 }
2621
2622 if let Some(completion_menu) = completion_menu {
2623 let cursor_position = new_cursor_position.to_offset(buffer);
2624 let (word_range, kind) =
2625 buffer.surrounding_word(completion_menu.initial_position, true);
2626 if kind == Some(CharKind::Word)
2627 && word_range.to_inclusive().contains(&cursor_position)
2628 {
2629 let mut completion_menu = completion_menu.clone();
2630 drop(context_menu);
2631
2632 let query = Self::completion_query(buffer, cursor_position);
2633 cx.spawn(async move |this, cx| {
2634 completion_menu
2635 .filter(query.as_deref(), cx.background_executor().clone())
2636 .await;
2637
2638 this.update(cx, |this, cx| {
2639 let mut context_menu = this.context_menu.borrow_mut();
2640 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2641 else {
2642 return;
2643 };
2644
2645 if menu.id > completion_menu.id {
2646 return;
2647 }
2648
2649 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2650 drop(context_menu);
2651 cx.notify();
2652 })
2653 })
2654 .detach();
2655
2656 if show_completions {
2657 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2658 }
2659 } else {
2660 drop(context_menu);
2661 self.hide_context_menu(window, cx);
2662 }
2663 } else {
2664 drop(context_menu);
2665 }
2666
2667 hide_hover(self, cx);
2668
2669 if old_cursor_position.to_display_point(&display_map).row()
2670 != new_cursor_position.to_display_point(&display_map).row()
2671 {
2672 self.available_code_actions.take();
2673 }
2674 self.refresh_code_actions(window, cx);
2675 self.refresh_document_highlights(cx);
2676 self.refresh_selected_text_highlights(false, window, cx);
2677 refresh_matching_bracket_highlights(self, window, cx);
2678 self.update_visible_inline_completion(window, cx);
2679 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2680 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2681 self.inline_blame_popover.take();
2682 if self.git_blame_inline_enabled {
2683 self.start_inline_blame_timer(window, cx);
2684 }
2685 }
2686
2687 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2688 cx.emit(EditorEvent::SelectionsChanged { local });
2689
2690 let selections = &self.selections.disjoint;
2691 if selections.len() == 1 {
2692 cx.emit(SearchEvent::ActiveMatchChanged)
2693 }
2694 if local {
2695 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2696 let inmemory_selections = selections
2697 .iter()
2698 .map(|s| {
2699 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2700 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2701 })
2702 .collect();
2703 self.update_restoration_data(cx, |data| {
2704 data.selections = inmemory_selections;
2705 });
2706
2707 if WorkspaceSettings::get(None, cx).restore_on_startup
2708 != RestoreOnStartupBehavior::None
2709 {
2710 if let Some(workspace_id) =
2711 self.workspace.as_ref().and_then(|workspace| workspace.1)
2712 {
2713 let snapshot = self.buffer().read(cx).snapshot(cx);
2714 let selections = selections.clone();
2715 let background_executor = cx.background_executor().clone();
2716 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2717 self.serialize_selections = cx.background_spawn(async move {
2718 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2719 let db_selections = selections
2720 .iter()
2721 .map(|selection| {
2722 (
2723 selection.start.to_offset(&snapshot),
2724 selection.end.to_offset(&snapshot),
2725 )
2726 })
2727 .collect();
2728
2729 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2730 .await
2731 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2732 .log_err();
2733 });
2734 }
2735 }
2736 }
2737 }
2738
2739 cx.notify();
2740 }
2741
2742 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2743 use text::ToOffset as _;
2744 use text::ToPoint as _;
2745
2746 if self.mode.is_minimap()
2747 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
2748 {
2749 return;
2750 }
2751
2752 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2753 return;
2754 };
2755
2756 let snapshot = singleton.read(cx).snapshot();
2757 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2758 let display_snapshot = display_map.snapshot(cx);
2759
2760 display_snapshot
2761 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2762 .map(|fold| {
2763 fold.range.start.text_anchor.to_point(&snapshot)
2764 ..fold.range.end.text_anchor.to_point(&snapshot)
2765 })
2766 .collect()
2767 });
2768 self.update_restoration_data(cx, |data| {
2769 data.folds = inmemory_folds;
2770 });
2771
2772 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2773 return;
2774 };
2775 let background_executor = cx.background_executor().clone();
2776 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2777 let db_folds = self.display_map.update(cx, |display_map, cx| {
2778 display_map
2779 .snapshot(cx)
2780 .folds_in_range(0..snapshot.len())
2781 .map(|fold| {
2782 (
2783 fold.range.start.text_anchor.to_offset(&snapshot),
2784 fold.range.end.text_anchor.to_offset(&snapshot),
2785 )
2786 })
2787 .collect()
2788 });
2789 self.serialize_folds = cx.background_spawn(async move {
2790 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2791 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2792 .await
2793 .with_context(|| {
2794 format!(
2795 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2796 )
2797 })
2798 .log_err();
2799 });
2800 }
2801
2802 pub fn sync_selections(
2803 &mut self,
2804 other: Entity<Editor>,
2805 cx: &mut Context<Self>,
2806 ) -> gpui::Subscription {
2807 let other_selections = other.read(cx).selections.disjoint.to_vec();
2808 self.selections.change_with(cx, |selections| {
2809 selections.select_anchors(other_selections);
2810 });
2811
2812 let other_subscription =
2813 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2814 EditorEvent::SelectionsChanged { local: true } => {
2815 let other_selections = other.read(cx).selections.disjoint.to_vec();
2816 if other_selections.is_empty() {
2817 return;
2818 }
2819 this.selections.change_with(cx, |selections| {
2820 selections.select_anchors(other_selections);
2821 });
2822 }
2823 _ => {}
2824 });
2825
2826 let this_subscription =
2827 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2828 EditorEvent::SelectionsChanged { local: true } => {
2829 let these_selections = this.selections.disjoint.to_vec();
2830 if these_selections.is_empty() {
2831 return;
2832 }
2833 other.update(cx, |other_editor, cx| {
2834 other_editor.selections.change_with(cx, |selections| {
2835 selections.select_anchors(these_selections);
2836 })
2837 });
2838 }
2839 _ => {}
2840 });
2841
2842 Subscription::join(other_subscription, this_subscription)
2843 }
2844
2845 pub fn change_selections<R>(
2846 &mut self,
2847 autoscroll: Option<Autoscroll>,
2848 window: &mut Window,
2849 cx: &mut Context<Self>,
2850 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2851 ) -> R {
2852 self.change_selections_inner(autoscroll, true, window, cx, change)
2853 }
2854
2855 fn change_selections_inner<R>(
2856 &mut self,
2857 autoscroll: Option<Autoscroll>,
2858 request_completions: bool,
2859 window: &mut Window,
2860 cx: &mut Context<Self>,
2861 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2862 ) -> R {
2863 let old_cursor_position = self.selections.newest_anchor().head();
2864 self.push_to_selection_history();
2865
2866 let (changed, result) = self.selections.change_with(cx, change);
2867
2868 if changed {
2869 if let Some(autoscroll) = autoscroll {
2870 self.request_autoscroll(autoscroll, cx);
2871 }
2872 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2873
2874 if self.should_open_signature_help_automatically(
2875 &old_cursor_position,
2876 self.signature_help_state.backspace_pressed(),
2877 cx,
2878 ) {
2879 self.show_signature_help(&ShowSignatureHelp, window, cx);
2880 }
2881 self.signature_help_state.set_backspace_pressed(false);
2882 }
2883
2884 result
2885 }
2886
2887 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2888 where
2889 I: IntoIterator<Item = (Range<S>, T)>,
2890 S: ToOffset,
2891 T: Into<Arc<str>>,
2892 {
2893 if self.read_only(cx) {
2894 return;
2895 }
2896
2897 self.buffer
2898 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2899 }
2900
2901 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2902 where
2903 I: IntoIterator<Item = (Range<S>, T)>,
2904 S: ToOffset,
2905 T: Into<Arc<str>>,
2906 {
2907 if self.read_only(cx) {
2908 return;
2909 }
2910
2911 self.buffer.update(cx, |buffer, cx| {
2912 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2913 });
2914 }
2915
2916 pub fn edit_with_block_indent<I, S, T>(
2917 &mut self,
2918 edits: I,
2919 original_indent_columns: Vec<Option<u32>>,
2920 cx: &mut Context<Self>,
2921 ) where
2922 I: IntoIterator<Item = (Range<S>, T)>,
2923 S: ToOffset,
2924 T: Into<Arc<str>>,
2925 {
2926 if self.read_only(cx) {
2927 return;
2928 }
2929
2930 self.buffer.update(cx, |buffer, cx| {
2931 buffer.edit(
2932 edits,
2933 Some(AutoindentMode::Block {
2934 original_indent_columns,
2935 }),
2936 cx,
2937 )
2938 });
2939 }
2940
2941 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2942 self.hide_context_menu(window, cx);
2943
2944 match phase {
2945 SelectPhase::Begin {
2946 position,
2947 add,
2948 click_count,
2949 } => self.begin_selection(position, add, click_count, window, cx),
2950 SelectPhase::BeginColumnar {
2951 position,
2952 goal_column,
2953 reset,
2954 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2955 SelectPhase::Extend {
2956 position,
2957 click_count,
2958 } => self.extend_selection(position, click_count, window, cx),
2959 SelectPhase::Update {
2960 position,
2961 goal_column,
2962 scroll_delta,
2963 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2964 SelectPhase::End => self.end_selection(window, cx),
2965 }
2966 }
2967
2968 fn extend_selection(
2969 &mut self,
2970 position: DisplayPoint,
2971 click_count: usize,
2972 window: &mut Window,
2973 cx: &mut Context<Self>,
2974 ) {
2975 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2976 let tail = self.selections.newest::<usize>(cx).tail();
2977 self.begin_selection(position, false, click_count, window, cx);
2978
2979 let position = position.to_offset(&display_map, Bias::Left);
2980 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2981
2982 let mut pending_selection = self
2983 .selections
2984 .pending_anchor()
2985 .expect("extend_selection not called with pending selection");
2986 if position >= tail {
2987 pending_selection.start = tail_anchor;
2988 } else {
2989 pending_selection.end = tail_anchor;
2990 pending_selection.reversed = true;
2991 }
2992
2993 let mut pending_mode = self.selections.pending_mode().unwrap();
2994 match &mut pending_mode {
2995 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2996 _ => {}
2997 }
2998
2999 let auto_scroll = EditorSettings::get_global(cx).autoscroll_on_clicks;
3000
3001 self.change_selections(auto_scroll.then(Autoscroll::fit), window, cx, |s| {
3002 s.set_pending(pending_selection, pending_mode)
3003 });
3004 }
3005
3006 fn begin_selection(
3007 &mut self,
3008 position: DisplayPoint,
3009 add: bool,
3010 click_count: usize,
3011 window: &mut Window,
3012 cx: &mut Context<Self>,
3013 ) {
3014 if !self.focus_handle.is_focused(window) {
3015 self.last_focused_descendant = None;
3016 window.focus(&self.focus_handle);
3017 }
3018
3019 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3020 let buffer = &display_map.buffer_snapshot;
3021 let position = display_map.clip_point(position, Bias::Left);
3022
3023 let start;
3024 let end;
3025 let mode;
3026 let mut auto_scroll;
3027 match click_count {
3028 1 => {
3029 start = buffer.anchor_before(position.to_point(&display_map));
3030 end = start;
3031 mode = SelectMode::Character;
3032 auto_scroll = true;
3033 }
3034 2 => {
3035 let range = movement::surrounding_word(&display_map, position);
3036 start = buffer.anchor_before(range.start.to_point(&display_map));
3037 end = buffer.anchor_before(range.end.to_point(&display_map));
3038 mode = SelectMode::Word(start..end);
3039 auto_scroll = true;
3040 }
3041 3 => {
3042 let position = display_map
3043 .clip_point(position, Bias::Left)
3044 .to_point(&display_map);
3045 let line_start = display_map.prev_line_boundary(position).0;
3046 let next_line_start = buffer.clip_point(
3047 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3048 Bias::Left,
3049 );
3050 start = buffer.anchor_before(line_start);
3051 end = buffer.anchor_before(next_line_start);
3052 mode = SelectMode::Line(start..end);
3053 auto_scroll = true;
3054 }
3055 _ => {
3056 start = buffer.anchor_before(0);
3057 end = buffer.anchor_before(buffer.len());
3058 mode = SelectMode::All;
3059 auto_scroll = false;
3060 }
3061 }
3062 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
3063
3064 let point_to_delete: Option<usize> = {
3065 let selected_points: Vec<Selection<Point>> =
3066 self.selections.disjoint_in_range(start..end, cx);
3067
3068 if !add || click_count > 1 {
3069 None
3070 } else if !selected_points.is_empty() {
3071 Some(selected_points[0].id)
3072 } else {
3073 let clicked_point_already_selected =
3074 self.selections.disjoint.iter().find(|selection| {
3075 selection.start.to_point(buffer) == start.to_point(buffer)
3076 || selection.end.to_point(buffer) == end.to_point(buffer)
3077 });
3078
3079 clicked_point_already_selected.map(|selection| selection.id)
3080 }
3081 };
3082
3083 let selections_count = self.selections.count();
3084
3085 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
3086 if let Some(point_to_delete) = point_to_delete {
3087 s.delete(point_to_delete);
3088
3089 if selections_count == 1 {
3090 s.set_pending_anchor_range(start..end, mode);
3091 }
3092 } else {
3093 if !add {
3094 s.clear_disjoint();
3095 }
3096
3097 s.set_pending_anchor_range(start..end, mode);
3098 }
3099 });
3100 }
3101
3102 fn begin_columnar_selection(
3103 &mut self,
3104 position: DisplayPoint,
3105 goal_column: u32,
3106 reset: bool,
3107 window: &mut Window,
3108 cx: &mut Context<Self>,
3109 ) {
3110 if !self.focus_handle.is_focused(window) {
3111 self.last_focused_descendant = None;
3112 window.focus(&self.focus_handle);
3113 }
3114
3115 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3116
3117 if reset {
3118 let pointer_position = display_map
3119 .buffer_snapshot
3120 .anchor_before(position.to_point(&display_map));
3121
3122 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
3123 s.clear_disjoint();
3124 s.set_pending_anchor_range(
3125 pointer_position..pointer_position,
3126 SelectMode::Character,
3127 );
3128 });
3129 }
3130
3131 let tail = self.selections.newest::<Point>(cx).tail();
3132 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3133
3134 if !reset {
3135 self.select_columns(
3136 tail.to_display_point(&display_map),
3137 position,
3138 goal_column,
3139 &display_map,
3140 window,
3141 cx,
3142 );
3143 }
3144 }
3145
3146 fn update_selection(
3147 &mut self,
3148 position: DisplayPoint,
3149 goal_column: u32,
3150 scroll_delta: gpui::Point<f32>,
3151 window: &mut Window,
3152 cx: &mut Context<Self>,
3153 ) {
3154 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3155
3156 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3157 let tail = tail.to_display_point(&display_map);
3158 self.select_columns(tail, position, goal_column, &display_map, window, cx);
3159 } else if let Some(mut pending) = self.selections.pending_anchor() {
3160 let buffer = self.buffer.read(cx).snapshot(cx);
3161 let head;
3162 let tail;
3163 let mode = self.selections.pending_mode().unwrap();
3164 match &mode {
3165 SelectMode::Character => {
3166 head = position.to_point(&display_map);
3167 tail = pending.tail().to_point(&buffer);
3168 }
3169 SelectMode::Word(original_range) => {
3170 let original_display_range = original_range.start.to_display_point(&display_map)
3171 ..original_range.end.to_display_point(&display_map);
3172 let original_buffer_range = original_display_range.start.to_point(&display_map)
3173 ..original_display_range.end.to_point(&display_map);
3174 if movement::is_inside_word(&display_map, position)
3175 || original_display_range.contains(&position)
3176 {
3177 let word_range = movement::surrounding_word(&display_map, position);
3178 if word_range.start < original_display_range.start {
3179 head = word_range.start.to_point(&display_map);
3180 } else {
3181 head = word_range.end.to_point(&display_map);
3182 }
3183 } else {
3184 head = position.to_point(&display_map);
3185 }
3186
3187 if head <= original_buffer_range.start {
3188 tail = original_buffer_range.end;
3189 } else {
3190 tail = original_buffer_range.start;
3191 }
3192 }
3193 SelectMode::Line(original_range) => {
3194 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3195
3196 let position = display_map
3197 .clip_point(position, Bias::Left)
3198 .to_point(&display_map);
3199 let line_start = display_map.prev_line_boundary(position).0;
3200 let next_line_start = buffer.clip_point(
3201 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3202 Bias::Left,
3203 );
3204
3205 if line_start < original_range.start {
3206 head = line_start
3207 } else {
3208 head = next_line_start
3209 }
3210
3211 if head <= original_range.start {
3212 tail = original_range.end;
3213 } else {
3214 tail = original_range.start;
3215 }
3216 }
3217 SelectMode::All => {
3218 return;
3219 }
3220 };
3221
3222 if head < tail {
3223 pending.start = buffer.anchor_before(head);
3224 pending.end = buffer.anchor_before(tail);
3225 pending.reversed = true;
3226 } else {
3227 pending.start = buffer.anchor_before(tail);
3228 pending.end = buffer.anchor_before(head);
3229 pending.reversed = false;
3230 }
3231
3232 self.change_selections(None, window, cx, |s| {
3233 s.set_pending(pending, mode);
3234 });
3235 } else {
3236 log::error!("update_selection dispatched with no pending selection");
3237 return;
3238 }
3239
3240 self.apply_scroll_delta(scroll_delta, window, cx);
3241 cx.notify();
3242 }
3243
3244 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3245 self.columnar_selection_tail.take();
3246 if self.selections.pending_anchor().is_some() {
3247 let selections = self.selections.all::<usize>(cx);
3248 self.change_selections(None, window, cx, |s| {
3249 s.select(selections);
3250 s.clear_pending();
3251 });
3252 }
3253 }
3254
3255 fn select_columns(
3256 &mut self,
3257 tail: DisplayPoint,
3258 head: DisplayPoint,
3259 goal_column: u32,
3260 display_map: &DisplaySnapshot,
3261 window: &mut Window,
3262 cx: &mut Context<Self>,
3263 ) {
3264 let start_row = cmp::min(tail.row(), head.row());
3265 let end_row = cmp::max(tail.row(), head.row());
3266 let start_column = cmp::min(tail.column(), goal_column);
3267 let end_column = cmp::max(tail.column(), goal_column);
3268 let reversed = start_column < tail.column();
3269
3270 let selection_ranges = (start_row.0..=end_row.0)
3271 .map(DisplayRow)
3272 .filter_map(|row| {
3273 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3274 let start = display_map
3275 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3276 .to_point(display_map);
3277 let end = display_map
3278 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3279 .to_point(display_map);
3280 if reversed {
3281 Some(end..start)
3282 } else {
3283 Some(start..end)
3284 }
3285 } else {
3286 None
3287 }
3288 })
3289 .collect::<Vec<_>>();
3290
3291 self.change_selections(None, window, cx, |s| {
3292 s.select_ranges(selection_ranges);
3293 });
3294 cx.notify();
3295 }
3296
3297 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3298 self.selections
3299 .all_adjusted(cx)
3300 .iter()
3301 .any(|selection| !selection.is_empty())
3302 }
3303
3304 pub fn has_pending_nonempty_selection(&self) -> bool {
3305 let pending_nonempty_selection = match self.selections.pending_anchor() {
3306 Some(Selection { start, end, .. }) => start != end,
3307 None => false,
3308 };
3309
3310 pending_nonempty_selection
3311 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3312 }
3313
3314 pub fn has_pending_selection(&self) -> bool {
3315 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3316 }
3317
3318 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3319 self.selection_mark_mode = false;
3320
3321 if self.clear_expanded_diff_hunks(cx) {
3322 cx.notify();
3323 return;
3324 }
3325 if self.dismiss_menus_and_popups(true, window, cx) {
3326 return;
3327 }
3328
3329 if self.mode.is_full()
3330 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3331 {
3332 return;
3333 }
3334
3335 cx.propagate();
3336 }
3337
3338 pub fn dismiss_menus_and_popups(
3339 &mut self,
3340 is_user_requested: bool,
3341 window: &mut Window,
3342 cx: &mut Context<Self>,
3343 ) -> bool {
3344 if self.take_rename(false, window, cx).is_some() {
3345 return true;
3346 }
3347
3348 if hide_hover(self, cx) {
3349 return true;
3350 }
3351
3352 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3353 return true;
3354 }
3355
3356 if self.hide_context_menu(window, cx).is_some() {
3357 return true;
3358 }
3359
3360 if self.mouse_context_menu.take().is_some() {
3361 return true;
3362 }
3363
3364 if is_user_requested && self.discard_inline_completion(true, cx) {
3365 return true;
3366 }
3367
3368 if self.snippet_stack.pop().is_some() {
3369 return true;
3370 }
3371
3372 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3373 self.dismiss_diagnostics(cx);
3374 return true;
3375 }
3376
3377 false
3378 }
3379
3380 fn linked_editing_ranges_for(
3381 &self,
3382 selection: Range<text::Anchor>,
3383 cx: &App,
3384 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3385 if self.linked_edit_ranges.is_empty() {
3386 return None;
3387 }
3388 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3389 selection.end.buffer_id.and_then(|end_buffer_id| {
3390 if selection.start.buffer_id != Some(end_buffer_id) {
3391 return None;
3392 }
3393 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3394 let snapshot = buffer.read(cx).snapshot();
3395 self.linked_edit_ranges
3396 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3397 .map(|ranges| (ranges, snapshot, buffer))
3398 })?;
3399 use text::ToOffset as TO;
3400 // find offset from the start of current range to current cursor position
3401 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3402
3403 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3404 let start_difference = start_offset - start_byte_offset;
3405 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3406 let end_difference = end_offset - start_byte_offset;
3407 // Current range has associated linked ranges.
3408 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3409 for range in linked_ranges.iter() {
3410 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3411 let end_offset = start_offset + end_difference;
3412 let start_offset = start_offset + start_difference;
3413 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3414 continue;
3415 }
3416 if self.selections.disjoint_anchor_ranges().any(|s| {
3417 if s.start.buffer_id != selection.start.buffer_id
3418 || s.end.buffer_id != selection.end.buffer_id
3419 {
3420 return false;
3421 }
3422 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3423 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3424 }) {
3425 continue;
3426 }
3427 let start = buffer_snapshot.anchor_after(start_offset);
3428 let end = buffer_snapshot.anchor_after(end_offset);
3429 linked_edits
3430 .entry(buffer.clone())
3431 .or_default()
3432 .push(start..end);
3433 }
3434 Some(linked_edits)
3435 }
3436
3437 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3438 let text: Arc<str> = text.into();
3439
3440 if self.read_only(cx) {
3441 return;
3442 }
3443
3444 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3445
3446 let selections = self.selections.all_adjusted(cx);
3447 let mut bracket_inserted = false;
3448 let mut edits = Vec::new();
3449 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3450 let mut new_selections = Vec::with_capacity(selections.len());
3451 let mut new_autoclose_regions = Vec::new();
3452 let snapshot = self.buffer.read(cx).read(cx);
3453 let mut clear_linked_edit_ranges = false;
3454
3455 for (selection, autoclose_region) in
3456 self.selections_with_autoclose_regions(selections, &snapshot)
3457 {
3458 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3459 // Determine if the inserted text matches the opening or closing
3460 // bracket of any of this language's bracket pairs.
3461 let mut bracket_pair = None;
3462 let mut is_bracket_pair_start = false;
3463 let mut is_bracket_pair_end = false;
3464 if !text.is_empty() {
3465 let mut bracket_pair_matching_end = None;
3466 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3467 // and they are removing the character that triggered IME popup.
3468 for (pair, enabled) in scope.brackets() {
3469 if !pair.close && !pair.surround {
3470 continue;
3471 }
3472
3473 if enabled && pair.start.ends_with(text.as_ref()) {
3474 let prefix_len = pair.start.len() - text.len();
3475 let preceding_text_matches_prefix = prefix_len == 0
3476 || (selection.start.column >= (prefix_len as u32)
3477 && snapshot.contains_str_at(
3478 Point::new(
3479 selection.start.row,
3480 selection.start.column - (prefix_len as u32),
3481 ),
3482 &pair.start[..prefix_len],
3483 ));
3484 if preceding_text_matches_prefix {
3485 bracket_pair = Some(pair.clone());
3486 is_bracket_pair_start = true;
3487 break;
3488 }
3489 }
3490 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3491 {
3492 // take first bracket pair matching end, but don't break in case a later bracket
3493 // pair matches start
3494 bracket_pair_matching_end = Some(pair.clone());
3495 }
3496 }
3497 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3498 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3499 is_bracket_pair_end = true;
3500 }
3501 }
3502
3503 if let Some(bracket_pair) = bracket_pair {
3504 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3505 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3506 let auto_surround =
3507 self.use_auto_surround && snapshot_settings.use_auto_surround;
3508 if selection.is_empty() {
3509 if is_bracket_pair_start {
3510 // If the inserted text is a suffix of an opening bracket and the
3511 // selection is preceded by the rest of the opening bracket, then
3512 // insert the closing bracket.
3513 let following_text_allows_autoclose = snapshot
3514 .chars_at(selection.start)
3515 .next()
3516 .map_or(true, |c| scope.should_autoclose_before(c));
3517
3518 let preceding_text_allows_autoclose = selection.start.column == 0
3519 || snapshot.reversed_chars_at(selection.start).next().map_or(
3520 true,
3521 |c| {
3522 bracket_pair.start != bracket_pair.end
3523 || !snapshot
3524 .char_classifier_at(selection.start)
3525 .is_word(c)
3526 },
3527 );
3528
3529 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3530 && bracket_pair.start.len() == 1
3531 {
3532 let target = bracket_pair.start.chars().next().unwrap();
3533 let current_line_count = snapshot
3534 .reversed_chars_at(selection.start)
3535 .take_while(|&c| c != '\n')
3536 .filter(|&c| c == target)
3537 .count();
3538 current_line_count % 2 == 1
3539 } else {
3540 false
3541 };
3542
3543 if autoclose
3544 && bracket_pair.close
3545 && following_text_allows_autoclose
3546 && preceding_text_allows_autoclose
3547 && !is_closing_quote
3548 {
3549 let anchor = snapshot.anchor_before(selection.end);
3550 new_selections.push((selection.map(|_| anchor), text.len()));
3551 new_autoclose_regions.push((
3552 anchor,
3553 text.len(),
3554 selection.id,
3555 bracket_pair.clone(),
3556 ));
3557 edits.push((
3558 selection.range(),
3559 format!("{}{}", text, bracket_pair.end).into(),
3560 ));
3561 bracket_inserted = true;
3562 continue;
3563 }
3564 }
3565
3566 if let Some(region) = autoclose_region {
3567 // If the selection is followed by an auto-inserted closing bracket,
3568 // then don't insert that closing bracket again; just move the selection
3569 // past the closing bracket.
3570 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3571 && text.as_ref() == region.pair.end.as_str();
3572 if should_skip {
3573 let anchor = snapshot.anchor_after(selection.end);
3574 new_selections
3575 .push((selection.map(|_| anchor), region.pair.end.len()));
3576 continue;
3577 }
3578 }
3579
3580 let always_treat_brackets_as_autoclosed = snapshot
3581 .language_settings_at(selection.start, cx)
3582 .always_treat_brackets_as_autoclosed;
3583 if always_treat_brackets_as_autoclosed
3584 && is_bracket_pair_end
3585 && snapshot.contains_str_at(selection.end, text.as_ref())
3586 {
3587 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3588 // and the inserted text is a closing bracket and the selection is followed
3589 // by the closing bracket then move the selection past the closing bracket.
3590 let anchor = snapshot.anchor_after(selection.end);
3591 new_selections.push((selection.map(|_| anchor), text.len()));
3592 continue;
3593 }
3594 }
3595 // If an opening bracket is 1 character long and is typed while
3596 // text is selected, then surround that text with the bracket pair.
3597 else if auto_surround
3598 && bracket_pair.surround
3599 && is_bracket_pair_start
3600 && bracket_pair.start.chars().count() == 1
3601 {
3602 edits.push((selection.start..selection.start, text.clone()));
3603 edits.push((
3604 selection.end..selection.end,
3605 bracket_pair.end.as_str().into(),
3606 ));
3607 bracket_inserted = true;
3608 new_selections.push((
3609 Selection {
3610 id: selection.id,
3611 start: snapshot.anchor_after(selection.start),
3612 end: snapshot.anchor_before(selection.end),
3613 reversed: selection.reversed,
3614 goal: selection.goal,
3615 },
3616 0,
3617 ));
3618 continue;
3619 }
3620 }
3621 }
3622
3623 if self.auto_replace_emoji_shortcode
3624 && selection.is_empty()
3625 && text.as_ref().ends_with(':')
3626 {
3627 if let Some(possible_emoji_short_code) =
3628 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3629 {
3630 if !possible_emoji_short_code.is_empty() {
3631 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3632 let emoji_shortcode_start = Point::new(
3633 selection.start.row,
3634 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3635 );
3636
3637 // Remove shortcode from buffer
3638 edits.push((
3639 emoji_shortcode_start..selection.start,
3640 "".to_string().into(),
3641 ));
3642 new_selections.push((
3643 Selection {
3644 id: selection.id,
3645 start: snapshot.anchor_after(emoji_shortcode_start),
3646 end: snapshot.anchor_before(selection.start),
3647 reversed: selection.reversed,
3648 goal: selection.goal,
3649 },
3650 0,
3651 ));
3652
3653 // Insert emoji
3654 let selection_start_anchor = snapshot.anchor_after(selection.start);
3655 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3656 edits.push((selection.start..selection.end, emoji.to_string().into()));
3657
3658 continue;
3659 }
3660 }
3661 }
3662 }
3663
3664 // If not handling any auto-close operation, then just replace the selected
3665 // text with the given input and move the selection to the end of the
3666 // newly inserted text.
3667 let anchor = snapshot.anchor_after(selection.end);
3668 if !self.linked_edit_ranges.is_empty() {
3669 let start_anchor = snapshot.anchor_before(selection.start);
3670
3671 let is_word_char = text.chars().next().map_or(true, |char| {
3672 let classifier = snapshot
3673 .char_classifier_at(start_anchor.to_offset(&snapshot))
3674 .ignore_punctuation(true);
3675 classifier.is_word(char)
3676 });
3677
3678 if is_word_char {
3679 if let Some(ranges) = self
3680 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3681 {
3682 for (buffer, edits) in ranges {
3683 linked_edits
3684 .entry(buffer.clone())
3685 .or_default()
3686 .extend(edits.into_iter().map(|range| (range, text.clone())));
3687 }
3688 }
3689 } else {
3690 clear_linked_edit_ranges = true;
3691 }
3692 }
3693
3694 new_selections.push((selection.map(|_| anchor), 0));
3695 edits.push((selection.start..selection.end, text.clone()));
3696 }
3697
3698 drop(snapshot);
3699
3700 self.transact(window, cx, |this, window, cx| {
3701 if clear_linked_edit_ranges {
3702 this.linked_edit_ranges.clear();
3703 }
3704 let initial_buffer_versions =
3705 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3706
3707 this.buffer.update(cx, |buffer, cx| {
3708 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3709 });
3710 for (buffer, edits) in linked_edits {
3711 buffer.update(cx, |buffer, cx| {
3712 let snapshot = buffer.snapshot();
3713 let edits = edits
3714 .into_iter()
3715 .map(|(range, text)| {
3716 use text::ToPoint as TP;
3717 let end_point = TP::to_point(&range.end, &snapshot);
3718 let start_point = TP::to_point(&range.start, &snapshot);
3719 (start_point..end_point, text)
3720 })
3721 .sorted_by_key(|(range, _)| range.start);
3722 buffer.edit(edits, None, cx);
3723 })
3724 }
3725 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3726 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3727 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3728 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3729 .zip(new_selection_deltas)
3730 .map(|(selection, delta)| Selection {
3731 id: selection.id,
3732 start: selection.start + delta,
3733 end: selection.end + delta,
3734 reversed: selection.reversed,
3735 goal: SelectionGoal::None,
3736 })
3737 .collect::<Vec<_>>();
3738
3739 let mut i = 0;
3740 for (position, delta, selection_id, pair) in new_autoclose_regions {
3741 let position = position.to_offset(&map.buffer_snapshot) + delta;
3742 let start = map.buffer_snapshot.anchor_before(position);
3743 let end = map.buffer_snapshot.anchor_after(position);
3744 while let Some(existing_state) = this.autoclose_regions.get(i) {
3745 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3746 Ordering::Less => i += 1,
3747 Ordering::Greater => break,
3748 Ordering::Equal => {
3749 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3750 Ordering::Less => i += 1,
3751 Ordering::Equal => break,
3752 Ordering::Greater => break,
3753 }
3754 }
3755 }
3756 }
3757 this.autoclose_regions.insert(
3758 i,
3759 AutocloseRegion {
3760 selection_id,
3761 range: start..end,
3762 pair,
3763 },
3764 );
3765 }
3766
3767 let had_active_inline_completion = this.has_active_inline_completion();
3768 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3769 s.select(new_selections)
3770 });
3771
3772 if !bracket_inserted {
3773 if let Some(on_type_format_task) =
3774 this.trigger_on_type_formatting(text.to_string(), window, cx)
3775 {
3776 on_type_format_task.detach_and_log_err(cx);
3777 }
3778 }
3779
3780 let editor_settings = EditorSettings::get_global(cx);
3781 if bracket_inserted
3782 && (editor_settings.auto_signature_help
3783 || editor_settings.show_signature_help_after_edits)
3784 {
3785 this.show_signature_help(&ShowSignatureHelp, window, cx);
3786 }
3787
3788 let trigger_in_words =
3789 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3790 if this.hard_wrap.is_some() {
3791 let latest: Range<Point> = this.selections.newest(cx).range();
3792 if latest.is_empty()
3793 && this
3794 .buffer()
3795 .read(cx)
3796 .snapshot(cx)
3797 .line_len(MultiBufferRow(latest.start.row))
3798 == latest.start.column
3799 {
3800 this.rewrap_impl(
3801 RewrapOptions {
3802 override_language_settings: true,
3803 preserve_existing_whitespace: true,
3804 },
3805 cx,
3806 )
3807 }
3808 }
3809 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3810 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3811 this.refresh_inline_completion(true, false, window, cx);
3812 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3813 });
3814 }
3815
3816 fn find_possible_emoji_shortcode_at_position(
3817 snapshot: &MultiBufferSnapshot,
3818 position: Point,
3819 ) -> Option<String> {
3820 let mut chars = Vec::new();
3821 let mut found_colon = false;
3822 for char in snapshot.reversed_chars_at(position).take(100) {
3823 // Found a possible emoji shortcode in the middle of the buffer
3824 if found_colon {
3825 if char.is_whitespace() {
3826 chars.reverse();
3827 return Some(chars.iter().collect());
3828 }
3829 // If the previous character is not a whitespace, we are in the middle of a word
3830 // and we only want to complete the shortcode if the word is made up of other emojis
3831 let mut containing_word = String::new();
3832 for ch in snapshot
3833 .reversed_chars_at(position)
3834 .skip(chars.len() + 1)
3835 .take(100)
3836 {
3837 if ch.is_whitespace() {
3838 break;
3839 }
3840 containing_word.push(ch);
3841 }
3842 let containing_word = containing_word.chars().rev().collect::<String>();
3843 if util::word_consists_of_emojis(containing_word.as_str()) {
3844 chars.reverse();
3845 return Some(chars.iter().collect());
3846 }
3847 }
3848
3849 if char.is_whitespace() || !char.is_ascii() {
3850 return None;
3851 }
3852 if char == ':' {
3853 found_colon = true;
3854 } else {
3855 chars.push(char);
3856 }
3857 }
3858 // Found a possible emoji shortcode at the beginning of the buffer
3859 chars.reverse();
3860 Some(chars.iter().collect())
3861 }
3862
3863 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3864 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3865 self.transact(window, cx, |this, window, cx| {
3866 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3867 let selections = this.selections.all::<usize>(cx);
3868 let multi_buffer = this.buffer.read(cx);
3869 let buffer = multi_buffer.snapshot(cx);
3870 selections
3871 .iter()
3872 .map(|selection| {
3873 let start_point = selection.start.to_point(&buffer);
3874 let mut indent =
3875 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3876 indent.len = cmp::min(indent.len, start_point.column);
3877 let start = selection.start;
3878 let end = selection.end;
3879 let selection_is_empty = start == end;
3880 let language_scope = buffer.language_scope_at(start);
3881 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3882 &language_scope
3883 {
3884 let insert_extra_newline =
3885 insert_extra_newline_brackets(&buffer, start..end, language)
3886 || insert_extra_newline_tree_sitter(&buffer, start..end);
3887
3888 // Comment extension on newline is allowed only for cursor selections
3889 let comment_delimiter = maybe!({
3890 if !selection_is_empty {
3891 return None;
3892 }
3893
3894 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3895 return None;
3896 }
3897
3898 let delimiters = language.line_comment_prefixes();
3899 let max_len_of_delimiter =
3900 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3901 let (snapshot, range) =
3902 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3903
3904 let mut index_of_first_non_whitespace = 0;
3905 let comment_candidate = snapshot
3906 .chars_for_range(range)
3907 .skip_while(|c| {
3908 let should_skip = c.is_whitespace();
3909 if should_skip {
3910 index_of_first_non_whitespace += 1;
3911 }
3912 should_skip
3913 })
3914 .take(max_len_of_delimiter)
3915 .collect::<String>();
3916 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3917 comment_candidate.starts_with(comment_prefix.as_ref())
3918 })?;
3919 let cursor_is_placed_after_comment_marker =
3920 index_of_first_non_whitespace + comment_prefix.len()
3921 <= start_point.column as usize;
3922 if cursor_is_placed_after_comment_marker {
3923 Some(comment_prefix.clone())
3924 } else {
3925 None
3926 }
3927 });
3928 (comment_delimiter, insert_extra_newline)
3929 } else {
3930 (None, false)
3931 };
3932
3933 let capacity_for_delimiter = comment_delimiter
3934 .as_deref()
3935 .map(str::len)
3936 .unwrap_or_default();
3937 let mut new_text =
3938 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3939 new_text.push('\n');
3940 new_text.extend(indent.chars());
3941 if let Some(delimiter) = &comment_delimiter {
3942 new_text.push_str(delimiter);
3943 }
3944 if insert_extra_newline {
3945 new_text = new_text.repeat(2);
3946 }
3947
3948 let anchor = buffer.anchor_after(end);
3949 let new_selection = selection.map(|_| anchor);
3950 (
3951 (start..end, new_text),
3952 (insert_extra_newline, new_selection),
3953 )
3954 })
3955 .unzip()
3956 };
3957
3958 this.edit_with_autoindent(edits, cx);
3959 let buffer = this.buffer.read(cx).snapshot(cx);
3960 let new_selections = selection_fixup_info
3961 .into_iter()
3962 .map(|(extra_newline_inserted, new_selection)| {
3963 let mut cursor = new_selection.end.to_point(&buffer);
3964 if extra_newline_inserted {
3965 cursor.row -= 1;
3966 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3967 }
3968 new_selection.map(|_| cursor)
3969 })
3970 .collect();
3971
3972 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3973 s.select(new_selections)
3974 });
3975 this.refresh_inline_completion(true, false, window, cx);
3976 });
3977 }
3978
3979 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3980 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3981
3982 let buffer = self.buffer.read(cx);
3983 let snapshot = buffer.snapshot(cx);
3984
3985 let mut edits = Vec::new();
3986 let mut rows = Vec::new();
3987
3988 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3989 let cursor = selection.head();
3990 let row = cursor.row;
3991
3992 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3993
3994 let newline = "\n".to_string();
3995 edits.push((start_of_line..start_of_line, newline));
3996
3997 rows.push(row + rows_inserted as u32);
3998 }
3999
4000 self.transact(window, cx, |editor, window, cx| {
4001 editor.edit(edits, cx);
4002
4003 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4004 let mut index = 0;
4005 s.move_cursors_with(|map, _, _| {
4006 let row = rows[index];
4007 index += 1;
4008
4009 let point = Point::new(row, 0);
4010 let boundary = map.next_line_boundary(point).1;
4011 let clipped = map.clip_point(boundary, Bias::Left);
4012
4013 (clipped, SelectionGoal::None)
4014 });
4015 });
4016
4017 let mut indent_edits = Vec::new();
4018 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4019 for row in rows {
4020 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4021 for (row, indent) in indents {
4022 if indent.len == 0 {
4023 continue;
4024 }
4025
4026 let text = match indent.kind {
4027 IndentKind::Space => " ".repeat(indent.len as usize),
4028 IndentKind::Tab => "\t".repeat(indent.len as usize),
4029 };
4030 let point = Point::new(row.0, 0);
4031 indent_edits.push((point..point, text));
4032 }
4033 }
4034 editor.edit(indent_edits, cx);
4035 });
4036 }
4037
4038 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
4039 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4040
4041 let buffer = self.buffer.read(cx);
4042 let snapshot = buffer.snapshot(cx);
4043
4044 let mut edits = Vec::new();
4045 let mut rows = Vec::new();
4046 let mut rows_inserted = 0;
4047
4048 for selection in self.selections.all_adjusted(cx) {
4049 let cursor = selection.head();
4050 let row = cursor.row;
4051
4052 let point = Point::new(row + 1, 0);
4053 let start_of_line = snapshot.clip_point(point, Bias::Left);
4054
4055 let newline = "\n".to_string();
4056 edits.push((start_of_line..start_of_line, newline));
4057
4058 rows_inserted += 1;
4059 rows.push(row + rows_inserted);
4060 }
4061
4062 self.transact(window, cx, |editor, window, cx| {
4063 editor.edit(edits, cx);
4064
4065 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4066 let mut index = 0;
4067 s.move_cursors_with(|map, _, _| {
4068 let row = rows[index];
4069 index += 1;
4070
4071 let point = Point::new(row, 0);
4072 let boundary = map.next_line_boundary(point).1;
4073 let clipped = map.clip_point(boundary, Bias::Left);
4074
4075 (clipped, SelectionGoal::None)
4076 });
4077 });
4078
4079 let mut indent_edits = Vec::new();
4080 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
4081 for row in rows {
4082 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
4083 for (row, indent) in indents {
4084 if indent.len == 0 {
4085 continue;
4086 }
4087
4088 let text = match indent.kind {
4089 IndentKind::Space => " ".repeat(indent.len as usize),
4090 IndentKind::Tab => "\t".repeat(indent.len as usize),
4091 };
4092 let point = Point::new(row.0, 0);
4093 indent_edits.push((point..point, text));
4094 }
4095 }
4096 editor.edit(indent_edits, cx);
4097 });
4098 }
4099
4100 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
4101 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4102 original_indent_columns: Vec::new(),
4103 });
4104 self.insert_with_autoindent_mode(text, autoindent, window, cx);
4105 }
4106
4107 fn insert_with_autoindent_mode(
4108 &mut self,
4109 text: &str,
4110 autoindent_mode: Option<AutoindentMode>,
4111 window: &mut Window,
4112 cx: &mut Context<Self>,
4113 ) {
4114 if self.read_only(cx) {
4115 return;
4116 }
4117
4118 let text: Arc<str> = text.into();
4119 self.transact(window, cx, |this, window, cx| {
4120 let old_selections = this.selections.all_adjusted(cx);
4121 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4122 let anchors = {
4123 let snapshot = buffer.read(cx);
4124 old_selections
4125 .iter()
4126 .map(|s| {
4127 let anchor = snapshot.anchor_after(s.head());
4128 s.map(|_| anchor)
4129 })
4130 .collect::<Vec<_>>()
4131 };
4132 buffer.edit(
4133 old_selections
4134 .iter()
4135 .map(|s| (s.start..s.end, text.clone())),
4136 autoindent_mode,
4137 cx,
4138 );
4139 anchors
4140 });
4141
4142 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
4143 s.select_anchors(selection_anchors);
4144 });
4145
4146 cx.notify();
4147 });
4148 }
4149
4150 fn trigger_completion_on_input(
4151 &mut self,
4152 text: &str,
4153 trigger_in_words: bool,
4154 window: &mut Window,
4155 cx: &mut Context<Self>,
4156 ) {
4157 let ignore_completion_provider = self
4158 .context_menu
4159 .borrow()
4160 .as_ref()
4161 .map(|menu| match menu {
4162 CodeContextMenu::Completions(completions_menu) => {
4163 completions_menu.ignore_completion_provider
4164 }
4165 CodeContextMenu::CodeActions(_) => false,
4166 })
4167 .unwrap_or(false);
4168
4169 if ignore_completion_provider {
4170 self.show_word_completions(&ShowWordCompletions, window, cx);
4171 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
4172 self.show_completions(
4173 &ShowCompletions {
4174 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4175 },
4176 window,
4177 cx,
4178 );
4179 } else {
4180 self.hide_context_menu(window, cx);
4181 }
4182 }
4183
4184 fn is_completion_trigger(
4185 &self,
4186 text: &str,
4187 trigger_in_words: bool,
4188 cx: &mut Context<Self>,
4189 ) -> bool {
4190 let position = self.selections.newest_anchor().head();
4191 let multibuffer = self.buffer.read(cx);
4192 let Some(buffer) = position
4193 .buffer_id
4194 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4195 else {
4196 return false;
4197 };
4198
4199 if let Some(completion_provider) = &self.completion_provider {
4200 completion_provider.is_completion_trigger(
4201 &buffer,
4202 position.text_anchor,
4203 text,
4204 trigger_in_words,
4205 cx,
4206 )
4207 } else {
4208 false
4209 }
4210 }
4211
4212 /// If any empty selections is touching the start of its innermost containing autoclose
4213 /// region, expand it to select the brackets.
4214 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4215 let selections = self.selections.all::<usize>(cx);
4216 let buffer = self.buffer.read(cx).read(cx);
4217 let new_selections = self
4218 .selections_with_autoclose_regions(selections, &buffer)
4219 .map(|(mut selection, region)| {
4220 if !selection.is_empty() {
4221 return selection;
4222 }
4223
4224 if let Some(region) = region {
4225 let mut range = region.range.to_offset(&buffer);
4226 if selection.start == range.start && range.start >= region.pair.start.len() {
4227 range.start -= region.pair.start.len();
4228 if buffer.contains_str_at(range.start, ®ion.pair.start)
4229 && buffer.contains_str_at(range.end, ®ion.pair.end)
4230 {
4231 range.end += region.pair.end.len();
4232 selection.start = range.start;
4233 selection.end = range.end;
4234
4235 return selection;
4236 }
4237 }
4238 }
4239
4240 let always_treat_brackets_as_autoclosed = buffer
4241 .language_settings_at(selection.start, cx)
4242 .always_treat_brackets_as_autoclosed;
4243
4244 if !always_treat_brackets_as_autoclosed {
4245 return selection;
4246 }
4247
4248 if let Some(scope) = buffer.language_scope_at(selection.start) {
4249 for (pair, enabled) in scope.brackets() {
4250 if !enabled || !pair.close {
4251 continue;
4252 }
4253
4254 if buffer.contains_str_at(selection.start, &pair.end) {
4255 let pair_start_len = pair.start.len();
4256 if buffer.contains_str_at(
4257 selection.start.saturating_sub(pair_start_len),
4258 &pair.start,
4259 ) {
4260 selection.start -= pair_start_len;
4261 selection.end += pair.end.len();
4262
4263 return selection;
4264 }
4265 }
4266 }
4267 }
4268
4269 selection
4270 })
4271 .collect();
4272
4273 drop(buffer);
4274 self.change_selections(None, window, cx, |selections| {
4275 selections.select(new_selections)
4276 });
4277 }
4278
4279 /// Iterate the given selections, and for each one, find the smallest surrounding
4280 /// autoclose region. This uses the ordering of the selections and the autoclose
4281 /// regions to avoid repeated comparisons.
4282 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4283 &'a self,
4284 selections: impl IntoIterator<Item = Selection<D>>,
4285 buffer: &'a MultiBufferSnapshot,
4286 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4287 let mut i = 0;
4288 let mut regions = self.autoclose_regions.as_slice();
4289 selections.into_iter().map(move |selection| {
4290 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4291
4292 let mut enclosing = None;
4293 while let Some(pair_state) = regions.get(i) {
4294 if pair_state.range.end.to_offset(buffer) < range.start {
4295 regions = ®ions[i + 1..];
4296 i = 0;
4297 } else if pair_state.range.start.to_offset(buffer) > range.end {
4298 break;
4299 } else {
4300 if pair_state.selection_id == selection.id {
4301 enclosing = Some(pair_state);
4302 }
4303 i += 1;
4304 }
4305 }
4306
4307 (selection, enclosing)
4308 })
4309 }
4310
4311 /// Remove any autoclose regions that no longer contain their selection.
4312 fn invalidate_autoclose_regions(
4313 &mut self,
4314 mut selections: &[Selection<Anchor>],
4315 buffer: &MultiBufferSnapshot,
4316 ) {
4317 self.autoclose_regions.retain(|state| {
4318 let mut i = 0;
4319 while let Some(selection) = selections.get(i) {
4320 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4321 selections = &selections[1..];
4322 continue;
4323 }
4324 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4325 break;
4326 }
4327 if selection.id == state.selection_id {
4328 return true;
4329 } else {
4330 i += 1;
4331 }
4332 }
4333 false
4334 });
4335 }
4336
4337 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4338 let offset = position.to_offset(buffer);
4339 let (word_range, kind) = buffer.surrounding_word(offset, true);
4340 if offset > word_range.start && kind == Some(CharKind::Word) {
4341 Some(
4342 buffer
4343 .text_for_range(word_range.start..offset)
4344 .collect::<String>(),
4345 )
4346 } else {
4347 None
4348 }
4349 }
4350
4351 pub fn toggle_inline_values(
4352 &mut self,
4353 _: &ToggleInlineValues,
4354 _: &mut Window,
4355 cx: &mut Context<Self>,
4356 ) {
4357 self.inline_value_cache.enabled = !self.inline_value_cache.enabled;
4358
4359 self.refresh_inline_values(cx);
4360 }
4361
4362 pub fn toggle_inlay_hints(
4363 &mut self,
4364 _: &ToggleInlayHints,
4365 _: &mut Window,
4366 cx: &mut Context<Self>,
4367 ) {
4368 self.refresh_inlay_hints(
4369 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4370 cx,
4371 );
4372 }
4373
4374 pub fn inlay_hints_enabled(&self) -> bool {
4375 self.inlay_hint_cache.enabled
4376 }
4377
4378 pub fn inline_values_enabled(&self) -> bool {
4379 self.inline_value_cache.enabled
4380 }
4381
4382 #[cfg(any(test, feature = "test-support"))]
4383 pub fn inline_value_inlays(&self, cx: &App) -> Vec<Inlay> {
4384 self.display_map
4385 .read(cx)
4386 .current_inlays()
4387 .filter(|inlay| matches!(inlay.id, InlayId::DebuggerValue(_)))
4388 .cloned()
4389 .collect()
4390 }
4391
4392 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4393 if self.semantics_provider.is_none() || !self.mode.is_full() {
4394 return;
4395 }
4396
4397 let reason_description = reason.description();
4398 let ignore_debounce = matches!(
4399 reason,
4400 InlayHintRefreshReason::SettingsChange(_)
4401 | InlayHintRefreshReason::Toggle(_)
4402 | InlayHintRefreshReason::ExcerptsRemoved(_)
4403 | InlayHintRefreshReason::ModifiersChanged(_)
4404 );
4405 let (invalidate_cache, required_languages) = match reason {
4406 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4407 match self.inlay_hint_cache.modifiers_override(enabled) {
4408 Some(enabled) => {
4409 if enabled {
4410 (InvalidationStrategy::RefreshRequested, None)
4411 } else {
4412 self.splice_inlays(
4413 &self
4414 .visible_inlay_hints(cx)
4415 .iter()
4416 .map(|inlay| inlay.id)
4417 .collect::<Vec<InlayId>>(),
4418 Vec::new(),
4419 cx,
4420 );
4421 return;
4422 }
4423 }
4424 None => return,
4425 }
4426 }
4427 InlayHintRefreshReason::Toggle(enabled) => {
4428 if self.inlay_hint_cache.toggle(enabled) {
4429 if enabled {
4430 (InvalidationStrategy::RefreshRequested, None)
4431 } else {
4432 self.splice_inlays(
4433 &self
4434 .visible_inlay_hints(cx)
4435 .iter()
4436 .map(|inlay| inlay.id)
4437 .collect::<Vec<InlayId>>(),
4438 Vec::new(),
4439 cx,
4440 );
4441 return;
4442 }
4443 } else {
4444 return;
4445 }
4446 }
4447 InlayHintRefreshReason::SettingsChange(new_settings) => {
4448 match self.inlay_hint_cache.update_settings(
4449 &self.buffer,
4450 new_settings,
4451 self.visible_inlay_hints(cx),
4452 cx,
4453 ) {
4454 ControlFlow::Break(Some(InlaySplice {
4455 to_remove,
4456 to_insert,
4457 })) => {
4458 self.splice_inlays(&to_remove, to_insert, cx);
4459 return;
4460 }
4461 ControlFlow::Break(None) => return,
4462 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4463 }
4464 }
4465 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4466 if let Some(InlaySplice {
4467 to_remove,
4468 to_insert,
4469 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4470 {
4471 self.splice_inlays(&to_remove, to_insert, cx);
4472 }
4473 self.display_map.update(cx, |display_map, _| {
4474 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4475 });
4476 return;
4477 }
4478 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4479 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4480 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4481 }
4482 InlayHintRefreshReason::RefreshRequested => {
4483 (InvalidationStrategy::RefreshRequested, None)
4484 }
4485 };
4486
4487 if let Some(InlaySplice {
4488 to_remove,
4489 to_insert,
4490 }) = self.inlay_hint_cache.spawn_hint_refresh(
4491 reason_description,
4492 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4493 invalidate_cache,
4494 ignore_debounce,
4495 cx,
4496 ) {
4497 self.splice_inlays(&to_remove, to_insert, cx);
4498 }
4499 }
4500
4501 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4502 self.display_map
4503 .read(cx)
4504 .current_inlays()
4505 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4506 .cloned()
4507 .collect()
4508 }
4509
4510 pub fn excerpts_for_inlay_hints_query(
4511 &self,
4512 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4513 cx: &mut Context<Editor>,
4514 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4515 let Some(project) = self.project.as_ref() else {
4516 return HashMap::default();
4517 };
4518 let project = project.read(cx);
4519 let multi_buffer = self.buffer().read(cx);
4520 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4521 let multi_buffer_visible_start = self
4522 .scroll_manager
4523 .anchor()
4524 .anchor
4525 .to_point(&multi_buffer_snapshot);
4526 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4527 multi_buffer_visible_start
4528 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4529 Bias::Left,
4530 );
4531 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4532 multi_buffer_snapshot
4533 .range_to_buffer_ranges(multi_buffer_visible_range)
4534 .into_iter()
4535 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4536 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4537 let buffer_file = project::File::from_dyn(buffer.file())?;
4538 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4539 let worktree_entry = buffer_worktree
4540 .read(cx)
4541 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4542 if worktree_entry.is_ignored {
4543 return None;
4544 }
4545
4546 let language = buffer.language()?;
4547 if let Some(restrict_to_languages) = restrict_to_languages {
4548 if !restrict_to_languages.contains(language) {
4549 return None;
4550 }
4551 }
4552 Some((
4553 excerpt_id,
4554 (
4555 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4556 buffer.version().clone(),
4557 excerpt_visible_range,
4558 ),
4559 ))
4560 })
4561 .collect()
4562 }
4563
4564 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4565 TextLayoutDetails {
4566 text_system: window.text_system().clone(),
4567 editor_style: self.style.clone().unwrap(),
4568 rem_size: window.rem_size(),
4569 scroll_anchor: self.scroll_manager.anchor(),
4570 visible_rows: self.visible_line_count(),
4571 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4572 }
4573 }
4574
4575 pub fn splice_inlays(
4576 &self,
4577 to_remove: &[InlayId],
4578 to_insert: Vec<Inlay>,
4579 cx: &mut Context<Self>,
4580 ) {
4581 self.display_map.update(cx, |display_map, cx| {
4582 display_map.splice_inlays(to_remove, to_insert, cx)
4583 });
4584 cx.notify();
4585 }
4586
4587 fn trigger_on_type_formatting(
4588 &self,
4589 input: String,
4590 window: &mut Window,
4591 cx: &mut Context<Self>,
4592 ) -> Option<Task<Result<()>>> {
4593 if input.len() != 1 {
4594 return None;
4595 }
4596
4597 let project = self.project.as_ref()?;
4598 let position = self.selections.newest_anchor().head();
4599 let (buffer, buffer_position) = self
4600 .buffer
4601 .read(cx)
4602 .text_anchor_for_position(position, cx)?;
4603
4604 let settings = language_settings::language_settings(
4605 buffer
4606 .read(cx)
4607 .language_at(buffer_position)
4608 .map(|l| l.name()),
4609 buffer.read(cx).file(),
4610 cx,
4611 );
4612 if !settings.use_on_type_format {
4613 return None;
4614 }
4615
4616 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4617 // hence we do LSP request & edit on host side only — add formats to host's history.
4618 let push_to_lsp_host_history = true;
4619 // If this is not the host, append its history with new edits.
4620 let push_to_client_history = project.read(cx).is_via_collab();
4621
4622 let on_type_formatting = project.update(cx, |project, cx| {
4623 project.on_type_format(
4624 buffer.clone(),
4625 buffer_position,
4626 input,
4627 push_to_lsp_host_history,
4628 cx,
4629 )
4630 });
4631 Some(cx.spawn_in(window, async move |editor, cx| {
4632 if let Some(transaction) = on_type_formatting.await? {
4633 if push_to_client_history {
4634 buffer
4635 .update(cx, |buffer, _| {
4636 buffer.push_transaction(transaction, Instant::now());
4637 buffer.finalize_last_transaction();
4638 })
4639 .ok();
4640 }
4641 editor.update(cx, |editor, cx| {
4642 editor.refresh_document_highlights(cx);
4643 })?;
4644 }
4645 Ok(())
4646 }))
4647 }
4648
4649 pub fn show_word_completions(
4650 &mut self,
4651 _: &ShowWordCompletions,
4652 window: &mut Window,
4653 cx: &mut Context<Self>,
4654 ) {
4655 self.open_completions_menu(true, None, window, cx);
4656 }
4657
4658 pub fn show_completions(
4659 &mut self,
4660 options: &ShowCompletions,
4661 window: &mut Window,
4662 cx: &mut Context<Self>,
4663 ) {
4664 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4665 }
4666
4667 fn open_completions_menu(
4668 &mut self,
4669 ignore_completion_provider: bool,
4670 trigger: Option<&str>,
4671 window: &mut Window,
4672 cx: &mut Context<Self>,
4673 ) {
4674 if self.pending_rename.is_some() {
4675 return;
4676 }
4677 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4678 return;
4679 }
4680
4681 let position = self.selections.newest_anchor().head();
4682 if position.diff_base_anchor.is_some() {
4683 return;
4684 }
4685 let (buffer, buffer_position) =
4686 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4687 output
4688 } else {
4689 return;
4690 };
4691 let buffer_snapshot = buffer.read(cx).snapshot();
4692 let show_completion_documentation = buffer_snapshot
4693 .settings_at(buffer_position, cx)
4694 .show_completion_documentation;
4695
4696 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4697
4698 let trigger_kind = match trigger {
4699 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4700 CompletionTriggerKind::TRIGGER_CHARACTER
4701 }
4702 _ => CompletionTriggerKind::INVOKED,
4703 };
4704 let completion_context = CompletionContext {
4705 trigger_character: trigger.and_then(|trigger| {
4706 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4707 Some(String::from(trigger))
4708 } else {
4709 None
4710 }
4711 }),
4712 trigger_kind,
4713 };
4714
4715 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4716 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4717 let word_to_exclude = buffer_snapshot
4718 .text_for_range(old_range.clone())
4719 .collect::<String>();
4720 (
4721 buffer_snapshot.anchor_before(old_range.start)
4722 ..buffer_snapshot.anchor_after(old_range.end),
4723 Some(word_to_exclude),
4724 )
4725 } else {
4726 (buffer_position..buffer_position, None)
4727 };
4728
4729 let completion_settings = language_settings(
4730 buffer_snapshot
4731 .language_at(buffer_position)
4732 .map(|language| language.name()),
4733 buffer_snapshot.file(),
4734 cx,
4735 )
4736 .completions;
4737
4738 // The document can be large, so stay in reasonable bounds when searching for words,
4739 // otherwise completion pop-up might be slow to appear.
4740 const WORD_LOOKUP_ROWS: u32 = 5_000;
4741 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4742 let min_word_search = buffer_snapshot.clip_point(
4743 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4744 Bias::Left,
4745 );
4746 let max_word_search = buffer_snapshot.clip_point(
4747 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4748 Bias::Right,
4749 );
4750 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4751 ..buffer_snapshot.point_to_offset(max_word_search);
4752
4753 let provider = self
4754 .completion_provider
4755 .as_ref()
4756 .filter(|_| !ignore_completion_provider);
4757 let skip_digits = query
4758 .as_ref()
4759 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4760
4761 let (mut words, provided_completions) = match provider {
4762 Some(provider) => {
4763 let completions = provider.completions(
4764 position.excerpt_id,
4765 &buffer,
4766 buffer_position,
4767 completion_context,
4768 window,
4769 cx,
4770 );
4771
4772 let words = match completion_settings.words {
4773 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4774 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4775 .background_spawn(async move {
4776 buffer_snapshot.words_in_range(WordsQuery {
4777 fuzzy_contents: None,
4778 range: word_search_range,
4779 skip_digits,
4780 })
4781 }),
4782 };
4783
4784 (words, completions)
4785 }
4786 None => (
4787 cx.background_spawn(async move {
4788 buffer_snapshot.words_in_range(WordsQuery {
4789 fuzzy_contents: None,
4790 range: word_search_range,
4791 skip_digits,
4792 })
4793 }),
4794 Task::ready(Ok(None)),
4795 ),
4796 };
4797
4798 let sort_completions = provider
4799 .as_ref()
4800 .map_or(false, |provider| provider.sort_completions());
4801
4802 let filter_completions = provider
4803 .as_ref()
4804 .map_or(true, |provider| provider.filter_completions());
4805
4806 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
4807
4808 let id = post_inc(&mut self.next_completion_id);
4809 let task = cx.spawn_in(window, async move |editor, cx| {
4810 async move {
4811 editor.update(cx, |this, _| {
4812 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4813 })?;
4814
4815 let mut completions = Vec::new();
4816 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4817 completions.extend(provided_completions);
4818 if completion_settings.words == WordsCompletionMode::Fallback {
4819 words = Task::ready(BTreeMap::default());
4820 }
4821 }
4822
4823 let mut words = words.await;
4824 if let Some(word_to_exclude) = &word_to_exclude {
4825 words.remove(word_to_exclude);
4826 }
4827 for lsp_completion in &completions {
4828 words.remove(&lsp_completion.new_text);
4829 }
4830 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4831 replace_range: old_range.clone(),
4832 new_text: word.clone(),
4833 label: CodeLabel::plain(word, None),
4834 icon_path: None,
4835 documentation: None,
4836 source: CompletionSource::BufferWord {
4837 word_range,
4838 resolved: false,
4839 },
4840 insert_text_mode: Some(InsertTextMode::AS_IS),
4841 confirm: None,
4842 }));
4843
4844 let menu = if completions.is_empty() {
4845 None
4846 } else {
4847 let mut menu = CompletionsMenu::new(
4848 id,
4849 sort_completions,
4850 show_completion_documentation,
4851 ignore_completion_provider,
4852 position,
4853 buffer.clone(),
4854 completions.into(),
4855 snippet_sort_order,
4856 );
4857
4858 menu.filter(
4859 if filter_completions {
4860 query.as_deref()
4861 } else {
4862 None
4863 },
4864 cx.background_executor().clone(),
4865 )
4866 .await;
4867
4868 menu.visible().then_some(menu)
4869 };
4870
4871 editor.update_in(cx, |editor, window, cx| {
4872 match editor.context_menu.borrow().as_ref() {
4873 None => {}
4874 Some(CodeContextMenu::Completions(prev_menu)) => {
4875 if prev_menu.id > id {
4876 return;
4877 }
4878 }
4879 _ => return,
4880 }
4881
4882 if editor.focus_handle.is_focused(window) && menu.is_some() {
4883 let mut menu = menu.unwrap();
4884 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4885
4886 *editor.context_menu.borrow_mut() =
4887 Some(CodeContextMenu::Completions(menu));
4888
4889 if editor.show_edit_predictions_in_menu() {
4890 editor.update_visible_inline_completion(window, cx);
4891 } else {
4892 editor.discard_inline_completion(false, cx);
4893 }
4894
4895 cx.notify();
4896 } else if editor.completion_tasks.len() <= 1 {
4897 // If there are no more completion tasks and the last menu was
4898 // empty, we should hide it.
4899 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4900 // If it was already hidden and we don't show inline
4901 // completions in the menu, we should also show the
4902 // inline-completion when available.
4903 if was_hidden && editor.show_edit_predictions_in_menu() {
4904 editor.update_visible_inline_completion(window, cx);
4905 }
4906 }
4907 })?;
4908
4909 anyhow::Ok(())
4910 }
4911 .log_err()
4912 .await
4913 });
4914
4915 self.completion_tasks.push((id, task));
4916 }
4917
4918 #[cfg(feature = "test-support")]
4919 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4920 let menu = self.context_menu.borrow();
4921 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4922 let completions = menu.completions.borrow();
4923 Some(completions.to_vec())
4924 } else {
4925 None
4926 }
4927 }
4928
4929 pub fn confirm_completion(
4930 &mut self,
4931 action: &ConfirmCompletion,
4932 window: &mut Window,
4933 cx: &mut Context<Self>,
4934 ) -> Option<Task<Result<()>>> {
4935 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4936 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4937 }
4938
4939 pub fn confirm_completion_insert(
4940 &mut self,
4941 _: &ConfirmCompletionInsert,
4942 window: &mut Window,
4943 cx: &mut Context<Self>,
4944 ) -> Option<Task<Result<()>>> {
4945 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4946 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4947 }
4948
4949 pub fn confirm_completion_replace(
4950 &mut self,
4951 _: &ConfirmCompletionReplace,
4952 window: &mut Window,
4953 cx: &mut Context<Self>,
4954 ) -> Option<Task<Result<()>>> {
4955 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4956 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4957 }
4958
4959 pub fn compose_completion(
4960 &mut self,
4961 action: &ComposeCompletion,
4962 window: &mut Window,
4963 cx: &mut Context<Self>,
4964 ) -> Option<Task<Result<()>>> {
4965 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4966 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4967 }
4968
4969 fn do_completion(
4970 &mut self,
4971 item_ix: Option<usize>,
4972 intent: CompletionIntent,
4973 window: &mut Window,
4974 cx: &mut Context<Editor>,
4975 ) -> Option<Task<Result<()>>> {
4976 use language::ToOffset as _;
4977
4978 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4979 else {
4980 return None;
4981 };
4982
4983 let candidate_id = {
4984 let entries = completions_menu.entries.borrow();
4985 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4986 if self.show_edit_predictions_in_menu() {
4987 self.discard_inline_completion(true, cx);
4988 }
4989 mat.candidate_id
4990 };
4991
4992 let buffer_handle = completions_menu.buffer;
4993 let completion = completions_menu
4994 .completions
4995 .borrow()
4996 .get(candidate_id)?
4997 .clone();
4998 cx.stop_propagation();
4999
5000 let snippet;
5001 let new_text;
5002 if completion.is_snippet() {
5003 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
5004 new_text = snippet.as_ref().unwrap().text.clone();
5005 } else {
5006 snippet = None;
5007 new_text = completion.new_text.clone();
5008 };
5009
5010 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
5011 let buffer = buffer_handle.read(cx);
5012 let snapshot = self.buffer.read(cx).snapshot(cx);
5013 let replace_range_multibuffer = {
5014 let excerpt = snapshot
5015 .excerpt_containing(self.selections.newest_anchor().range())
5016 .unwrap();
5017 let multibuffer_anchor = snapshot
5018 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
5019 .unwrap()
5020 ..snapshot
5021 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
5022 .unwrap();
5023 multibuffer_anchor.start.to_offset(&snapshot)
5024 ..multibuffer_anchor.end.to_offset(&snapshot)
5025 };
5026 let newest_anchor = self.selections.newest_anchor();
5027 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
5028 return None;
5029 }
5030
5031 let old_text = buffer
5032 .text_for_range(replace_range.clone())
5033 .collect::<String>();
5034 let lookbehind = newest_anchor
5035 .start
5036 .text_anchor
5037 .to_offset(buffer)
5038 .saturating_sub(replace_range.start);
5039 let lookahead = replace_range
5040 .end
5041 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
5042 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
5043 let suffix = &old_text[lookbehind.min(old_text.len())..];
5044
5045 let selections = self.selections.all::<usize>(cx);
5046 let mut ranges = Vec::new();
5047 let mut linked_edits = HashMap::<_, Vec<_>>::default();
5048
5049 for selection in &selections {
5050 let range = if selection.id == newest_anchor.id {
5051 replace_range_multibuffer.clone()
5052 } else {
5053 let mut range = selection.range();
5054
5055 // if prefix is present, don't duplicate it
5056 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
5057 range.start = range.start.saturating_sub(lookbehind);
5058
5059 // if suffix is also present, mimic the newest cursor and replace it
5060 if selection.id != newest_anchor.id
5061 && snapshot.contains_str_at(range.end, suffix)
5062 {
5063 range.end += lookahead;
5064 }
5065 }
5066 range
5067 };
5068
5069 ranges.push(range.clone());
5070
5071 if !self.linked_edit_ranges.is_empty() {
5072 let start_anchor = snapshot.anchor_before(range.start);
5073 let end_anchor = snapshot.anchor_after(range.end);
5074 if let Some(ranges) = self
5075 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
5076 {
5077 for (buffer, edits) in ranges {
5078 linked_edits
5079 .entry(buffer.clone())
5080 .or_default()
5081 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
5082 }
5083 }
5084 }
5085 }
5086
5087 cx.emit(EditorEvent::InputHandled {
5088 utf16_range_to_replace: None,
5089 text: new_text.clone().into(),
5090 });
5091
5092 self.transact(window, cx, |this, window, cx| {
5093 if let Some(mut snippet) = snippet {
5094 snippet.text = new_text.to_string();
5095 this.insert_snippet(&ranges, snippet, window, cx).log_err();
5096 } else {
5097 this.buffer.update(cx, |buffer, cx| {
5098 let auto_indent = match completion.insert_text_mode {
5099 Some(InsertTextMode::AS_IS) => None,
5100 _ => this.autoindent_mode.clone(),
5101 };
5102 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
5103 buffer.edit(edits, auto_indent, cx);
5104 });
5105 }
5106 for (buffer, edits) in linked_edits {
5107 buffer.update(cx, |buffer, cx| {
5108 let snapshot = buffer.snapshot();
5109 let edits = edits
5110 .into_iter()
5111 .map(|(range, text)| {
5112 use text::ToPoint as TP;
5113 let end_point = TP::to_point(&range.end, &snapshot);
5114 let start_point = TP::to_point(&range.start, &snapshot);
5115 (start_point..end_point, text)
5116 })
5117 .sorted_by_key(|(range, _)| range.start);
5118 buffer.edit(edits, None, cx);
5119 })
5120 }
5121
5122 this.refresh_inline_completion(true, false, window, cx);
5123 });
5124
5125 let show_new_completions_on_confirm = completion
5126 .confirm
5127 .as_ref()
5128 .map_or(false, |confirm| confirm(intent, window, cx));
5129 if show_new_completions_on_confirm {
5130 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
5131 }
5132
5133 let provider = self.completion_provider.as_ref()?;
5134 drop(completion);
5135 let apply_edits = provider.apply_additional_edits_for_completion(
5136 buffer_handle,
5137 completions_menu.completions.clone(),
5138 candidate_id,
5139 true,
5140 cx,
5141 );
5142
5143 let editor_settings = EditorSettings::get_global(cx);
5144 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
5145 // After the code completion is finished, users often want to know what signatures are needed.
5146 // so we should automatically call signature_help
5147 self.show_signature_help(&ShowSignatureHelp, window, cx);
5148 }
5149
5150 Some(cx.foreground_executor().spawn(async move {
5151 apply_edits.await?;
5152 Ok(())
5153 }))
5154 }
5155
5156 pub fn toggle_code_actions(
5157 &mut self,
5158 action: &ToggleCodeActions,
5159 window: &mut Window,
5160 cx: &mut Context<Self>,
5161 ) {
5162 let quick_launch = action.quick_launch;
5163 let mut context_menu = self.context_menu.borrow_mut();
5164 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
5165 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
5166 // Toggle if we're selecting the same one
5167 *context_menu = None;
5168 cx.notify();
5169 return;
5170 } else {
5171 // Otherwise, clear it and start a new one
5172 *context_menu = None;
5173 cx.notify();
5174 }
5175 }
5176 drop(context_menu);
5177 let snapshot = self.snapshot(window, cx);
5178 let deployed_from_indicator = action.deployed_from_indicator;
5179 let mut task = self.code_actions_task.take();
5180 let action = action.clone();
5181 cx.spawn_in(window, async move |editor, cx| {
5182 while let Some(prev_task) = task {
5183 prev_task.await.log_err();
5184 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
5185 }
5186
5187 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
5188 if editor.focus_handle.is_focused(window) {
5189 let multibuffer_point = action
5190 .deployed_from_indicator
5191 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
5192 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
5193 let (buffer, buffer_row) = snapshot
5194 .buffer_snapshot
5195 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
5196 .and_then(|(buffer_snapshot, range)| {
5197 editor
5198 .buffer
5199 .read(cx)
5200 .buffer(buffer_snapshot.remote_id())
5201 .map(|buffer| (buffer, range.start.row))
5202 })?;
5203 let (_, code_actions) = editor
5204 .available_code_actions
5205 .clone()
5206 .and_then(|(location, code_actions)| {
5207 let snapshot = location.buffer.read(cx).snapshot();
5208 let point_range = location.range.to_point(&snapshot);
5209 let point_range = point_range.start.row..=point_range.end.row;
5210 if point_range.contains(&buffer_row) {
5211 Some((location, code_actions))
5212 } else {
5213 None
5214 }
5215 })
5216 .unzip();
5217 let buffer_id = buffer.read(cx).remote_id();
5218 let tasks = editor
5219 .tasks
5220 .get(&(buffer_id, buffer_row))
5221 .map(|t| Arc::new(t.to_owned()));
5222 if tasks.is_none() && code_actions.is_none() {
5223 return None;
5224 }
5225
5226 editor.completion_tasks.clear();
5227 editor.discard_inline_completion(false, cx);
5228 let task_context =
5229 tasks
5230 .as_ref()
5231 .zip(editor.project.clone())
5232 .map(|(tasks, project)| {
5233 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5234 });
5235
5236 Some(cx.spawn_in(window, async move |editor, cx| {
5237 let task_context = match task_context {
5238 Some(task_context) => task_context.await,
5239 None => None,
5240 };
5241 let resolved_tasks =
5242 tasks
5243 .zip(task_context.clone())
5244 .map(|(tasks, task_context)| ResolvedTasks {
5245 templates: tasks.resolve(&task_context).collect(),
5246 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5247 multibuffer_point.row,
5248 tasks.column,
5249 )),
5250 });
5251 let debug_scenarios = editor.update(cx, |editor, cx| {
5252 if cx.has_flag::<DebuggerFeatureFlag>() {
5253 maybe!({
5254 let project = editor.project.as_ref()?;
5255 let dap_store = project.read(cx).dap_store();
5256 let mut scenarios = vec![];
5257 let resolved_tasks = resolved_tasks.as_ref()?;
5258 let buffer = buffer.read(cx);
5259 let language = buffer.language()?;
5260 let file = buffer.file();
5261 let debug_adapter =
5262 language_settings(language.name().into(), file, cx)
5263 .debuggers
5264 .first()
5265 .map(SharedString::from)
5266 .or_else(|| {
5267 language
5268 .config()
5269 .debuggers
5270 .first()
5271 .map(SharedString::from)
5272 })?;
5273
5274 dap_store.update(cx, |this, cx| {
5275 for (_, task) in &resolved_tasks.templates {
5276 if let Some(scenario) = this
5277 .debug_scenario_for_build_task(
5278 task.original_task().clone(),
5279 debug_adapter.clone().into(),
5280 task.display_label().to_owned().into(),
5281 cx,
5282 )
5283 {
5284 scenarios.push(scenario);
5285 }
5286 }
5287 });
5288 Some(scenarios)
5289 })
5290 .unwrap_or_default()
5291 } else {
5292 vec![]
5293 }
5294 })?;
5295 let spawn_straight_away = quick_launch
5296 && resolved_tasks
5297 .as_ref()
5298 .map_or(false, |tasks| tasks.templates.len() == 1)
5299 && code_actions
5300 .as_ref()
5301 .map_or(true, |actions| actions.is_empty())
5302 && debug_scenarios.is_empty();
5303 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5304 *editor.context_menu.borrow_mut() =
5305 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5306 buffer,
5307 actions: CodeActionContents::new(
5308 resolved_tasks,
5309 code_actions,
5310 debug_scenarios,
5311 task_context.unwrap_or_default(),
5312 ),
5313 selected_item: Default::default(),
5314 scroll_handle: UniformListScrollHandle::default(),
5315 deployed_from_indicator,
5316 }));
5317 if spawn_straight_away {
5318 if let Some(task) = editor.confirm_code_action(
5319 &ConfirmCodeAction { item_ix: Some(0) },
5320 window,
5321 cx,
5322 ) {
5323 cx.notify();
5324 return task;
5325 }
5326 }
5327 cx.notify();
5328 Task::ready(Ok(()))
5329 }) {
5330 task.await
5331 } else {
5332 Ok(())
5333 }
5334 }))
5335 } else {
5336 Some(Task::ready(Ok(())))
5337 }
5338 })?;
5339 if let Some(task) = spawned_test_task {
5340 task.await?;
5341 }
5342
5343 Ok::<_, anyhow::Error>(())
5344 })
5345 .detach_and_log_err(cx);
5346 }
5347
5348 pub fn confirm_code_action(
5349 &mut self,
5350 action: &ConfirmCodeAction,
5351 window: &mut Window,
5352 cx: &mut Context<Self>,
5353 ) -> Option<Task<Result<()>>> {
5354 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5355
5356 let actions_menu =
5357 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5358 menu
5359 } else {
5360 return None;
5361 };
5362
5363 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5364 let action = actions_menu.actions.get(action_ix)?;
5365 let title = action.label();
5366 let buffer = actions_menu.buffer;
5367 let workspace = self.workspace()?;
5368
5369 match action {
5370 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5371 workspace.update(cx, |workspace, cx| {
5372 workspace.schedule_resolved_task(
5373 task_source_kind,
5374 resolved_task,
5375 false,
5376 window,
5377 cx,
5378 );
5379
5380 Some(Task::ready(Ok(())))
5381 })
5382 }
5383 CodeActionsItem::CodeAction {
5384 excerpt_id,
5385 action,
5386 provider,
5387 } => {
5388 let apply_code_action =
5389 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5390 let workspace = workspace.downgrade();
5391 Some(cx.spawn_in(window, async move |editor, cx| {
5392 let project_transaction = apply_code_action.await?;
5393 Self::open_project_transaction(
5394 &editor,
5395 workspace,
5396 project_transaction,
5397 title,
5398 cx,
5399 )
5400 .await
5401 }))
5402 }
5403 CodeActionsItem::DebugScenario(scenario) => {
5404 let context = actions_menu.actions.context.clone();
5405
5406 workspace.update(cx, |workspace, cx| {
5407 workspace.start_debug_session(scenario, context, Some(buffer), window, cx);
5408 });
5409 Some(Task::ready(Ok(())))
5410 }
5411 }
5412 }
5413
5414 pub async fn open_project_transaction(
5415 this: &WeakEntity<Editor>,
5416 workspace: WeakEntity<Workspace>,
5417 transaction: ProjectTransaction,
5418 title: String,
5419 cx: &mut AsyncWindowContext,
5420 ) -> Result<()> {
5421 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5422 cx.update(|_, cx| {
5423 entries.sort_unstable_by_key(|(buffer, _)| {
5424 buffer.read(cx).file().map(|f| f.path().clone())
5425 });
5426 })?;
5427
5428 // If the project transaction's edits are all contained within this editor, then
5429 // avoid opening a new editor to display them.
5430
5431 if let Some((buffer, transaction)) = entries.first() {
5432 if entries.len() == 1 {
5433 let excerpt = this.update(cx, |editor, cx| {
5434 editor
5435 .buffer()
5436 .read(cx)
5437 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5438 })?;
5439 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5440 if excerpted_buffer == *buffer {
5441 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5442 let excerpt_range = excerpt_range.to_offset(buffer);
5443 buffer
5444 .edited_ranges_for_transaction::<usize>(transaction)
5445 .all(|range| {
5446 excerpt_range.start <= range.start
5447 && excerpt_range.end >= range.end
5448 })
5449 })?;
5450
5451 if all_edits_within_excerpt {
5452 return Ok(());
5453 }
5454 }
5455 }
5456 }
5457 } else {
5458 return Ok(());
5459 }
5460
5461 let mut ranges_to_highlight = Vec::new();
5462 let excerpt_buffer = cx.new(|cx| {
5463 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5464 for (buffer_handle, transaction) in &entries {
5465 let edited_ranges = buffer_handle
5466 .read(cx)
5467 .edited_ranges_for_transaction::<Point>(transaction)
5468 .collect::<Vec<_>>();
5469 let (ranges, _) = multibuffer.set_excerpts_for_path(
5470 PathKey::for_buffer(buffer_handle, cx),
5471 buffer_handle.clone(),
5472 edited_ranges,
5473 DEFAULT_MULTIBUFFER_CONTEXT,
5474 cx,
5475 );
5476
5477 ranges_to_highlight.extend(ranges);
5478 }
5479 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5480 multibuffer
5481 })?;
5482
5483 workspace.update_in(cx, |workspace, window, cx| {
5484 let project = workspace.project().clone();
5485 let editor =
5486 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5487 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5488 editor.update(cx, |editor, cx| {
5489 editor.highlight_background::<Self>(
5490 &ranges_to_highlight,
5491 |theme| theme.editor_highlighted_line_background,
5492 cx,
5493 );
5494 });
5495 })?;
5496
5497 Ok(())
5498 }
5499
5500 pub fn clear_code_action_providers(&mut self) {
5501 self.code_action_providers.clear();
5502 self.available_code_actions.take();
5503 }
5504
5505 pub fn add_code_action_provider(
5506 &mut self,
5507 provider: Rc<dyn CodeActionProvider>,
5508 window: &mut Window,
5509 cx: &mut Context<Self>,
5510 ) {
5511 if self
5512 .code_action_providers
5513 .iter()
5514 .any(|existing_provider| existing_provider.id() == provider.id())
5515 {
5516 return;
5517 }
5518
5519 self.code_action_providers.push(provider);
5520 self.refresh_code_actions(window, cx);
5521 }
5522
5523 pub fn remove_code_action_provider(
5524 &mut self,
5525 id: Arc<str>,
5526 window: &mut Window,
5527 cx: &mut Context<Self>,
5528 ) {
5529 self.code_action_providers
5530 .retain(|provider| provider.id() != id);
5531 self.refresh_code_actions(window, cx);
5532 }
5533
5534 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5535 let newest_selection = self.selections.newest_anchor().clone();
5536 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5537 let buffer = self.buffer.read(cx);
5538 if newest_selection.head().diff_base_anchor.is_some() {
5539 return None;
5540 }
5541 let (start_buffer, start) =
5542 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5543 let (end_buffer, end) =
5544 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5545 if start_buffer != end_buffer {
5546 return None;
5547 }
5548
5549 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5550 cx.background_executor()
5551 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5552 .await;
5553
5554 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5555 let providers = this.code_action_providers.clone();
5556 let tasks = this
5557 .code_action_providers
5558 .iter()
5559 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5560 .collect::<Vec<_>>();
5561 (providers, tasks)
5562 })?;
5563
5564 let mut actions = Vec::new();
5565 for (provider, provider_actions) in
5566 providers.into_iter().zip(future::join_all(tasks).await)
5567 {
5568 if let Some(provider_actions) = provider_actions.log_err() {
5569 actions.extend(provider_actions.into_iter().map(|action| {
5570 AvailableCodeAction {
5571 excerpt_id: newest_selection.start.excerpt_id,
5572 action,
5573 provider: provider.clone(),
5574 }
5575 }));
5576 }
5577 }
5578
5579 this.update(cx, |this, cx| {
5580 this.available_code_actions = if actions.is_empty() {
5581 None
5582 } else {
5583 Some((
5584 Location {
5585 buffer: start_buffer,
5586 range: start..end,
5587 },
5588 actions.into(),
5589 ))
5590 };
5591 cx.notify();
5592 })
5593 }));
5594 None
5595 }
5596
5597 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5598 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5599 self.show_git_blame_inline = false;
5600
5601 self.show_git_blame_inline_delay_task =
5602 Some(cx.spawn_in(window, async move |this, cx| {
5603 cx.background_executor().timer(delay).await;
5604
5605 this.update(cx, |this, cx| {
5606 this.show_git_blame_inline = true;
5607 cx.notify();
5608 })
5609 .log_err();
5610 }));
5611 }
5612 }
5613
5614 fn show_blame_popover(
5615 &mut self,
5616 blame_entry: &BlameEntry,
5617 position: gpui::Point<Pixels>,
5618 cx: &mut Context<Self>,
5619 ) {
5620 if let Some(state) = &mut self.inline_blame_popover {
5621 state.hide_task.take();
5622 cx.notify();
5623 } else {
5624 let delay = EditorSettings::get_global(cx).hover_popover_delay;
5625 let show_task = cx.spawn(async move |editor, cx| {
5626 cx.background_executor()
5627 .timer(std::time::Duration::from_millis(delay))
5628 .await;
5629 editor
5630 .update(cx, |editor, cx| {
5631 if let Some(state) = &mut editor.inline_blame_popover {
5632 state.show_task = None;
5633 cx.notify();
5634 }
5635 })
5636 .ok();
5637 });
5638 let Some(blame) = self.blame.as_ref() else {
5639 return;
5640 };
5641 let blame = blame.read(cx);
5642 let details = blame.details_for_entry(&blame_entry);
5643 let markdown = cx.new(|cx| {
5644 Markdown::new(
5645 details
5646 .as_ref()
5647 .map(|message| message.message.clone())
5648 .unwrap_or_default(),
5649 None,
5650 None,
5651 cx,
5652 )
5653 });
5654 self.inline_blame_popover = Some(InlineBlamePopover {
5655 position,
5656 show_task: Some(show_task),
5657 hide_task: None,
5658 popover_bounds: None,
5659 popover_state: InlineBlamePopoverState {
5660 scroll_handle: ScrollHandle::new(),
5661 commit_message: details,
5662 markdown,
5663 },
5664 });
5665 }
5666 }
5667
5668 fn hide_blame_popover(&mut self, cx: &mut Context<Self>) {
5669 if let Some(state) = &mut self.inline_blame_popover {
5670 if state.show_task.is_some() {
5671 self.inline_blame_popover.take();
5672 cx.notify();
5673 } else {
5674 let hide_task = cx.spawn(async move |editor, cx| {
5675 cx.background_executor()
5676 .timer(std::time::Duration::from_millis(100))
5677 .await;
5678 editor
5679 .update(cx, |editor, cx| {
5680 editor.inline_blame_popover.take();
5681 cx.notify();
5682 })
5683 .ok();
5684 });
5685 state.hide_task = Some(hide_task);
5686 }
5687 }
5688 }
5689
5690 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5691 if self.pending_rename.is_some() {
5692 return None;
5693 }
5694
5695 let provider = self.semantics_provider.clone()?;
5696 let buffer = self.buffer.read(cx);
5697 let newest_selection = self.selections.newest_anchor().clone();
5698 let cursor_position = newest_selection.head();
5699 let (cursor_buffer, cursor_buffer_position) =
5700 buffer.text_anchor_for_position(cursor_position, cx)?;
5701 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5702 if cursor_buffer != tail_buffer {
5703 return None;
5704 }
5705 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5706 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5707 cx.background_executor()
5708 .timer(Duration::from_millis(debounce))
5709 .await;
5710
5711 let highlights = if let Some(highlights) = cx
5712 .update(|cx| {
5713 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5714 })
5715 .ok()
5716 .flatten()
5717 {
5718 highlights.await.log_err()
5719 } else {
5720 None
5721 };
5722
5723 if let Some(highlights) = highlights {
5724 this.update(cx, |this, cx| {
5725 if this.pending_rename.is_some() {
5726 return;
5727 }
5728
5729 let buffer_id = cursor_position.buffer_id;
5730 let buffer = this.buffer.read(cx);
5731 if !buffer
5732 .text_anchor_for_position(cursor_position, cx)
5733 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5734 {
5735 return;
5736 }
5737
5738 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5739 let mut write_ranges = Vec::new();
5740 let mut read_ranges = Vec::new();
5741 for highlight in highlights {
5742 for (excerpt_id, excerpt_range) in
5743 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5744 {
5745 let start = highlight
5746 .range
5747 .start
5748 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5749 let end = highlight
5750 .range
5751 .end
5752 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5753 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5754 continue;
5755 }
5756
5757 let range = Anchor {
5758 buffer_id,
5759 excerpt_id,
5760 text_anchor: start,
5761 diff_base_anchor: None,
5762 }..Anchor {
5763 buffer_id,
5764 excerpt_id,
5765 text_anchor: end,
5766 diff_base_anchor: None,
5767 };
5768 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5769 write_ranges.push(range);
5770 } else {
5771 read_ranges.push(range);
5772 }
5773 }
5774 }
5775
5776 this.highlight_background::<DocumentHighlightRead>(
5777 &read_ranges,
5778 |theme| theme.editor_document_highlight_read_background,
5779 cx,
5780 );
5781 this.highlight_background::<DocumentHighlightWrite>(
5782 &write_ranges,
5783 |theme| theme.editor_document_highlight_write_background,
5784 cx,
5785 );
5786 cx.notify();
5787 })
5788 .log_err();
5789 }
5790 }));
5791 None
5792 }
5793
5794 fn prepare_highlight_query_from_selection(
5795 &mut self,
5796 cx: &mut Context<Editor>,
5797 ) -> Option<(String, Range<Anchor>)> {
5798 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5799 return None;
5800 }
5801 if !EditorSettings::get_global(cx).selection_highlight {
5802 return None;
5803 }
5804 if self.selections.count() != 1 || self.selections.line_mode {
5805 return None;
5806 }
5807 let selection = self.selections.newest::<Point>(cx);
5808 if selection.is_empty() || selection.start.row != selection.end.row {
5809 return None;
5810 }
5811 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5812 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5813 let query = multi_buffer_snapshot
5814 .text_for_range(selection_anchor_range.clone())
5815 .collect::<String>();
5816 if query.trim().is_empty() {
5817 return None;
5818 }
5819 Some((query, selection_anchor_range))
5820 }
5821
5822 fn update_selection_occurrence_highlights(
5823 &mut self,
5824 query_text: String,
5825 query_range: Range<Anchor>,
5826 multi_buffer_range_to_query: Range<Point>,
5827 use_debounce: bool,
5828 window: &mut Window,
5829 cx: &mut Context<Editor>,
5830 ) -> Task<()> {
5831 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5832 cx.spawn_in(window, async move |editor, cx| {
5833 if use_debounce {
5834 cx.background_executor()
5835 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5836 .await;
5837 }
5838 let match_task = cx.background_spawn(async move {
5839 let buffer_ranges = multi_buffer_snapshot
5840 .range_to_buffer_ranges(multi_buffer_range_to_query)
5841 .into_iter()
5842 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5843 let mut match_ranges = Vec::new();
5844 let Ok(regex) = project::search::SearchQuery::text(
5845 query_text.clone(),
5846 false,
5847 false,
5848 false,
5849 Default::default(),
5850 Default::default(),
5851 false,
5852 None,
5853 ) else {
5854 return Vec::default();
5855 };
5856 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5857 match_ranges.extend(
5858 regex
5859 .search(&buffer_snapshot, Some(search_range.clone()))
5860 .await
5861 .into_iter()
5862 .filter_map(|match_range| {
5863 let match_start = buffer_snapshot
5864 .anchor_after(search_range.start + match_range.start);
5865 let match_end = buffer_snapshot
5866 .anchor_before(search_range.start + match_range.end);
5867 let match_anchor_range = Anchor::range_in_buffer(
5868 excerpt_id,
5869 buffer_snapshot.remote_id(),
5870 match_start..match_end,
5871 );
5872 (match_anchor_range != query_range).then_some(match_anchor_range)
5873 }),
5874 );
5875 }
5876 match_ranges
5877 });
5878 let match_ranges = match_task.await;
5879 editor
5880 .update_in(cx, |editor, _, cx| {
5881 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5882 if !match_ranges.is_empty() {
5883 editor.highlight_background::<SelectedTextHighlight>(
5884 &match_ranges,
5885 |theme| theme.editor_document_highlight_bracket_background,
5886 cx,
5887 )
5888 }
5889 })
5890 .log_err();
5891 })
5892 }
5893
5894 fn refresh_selected_text_highlights(
5895 &mut self,
5896 on_buffer_edit: bool,
5897 window: &mut Window,
5898 cx: &mut Context<Editor>,
5899 ) {
5900 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5901 else {
5902 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5903 self.quick_selection_highlight_task.take();
5904 self.debounced_selection_highlight_task.take();
5905 return;
5906 };
5907 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5908 if on_buffer_edit
5909 || self
5910 .quick_selection_highlight_task
5911 .as_ref()
5912 .map_or(true, |(prev_anchor_range, _)| {
5913 prev_anchor_range != &query_range
5914 })
5915 {
5916 let multi_buffer_visible_start = self
5917 .scroll_manager
5918 .anchor()
5919 .anchor
5920 .to_point(&multi_buffer_snapshot);
5921 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5922 multi_buffer_visible_start
5923 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5924 Bias::Left,
5925 );
5926 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5927 self.quick_selection_highlight_task = Some((
5928 query_range.clone(),
5929 self.update_selection_occurrence_highlights(
5930 query_text.clone(),
5931 query_range.clone(),
5932 multi_buffer_visible_range,
5933 false,
5934 window,
5935 cx,
5936 ),
5937 ));
5938 }
5939 if on_buffer_edit
5940 || self
5941 .debounced_selection_highlight_task
5942 .as_ref()
5943 .map_or(true, |(prev_anchor_range, _)| {
5944 prev_anchor_range != &query_range
5945 })
5946 {
5947 let multi_buffer_start = multi_buffer_snapshot
5948 .anchor_before(0)
5949 .to_point(&multi_buffer_snapshot);
5950 let multi_buffer_end = multi_buffer_snapshot
5951 .anchor_after(multi_buffer_snapshot.len())
5952 .to_point(&multi_buffer_snapshot);
5953 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5954 self.debounced_selection_highlight_task = Some((
5955 query_range.clone(),
5956 self.update_selection_occurrence_highlights(
5957 query_text,
5958 query_range,
5959 multi_buffer_full_range,
5960 true,
5961 window,
5962 cx,
5963 ),
5964 ));
5965 }
5966 }
5967
5968 pub fn refresh_inline_completion(
5969 &mut self,
5970 debounce: bool,
5971 user_requested: bool,
5972 window: &mut Window,
5973 cx: &mut Context<Self>,
5974 ) -> Option<()> {
5975 let provider = self.edit_prediction_provider()?;
5976 let cursor = self.selections.newest_anchor().head();
5977 let (buffer, cursor_buffer_position) =
5978 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5979
5980 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5981 self.discard_inline_completion(false, cx);
5982 return None;
5983 }
5984
5985 if !user_requested
5986 && (!self.should_show_edit_predictions()
5987 || !self.is_focused(window)
5988 || buffer.read(cx).is_empty())
5989 {
5990 self.discard_inline_completion(false, cx);
5991 return None;
5992 }
5993
5994 self.update_visible_inline_completion(window, cx);
5995 provider.refresh(
5996 self.project.clone(),
5997 buffer,
5998 cursor_buffer_position,
5999 debounce,
6000 cx,
6001 );
6002 Some(())
6003 }
6004
6005 fn show_edit_predictions_in_menu(&self) -> bool {
6006 match self.edit_prediction_settings {
6007 EditPredictionSettings::Disabled => false,
6008 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
6009 }
6010 }
6011
6012 pub fn edit_predictions_enabled(&self) -> bool {
6013 match self.edit_prediction_settings {
6014 EditPredictionSettings::Disabled => false,
6015 EditPredictionSettings::Enabled { .. } => true,
6016 }
6017 }
6018
6019 fn edit_prediction_requires_modifier(&self) -> bool {
6020 match self.edit_prediction_settings {
6021 EditPredictionSettings::Disabled => false,
6022 EditPredictionSettings::Enabled {
6023 preview_requires_modifier,
6024 ..
6025 } => preview_requires_modifier,
6026 }
6027 }
6028
6029 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
6030 if self.edit_prediction_provider.is_none() {
6031 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6032 } else {
6033 let selection = self.selections.newest_anchor();
6034 let cursor = selection.head();
6035
6036 if let Some((buffer, cursor_buffer_position)) =
6037 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
6038 {
6039 self.edit_prediction_settings =
6040 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6041 }
6042 }
6043 }
6044
6045 fn edit_prediction_settings_at_position(
6046 &self,
6047 buffer: &Entity<Buffer>,
6048 buffer_position: language::Anchor,
6049 cx: &App,
6050 ) -> EditPredictionSettings {
6051 if !self.mode.is_full()
6052 || !self.show_inline_completions_override.unwrap_or(true)
6053 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
6054 {
6055 return EditPredictionSettings::Disabled;
6056 }
6057
6058 let buffer = buffer.read(cx);
6059
6060 let file = buffer.file();
6061
6062 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
6063 return EditPredictionSettings::Disabled;
6064 };
6065
6066 let by_provider = matches!(
6067 self.menu_inline_completions_policy,
6068 MenuInlineCompletionsPolicy::ByProvider
6069 );
6070
6071 let show_in_menu = by_provider
6072 && self
6073 .edit_prediction_provider
6074 .as_ref()
6075 .map_or(false, |provider| {
6076 provider.provider.show_completions_in_menu()
6077 });
6078
6079 let preview_requires_modifier =
6080 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
6081
6082 EditPredictionSettings::Enabled {
6083 show_in_menu,
6084 preview_requires_modifier,
6085 }
6086 }
6087
6088 fn should_show_edit_predictions(&self) -> bool {
6089 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
6090 }
6091
6092 pub fn edit_prediction_preview_is_active(&self) -> bool {
6093 matches!(
6094 self.edit_prediction_preview,
6095 EditPredictionPreview::Active { .. }
6096 )
6097 }
6098
6099 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
6100 let cursor = self.selections.newest_anchor().head();
6101 if let Some((buffer, cursor_position)) =
6102 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
6103 {
6104 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
6105 } else {
6106 false
6107 }
6108 }
6109
6110 pub fn supports_minimap(&self) -> bool {
6111 self.mode.is_full()
6112 }
6113
6114 fn edit_predictions_enabled_in_buffer(
6115 &self,
6116 buffer: &Entity<Buffer>,
6117 buffer_position: language::Anchor,
6118 cx: &App,
6119 ) -> bool {
6120 maybe!({
6121 if self.read_only(cx) {
6122 return Some(false);
6123 }
6124 let provider = self.edit_prediction_provider()?;
6125 if !provider.is_enabled(&buffer, buffer_position, cx) {
6126 return Some(false);
6127 }
6128 let buffer = buffer.read(cx);
6129 let Some(file) = buffer.file() else {
6130 return Some(true);
6131 };
6132 let settings = all_language_settings(Some(file), cx);
6133 Some(settings.edit_predictions_enabled_for_file(file, cx))
6134 })
6135 .unwrap_or(false)
6136 }
6137
6138 fn cycle_inline_completion(
6139 &mut self,
6140 direction: Direction,
6141 window: &mut Window,
6142 cx: &mut Context<Self>,
6143 ) -> Option<()> {
6144 let provider = self.edit_prediction_provider()?;
6145 let cursor = self.selections.newest_anchor().head();
6146 let (buffer, cursor_buffer_position) =
6147 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6148 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
6149 return None;
6150 }
6151
6152 provider.cycle(buffer, cursor_buffer_position, direction, cx);
6153 self.update_visible_inline_completion(window, cx);
6154
6155 Some(())
6156 }
6157
6158 pub fn show_inline_completion(
6159 &mut self,
6160 _: &ShowEditPrediction,
6161 window: &mut Window,
6162 cx: &mut Context<Self>,
6163 ) {
6164 if !self.has_active_inline_completion() {
6165 self.refresh_inline_completion(false, true, window, cx);
6166 return;
6167 }
6168
6169 self.update_visible_inline_completion(window, cx);
6170 }
6171
6172 pub fn display_cursor_names(
6173 &mut self,
6174 _: &DisplayCursorNames,
6175 window: &mut Window,
6176 cx: &mut Context<Self>,
6177 ) {
6178 self.show_cursor_names(window, cx);
6179 }
6180
6181 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6182 self.show_cursor_names = true;
6183 cx.notify();
6184 cx.spawn_in(window, async move |this, cx| {
6185 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
6186 this.update(cx, |this, cx| {
6187 this.show_cursor_names = false;
6188 cx.notify()
6189 })
6190 .ok()
6191 })
6192 .detach();
6193 }
6194
6195 pub fn next_edit_prediction(
6196 &mut self,
6197 _: &NextEditPrediction,
6198 window: &mut Window,
6199 cx: &mut Context<Self>,
6200 ) {
6201 if self.has_active_inline_completion() {
6202 self.cycle_inline_completion(Direction::Next, window, cx);
6203 } else {
6204 let is_copilot_disabled = self
6205 .refresh_inline_completion(false, true, window, cx)
6206 .is_none();
6207 if is_copilot_disabled {
6208 cx.propagate();
6209 }
6210 }
6211 }
6212
6213 pub fn previous_edit_prediction(
6214 &mut self,
6215 _: &PreviousEditPrediction,
6216 window: &mut Window,
6217 cx: &mut Context<Self>,
6218 ) {
6219 if self.has_active_inline_completion() {
6220 self.cycle_inline_completion(Direction::Prev, window, cx);
6221 } else {
6222 let is_copilot_disabled = self
6223 .refresh_inline_completion(false, true, window, cx)
6224 .is_none();
6225 if is_copilot_disabled {
6226 cx.propagate();
6227 }
6228 }
6229 }
6230
6231 pub fn accept_edit_prediction(
6232 &mut self,
6233 _: &AcceptEditPrediction,
6234 window: &mut Window,
6235 cx: &mut Context<Self>,
6236 ) {
6237 if self.show_edit_predictions_in_menu() {
6238 self.hide_context_menu(window, cx);
6239 }
6240
6241 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6242 return;
6243 };
6244
6245 self.report_inline_completion_event(
6246 active_inline_completion.completion_id.clone(),
6247 true,
6248 cx,
6249 );
6250
6251 match &active_inline_completion.completion {
6252 InlineCompletion::Move { target, .. } => {
6253 let target = *target;
6254
6255 if let Some(position_map) = &self.last_position_map {
6256 if position_map
6257 .visible_row_range
6258 .contains(&target.to_display_point(&position_map.snapshot).row())
6259 || !self.edit_prediction_requires_modifier()
6260 {
6261 self.unfold_ranges(&[target..target], true, false, cx);
6262 // Note that this is also done in vim's handler of the Tab action.
6263 self.change_selections(
6264 Some(Autoscroll::newest()),
6265 window,
6266 cx,
6267 |selections| {
6268 selections.select_anchor_ranges([target..target]);
6269 },
6270 );
6271 self.clear_row_highlights::<EditPredictionPreview>();
6272
6273 self.edit_prediction_preview
6274 .set_previous_scroll_position(None);
6275 } else {
6276 self.edit_prediction_preview
6277 .set_previous_scroll_position(Some(
6278 position_map.snapshot.scroll_anchor,
6279 ));
6280
6281 self.highlight_rows::<EditPredictionPreview>(
6282 target..target,
6283 cx.theme().colors().editor_highlighted_line_background,
6284 RowHighlightOptions {
6285 autoscroll: true,
6286 ..Default::default()
6287 },
6288 cx,
6289 );
6290 self.request_autoscroll(Autoscroll::fit(), cx);
6291 }
6292 }
6293 }
6294 InlineCompletion::Edit { edits, .. } => {
6295 if let Some(provider) = self.edit_prediction_provider() {
6296 provider.accept(cx);
6297 }
6298
6299 let snapshot = self.buffer.read(cx).snapshot(cx);
6300 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
6301
6302 self.buffer.update(cx, |buffer, cx| {
6303 buffer.edit(edits.iter().cloned(), None, cx)
6304 });
6305
6306 self.change_selections(None, window, cx, |s| {
6307 s.select_anchor_ranges([last_edit_end..last_edit_end])
6308 });
6309
6310 self.update_visible_inline_completion(window, cx);
6311 if self.active_inline_completion.is_none() {
6312 self.refresh_inline_completion(true, true, window, cx);
6313 }
6314
6315 cx.notify();
6316 }
6317 }
6318
6319 self.edit_prediction_requires_modifier_in_indent_conflict = false;
6320 }
6321
6322 pub fn accept_partial_inline_completion(
6323 &mut self,
6324 _: &AcceptPartialEditPrediction,
6325 window: &mut Window,
6326 cx: &mut Context<Self>,
6327 ) {
6328 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
6329 return;
6330 };
6331 if self.selections.count() != 1 {
6332 return;
6333 }
6334
6335 self.report_inline_completion_event(
6336 active_inline_completion.completion_id.clone(),
6337 true,
6338 cx,
6339 );
6340
6341 match &active_inline_completion.completion {
6342 InlineCompletion::Move { target, .. } => {
6343 let target = *target;
6344 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6345 selections.select_anchor_ranges([target..target]);
6346 });
6347 }
6348 InlineCompletion::Edit { edits, .. } => {
6349 // Find an insertion that starts at the cursor position.
6350 let snapshot = self.buffer.read(cx).snapshot(cx);
6351 let cursor_offset = self.selections.newest::<usize>(cx).head();
6352 let insertion = edits.iter().find_map(|(range, text)| {
6353 let range = range.to_offset(&snapshot);
6354 if range.is_empty() && range.start == cursor_offset {
6355 Some(text)
6356 } else {
6357 None
6358 }
6359 });
6360
6361 if let Some(text) = insertion {
6362 let mut partial_completion = text
6363 .chars()
6364 .by_ref()
6365 .take_while(|c| c.is_alphabetic())
6366 .collect::<String>();
6367 if partial_completion.is_empty() {
6368 partial_completion = text
6369 .chars()
6370 .by_ref()
6371 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6372 .collect::<String>();
6373 }
6374
6375 cx.emit(EditorEvent::InputHandled {
6376 utf16_range_to_replace: None,
6377 text: partial_completion.clone().into(),
6378 });
6379
6380 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6381
6382 self.refresh_inline_completion(true, true, window, cx);
6383 cx.notify();
6384 } else {
6385 self.accept_edit_prediction(&Default::default(), window, cx);
6386 }
6387 }
6388 }
6389 }
6390
6391 fn discard_inline_completion(
6392 &mut self,
6393 should_report_inline_completion_event: bool,
6394 cx: &mut Context<Self>,
6395 ) -> bool {
6396 if should_report_inline_completion_event {
6397 let completion_id = self
6398 .active_inline_completion
6399 .as_ref()
6400 .and_then(|active_completion| active_completion.completion_id.clone());
6401
6402 self.report_inline_completion_event(completion_id, false, cx);
6403 }
6404
6405 if let Some(provider) = self.edit_prediction_provider() {
6406 provider.discard(cx);
6407 }
6408
6409 self.take_active_inline_completion(cx)
6410 }
6411
6412 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6413 let Some(provider) = self.edit_prediction_provider() else {
6414 return;
6415 };
6416
6417 let Some((_, buffer, _)) = self
6418 .buffer
6419 .read(cx)
6420 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6421 else {
6422 return;
6423 };
6424
6425 let extension = buffer
6426 .read(cx)
6427 .file()
6428 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6429
6430 let event_type = match accepted {
6431 true => "Edit Prediction Accepted",
6432 false => "Edit Prediction Discarded",
6433 };
6434 telemetry::event!(
6435 event_type,
6436 provider = provider.name(),
6437 prediction_id = id,
6438 suggestion_accepted = accepted,
6439 file_extension = extension,
6440 );
6441 }
6442
6443 pub fn has_active_inline_completion(&self) -> bool {
6444 self.active_inline_completion.is_some()
6445 }
6446
6447 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6448 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6449 return false;
6450 };
6451
6452 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6453 self.clear_highlights::<InlineCompletionHighlight>(cx);
6454 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6455 true
6456 }
6457
6458 /// Returns true when we're displaying the edit prediction popover below the cursor
6459 /// like we are not previewing and the LSP autocomplete menu is visible
6460 /// or we are in `when_holding_modifier` mode.
6461 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6462 if self.edit_prediction_preview_is_active()
6463 || !self.show_edit_predictions_in_menu()
6464 || !self.edit_predictions_enabled()
6465 {
6466 return false;
6467 }
6468
6469 if self.has_visible_completions_menu() {
6470 return true;
6471 }
6472
6473 has_completion && self.edit_prediction_requires_modifier()
6474 }
6475
6476 fn handle_modifiers_changed(
6477 &mut self,
6478 modifiers: Modifiers,
6479 position_map: &PositionMap,
6480 window: &mut Window,
6481 cx: &mut Context<Self>,
6482 ) {
6483 if self.show_edit_predictions_in_menu() {
6484 self.update_edit_prediction_preview(&modifiers, window, cx);
6485 }
6486
6487 self.update_selection_mode(&modifiers, position_map, window, cx);
6488
6489 let mouse_position = window.mouse_position();
6490 if !position_map.text_hitbox.is_hovered(window) {
6491 return;
6492 }
6493
6494 self.update_hovered_link(
6495 position_map.point_for_position(mouse_position),
6496 &position_map.snapshot,
6497 modifiers,
6498 window,
6499 cx,
6500 )
6501 }
6502
6503 fn update_selection_mode(
6504 &mut self,
6505 modifiers: &Modifiers,
6506 position_map: &PositionMap,
6507 window: &mut Window,
6508 cx: &mut Context<Self>,
6509 ) {
6510 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6511 return;
6512 }
6513
6514 let mouse_position = window.mouse_position();
6515 let point_for_position = position_map.point_for_position(mouse_position);
6516 let position = point_for_position.previous_valid;
6517
6518 self.select(
6519 SelectPhase::BeginColumnar {
6520 position,
6521 reset: false,
6522 goal_column: point_for_position.exact_unclipped.column(),
6523 },
6524 window,
6525 cx,
6526 );
6527 }
6528
6529 fn update_edit_prediction_preview(
6530 &mut self,
6531 modifiers: &Modifiers,
6532 window: &mut Window,
6533 cx: &mut Context<Self>,
6534 ) {
6535 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6536 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6537 return;
6538 };
6539
6540 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6541 if matches!(
6542 self.edit_prediction_preview,
6543 EditPredictionPreview::Inactive { .. }
6544 ) {
6545 self.edit_prediction_preview = EditPredictionPreview::Active {
6546 previous_scroll_position: None,
6547 since: Instant::now(),
6548 };
6549
6550 self.update_visible_inline_completion(window, cx);
6551 cx.notify();
6552 }
6553 } else if let EditPredictionPreview::Active {
6554 previous_scroll_position,
6555 since,
6556 } = self.edit_prediction_preview
6557 {
6558 if let (Some(previous_scroll_position), Some(position_map)) =
6559 (previous_scroll_position, self.last_position_map.as_ref())
6560 {
6561 self.set_scroll_position(
6562 previous_scroll_position
6563 .scroll_position(&position_map.snapshot.display_snapshot),
6564 window,
6565 cx,
6566 );
6567 }
6568
6569 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6570 released_too_fast: since.elapsed() < Duration::from_millis(200),
6571 };
6572 self.clear_row_highlights::<EditPredictionPreview>();
6573 self.update_visible_inline_completion(window, cx);
6574 cx.notify();
6575 }
6576 }
6577
6578 fn update_visible_inline_completion(
6579 &mut self,
6580 _window: &mut Window,
6581 cx: &mut Context<Self>,
6582 ) -> Option<()> {
6583 let selection = self.selections.newest_anchor();
6584 let cursor = selection.head();
6585 let multibuffer = self.buffer.read(cx).snapshot(cx);
6586 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6587 let excerpt_id = cursor.excerpt_id;
6588
6589 let show_in_menu = self.show_edit_predictions_in_menu();
6590 let completions_menu_has_precedence = !show_in_menu
6591 && (self.context_menu.borrow().is_some()
6592 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6593
6594 if completions_menu_has_precedence
6595 || !offset_selection.is_empty()
6596 || self
6597 .active_inline_completion
6598 .as_ref()
6599 .map_or(false, |completion| {
6600 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6601 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6602 !invalidation_range.contains(&offset_selection.head())
6603 })
6604 {
6605 self.discard_inline_completion(false, cx);
6606 return None;
6607 }
6608
6609 self.take_active_inline_completion(cx);
6610 let Some(provider) = self.edit_prediction_provider() else {
6611 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6612 return None;
6613 };
6614
6615 let (buffer, cursor_buffer_position) =
6616 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6617
6618 self.edit_prediction_settings =
6619 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6620
6621 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6622
6623 if self.edit_prediction_indent_conflict {
6624 let cursor_point = cursor.to_point(&multibuffer);
6625
6626 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6627
6628 if let Some((_, indent)) = indents.iter().next() {
6629 if indent.len == cursor_point.column {
6630 self.edit_prediction_indent_conflict = false;
6631 }
6632 }
6633 }
6634
6635 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6636 let edits = inline_completion
6637 .edits
6638 .into_iter()
6639 .flat_map(|(range, new_text)| {
6640 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6641 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6642 Some((start..end, new_text))
6643 })
6644 .collect::<Vec<_>>();
6645 if edits.is_empty() {
6646 return None;
6647 }
6648
6649 let first_edit_start = edits.first().unwrap().0.start;
6650 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6651 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6652
6653 let last_edit_end = edits.last().unwrap().0.end;
6654 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6655 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6656
6657 let cursor_row = cursor.to_point(&multibuffer).row;
6658
6659 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6660
6661 let mut inlay_ids = Vec::new();
6662 let invalidation_row_range;
6663 let move_invalidation_row_range = if cursor_row < edit_start_row {
6664 Some(cursor_row..edit_end_row)
6665 } else if cursor_row > edit_end_row {
6666 Some(edit_start_row..cursor_row)
6667 } else {
6668 None
6669 };
6670 let is_move =
6671 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6672 let completion = if is_move {
6673 invalidation_row_range =
6674 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6675 let target = first_edit_start;
6676 InlineCompletion::Move { target, snapshot }
6677 } else {
6678 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6679 && !self.inline_completions_hidden_for_vim_mode;
6680
6681 if show_completions_in_buffer {
6682 if edits
6683 .iter()
6684 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6685 {
6686 let mut inlays = Vec::new();
6687 for (range, new_text) in &edits {
6688 let inlay = Inlay::inline_completion(
6689 post_inc(&mut self.next_inlay_id),
6690 range.start,
6691 new_text.as_str(),
6692 );
6693 inlay_ids.push(inlay.id);
6694 inlays.push(inlay);
6695 }
6696
6697 self.splice_inlays(&[], inlays, cx);
6698 } else {
6699 let background_color = cx.theme().status().deleted_background;
6700 self.highlight_text::<InlineCompletionHighlight>(
6701 edits.iter().map(|(range, _)| range.clone()).collect(),
6702 HighlightStyle {
6703 background_color: Some(background_color),
6704 ..Default::default()
6705 },
6706 cx,
6707 );
6708 }
6709 }
6710
6711 invalidation_row_range = edit_start_row..edit_end_row;
6712
6713 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6714 if provider.show_tab_accept_marker() {
6715 EditDisplayMode::TabAccept
6716 } else {
6717 EditDisplayMode::Inline
6718 }
6719 } else {
6720 EditDisplayMode::DiffPopover
6721 };
6722
6723 InlineCompletion::Edit {
6724 edits,
6725 edit_preview: inline_completion.edit_preview,
6726 display_mode,
6727 snapshot,
6728 }
6729 };
6730
6731 let invalidation_range = multibuffer
6732 .anchor_before(Point::new(invalidation_row_range.start, 0))
6733 ..multibuffer.anchor_after(Point::new(
6734 invalidation_row_range.end,
6735 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6736 ));
6737
6738 self.stale_inline_completion_in_menu = None;
6739 self.active_inline_completion = Some(InlineCompletionState {
6740 inlay_ids,
6741 completion,
6742 completion_id: inline_completion.id,
6743 invalidation_range,
6744 });
6745
6746 cx.notify();
6747
6748 Some(())
6749 }
6750
6751 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6752 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6753 }
6754
6755 fn clear_tasks(&mut self) {
6756 self.tasks.clear()
6757 }
6758
6759 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6760 if self.tasks.insert(key, value).is_some() {
6761 // This case should hopefully be rare, but just in case...
6762 log::error!(
6763 "multiple different run targets found on a single line, only the last target will be rendered"
6764 )
6765 }
6766 }
6767
6768 /// Get all display points of breakpoints that will be rendered within editor
6769 ///
6770 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6771 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6772 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6773 fn active_breakpoints(
6774 &self,
6775 range: Range<DisplayRow>,
6776 window: &mut Window,
6777 cx: &mut Context<Self>,
6778 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6779 let mut breakpoint_display_points = HashMap::default();
6780
6781 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6782 return breakpoint_display_points;
6783 };
6784
6785 let snapshot = self.snapshot(window, cx);
6786
6787 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6788 let Some(project) = self.project.as_ref() else {
6789 return breakpoint_display_points;
6790 };
6791
6792 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6793 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6794
6795 for (buffer_snapshot, range, excerpt_id) in
6796 multi_buffer_snapshot.range_to_buffer_ranges(range)
6797 {
6798 let Some(buffer) = project.read_with(cx, |this, cx| {
6799 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6800 }) else {
6801 continue;
6802 };
6803 let breakpoints = breakpoint_store.read(cx).breakpoints(
6804 &buffer,
6805 Some(
6806 buffer_snapshot.anchor_before(range.start)
6807 ..buffer_snapshot.anchor_after(range.end),
6808 ),
6809 buffer_snapshot,
6810 cx,
6811 );
6812 for (anchor, breakpoint) in breakpoints {
6813 let multi_buffer_anchor =
6814 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6815 let position = multi_buffer_anchor
6816 .to_point(&multi_buffer_snapshot)
6817 .to_display_point(&snapshot);
6818
6819 breakpoint_display_points
6820 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6821 }
6822 }
6823
6824 breakpoint_display_points
6825 }
6826
6827 fn breakpoint_context_menu(
6828 &self,
6829 anchor: Anchor,
6830 window: &mut Window,
6831 cx: &mut Context<Self>,
6832 ) -> Entity<ui::ContextMenu> {
6833 let weak_editor = cx.weak_entity();
6834 let focus_handle = self.focus_handle(cx);
6835
6836 let row = self
6837 .buffer
6838 .read(cx)
6839 .snapshot(cx)
6840 .summary_for_anchor::<Point>(&anchor)
6841 .row;
6842
6843 let breakpoint = self
6844 .breakpoint_at_row(row, window, cx)
6845 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6846
6847 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6848 "Edit Log Breakpoint"
6849 } else {
6850 "Set Log Breakpoint"
6851 };
6852
6853 let condition_breakpoint_msg = if breakpoint
6854 .as_ref()
6855 .is_some_and(|bp| bp.1.condition.is_some())
6856 {
6857 "Edit Condition Breakpoint"
6858 } else {
6859 "Set Condition Breakpoint"
6860 };
6861
6862 let hit_condition_breakpoint_msg = if breakpoint
6863 .as_ref()
6864 .is_some_and(|bp| bp.1.hit_condition.is_some())
6865 {
6866 "Edit Hit Condition Breakpoint"
6867 } else {
6868 "Set Hit Condition Breakpoint"
6869 };
6870
6871 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6872 "Unset Breakpoint"
6873 } else {
6874 "Set Breakpoint"
6875 };
6876
6877 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6878 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6879
6880 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6881 BreakpointState::Enabled => Some("Disable"),
6882 BreakpointState::Disabled => Some("Enable"),
6883 });
6884
6885 let (anchor, breakpoint) =
6886 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6887
6888 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6889 menu.on_blur_subscription(Subscription::new(|| {}))
6890 .context(focus_handle)
6891 .when(run_to_cursor, |this| {
6892 let weak_editor = weak_editor.clone();
6893 this.entry("Run to cursor", None, move |window, cx| {
6894 weak_editor
6895 .update(cx, |editor, cx| {
6896 editor.change_selections(None, window, cx, |s| {
6897 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6898 });
6899 })
6900 .ok();
6901
6902 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6903 })
6904 .separator()
6905 })
6906 .when_some(toggle_state_msg, |this, msg| {
6907 this.entry(msg, None, {
6908 let weak_editor = weak_editor.clone();
6909 let breakpoint = breakpoint.clone();
6910 move |_window, cx| {
6911 weak_editor
6912 .update(cx, |this, cx| {
6913 this.edit_breakpoint_at_anchor(
6914 anchor,
6915 breakpoint.as_ref().clone(),
6916 BreakpointEditAction::InvertState,
6917 cx,
6918 );
6919 })
6920 .log_err();
6921 }
6922 })
6923 })
6924 .entry(set_breakpoint_msg, None, {
6925 let weak_editor = weak_editor.clone();
6926 let breakpoint = breakpoint.clone();
6927 move |_window, cx| {
6928 weak_editor
6929 .update(cx, |this, cx| {
6930 this.edit_breakpoint_at_anchor(
6931 anchor,
6932 breakpoint.as_ref().clone(),
6933 BreakpointEditAction::Toggle,
6934 cx,
6935 );
6936 })
6937 .log_err();
6938 }
6939 })
6940 .entry(log_breakpoint_msg, None, {
6941 let breakpoint = breakpoint.clone();
6942 let weak_editor = weak_editor.clone();
6943 move |window, cx| {
6944 weak_editor
6945 .update(cx, |this, cx| {
6946 this.add_edit_breakpoint_block(
6947 anchor,
6948 breakpoint.as_ref(),
6949 BreakpointPromptEditAction::Log,
6950 window,
6951 cx,
6952 );
6953 })
6954 .log_err();
6955 }
6956 })
6957 .entry(condition_breakpoint_msg, None, {
6958 let breakpoint = breakpoint.clone();
6959 let weak_editor = weak_editor.clone();
6960 move |window, cx| {
6961 weak_editor
6962 .update(cx, |this, cx| {
6963 this.add_edit_breakpoint_block(
6964 anchor,
6965 breakpoint.as_ref(),
6966 BreakpointPromptEditAction::Condition,
6967 window,
6968 cx,
6969 );
6970 })
6971 .log_err();
6972 }
6973 })
6974 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6975 weak_editor
6976 .update(cx, |this, cx| {
6977 this.add_edit_breakpoint_block(
6978 anchor,
6979 breakpoint.as_ref(),
6980 BreakpointPromptEditAction::HitCondition,
6981 window,
6982 cx,
6983 );
6984 })
6985 .log_err();
6986 })
6987 })
6988 }
6989
6990 fn render_breakpoint(
6991 &self,
6992 position: Anchor,
6993 row: DisplayRow,
6994 breakpoint: &Breakpoint,
6995 cx: &mut Context<Self>,
6996 ) -> IconButton {
6997 // Is it a breakpoint that shows up when hovering over gutter?
6998 let (is_phantom, collides_with_existing) = self.gutter_breakpoint_indicator.0.map_or(
6999 (false, false),
7000 |PhantomBreakpointIndicator {
7001 is_active,
7002 display_row,
7003 collides_with_existing_breakpoint,
7004 }| {
7005 (
7006 is_active && display_row == row,
7007 collides_with_existing_breakpoint,
7008 )
7009 },
7010 );
7011
7012 let (color, icon) = {
7013 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
7014 (false, false) => ui::IconName::DebugBreakpoint,
7015 (true, false) => ui::IconName::DebugLogBreakpoint,
7016 (false, true) => ui::IconName::DebugDisabledBreakpoint,
7017 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
7018 };
7019
7020 let color = if is_phantom {
7021 Color::Hint
7022 } else {
7023 Color::Debugger
7024 };
7025
7026 (color, icon)
7027 };
7028
7029 let breakpoint = Arc::from(breakpoint.clone());
7030
7031 let alt_as_text = gpui::Keystroke {
7032 modifiers: Modifiers::secondary_key(),
7033 ..Default::default()
7034 };
7035 let primary_action_text = if breakpoint.is_disabled() {
7036 "enable"
7037 } else if is_phantom && !collides_with_existing {
7038 "set"
7039 } else {
7040 "unset"
7041 };
7042 let mut primary_text = format!("Click to {primary_action_text}");
7043 if collides_with_existing && !breakpoint.is_disabled() {
7044 use std::fmt::Write;
7045 write!(primary_text, ", {alt_as_text}-click to disable").ok();
7046 }
7047 let primary_text = SharedString::from(primary_text);
7048 let focus_handle = self.focus_handle.clone();
7049 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
7050 .icon_size(IconSize::XSmall)
7051 .size(ui::ButtonSize::None)
7052 .icon_color(color)
7053 .style(ButtonStyle::Transparent)
7054 .on_click(cx.listener({
7055 let breakpoint = breakpoint.clone();
7056
7057 move |editor, event: &ClickEvent, window, cx| {
7058 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
7059 BreakpointEditAction::InvertState
7060 } else {
7061 BreakpointEditAction::Toggle
7062 };
7063
7064 window.focus(&editor.focus_handle(cx));
7065 editor.edit_breakpoint_at_anchor(
7066 position,
7067 breakpoint.as_ref().clone(),
7068 edit_action,
7069 cx,
7070 );
7071 }
7072 }))
7073 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7074 editor.set_breakpoint_context_menu(
7075 row,
7076 Some(position),
7077 event.down.position,
7078 window,
7079 cx,
7080 );
7081 }))
7082 .tooltip(move |window, cx| {
7083 Tooltip::with_meta_in(
7084 primary_text.clone(),
7085 None,
7086 "Right-click for more options",
7087 &focus_handle,
7088 window,
7089 cx,
7090 )
7091 })
7092 }
7093
7094 fn build_tasks_context(
7095 project: &Entity<Project>,
7096 buffer: &Entity<Buffer>,
7097 buffer_row: u32,
7098 tasks: &Arc<RunnableTasks>,
7099 cx: &mut Context<Self>,
7100 ) -> Task<Option<task::TaskContext>> {
7101 let position = Point::new(buffer_row, tasks.column);
7102 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
7103 let location = Location {
7104 buffer: buffer.clone(),
7105 range: range_start..range_start,
7106 };
7107 // Fill in the environmental variables from the tree-sitter captures
7108 let mut captured_task_variables = TaskVariables::default();
7109 for (capture_name, value) in tasks.extra_variables.clone() {
7110 captured_task_variables.insert(
7111 task::VariableName::Custom(capture_name.into()),
7112 value.clone(),
7113 );
7114 }
7115 project.update(cx, |project, cx| {
7116 project.task_store().update(cx, |task_store, cx| {
7117 task_store.task_context_for_location(captured_task_variables, location, cx)
7118 })
7119 })
7120 }
7121
7122 pub fn spawn_nearest_task(
7123 &mut self,
7124 action: &SpawnNearestTask,
7125 window: &mut Window,
7126 cx: &mut Context<Self>,
7127 ) {
7128 let Some((workspace, _)) = self.workspace.clone() else {
7129 return;
7130 };
7131 let Some(project) = self.project.clone() else {
7132 return;
7133 };
7134
7135 // Try to find a closest, enclosing node using tree-sitter that has a
7136 // task
7137 let Some((buffer, buffer_row, tasks)) = self
7138 .find_enclosing_node_task(cx)
7139 // Or find the task that's closest in row-distance.
7140 .or_else(|| self.find_closest_task(cx))
7141 else {
7142 return;
7143 };
7144
7145 let reveal_strategy = action.reveal;
7146 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
7147 cx.spawn_in(window, async move |_, cx| {
7148 let context = task_context.await?;
7149 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
7150
7151 let resolved = &mut resolved_task.resolved;
7152 resolved.reveal = reveal_strategy;
7153
7154 workspace
7155 .update_in(cx, |workspace, window, cx| {
7156 workspace.schedule_resolved_task(
7157 task_source_kind,
7158 resolved_task,
7159 false,
7160 window,
7161 cx,
7162 );
7163 })
7164 .ok()
7165 })
7166 .detach();
7167 }
7168
7169 fn find_closest_task(
7170 &mut self,
7171 cx: &mut Context<Self>,
7172 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7173 let cursor_row = self.selections.newest_adjusted(cx).head().row;
7174
7175 let ((buffer_id, row), tasks) = self
7176 .tasks
7177 .iter()
7178 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
7179
7180 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
7181 let tasks = Arc::new(tasks.to_owned());
7182 Some((buffer, *row, tasks))
7183 }
7184
7185 fn find_enclosing_node_task(
7186 &mut self,
7187 cx: &mut Context<Self>,
7188 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
7189 let snapshot = self.buffer.read(cx).snapshot(cx);
7190 let offset = self.selections.newest::<usize>(cx).head();
7191 let excerpt = snapshot.excerpt_containing(offset..offset)?;
7192 let buffer_id = excerpt.buffer().remote_id();
7193
7194 let layer = excerpt.buffer().syntax_layer_at(offset)?;
7195 let mut cursor = layer.node().walk();
7196
7197 while cursor.goto_first_child_for_byte(offset).is_some() {
7198 if cursor.node().end_byte() == offset {
7199 cursor.goto_next_sibling();
7200 }
7201 }
7202
7203 // Ascend to the smallest ancestor that contains the range and has a task.
7204 loop {
7205 let node = cursor.node();
7206 let node_range = node.byte_range();
7207 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
7208
7209 // Check if this node contains our offset
7210 if node_range.start <= offset && node_range.end >= offset {
7211 // If it contains offset, check for task
7212 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
7213 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
7214 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
7215 }
7216 }
7217
7218 if !cursor.goto_parent() {
7219 break;
7220 }
7221 }
7222 None
7223 }
7224
7225 fn render_run_indicator(
7226 &self,
7227 _style: &EditorStyle,
7228 is_active: bool,
7229 row: DisplayRow,
7230 breakpoint: Option<(Anchor, Breakpoint)>,
7231 cx: &mut Context<Self>,
7232 ) -> IconButton {
7233 let color = Color::Muted;
7234 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
7235
7236 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
7237 .shape(ui::IconButtonShape::Square)
7238 .icon_size(IconSize::XSmall)
7239 .icon_color(color)
7240 .toggle_state(is_active)
7241 .on_click(cx.listener(move |editor, e: &ClickEvent, window, cx| {
7242 let quick_launch = e.down.button == MouseButton::Left;
7243 window.focus(&editor.focus_handle(cx));
7244 editor.toggle_code_actions(
7245 &ToggleCodeActions {
7246 deployed_from_indicator: Some(row),
7247 quick_launch,
7248 },
7249 window,
7250 cx,
7251 );
7252 }))
7253 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
7254 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
7255 }))
7256 }
7257
7258 pub fn context_menu_visible(&self) -> bool {
7259 !self.edit_prediction_preview_is_active()
7260 && self
7261 .context_menu
7262 .borrow()
7263 .as_ref()
7264 .map_or(false, |menu| menu.visible())
7265 }
7266
7267 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
7268 self.context_menu
7269 .borrow()
7270 .as_ref()
7271 .map(|menu| menu.origin())
7272 }
7273
7274 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
7275 self.context_menu_options = Some(options);
7276 }
7277
7278 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
7279 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
7280
7281 fn render_edit_prediction_popover(
7282 &mut self,
7283 text_bounds: &Bounds<Pixels>,
7284 content_origin: gpui::Point<Pixels>,
7285 right_margin: Pixels,
7286 editor_snapshot: &EditorSnapshot,
7287 visible_row_range: Range<DisplayRow>,
7288 scroll_top: f32,
7289 scroll_bottom: f32,
7290 line_layouts: &[LineWithInvisibles],
7291 line_height: Pixels,
7292 scroll_pixel_position: gpui::Point<Pixels>,
7293 newest_selection_head: Option<DisplayPoint>,
7294 editor_width: Pixels,
7295 style: &EditorStyle,
7296 window: &mut Window,
7297 cx: &mut App,
7298 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7299 if self.mode().is_minimap() {
7300 return None;
7301 }
7302 let active_inline_completion = self.active_inline_completion.as_ref()?;
7303
7304 if self.edit_prediction_visible_in_cursor_popover(true) {
7305 return None;
7306 }
7307
7308 match &active_inline_completion.completion {
7309 InlineCompletion::Move { target, .. } => {
7310 let target_display_point = target.to_display_point(editor_snapshot);
7311
7312 if self.edit_prediction_requires_modifier() {
7313 if !self.edit_prediction_preview_is_active() {
7314 return None;
7315 }
7316
7317 self.render_edit_prediction_modifier_jump_popover(
7318 text_bounds,
7319 content_origin,
7320 visible_row_range,
7321 line_layouts,
7322 line_height,
7323 scroll_pixel_position,
7324 newest_selection_head,
7325 target_display_point,
7326 window,
7327 cx,
7328 )
7329 } else {
7330 self.render_edit_prediction_eager_jump_popover(
7331 text_bounds,
7332 content_origin,
7333 editor_snapshot,
7334 visible_row_range,
7335 scroll_top,
7336 scroll_bottom,
7337 line_height,
7338 scroll_pixel_position,
7339 target_display_point,
7340 editor_width,
7341 window,
7342 cx,
7343 )
7344 }
7345 }
7346 InlineCompletion::Edit {
7347 display_mode: EditDisplayMode::Inline,
7348 ..
7349 } => None,
7350 InlineCompletion::Edit {
7351 display_mode: EditDisplayMode::TabAccept,
7352 edits,
7353 ..
7354 } => {
7355 let range = &edits.first()?.0;
7356 let target_display_point = range.end.to_display_point(editor_snapshot);
7357
7358 self.render_edit_prediction_end_of_line_popover(
7359 "Accept",
7360 editor_snapshot,
7361 visible_row_range,
7362 target_display_point,
7363 line_height,
7364 scroll_pixel_position,
7365 content_origin,
7366 editor_width,
7367 window,
7368 cx,
7369 )
7370 }
7371 InlineCompletion::Edit {
7372 edits,
7373 edit_preview,
7374 display_mode: EditDisplayMode::DiffPopover,
7375 snapshot,
7376 } => self.render_edit_prediction_diff_popover(
7377 text_bounds,
7378 content_origin,
7379 right_margin,
7380 editor_snapshot,
7381 visible_row_range,
7382 line_layouts,
7383 line_height,
7384 scroll_pixel_position,
7385 newest_selection_head,
7386 editor_width,
7387 style,
7388 edits,
7389 edit_preview,
7390 snapshot,
7391 window,
7392 cx,
7393 ),
7394 }
7395 }
7396
7397 fn render_edit_prediction_modifier_jump_popover(
7398 &mut self,
7399 text_bounds: &Bounds<Pixels>,
7400 content_origin: gpui::Point<Pixels>,
7401 visible_row_range: Range<DisplayRow>,
7402 line_layouts: &[LineWithInvisibles],
7403 line_height: Pixels,
7404 scroll_pixel_position: gpui::Point<Pixels>,
7405 newest_selection_head: Option<DisplayPoint>,
7406 target_display_point: DisplayPoint,
7407 window: &mut Window,
7408 cx: &mut App,
7409 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7410 let scrolled_content_origin =
7411 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7412
7413 const SCROLL_PADDING_Y: Pixels = px(12.);
7414
7415 if target_display_point.row() < visible_row_range.start {
7416 return self.render_edit_prediction_scroll_popover(
7417 |_| SCROLL_PADDING_Y,
7418 IconName::ArrowUp,
7419 visible_row_range,
7420 line_layouts,
7421 newest_selection_head,
7422 scrolled_content_origin,
7423 window,
7424 cx,
7425 );
7426 } else if target_display_point.row() >= visible_row_range.end {
7427 return self.render_edit_prediction_scroll_popover(
7428 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7429 IconName::ArrowDown,
7430 visible_row_range,
7431 line_layouts,
7432 newest_selection_head,
7433 scrolled_content_origin,
7434 window,
7435 cx,
7436 );
7437 }
7438
7439 const POLE_WIDTH: Pixels = px(2.);
7440
7441 let line_layout =
7442 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7443 let target_column = target_display_point.column() as usize;
7444
7445 let target_x = line_layout.x_for_index(target_column);
7446 let target_y =
7447 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7448
7449 let flag_on_right = target_x < text_bounds.size.width / 2.;
7450
7451 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7452 border_color.l += 0.001;
7453
7454 let mut element = v_flex()
7455 .items_end()
7456 .when(flag_on_right, |el| el.items_start())
7457 .child(if flag_on_right {
7458 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7459 .rounded_bl(px(0.))
7460 .rounded_tl(px(0.))
7461 .border_l_2()
7462 .border_color(border_color)
7463 } else {
7464 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7465 .rounded_br(px(0.))
7466 .rounded_tr(px(0.))
7467 .border_r_2()
7468 .border_color(border_color)
7469 })
7470 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7471 .into_any();
7472
7473 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7474
7475 let mut origin = scrolled_content_origin + point(target_x, target_y)
7476 - point(
7477 if flag_on_right {
7478 POLE_WIDTH
7479 } else {
7480 size.width - POLE_WIDTH
7481 },
7482 size.height - line_height,
7483 );
7484
7485 origin.x = origin.x.max(content_origin.x);
7486
7487 element.prepaint_at(origin, window, cx);
7488
7489 Some((element, origin))
7490 }
7491
7492 fn render_edit_prediction_scroll_popover(
7493 &mut self,
7494 to_y: impl Fn(Size<Pixels>) -> Pixels,
7495 scroll_icon: IconName,
7496 visible_row_range: Range<DisplayRow>,
7497 line_layouts: &[LineWithInvisibles],
7498 newest_selection_head: Option<DisplayPoint>,
7499 scrolled_content_origin: gpui::Point<Pixels>,
7500 window: &mut Window,
7501 cx: &mut App,
7502 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7503 let mut element = self
7504 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7505 .into_any();
7506
7507 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7508
7509 let cursor = newest_selection_head?;
7510 let cursor_row_layout =
7511 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7512 let cursor_column = cursor.column() as usize;
7513
7514 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7515
7516 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7517
7518 element.prepaint_at(origin, window, cx);
7519 Some((element, origin))
7520 }
7521
7522 fn render_edit_prediction_eager_jump_popover(
7523 &mut self,
7524 text_bounds: &Bounds<Pixels>,
7525 content_origin: gpui::Point<Pixels>,
7526 editor_snapshot: &EditorSnapshot,
7527 visible_row_range: Range<DisplayRow>,
7528 scroll_top: f32,
7529 scroll_bottom: f32,
7530 line_height: Pixels,
7531 scroll_pixel_position: gpui::Point<Pixels>,
7532 target_display_point: DisplayPoint,
7533 editor_width: Pixels,
7534 window: &mut Window,
7535 cx: &mut App,
7536 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7537 if target_display_point.row().as_f32() < scroll_top {
7538 let mut element = self
7539 .render_edit_prediction_line_popover(
7540 "Jump to Edit",
7541 Some(IconName::ArrowUp),
7542 window,
7543 cx,
7544 )?
7545 .into_any();
7546
7547 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7548 let offset = point(
7549 (text_bounds.size.width - size.width) / 2.,
7550 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7551 );
7552
7553 let origin = text_bounds.origin + offset;
7554 element.prepaint_at(origin, window, cx);
7555 Some((element, origin))
7556 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7557 let mut element = self
7558 .render_edit_prediction_line_popover(
7559 "Jump to Edit",
7560 Some(IconName::ArrowDown),
7561 window,
7562 cx,
7563 )?
7564 .into_any();
7565
7566 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7567 let offset = point(
7568 (text_bounds.size.width - size.width) / 2.,
7569 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7570 );
7571
7572 let origin = text_bounds.origin + offset;
7573 element.prepaint_at(origin, window, cx);
7574 Some((element, origin))
7575 } else {
7576 self.render_edit_prediction_end_of_line_popover(
7577 "Jump to Edit",
7578 editor_snapshot,
7579 visible_row_range,
7580 target_display_point,
7581 line_height,
7582 scroll_pixel_position,
7583 content_origin,
7584 editor_width,
7585 window,
7586 cx,
7587 )
7588 }
7589 }
7590
7591 fn render_edit_prediction_end_of_line_popover(
7592 self: &mut Editor,
7593 label: &'static str,
7594 editor_snapshot: &EditorSnapshot,
7595 visible_row_range: Range<DisplayRow>,
7596 target_display_point: DisplayPoint,
7597 line_height: Pixels,
7598 scroll_pixel_position: gpui::Point<Pixels>,
7599 content_origin: gpui::Point<Pixels>,
7600 editor_width: Pixels,
7601 window: &mut Window,
7602 cx: &mut App,
7603 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7604 let target_line_end = DisplayPoint::new(
7605 target_display_point.row(),
7606 editor_snapshot.line_len(target_display_point.row()),
7607 );
7608
7609 let mut element = self
7610 .render_edit_prediction_line_popover(label, None, window, cx)?
7611 .into_any();
7612
7613 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7614
7615 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7616
7617 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7618 let mut origin = start_point
7619 + line_origin
7620 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7621 origin.x = origin.x.max(content_origin.x);
7622
7623 let max_x = content_origin.x + editor_width - size.width;
7624
7625 if origin.x > max_x {
7626 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7627
7628 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7629 origin.y += offset;
7630 IconName::ArrowUp
7631 } else {
7632 origin.y -= offset;
7633 IconName::ArrowDown
7634 };
7635
7636 element = self
7637 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7638 .into_any();
7639
7640 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7641
7642 origin.x = content_origin.x + editor_width - size.width - px(2.);
7643 }
7644
7645 element.prepaint_at(origin, window, cx);
7646 Some((element, origin))
7647 }
7648
7649 fn render_edit_prediction_diff_popover(
7650 self: &Editor,
7651 text_bounds: &Bounds<Pixels>,
7652 content_origin: gpui::Point<Pixels>,
7653 right_margin: Pixels,
7654 editor_snapshot: &EditorSnapshot,
7655 visible_row_range: Range<DisplayRow>,
7656 line_layouts: &[LineWithInvisibles],
7657 line_height: Pixels,
7658 scroll_pixel_position: gpui::Point<Pixels>,
7659 newest_selection_head: Option<DisplayPoint>,
7660 editor_width: Pixels,
7661 style: &EditorStyle,
7662 edits: &Vec<(Range<Anchor>, String)>,
7663 edit_preview: &Option<language::EditPreview>,
7664 snapshot: &language::BufferSnapshot,
7665 window: &mut Window,
7666 cx: &mut App,
7667 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7668 let edit_start = edits
7669 .first()
7670 .unwrap()
7671 .0
7672 .start
7673 .to_display_point(editor_snapshot);
7674 let edit_end = edits
7675 .last()
7676 .unwrap()
7677 .0
7678 .end
7679 .to_display_point(editor_snapshot);
7680
7681 let is_visible = visible_row_range.contains(&edit_start.row())
7682 || visible_row_range.contains(&edit_end.row());
7683 if !is_visible {
7684 return None;
7685 }
7686
7687 let highlighted_edits =
7688 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7689
7690 let styled_text = highlighted_edits.to_styled_text(&style.text);
7691 let line_count = highlighted_edits.text.lines().count();
7692
7693 const BORDER_WIDTH: Pixels = px(1.);
7694
7695 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7696 let has_keybind = keybind.is_some();
7697
7698 let mut element = h_flex()
7699 .items_start()
7700 .child(
7701 h_flex()
7702 .bg(cx.theme().colors().editor_background)
7703 .border(BORDER_WIDTH)
7704 .shadow_sm()
7705 .border_color(cx.theme().colors().border)
7706 .rounded_l_lg()
7707 .when(line_count > 1, |el| el.rounded_br_lg())
7708 .pr_1()
7709 .child(styled_text),
7710 )
7711 .child(
7712 h_flex()
7713 .h(line_height + BORDER_WIDTH * 2.)
7714 .px_1p5()
7715 .gap_1()
7716 // Workaround: For some reason, there's a gap if we don't do this
7717 .ml(-BORDER_WIDTH)
7718 .shadow(smallvec![gpui::BoxShadow {
7719 color: gpui::black().opacity(0.05),
7720 offset: point(px(1.), px(1.)),
7721 blur_radius: px(2.),
7722 spread_radius: px(0.),
7723 }])
7724 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7725 .border(BORDER_WIDTH)
7726 .border_color(cx.theme().colors().border)
7727 .rounded_r_lg()
7728 .id("edit_prediction_diff_popover_keybind")
7729 .when(!has_keybind, |el| {
7730 let status_colors = cx.theme().status();
7731
7732 el.bg(status_colors.error_background)
7733 .border_color(status_colors.error.opacity(0.6))
7734 .child(Icon::new(IconName::Info).color(Color::Error))
7735 .cursor_default()
7736 .hoverable_tooltip(move |_window, cx| {
7737 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7738 })
7739 })
7740 .children(keybind),
7741 )
7742 .into_any();
7743
7744 let longest_row =
7745 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7746 let longest_line_width = if visible_row_range.contains(&longest_row) {
7747 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7748 } else {
7749 layout_line(
7750 longest_row,
7751 editor_snapshot,
7752 style,
7753 editor_width,
7754 |_| false,
7755 window,
7756 cx,
7757 )
7758 .width
7759 };
7760
7761 let viewport_bounds =
7762 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7763 right: -right_margin,
7764 ..Default::default()
7765 });
7766
7767 let x_after_longest =
7768 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7769 - scroll_pixel_position.x;
7770
7771 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7772
7773 // Fully visible if it can be displayed within the window (allow overlapping other
7774 // panes). However, this is only allowed if the popover starts within text_bounds.
7775 let can_position_to_the_right = x_after_longest < text_bounds.right()
7776 && x_after_longest + element_bounds.width < viewport_bounds.right();
7777
7778 let mut origin = if can_position_to_the_right {
7779 point(
7780 x_after_longest,
7781 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7782 - scroll_pixel_position.y,
7783 )
7784 } else {
7785 let cursor_row = newest_selection_head.map(|head| head.row());
7786 let above_edit = edit_start
7787 .row()
7788 .0
7789 .checked_sub(line_count as u32)
7790 .map(DisplayRow);
7791 let below_edit = Some(edit_end.row() + 1);
7792 let above_cursor =
7793 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7794 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7795
7796 // Place the edit popover adjacent to the edit if there is a location
7797 // available that is onscreen and does not obscure the cursor. Otherwise,
7798 // place it adjacent to the cursor.
7799 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7800 .into_iter()
7801 .flatten()
7802 .find(|&start_row| {
7803 let end_row = start_row + line_count as u32;
7804 visible_row_range.contains(&start_row)
7805 && visible_row_range.contains(&end_row)
7806 && cursor_row.map_or(true, |cursor_row| {
7807 !((start_row..end_row).contains(&cursor_row))
7808 })
7809 })?;
7810
7811 content_origin
7812 + point(
7813 -scroll_pixel_position.x,
7814 row_target.as_f32() * line_height - scroll_pixel_position.y,
7815 )
7816 };
7817
7818 origin.x -= BORDER_WIDTH;
7819
7820 window.defer_draw(element, origin, 1);
7821
7822 // Do not return an element, since it will already be drawn due to defer_draw.
7823 None
7824 }
7825
7826 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7827 px(30.)
7828 }
7829
7830 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7831 if self.read_only(cx) {
7832 cx.theme().players().read_only()
7833 } else {
7834 self.style.as_ref().unwrap().local_player
7835 }
7836 }
7837
7838 fn render_edit_prediction_accept_keybind(
7839 &self,
7840 window: &mut Window,
7841 cx: &App,
7842 ) -> Option<AnyElement> {
7843 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7844 let accept_keystroke = accept_binding.keystroke()?;
7845
7846 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7847
7848 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7849 Color::Accent
7850 } else {
7851 Color::Muted
7852 };
7853
7854 h_flex()
7855 .px_0p5()
7856 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7857 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7858 .text_size(TextSize::XSmall.rems(cx))
7859 .child(h_flex().children(ui::render_modifiers(
7860 &accept_keystroke.modifiers,
7861 PlatformStyle::platform(),
7862 Some(modifiers_color),
7863 Some(IconSize::XSmall.rems().into()),
7864 true,
7865 )))
7866 .when(is_platform_style_mac, |parent| {
7867 parent.child(accept_keystroke.key.clone())
7868 })
7869 .when(!is_platform_style_mac, |parent| {
7870 parent.child(
7871 Key::new(
7872 util::capitalize(&accept_keystroke.key),
7873 Some(Color::Default),
7874 )
7875 .size(Some(IconSize::XSmall.rems().into())),
7876 )
7877 })
7878 .into_any()
7879 .into()
7880 }
7881
7882 fn render_edit_prediction_line_popover(
7883 &self,
7884 label: impl Into<SharedString>,
7885 icon: Option<IconName>,
7886 window: &mut Window,
7887 cx: &App,
7888 ) -> Option<Stateful<Div>> {
7889 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7890
7891 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7892 let has_keybind = keybind.is_some();
7893
7894 let result = h_flex()
7895 .id("ep-line-popover")
7896 .py_0p5()
7897 .pl_1()
7898 .pr(padding_right)
7899 .gap_1()
7900 .rounded_md()
7901 .border_1()
7902 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7903 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7904 .shadow_sm()
7905 .when(!has_keybind, |el| {
7906 let status_colors = cx.theme().status();
7907
7908 el.bg(status_colors.error_background)
7909 .border_color(status_colors.error.opacity(0.6))
7910 .pl_2()
7911 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7912 .cursor_default()
7913 .hoverable_tooltip(move |_window, cx| {
7914 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7915 })
7916 })
7917 .children(keybind)
7918 .child(
7919 Label::new(label)
7920 .size(LabelSize::Small)
7921 .when(!has_keybind, |el| {
7922 el.color(cx.theme().status().error.into()).strikethrough()
7923 }),
7924 )
7925 .when(!has_keybind, |el| {
7926 el.child(
7927 h_flex().ml_1().child(
7928 Icon::new(IconName::Info)
7929 .size(IconSize::Small)
7930 .color(cx.theme().status().error.into()),
7931 ),
7932 )
7933 })
7934 .when_some(icon, |element, icon| {
7935 element.child(
7936 div()
7937 .mt(px(1.5))
7938 .child(Icon::new(icon).size(IconSize::Small)),
7939 )
7940 });
7941
7942 Some(result)
7943 }
7944
7945 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7946 let accent_color = cx.theme().colors().text_accent;
7947 let editor_bg_color = cx.theme().colors().editor_background;
7948 editor_bg_color.blend(accent_color.opacity(0.1))
7949 }
7950
7951 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7952 let accent_color = cx.theme().colors().text_accent;
7953 let editor_bg_color = cx.theme().colors().editor_background;
7954 editor_bg_color.blend(accent_color.opacity(0.6))
7955 }
7956
7957 fn render_edit_prediction_cursor_popover(
7958 &self,
7959 min_width: Pixels,
7960 max_width: Pixels,
7961 cursor_point: Point,
7962 style: &EditorStyle,
7963 accept_keystroke: Option<&gpui::Keystroke>,
7964 _window: &Window,
7965 cx: &mut Context<Editor>,
7966 ) -> Option<AnyElement> {
7967 let provider = self.edit_prediction_provider.as_ref()?;
7968
7969 if provider.provider.needs_terms_acceptance(cx) {
7970 return Some(
7971 h_flex()
7972 .min_w(min_width)
7973 .flex_1()
7974 .px_2()
7975 .py_1()
7976 .gap_3()
7977 .elevation_2(cx)
7978 .hover(|style| style.bg(cx.theme().colors().element_hover))
7979 .id("accept-terms")
7980 .cursor_pointer()
7981 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7982 .on_click(cx.listener(|this, _event, window, cx| {
7983 cx.stop_propagation();
7984 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7985 window.dispatch_action(
7986 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7987 cx,
7988 );
7989 }))
7990 .child(
7991 h_flex()
7992 .flex_1()
7993 .gap_2()
7994 .child(Icon::new(IconName::ZedPredict))
7995 .child(Label::new("Accept Terms of Service"))
7996 .child(div().w_full())
7997 .child(
7998 Icon::new(IconName::ArrowUpRight)
7999 .color(Color::Muted)
8000 .size(IconSize::Small),
8001 )
8002 .into_any_element(),
8003 )
8004 .into_any(),
8005 );
8006 }
8007
8008 let is_refreshing = provider.provider.is_refreshing(cx);
8009
8010 fn pending_completion_container() -> Div {
8011 h_flex()
8012 .h_full()
8013 .flex_1()
8014 .gap_2()
8015 .child(Icon::new(IconName::ZedPredict))
8016 }
8017
8018 let completion = match &self.active_inline_completion {
8019 Some(prediction) => {
8020 if !self.has_visible_completions_menu() {
8021 const RADIUS: Pixels = px(6.);
8022 const BORDER_WIDTH: Pixels = px(1.);
8023
8024 return Some(
8025 h_flex()
8026 .elevation_2(cx)
8027 .border(BORDER_WIDTH)
8028 .border_color(cx.theme().colors().border)
8029 .when(accept_keystroke.is_none(), |el| {
8030 el.border_color(cx.theme().status().error)
8031 })
8032 .rounded(RADIUS)
8033 .rounded_tl(px(0.))
8034 .overflow_hidden()
8035 .child(div().px_1p5().child(match &prediction.completion {
8036 InlineCompletion::Move { target, snapshot } => {
8037 use text::ToPoint as _;
8038 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
8039 {
8040 Icon::new(IconName::ZedPredictDown)
8041 } else {
8042 Icon::new(IconName::ZedPredictUp)
8043 }
8044 }
8045 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
8046 }))
8047 .child(
8048 h_flex()
8049 .gap_1()
8050 .py_1()
8051 .px_2()
8052 .rounded_r(RADIUS - BORDER_WIDTH)
8053 .border_l_1()
8054 .border_color(cx.theme().colors().border)
8055 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8056 .when(self.edit_prediction_preview.released_too_fast(), |el| {
8057 el.child(
8058 Label::new("Hold")
8059 .size(LabelSize::Small)
8060 .when(accept_keystroke.is_none(), |el| {
8061 el.strikethrough()
8062 })
8063 .line_height_style(LineHeightStyle::UiLabel),
8064 )
8065 })
8066 .id("edit_prediction_cursor_popover_keybind")
8067 .when(accept_keystroke.is_none(), |el| {
8068 let status_colors = cx.theme().status();
8069
8070 el.bg(status_colors.error_background)
8071 .border_color(status_colors.error.opacity(0.6))
8072 .child(Icon::new(IconName::Info).color(Color::Error))
8073 .cursor_default()
8074 .hoverable_tooltip(move |_window, cx| {
8075 cx.new(|_| MissingEditPredictionKeybindingTooltip)
8076 .into()
8077 })
8078 })
8079 .when_some(
8080 accept_keystroke.as_ref(),
8081 |el, accept_keystroke| {
8082 el.child(h_flex().children(ui::render_modifiers(
8083 &accept_keystroke.modifiers,
8084 PlatformStyle::platform(),
8085 Some(Color::Default),
8086 Some(IconSize::XSmall.rems().into()),
8087 false,
8088 )))
8089 },
8090 ),
8091 )
8092 .into_any(),
8093 );
8094 }
8095
8096 self.render_edit_prediction_cursor_popover_preview(
8097 prediction,
8098 cursor_point,
8099 style,
8100 cx,
8101 )?
8102 }
8103
8104 None if is_refreshing => match &self.stale_inline_completion_in_menu {
8105 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
8106 stale_completion,
8107 cursor_point,
8108 style,
8109 cx,
8110 )?,
8111
8112 None => {
8113 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
8114 }
8115 },
8116
8117 None => pending_completion_container().child(Label::new("No Prediction")),
8118 };
8119
8120 let completion = if is_refreshing {
8121 completion
8122 .with_animation(
8123 "loading-completion",
8124 Animation::new(Duration::from_secs(2))
8125 .repeat()
8126 .with_easing(pulsating_between(0.4, 0.8)),
8127 |label, delta| label.opacity(delta),
8128 )
8129 .into_any_element()
8130 } else {
8131 completion.into_any_element()
8132 };
8133
8134 let has_completion = self.active_inline_completion.is_some();
8135
8136 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
8137 Some(
8138 h_flex()
8139 .min_w(min_width)
8140 .max_w(max_width)
8141 .flex_1()
8142 .elevation_2(cx)
8143 .border_color(cx.theme().colors().border)
8144 .child(
8145 div()
8146 .flex_1()
8147 .py_1()
8148 .px_2()
8149 .overflow_hidden()
8150 .child(completion),
8151 )
8152 .when_some(accept_keystroke, |el, accept_keystroke| {
8153 if !accept_keystroke.modifiers.modified() {
8154 return el;
8155 }
8156
8157 el.child(
8158 h_flex()
8159 .h_full()
8160 .border_l_1()
8161 .rounded_r_lg()
8162 .border_color(cx.theme().colors().border)
8163 .bg(Self::edit_prediction_line_popover_bg_color(cx))
8164 .gap_1()
8165 .py_1()
8166 .px_2()
8167 .child(
8168 h_flex()
8169 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8170 .when(is_platform_style_mac, |parent| parent.gap_1())
8171 .child(h_flex().children(ui::render_modifiers(
8172 &accept_keystroke.modifiers,
8173 PlatformStyle::platform(),
8174 Some(if !has_completion {
8175 Color::Muted
8176 } else {
8177 Color::Default
8178 }),
8179 None,
8180 false,
8181 ))),
8182 )
8183 .child(Label::new("Preview").into_any_element())
8184 .opacity(if has_completion { 1.0 } else { 0.4 }),
8185 )
8186 })
8187 .into_any(),
8188 )
8189 }
8190
8191 fn render_edit_prediction_cursor_popover_preview(
8192 &self,
8193 completion: &InlineCompletionState,
8194 cursor_point: Point,
8195 style: &EditorStyle,
8196 cx: &mut Context<Editor>,
8197 ) -> Option<Div> {
8198 use text::ToPoint as _;
8199
8200 fn render_relative_row_jump(
8201 prefix: impl Into<String>,
8202 current_row: u32,
8203 target_row: u32,
8204 ) -> Div {
8205 let (row_diff, arrow) = if target_row < current_row {
8206 (current_row - target_row, IconName::ArrowUp)
8207 } else {
8208 (target_row - current_row, IconName::ArrowDown)
8209 };
8210
8211 h_flex()
8212 .child(
8213 Label::new(format!("{}{}", prefix.into(), row_diff))
8214 .color(Color::Muted)
8215 .size(LabelSize::Small),
8216 )
8217 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
8218 }
8219
8220 match &completion.completion {
8221 InlineCompletion::Move {
8222 target, snapshot, ..
8223 } => Some(
8224 h_flex()
8225 .px_2()
8226 .gap_2()
8227 .flex_1()
8228 .child(
8229 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
8230 Icon::new(IconName::ZedPredictDown)
8231 } else {
8232 Icon::new(IconName::ZedPredictUp)
8233 },
8234 )
8235 .child(Label::new("Jump to Edit")),
8236 ),
8237
8238 InlineCompletion::Edit {
8239 edits,
8240 edit_preview,
8241 snapshot,
8242 display_mode: _,
8243 } => {
8244 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
8245
8246 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
8247 &snapshot,
8248 &edits,
8249 edit_preview.as_ref()?,
8250 true,
8251 cx,
8252 )
8253 .first_line_preview();
8254
8255 let styled_text = gpui::StyledText::new(highlighted_edits.text)
8256 .with_default_highlights(&style.text, highlighted_edits.highlights);
8257
8258 let preview = h_flex()
8259 .gap_1()
8260 .min_w_16()
8261 .child(styled_text)
8262 .when(has_more_lines, |parent| parent.child("…"));
8263
8264 let left = if first_edit_row != cursor_point.row {
8265 render_relative_row_jump("", cursor_point.row, first_edit_row)
8266 .into_any_element()
8267 } else {
8268 Icon::new(IconName::ZedPredict).into_any_element()
8269 };
8270
8271 Some(
8272 h_flex()
8273 .h_full()
8274 .flex_1()
8275 .gap_2()
8276 .pr_1()
8277 .overflow_x_hidden()
8278 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
8279 .child(left)
8280 .child(preview),
8281 )
8282 }
8283 }
8284 }
8285
8286 fn render_context_menu(
8287 &self,
8288 style: &EditorStyle,
8289 max_height_in_lines: u32,
8290 window: &mut Window,
8291 cx: &mut Context<Editor>,
8292 ) -> Option<AnyElement> {
8293 let menu = self.context_menu.borrow();
8294 let menu = menu.as_ref()?;
8295 if !menu.visible() {
8296 return None;
8297 };
8298 Some(menu.render(style, max_height_in_lines, window, cx))
8299 }
8300
8301 fn render_context_menu_aside(
8302 &mut self,
8303 max_size: Size<Pixels>,
8304 window: &mut Window,
8305 cx: &mut Context<Editor>,
8306 ) -> Option<AnyElement> {
8307 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
8308 if menu.visible() {
8309 menu.render_aside(self, max_size, window, cx)
8310 } else {
8311 None
8312 }
8313 })
8314 }
8315
8316 fn hide_context_menu(
8317 &mut self,
8318 window: &mut Window,
8319 cx: &mut Context<Self>,
8320 ) -> Option<CodeContextMenu> {
8321 cx.notify();
8322 self.completion_tasks.clear();
8323 let context_menu = self.context_menu.borrow_mut().take();
8324 self.stale_inline_completion_in_menu.take();
8325 self.update_visible_inline_completion(window, cx);
8326 context_menu
8327 }
8328
8329 fn show_snippet_choices(
8330 &mut self,
8331 choices: &Vec<String>,
8332 selection: Range<Anchor>,
8333 cx: &mut Context<Self>,
8334 ) {
8335 if selection.start.buffer_id.is_none() {
8336 return;
8337 }
8338 let buffer_id = selection.start.buffer_id.unwrap();
8339 let buffer = self.buffer().read(cx).buffer(buffer_id);
8340 let id = post_inc(&mut self.next_completion_id);
8341 let snippet_sort_order = EditorSettings::get_global(cx).snippet_sort_order;
8342
8343 if let Some(buffer) = buffer {
8344 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8345 CompletionsMenu::new_snippet_choices(
8346 id,
8347 true,
8348 choices,
8349 selection,
8350 buffer,
8351 snippet_sort_order,
8352 ),
8353 ));
8354 }
8355 }
8356
8357 pub fn insert_snippet(
8358 &mut self,
8359 insertion_ranges: &[Range<usize>],
8360 snippet: Snippet,
8361 window: &mut Window,
8362 cx: &mut Context<Self>,
8363 ) -> Result<()> {
8364 struct Tabstop<T> {
8365 is_end_tabstop: bool,
8366 ranges: Vec<Range<T>>,
8367 choices: Option<Vec<String>>,
8368 }
8369
8370 let tabstops = self.buffer.update(cx, |buffer, cx| {
8371 let snippet_text: Arc<str> = snippet.text.clone().into();
8372 let edits = insertion_ranges
8373 .iter()
8374 .cloned()
8375 .map(|range| (range, snippet_text.clone()));
8376 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8377
8378 let snapshot = &*buffer.read(cx);
8379 let snippet = &snippet;
8380 snippet
8381 .tabstops
8382 .iter()
8383 .map(|tabstop| {
8384 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8385 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8386 });
8387 let mut tabstop_ranges = tabstop
8388 .ranges
8389 .iter()
8390 .flat_map(|tabstop_range| {
8391 let mut delta = 0_isize;
8392 insertion_ranges.iter().map(move |insertion_range| {
8393 let insertion_start = insertion_range.start as isize + delta;
8394 delta +=
8395 snippet.text.len() as isize - insertion_range.len() as isize;
8396
8397 let start = ((insertion_start + tabstop_range.start) as usize)
8398 .min(snapshot.len());
8399 let end = ((insertion_start + tabstop_range.end) as usize)
8400 .min(snapshot.len());
8401 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8402 })
8403 })
8404 .collect::<Vec<_>>();
8405 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8406
8407 Tabstop {
8408 is_end_tabstop,
8409 ranges: tabstop_ranges,
8410 choices: tabstop.choices.clone(),
8411 }
8412 })
8413 .collect::<Vec<_>>()
8414 });
8415 if let Some(tabstop) = tabstops.first() {
8416 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8417 s.select_ranges(tabstop.ranges.iter().cloned());
8418 });
8419
8420 if let Some(choices) = &tabstop.choices {
8421 if let Some(selection) = tabstop.ranges.first() {
8422 self.show_snippet_choices(choices, selection.clone(), cx)
8423 }
8424 }
8425
8426 // If we're already at the last tabstop and it's at the end of the snippet,
8427 // we're done, we don't need to keep the state around.
8428 if !tabstop.is_end_tabstop {
8429 let choices = tabstops
8430 .iter()
8431 .map(|tabstop| tabstop.choices.clone())
8432 .collect();
8433
8434 let ranges = tabstops
8435 .into_iter()
8436 .map(|tabstop| tabstop.ranges)
8437 .collect::<Vec<_>>();
8438
8439 self.snippet_stack.push(SnippetState {
8440 active_index: 0,
8441 ranges,
8442 choices,
8443 });
8444 }
8445
8446 // Check whether the just-entered snippet ends with an auto-closable bracket.
8447 if self.autoclose_regions.is_empty() {
8448 let snapshot = self.buffer.read(cx).snapshot(cx);
8449 for selection in &mut self.selections.all::<Point>(cx) {
8450 let selection_head = selection.head();
8451 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8452 continue;
8453 };
8454
8455 let mut bracket_pair = None;
8456 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8457 let prev_chars = snapshot
8458 .reversed_chars_at(selection_head)
8459 .collect::<String>();
8460 for (pair, enabled) in scope.brackets() {
8461 if enabled
8462 && pair.close
8463 && prev_chars.starts_with(pair.start.as_str())
8464 && next_chars.starts_with(pair.end.as_str())
8465 {
8466 bracket_pair = Some(pair.clone());
8467 break;
8468 }
8469 }
8470 if let Some(pair) = bracket_pair {
8471 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8472 let autoclose_enabled =
8473 self.use_autoclose && snapshot_settings.use_autoclose;
8474 if autoclose_enabled {
8475 let start = snapshot.anchor_after(selection_head);
8476 let end = snapshot.anchor_after(selection_head);
8477 self.autoclose_regions.push(AutocloseRegion {
8478 selection_id: selection.id,
8479 range: start..end,
8480 pair,
8481 });
8482 }
8483 }
8484 }
8485 }
8486 }
8487 Ok(())
8488 }
8489
8490 pub fn move_to_next_snippet_tabstop(
8491 &mut self,
8492 window: &mut Window,
8493 cx: &mut Context<Self>,
8494 ) -> bool {
8495 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8496 }
8497
8498 pub fn move_to_prev_snippet_tabstop(
8499 &mut self,
8500 window: &mut Window,
8501 cx: &mut Context<Self>,
8502 ) -> bool {
8503 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8504 }
8505
8506 pub fn move_to_snippet_tabstop(
8507 &mut self,
8508 bias: Bias,
8509 window: &mut Window,
8510 cx: &mut Context<Self>,
8511 ) -> bool {
8512 if let Some(mut snippet) = self.snippet_stack.pop() {
8513 match bias {
8514 Bias::Left => {
8515 if snippet.active_index > 0 {
8516 snippet.active_index -= 1;
8517 } else {
8518 self.snippet_stack.push(snippet);
8519 return false;
8520 }
8521 }
8522 Bias::Right => {
8523 if snippet.active_index + 1 < snippet.ranges.len() {
8524 snippet.active_index += 1;
8525 } else {
8526 self.snippet_stack.push(snippet);
8527 return false;
8528 }
8529 }
8530 }
8531 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8532 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8533 s.select_anchor_ranges(current_ranges.iter().cloned())
8534 });
8535
8536 if let Some(choices) = &snippet.choices[snippet.active_index] {
8537 if let Some(selection) = current_ranges.first() {
8538 self.show_snippet_choices(&choices, selection.clone(), cx);
8539 }
8540 }
8541
8542 // If snippet state is not at the last tabstop, push it back on the stack
8543 if snippet.active_index + 1 < snippet.ranges.len() {
8544 self.snippet_stack.push(snippet);
8545 }
8546 return true;
8547 }
8548 }
8549
8550 false
8551 }
8552
8553 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8554 self.transact(window, cx, |this, window, cx| {
8555 this.select_all(&SelectAll, window, cx);
8556 this.insert("", window, cx);
8557 });
8558 }
8559
8560 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8561 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8562 self.transact(window, cx, |this, window, cx| {
8563 this.select_autoclose_pair(window, cx);
8564 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8565 if !this.linked_edit_ranges.is_empty() {
8566 let selections = this.selections.all::<MultiBufferPoint>(cx);
8567 let snapshot = this.buffer.read(cx).snapshot(cx);
8568
8569 for selection in selections.iter() {
8570 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8571 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8572 if selection_start.buffer_id != selection_end.buffer_id {
8573 continue;
8574 }
8575 if let Some(ranges) =
8576 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8577 {
8578 for (buffer, entries) in ranges {
8579 linked_ranges.entry(buffer).or_default().extend(entries);
8580 }
8581 }
8582 }
8583 }
8584
8585 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8586 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8587 for selection in &mut selections {
8588 if selection.is_empty() {
8589 let old_head = selection.head();
8590 let mut new_head =
8591 movement::left(&display_map, old_head.to_display_point(&display_map))
8592 .to_point(&display_map);
8593 if let Some((buffer, line_buffer_range)) = display_map
8594 .buffer_snapshot
8595 .buffer_line_for_row(MultiBufferRow(old_head.row))
8596 {
8597 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8598 let indent_len = match indent_size.kind {
8599 IndentKind::Space => {
8600 buffer.settings_at(line_buffer_range.start, cx).tab_size
8601 }
8602 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8603 };
8604 if old_head.column <= indent_size.len && old_head.column > 0 {
8605 let indent_len = indent_len.get();
8606 new_head = cmp::min(
8607 new_head,
8608 MultiBufferPoint::new(
8609 old_head.row,
8610 ((old_head.column - 1) / indent_len) * indent_len,
8611 ),
8612 );
8613 }
8614 }
8615
8616 selection.set_head(new_head, SelectionGoal::None);
8617 }
8618 }
8619
8620 this.signature_help_state.set_backspace_pressed(true);
8621 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8622 s.select(selections)
8623 });
8624 this.insert("", window, cx);
8625 let empty_str: Arc<str> = Arc::from("");
8626 for (buffer, edits) in linked_ranges {
8627 let snapshot = buffer.read(cx).snapshot();
8628 use text::ToPoint as TP;
8629
8630 let edits = edits
8631 .into_iter()
8632 .map(|range| {
8633 let end_point = TP::to_point(&range.end, &snapshot);
8634 let mut start_point = TP::to_point(&range.start, &snapshot);
8635
8636 if end_point == start_point {
8637 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8638 .saturating_sub(1);
8639 start_point =
8640 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8641 };
8642
8643 (start_point..end_point, empty_str.clone())
8644 })
8645 .sorted_by_key(|(range, _)| range.start)
8646 .collect::<Vec<_>>();
8647 buffer.update(cx, |this, cx| {
8648 this.edit(edits, None, cx);
8649 })
8650 }
8651 this.refresh_inline_completion(true, false, window, cx);
8652 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8653 });
8654 }
8655
8656 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8657 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8658 self.transact(window, cx, |this, window, cx| {
8659 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8660 s.move_with(|map, selection| {
8661 if selection.is_empty() {
8662 let cursor = movement::right(map, selection.head());
8663 selection.end = cursor;
8664 selection.reversed = true;
8665 selection.goal = SelectionGoal::None;
8666 }
8667 })
8668 });
8669 this.insert("", window, cx);
8670 this.refresh_inline_completion(true, false, window, cx);
8671 });
8672 }
8673
8674 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8675 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8676 if self.move_to_prev_snippet_tabstop(window, cx) {
8677 return;
8678 }
8679 self.outdent(&Outdent, window, cx);
8680 }
8681
8682 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8683 if self.move_to_next_snippet_tabstop(window, cx) {
8684 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8685 return;
8686 }
8687 if self.read_only(cx) {
8688 return;
8689 }
8690 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8691 let mut selections = self.selections.all_adjusted(cx);
8692 let buffer = self.buffer.read(cx);
8693 let snapshot = buffer.snapshot(cx);
8694 let rows_iter = selections.iter().map(|s| s.head().row);
8695 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8696
8697 let has_some_cursor_in_whitespace = selections
8698 .iter()
8699 .filter(|selection| selection.is_empty())
8700 .any(|selection| {
8701 let cursor = selection.head();
8702 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8703 cursor.column < current_indent.len
8704 });
8705
8706 let mut edits = Vec::new();
8707 let mut prev_edited_row = 0;
8708 let mut row_delta = 0;
8709 for selection in &mut selections {
8710 if selection.start.row != prev_edited_row {
8711 row_delta = 0;
8712 }
8713 prev_edited_row = selection.end.row;
8714
8715 // If the selection is non-empty, then increase the indentation of the selected lines.
8716 if !selection.is_empty() {
8717 row_delta =
8718 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8719 continue;
8720 }
8721
8722 // If the selection is empty and the cursor is in the leading whitespace before the
8723 // suggested indentation, then auto-indent the line.
8724 let cursor = selection.head();
8725 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8726 if let Some(suggested_indent) =
8727 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8728 {
8729 // If there exist any empty selection in the leading whitespace, then skip
8730 // indent for selections at the boundary.
8731 if has_some_cursor_in_whitespace
8732 && cursor.column == current_indent.len
8733 && current_indent.len == suggested_indent.len
8734 {
8735 continue;
8736 }
8737
8738 if cursor.column < suggested_indent.len
8739 && cursor.column <= current_indent.len
8740 && current_indent.len <= suggested_indent.len
8741 {
8742 selection.start = Point::new(cursor.row, suggested_indent.len);
8743 selection.end = selection.start;
8744 if row_delta == 0 {
8745 edits.extend(Buffer::edit_for_indent_size_adjustment(
8746 cursor.row,
8747 current_indent,
8748 suggested_indent,
8749 ));
8750 row_delta = suggested_indent.len - current_indent.len;
8751 }
8752 continue;
8753 }
8754 }
8755
8756 // Otherwise, insert a hard or soft tab.
8757 let settings = buffer.language_settings_at(cursor, cx);
8758 let tab_size = if settings.hard_tabs {
8759 IndentSize::tab()
8760 } else {
8761 let tab_size = settings.tab_size.get();
8762 let indent_remainder = snapshot
8763 .text_for_range(Point::new(cursor.row, 0)..cursor)
8764 .flat_map(str::chars)
8765 .fold(row_delta % tab_size, |counter: u32, c| {
8766 if c == '\t' {
8767 0
8768 } else {
8769 (counter + 1) % tab_size
8770 }
8771 });
8772
8773 let chars_to_next_tab_stop = tab_size - indent_remainder;
8774 IndentSize::spaces(chars_to_next_tab_stop)
8775 };
8776 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8777 selection.end = selection.start;
8778 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8779 row_delta += tab_size.len;
8780 }
8781
8782 self.transact(window, cx, |this, window, cx| {
8783 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8784 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8785 s.select(selections)
8786 });
8787 this.refresh_inline_completion(true, false, window, cx);
8788 });
8789 }
8790
8791 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8792 if self.read_only(cx) {
8793 return;
8794 }
8795 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8796 let mut selections = self.selections.all::<Point>(cx);
8797 let mut prev_edited_row = 0;
8798 let mut row_delta = 0;
8799 let mut edits = Vec::new();
8800 let buffer = self.buffer.read(cx);
8801 let snapshot = buffer.snapshot(cx);
8802 for selection in &mut selections {
8803 if selection.start.row != prev_edited_row {
8804 row_delta = 0;
8805 }
8806 prev_edited_row = selection.end.row;
8807
8808 row_delta =
8809 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8810 }
8811
8812 self.transact(window, cx, |this, window, cx| {
8813 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8814 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8815 s.select(selections)
8816 });
8817 });
8818 }
8819
8820 fn indent_selection(
8821 buffer: &MultiBuffer,
8822 snapshot: &MultiBufferSnapshot,
8823 selection: &mut Selection<Point>,
8824 edits: &mut Vec<(Range<Point>, String)>,
8825 delta_for_start_row: u32,
8826 cx: &App,
8827 ) -> u32 {
8828 let settings = buffer.language_settings_at(selection.start, cx);
8829 let tab_size = settings.tab_size.get();
8830 let indent_kind = if settings.hard_tabs {
8831 IndentKind::Tab
8832 } else {
8833 IndentKind::Space
8834 };
8835 let mut start_row = selection.start.row;
8836 let mut end_row = selection.end.row + 1;
8837
8838 // If a selection ends at the beginning of a line, don't indent
8839 // that last line.
8840 if selection.end.column == 0 && selection.end.row > selection.start.row {
8841 end_row -= 1;
8842 }
8843
8844 // Avoid re-indenting a row that has already been indented by a
8845 // previous selection, but still update this selection's column
8846 // to reflect that indentation.
8847 if delta_for_start_row > 0 {
8848 start_row += 1;
8849 selection.start.column += delta_for_start_row;
8850 if selection.end.row == selection.start.row {
8851 selection.end.column += delta_for_start_row;
8852 }
8853 }
8854
8855 let mut delta_for_end_row = 0;
8856 let has_multiple_rows = start_row + 1 != end_row;
8857 for row in start_row..end_row {
8858 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8859 let indent_delta = match (current_indent.kind, indent_kind) {
8860 (IndentKind::Space, IndentKind::Space) => {
8861 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8862 IndentSize::spaces(columns_to_next_tab_stop)
8863 }
8864 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8865 (_, IndentKind::Tab) => IndentSize::tab(),
8866 };
8867
8868 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8869 0
8870 } else {
8871 selection.start.column
8872 };
8873 let row_start = Point::new(row, start);
8874 edits.push((
8875 row_start..row_start,
8876 indent_delta.chars().collect::<String>(),
8877 ));
8878
8879 // Update this selection's endpoints to reflect the indentation.
8880 if row == selection.start.row {
8881 selection.start.column += indent_delta.len;
8882 }
8883 if row == selection.end.row {
8884 selection.end.column += indent_delta.len;
8885 delta_for_end_row = indent_delta.len;
8886 }
8887 }
8888
8889 if selection.start.row == selection.end.row {
8890 delta_for_start_row + delta_for_end_row
8891 } else {
8892 delta_for_end_row
8893 }
8894 }
8895
8896 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8897 if self.read_only(cx) {
8898 return;
8899 }
8900 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8901 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8902 let selections = self.selections.all::<Point>(cx);
8903 let mut deletion_ranges = Vec::new();
8904 let mut last_outdent = None;
8905 {
8906 let buffer = self.buffer.read(cx);
8907 let snapshot = buffer.snapshot(cx);
8908 for selection in &selections {
8909 let settings = buffer.language_settings_at(selection.start, cx);
8910 let tab_size = settings.tab_size.get();
8911 let mut rows = selection.spanned_rows(false, &display_map);
8912
8913 // Avoid re-outdenting a row that has already been outdented by a
8914 // previous selection.
8915 if let Some(last_row) = last_outdent {
8916 if last_row == rows.start {
8917 rows.start = rows.start.next_row();
8918 }
8919 }
8920 let has_multiple_rows = rows.len() > 1;
8921 for row in rows.iter_rows() {
8922 let indent_size = snapshot.indent_size_for_line(row);
8923 if indent_size.len > 0 {
8924 let deletion_len = match indent_size.kind {
8925 IndentKind::Space => {
8926 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8927 if columns_to_prev_tab_stop == 0 {
8928 tab_size
8929 } else {
8930 columns_to_prev_tab_stop
8931 }
8932 }
8933 IndentKind::Tab => 1,
8934 };
8935 let start = if has_multiple_rows
8936 || deletion_len > selection.start.column
8937 || indent_size.len < selection.start.column
8938 {
8939 0
8940 } else {
8941 selection.start.column - deletion_len
8942 };
8943 deletion_ranges.push(
8944 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8945 );
8946 last_outdent = Some(row);
8947 }
8948 }
8949 }
8950 }
8951
8952 self.transact(window, cx, |this, window, cx| {
8953 this.buffer.update(cx, |buffer, cx| {
8954 let empty_str: Arc<str> = Arc::default();
8955 buffer.edit(
8956 deletion_ranges
8957 .into_iter()
8958 .map(|range| (range, empty_str.clone())),
8959 None,
8960 cx,
8961 );
8962 });
8963 let selections = this.selections.all::<usize>(cx);
8964 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8965 s.select(selections)
8966 });
8967 });
8968 }
8969
8970 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8971 if self.read_only(cx) {
8972 return;
8973 }
8974 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8975 let selections = self
8976 .selections
8977 .all::<usize>(cx)
8978 .into_iter()
8979 .map(|s| s.range());
8980
8981 self.transact(window, cx, |this, window, cx| {
8982 this.buffer.update(cx, |buffer, cx| {
8983 buffer.autoindent_ranges(selections, cx);
8984 });
8985 let selections = this.selections.all::<usize>(cx);
8986 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8987 s.select(selections)
8988 });
8989 });
8990 }
8991
8992 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8993 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8994 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8995 let selections = self.selections.all::<Point>(cx);
8996
8997 let mut new_cursors = Vec::new();
8998 let mut edit_ranges = Vec::new();
8999 let mut selections = selections.iter().peekable();
9000 while let Some(selection) = selections.next() {
9001 let mut rows = selection.spanned_rows(false, &display_map);
9002 let goal_display_column = selection.head().to_display_point(&display_map).column();
9003
9004 // Accumulate contiguous regions of rows that we want to delete.
9005 while let Some(next_selection) = selections.peek() {
9006 let next_rows = next_selection.spanned_rows(false, &display_map);
9007 if next_rows.start <= rows.end {
9008 rows.end = next_rows.end;
9009 selections.next().unwrap();
9010 } else {
9011 break;
9012 }
9013 }
9014
9015 let buffer = &display_map.buffer_snapshot;
9016 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
9017 let edit_end;
9018 let cursor_buffer_row;
9019 if buffer.max_point().row >= rows.end.0 {
9020 // If there's a line after the range, delete the \n from the end of the row range
9021 // and position the cursor on the next line.
9022 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
9023 cursor_buffer_row = rows.end;
9024 } else {
9025 // If there isn't a line after the range, delete the \n from the line before the
9026 // start of the row range and position the cursor there.
9027 edit_start = edit_start.saturating_sub(1);
9028 edit_end = buffer.len();
9029 cursor_buffer_row = rows.start.previous_row();
9030 }
9031
9032 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
9033 *cursor.column_mut() =
9034 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
9035
9036 new_cursors.push((
9037 selection.id,
9038 buffer.anchor_after(cursor.to_point(&display_map)),
9039 ));
9040 edit_ranges.push(edit_start..edit_end);
9041 }
9042
9043 self.transact(window, cx, |this, window, cx| {
9044 let buffer = this.buffer.update(cx, |buffer, cx| {
9045 let empty_str: Arc<str> = Arc::default();
9046 buffer.edit(
9047 edit_ranges
9048 .into_iter()
9049 .map(|range| (range, empty_str.clone())),
9050 None,
9051 cx,
9052 );
9053 buffer.snapshot(cx)
9054 });
9055 let new_selections = new_cursors
9056 .into_iter()
9057 .map(|(id, cursor)| {
9058 let cursor = cursor.to_point(&buffer);
9059 Selection {
9060 id,
9061 start: cursor,
9062 end: cursor,
9063 reversed: false,
9064 goal: SelectionGoal::None,
9065 }
9066 })
9067 .collect();
9068
9069 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9070 s.select(new_selections);
9071 });
9072 });
9073 }
9074
9075 pub fn join_lines_impl(
9076 &mut self,
9077 insert_whitespace: bool,
9078 window: &mut Window,
9079 cx: &mut Context<Self>,
9080 ) {
9081 if self.read_only(cx) {
9082 return;
9083 }
9084 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
9085 for selection in self.selections.all::<Point>(cx) {
9086 let start = MultiBufferRow(selection.start.row);
9087 // Treat single line selections as if they include the next line. Otherwise this action
9088 // would do nothing for single line selections individual cursors.
9089 let end = if selection.start.row == selection.end.row {
9090 MultiBufferRow(selection.start.row + 1)
9091 } else {
9092 MultiBufferRow(selection.end.row)
9093 };
9094
9095 if let Some(last_row_range) = row_ranges.last_mut() {
9096 if start <= last_row_range.end {
9097 last_row_range.end = end;
9098 continue;
9099 }
9100 }
9101 row_ranges.push(start..end);
9102 }
9103
9104 let snapshot = self.buffer.read(cx).snapshot(cx);
9105 let mut cursor_positions = Vec::new();
9106 for row_range in &row_ranges {
9107 let anchor = snapshot.anchor_before(Point::new(
9108 row_range.end.previous_row().0,
9109 snapshot.line_len(row_range.end.previous_row()),
9110 ));
9111 cursor_positions.push(anchor..anchor);
9112 }
9113
9114 self.transact(window, cx, |this, window, cx| {
9115 for row_range in row_ranges.into_iter().rev() {
9116 for row in row_range.iter_rows().rev() {
9117 let end_of_line = Point::new(row.0, snapshot.line_len(row));
9118 let next_line_row = row.next_row();
9119 let indent = snapshot.indent_size_for_line(next_line_row);
9120 let start_of_next_line = Point::new(next_line_row.0, indent.len);
9121
9122 let replace =
9123 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
9124 " "
9125 } else {
9126 ""
9127 };
9128
9129 this.buffer.update(cx, |buffer, cx| {
9130 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
9131 });
9132 }
9133 }
9134
9135 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9136 s.select_anchor_ranges(cursor_positions)
9137 });
9138 });
9139 }
9140
9141 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
9142 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9143 self.join_lines_impl(true, window, cx);
9144 }
9145
9146 pub fn sort_lines_case_sensitive(
9147 &mut self,
9148 _: &SortLinesCaseSensitive,
9149 window: &mut Window,
9150 cx: &mut Context<Self>,
9151 ) {
9152 self.manipulate_lines(window, cx, |lines| lines.sort())
9153 }
9154
9155 pub fn sort_lines_case_insensitive(
9156 &mut self,
9157 _: &SortLinesCaseInsensitive,
9158 window: &mut Window,
9159 cx: &mut Context<Self>,
9160 ) {
9161 self.manipulate_lines(window, cx, |lines| {
9162 lines.sort_by_key(|line| line.to_lowercase())
9163 })
9164 }
9165
9166 pub fn unique_lines_case_insensitive(
9167 &mut self,
9168 _: &UniqueLinesCaseInsensitive,
9169 window: &mut Window,
9170 cx: &mut Context<Self>,
9171 ) {
9172 self.manipulate_lines(window, cx, |lines| {
9173 let mut seen = HashSet::default();
9174 lines.retain(|line| seen.insert(line.to_lowercase()));
9175 })
9176 }
9177
9178 pub fn unique_lines_case_sensitive(
9179 &mut self,
9180 _: &UniqueLinesCaseSensitive,
9181 window: &mut Window,
9182 cx: &mut Context<Self>,
9183 ) {
9184 self.manipulate_lines(window, cx, |lines| {
9185 let mut seen = HashSet::default();
9186 lines.retain(|line| seen.insert(*line));
9187 })
9188 }
9189
9190 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
9191 let Some(project) = self.project.clone() else {
9192 return;
9193 };
9194 self.reload(project, window, cx)
9195 .detach_and_notify_err(window, cx);
9196 }
9197
9198 pub fn restore_file(
9199 &mut self,
9200 _: &::git::RestoreFile,
9201 window: &mut Window,
9202 cx: &mut Context<Self>,
9203 ) {
9204 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9205 let mut buffer_ids = HashSet::default();
9206 let snapshot = self.buffer().read(cx).snapshot(cx);
9207 for selection in self.selections.all::<usize>(cx) {
9208 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
9209 }
9210
9211 let buffer = self.buffer().read(cx);
9212 let ranges = buffer_ids
9213 .into_iter()
9214 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
9215 .collect::<Vec<_>>();
9216
9217 self.restore_hunks_in_ranges(ranges, window, cx);
9218 }
9219
9220 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
9221 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9222 let selections = self
9223 .selections
9224 .all(cx)
9225 .into_iter()
9226 .map(|s| s.range())
9227 .collect();
9228 self.restore_hunks_in_ranges(selections, window, cx);
9229 }
9230
9231 pub fn restore_hunks_in_ranges(
9232 &mut self,
9233 ranges: Vec<Range<Point>>,
9234 window: &mut Window,
9235 cx: &mut Context<Editor>,
9236 ) {
9237 let mut revert_changes = HashMap::default();
9238 let chunk_by = self
9239 .snapshot(window, cx)
9240 .hunks_for_ranges(ranges)
9241 .into_iter()
9242 .chunk_by(|hunk| hunk.buffer_id);
9243 for (buffer_id, hunks) in &chunk_by {
9244 let hunks = hunks.collect::<Vec<_>>();
9245 for hunk in &hunks {
9246 self.prepare_restore_change(&mut revert_changes, hunk, cx);
9247 }
9248 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
9249 }
9250 drop(chunk_by);
9251 if !revert_changes.is_empty() {
9252 self.transact(window, cx, |editor, window, cx| {
9253 editor.restore(revert_changes, window, cx);
9254 });
9255 }
9256 }
9257
9258 pub fn open_active_item_in_terminal(
9259 &mut self,
9260 _: &OpenInTerminal,
9261 window: &mut Window,
9262 cx: &mut Context<Self>,
9263 ) {
9264 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
9265 let project_path = buffer.read(cx).project_path(cx)?;
9266 let project = self.project.as_ref()?.read(cx);
9267 let entry = project.entry_for_path(&project_path, cx)?;
9268 let parent = match &entry.canonical_path {
9269 Some(canonical_path) => canonical_path.to_path_buf(),
9270 None => project.absolute_path(&project_path, cx)?,
9271 }
9272 .parent()?
9273 .to_path_buf();
9274 Some(parent)
9275 }) {
9276 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
9277 }
9278 }
9279
9280 fn set_breakpoint_context_menu(
9281 &mut self,
9282 display_row: DisplayRow,
9283 position: Option<Anchor>,
9284 clicked_point: gpui::Point<Pixels>,
9285 window: &mut Window,
9286 cx: &mut Context<Self>,
9287 ) {
9288 if !cx.has_flag::<DebuggerFeatureFlag>() {
9289 return;
9290 }
9291 let source = self
9292 .buffer
9293 .read(cx)
9294 .snapshot(cx)
9295 .anchor_before(Point::new(display_row.0, 0u32));
9296
9297 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
9298
9299 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
9300 self,
9301 source,
9302 clicked_point,
9303 context_menu,
9304 window,
9305 cx,
9306 );
9307 }
9308
9309 fn add_edit_breakpoint_block(
9310 &mut self,
9311 anchor: Anchor,
9312 breakpoint: &Breakpoint,
9313 edit_action: BreakpointPromptEditAction,
9314 window: &mut Window,
9315 cx: &mut Context<Self>,
9316 ) {
9317 let weak_editor = cx.weak_entity();
9318 let bp_prompt = cx.new(|cx| {
9319 BreakpointPromptEditor::new(
9320 weak_editor,
9321 anchor,
9322 breakpoint.clone(),
9323 edit_action,
9324 window,
9325 cx,
9326 )
9327 });
9328
9329 let height = bp_prompt.update(cx, |this, cx| {
9330 this.prompt
9331 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
9332 });
9333 let cloned_prompt = bp_prompt.clone();
9334 let blocks = vec![BlockProperties {
9335 style: BlockStyle::Sticky,
9336 placement: BlockPlacement::Above(anchor),
9337 height: Some(height),
9338 render: Arc::new(move |cx| {
9339 *cloned_prompt.read(cx).editor_margins.lock() = *cx.margins;
9340 cloned_prompt.clone().into_any_element()
9341 }),
9342 priority: 0,
9343 render_in_minimap: true,
9344 }];
9345
9346 let focus_handle = bp_prompt.focus_handle(cx);
9347 window.focus(&focus_handle);
9348
9349 let block_ids = self.insert_blocks(blocks, None, cx);
9350 bp_prompt.update(cx, |prompt, _| {
9351 prompt.add_block_ids(block_ids);
9352 });
9353 }
9354
9355 pub(crate) fn breakpoint_at_row(
9356 &self,
9357 row: u32,
9358 window: &mut Window,
9359 cx: &mut Context<Self>,
9360 ) -> Option<(Anchor, Breakpoint)> {
9361 let snapshot = self.snapshot(window, cx);
9362 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9363
9364 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9365 }
9366
9367 pub(crate) fn breakpoint_at_anchor(
9368 &self,
9369 breakpoint_position: Anchor,
9370 snapshot: &EditorSnapshot,
9371 cx: &mut Context<Self>,
9372 ) -> Option<(Anchor, Breakpoint)> {
9373 let project = self.project.clone()?;
9374
9375 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9376 snapshot
9377 .buffer_snapshot
9378 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9379 })?;
9380
9381 let enclosing_excerpt = breakpoint_position.excerpt_id;
9382 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9383 let buffer_snapshot = buffer.read(cx).snapshot();
9384
9385 let row = buffer_snapshot
9386 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9387 .row;
9388
9389 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9390 let anchor_end = snapshot
9391 .buffer_snapshot
9392 .anchor_after(Point::new(row, line_len));
9393
9394 let bp = self
9395 .breakpoint_store
9396 .as_ref()?
9397 .read_with(cx, |breakpoint_store, cx| {
9398 breakpoint_store
9399 .breakpoints(
9400 &buffer,
9401 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9402 &buffer_snapshot,
9403 cx,
9404 )
9405 .next()
9406 .and_then(|(anchor, bp)| {
9407 let breakpoint_row = buffer_snapshot
9408 .summary_for_anchor::<text::PointUtf16>(anchor)
9409 .row;
9410
9411 if breakpoint_row == row {
9412 snapshot
9413 .buffer_snapshot
9414 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9415 .map(|anchor| (anchor, bp.clone()))
9416 } else {
9417 None
9418 }
9419 })
9420 });
9421 bp
9422 }
9423
9424 pub fn edit_log_breakpoint(
9425 &mut self,
9426 _: &EditLogBreakpoint,
9427 window: &mut Window,
9428 cx: &mut Context<Self>,
9429 ) {
9430 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9431 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9432 message: None,
9433 state: BreakpointState::Enabled,
9434 condition: None,
9435 hit_condition: None,
9436 });
9437
9438 self.add_edit_breakpoint_block(
9439 anchor,
9440 &breakpoint,
9441 BreakpointPromptEditAction::Log,
9442 window,
9443 cx,
9444 );
9445 }
9446 }
9447
9448 fn breakpoints_at_cursors(
9449 &self,
9450 window: &mut Window,
9451 cx: &mut Context<Self>,
9452 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9453 let snapshot = self.snapshot(window, cx);
9454 let cursors = self
9455 .selections
9456 .disjoint_anchors()
9457 .into_iter()
9458 .map(|selection| {
9459 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9460
9461 let breakpoint_position = self
9462 .breakpoint_at_row(cursor_position.row, window, cx)
9463 .map(|bp| bp.0)
9464 .unwrap_or_else(|| {
9465 snapshot
9466 .display_snapshot
9467 .buffer_snapshot
9468 .anchor_after(Point::new(cursor_position.row, 0))
9469 });
9470
9471 let breakpoint = self
9472 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9473 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9474
9475 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9476 })
9477 // 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.
9478 .collect::<HashMap<Anchor, _>>();
9479
9480 cursors.into_iter().collect()
9481 }
9482
9483 pub fn enable_breakpoint(
9484 &mut self,
9485 _: &crate::actions::EnableBreakpoint,
9486 window: &mut Window,
9487 cx: &mut Context<Self>,
9488 ) {
9489 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9490 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9491 continue;
9492 };
9493 self.edit_breakpoint_at_anchor(
9494 anchor,
9495 breakpoint,
9496 BreakpointEditAction::InvertState,
9497 cx,
9498 );
9499 }
9500 }
9501
9502 pub fn disable_breakpoint(
9503 &mut self,
9504 _: &crate::actions::DisableBreakpoint,
9505 window: &mut Window,
9506 cx: &mut Context<Self>,
9507 ) {
9508 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9509 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9510 continue;
9511 };
9512 self.edit_breakpoint_at_anchor(
9513 anchor,
9514 breakpoint,
9515 BreakpointEditAction::InvertState,
9516 cx,
9517 );
9518 }
9519 }
9520
9521 pub fn toggle_breakpoint(
9522 &mut self,
9523 _: &crate::actions::ToggleBreakpoint,
9524 window: &mut Window,
9525 cx: &mut Context<Self>,
9526 ) {
9527 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9528 if let Some(breakpoint) = breakpoint {
9529 self.edit_breakpoint_at_anchor(
9530 anchor,
9531 breakpoint,
9532 BreakpointEditAction::Toggle,
9533 cx,
9534 );
9535 } else {
9536 self.edit_breakpoint_at_anchor(
9537 anchor,
9538 Breakpoint::new_standard(),
9539 BreakpointEditAction::Toggle,
9540 cx,
9541 );
9542 }
9543 }
9544 }
9545
9546 pub fn edit_breakpoint_at_anchor(
9547 &mut self,
9548 breakpoint_position: Anchor,
9549 breakpoint: Breakpoint,
9550 edit_action: BreakpointEditAction,
9551 cx: &mut Context<Self>,
9552 ) {
9553 let Some(breakpoint_store) = &self.breakpoint_store else {
9554 return;
9555 };
9556
9557 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9558 if breakpoint_position == Anchor::min() {
9559 self.buffer()
9560 .read(cx)
9561 .excerpt_buffer_ids()
9562 .into_iter()
9563 .next()
9564 } else {
9565 None
9566 }
9567 }) else {
9568 return;
9569 };
9570
9571 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9572 return;
9573 };
9574
9575 breakpoint_store.update(cx, |breakpoint_store, cx| {
9576 breakpoint_store.toggle_breakpoint(
9577 buffer,
9578 (breakpoint_position.text_anchor, breakpoint),
9579 edit_action,
9580 cx,
9581 );
9582 });
9583
9584 cx.notify();
9585 }
9586
9587 #[cfg(any(test, feature = "test-support"))]
9588 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9589 self.breakpoint_store.clone()
9590 }
9591
9592 pub fn prepare_restore_change(
9593 &self,
9594 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9595 hunk: &MultiBufferDiffHunk,
9596 cx: &mut App,
9597 ) -> Option<()> {
9598 if hunk.is_created_file() {
9599 return None;
9600 }
9601 let buffer = self.buffer.read(cx);
9602 let diff = buffer.diff_for(hunk.buffer_id)?;
9603 let buffer = buffer.buffer(hunk.buffer_id)?;
9604 let buffer = buffer.read(cx);
9605 let original_text = diff
9606 .read(cx)
9607 .base_text()
9608 .as_rope()
9609 .slice(hunk.diff_base_byte_range.clone());
9610 let buffer_snapshot = buffer.snapshot();
9611 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9612 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9613 probe
9614 .0
9615 .start
9616 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9617 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9618 }) {
9619 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9620 Some(())
9621 } else {
9622 None
9623 }
9624 }
9625
9626 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9627 self.manipulate_lines(window, cx, |lines| lines.reverse())
9628 }
9629
9630 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9631 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9632 }
9633
9634 fn manipulate_lines<Fn>(
9635 &mut self,
9636 window: &mut Window,
9637 cx: &mut Context<Self>,
9638 mut callback: Fn,
9639 ) where
9640 Fn: FnMut(&mut Vec<&str>),
9641 {
9642 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9643
9644 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9645 let buffer = self.buffer.read(cx).snapshot(cx);
9646
9647 let mut edits = Vec::new();
9648
9649 let selections = self.selections.all::<Point>(cx);
9650 let mut selections = selections.iter().peekable();
9651 let mut contiguous_row_selections = Vec::new();
9652 let mut new_selections = Vec::new();
9653 let mut added_lines = 0;
9654 let mut removed_lines = 0;
9655
9656 while let Some(selection) = selections.next() {
9657 let (start_row, end_row) = consume_contiguous_rows(
9658 &mut contiguous_row_selections,
9659 selection,
9660 &display_map,
9661 &mut selections,
9662 );
9663
9664 let start_point = Point::new(start_row.0, 0);
9665 let end_point = Point::new(
9666 end_row.previous_row().0,
9667 buffer.line_len(end_row.previous_row()),
9668 );
9669 let text = buffer
9670 .text_for_range(start_point..end_point)
9671 .collect::<String>();
9672
9673 let mut lines = text.split('\n').collect_vec();
9674
9675 let lines_before = lines.len();
9676 callback(&mut lines);
9677 let lines_after = lines.len();
9678
9679 edits.push((start_point..end_point, lines.join("\n")));
9680
9681 // Selections must change based on added and removed line count
9682 let start_row =
9683 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9684 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9685 new_selections.push(Selection {
9686 id: selection.id,
9687 start: start_row,
9688 end: end_row,
9689 goal: SelectionGoal::None,
9690 reversed: selection.reversed,
9691 });
9692
9693 if lines_after > lines_before {
9694 added_lines += lines_after - lines_before;
9695 } else if lines_before > lines_after {
9696 removed_lines += lines_before - lines_after;
9697 }
9698 }
9699
9700 self.transact(window, cx, |this, window, cx| {
9701 let buffer = this.buffer.update(cx, |buffer, cx| {
9702 buffer.edit(edits, None, cx);
9703 buffer.snapshot(cx)
9704 });
9705
9706 // Recalculate offsets on newly edited buffer
9707 let new_selections = new_selections
9708 .iter()
9709 .map(|s| {
9710 let start_point = Point::new(s.start.0, 0);
9711 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9712 Selection {
9713 id: s.id,
9714 start: buffer.point_to_offset(start_point),
9715 end: buffer.point_to_offset(end_point),
9716 goal: s.goal,
9717 reversed: s.reversed,
9718 }
9719 })
9720 .collect();
9721
9722 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9723 s.select(new_selections);
9724 });
9725
9726 this.request_autoscroll(Autoscroll::fit(), cx);
9727 });
9728 }
9729
9730 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9731 self.manipulate_text(window, cx, |text| {
9732 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9733 if has_upper_case_characters {
9734 text.to_lowercase()
9735 } else {
9736 text.to_uppercase()
9737 }
9738 })
9739 }
9740
9741 pub fn convert_to_upper_case(
9742 &mut self,
9743 _: &ConvertToUpperCase,
9744 window: &mut Window,
9745 cx: &mut Context<Self>,
9746 ) {
9747 self.manipulate_text(window, cx, |text| text.to_uppercase())
9748 }
9749
9750 pub fn convert_to_lower_case(
9751 &mut self,
9752 _: &ConvertToLowerCase,
9753 window: &mut Window,
9754 cx: &mut Context<Self>,
9755 ) {
9756 self.manipulate_text(window, cx, |text| text.to_lowercase())
9757 }
9758
9759 pub fn convert_to_title_case(
9760 &mut self,
9761 _: &ConvertToTitleCase,
9762 window: &mut Window,
9763 cx: &mut Context<Self>,
9764 ) {
9765 self.manipulate_text(window, cx, |text| {
9766 text.split('\n')
9767 .map(|line| line.to_case(Case::Title))
9768 .join("\n")
9769 })
9770 }
9771
9772 pub fn convert_to_snake_case(
9773 &mut self,
9774 _: &ConvertToSnakeCase,
9775 window: &mut Window,
9776 cx: &mut Context<Self>,
9777 ) {
9778 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9779 }
9780
9781 pub fn convert_to_kebab_case(
9782 &mut self,
9783 _: &ConvertToKebabCase,
9784 window: &mut Window,
9785 cx: &mut Context<Self>,
9786 ) {
9787 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9788 }
9789
9790 pub fn convert_to_upper_camel_case(
9791 &mut self,
9792 _: &ConvertToUpperCamelCase,
9793 window: &mut Window,
9794 cx: &mut Context<Self>,
9795 ) {
9796 self.manipulate_text(window, cx, |text| {
9797 text.split('\n')
9798 .map(|line| line.to_case(Case::UpperCamel))
9799 .join("\n")
9800 })
9801 }
9802
9803 pub fn convert_to_lower_camel_case(
9804 &mut self,
9805 _: &ConvertToLowerCamelCase,
9806 window: &mut Window,
9807 cx: &mut Context<Self>,
9808 ) {
9809 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9810 }
9811
9812 pub fn convert_to_opposite_case(
9813 &mut self,
9814 _: &ConvertToOppositeCase,
9815 window: &mut Window,
9816 cx: &mut Context<Self>,
9817 ) {
9818 self.manipulate_text(window, cx, |text| {
9819 text.chars()
9820 .fold(String::with_capacity(text.len()), |mut t, c| {
9821 if c.is_uppercase() {
9822 t.extend(c.to_lowercase());
9823 } else {
9824 t.extend(c.to_uppercase());
9825 }
9826 t
9827 })
9828 })
9829 }
9830
9831 pub fn convert_to_rot13(
9832 &mut self,
9833 _: &ConvertToRot13,
9834 window: &mut Window,
9835 cx: &mut Context<Self>,
9836 ) {
9837 self.manipulate_text(window, cx, |text| {
9838 text.chars()
9839 .map(|c| match c {
9840 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9841 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9842 _ => c,
9843 })
9844 .collect()
9845 })
9846 }
9847
9848 pub fn convert_to_rot47(
9849 &mut self,
9850 _: &ConvertToRot47,
9851 window: &mut Window,
9852 cx: &mut Context<Self>,
9853 ) {
9854 self.manipulate_text(window, cx, |text| {
9855 text.chars()
9856 .map(|c| {
9857 let code_point = c as u32;
9858 if code_point >= 33 && code_point <= 126 {
9859 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9860 }
9861 c
9862 })
9863 .collect()
9864 })
9865 }
9866
9867 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9868 where
9869 Fn: FnMut(&str) -> String,
9870 {
9871 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9872 let buffer = self.buffer.read(cx).snapshot(cx);
9873
9874 let mut new_selections = Vec::new();
9875 let mut edits = Vec::new();
9876 let mut selection_adjustment = 0i32;
9877
9878 for selection in self.selections.all::<usize>(cx) {
9879 let selection_is_empty = selection.is_empty();
9880
9881 let (start, end) = if selection_is_empty {
9882 let word_range = movement::surrounding_word(
9883 &display_map,
9884 selection.start.to_display_point(&display_map),
9885 );
9886 let start = word_range.start.to_offset(&display_map, Bias::Left);
9887 let end = word_range.end.to_offset(&display_map, Bias::Left);
9888 (start, end)
9889 } else {
9890 (selection.start, selection.end)
9891 };
9892
9893 let text = buffer.text_for_range(start..end).collect::<String>();
9894 let old_length = text.len() as i32;
9895 let text = callback(&text);
9896
9897 new_selections.push(Selection {
9898 start: (start as i32 - selection_adjustment) as usize,
9899 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9900 goal: SelectionGoal::None,
9901 ..selection
9902 });
9903
9904 selection_adjustment += old_length - text.len() as i32;
9905
9906 edits.push((start..end, text));
9907 }
9908
9909 self.transact(window, cx, |this, window, cx| {
9910 this.buffer.update(cx, |buffer, cx| {
9911 buffer.edit(edits, None, cx);
9912 });
9913
9914 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9915 s.select(new_selections);
9916 });
9917
9918 this.request_autoscroll(Autoscroll::fit(), cx);
9919 });
9920 }
9921
9922 pub fn duplicate(
9923 &mut self,
9924 upwards: bool,
9925 whole_lines: bool,
9926 window: &mut Window,
9927 cx: &mut Context<Self>,
9928 ) {
9929 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9930
9931 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9932 let buffer = &display_map.buffer_snapshot;
9933 let selections = self.selections.all::<Point>(cx);
9934
9935 let mut edits = Vec::new();
9936 let mut selections_iter = selections.iter().peekable();
9937 while let Some(selection) = selections_iter.next() {
9938 let mut rows = selection.spanned_rows(false, &display_map);
9939 // duplicate line-wise
9940 if whole_lines || selection.start == selection.end {
9941 // Avoid duplicating the same lines twice.
9942 while let Some(next_selection) = selections_iter.peek() {
9943 let next_rows = next_selection.spanned_rows(false, &display_map);
9944 if next_rows.start < rows.end {
9945 rows.end = next_rows.end;
9946 selections_iter.next().unwrap();
9947 } else {
9948 break;
9949 }
9950 }
9951
9952 // Copy the text from the selected row region and splice it either at the start
9953 // or end of the region.
9954 let start = Point::new(rows.start.0, 0);
9955 let end = Point::new(
9956 rows.end.previous_row().0,
9957 buffer.line_len(rows.end.previous_row()),
9958 );
9959 let text = buffer
9960 .text_for_range(start..end)
9961 .chain(Some("\n"))
9962 .collect::<String>();
9963 let insert_location = if upwards {
9964 Point::new(rows.end.0, 0)
9965 } else {
9966 start
9967 };
9968 edits.push((insert_location..insert_location, text));
9969 } else {
9970 // duplicate character-wise
9971 let start = selection.start;
9972 let end = selection.end;
9973 let text = buffer.text_for_range(start..end).collect::<String>();
9974 edits.push((selection.end..selection.end, text));
9975 }
9976 }
9977
9978 self.transact(window, cx, |this, _, cx| {
9979 this.buffer.update(cx, |buffer, cx| {
9980 buffer.edit(edits, None, cx);
9981 });
9982
9983 this.request_autoscroll(Autoscroll::fit(), cx);
9984 });
9985 }
9986
9987 pub fn duplicate_line_up(
9988 &mut self,
9989 _: &DuplicateLineUp,
9990 window: &mut Window,
9991 cx: &mut Context<Self>,
9992 ) {
9993 self.duplicate(true, true, window, cx);
9994 }
9995
9996 pub fn duplicate_line_down(
9997 &mut self,
9998 _: &DuplicateLineDown,
9999 window: &mut Window,
10000 cx: &mut Context<Self>,
10001 ) {
10002 self.duplicate(false, true, window, cx);
10003 }
10004
10005 pub fn duplicate_selection(
10006 &mut self,
10007 _: &DuplicateSelection,
10008 window: &mut Window,
10009 cx: &mut Context<Self>,
10010 ) {
10011 self.duplicate(false, false, window, cx);
10012 }
10013
10014 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
10015 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10016
10017 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10018 let buffer = self.buffer.read(cx).snapshot(cx);
10019
10020 let mut edits = Vec::new();
10021 let mut unfold_ranges = Vec::new();
10022 let mut refold_creases = Vec::new();
10023
10024 let selections = self.selections.all::<Point>(cx);
10025 let mut selections = selections.iter().peekable();
10026 let mut contiguous_row_selections = Vec::new();
10027 let mut new_selections = Vec::new();
10028
10029 while let Some(selection) = selections.next() {
10030 // Find all the selections that span a contiguous row range
10031 let (start_row, end_row) = consume_contiguous_rows(
10032 &mut contiguous_row_selections,
10033 selection,
10034 &display_map,
10035 &mut selections,
10036 );
10037
10038 // Move the text spanned by the row range to be before the line preceding the row range
10039 if start_row.0 > 0 {
10040 let range_to_move = Point::new(
10041 start_row.previous_row().0,
10042 buffer.line_len(start_row.previous_row()),
10043 )
10044 ..Point::new(
10045 end_row.previous_row().0,
10046 buffer.line_len(end_row.previous_row()),
10047 );
10048 let insertion_point = display_map
10049 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
10050 .0;
10051
10052 // Don't move lines across excerpts
10053 if buffer
10054 .excerpt_containing(insertion_point..range_to_move.end)
10055 .is_some()
10056 {
10057 let text = buffer
10058 .text_for_range(range_to_move.clone())
10059 .flat_map(|s| s.chars())
10060 .skip(1)
10061 .chain(['\n'])
10062 .collect::<String>();
10063
10064 edits.push((
10065 buffer.anchor_after(range_to_move.start)
10066 ..buffer.anchor_before(range_to_move.end),
10067 String::new(),
10068 ));
10069 let insertion_anchor = buffer.anchor_after(insertion_point);
10070 edits.push((insertion_anchor..insertion_anchor, text));
10071
10072 let row_delta = range_to_move.start.row - insertion_point.row + 1;
10073
10074 // Move selections up
10075 new_selections.extend(contiguous_row_selections.drain(..).map(
10076 |mut selection| {
10077 selection.start.row -= row_delta;
10078 selection.end.row -= row_delta;
10079 selection
10080 },
10081 ));
10082
10083 // Move folds up
10084 unfold_ranges.push(range_to_move.clone());
10085 for fold in display_map.folds_in_range(
10086 buffer.anchor_before(range_to_move.start)
10087 ..buffer.anchor_after(range_to_move.end),
10088 ) {
10089 let mut start = fold.range.start.to_point(&buffer);
10090 let mut end = fold.range.end.to_point(&buffer);
10091 start.row -= row_delta;
10092 end.row -= row_delta;
10093 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10094 }
10095 }
10096 }
10097
10098 // If we didn't move line(s), preserve the existing selections
10099 new_selections.append(&mut contiguous_row_selections);
10100 }
10101
10102 self.transact(window, cx, |this, window, cx| {
10103 this.unfold_ranges(&unfold_ranges, true, true, cx);
10104 this.buffer.update(cx, |buffer, cx| {
10105 for (range, text) in edits {
10106 buffer.edit([(range, text)], None, cx);
10107 }
10108 });
10109 this.fold_creases(refold_creases, true, window, cx);
10110 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10111 s.select(new_selections);
10112 })
10113 });
10114 }
10115
10116 pub fn move_line_down(
10117 &mut self,
10118 _: &MoveLineDown,
10119 window: &mut Window,
10120 cx: &mut Context<Self>,
10121 ) {
10122 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10123
10124 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10125 let buffer = self.buffer.read(cx).snapshot(cx);
10126
10127 let mut edits = Vec::new();
10128 let mut unfold_ranges = Vec::new();
10129 let mut refold_creases = Vec::new();
10130
10131 let selections = self.selections.all::<Point>(cx);
10132 let mut selections = selections.iter().peekable();
10133 let mut contiguous_row_selections = Vec::new();
10134 let mut new_selections = Vec::new();
10135
10136 while let Some(selection) = selections.next() {
10137 // Find all the selections that span a contiguous row range
10138 let (start_row, end_row) = consume_contiguous_rows(
10139 &mut contiguous_row_selections,
10140 selection,
10141 &display_map,
10142 &mut selections,
10143 );
10144
10145 // Move the text spanned by the row range to be after the last line of the row range
10146 if end_row.0 <= buffer.max_point().row {
10147 let range_to_move =
10148 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
10149 let insertion_point = display_map
10150 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
10151 .0;
10152
10153 // Don't move lines across excerpt boundaries
10154 if buffer
10155 .excerpt_containing(range_to_move.start..insertion_point)
10156 .is_some()
10157 {
10158 let mut text = String::from("\n");
10159 text.extend(buffer.text_for_range(range_to_move.clone()));
10160 text.pop(); // Drop trailing newline
10161 edits.push((
10162 buffer.anchor_after(range_to_move.start)
10163 ..buffer.anchor_before(range_to_move.end),
10164 String::new(),
10165 ));
10166 let insertion_anchor = buffer.anchor_after(insertion_point);
10167 edits.push((insertion_anchor..insertion_anchor, text));
10168
10169 let row_delta = insertion_point.row - range_to_move.end.row + 1;
10170
10171 // Move selections down
10172 new_selections.extend(contiguous_row_selections.drain(..).map(
10173 |mut selection| {
10174 selection.start.row += row_delta;
10175 selection.end.row += row_delta;
10176 selection
10177 },
10178 ));
10179
10180 // Move folds down
10181 unfold_ranges.push(range_to_move.clone());
10182 for fold in display_map.folds_in_range(
10183 buffer.anchor_before(range_to_move.start)
10184 ..buffer.anchor_after(range_to_move.end),
10185 ) {
10186 let mut start = fold.range.start.to_point(&buffer);
10187 let mut end = fold.range.end.to_point(&buffer);
10188 start.row += row_delta;
10189 end.row += row_delta;
10190 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
10191 }
10192 }
10193 }
10194
10195 // If we didn't move line(s), preserve the existing selections
10196 new_selections.append(&mut contiguous_row_selections);
10197 }
10198
10199 self.transact(window, cx, |this, window, cx| {
10200 this.unfold_ranges(&unfold_ranges, true, true, cx);
10201 this.buffer.update(cx, |buffer, cx| {
10202 for (range, text) in edits {
10203 buffer.edit([(range, text)], None, cx);
10204 }
10205 });
10206 this.fold_creases(refold_creases, true, window, cx);
10207 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10208 s.select(new_selections)
10209 });
10210 });
10211 }
10212
10213 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
10214 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10215 let text_layout_details = &self.text_layout_details(window);
10216 self.transact(window, cx, |this, window, cx| {
10217 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10218 let mut edits: Vec<(Range<usize>, String)> = Default::default();
10219 s.move_with(|display_map, selection| {
10220 if !selection.is_empty() {
10221 return;
10222 }
10223
10224 let mut head = selection.head();
10225 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
10226 if head.column() == display_map.line_len(head.row()) {
10227 transpose_offset = display_map
10228 .buffer_snapshot
10229 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10230 }
10231
10232 if transpose_offset == 0 {
10233 return;
10234 }
10235
10236 *head.column_mut() += 1;
10237 head = display_map.clip_point(head, Bias::Right);
10238 let goal = SelectionGoal::HorizontalPosition(
10239 display_map
10240 .x_for_display_point(head, text_layout_details)
10241 .into(),
10242 );
10243 selection.collapse_to(head, goal);
10244
10245 let transpose_start = display_map
10246 .buffer_snapshot
10247 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
10248 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
10249 let transpose_end = display_map
10250 .buffer_snapshot
10251 .clip_offset(transpose_offset + 1, Bias::Right);
10252 if let Some(ch) =
10253 display_map.buffer_snapshot.chars_at(transpose_start).next()
10254 {
10255 edits.push((transpose_start..transpose_offset, String::new()));
10256 edits.push((transpose_end..transpose_end, ch.to_string()));
10257 }
10258 }
10259 });
10260 edits
10261 });
10262 this.buffer
10263 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10264 let selections = this.selections.all::<usize>(cx);
10265 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10266 s.select(selections);
10267 });
10268 });
10269 }
10270
10271 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
10272 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10273 self.rewrap_impl(RewrapOptions::default(), cx)
10274 }
10275
10276 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
10277 let buffer = self.buffer.read(cx).snapshot(cx);
10278 let selections = self.selections.all::<Point>(cx);
10279 let mut selections = selections.iter().peekable();
10280
10281 let mut edits = Vec::new();
10282 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
10283
10284 while let Some(selection) = selections.next() {
10285 let mut start_row = selection.start.row;
10286 let mut end_row = selection.end.row;
10287
10288 // Skip selections that overlap with a range that has already been rewrapped.
10289 let selection_range = start_row..end_row;
10290 if rewrapped_row_ranges
10291 .iter()
10292 .any(|range| range.overlaps(&selection_range))
10293 {
10294 continue;
10295 }
10296
10297 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
10298
10299 // Since not all lines in the selection may be at the same indent
10300 // level, choose the indent size that is the most common between all
10301 // of the lines.
10302 //
10303 // If there is a tie, we use the deepest indent.
10304 let (indent_size, indent_end) = {
10305 let mut indent_size_occurrences = HashMap::default();
10306 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
10307
10308 for row in start_row..=end_row {
10309 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
10310 rows_by_indent_size.entry(indent).or_default().push(row);
10311 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
10312 }
10313
10314 let indent_size = indent_size_occurrences
10315 .into_iter()
10316 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
10317 .map(|(indent, _)| indent)
10318 .unwrap_or_default();
10319 let row = rows_by_indent_size[&indent_size][0];
10320 let indent_end = Point::new(row, indent_size.len);
10321
10322 (indent_size, indent_end)
10323 };
10324
10325 let mut line_prefix = indent_size.chars().collect::<String>();
10326
10327 let mut inside_comment = false;
10328 if let Some(comment_prefix) =
10329 buffer
10330 .language_scope_at(selection.head())
10331 .and_then(|language| {
10332 language
10333 .line_comment_prefixes()
10334 .iter()
10335 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
10336 .cloned()
10337 })
10338 {
10339 line_prefix.push_str(&comment_prefix);
10340 inside_comment = true;
10341 }
10342
10343 let language_settings = buffer.language_settings_at(selection.head(), cx);
10344 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
10345 RewrapBehavior::InComments => inside_comment,
10346 RewrapBehavior::InSelections => !selection.is_empty(),
10347 RewrapBehavior::Anywhere => true,
10348 };
10349
10350 let should_rewrap = options.override_language_settings
10351 || allow_rewrap_based_on_language
10352 || self.hard_wrap.is_some();
10353 if !should_rewrap {
10354 continue;
10355 }
10356
10357 if selection.is_empty() {
10358 'expand_upwards: while start_row > 0 {
10359 let prev_row = start_row - 1;
10360 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10361 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10362 {
10363 start_row = prev_row;
10364 } else {
10365 break 'expand_upwards;
10366 }
10367 }
10368
10369 'expand_downwards: while end_row < buffer.max_point().row {
10370 let next_row = end_row + 1;
10371 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10372 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10373 {
10374 end_row = next_row;
10375 } else {
10376 break 'expand_downwards;
10377 }
10378 }
10379 }
10380
10381 let start = Point::new(start_row, 0);
10382 let start_offset = start.to_offset(&buffer);
10383 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10384 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10385 let Some(lines_without_prefixes) = selection_text
10386 .lines()
10387 .map(|line| {
10388 line.strip_prefix(&line_prefix)
10389 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10390 .ok_or_else(|| {
10391 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10392 })
10393 })
10394 .collect::<Result<Vec<_>, _>>()
10395 .log_err()
10396 else {
10397 continue;
10398 };
10399
10400 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10401 buffer
10402 .language_settings_at(Point::new(start_row, 0), cx)
10403 .preferred_line_length as usize
10404 });
10405 let wrapped_text = wrap_with_prefix(
10406 line_prefix,
10407 lines_without_prefixes.join("\n"),
10408 wrap_column,
10409 tab_size,
10410 options.preserve_existing_whitespace,
10411 );
10412
10413 // TODO: should always use char-based diff while still supporting cursor behavior that
10414 // matches vim.
10415 let mut diff_options = DiffOptions::default();
10416 if options.override_language_settings {
10417 diff_options.max_word_diff_len = 0;
10418 diff_options.max_word_diff_line_count = 0;
10419 } else {
10420 diff_options.max_word_diff_len = usize::MAX;
10421 diff_options.max_word_diff_line_count = usize::MAX;
10422 }
10423
10424 for (old_range, new_text) in
10425 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10426 {
10427 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10428 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10429 edits.push((edit_start..edit_end, new_text));
10430 }
10431
10432 rewrapped_row_ranges.push(start_row..=end_row);
10433 }
10434
10435 self.buffer
10436 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10437 }
10438
10439 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10440 let mut text = String::new();
10441 let buffer = self.buffer.read(cx).snapshot(cx);
10442 let mut selections = self.selections.all::<Point>(cx);
10443 let mut clipboard_selections = Vec::with_capacity(selections.len());
10444 {
10445 let max_point = buffer.max_point();
10446 let mut is_first = true;
10447 for selection in &mut selections {
10448 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10449 if is_entire_line {
10450 selection.start = Point::new(selection.start.row, 0);
10451 if !selection.is_empty() && selection.end.column == 0 {
10452 selection.end = cmp::min(max_point, selection.end);
10453 } else {
10454 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10455 }
10456 selection.goal = SelectionGoal::None;
10457 }
10458 if is_first {
10459 is_first = false;
10460 } else {
10461 text += "\n";
10462 }
10463 let mut len = 0;
10464 for chunk in buffer.text_for_range(selection.start..selection.end) {
10465 text.push_str(chunk);
10466 len += chunk.len();
10467 }
10468 clipboard_selections.push(ClipboardSelection {
10469 len,
10470 is_entire_line,
10471 first_line_indent: buffer
10472 .indent_size_for_line(MultiBufferRow(selection.start.row))
10473 .len,
10474 });
10475 }
10476 }
10477
10478 self.transact(window, cx, |this, window, cx| {
10479 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10480 s.select(selections);
10481 });
10482 this.insert("", window, cx);
10483 });
10484 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10485 }
10486
10487 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10488 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10489 let item = self.cut_common(window, cx);
10490 cx.write_to_clipboard(item);
10491 }
10492
10493 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10494 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10495 self.change_selections(None, window, cx, |s| {
10496 s.move_with(|snapshot, sel| {
10497 if sel.is_empty() {
10498 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10499 }
10500 });
10501 });
10502 let item = self.cut_common(window, cx);
10503 cx.set_global(KillRing(item))
10504 }
10505
10506 pub fn kill_ring_yank(
10507 &mut self,
10508 _: &KillRingYank,
10509 window: &mut Window,
10510 cx: &mut Context<Self>,
10511 ) {
10512 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10513 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10514 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10515 (kill_ring.text().to_string(), kill_ring.metadata_json())
10516 } else {
10517 return;
10518 }
10519 } else {
10520 return;
10521 };
10522 self.do_paste(&text, metadata, false, window, cx);
10523 }
10524
10525 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10526 self.do_copy(true, cx);
10527 }
10528
10529 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10530 self.do_copy(false, cx);
10531 }
10532
10533 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10534 let selections = self.selections.all::<Point>(cx);
10535 let buffer = self.buffer.read(cx).read(cx);
10536 let mut text = String::new();
10537
10538 let mut clipboard_selections = Vec::with_capacity(selections.len());
10539 {
10540 let max_point = buffer.max_point();
10541 let mut is_first = true;
10542 for selection in &selections {
10543 let mut start = selection.start;
10544 let mut end = selection.end;
10545 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10546 if is_entire_line {
10547 start = Point::new(start.row, 0);
10548 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10549 }
10550
10551 let mut trimmed_selections = Vec::new();
10552 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10553 let row = MultiBufferRow(start.row);
10554 let first_indent = buffer.indent_size_for_line(row);
10555 if first_indent.len == 0 || start.column > first_indent.len {
10556 trimmed_selections.push(start..end);
10557 } else {
10558 trimmed_selections.push(
10559 Point::new(row.0, first_indent.len)
10560 ..Point::new(row.0, buffer.line_len(row)),
10561 );
10562 for row in start.row + 1..=end.row {
10563 let mut line_len = buffer.line_len(MultiBufferRow(row));
10564 if row == end.row {
10565 line_len = end.column;
10566 }
10567 if line_len == 0 {
10568 trimmed_selections
10569 .push(Point::new(row, 0)..Point::new(row, line_len));
10570 continue;
10571 }
10572 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10573 if row_indent_size.len >= first_indent.len {
10574 trimmed_selections.push(
10575 Point::new(row, first_indent.len)..Point::new(row, line_len),
10576 );
10577 } else {
10578 trimmed_selections.clear();
10579 trimmed_selections.push(start..end);
10580 break;
10581 }
10582 }
10583 }
10584 } else {
10585 trimmed_selections.push(start..end);
10586 }
10587
10588 for trimmed_range in trimmed_selections {
10589 if is_first {
10590 is_first = false;
10591 } else {
10592 text += "\n";
10593 }
10594 let mut len = 0;
10595 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10596 text.push_str(chunk);
10597 len += chunk.len();
10598 }
10599 clipboard_selections.push(ClipboardSelection {
10600 len,
10601 is_entire_line,
10602 first_line_indent: buffer
10603 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10604 .len,
10605 });
10606 }
10607 }
10608 }
10609
10610 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10611 text,
10612 clipboard_selections,
10613 ));
10614 }
10615
10616 pub fn do_paste(
10617 &mut self,
10618 text: &String,
10619 clipboard_selections: Option<Vec<ClipboardSelection>>,
10620 handle_entire_lines: bool,
10621 window: &mut Window,
10622 cx: &mut Context<Self>,
10623 ) {
10624 if self.read_only(cx) {
10625 return;
10626 }
10627
10628 let clipboard_text = Cow::Borrowed(text);
10629
10630 self.transact(window, cx, |this, window, cx| {
10631 if let Some(mut clipboard_selections) = clipboard_selections {
10632 let old_selections = this.selections.all::<usize>(cx);
10633 let all_selections_were_entire_line =
10634 clipboard_selections.iter().all(|s| s.is_entire_line);
10635 let first_selection_indent_column =
10636 clipboard_selections.first().map(|s| s.first_line_indent);
10637 if clipboard_selections.len() != old_selections.len() {
10638 clipboard_selections.drain(..);
10639 }
10640 let cursor_offset = this.selections.last::<usize>(cx).head();
10641 let mut auto_indent_on_paste = true;
10642
10643 this.buffer.update(cx, |buffer, cx| {
10644 let snapshot = buffer.read(cx);
10645 auto_indent_on_paste = snapshot
10646 .language_settings_at(cursor_offset, cx)
10647 .auto_indent_on_paste;
10648
10649 let mut start_offset = 0;
10650 let mut edits = Vec::new();
10651 let mut original_indent_columns = Vec::new();
10652 for (ix, selection) in old_selections.iter().enumerate() {
10653 let to_insert;
10654 let entire_line;
10655 let original_indent_column;
10656 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10657 let end_offset = start_offset + clipboard_selection.len;
10658 to_insert = &clipboard_text[start_offset..end_offset];
10659 entire_line = clipboard_selection.is_entire_line;
10660 start_offset = end_offset + 1;
10661 original_indent_column = Some(clipboard_selection.first_line_indent);
10662 } else {
10663 to_insert = clipboard_text.as_str();
10664 entire_line = all_selections_were_entire_line;
10665 original_indent_column = first_selection_indent_column
10666 }
10667
10668 // If the corresponding selection was empty when this slice of the
10669 // clipboard text was written, then the entire line containing the
10670 // selection was copied. If this selection is also currently empty,
10671 // then paste the line before the current line of the buffer.
10672 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10673 let column = selection.start.to_point(&snapshot).column as usize;
10674 let line_start = selection.start - column;
10675 line_start..line_start
10676 } else {
10677 selection.range()
10678 };
10679
10680 edits.push((range, to_insert));
10681 original_indent_columns.push(original_indent_column);
10682 }
10683 drop(snapshot);
10684
10685 buffer.edit(
10686 edits,
10687 if auto_indent_on_paste {
10688 Some(AutoindentMode::Block {
10689 original_indent_columns,
10690 })
10691 } else {
10692 None
10693 },
10694 cx,
10695 );
10696 });
10697
10698 let selections = this.selections.all::<usize>(cx);
10699 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10700 s.select(selections)
10701 });
10702 } else {
10703 this.insert(&clipboard_text, window, cx);
10704 }
10705 });
10706 }
10707
10708 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10709 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10710 if let Some(item) = cx.read_from_clipboard() {
10711 let entries = item.entries();
10712
10713 match entries.first() {
10714 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10715 // of all the pasted entries.
10716 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10717 .do_paste(
10718 clipboard_string.text(),
10719 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10720 true,
10721 window,
10722 cx,
10723 ),
10724 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10725 }
10726 }
10727 }
10728
10729 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10730 if self.read_only(cx) {
10731 return;
10732 }
10733
10734 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10735
10736 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10737 if let Some((selections, _)) =
10738 self.selection_history.transaction(transaction_id).cloned()
10739 {
10740 self.change_selections(None, window, cx, |s| {
10741 s.select_anchors(selections.to_vec());
10742 });
10743 } else {
10744 log::error!(
10745 "No entry in selection_history found for undo. \
10746 This may correspond to a bug where undo does not update the selection. \
10747 If this is occurring, please add details to \
10748 https://github.com/zed-industries/zed/issues/22692"
10749 );
10750 }
10751 self.request_autoscroll(Autoscroll::fit(), cx);
10752 self.unmark_text(window, cx);
10753 self.refresh_inline_completion(true, false, window, cx);
10754 cx.emit(EditorEvent::Edited { transaction_id });
10755 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10756 }
10757 }
10758
10759 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10760 if self.read_only(cx) {
10761 return;
10762 }
10763
10764 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10765
10766 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10767 if let Some((_, Some(selections))) =
10768 self.selection_history.transaction(transaction_id).cloned()
10769 {
10770 self.change_selections(None, window, cx, |s| {
10771 s.select_anchors(selections.to_vec());
10772 });
10773 } else {
10774 log::error!(
10775 "No entry in selection_history found for redo. \
10776 This may correspond to a bug where undo does not update the selection. \
10777 If this is occurring, please add details to \
10778 https://github.com/zed-industries/zed/issues/22692"
10779 );
10780 }
10781 self.request_autoscroll(Autoscroll::fit(), cx);
10782 self.unmark_text(window, cx);
10783 self.refresh_inline_completion(true, false, window, cx);
10784 cx.emit(EditorEvent::Edited { transaction_id });
10785 }
10786 }
10787
10788 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10789 self.buffer
10790 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10791 }
10792
10793 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10794 self.buffer
10795 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10796 }
10797
10798 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10799 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10800 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10801 s.move_with(|map, selection| {
10802 let cursor = if selection.is_empty() {
10803 movement::left(map, selection.start)
10804 } else {
10805 selection.start
10806 };
10807 selection.collapse_to(cursor, SelectionGoal::None);
10808 });
10809 })
10810 }
10811
10812 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10813 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10814 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10815 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10816 })
10817 }
10818
10819 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10820 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10821 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10822 s.move_with(|map, selection| {
10823 let cursor = if selection.is_empty() {
10824 movement::right(map, selection.end)
10825 } else {
10826 selection.end
10827 };
10828 selection.collapse_to(cursor, SelectionGoal::None)
10829 });
10830 })
10831 }
10832
10833 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10834 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10835 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10836 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10837 })
10838 }
10839
10840 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10841 if self.take_rename(true, window, cx).is_some() {
10842 return;
10843 }
10844
10845 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10846 cx.propagate();
10847 return;
10848 }
10849
10850 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10851
10852 let text_layout_details = &self.text_layout_details(window);
10853 let selection_count = self.selections.count();
10854 let first_selection = self.selections.first_anchor();
10855
10856 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10857 s.move_with(|map, selection| {
10858 if !selection.is_empty() {
10859 selection.goal = SelectionGoal::None;
10860 }
10861 let (cursor, goal) = movement::up(
10862 map,
10863 selection.start,
10864 selection.goal,
10865 false,
10866 text_layout_details,
10867 );
10868 selection.collapse_to(cursor, goal);
10869 });
10870 });
10871
10872 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10873 {
10874 cx.propagate();
10875 }
10876 }
10877
10878 pub fn move_up_by_lines(
10879 &mut self,
10880 action: &MoveUpByLines,
10881 window: &mut Window,
10882 cx: &mut Context<Self>,
10883 ) {
10884 if self.take_rename(true, window, cx).is_some() {
10885 return;
10886 }
10887
10888 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10889 cx.propagate();
10890 return;
10891 }
10892
10893 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10894
10895 let text_layout_details = &self.text_layout_details(window);
10896
10897 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10898 s.move_with(|map, selection| {
10899 if !selection.is_empty() {
10900 selection.goal = SelectionGoal::None;
10901 }
10902 let (cursor, goal) = movement::up_by_rows(
10903 map,
10904 selection.start,
10905 action.lines,
10906 selection.goal,
10907 false,
10908 text_layout_details,
10909 );
10910 selection.collapse_to(cursor, goal);
10911 });
10912 })
10913 }
10914
10915 pub fn move_down_by_lines(
10916 &mut self,
10917 action: &MoveDownByLines,
10918 window: &mut Window,
10919 cx: &mut Context<Self>,
10920 ) {
10921 if self.take_rename(true, window, cx).is_some() {
10922 return;
10923 }
10924
10925 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10926 cx.propagate();
10927 return;
10928 }
10929
10930 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10931
10932 let text_layout_details = &self.text_layout_details(window);
10933
10934 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10935 s.move_with(|map, selection| {
10936 if !selection.is_empty() {
10937 selection.goal = SelectionGoal::None;
10938 }
10939 let (cursor, goal) = movement::down_by_rows(
10940 map,
10941 selection.start,
10942 action.lines,
10943 selection.goal,
10944 false,
10945 text_layout_details,
10946 );
10947 selection.collapse_to(cursor, goal);
10948 });
10949 })
10950 }
10951
10952 pub fn select_down_by_lines(
10953 &mut self,
10954 action: &SelectDownByLines,
10955 window: &mut Window,
10956 cx: &mut Context<Self>,
10957 ) {
10958 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10959 let text_layout_details = &self.text_layout_details(window);
10960 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10961 s.move_heads_with(|map, head, goal| {
10962 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10963 })
10964 })
10965 }
10966
10967 pub fn select_up_by_lines(
10968 &mut self,
10969 action: &SelectUpByLines,
10970 window: &mut Window,
10971 cx: &mut Context<Self>,
10972 ) {
10973 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10974 let text_layout_details = &self.text_layout_details(window);
10975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10976 s.move_heads_with(|map, head, goal| {
10977 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10978 })
10979 })
10980 }
10981
10982 pub fn select_page_up(
10983 &mut self,
10984 _: &SelectPageUp,
10985 window: &mut Window,
10986 cx: &mut Context<Self>,
10987 ) {
10988 let Some(row_count) = self.visible_row_count() else {
10989 return;
10990 };
10991
10992 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10993
10994 let text_layout_details = &self.text_layout_details(window);
10995
10996 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10997 s.move_heads_with(|map, head, goal| {
10998 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10999 })
11000 })
11001 }
11002
11003 pub fn move_page_up(
11004 &mut self,
11005 action: &MovePageUp,
11006 window: &mut Window,
11007 cx: &mut Context<Self>,
11008 ) {
11009 if self.take_rename(true, window, cx).is_some() {
11010 return;
11011 }
11012
11013 if self
11014 .context_menu
11015 .borrow_mut()
11016 .as_mut()
11017 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
11018 .unwrap_or(false)
11019 {
11020 return;
11021 }
11022
11023 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11024 cx.propagate();
11025 return;
11026 }
11027
11028 let Some(row_count) = self.visible_row_count() else {
11029 return;
11030 };
11031
11032 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11033
11034 let autoscroll = if action.center_cursor {
11035 Autoscroll::center()
11036 } else {
11037 Autoscroll::fit()
11038 };
11039
11040 let text_layout_details = &self.text_layout_details(window);
11041
11042 self.change_selections(Some(autoscroll), window, cx, |s| {
11043 s.move_with(|map, selection| {
11044 if !selection.is_empty() {
11045 selection.goal = SelectionGoal::None;
11046 }
11047 let (cursor, goal) = movement::up_by_rows(
11048 map,
11049 selection.end,
11050 row_count,
11051 selection.goal,
11052 false,
11053 text_layout_details,
11054 );
11055 selection.collapse_to(cursor, goal);
11056 });
11057 });
11058 }
11059
11060 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
11061 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11062 let text_layout_details = &self.text_layout_details(window);
11063 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11064 s.move_heads_with(|map, head, goal| {
11065 movement::up(map, head, goal, false, text_layout_details)
11066 })
11067 })
11068 }
11069
11070 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
11071 self.take_rename(true, window, cx);
11072
11073 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11074 cx.propagate();
11075 return;
11076 }
11077
11078 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11079
11080 let text_layout_details = &self.text_layout_details(window);
11081 let selection_count = self.selections.count();
11082 let first_selection = self.selections.first_anchor();
11083
11084 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11085 s.move_with(|map, selection| {
11086 if !selection.is_empty() {
11087 selection.goal = SelectionGoal::None;
11088 }
11089 let (cursor, goal) = movement::down(
11090 map,
11091 selection.end,
11092 selection.goal,
11093 false,
11094 text_layout_details,
11095 );
11096 selection.collapse_to(cursor, goal);
11097 });
11098 });
11099
11100 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
11101 {
11102 cx.propagate();
11103 }
11104 }
11105
11106 pub fn select_page_down(
11107 &mut self,
11108 _: &SelectPageDown,
11109 window: &mut Window,
11110 cx: &mut Context<Self>,
11111 ) {
11112 let Some(row_count) = self.visible_row_count() else {
11113 return;
11114 };
11115
11116 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11117
11118 let text_layout_details = &self.text_layout_details(window);
11119
11120 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11121 s.move_heads_with(|map, head, goal| {
11122 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
11123 })
11124 })
11125 }
11126
11127 pub fn move_page_down(
11128 &mut self,
11129 action: &MovePageDown,
11130 window: &mut Window,
11131 cx: &mut Context<Self>,
11132 ) {
11133 if self.take_rename(true, window, cx).is_some() {
11134 return;
11135 }
11136
11137 if self
11138 .context_menu
11139 .borrow_mut()
11140 .as_mut()
11141 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
11142 .unwrap_or(false)
11143 {
11144 return;
11145 }
11146
11147 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11148 cx.propagate();
11149 return;
11150 }
11151
11152 let Some(row_count) = self.visible_row_count() else {
11153 return;
11154 };
11155
11156 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11157
11158 let autoscroll = if action.center_cursor {
11159 Autoscroll::center()
11160 } else {
11161 Autoscroll::fit()
11162 };
11163
11164 let text_layout_details = &self.text_layout_details(window);
11165 self.change_selections(Some(autoscroll), window, cx, |s| {
11166 s.move_with(|map, selection| {
11167 if !selection.is_empty() {
11168 selection.goal = SelectionGoal::None;
11169 }
11170 let (cursor, goal) = movement::down_by_rows(
11171 map,
11172 selection.end,
11173 row_count,
11174 selection.goal,
11175 false,
11176 text_layout_details,
11177 );
11178 selection.collapse_to(cursor, goal);
11179 });
11180 });
11181 }
11182
11183 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
11184 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11185 let text_layout_details = &self.text_layout_details(window);
11186 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11187 s.move_heads_with(|map, head, goal| {
11188 movement::down(map, head, goal, false, text_layout_details)
11189 })
11190 });
11191 }
11192
11193 pub fn context_menu_first(
11194 &mut self,
11195 _: &ContextMenuFirst,
11196 _window: &mut Window,
11197 cx: &mut Context<Self>,
11198 ) {
11199 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11200 context_menu.select_first(self.completion_provider.as_deref(), cx);
11201 }
11202 }
11203
11204 pub fn context_menu_prev(
11205 &mut self,
11206 _: &ContextMenuPrevious,
11207 _window: &mut Window,
11208 cx: &mut Context<Self>,
11209 ) {
11210 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11211 context_menu.select_prev(self.completion_provider.as_deref(), cx);
11212 }
11213 }
11214
11215 pub fn context_menu_next(
11216 &mut self,
11217 _: &ContextMenuNext,
11218 _window: &mut Window,
11219 cx: &mut Context<Self>,
11220 ) {
11221 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11222 context_menu.select_next(self.completion_provider.as_deref(), cx);
11223 }
11224 }
11225
11226 pub fn context_menu_last(
11227 &mut self,
11228 _: &ContextMenuLast,
11229 _window: &mut Window,
11230 cx: &mut Context<Self>,
11231 ) {
11232 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
11233 context_menu.select_last(self.completion_provider.as_deref(), cx);
11234 }
11235 }
11236
11237 pub fn move_to_previous_word_start(
11238 &mut self,
11239 _: &MoveToPreviousWordStart,
11240 window: &mut Window,
11241 cx: &mut Context<Self>,
11242 ) {
11243 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11244 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11245 s.move_cursors_with(|map, head, _| {
11246 (
11247 movement::previous_word_start(map, head),
11248 SelectionGoal::None,
11249 )
11250 });
11251 })
11252 }
11253
11254 pub fn move_to_previous_subword_start(
11255 &mut self,
11256 _: &MoveToPreviousSubwordStart,
11257 window: &mut Window,
11258 cx: &mut Context<Self>,
11259 ) {
11260 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11261 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11262 s.move_cursors_with(|map, head, _| {
11263 (
11264 movement::previous_subword_start(map, head),
11265 SelectionGoal::None,
11266 )
11267 });
11268 })
11269 }
11270
11271 pub fn select_to_previous_word_start(
11272 &mut self,
11273 _: &SelectToPreviousWordStart,
11274 window: &mut Window,
11275 cx: &mut Context<Self>,
11276 ) {
11277 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11278 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11279 s.move_heads_with(|map, head, _| {
11280 (
11281 movement::previous_word_start(map, head),
11282 SelectionGoal::None,
11283 )
11284 });
11285 })
11286 }
11287
11288 pub fn select_to_previous_subword_start(
11289 &mut self,
11290 _: &SelectToPreviousSubwordStart,
11291 window: &mut Window,
11292 cx: &mut Context<Self>,
11293 ) {
11294 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11295 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11296 s.move_heads_with(|map, head, _| {
11297 (
11298 movement::previous_subword_start(map, head),
11299 SelectionGoal::None,
11300 )
11301 });
11302 })
11303 }
11304
11305 pub fn delete_to_previous_word_start(
11306 &mut self,
11307 action: &DeleteToPreviousWordStart,
11308 window: &mut Window,
11309 cx: &mut Context<Self>,
11310 ) {
11311 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11312 self.transact(window, cx, |this, window, cx| {
11313 this.select_autoclose_pair(window, cx);
11314 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11315 s.move_with(|map, selection| {
11316 if selection.is_empty() {
11317 let cursor = if action.ignore_newlines {
11318 movement::previous_word_start(map, selection.head())
11319 } else {
11320 movement::previous_word_start_or_newline(map, selection.head())
11321 };
11322 selection.set_head(cursor, SelectionGoal::None);
11323 }
11324 });
11325 });
11326 this.insert("", window, cx);
11327 });
11328 }
11329
11330 pub fn delete_to_previous_subword_start(
11331 &mut self,
11332 _: &DeleteToPreviousSubwordStart,
11333 window: &mut Window,
11334 cx: &mut Context<Self>,
11335 ) {
11336 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11337 self.transact(window, cx, |this, window, cx| {
11338 this.select_autoclose_pair(window, cx);
11339 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11340 s.move_with(|map, selection| {
11341 if selection.is_empty() {
11342 let cursor = movement::previous_subword_start(map, selection.head());
11343 selection.set_head(cursor, SelectionGoal::None);
11344 }
11345 });
11346 });
11347 this.insert("", window, cx);
11348 });
11349 }
11350
11351 pub fn move_to_next_word_end(
11352 &mut self,
11353 _: &MoveToNextWordEnd,
11354 window: &mut Window,
11355 cx: &mut Context<Self>,
11356 ) {
11357 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11358 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11359 s.move_cursors_with(|map, head, _| {
11360 (movement::next_word_end(map, head), SelectionGoal::None)
11361 });
11362 })
11363 }
11364
11365 pub fn move_to_next_subword_end(
11366 &mut self,
11367 _: &MoveToNextSubwordEnd,
11368 window: &mut Window,
11369 cx: &mut Context<Self>,
11370 ) {
11371 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11372 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11373 s.move_cursors_with(|map, head, _| {
11374 (movement::next_subword_end(map, head), SelectionGoal::None)
11375 });
11376 })
11377 }
11378
11379 pub fn select_to_next_word_end(
11380 &mut self,
11381 _: &SelectToNextWordEnd,
11382 window: &mut Window,
11383 cx: &mut Context<Self>,
11384 ) {
11385 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11386 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11387 s.move_heads_with(|map, head, _| {
11388 (movement::next_word_end(map, head), SelectionGoal::None)
11389 });
11390 })
11391 }
11392
11393 pub fn select_to_next_subword_end(
11394 &mut self,
11395 _: &SelectToNextSubwordEnd,
11396 window: &mut Window,
11397 cx: &mut Context<Self>,
11398 ) {
11399 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11400 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11401 s.move_heads_with(|map, head, _| {
11402 (movement::next_subword_end(map, head), SelectionGoal::None)
11403 });
11404 })
11405 }
11406
11407 pub fn delete_to_next_word_end(
11408 &mut self,
11409 action: &DeleteToNextWordEnd,
11410 window: &mut Window,
11411 cx: &mut Context<Self>,
11412 ) {
11413 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11414 self.transact(window, cx, |this, window, cx| {
11415 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11416 s.move_with(|map, selection| {
11417 if selection.is_empty() {
11418 let cursor = if action.ignore_newlines {
11419 movement::next_word_end(map, selection.head())
11420 } else {
11421 movement::next_word_end_or_newline(map, selection.head())
11422 };
11423 selection.set_head(cursor, SelectionGoal::None);
11424 }
11425 });
11426 });
11427 this.insert("", window, cx);
11428 });
11429 }
11430
11431 pub fn delete_to_next_subword_end(
11432 &mut self,
11433 _: &DeleteToNextSubwordEnd,
11434 window: &mut Window,
11435 cx: &mut Context<Self>,
11436 ) {
11437 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11438 self.transact(window, cx, |this, window, cx| {
11439 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11440 s.move_with(|map, selection| {
11441 if selection.is_empty() {
11442 let cursor = movement::next_subword_end(map, selection.head());
11443 selection.set_head(cursor, SelectionGoal::None);
11444 }
11445 });
11446 });
11447 this.insert("", window, cx);
11448 });
11449 }
11450
11451 pub fn move_to_beginning_of_line(
11452 &mut self,
11453 action: &MoveToBeginningOfLine,
11454 window: &mut Window,
11455 cx: &mut Context<Self>,
11456 ) {
11457 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11458 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11459 s.move_cursors_with(|map, head, _| {
11460 (
11461 movement::indented_line_beginning(
11462 map,
11463 head,
11464 action.stop_at_soft_wraps,
11465 action.stop_at_indent,
11466 ),
11467 SelectionGoal::None,
11468 )
11469 });
11470 })
11471 }
11472
11473 pub fn select_to_beginning_of_line(
11474 &mut self,
11475 action: &SelectToBeginningOfLine,
11476 window: &mut Window,
11477 cx: &mut Context<Self>,
11478 ) {
11479 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11480 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11481 s.move_heads_with(|map, head, _| {
11482 (
11483 movement::indented_line_beginning(
11484 map,
11485 head,
11486 action.stop_at_soft_wraps,
11487 action.stop_at_indent,
11488 ),
11489 SelectionGoal::None,
11490 )
11491 });
11492 });
11493 }
11494
11495 pub fn delete_to_beginning_of_line(
11496 &mut self,
11497 action: &DeleteToBeginningOfLine,
11498 window: &mut Window,
11499 cx: &mut Context<Self>,
11500 ) {
11501 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11502 self.transact(window, cx, |this, window, cx| {
11503 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11504 s.move_with(|_, selection| {
11505 selection.reversed = true;
11506 });
11507 });
11508
11509 this.select_to_beginning_of_line(
11510 &SelectToBeginningOfLine {
11511 stop_at_soft_wraps: false,
11512 stop_at_indent: action.stop_at_indent,
11513 },
11514 window,
11515 cx,
11516 );
11517 this.backspace(&Backspace, window, cx);
11518 });
11519 }
11520
11521 pub fn move_to_end_of_line(
11522 &mut self,
11523 action: &MoveToEndOfLine,
11524 window: &mut Window,
11525 cx: &mut Context<Self>,
11526 ) {
11527 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11528 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11529 s.move_cursors_with(|map, head, _| {
11530 (
11531 movement::line_end(map, head, action.stop_at_soft_wraps),
11532 SelectionGoal::None,
11533 )
11534 });
11535 })
11536 }
11537
11538 pub fn select_to_end_of_line(
11539 &mut self,
11540 action: &SelectToEndOfLine,
11541 window: &mut Window,
11542 cx: &mut Context<Self>,
11543 ) {
11544 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11545 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11546 s.move_heads_with(|map, head, _| {
11547 (
11548 movement::line_end(map, head, action.stop_at_soft_wraps),
11549 SelectionGoal::None,
11550 )
11551 });
11552 })
11553 }
11554
11555 pub fn delete_to_end_of_line(
11556 &mut self,
11557 _: &DeleteToEndOfLine,
11558 window: &mut Window,
11559 cx: &mut Context<Self>,
11560 ) {
11561 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11562 self.transact(window, cx, |this, window, cx| {
11563 this.select_to_end_of_line(
11564 &SelectToEndOfLine {
11565 stop_at_soft_wraps: false,
11566 },
11567 window,
11568 cx,
11569 );
11570 this.delete(&Delete, window, cx);
11571 });
11572 }
11573
11574 pub fn cut_to_end_of_line(
11575 &mut self,
11576 _: &CutToEndOfLine,
11577 window: &mut Window,
11578 cx: &mut Context<Self>,
11579 ) {
11580 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11581 self.transact(window, cx, |this, window, cx| {
11582 this.select_to_end_of_line(
11583 &SelectToEndOfLine {
11584 stop_at_soft_wraps: false,
11585 },
11586 window,
11587 cx,
11588 );
11589 this.cut(&Cut, window, cx);
11590 });
11591 }
11592
11593 pub fn move_to_start_of_paragraph(
11594 &mut self,
11595 _: &MoveToStartOfParagraph,
11596 window: &mut Window,
11597 cx: &mut Context<Self>,
11598 ) {
11599 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11600 cx.propagate();
11601 return;
11602 }
11603 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11604 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11605 s.move_with(|map, selection| {
11606 selection.collapse_to(
11607 movement::start_of_paragraph(map, selection.head(), 1),
11608 SelectionGoal::None,
11609 )
11610 });
11611 })
11612 }
11613
11614 pub fn move_to_end_of_paragraph(
11615 &mut self,
11616 _: &MoveToEndOfParagraph,
11617 window: &mut Window,
11618 cx: &mut Context<Self>,
11619 ) {
11620 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11621 cx.propagate();
11622 return;
11623 }
11624 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11625 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11626 s.move_with(|map, selection| {
11627 selection.collapse_to(
11628 movement::end_of_paragraph(map, selection.head(), 1),
11629 SelectionGoal::None,
11630 )
11631 });
11632 })
11633 }
11634
11635 pub fn select_to_start_of_paragraph(
11636 &mut self,
11637 _: &SelectToStartOfParagraph,
11638 window: &mut Window,
11639 cx: &mut Context<Self>,
11640 ) {
11641 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11642 cx.propagate();
11643 return;
11644 }
11645 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11646 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11647 s.move_heads_with(|map, head, _| {
11648 (
11649 movement::start_of_paragraph(map, head, 1),
11650 SelectionGoal::None,
11651 )
11652 });
11653 })
11654 }
11655
11656 pub fn select_to_end_of_paragraph(
11657 &mut self,
11658 _: &SelectToEndOfParagraph,
11659 window: &mut Window,
11660 cx: &mut Context<Self>,
11661 ) {
11662 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11663 cx.propagate();
11664 return;
11665 }
11666 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11667 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11668 s.move_heads_with(|map, head, _| {
11669 (
11670 movement::end_of_paragraph(map, head, 1),
11671 SelectionGoal::None,
11672 )
11673 });
11674 })
11675 }
11676
11677 pub fn move_to_start_of_excerpt(
11678 &mut self,
11679 _: &MoveToStartOfExcerpt,
11680 window: &mut Window,
11681 cx: &mut Context<Self>,
11682 ) {
11683 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11684 cx.propagate();
11685 return;
11686 }
11687 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11688 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11689 s.move_with(|map, selection| {
11690 selection.collapse_to(
11691 movement::start_of_excerpt(
11692 map,
11693 selection.head(),
11694 workspace::searchable::Direction::Prev,
11695 ),
11696 SelectionGoal::None,
11697 )
11698 });
11699 })
11700 }
11701
11702 pub fn move_to_start_of_next_excerpt(
11703 &mut self,
11704 _: &MoveToStartOfNextExcerpt,
11705 window: &mut Window,
11706 cx: &mut Context<Self>,
11707 ) {
11708 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11709 cx.propagate();
11710 return;
11711 }
11712
11713 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11714 s.move_with(|map, selection| {
11715 selection.collapse_to(
11716 movement::start_of_excerpt(
11717 map,
11718 selection.head(),
11719 workspace::searchable::Direction::Next,
11720 ),
11721 SelectionGoal::None,
11722 )
11723 });
11724 })
11725 }
11726
11727 pub fn move_to_end_of_excerpt(
11728 &mut self,
11729 _: &MoveToEndOfExcerpt,
11730 window: &mut Window,
11731 cx: &mut Context<Self>,
11732 ) {
11733 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11734 cx.propagate();
11735 return;
11736 }
11737 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11738 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11739 s.move_with(|map, selection| {
11740 selection.collapse_to(
11741 movement::end_of_excerpt(
11742 map,
11743 selection.head(),
11744 workspace::searchable::Direction::Next,
11745 ),
11746 SelectionGoal::None,
11747 )
11748 });
11749 })
11750 }
11751
11752 pub fn move_to_end_of_previous_excerpt(
11753 &mut self,
11754 _: &MoveToEndOfPreviousExcerpt,
11755 window: &mut Window,
11756 cx: &mut Context<Self>,
11757 ) {
11758 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11759 cx.propagate();
11760 return;
11761 }
11762 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11763 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11764 s.move_with(|map, selection| {
11765 selection.collapse_to(
11766 movement::end_of_excerpt(
11767 map,
11768 selection.head(),
11769 workspace::searchable::Direction::Prev,
11770 ),
11771 SelectionGoal::None,
11772 )
11773 });
11774 })
11775 }
11776
11777 pub fn select_to_start_of_excerpt(
11778 &mut self,
11779 _: &SelectToStartOfExcerpt,
11780 window: &mut Window,
11781 cx: &mut Context<Self>,
11782 ) {
11783 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11784 cx.propagate();
11785 return;
11786 }
11787 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11788 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11789 s.move_heads_with(|map, head, _| {
11790 (
11791 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11792 SelectionGoal::None,
11793 )
11794 });
11795 })
11796 }
11797
11798 pub fn select_to_start_of_next_excerpt(
11799 &mut self,
11800 _: &SelectToStartOfNextExcerpt,
11801 window: &mut Window,
11802 cx: &mut Context<Self>,
11803 ) {
11804 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11805 cx.propagate();
11806 return;
11807 }
11808 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11809 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11810 s.move_heads_with(|map, head, _| {
11811 (
11812 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11813 SelectionGoal::None,
11814 )
11815 });
11816 })
11817 }
11818
11819 pub fn select_to_end_of_excerpt(
11820 &mut self,
11821 _: &SelectToEndOfExcerpt,
11822 window: &mut Window,
11823 cx: &mut Context<Self>,
11824 ) {
11825 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11826 cx.propagate();
11827 return;
11828 }
11829 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11830 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11831 s.move_heads_with(|map, head, _| {
11832 (
11833 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11834 SelectionGoal::None,
11835 )
11836 });
11837 })
11838 }
11839
11840 pub fn select_to_end_of_previous_excerpt(
11841 &mut self,
11842 _: &SelectToEndOfPreviousExcerpt,
11843 window: &mut Window,
11844 cx: &mut Context<Self>,
11845 ) {
11846 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11847 cx.propagate();
11848 return;
11849 }
11850 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11851 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11852 s.move_heads_with(|map, head, _| {
11853 (
11854 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11855 SelectionGoal::None,
11856 )
11857 });
11858 })
11859 }
11860
11861 pub fn move_to_beginning(
11862 &mut self,
11863 _: &MoveToBeginning,
11864 window: &mut Window,
11865 cx: &mut Context<Self>,
11866 ) {
11867 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11868 cx.propagate();
11869 return;
11870 }
11871 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11872 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11873 s.select_ranges(vec![0..0]);
11874 });
11875 }
11876
11877 pub fn select_to_beginning(
11878 &mut self,
11879 _: &SelectToBeginning,
11880 window: &mut Window,
11881 cx: &mut Context<Self>,
11882 ) {
11883 let mut selection = self.selections.last::<Point>(cx);
11884 selection.set_head(Point::zero(), SelectionGoal::None);
11885 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11886 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11887 s.select(vec![selection]);
11888 });
11889 }
11890
11891 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11892 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11893 cx.propagate();
11894 return;
11895 }
11896 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11897 let cursor = self.buffer.read(cx).read(cx).len();
11898 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11899 s.select_ranges(vec![cursor..cursor])
11900 });
11901 }
11902
11903 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11904 self.nav_history = nav_history;
11905 }
11906
11907 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11908 self.nav_history.as_ref()
11909 }
11910
11911 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11912 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11913 }
11914
11915 fn push_to_nav_history(
11916 &mut self,
11917 cursor_anchor: Anchor,
11918 new_position: Option<Point>,
11919 is_deactivate: bool,
11920 cx: &mut Context<Self>,
11921 ) {
11922 if let Some(nav_history) = self.nav_history.as_mut() {
11923 let buffer = self.buffer.read(cx).read(cx);
11924 let cursor_position = cursor_anchor.to_point(&buffer);
11925 let scroll_state = self.scroll_manager.anchor();
11926 let scroll_top_row = scroll_state.top_row(&buffer);
11927 drop(buffer);
11928
11929 if let Some(new_position) = new_position {
11930 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11931 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11932 return;
11933 }
11934 }
11935
11936 nav_history.push(
11937 Some(NavigationData {
11938 cursor_anchor,
11939 cursor_position,
11940 scroll_anchor: scroll_state,
11941 scroll_top_row,
11942 }),
11943 cx,
11944 );
11945 cx.emit(EditorEvent::PushedToNavHistory {
11946 anchor: cursor_anchor,
11947 is_deactivate,
11948 })
11949 }
11950 }
11951
11952 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11953 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11954 let buffer = self.buffer.read(cx).snapshot(cx);
11955 let mut selection = self.selections.first::<usize>(cx);
11956 selection.set_head(buffer.len(), SelectionGoal::None);
11957 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11958 s.select(vec![selection]);
11959 });
11960 }
11961
11962 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11963 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11964 let end = self.buffer.read(cx).read(cx).len();
11965 self.change_selections(None, window, cx, |s| {
11966 s.select_ranges(vec![0..end]);
11967 });
11968 }
11969
11970 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11971 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11972 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11973 let mut selections = self.selections.all::<Point>(cx);
11974 let max_point = display_map.buffer_snapshot.max_point();
11975 for selection in &mut selections {
11976 let rows = selection.spanned_rows(true, &display_map);
11977 selection.start = Point::new(rows.start.0, 0);
11978 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11979 selection.reversed = false;
11980 }
11981 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11982 s.select(selections);
11983 });
11984 }
11985
11986 pub fn split_selection_into_lines(
11987 &mut self,
11988 _: &SplitSelectionIntoLines,
11989 window: &mut Window,
11990 cx: &mut Context<Self>,
11991 ) {
11992 let selections = self
11993 .selections
11994 .all::<Point>(cx)
11995 .into_iter()
11996 .map(|selection| selection.start..selection.end)
11997 .collect::<Vec<_>>();
11998 self.unfold_ranges(&selections, true, true, cx);
11999
12000 let mut new_selection_ranges = Vec::new();
12001 {
12002 let buffer = self.buffer.read(cx).read(cx);
12003 for selection in selections {
12004 for row in selection.start.row..selection.end.row {
12005 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
12006 new_selection_ranges.push(cursor..cursor);
12007 }
12008
12009 let is_multiline_selection = selection.start.row != selection.end.row;
12010 // Don't insert last one if it's a multi-line selection ending at the start of a line,
12011 // so this action feels more ergonomic when paired with other selection operations
12012 let should_skip_last = is_multiline_selection && selection.end.column == 0;
12013 if !should_skip_last {
12014 new_selection_ranges.push(selection.end..selection.end);
12015 }
12016 }
12017 }
12018 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12019 s.select_ranges(new_selection_ranges);
12020 });
12021 }
12022
12023 pub fn add_selection_above(
12024 &mut self,
12025 _: &AddSelectionAbove,
12026 window: &mut Window,
12027 cx: &mut Context<Self>,
12028 ) {
12029 self.add_selection(true, window, cx);
12030 }
12031
12032 pub fn add_selection_below(
12033 &mut self,
12034 _: &AddSelectionBelow,
12035 window: &mut Window,
12036 cx: &mut Context<Self>,
12037 ) {
12038 self.add_selection(false, window, cx);
12039 }
12040
12041 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
12042 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12043
12044 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12045 let mut selections = self.selections.all::<Point>(cx);
12046 let text_layout_details = self.text_layout_details(window);
12047 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
12048 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
12049 let range = oldest_selection.display_range(&display_map).sorted();
12050
12051 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
12052 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
12053 let positions = start_x.min(end_x)..start_x.max(end_x);
12054
12055 selections.clear();
12056 let mut stack = Vec::new();
12057 for row in range.start.row().0..=range.end.row().0 {
12058 if let Some(selection) = self.selections.build_columnar_selection(
12059 &display_map,
12060 DisplayRow(row),
12061 &positions,
12062 oldest_selection.reversed,
12063 &text_layout_details,
12064 ) {
12065 stack.push(selection.id);
12066 selections.push(selection);
12067 }
12068 }
12069
12070 if above {
12071 stack.reverse();
12072 }
12073
12074 AddSelectionsState { above, stack }
12075 });
12076
12077 let last_added_selection = *state.stack.last().unwrap();
12078 let mut new_selections = Vec::new();
12079 if above == state.above {
12080 let end_row = if above {
12081 DisplayRow(0)
12082 } else {
12083 display_map.max_point().row()
12084 };
12085
12086 'outer: for selection in selections {
12087 if selection.id == last_added_selection {
12088 let range = selection.display_range(&display_map).sorted();
12089 debug_assert_eq!(range.start.row(), range.end.row());
12090 let mut row = range.start.row();
12091 let positions =
12092 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
12093 px(start)..px(end)
12094 } else {
12095 let start_x =
12096 display_map.x_for_display_point(range.start, &text_layout_details);
12097 let end_x =
12098 display_map.x_for_display_point(range.end, &text_layout_details);
12099 start_x.min(end_x)..start_x.max(end_x)
12100 };
12101
12102 while row != end_row {
12103 if above {
12104 row.0 -= 1;
12105 } else {
12106 row.0 += 1;
12107 }
12108
12109 if let Some(new_selection) = self.selections.build_columnar_selection(
12110 &display_map,
12111 row,
12112 &positions,
12113 selection.reversed,
12114 &text_layout_details,
12115 ) {
12116 state.stack.push(new_selection.id);
12117 if above {
12118 new_selections.push(new_selection);
12119 new_selections.push(selection);
12120 } else {
12121 new_selections.push(selection);
12122 new_selections.push(new_selection);
12123 }
12124
12125 continue 'outer;
12126 }
12127 }
12128 }
12129
12130 new_selections.push(selection);
12131 }
12132 } else {
12133 new_selections = selections;
12134 new_selections.retain(|s| s.id != last_added_selection);
12135 state.stack.pop();
12136 }
12137
12138 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12139 s.select(new_selections);
12140 });
12141 if state.stack.len() > 1 {
12142 self.add_selections_state = Some(state);
12143 }
12144 }
12145
12146 fn select_match_ranges(
12147 &mut self,
12148 range: Range<usize>,
12149 reversed: bool,
12150 replace_newest: bool,
12151 auto_scroll: Option<Autoscroll>,
12152 window: &mut Window,
12153 cx: &mut Context<Editor>,
12154 ) {
12155 self.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
12156 self.change_selections(auto_scroll, window, cx, |s| {
12157 if replace_newest {
12158 s.delete(s.newest_anchor().id);
12159 }
12160 if reversed {
12161 s.insert_range(range.end..range.start);
12162 } else {
12163 s.insert_range(range);
12164 }
12165 });
12166 }
12167
12168 pub fn select_next_match_internal(
12169 &mut self,
12170 display_map: &DisplaySnapshot,
12171 replace_newest: bool,
12172 autoscroll: Option<Autoscroll>,
12173 window: &mut Window,
12174 cx: &mut Context<Self>,
12175 ) -> Result<()> {
12176 let buffer = &display_map.buffer_snapshot;
12177 let mut selections = self.selections.all::<usize>(cx);
12178 if let Some(mut select_next_state) = self.select_next_state.take() {
12179 let query = &select_next_state.query;
12180 if !select_next_state.done {
12181 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12182 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12183 let mut next_selected_range = None;
12184
12185 let bytes_after_last_selection =
12186 buffer.bytes_in_range(last_selection.end..buffer.len());
12187 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
12188 let query_matches = query
12189 .stream_find_iter(bytes_after_last_selection)
12190 .map(|result| (last_selection.end, result))
12191 .chain(
12192 query
12193 .stream_find_iter(bytes_before_first_selection)
12194 .map(|result| (0, result)),
12195 );
12196
12197 for (start_offset, query_match) in query_matches {
12198 let query_match = query_match.unwrap(); // can only fail due to I/O
12199 let offset_range =
12200 start_offset + query_match.start()..start_offset + query_match.end();
12201 let display_range = offset_range.start.to_display_point(display_map)
12202 ..offset_range.end.to_display_point(display_map);
12203
12204 if !select_next_state.wordwise
12205 || (!movement::is_inside_word(display_map, display_range.start)
12206 && !movement::is_inside_word(display_map, display_range.end))
12207 {
12208 // TODO: This is n^2, because we might check all the selections
12209 if !selections
12210 .iter()
12211 .any(|selection| selection.range().overlaps(&offset_range))
12212 {
12213 next_selected_range = Some(offset_range);
12214 break;
12215 }
12216 }
12217 }
12218
12219 if let Some(next_selected_range) = next_selected_range {
12220 self.select_match_ranges(
12221 next_selected_range,
12222 last_selection.reversed,
12223 replace_newest,
12224 autoscroll,
12225 window,
12226 cx,
12227 );
12228 } else {
12229 select_next_state.done = true;
12230 }
12231 }
12232
12233 self.select_next_state = Some(select_next_state);
12234 } else {
12235 let mut only_carets = true;
12236 let mut same_text_selected = true;
12237 let mut selected_text = None;
12238
12239 let mut selections_iter = selections.iter().peekable();
12240 while let Some(selection) = selections_iter.next() {
12241 if selection.start != selection.end {
12242 only_carets = false;
12243 }
12244
12245 if same_text_selected {
12246 if selected_text.is_none() {
12247 selected_text =
12248 Some(buffer.text_for_range(selection.range()).collect::<String>());
12249 }
12250
12251 if let Some(next_selection) = selections_iter.peek() {
12252 if next_selection.range().len() == selection.range().len() {
12253 let next_selected_text = buffer
12254 .text_for_range(next_selection.range())
12255 .collect::<String>();
12256 if Some(next_selected_text) != selected_text {
12257 same_text_selected = false;
12258 selected_text = None;
12259 }
12260 } else {
12261 same_text_selected = false;
12262 selected_text = None;
12263 }
12264 }
12265 }
12266 }
12267
12268 if only_carets {
12269 for selection in &mut selections {
12270 let word_range = movement::surrounding_word(
12271 display_map,
12272 selection.start.to_display_point(display_map),
12273 );
12274 selection.start = word_range.start.to_offset(display_map, Bias::Left);
12275 selection.end = word_range.end.to_offset(display_map, Bias::Left);
12276 selection.goal = SelectionGoal::None;
12277 selection.reversed = false;
12278 self.select_match_ranges(
12279 selection.start..selection.end,
12280 selection.reversed,
12281 replace_newest,
12282 autoscroll,
12283 window,
12284 cx,
12285 );
12286 }
12287
12288 if selections.len() == 1 {
12289 let selection = selections
12290 .last()
12291 .expect("ensured that there's only one selection");
12292 let query = buffer
12293 .text_for_range(selection.start..selection.end)
12294 .collect::<String>();
12295 let is_empty = query.is_empty();
12296 let select_state = SelectNextState {
12297 query: AhoCorasick::new(&[query])?,
12298 wordwise: true,
12299 done: is_empty,
12300 };
12301 self.select_next_state = Some(select_state);
12302 } else {
12303 self.select_next_state = None;
12304 }
12305 } else if let Some(selected_text) = selected_text {
12306 self.select_next_state = Some(SelectNextState {
12307 query: AhoCorasick::new(&[selected_text])?,
12308 wordwise: false,
12309 done: false,
12310 });
12311 self.select_next_match_internal(
12312 display_map,
12313 replace_newest,
12314 autoscroll,
12315 window,
12316 cx,
12317 )?;
12318 }
12319 }
12320 Ok(())
12321 }
12322
12323 pub fn select_all_matches(
12324 &mut self,
12325 _action: &SelectAllMatches,
12326 window: &mut Window,
12327 cx: &mut Context<Self>,
12328 ) -> Result<()> {
12329 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12330
12331 self.push_to_selection_history();
12332 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12333
12334 self.select_next_match_internal(&display_map, false, None, window, cx)?;
12335 let Some(select_next_state) = self.select_next_state.as_mut() else {
12336 return Ok(());
12337 };
12338 if select_next_state.done {
12339 return Ok(());
12340 }
12341
12342 let mut new_selections = Vec::new();
12343
12344 let reversed = self.selections.oldest::<usize>(cx).reversed;
12345 let buffer = &display_map.buffer_snapshot;
12346 let query_matches = select_next_state
12347 .query
12348 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
12349
12350 for query_match in query_matches.into_iter() {
12351 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
12352 let offset_range = if reversed {
12353 query_match.end()..query_match.start()
12354 } else {
12355 query_match.start()..query_match.end()
12356 };
12357 let display_range = offset_range.start.to_display_point(&display_map)
12358 ..offset_range.end.to_display_point(&display_map);
12359
12360 if !select_next_state.wordwise
12361 || (!movement::is_inside_word(&display_map, display_range.start)
12362 && !movement::is_inside_word(&display_map, display_range.end))
12363 {
12364 new_selections.push(offset_range.start..offset_range.end);
12365 }
12366 }
12367
12368 select_next_state.done = true;
12369 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12370 self.change_selections(None, window, cx, |selections| {
12371 selections.select_ranges(new_selections)
12372 });
12373
12374 Ok(())
12375 }
12376
12377 pub fn select_next(
12378 &mut self,
12379 action: &SelectNext,
12380 window: &mut Window,
12381 cx: &mut Context<Self>,
12382 ) -> Result<()> {
12383 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12384 self.push_to_selection_history();
12385 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12386 self.select_next_match_internal(
12387 &display_map,
12388 action.replace_newest,
12389 Some(Autoscroll::newest()),
12390 window,
12391 cx,
12392 )?;
12393 Ok(())
12394 }
12395
12396 pub fn select_previous(
12397 &mut self,
12398 action: &SelectPrevious,
12399 window: &mut Window,
12400 cx: &mut Context<Self>,
12401 ) -> Result<()> {
12402 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12403 self.push_to_selection_history();
12404 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12405 let buffer = &display_map.buffer_snapshot;
12406 let mut selections = self.selections.all::<usize>(cx);
12407 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12408 let query = &select_prev_state.query;
12409 if !select_prev_state.done {
12410 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12411 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12412 let mut next_selected_range = None;
12413 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12414 let bytes_before_last_selection =
12415 buffer.reversed_bytes_in_range(0..last_selection.start);
12416 let bytes_after_first_selection =
12417 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12418 let query_matches = query
12419 .stream_find_iter(bytes_before_last_selection)
12420 .map(|result| (last_selection.start, result))
12421 .chain(
12422 query
12423 .stream_find_iter(bytes_after_first_selection)
12424 .map(|result| (buffer.len(), result)),
12425 );
12426 for (end_offset, query_match) in query_matches {
12427 let query_match = query_match.unwrap(); // can only fail due to I/O
12428 let offset_range =
12429 end_offset - query_match.end()..end_offset - query_match.start();
12430 let display_range = offset_range.start.to_display_point(&display_map)
12431 ..offset_range.end.to_display_point(&display_map);
12432
12433 if !select_prev_state.wordwise
12434 || (!movement::is_inside_word(&display_map, display_range.start)
12435 && !movement::is_inside_word(&display_map, display_range.end))
12436 {
12437 next_selected_range = Some(offset_range);
12438 break;
12439 }
12440 }
12441
12442 if let Some(next_selected_range) = next_selected_range {
12443 self.select_match_ranges(
12444 next_selected_range,
12445 last_selection.reversed,
12446 action.replace_newest,
12447 Some(Autoscroll::newest()),
12448 window,
12449 cx,
12450 );
12451 } else {
12452 select_prev_state.done = true;
12453 }
12454 }
12455
12456 self.select_prev_state = Some(select_prev_state);
12457 } else {
12458 let mut only_carets = true;
12459 let mut same_text_selected = true;
12460 let mut selected_text = None;
12461
12462 let mut selections_iter = selections.iter().peekable();
12463 while let Some(selection) = selections_iter.next() {
12464 if selection.start != selection.end {
12465 only_carets = false;
12466 }
12467
12468 if same_text_selected {
12469 if selected_text.is_none() {
12470 selected_text =
12471 Some(buffer.text_for_range(selection.range()).collect::<String>());
12472 }
12473
12474 if let Some(next_selection) = selections_iter.peek() {
12475 if next_selection.range().len() == selection.range().len() {
12476 let next_selected_text = buffer
12477 .text_for_range(next_selection.range())
12478 .collect::<String>();
12479 if Some(next_selected_text) != selected_text {
12480 same_text_selected = false;
12481 selected_text = None;
12482 }
12483 } else {
12484 same_text_selected = false;
12485 selected_text = None;
12486 }
12487 }
12488 }
12489 }
12490
12491 if only_carets {
12492 for selection in &mut selections {
12493 let word_range = movement::surrounding_word(
12494 &display_map,
12495 selection.start.to_display_point(&display_map),
12496 );
12497 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12498 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12499 selection.goal = SelectionGoal::None;
12500 selection.reversed = false;
12501 self.select_match_ranges(
12502 selection.start..selection.end,
12503 selection.reversed,
12504 action.replace_newest,
12505 Some(Autoscroll::newest()),
12506 window,
12507 cx,
12508 );
12509 }
12510 if selections.len() == 1 {
12511 let selection = selections
12512 .last()
12513 .expect("ensured that there's only one selection");
12514 let query = buffer
12515 .text_for_range(selection.start..selection.end)
12516 .collect::<String>();
12517 let is_empty = query.is_empty();
12518 let select_state = SelectNextState {
12519 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12520 wordwise: true,
12521 done: is_empty,
12522 };
12523 self.select_prev_state = Some(select_state);
12524 } else {
12525 self.select_prev_state = None;
12526 }
12527 } else if let Some(selected_text) = selected_text {
12528 self.select_prev_state = Some(SelectNextState {
12529 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12530 wordwise: false,
12531 done: false,
12532 });
12533 self.select_previous(action, window, cx)?;
12534 }
12535 }
12536 Ok(())
12537 }
12538
12539 pub fn find_next_match(
12540 &mut self,
12541 _: &FindNextMatch,
12542 window: &mut Window,
12543 cx: &mut Context<Self>,
12544 ) -> Result<()> {
12545 let selections = self.selections.disjoint_anchors();
12546 match selections.first() {
12547 Some(first) if selections.len() >= 2 => {
12548 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12549 s.select_ranges([first.range()]);
12550 });
12551 }
12552 _ => self.select_next(
12553 &SelectNext {
12554 replace_newest: true,
12555 },
12556 window,
12557 cx,
12558 )?,
12559 }
12560 Ok(())
12561 }
12562
12563 pub fn find_previous_match(
12564 &mut self,
12565 _: &FindPreviousMatch,
12566 window: &mut Window,
12567 cx: &mut Context<Self>,
12568 ) -> Result<()> {
12569 let selections = self.selections.disjoint_anchors();
12570 match selections.last() {
12571 Some(last) if selections.len() >= 2 => {
12572 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12573 s.select_ranges([last.range()]);
12574 });
12575 }
12576 _ => self.select_previous(
12577 &SelectPrevious {
12578 replace_newest: true,
12579 },
12580 window,
12581 cx,
12582 )?,
12583 }
12584 Ok(())
12585 }
12586
12587 pub fn toggle_comments(
12588 &mut self,
12589 action: &ToggleComments,
12590 window: &mut Window,
12591 cx: &mut Context<Self>,
12592 ) {
12593 if self.read_only(cx) {
12594 return;
12595 }
12596 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12597 let text_layout_details = &self.text_layout_details(window);
12598 self.transact(window, cx, |this, window, cx| {
12599 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12600 let mut edits = Vec::new();
12601 let mut selection_edit_ranges = Vec::new();
12602 let mut last_toggled_row = None;
12603 let snapshot = this.buffer.read(cx).read(cx);
12604 let empty_str: Arc<str> = Arc::default();
12605 let mut suffixes_inserted = Vec::new();
12606 let ignore_indent = action.ignore_indent;
12607
12608 fn comment_prefix_range(
12609 snapshot: &MultiBufferSnapshot,
12610 row: MultiBufferRow,
12611 comment_prefix: &str,
12612 comment_prefix_whitespace: &str,
12613 ignore_indent: bool,
12614 ) -> Range<Point> {
12615 let indent_size = if ignore_indent {
12616 0
12617 } else {
12618 snapshot.indent_size_for_line(row).len
12619 };
12620
12621 let start = Point::new(row.0, indent_size);
12622
12623 let mut line_bytes = snapshot
12624 .bytes_in_range(start..snapshot.max_point())
12625 .flatten()
12626 .copied();
12627
12628 // If this line currently begins with the line comment prefix, then record
12629 // the range containing the prefix.
12630 if line_bytes
12631 .by_ref()
12632 .take(comment_prefix.len())
12633 .eq(comment_prefix.bytes())
12634 {
12635 // Include any whitespace that matches the comment prefix.
12636 let matching_whitespace_len = line_bytes
12637 .zip(comment_prefix_whitespace.bytes())
12638 .take_while(|(a, b)| a == b)
12639 .count() as u32;
12640 let end = Point::new(
12641 start.row,
12642 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12643 );
12644 start..end
12645 } else {
12646 start..start
12647 }
12648 }
12649
12650 fn comment_suffix_range(
12651 snapshot: &MultiBufferSnapshot,
12652 row: MultiBufferRow,
12653 comment_suffix: &str,
12654 comment_suffix_has_leading_space: bool,
12655 ) -> Range<Point> {
12656 let end = Point::new(row.0, snapshot.line_len(row));
12657 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12658
12659 let mut line_end_bytes = snapshot
12660 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12661 .flatten()
12662 .copied();
12663
12664 let leading_space_len = if suffix_start_column > 0
12665 && line_end_bytes.next() == Some(b' ')
12666 && comment_suffix_has_leading_space
12667 {
12668 1
12669 } else {
12670 0
12671 };
12672
12673 // If this line currently begins with the line comment prefix, then record
12674 // the range containing the prefix.
12675 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12676 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12677 start..end
12678 } else {
12679 end..end
12680 }
12681 }
12682
12683 // TODO: Handle selections that cross excerpts
12684 for selection in &mut selections {
12685 let start_column = snapshot
12686 .indent_size_for_line(MultiBufferRow(selection.start.row))
12687 .len;
12688 let language = if let Some(language) =
12689 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12690 {
12691 language
12692 } else {
12693 continue;
12694 };
12695
12696 selection_edit_ranges.clear();
12697
12698 // If multiple selections contain a given row, avoid processing that
12699 // row more than once.
12700 let mut start_row = MultiBufferRow(selection.start.row);
12701 if last_toggled_row == Some(start_row) {
12702 start_row = start_row.next_row();
12703 }
12704 let end_row =
12705 if selection.end.row > selection.start.row && selection.end.column == 0 {
12706 MultiBufferRow(selection.end.row - 1)
12707 } else {
12708 MultiBufferRow(selection.end.row)
12709 };
12710 last_toggled_row = Some(end_row);
12711
12712 if start_row > end_row {
12713 continue;
12714 }
12715
12716 // If the language has line comments, toggle those.
12717 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12718
12719 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12720 if ignore_indent {
12721 full_comment_prefixes = full_comment_prefixes
12722 .into_iter()
12723 .map(|s| Arc::from(s.trim_end()))
12724 .collect();
12725 }
12726
12727 if !full_comment_prefixes.is_empty() {
12728 let first_prefix = full_comment_prefixes
12729 .first()
12730 .expect("prefixes is non-empty");
12731 let prefix_trimmed_lengths = full_comment_prefixes
12732 .iter()
12733 .map(|p| p.trim_end_matches(' ').len())
12734 .collect::<SmallVec<[usize; 4]>>();
12735
12736 let mut all_selection_lines_are_comments = true;
12737
12738 for row in start_row.0..=end_row.0 {
12739 let row = MultiBufferRow(row);
12740 if start_row < end_row && snapshot.is_line_blank(row) {
12741 continue;
12742 }
12743
12744 let prefix_range = full_comment_prefixes
12745 .iter()
12746 .zip(prefix_trimmed_lengths.iter().copied())
12747 .map(|(prefix, trimmed_prefix_len)| {
12748 comment_prefix_range(
12749 snapshot.deref(),
12750 row,
12751 &prefix[..trimmed_prefix_len],
12752 &prefix[trimmed_prefix_len..],
12753 ignore_indent,
12754 )
12755 })
12756 .max_by_key(|range| range.end.column - range.start.column)
12757 .expect("prefixes is non-empty");
12758
12759 if prefix_range.is_empty() {
12760 all_selection_lines_are_comments = false;
12761 }
12762
12763 selection_edit_ranges.push(prefix_range);
12764 }
12765
12766 if all_selection_lines_are_comments {
12767 edits.extend(
12768 selection_edit_ranges
12769 .iter()
12770 .cloned()
12771 .map(|range| (range, empty_str.clone())),
12772 );
12773 } else {
12774 let min_column = selection_edit_ranges
12775 .iter()
12776 .map(|range| range.start.column)
12777 .min()
12778 .unwrap_or(0);
12779 edits.extend(selection_edit_ranges.iter().map(|range| {
12780 let position = Point::new(range.start.row, min_column);
12781 (position..position, first_prefix.clone())
12782 }));
12783 }
12784 } else if let Some((full_comment_prefix, comment_suffix)) =
12785 language.block_comment_delimiters()
12786 {
12787 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12788 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12789 let prefix_range = comment_prefix_range(
12790 snapshot.deref(),
12791 start_row,
12792 comment_prefix,
12793 comment_prefix_whitespace,
12794 ignore_indent,
12795 );
12796 let suffix_range = comment_suffix_range(
12797 snapshot.deref(),
12798 end_row,
12799 comment_suffix.trim_start_matches(' '),
12800 comment_suffix.starts_with(' '),
12801 );
12802
12803 if prefix_range.is_empty() || suffix_range.is_empty() {
12804 edits.push((
12805 prefix_range.start..prefix_range.start,
12806 full_comment_prefix.clone(),
12807 ));
12808 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12809 suffixes_inserted.push((end_row, comment_suffix.len()));
12810 } else {
12811 edits.push((prefix_range, empty_str.clone()));
12812 edits.push((suffix_range, empty_str.clone()));
12813 }
12814 } else {
12815 continue;
12816 }
12817 }
12818
12819 drop(snapshot);
12820 this.buffer.update(cx, |buffer, cx| {
12821 buffer.edit(edits, None, cx);
12822 });
12823
12824 // Adjust selections so that they end before any comment suffixes that
12825 // were inserted.
12826 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12827 let mut selections = this.selections.all::<Point>(cx);
12828 let snapshot = this.buffer.read(cx).read(cx);
12829 for selection in &mut selections {
12830 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12831 match row.cmp(&MultiBufferRow(selection.end.row)) {
12832 Ordering::Less => {
12833 suffixes_inserted.next();
12834 continue;
12835 }
12836 Ordering::Greater => break,
12837 Ordering::Equal => {
12838 if selection.end.column == snapshot.line_len(row) {
12839 if selection.is_empty() {
12840 selection.start.column -= suffix_len as u32;
12841 }
12842 selection.end.column -= suffix_len as u32;
12843 }
12844 break;
12845 }
12846 }
12847 }
12848 }
12849
12850 drop(snapshot);
12851 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12852 s.select(selections)
12853 });
12854
12855 let selections = this.selections.all::<Point>(cx);
12856 let selections_on_single_row = selections.windows(2).all(|selections| {
12857 selections[0].start.row == selections[1].start.row
12858 && selections[0].end.row == selections[1].end.row
12859 && selections[0].start.row == selections[0].end.row
12860 });
12861 let selections_selecting = selections
12862 .iter()
12863 .any(|selection| selection.start != selection.end);
12864 let advance_downwards = action.advance_downwards
12865 && selections_on_single_row
12866 && !selections_selecting
12867 && !matches!(this.mode, EditorMode::SingleLine { .. });
12868
12869 if advance_downwards {
12870 let snapshot = this.buffer.read(cx).snapshot(cx);
12871
12872 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12873 s.move_cursors_with(|display_snapshot, display_point, _| {
12874 let mut point = display_point.to_point(display_snapshot);
12875 point.row += 1;
12876 point = snapshot.clip_point(point, Bias::Left);
12877 let display_point = point.to_display_point(display_snapshot);
12878 let goal = SelectionGoal::HorizontalPosition(
12879 display_snapshot
12880 .x_for_display_point(display_point, text_layout_details)
12881 .into(),
12882 );
12883 (display_point, goal)
12884 })
12885 });
12886 }
12887 });
12888 }
12889
12890 pub fn select_enclosing_symbol(
12891 &mut self,
12892 _: &SelectEnclosingSymbol,
12893 window: &mut Window,
12894 cx: &mut Context<Self>,
12895 ) {
12896 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12897
12898 let buffer = self.buffer.read(cx).snapshot(cx);
12899 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12900
12901 fn update_selection(
12902 selection: &Selection<usize>,
12903 buffer_snap: &MultiBufferSnapshot,
12904 ) -> Option<Selection<usize>> {
12905 let cursor = selection.head();
12906 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12907 for symbol in symbols.iter().rev() {
12908 let start = symbol.range.start.to_offset(buffer_snap);
12909 let end = symbol.range.end.to_offset(buffer_snap);
12910 let new_range = start..end;
12911 if start < selection.start || end > selection.end {
12912 return Some(Selection {
12913 id: selection.id,
12914 start: new_range.start,
12915 end: new_range.end,
12916 goal: SelectionGoal::None,
12917 reversed: selection.reversed,
12918 });
12919 }
12920 }
12921 None
12922 }
12923
12924 let mut selected_larger_symbol = false;
12925 let new_selections = old_selections
12926 .iter()
12927 .map(|selection| match update_selection(selection, &buffer) {
12928 Some(new_selection) => {
12929 if new_selection.range() != selection.range() {
12930 selected_larger_symbol = true;
12931 }
12932 new_selection
12933 }
12934 None => selection.clone(),
12935 })
12936 .collect::<Vec<_>>();
12937
12938 if selected_larger_symbol {
12939 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12940 s.select(new_selections);
12941 });
12942 }
12943 }
12944
12945 pub fn select_larger_syntax_node(
12946 &mut self,
12947 _: &SelectLargerSyntaxNode,
12948 window: &mut Window,
12949 cx: &mut Context<Self>,
12950 ) {
12951 let Some(visible_row_count) = self.visible_row_count() else {
12952 return;
12953 };
12954 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12955 if old_selections.is_empty() {
12956 return;
12957 }
12958
12959 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12960
12961 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12962 let buffer = self.buffer.read(cx).snapshot(cx);
12963
12964 let mut selected_larger_node = false;
12965 let mut new_selections = old_selections
12966 .iter()
12967 .map(|selection| {
12968 let old_range = selection.start..selection.end;
12969
12970 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12971 // manually select word at selection
12972 if ["string_content", "inline"].contains(&node.kind()) {
12973 let word_range = {
12974 let display_point = buffer
12975 .offset_to_point(old_range.start)
12976 .to_display_point(&display_map);
12977 let Range { start, end } =
12978 movement::surrounding_word(&display_map, display_point);
12979 start.to_point(&display_map).to_offset(&buffer)
12980 ..end.to_point(&display_map).to_offset(&buffer)
12981 };
12982 // ignore if word is already selected
12983 if !word_range.is_empty() && old_range != word_range {
12984 let last_word_range = {
12985 let display_point = buffer
12986 .offset_to_point(old_range.end)
12987 .to_display_point(&display_map);
12988 let Range { start, end } =
12989 movement::surrounding_word(&display_map, display_point);
12990 start.to_point(&display_map).to_offset(&buffer)
12991 ..end.to_point(&display_map).to_offset(&buffer)
12992 };
12993 // only select word if start and end point belongs to same word
12994 if word_range == last_word_range {
12995 selected_larger_node = true;
12996 return Selection {
12997 id: selection.id,
12998 start: word_range.start,
12999 end: word_range.end,
13000 goal: SelectionGoal::None,
13001 reversed: selection.reversed,
13002 };
13003 }
13004 }
13005 }
13006 }
13007
13008 let mut new_range = old_range.clone();
13009 while let Some((_node, containing_range)) =
13010 buffer.syntax_ancestor(new_range.clone())
13011 {
13012 new_range = match containing_range {
13013 MultiOrSingleBufferOffsetRange::Single(_) => break,
13014 MultiOrSingleBufferOffsetRange::Multi(range) => range,
13015 };
13016 if !display_map.intersects_fold(new_range.start)
13017 && !display_map.intersects_fold(new_range.end)
13018 {
13019 break;
13020 }
13021 }
13022
13023 selected_larger_node |= new_range != old_range;
13024 Selection {
13025 id: selection.id,
13026 start: new_range.start,
13027 end: new_range.end,
13028 goal: SelectionGoal::None,
13029 reversed: selection.reversed,
13030 }
13031 })
13032 .collect::<Vec<_>>();
13033
13034 if !selected_larger_node {
13035 return; // don't put this call in the history
13036 }
13037
13038 // scroll based on transformation done to the last selection created by the user
13039 let (last_old, last_new) = old_selections
13040 .last()
13041 .zip(new_selections.last().cloned())
13042 .expect("old_selections isn't empty");
13043
13044 // revert selection
13045 let is_selection_reversed = {
13046 let should_newest_selection_be_reversed = last_old.start != last_new.start;
13047 new_selections.last_mut().expect("checked above").reversed =
13048 should_newest_selection_be_reversed;
13049 should_newest_selection_be_reversed
13050 };
13051
13052 if selected_larger_node {
13053 self.select_syntax_node_history.disable_clearing = true;
13054 self.change_selections(None, window, cx, |s| {
13055 s.select(new_selections.clone());
13056 });
13057 self.select_syntax_node_history.disable_clearing = false;
13058 }
13059
13060 let start_row = last_new.start.to_display_point(&display_map).row().0;
13061 let end_row = last_new.end.to_display_point(&display_map).row().0;
13062 let selection_height = end_row - start_row + 1;
13063 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
13064
13065 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
13066 let scroll_behavior = if fits_on_the_screen {
13067 self.request_autoscroll(Autoscroll::fit(), cx);
13068 SelectSyntaxNodeScrollBehavior::FitSelection
13069 } else if is_selection_reversed {
13070 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13071 SelectSyntaxNodeScrollBehavior::CursorTop
13072 } else {
13073 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13074 SelectSyntaxNodeScrollBehavior::CursorBottom
13075 };
13076
13077 self.select_syntax_node_history.push((
13078 old_selections,
13079 scroll_behavior,
13080 is_selection_reversed,
13081 ));
13082 }
13083
13084 pub fn select_smaller_syntax_node(
13085 &mut self,
13086 _: &SelectSmallerSyntaxNode,
13087 window: &mut Window,
13088 cx: &mut Context<Self>,
13089 ) {
13090 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13091
13092 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
13093 self.select_syntax_node_history.pop()
13094 {
13095 if let Some(selection) = selections.last_mut() {
13096 selection.reversed = is_selection_reversed;
13097 }
13098
13099 self.select_syntax_node_history.disable_clearing = true;
13100 self.change_selections(None, window, cx, |s| {
13101 s.select(selections.to_vec());
13102 });
13103 self.select_syntax_node_history.disable_clearing = false;
13104
13105 match scroll_behavior {
13106 SelectSyntaxNodeScrollBehavior::CursorTop => {
13107 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
13108 }
13109 SelectSyntaxNodeScrollBehavior::FitSelection => {
13110 self.request_autoscroll(Autoscroll::fit(), cx);
13111 }
13112 SelectSyntaxNodeScrollBehavior::CursorBottom => {
13113 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
13114 }
13115 }
13116 }
13117 }
13118
13119 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
13120 if !EditorSettings::get_global(cx).gutter.runnables {
13121 self.clear_tasks();
13122 return Task::ready(());
13123 }
13124 let project = self.project.as_ref().map(Entity::downgrade);
13125 let task_sources = self.lsp_task_sources(cx);
13126 cx.spawn_in(window, async move |editor, cx| {
13127 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
13128 let Some(project) = project.and_then(|p| p.upgrade()) else {
13129 return;
13130 };
13131 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
13132 this.display_map.update(cx, |map, cx| map.snapshot(cx))
13133 }) else {
13134 return;
13135 };
13136
13137 let hide_runnables = project
13138 .update(cx, |project, cx| {
13139 // Do not display any test indicators in non-dev server remote projects.
13140 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
13141 })
13142 .unwrap_or(true);
13143 if hide_runnables {
13144 return;
13145 }
13146 let new_rows =
13147 cx.background_spawn({
13148 let snapshot = display_snapshot.clone();
13149 async move {
13150 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
13151 }
13152 })
13153 .await;
13154 let Ok(lsp_tasks) =
13155 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
13156 else {
13157 return;
13158 };
13159 let lsp_tasks = lsp_tasks.await;
13160
13161 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
13162 lsp_tasks
13163 .into_iter()
13164 .flat_map(|(kind, tasks)| {
13165 tasks.into_iter().filter_map(move |(location, task)| {
13166 Some((kind.clone(), location?, task))
13167 })
13168 })
13169 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
13170 let buffer = location.target.buffer;
13171 let buffer_snapshot = buffer.read(cx).snapshot();
13172 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
13173 |(excerpt_id, snapshot, _)| {
13174 if snapshot.remote_id() == buffer_snapshot.remote_id() {
13175 display_snapshot
13176 .buffer_snapshot
13177 .anchor_in_excerpt(excerpt_id, location.target.range.start)
13178 } else {
13179 None
13180 }
13181 },
13182 );
13183 if let Some(offset) = offset {
13184 let task_buffer_range =
13185 location.target.range.to_point(&buffer_snapshot);
13186 let context_buffer_range =
13187 task_buffer_range.to_offset(&buffer_snapshot);
13188 let context_range = BufferOffset(context_buffer_range.start)
13189 ..BufferOffset(context_buffer_range.end);
13190
13191 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
13192 .or_insert_with(|| RunnableTasks {
13193 templates: Vec::new(),
13194 offset,
13195 column: task_buffer_range.start.column,
13196 extra_variables: HashMap::default(),
13197 context_range,
13198 })
13199 .templates
13200 .push((kind, task.original_task().clone()));
13201 }
13202
13203 acc
13204 })
13205 }) else {
13206 return;
13207 };
13208
13209 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
13210 editor
13211 .update(cx, |editor, _| {
13212 editor.clear_tasks();
13213 for (key, mut value) in rows {
13214 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
13215 value.templates.extend(lsp_tasks.templates);
13216 }
13217
13218 editor.insert_tasks(key, value);
13219 }
13220 for (key, value) in lsp_tasks_by_rows {
13221 editor.insert_tasks(key, value);
13222 }
13223 })
13224 .ok();
13225 })
13226 }
13227 fn fetch_runnable_ranges(
13228 snapshot: &DisplaySnapshot,
13229 range: Range<Anchor>,
13230 ) -> Vec<language::RunnableRange> {
13231 snapshot.buffer_snapshot.runnable_ranges(range).collect()
13232 }
13233
13234 fn runnable_rows(
13235 project: Entity<Project>,
13236 snapshot: DisplaySnapshot,
13237 runnable_ranges: Vec<RunnableRange>,
13238 mut cx: AsyncWindowContext,
13239 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
13240 runnable_ranges
13241 .into_iter()
13242 .filter_map(|mut runnable| {
13243 let tasks = cx
13244 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
13245 .ok()?;
13246 if tasks.is_empty() {
13247 return None;
13248 }
13249
13250 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
13251
13252 let row = snapshot
13253 .buffer_snapshot
13254 .buffer_line_for_row(MultiBufferRow(point.row))?
13255 .1
13256 .start
13257 .row;
13258
13259 let context_range =
13260 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
13261 Some((
13262 (runnable.buffer_id, row),
13263 RunnableTasks {
13264 templates: tasks,
13265 offset: snapshot
13266 .buffer_snapshot
13267 .anchor_before(runnable.run_range.start),
13268 context_range,
13269 column: point.column,
13270 extra_variables: runnable.extra_captures,
13271 },
13272 ))
13273 })
13274 .collect()
13275 }
13276
13277 fn templates_with_tags(
13278 project: &Entity<Project>,
13279 runnable: &mut Runnable,
13280 cx: &mut App,
13281 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
13282 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
13283 let (worktree_id, file) = project
13284 .buffer_for_id(runnable.buffer, cx)
13285 .and_then(|buffer| buffer.read(cx).file())
13286 .map(|file| (file.worktree_id(cx), file.clone()))
13287 .unzip();
13288
13289 (
13290 project.task_store().read(cx).task_inventory().cloned(),
13291 worktree_id,
13292 file,
13293 )
13294 });
13295
13296 let mut templates_with_tags = mem::take(&mut runnable.tags)
13297 .into_iter()
13298 .flat_map(|RunnableTag(tag)| {
13299 inventory
13300 .as_ref()
13301 .into_iter()
13302 .flat_map(|inventory| {
13303 inventory.read(cx).list_tasks(
13304 file.clone(),
13305 Some(runnable.language.clone()),
13306 worktree_id,
13307 cx,
13308 )
13309 })
13310 .filter(move |(_, template)| {
13311 template.tags.iter().any(|source_tag| source_tag == &tag)
13312 })
13313 })
13314 .sorted_by_key(|(kind, _)| kind.to_owned())
13315 .collect::<Vec<_>>();
13316 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
13317 // Strongest source wins; if we have worktree tag binding, prefer that to
13318 // global and language bindings;
13319 // if we have a global binding, prefer that to language binding.
13320 let first_mismatch = templates_with_tags
13321 .iter()
13322 .position(|(tag_source, _)| tag_source != leading_tag_source);
13323 if let Some(index) = first_mismatch {
13324 templates_with_tags.truncate(index);
13325 }
13326 }
13327
13328 templates_with_tags
13329 }
13330
13331 pub fn move_to_enclosing_bracket(
13332 &mut self,
13333 _: &MoveToEnclosingBracket,
13334 window: &mut Window,
13335 cx: &mut Context<Self>,
13336 ) {
13337 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13338 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13339 s.move_offsets_with(|snapshot, selection| {
13340 let Some(enclosing_bracket_ranges) =
13341 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13342 else {
13343 return;
13344 };
13345
13346 let mut best_length = usize::MAX;
13347 let mut best_inside = false;
13348 let mut best_in_bracket_range = false;
13349 let mut best_destination = None;
13350 for (open, close) in enclosing_bracket_ranges {
13351 let close = close.to_inclusive();
13352 let length = close.end() - open.start;
13353 let inside = selection.start >= open.end && selection.end <= *close.start();
13354 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13355 || close.contains(&selection.head());
13356
13357 // If best is next to a bracket and current isn't, skip
13358 if !in_bracket_range && best_in_bracket_range {
13359 continue;
13360 }
13361
13362 // Prefer smaller lengths unless best is inside and current isn't
13363 if length > best_length && (best_inside || !inside) {
13364 continue;
13365 }
13366
13367 best_length = length;
13368 best_inside = inside;
13369 best_in_bracket_range = in_bracket_range;
13370 best_destination = Some(
13371 if close.contains(&selection.start) && close.contains(&selection.end) {
13372 if inside { open.end } else { open.start }
13373 } else if inside {
13374 *close.start()
13375 } else {
13376 *close.end()
13377 },
13378 );
13379 }
13380
13381 if let Some(destination) = best_destination {
13382 selection.collapse_to(destination, SelectionGoal::None);
13383 }
13384 })
13385 });
13386 }
13387
13388 pub fn undo_selection(
13389 &mut self,
13390 _: &UndoSelection,
13391 window: &mut Window,
13392 cx: &mut Context<Self>,
13393 ) {
13394 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13395 self.end_selection(window, cx);
13396 self.selection_history.mode = SelectionHistoryMode::Undoing;
13397 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13398 self.change_selections(None, window, cx, |s| {
13399 s.select_anchors(entry.selections.to_vec())
13400 });
13401 self.select_next_state = entry.select_next_state;
13402 self.select_prev_state = entry.select_prev_state;
13403 self.add_selections_state = entry.add_selections_state;
13404 self.request_autoscroll(Autoscroll::newest(), cx);
13405 }
13406 self.selection_history.mode = SelectionHistoryMode::Normal;
13407 }
13408
13409 pub fn redo_selection(
13410 &mut self,
13411 _: &RedoSelection,
13412 window: &mut Window,
13413 cx: &mut Context<Self>,
13414 ) {
13415 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13416 self.end_selection(window, cx);
13417 self.selection_history.mode = SelectionHistoryMode::Redoing;
13418 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13419 self.change_selections(None, window, cx, |s| {
13420 s.select_anchors(entry.selections.to_vec())
13421 });
13422 self.select_next_state = entry.select_next_state;
13423 self.select_prev_state = entry.select_prev_state;
13424 self.add_selections_state = entry.add_selections_state;
13425 self.request_autoscroll(Autoscroll::newest(), cx);
13426 }
13427 self.selection_history.mode = SelectionHistoryMode::Normal;
13428 }
13429
13430 pub fn expand_excerpts(
13431 &mut self,
13432 action: &ExpandExcerpts,
13433 _: &mut Window,
13434 cx: &mut Context<Self>,
13435 ) {
13436 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13437 }
13438
13439 pub fn expand_excerpts_down(
13440 &mut self,
13441 action: &ExpandExcerptsDown,
13442 _: &mut Window,
13443 cx: &mut Context<Self>,
13444 ) {
13445 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13446 }
13447
13448 pub fn expand_excerpts_up(
13449 &mut self,
13450 action: &ExpandExcerptsUp,
13451 _: &mut Window,
13452 cx: &mut Context<Self>,
13453 ) {
13454 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13455 }
13456
13457 pub fn expand_excerpts_for_direction(
13458 &mut self,
13459 lines: u32,
13460 direction: ExpandExcerptDirection,
13461
13462 cx: &mut Context<Self>,
13463 ) {
13464 let selections = self.selections.disjoint_anchors();
13465
13466 let lines = if lines == 0 {
13467 EditorSettings::get_global(cx).expand_excerpt_lines
13468 } else {
13469 lines
13470 };
13471
13472 self.buffer.update(cx, |buffer, cx| {
13473 let snapshot = buffer.snapshot(cx);
13474 let mut excerpt_ids = selections
13475 .iter()
13476 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13477 .collect::<Vec<_>>();
13478 excerpt_ids.sort();
13479 excerpt_ids.dedup();
13480 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13481 })
13482 }
13483
13484 pub fn expand_excerpt(
13485 &mut self,
13486 excerpt: ExcerptId,
13487 direction: ExpandExcerptDirection,
13488 window: &mut Window,
13489 cx: &mut Context<Self>,
13490 ) {
13491 let current_scroll_position = self.scroll_position(cx);
13492 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13493 let mut should_scroll_up = false;
13494
13495 if direction == ExpandExcerptDirection::Down {
13496 let multi_buffer = self.buffer.read(cx);
13497 let snapshot = multi_buffer.snapshot(cx);
13498 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13499 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13500 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13501 let buffer_snapshot = buffer.read(cx).snapshot();
13502 let excerpt_end_row =
13503 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13504 let last_row = buffer_snapshot.max_point().row;
13505 let lines_below = last_row.saturating_sub(excerpt_end_row);
13506 should_scroll_up = lines_below >= lines_to_expand;
13507 }
13508 }
13509 }
13510 }
13511
13512 self.buffer.update(cx, |buffer, cx| {
13513 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13514 });
13515
13516 if should_scroll_up {
13517 let new_scroll_position =
13518 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13519 self.set_scroll_position(new_scroll_position, window, cx);
13520 }
13521 }
13522
13523 pub fn go_to_singleton_buffer_point(
13524 &mut self,
13525 point: Point,
13526 window: &mut Window,
13527 cx: &mut Context<Self>,
13528 ) {
13529 self.go_to_singleton_buffer_range(point..point, window, cx);
13530 }
13531
13532 pub fn go_to_singleton_buffer_range(
13533 &mut self,
13534 range: Range<Point>,
13535 window: &mut Window,
13536 cx: &mut Context<Self>,
13537 ) {
13538 let multibuffer = self.buffer().read(cx);
13539 let Some(buffer) = multibuffer.as_singleton() else {
13540 return;
13541 };
13542 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13543 return;
13544 };
13545 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13546 return;
13547 };
13548 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13549 s.select_anchor_ranges([start..end])
13550 });
13551 }
13552
13553 pub fn go_to_diagnostic(
13554 &mut self,
13555 _: &GoToDiagnostic,
13556 window: &mut Window,
13557 cx: &mut Context<Self>,
13558 ) {
13559 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13560 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13561 }
13562
13563 pub fn go_to_prev_diagnostic(
13564 &mut self,
13565 _: &GoToPreviousDiagnostic,
13566 window: &mut Window,
13567 cx: &mut Context<Self>,
13568 ) {
13569 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13570 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13571 }
13572
13573 pub fn go_to_diagnostic_impl(
13574 &mut self,
13575 direction: Direction,
13576 window: &mut Window,
13577 cx: &mut Context<Self>,
13578 ) {
13579 let buffer = self.buffer.read(cx).snapshot(cx);
13580 let selection = self.selections.newest::<usize>(cx);
13581
13582 let mut active_group_id = None;
13583 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13584 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13585 active_group_id = Some(active_group.group_id);
13586 }
13587 }
13588
13589 fn filtered(
13590 snapshot: EditorSnapshot,
13591 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13592 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13593 diagnostics
13594 .filter(|entry| entry.range.start != entry.range.end)
13595 .filter(|entry| !entry.diagnostic.is_unnecessary)
13596 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13597 }
13598
13599 let snapshot = self.snapshot(window, cx);
13600 let before = filtered(
13601 snapshot.clone(),
13602 buffer
13603 .diagnostics_in_range(0..selection.start)
13604 .filter(|entry| entry.range.start <= selection.start),
13605 );
13606 let after = filtered(
13607 snapshot,
13608 buffer
13609 .diagnostics_in_range(selection.start..buffer.len())
13610 .filter(|entry| entry.range.start >= selection.start),
13611 );
13612
13613 let mut found: Option<DiagnosticEntry<usize>> = None;
13614 if direction == Direction::Prev {
13615 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13616 {
13617 for diagnostic in prev_diagnostics.into_iter().rev() {
13618 if diagnostic.range.start != selection.start
13619 || active_group_id
13620 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13621 {
13622 found = Some(diagnostic);
13623 break 'outer;
13624 }
13625 }
13626 }
13627 } else {
13628 for diagnostic in after.chain(before) {
13629 if diagnostic.range.start != selection.start
13630 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13631 {
13632 found = Some(diagnostic);
13633 break;
13634 }
13635 }
13636 }
13637 let Some(next_diagnostic) = found else {
13638 return;
13639 };
13640
13641 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13642 return;
13643 };
13644 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13645 s.select_ranges(vec![
13646 next_diagnostic.range.start..next_diagnostic.range.start,
13647 ])
13648 });
13649 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13650 self.refresh_inline_completion(false, true, window, cx);
13651 }
13652
13653 pub fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13654 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13655 let snapshot = self.snapshot(window, cx);
13656 let selection = self.selections.newest::<Point>(cx);
13657 self.go_to_hunk_before_or_after_position(
13658 &snapshot,
13659 selection.head(),
13660 Direction::Next,
13661 window,
13662 cx,
13663 );
13664 }
13665
13666 pub fn go_to_hunk_before_or_after_position(
13667 &mut self,
13668 snapshot: &EditorSnapshot,
13669 position: Point,
13670 direction: Direction,
13671 window: &mut Window,
13672 cx: &mut Context<Editor>,
13673 ) {
13674 let row = if direction == Direction::Next {
13675 self.hunk_after_position(snapshot, position)
13676 .map(|hunk| hunk.row_range.start)
13677 } else {
13678 self.hunk_before_position(snapshot, position)
13679 };
13680
13681 if let Some(row) = row {
13682 let destination = Point::new(row.0, 0);
13683 let autoscroll = Autoscroll::center();
13684
13685 self.unfold_ranges(&[destination..destination], false, false, cx);
13686 self.change_selections(Some(autoscroll), window, cx, |s| {
13687 s.select_ranges([destination..destination]);
13688 });
13689 }
13690 }
13691
13692 fn hunk_after_position(
13693 &mut self,
13694 snapshot: &EditorSnapshot,
13695 position: Point,
13696 ) -> Option<MultiBufferDiffHunk> {
13697 snapshot
13698 .buffer_snapshot
13699 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13700 .find(|hunk| hunk.row_range.start.0 > position.row)
13701 .or_else(|| {
13702 snapshot
13703 .buffer_snapshot
13704 .diff_hunks_in_range(Point::zero()..position)
13705 .find(|hunk| hunk.row_range.end.0 < position.row)
13706 })
13707 }
13708
13709 fn go_to_prev_hunk(
13710 &mut self,
13711 _: &GoToPreviousHunk,
13712 window: &mut Window,
13713 cx: &mut Context<Self>,
13714 ) {
13715 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13716 let snapshot = self.snapshot(window, cx);
13717 let selection = self.selections.newest::<Point>(cx);
13718 self.go_to_hunk_before_or_after_position(
13719 &snapshot,
13720 selection.head(),
13721 Direction::Prev,
13722 window,
13723 cx,
13724 );
13725 }
13726
13727 fn hunk_before_position(
13728 &mut self,
13729 snapshot: &EditorSnapshot,
13730 position: Point,
13731 ) -> Option<MultiBufferRow> {
13732 snapshot
13733 .buffer_snapshot
13734 .diff_hunk_before(position)
13735 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13736 }
13737
13738 fn go_to_next_change(
13739 &mut self,
13740 _: &GoToNextChange,
13741 window: &mut Window,
13742 cx: &mut Context<Self>,
13743 ) {
13744 if let Some(selections) = self
13745 .change_list
13746 .next_change(1, Direction::Next)
13747 .map(|s| s.to_vec())
13748 {
13749 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13750 let map = s.display_map();
13751 s.select_display_ranges(selections.iter().map(|a| {
13752 let point = a.to_display_point(&map);
13753 point..point
13754 }))
13755 })
13756 }
13757 }
13758
13759 fn go_to_previous_change(
13760 &mut self,
13761 _: &GoToPreviousChange,
13762 window: &mut Window,
13763 cx: &mut Context<Self>,
13764 ) {
13765 if let Some(selections) = self
13766 .change_list
13767 .next_change(1, Direction::Prev)
13768 .map(|s| s.to_vec())
13769 {
13770 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13771 let map = s.display_map();
13772 s.select_display_ranges(selections.iter().map(|a| {
13773 let point = a.to_display_point(&map);
13774 point..point
13775 }))
13776 })
13777 }
13778 }
13779
13780 fn go_to_line<T: 'static>(
13781 &mut self,
13782 position: Anchor,
13783 highlight_color: Option<Hsla>,
13784 window: &mut Window,
13785 cx: &mut Context<Self>,
13786 ) {
13787 let snapshot = self.snapshot(window, cx).display_snapshot;
13788 let position = position.to_point(&snapshot.buffer_snapshot);
13789 let start = snapshot
13790 .buffer_snapshot
13791 .clip_point(Point::new(position.row, 0), Bias::Left);
13792 let end = start + Point::new(1, 0);
13793 let start = snapshot.buffer_snapshot.anchor_before(start);
13794 let end = snapshot.buffer_snapshot.anchor_before(end);
13795
13796 self.highlight_rows::<T>(
13797 start..end,
13798 highlight_color
13799 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13800 Default::default(),
13801 cx,
13802 );
13803 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13804 }
13805
13806 pub fn go_to_definition(
13807 &mut self,
13808 _: &GoToDefinition,
13809 window: &mut Window,
13810 cx: &mut Context<Self>,
13811 ) -> Task<Result<Navigated>> {
13812 let definition =
13813 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13814 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13815 cx.spawn_in(window, async move |editor, cx| {
13816 if definition.await? == Navigated::Yes {
13817 return Ok(Navigated::Yes);
13818 }
13819 match fallback_strategy {
13820 GoToDefinitionFallback::None => Ok(Navigated::No),
13821 GoToDefinitionFallback::FindAllReferences => {
13822 match editor.update_in(cx, |editor, window, cx| {
13823 editor.find_all_references(&FindAllReferences, window, cx)
13824 })? {
13825 Some(references) => references.await,
13826 None => Ok(Navigated::No),
13827 }
13828 }
13829 }
13830 })
13831 }
13832
13833 pub fn go_to_declaration(
13834 &mut self,
13835 _: &GoToDeclaration,
13836 window: &mut Window,
13837 cx: &mut Context<Self>,
13838 ) -> Task<Result<Navigated>> {
13839 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13840 }
13841
13842 pub fn go_to_declaration_split(
13843 &mut self,
13844 _: &GoToDeclaration,
13845 window: &mut Window,
13846 cx: &mut Context<Self>,
13847 ) -> Task<Result<Navigated>> {
13848 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13849 }
13850
13851 pub fn go_to_implementation(
13852 &mut self,
13853 _: &GoToImplementation,
13854 window: &mut Window,
13855 cx: &mut Context<Self>,
13856 ) -> Task<Result<Navigated>> {
13857 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13858 }
13859
13860 pub fn go_to_implementation_split(
13861 &mut self,
13862 _: &GoToImplementationSplit,
13863 window: &mut Window,
13864 cx: &mut Context<Self>,
13865 ) -> Task<Result<Navigated>> {
13866 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13867 }
13868
13869 pub fn go_to_type_definition(
13870 &mut self,
13871 _: &GoToTypeDefinition,
13872 window: &mut Window,
13873 cx: &mut Context<Self>,
13874 ) -> Task<Result<Navigated>> {
13875 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13876 }
13877
13878 pub fn go_to_definition_split(
13879 &mut self,
13880 _: &GoToDefinitionSplit,
13881 window: &mut Window,
13882 cx: &mut Context<Self>,
13883 ) -> Task<Result<Navigated>> {
13884 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13885 }
13886
13887 pub fn go_to_type_definition_split(
13888 &mut self,
13889 _: &GoToTypeDefinitionSplit,
13890 window: &mut Window,
13891 cx: &mut Context<Self>,
13892 ) -> Task<Result<Navigated>> {
13893 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13894 }
13895
13896 fn go_to_definition_of_kind(
13897 &mut self,
13898 kind: GotoDefinitionKind,
13899 split: bool,
13900 window: &mut Window,
13901 cx: &mut Context<Self>,
13902 ) -> Task<Result<Navigated>> {
13903 let Some(provider) = self.semantics_provider.clone() else {
13904 return Task::ready(Ok(Navigated::No));
13905 };
13906 let head = self.selections.newest::<usize>(cx).head();
13907 let buffer = self.buffer.read(cx);
13908 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13909 text_anchor
13910 } else {
13911 return Task::ready(Ok(Navigated::No));
13912 };
13913
13914 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13915 return Task::ready(Ok(Navigated::No));
13916 };
13917
13918 cx.spawn_in(window, async move |editor, cx| {
13919 let definitions = definitions.await?;
13920 let navigated = editor
13921 .update_in(cx, |editor, window, cx| {
13922 editor.navigate_to_hover_links(
13923 Some(kind),
13924 definitions
13925 .into_iter()
13926 .filter(|location| {
13927 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13928 })
13929 .map(HoverLink::Text)
13930 .collect::<Vec<_>>(),
13931 split,
13932 window,
13933 cx,
13934 )
13935 })?
13936 .await?;
13937 anyhow::Ok(navigated)
13938 })
13939 }
13940
13941 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13942 let selection = self.selections.newest_anchor();
13943 let head = selection.head();
13944 let tail = selection.tail();
13945
13946 let Some((buffer, start_position)) =
13947 self.buffer.read(cx).text_anchor_for_position(head, cx)
13948 else {
13949 return;
13950 };
13951
13952 let end_position = if head != tail {
13953 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13954 return;
13955 };
13956 Some(pos)
13957 } else {
13958 None
13959 };
13960
13961 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13962 let url = if let Some(end_pos) = end_position {
13963 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13964 } else {
13965 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13966 };
13967
13968 if let Some(url) = url {
13969 editor.update(cx, |_, cx| {
13970 cx.open_url(&url);
13971 })
13972 } else {
13973 Ok(())
13974 }
13975 });
13976
13977 url_finder.detach();
13978 }
13979
13980 pub fn open_selected_filename(
13981 &mut self,
13982 _: &OpenSelectedFilename,
13983 window: &mut Window,
13984 cx: &mut Context<Self>,
13985 ) {
13986 let Some(workspace) = self.workspace() else {
13987 return;
13988 };
13989
13990 let position = self.selections.newest_anchor().head();
13991
13992 let Some((buffer, buffer_position)) =
13993 self.buffer.read(cx).text_anchor_for_position(position, cx)
13994 else {
13995 return;
13996 };
13997
13998 let project = self.project.clone();
13999
14000 cx.spawn_in(window, async move |_, cx| {
14001 let result = find_file(&buffer, project, buffer_position, cx).await;
14002
14003 if let Some((_, path)) = result {
14004 workspace
14005 .update_in(cx, |workspace, window, cx| {
14006 workspace.open_resolved_path(path, window, cx)
14007 })?
14008 .await?;
14009 }
14010 anyhow::Ok(())
14011 })
14012 .detach();
14013 }
14014
14015 pub(crate) fn navigate_to_hover_links(
14016 &mut self,
14017 kind: Option<GotoDefinitionKind>,
14018 mut definitions: Vec<HoverLink>,
14019 split: bool,
14020 window: &mut Window,
14021 cx: &mut Context<Editor>,
14022 ) -> Task<Result<Navigated>> {
14023 // If there is one definition, just open it directly
14024 if definitions.len() == 1 {
14025 let definition = definitions.pop().unwrap();
14026
14027 enum TargetTaskResult {
14028 Location(Option<Location>),
14029 AlreadyNavigated,
14030 }
14031
14032 let target_task = match definition {
14033 HoverLink::Text(link) => {
14034 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
14035 }
14036 HoverLink::InlayHint(lsp_location, server_id) => {
14037 let computation =
14038 self.compute_target_location(lsp_location, server_id, window, cx);
14039 cx.background_spawn(async move {
14040 let location = computation.await?;
14041 Ok(TargetTaskResult::Location(location))
14042 })
14043 }
14044 HoverLink::Url(url) => {
14045 cx.open_url(&url);
14046 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
14047 }
14048 HoverLink::File(path) => {
14049 if let Some(workspace) = self.workspace() {
14050 cx.spawn_in(window, async move |_, cx| {
14051 workspace
14052 .update_in(cx, |workspace, window, cx| {
14053 workspace.open_resolved_path(path, window, cx)
14054 })?
14055 .await
14056 .map(|_| TargetTaskResult::AlreadyNavigated)
14057 })
14058 } else {
14059 Task::ready(Ok(TargetTaskResult::Location(None)))
14060 }
14061 }
14062 };
14063 cx.spawn_in(window, async move |editor, cx| {
14064 let target = match target_task.await.context("target resolution task")? {
14065 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
14066 TargetTaskResult::Location(None) => return Ok(Navigated::No),
14067 TargetTaskResult::Location(Some(target)) => target,
14068 };
14069
14070 editor.update_in(cx, |editor, window, cx| {
14071 let Some(workspace) = editor.workspace() else {
14072 return Navigated::No;
14073 };
14074 let pane = workspace.read(cx).active_pane().clone();
14075
14076 let range = target.range.to_point(target.buffer.read(cx));
14077 let range = editor.range_for_match(&range);
14078 let range = collapse_multiline_range(range);
14079
14080 if !split
14081 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
14082 {
14083 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
14084 } else {
14085 window.defer(cx, move |window, cx| {
14086 let target_editor: Entity<Self> =
14087 workspace.update(cx, |workspace, cx| {
14088 let pane = if split {
14089 workspace.adjacent_pane(window, cx)
14090 } else {
14091 workspace.active_pane().clone()
14092 };
14093
14094 workspace.open_project_item(
14095 pane,
14096 target.buffer.clone(),
14097 true,
14098 true,
14099 window,
14100 cx,
14101 )
14102 });
14103 target_editor.update(cx, |target_editor, cx| {
14104 // When selecting a definition in a different buffer, disable the nav history
14105 // to avoid creating a history entry at the previous cursor location.
14106 pane.update(cx, |pane, _| pane.disable_history());
14107 target_editor.go_to_singleton_buffer_range(range, window, cx);
14108 pane.update(cx, |pane, _| pane.enable_history());
14109 });
14110 });
14111 }
14112 Navigated::Yes
14113 })
14114 })
14115 } else if !definitions.is_empty() {
14116 cx.spawn_in(window, async move |editor, cx| {
14117 let (title, location_tasks, workspace) = editor
14118 .update_in(cx, |editor, window, cx| {
14119 let tab_kind = match kind {
14120 Some(GotoDefinitionKind::Implementation) => "Implementations",
14121 _ => "Definitions",
14122 };
14123 let title = definitions
14124 .iter()
14125 .find_map(|definition| match definition {
14126 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
14127 let buffer = origin.buffer.read(cx);
14128 format!(
14129 "{} for {}",
14130 tab_kind,
14131 buffer
14132 .text_for_range(origin.range.clone())
14133 .collect::<String>()
14134 )
14135 }),
14136 HoverLink::InlayHint(_, _) => None,
14137 HoverLink::Url(_) => None,
14138 HoverLink::File(_) => None,
14139 })
14140 .unwrap_or(tab_kind.to_string());
14141 let location_tasks = definitions
14142 .into_iter()
14143 .map(|definition| match definition {
14144 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
14145 HoverLink::InlayHint(lsp_location, server_id) => editor
14146 .compute_target_location(lsp_location, server_id, window, cx),
14147 HoverLink::Url(_) => Task::ready(Ok(None)),
14148 HoverLink::File(_) => Task::ready(Ok(None)),
14149 })
14150 .collect::<Vec<_>>();
14151 (title, location_tasks, editor.workspace().clone())
14152 })
14153 .context("location tasks preparation")?;
14154
14155 let locations = future::join_all(location_tasks)
14156 .await
14157 .into_iter()
14158 .filter_map(|location| location.transpose())
14159 .collect::<Result<_>>()
14160 .context("location tasks")?;
14161
14162 let Some(workspace) = workspace else {
14163 return Ok(Navigated::No);
14164 };
14165 let opened = workspace
14166 .update_in(cx, |workspace, window, cx| {
14167 Self::open_locations_in_multibuffer(
14168 workspace,
14169 locations,
14170 title,
14171 split,
14172 MultibufferSelectionMode::First,
14173 window,
14174 cx,
14175 )
14176 })
14177 .ok();
14178
14179 anyhow::Ok(Navigated::from_bool(opened.is_some()))
14180 })
14181 } else {
14182 Task::ready(Ok(Navigated::No))
14183 }
14184 }
14185
14186 fn compute_target_location(
14187 &self,
14188 lsp_location: lsp::Location,
14189 server_id: LanguageServerId,
14190 window: &mut Window,
14191 cx: &mut Context<Self>,
14192 ) -> Task<anyhow::Result<Option<Location>>> {
14193 let Some(project) = self.project.clone() else {
14194 return Task::ready(Ok(None));
14195 };
14196
14197 cx.spawn_in(window, async move |editor, cx| {
14198 let location_task = editor.update(cx, |_, cx| {
14199 project.update(cx, |project, cx| {
14200 let language_server_name = project
14201 .language_server_statuses(cx)
14202 .find(|(id, _)| server_id == *id)
14203 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
14204 language_server_name.map(|language_server_name| {
14205 project.open_local_buffer_via_lsp(
14206 lsp_location.uri.clone(),
14207 server_id,
14208 language_server_name,
14209 cx,
14210 )
14211 })
14212 })
14213 })?;
14214 let location = match location_task {
14215 Some(task) => Some({
14216 let target_buffer_handle = task.await.context("open local buffer")?;
14217 let range = target_buffer_handle.update(cx, |target_buffer, _| {
14218 let target_start = target_buffer
14219 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
14220 let target_end = target_buffer
14221 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
14222 target_buffer.anchor_after(target_start)
14223 ..target_buffer.anchor_before(target_end)
14224 })?;
14225 Location {
14226 buffer: target_buffer_handle,
14227 range,
14228 }
14229 }),
14230 None => None,
14231 };
14232 Ok(location)
14233 })
14234 }
14235
14236 pub fn find_all_references(
14237 &mut self,
14238 _: &FindAllReferences,
14239 window: &mut Window,
14240 cx: &mut Context<Self>,
14241 ) -> Option<Task<Result<Navigated>>> {
14242 let selection = self.selections.newest::<usize>(cx);
14243 let multi_buffer = self.buffer.read(cx);
14244 let head = selection.head();
14245
14246 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14247 let head_anchor = multi_buffer_snapshot.anchor_at(
14248 head,
14249 if head < selection.tail() {
14250 Bias::Right
14251 } else {
14252 Bias::Left
14253 },
14254 );
14255
14256 match self
14257 .find_all_references_task_sources
14258 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14259 {
14260 Ok(_) => {
14261 log::info!(
14262 "Ignoring repeated FindAllReferences invocation with the position of already running task"
14263 );
14264 return None;
14265 }
14266 Err(i) => {
14267 self.find_all_references_task_sources.insert(i, head_anchor);
14268 }
14269 }
14270
14271 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
14272 let workspace = self.workspace()?;
14273 let project = workspace.read(cx).project().clone();
14274 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
14275 Some(cx.spawn_in(window, async move |editor, cx| {
14276 let _cleanup = cx.on_drop(&editor, move |editor, _| {
14277 if let Ok(i) = editor
14278 .find_all_references_task_sources
14279 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
14280 {
14281 editor.find_all_references_task_sources.remove(i);
14282 }
14283 });
14284
14285 let locations = references.await?;
14286 if locations.is_empty() {
14287 return anyhow::Ok(Navigated::No);
14288 }
14289
14290 workspace.update_in(cx, |workspace, window, cx| {
14291 let title = locations
14292 .first()
14293 .as_ref()
14294 .map(|location| {
14295 let buffer = location.buffer.read(cx);
14296 format!(
14297 "References to `{}`",
14298 buffer
14299 .text_for_range(location.range.clone())
14300 .collect::<String>()
14301 )
14302 })
14303 .unwrap();
14304 Self::open_locations_in_multibuffer(
14305 workspace,
14306 locations,
14307 title,
14308 false,
14309 MultibufferSelectionMode::First,
14310 window,
14311 cx,
14312 );
14313 Navigated::Yes
14314 })
14315 }))
14316 }
14317
14318 /// Opens a multibuffer with the given project locations in it
14319 pub fn open_locations_in_multibuffer(
14320 workspace: &mut Workspace,
14321 mut locations: Vec<Location>,
14322 title: String,
14323 split: bool,
14324 multibuffer_selection_mode: MultibufferSelectionMode,
14325 window: &mut Window,
14326 cx: &mut Context<Workspace>,
14327 ) {
14328 // If there are multiple definitions, open them in a multibuffer
14329 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
14330 let mut locations = locations.into_iter().peekable();
14331 let mut ranges: Vec<Range<Anchor>> = Vec::new();
14332 let capability = workspace.project().read(cx).capability();
14333
14334 let excerpt_buffer = cx.new(|cx| {
14335 let mut multibuffer = MultiBuffer::new(capability);
14336 while let Some(location) = locations.next() {
14337 let buffer = location.buffer.read(cx);
14338 let mut ranges_for_buffer = Vec::new();
14339 let range = location.range.to_point(buffer);
14340 ranges_for_buffer.push(range.clone());
14341
14342 while let Some(next_location) = locations.peek() {
14343 if next_location.buffer == location.buffer {
14344 ranges_for_buffer.push(next_location.range.to_point(buffer));
14345 locations.next();
14346 } else {
14347 break;
14348 }
14349 }
14350
14351 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14352 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14353 PathKey::for_buffer(&location.buffer, cx),
14354 location.buffer.clone(),
14355 ranges_for_buffer,
14356 DEFAULT_MULTIBUFFER_CONTEXT,
14357 cx,
14358 );
14359 ranges.extend(new_ranges)
14360 }
14361
14362 multibuffer.with_title(title)
14363 });
14364
14365 let editor = cx.new(|cx| {
14366 Editor::for_multibuffer(
14367 excerpt_buffer,
14368 Some(workspace.project().clone()),
14369 window,
14370 cx,
14371 )
14372 });
14373 editor.update(cx, |editor, cx| {
14374 match multibuffer_selection_mode {
14375 MultibufferSelectionMode::First => {
14376 if let Some(first_range) = ranges.first() {
14377 editor.change_selections(None, window, cx, |selections| {
14378 selections.clear_disjoint();
14379 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14380 });
14381 }
14382 editor.highlight_background::<Self>(
14383 &ranges,
14384 |theme| theme.editor_highlighted_line_background,
14385 cx,
14386 );
14387 }
14388 MultibufferSelectionMode::All => {
14389 editor.change_selections(None, window, cx, |selections| {
14390 selections.clear_disjoint();
14391 selections.select_anchor_ranges(ranges);
14392 });
14393 }
14394 }
14395 editor.register_buffers_with_language_servers(cx);
14396 });
14397
14398 let item = Box::new(editor);
14399 let item_id = item.item_id();
14400
14401 if split {
14402 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14403 } else {
14404 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14405 let (preview_item_id, preview_item_idx) =
14406 workspace.active_pane().update(cx, |pane, _| {
14407 (pane.preview_item_id(), pane.preview_item_idx())
14408 });
14409
14410 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14411
14412 if let Some(preview_item_id) = preview_item_id {
14413 workspace.active_pane().update(cx, |pane, cx| {
14414 pane.remove_item(preview_item_id, false, false, window, cx);
14415 });
14416 }
14417 } else {
14418 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14419 }
14420 }
14421 workspace.active_pane().update(cx, |pane, cx| {
14422 pane.set_preview_item_id(Some(item_id), cx);
14423 });
14424 }
14425
14426 pub fn rename(
14427 &mut self,
14428 _: &Rename,
14429 window: &mut Window,
14430 cx: &mut Context<Self>,
14431 ) -> Option<Task<Result<()>>> {
14432 use language::ToOffset as _;
14433
14434 let provider = self.semantics_provider.clone()?;
14435 let selection = self.selections.newest_anchor().clone();
14436 let (cursor_buffer, cursor_buffer_position) = self
14437 .buffer
14438 .read(cx)
14439 .text_anchor_for_position(selection.head(), cx)?;
14440 let (tail_buffer, cursor_buffer_position_end) = self
14441 .buffer
14442 .read(cx)
14443 .text_anchor_for_position(selection.tail(), cx)?;
14444 if tail_buffer != cursor_buffer {
14445 return None;
14446 }
14447
14448 let snapshot = cursor_buffer.read(cx).snapshot();
14449 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14450 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14451 let prepare_rename = provider
14452 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14453 .unwrap_or_else(|| Task::ready(Ok(None)));
14454 drop(snapshot);
14455
14456 Some(cx.spawn_in(window, async move |this, cx| {
14457 let rename_range = if let Some(range) = prepare_rename.await? {
14458 Some(range)
14459 } else {
14460 this.update(cx, |this, cx| {
14461 let buffer = this.buffer.read(cx).snapshot(cx);
14462 let mut buffer_highlights = this
14463 .document_highlights_for_position(selection.head(), &buffer)
14464 .filter(|highlight| {
14465 highlight.start.excerpt_id == selection.head().excerpt_id
14466 && highlight.end.excerpt_id == selection.head().excerpt_id
14467 });
14468 buffer_highlights
14469 .next()
14470 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14471 })?
14472 };
14473 if let Some(rename_range) = rename_range {
14474 this.update_in(cx, |this, window, cx| {
14475 let snapshot = cursor_buffer.read(cx).snapshot();
14476 let rename_buffer_range = rename_range.to_offset(&snapshot);
14477 let cursor_offset_in_rename_range =
14478 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14479 let cursor_offset_in_rename_range_end =
14480 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14481
14482 this.take_rename(false, window, cx);
14483 let buffer = this.buffer.read(cx).read(cx);
14484 let cursor_offset = selection.head().to_offset(&buffer);
14485 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14486 let rename_end = rename_start + rename_buffer_range.len();
14487 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14488 let mut old_highlight_id = None;
14489 let old_name: Arc<str> = buffer
14490 .chunks(rename_start..rename_end, true)
14491 .map(|chunk| {
14492 if old_highlight_id.is_none() {
14493 old_highlight_id = chunk.syntax_highlight_id;
14494 }
14495 chunk.text
14496 })
14497 .collect::<String>()
14498 .into();
14499
14500 drop(buffer);
14501
14502 // Position the selection in the rename editor so that it matches the current selection.
14503 this.show_local_selections = false;
14504 let rename_editor = cx.new(|cx| {
14505 let mut editor = Editor::single_line(window, cx);
14506 editor.buffer.update(cx, |buffer, cx| {
14507 buffer.edit([(0..0, old_name.clone())], None, cx)
14508 });
14509 let rename_selection_range = match cursor_offset_in_rename_range
14510 .cmp(&cursor_offset_in_rename_range_end)
14511 {
14512 Ordering::Equal => {
14513 editor.select_all(&SelectAll, window, cx);
14514 return editor;
14515 }
14516 Ordering::Less => {
14517 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14518 }
14519 Ordering::Greater => {
14520 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14521 }
14522 };
14523 if rename_selection_range.end > old_name.len() {
14524 editor.select_all(&SelectAll, window, cx);
14525 } else {
14526 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14527 s.select_ranges([rename_selection_range]);
14528 });
14529 }
14530 editor
14531 });
14532 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14533 if e == &EditorEvent::Focused {
14534 cx.emit(EditorEvent::FocusedIn)
14535 }
14536 })
14537 .detach();
14538
14539 let write_highlights =
14540 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14541 let read_highlights =
14542 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14543 let ranges = write_highlights
14544 .iter()
14545 .flat_map(|(_, ranges)| ranges.iter())
14546 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14547 .cloned()
14548 .collect();
14549
14550 this.highlight_text::<Rename>(
14551 ranges,
14552 HighlightStyle {
14553 fade_out: Some(0.6),
14554 ..Default::default()
14555 },
14556 cx,
14557 );
14558 let rename_focus_handle = rename_editor.focus_handle(cx);
14559 window.focus(&rename_focus_handle);
14560 let block_id = this.insert_blocks(
14561 [BlockProperties {
14562 style: BlockStyle::Flex,
14563 placement: BlockPlacement::Below(range.start),
14564 height: Some(1),
14565 render: Arc::new({
14566 let rename_editor = rename_editor.clone();
14567 move |cx: &mut BlockContext| {
14568 let mut text_style = cx.editor_style.text.clone();
14569 if let Some(highlight_style) = old_highlight_id
14570 .and_then(|h| h.style(&cx.editor_style.syntax))
14571 {
14572 text_style = text_style.highlight(highlight_style);
14573 }
14574 div()
14575 .block_mouse_down()
14576 .pl(cx.anchor_x)
14577 .child(EditorElement::new(
14578 &rename_editor,
14579 EditorStyle {
14580 background: cx.theme().system().transparent,
14581 local_player: cx.editor_style.local_player,
14582 text: text_style,
14583 scrollbar_width: cx.editor_style.scrollbar_width,
14584 syntax: cx.editor_style.syntax.clone(),
14585 status: cx.editor_style.status.clone(),
14586 inlay_hints_style: HighlightStyle {
14587 font_weight: Some(FontWeight::BOLD),
14588 ..make_inlay_hints_style(cx.app)
14589 },
14590 inline_completion_styles: make_suggestion_styles(
14591 cx.app,
14592 ),
14593 ..EditorStyle::default()
14594 },
14595 ))
14596 .into_any_element()
14597 }
14598 }),
14599 priority: 0,
14600 render_in_minimap: true,
14601 }],
14602 Some(Autoscroll::fit()),
14603 cx,
14604 )[0];
14605 this.pending_rename = Some(RenameState {
14606 range,
14607 old_name,
14608 editor: rename_editor,
14609 block_id,
14610 });
14611 })?;
14612 }
14613
14614 Ok(())
14615 }))
14616 }
14617
14618 pub fn confirm_rename(
14619 &mut self,
14620 _: &ConfirmRename,
14621 window: &mut Window,
14622 cx: &mut Context<Self>,
14623 ) -> Option<Task<Result<()>>> {
14624 let rename = self.take_rename(false, window, cx)?;
14625 let workspace = self.workspace()?.downgrade();
14626 let (buffer, start) = self
14627 .buffer
14628 .read(cx)
14629 .text_anchor_for_position(rename.range.start, cx)?;
14630 let (end_buffer, _) = self
14631 .buffer
14632 .read(cx)
14633 .text_anchor_for_position(rename.range.end, cx)?;
14634 if buffer != end_buffer {
14635 return None;
14636 }
14637
14638 let old_name = rename.old_name;
14639 let new_name = rename.editor.read(cx).text(cx);
14640
14641 let rename = self.semantics_provider.as_ref()?.perform_rename(
14642 &buffer,
14643 start,
14644 new_name.clone(),
14645 cx,
14646 )?;
14647
14648 Some(cx.spawn_in(window, async move |editor, cx| {
14649 let project_transaction = rename.await?;
14650 Self::open_project_transaction(
14651 &editor,
14652 workspace,
14653 project_transaction,
14654 format!("Rename: {} → {}", old_name, new_name),
14655 cx,
14656 )
14657 .await?;
14658
14659 editor.update(cx, |editor, cx| {
14660 editor.refresh_document_highlights(cx);
14661 })?;
14662 Ok(())
14663 }))
14664 }
14665
14666 fn take_rename(
14667 &mut self,
14668 moving_cursor: bool,
14669 window: &mut Window,
14670 cx: &mut Context<Self>,
14671 ) -> Option<RenameState> {
14672 let rename = self.pending_rename.take()?;
14673 if rename.editor.focus_handle(cx).is_focused(window) {
14674 window.focus(&self.focus_handle);
14675 }
14676
14677 self.remove_blocks(
14678 [rename.block_id].into_iter().collect(),
14679 Some(Autoscroll::fit()),
14680 cx,
14681 );
14682 self.clear_highlights::<Rename>(cx);
14683 self.show_local_selections = true;
14684
14685 if moving_cursor {
14686 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14687 editor.selections.newest::<usize>(cx).head()
14688 });
14689
14690 // Update the selection to match the position of the selection inside
14691 // the rename editor.
14692 let snapshot = self.buffer.read(cx).read(cx);
14693 let rename_range = rename.range.to_offset(&snapshot);
14694 let cursor_in_editor = snapshot
14695 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14696 .min(rename_range.end);
14697 drop(snapshot);
14698
14699 self.change_selections(None, window, cx, |s| {
14700 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14701 });
14702 } else {
14703 self.refresh_document_highlights(cx);
14704 }
14705
14706 Some(rename)
14707 }
14708
14709 pub fn pending_rename(&self) -> Option<&RenameState> {
14710 self.pending_rename.as_ref()
14711 }
14712
14713 fn format(
14714 &mut self,
14715 _: &Format,
14716 window: &mut Window,
14717 cx: &mut Context<Self>,
14718 ) -> Option<Task<Result<()>>> {
14719 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14720
14721 let project = match &self.project {
14722 Some(project) => project.clone(),
14723 None => return None,
14724 };
14725
14726 Some(self.perform_format(
14727 project,
14728 FormatTrigger::Manual,
14729 FormatTarget::Buffers,
14730 window,
14731 cx,
14732 ))
14733 }
14734
14735 fn format_selections(
14736 &mut self,
14737 _: &FormatSelections,
14738 window: &mut Window,
14739 cx: &mut Context<Self>,
14740 ) -> Option<Task<Result<()>>> {
14741 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14742
14743 let project = match &self.project {
14744 Some(project) => project.clone(),
14745 None => return None,
14746 };
14747
14748 let ranges = self
14749 .selections
14750 .all_adjusted(cx)
14751 .into_iter()
14752 .map(|selection| selection.range())
14753 .collect_vec();
14754
14755 Some(self.perform_format(
14756 project,
14757 FormatTrigger::Manual,
14758 FormatTarget::Ranges(ranges),
14759 window,
14760 cx,
14761 ))
14762 }
14763
14764 fn perform_format(
14765 &mut self,
14766 project: Entity<Project>,
14767 trigger: FormatTrigger,
14768 target: FormatTarget,
14769 window: &mut Window,
14770 cx: &mut Context<Self>,
14771 ) -> Task<Result<()>> {
14772 let buffer = self.buffer.clone();
14773 let (buffers, target) = match target {
14774 FormatTarget::Buffers => {
14775 let mut buffers = buffer.read(cx).all_buffers();
14776 if trigger == FormatTrigger::Save {
14777 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14778 }
14779 (buffers, LspFormatTarget::Buffers)
14780 }
14781 FormatTarget::Ranges(selection_ranges) => {
14782 let multi_buffer = buffer.read(cx);
14783 let snapshot = multi_buffer.read(cx);
14784 let mut buffers = HashSet::default();
14785 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14786 BTreeMap::new();
14787 for selection_range in selection_ranges {
14788 for (buffer, buffer_range, _) in
14789 snapshot.range_to_buffer_ranges(selection_range)
14790 {
14791 let buffer_id = buffer.remote_id();
14792 let start = buffer.anchor_before(buffer_range.start);
14793 let end = buffer.anchor_after(buffer_range.end);
14794 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14795 buffer_id_to_ranges
14796 .entry(buffer_id)
14797 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14798 .or_insert_with(|| vec![start..end]);
14799 }
14800 }
14801 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14802 }
14803 };
14804
14805 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14806 let selections_prev = transaction_id_prev
14807 .and_then(|transaction_id_prev| {
14808 // default to selections as they were after the last edit, if we have them,
14809 // instead of how they are now.
14810 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14811 // will take you back to where you made the last edit, instead of staying where you scrolled
14812 self.selection_history
14813 .transaction(transaction_id_prev)
14814 .map(|t| t.0.clone())
14815 })
14816 .unwrap_or_else(|| {
14817 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14818 self.selections.disjoint_anchors()
14819 });
14820
14821 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14822 let format = project.update(cx, |project, cx| {
14823 project.format(buffers, target, true, trigger, cx)
14824 });
14825
14826 cx.spawn_in(window, async move |editor, cx| {
14827 let transaction = futures::select_biased! {
14828 transaction = format.log_err().fuse() => transaction,
14829 () = timeout => {
14830 log::warn!("timed out waiting for formatting");
14831 None
14832 }
14833 };
14834
14835 buffer
14836 .update(cx, |buffer, cx| {
14837 if let Some(transaction) = transaction {
14838 if !buffer.is_singleton() {
14839 buffer.push_transaction(&transaction.0, cx);
14840 }
14841 }
14842 cx.notify();
14843 })
14844 .ok();
14845
14846 if let Some(transaction_id_now) =
14847 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14848 {
14849 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14850 if has_new_transaction {
14851 _ = editor.update(cx, |editor, _| {
14852 editor
14853 .selection_history
14854 .insert_transaction(transaction_id_now, selections_prev);
14855 });
14856 }
14857 }
14858
14859 Ok(())
14860 })
14861 }
14862
14863 fn organize_imports(
14864 &mut self,
14865 _: &OrganizeImports,
14866 window: &mut Window,
14867 cx: &mut Context<Self>,
14868 ) -> Option<Task<Result<()>>> {
14869 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14870 let project = match &self.project {
14871 Some(project) => project.clone(),
14872 None => return None,
14873 };
14874 Some(self.perform_code_action_kind(
14875 project,
14876 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14877 window,
14878 cx,
14879 ))
14880 }
14881
14882 fn perform_code_action_kind(
14883 &mut self,
14884 project: Entity<Project>,
14885 kind: CodeActionKind,
14886 window: &mut Window,
14887 cx: &mut Context<Self>,
14888 ) -> Task<Result<()>> {
14889 let buffer = self.buffer.clone();
14890 let buffers = buffer.read(cx).all_buffers();
14891 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14892 let apply_action = project.update(cx, |project, cx| {
14893 project.apply_code_action_kind(buffers, kind, true, cx)
14894 });
14895 cx.spawn_in(window, async move |_, cx| {
14896 let transaction = futures::select_biased! {
14897 () = timeout => {
14898 log::warn!("timed out waiting for executing code action");
14899 None
14900 }
14901 transaction = apply_action.log_err().fuse() => transaction,
14902 };
14903 buffer
14904 .update(cx, |buffer, cx| {
14905 // check if we need this
14906 if let Some(transaction) = transaction {
14907 if !buffer.is_singleton() {
14908 buffer.push_transaction(&transaction.0, cx);
14909 }
14910 }
14911 cx.notify();
14912 })
14913 .ok();
14914 Ok(())
14915 })
14916 }
14917
14918 fn restart_language_server(
14919 &mut self,
14920 _: &RestartLanguageServer,
14921 _: &mut Window,
14922 cx: &mut Context<Self>,
14923 ) {
14924 if let Some(project) = self.project.clone() {
14925 self.buffer.update(cx, |multi_buffer, cx| {
14926 project.update(cx, |project, cx| {
14927 project.restart_language_servers_for_buffers(
14928 multi_buffer.all_buffers().into_iter().collect(),
14929 cx,
14930 );
14931 });
14932 })
14933 }
14934 }
14935
14936 fn stop_language_server(
14937 &mut self,
14938 _: &StopLanguageServer,
14939 _: &mut Window,
14940 cx: &mut Context<Self>,
14941 ) {
14942 if let Some(project) = self.project.clone() {
14943 self.buffer.update(cx, |multi_buffer, cx| {
14944 project.update(cx, |project, cx| {
14945 project.stop_language_servers_for_buffers(
14946 multi_buffer.all_buffers().into_iter().collect(),
14947 cx,
14948 );
14949 cx.emit(project::Event::RefreshInlayHints);
14950 });
14951 });
14952 }
14953 }
14954
14955 fn cancel_language_server_work(
14956 workspace: &mut Workspace,
14957 _: &actions::CancelLanguageServerWork,
14958 _: &mut Window,
14959 cx: &mut Context<Workspace>,
14960 ) {
14961 let project = workspace.project();
14962 let buffers = workspace
14963 .active_item(cx)
14964 .and_then(|item| item.act_as::<Editor>(cx))
14965 .map_or(HashSet::default(), |editor| {
14966 editor.read(cx).buffer.read(cx).all_buffers()
14967 });
14968 project.update(cx, |project, cx| {
14969 project.cancel_language_server_work_for_buffers(buffers, cx);
14970 });
14971 }
14972
14973 fn show_character_palette(
14974 &mut self,
14975 _: &ShowCharacterPalette,
14976 window: &mut Window,
14977 _: &mut Context<Self>,
14978 ) {
14979 window.show_character_palette();
14980 }
14981
14982 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14983 if self.mode.is_minimap() {
14984 return;
14985 }
14986
14987 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14988 let buffer = self.buffer.read(cx).snapshot(cx);
14989 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14990 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14991 let is_valid = buffer
14992 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14993 .any(|entry| {
14994 entry.diagnostic.is_primary
14995 && !entry.range.is_empty()
14996 && entry.range.start == primary_range_start
14997 && entry.diagnostic.message == active_diagnostics.active_message
14998 });
14999
15000 if !is_valid {
15001 self.dismiss_diagnostics(cx);
15002 }
15003 }
15004 }
15005
15006 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
15007 match &self.active_diagnostics {
15008 ActiveDiagnostic::Group(group) => Some(group),
15009 _ => None,
15010 }
15011 }
15012
15013 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
15014 self.dismiss_diagnostics(cx);
15015 self.active_diagnostics = ActiveDiagnostic::All;
15016 }
15017
15018 fn activate_diagnostics(
15019 &mut self,
15020 buffer_id: BufferId,
15021 diagnostic: DiagnosticEntry<usize>,
15022 window: &mut Window,
15023 cx: &mut Context<Self>,
15024 ) {
15025 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15026 return;
15027 }
15028 self.dismiss_diagnostics(cx);
15029 let snapshot = self.snapshot(window, cx);
15030 let buffer = self.buffer.read(cx).snapshot(cx);
15031 let Some(renderer) = GlobalDiagnosticRenderer::global(cx) else {
15032 return;
15033 };
15034
15035 let diagnostic_group = buffer
15036 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
15037 .collect::<Vec<_>>();
15038
15039 let blocks =
15040 renderer.render_group(diagnostic_group, buffer_id, snapshot, cx.weak_entity(), cx);
15041
15042 let blocks = self.display_map.update(cx, |display_map, cx| {
15043 display_map.insert_blocks(blocks, cx).into_iter().collect()
15044 });
15045 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
15046 active_range: buffer.anchor_before(diagnostic.range.start)
15047 ..buffer.anchor_after(diagnostic.range.end),
15048 active_message: diagnostic.diagnostic.message.clone(),
15049 group_id: diagnostic.diagnostic.group_id,
15050 blocks,
15051 });
15052 cx.notify();
15053 }
15054
15055 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
15056 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
15057 return;
15058 };
15059
15060 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
15061 if let ActiveDiagnostic::Group(group) = prev {
15062 self.display_map.update(cx, |display_map, cx| {
15063 display_map.remove_blocks(group.blocks, cx);
15064 });
15065 cx.notify();
15066 }
15067 }
15068
15069 /// Disable inline diagnostics rendering for this editor.
15070 pub fn disable_inline_diagnostics(&mut self) {
15071 self.inline_diagnostics_enabled = false;
15072 self.inline_diagnostics_update = Task::ready(());
15073 self.inline_diagnostics.clear();
15074 }
15075
15076 pub fn inline_diagnostics_enabled(&self) -> bool {
15077 self.inline_diagnostics_enabled
15078 }
15079
15080 pub fn show_inline_diagnostics(&self) -> bool {
15081 self.show_inline_diagnostics
15082 }
15083
15084 pub fn toggle_inline_diagnostics(
15085 &mut self,
15086 _: &ToggleInlineDiagnostics,
15087 window: &mut Window,
15088 cx: &mut Context<Editor>,
15089 ) {
15090 self.show_inline_diagnostics = !self.show_inline_diagnostics;
15091 self.refresh_inline_diagnostics(false, window, cx);
15092 }
15093
15094 pub fn toggle_minimap(
15095 &mut self,
15096 _: &ToggleMinimap,
15097 window: &mut Window,
15098 cx: &mut Context<Editor>,
15099 ) {
15100 if self.supports_minimap() {
15101 self.set_show_minimap(!self.show_minimap, window, cx);
15102 }
15103 }
15104
15105 fn refresh_inline_diagnostics(
15106 &mut self,
15107 debounce: bool,
15108 window: &mut Window,
15109 cx: &mut Context<Self>,
15110 ) {
15111 if self.mode.is_minimap()
15112 || !self.inline_diagnostics_enabled
15113 || !self.show_inline_diagnostics
15114 {
15115 self.inline_diagnostics_update = Task::ready(());
15116 self.inline_diagnostics.clear();
15117 return;
15118 }
15119
15120 let debounce_ms = ProjectSettings::get_global(cx)
15121 .diagnostics
15122 .inline
15123 .update_debounce_ms;
15124 let debounce = if debounce && debounce_ms > 0 {
15125 Some(Duration::from_millis(debounce_ms))
15126 } else {
15127 None
15128 };
15129 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
15130 let editor = editor.upgrade().unwrap();
15131
15132 if let Some(debounce) = debounce {
15133 cx.background_executor().timer(debounce).await;
15134 }
15135 let Some(snapshot) = editor
15136 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
15137 .ok()
15138 else {
15139 return;
15140 };
15141
15142 let new_inline_diagnostics = cx
15143 .background_spawn(async move {
15144 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
15145 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
15146 let message = diagnostic_entry
15147 .diagnostic
15148 .message
15149 .split_once('\n')
15150 .map(|(line, _)| line)
15151 .map(SharedString::new)
15152 .unwrap_or_else(|| {
15153 SharedString::from(diagnostic_entry.diagnostic.message)
15154 });
15155 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
15156 let (Ok(i) | Err(i)) = inline_diagnostics
15157 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
15158 inline_diagnostics.insert(
15159 i,
15160 (
15161 start_anchor,
15162 InlineDiagnostic {
15163 message,
15164 group_id: diagnostic_entry.diagnostic.group_id,
15165 start: diagnostic_entry.range.start.to_point(&snapshot),
15166 is_primary: diagnostic_entry.diagnostic.is_primary,
15167 severity: diagnostic_entry.diagnostic.severity,
15168 },
15169 ),
15170 );
15171 }
15172 inline_diagnostics
15173 })
15174 .await;
15175
15176 editor
15177 .update(cx, |editor, cx| {
15178 editor.inline_diagnostics = new_inline_diagnostics;
15179 cx.notify();
15180 })
15181 .ok();
15182 });
15183 }
15184
15185 pub fn set_selections_from_remote(
15186 &mut self,
15187 selections: Vec<Selection<Anchor>>,
15188 pending_selection: Option<Selection<Anchor>>,
15189 window: &mut Window,
15190 cx: &mut Context<Self>,
15191 ) {
15192 let old_cursor_position = self.selections.newest_anchor().head();
15193 self.selections.change_with(cx, |s| {
15194 s.select_anchors(selections);
15195 if let Some(pending_selection) = pending_selection {
15196 s.set_pending(pending_selection, SelectMode::Character);
15197 } else {
15198 s.clear_pending();
15199 }
15200 });
15201 self.selections_did_change(false, &old_cursor_position, true, window, cx);
15202 }
15203
15204 fn push_to_selection_history(&mut self) {
15205 self.selection_history.push(SelectionHistoryEntry {
15206 selections: self.selections.disjoint_anchors(),
15207 select_next_state: self.select_next_state.clone(),
15208 select_prev_state: self.select_prev_state.clone(),
15209 add_selections_state: self.add_selections_state.clone(),
15210 });
15211 }
15212
15213 pub fn transact(
15214 &mut self,
15215 window: &mut Window,
15216 cx: &mut Context<Self>,
15217 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
15218 ) -> Option<TransactionId> {
15219 self.start_transaction_at(Instant::now(), window, cx);
15220 update(self, window, cx);
15221 self.end_transaction_at(Instant::now(), cx)
15222 }
15223
15224 pub fn start_transaction_at(
15225 &mut self,
15226 now: Instant,
15227 window: &mut Window,
15228 cx: &mut Context<Self>,
15229 ) {
15230 self.end_selection(window, cx);
15231 if let Some(tx_id) = self
15232 .buffer
15233 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
15234 {
15235 self.selection_history
15236 .insert_transaction(tx_id, self.selections.disjoint_anchors());
15237 cx.emit(EditorEvent::TransactionBegun {
15238 transaction_id: tx_id,
15239 })
15240 }
15241 }
15242
15243 pub fn end_transaction_at(
15244 &mut self,
15245 now: Instant,
15246 cx: &mut Context<Self>,
15247 ) -> Option<TransactionId> {
15248 if let Some(transaction_id) = self
15249 .buffer
15250 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
15251 {
15252 if let Some((_, end_selections)) =
15253 self.selection_history.transaction_mut(transaction_id)
15254 {
15255 *end_selections = Some(self.selections.disjoint_anchors());
15256 } else {
15257 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
15258 }
15259
15260 cx.emit(EditorEvent::Edited { transaction_id });
15261 Some(transaction_id)
15262 } else {
15263 None
15264 }
15265 }
15266
15267 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
15268 if self.selection_mark_mode {
15269 self.change_selections(None, window, cx, |s| {
15270 s.move_with(|_, sel| {
15271 sel.collapse_to(sel.head(), SelectionGoal::None);
15272 });
15273 })
15274 }
15275 self.selection_mark_mode = true;
15276 cx.notify();
15277 }
15278
15279 pub fn swap_selection_ends(
15280 &mut self,
15281 _: &actions::SwapSelectionEnds,
15282 window: &mut Window,
15283 cx: &mut Context<Self>,
15284 ) {
15285 self.change_selections(None, window, cx, |s| {
15286 s.move_with(|_, sel| {
15287 if sel.start != sel.end {
15288 sel.reversed = !sel.reversed
15289 }
15290 });
15291 });
15292 self.request_autoscroll(Autoscroll::newest(), cx);
15293 cx.notify();
15294 }
15295
15296 pub fn toggle_fold(
15297 &mut self,
15298 _: &actions::ToggleFold,
15299 window: &mut Window,
15300 cx: &mut Context<Self>,
15301 ) {
15302 if self.is_singleton(cx) {
15303 let selection = self.selections.newest::<Point>(cx);
15304
15305 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15306 let range = if selection.is_empty() {
15307 let point = selection.head().to_display_point(&display_map);
15308 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15309 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15310 .to_point(&display_map);
15311 start..end
15312 } else {
15313 selection.range()
15314 };
15315 if display_map.folds_in_range(range).next().is_some() {
15316 self.unfold_lines(&Default::default(), window, cx)
15317 } else {
15318 self.fold(&Default::default(), window, cx)
15319 }
15320 } else {
15321 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15322 let buffer_ids: HashSet<_> = self
15323 .selections
15324 .disjoint_anchor_ranges()
15325 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15326 .collect();
15327
15328 let should_unfold = buffer_ids
15329 .iter()
15330 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
15331
15332 for buffer_id in buffer_ids {
15333 if should_unfold {
15334 self.unfold_buffer(buffer_id, cx);
15335 } else {
15336 self.fold_buffer(buffer_id, cx);
15337 }
15338 }
15339 }
15340 }
15341
15342 pub fn toggle_fold_recursive(
15343 &mut self,
15344 _: &actions::ToggleFoldRecursive,
15345 window: &mut Window,
15346 cx: &mut Context<Self>,
15347 ) {
15348 let selection = self.selections.newest::<Point>(cx);
15349
15350 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15351 let range = if selection.is_empty() {
15352 let point = selection.head().to_display_point(&display_map);
15353 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15354 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15355 .to_point(&display_map);
15356 start..end
15357 } else {
15358 selection.range()
15359 };
15360 if display_map.folds_in_range(range).next().is_some() {
15361 self.unfold_recursive(&Default::default(), window, cx)
15362 } else {
15363 self.fold_recursive(&Default::default(), window, cx)
15364 }
15365 }
15366
15367 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15368 if self.is_singleton(cx) {
15369 let mut to_fold = Vec::new();
15370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15371 let selections = self.selections.all_adjusted(cx);
15372
15373 for selection in selections {
15374 let range = selection.range().sorted();
15375 let buffer_start_row = range.start.row;
15376
15377 if range.start.row != range.end.row {
15378 let mut found = false;
15379 let mut row = range.start.row;
15380 while row <= range.end.row {
15381 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15382 {
15383 found = true;
15384 row = crease.range().end.row + 1;
15385 to_fold.push(crease);
15386 } else {
15387 row += 1
15388 }
15389 }
15390 if found {
15391 continue;
15392 }
15393 }
15394
15395 for row in (0..=range.start.row).rev() {
15396 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15397 if crease.range().end.row >= buffer_start_row {
15398 to_fold.push(crease);
15399 if row <= range.start.row {
15400 break;
15401 }
15402 }
15403 }
15404 }
15405 }
15406
15407 self.fold_creases(to_fold, true, window, cx);
15408 } else {
15409 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15410 let buffer_ids = self
15411 .selections
15412 .disjoint_anchor_ranges()
15413 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15414 .collect::<HashSet<_>>();
15415 for buffer_id in buffer_ids {
15416 self.fold_buffer(buffer_id, cx);
15417 }
15418 }
15419 }
15420
15421 fn fold_at_level(
15422 &mut self,
15423 fold_at: &FoldAtLevel,
15424 window: &mut Window,
15425 cx: &mut Context<Self>,
15426 ) {
15427 if !self.buffer.read(cx).is_singleton() {
15428 return;
15429 }
15430
15431 let fold_at_level = fold_at.0;
15432 let snapshot = self.buffer.read(cx).snapshot(cx);
15433 let mut to_fold = Vec::new();
15434 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15435
15436 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15437 while start_row < end_row {
15438 match self
15439 .snapshot(window, cx)
15440 .crease_for_buffer_row(MultiBufferRow(start_row))
15441 {
15442 Some(crease) => {
15443 let nested_start_row = crease.range().start.row + 1;
15444 let nested_end_row = crease.range().end.row;
15445
15446 if current_level < fold_at_level {
15447 stack.push((nested_start_row, nested_end_row, current_level + 1));
15448 } else if current_level == fold_at_level {
15449 to_fold.push(crease);
15450 }
15451
15452 start_row = nested_end_row + 1;
15453 }
15454 None => start_row += 1,
15455 }
15456 }
15457 }
15458
15459 self.fold_creases(to_fold, true, window, cx);
15460 }
15461
15462 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15463 if self.buffer.read(cx).is_singleton() {
15464 let mut fold_ranges = Vec::new();
15465 let snapshot = self.buffer.read(cx).snapshot(cx);
15466
15467 for row in 0..snapshot.max_row().0 {
15468 if let Some(foldable_range) = self
15469 .snapshot(window, cx)
15470 .crease_for_buffer_row(MultiBufferRow(row))
15471 {
15472 fold_ranges.push(foldable_range);
15473 }
15474 }
15475
15476 self.fold_creases(fold_ranges, true, window, cx);
15477 } else {
15478 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15479 editor
15480 .update_in(cx, |editor, _, cx| {
15481 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15482 editor.fold_buffer(buffer_id, cx);
15483 }
15484 })
15485 .ok();
15486 });
15487 }
15488 }
15489
15490 pub fn fold_function_bodies(
15491 &mut self,
15492 _: &actions::FoldFunctionBodies,
15493 window: &mut Window,
15494 cx: &mut Context<Self>,
15495 ) {
15496 let snapshot = self.buffer.read(cx).snapshot(cx);
15497
15498 let ranges = snapshot
15499 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15500 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15501 .collect::<Vec<_>>();
15502
15503 let creases = ranges
15504 .into_iter()
15505 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15506 .collect();
15507
15508 self.fold_creases(creases, true, window, cx);
15509 }
15510
15511 pub fn fold_recursive(
15512 &mut self,
15513 _: &actions::FoldRecursive,
15514 window: &mut Window,
15515 cx: &mut Context<Self>,
15516 ) {
15517 let mut to_fold = Vec::new();
15518 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15519 let selections = self.selections.all_adjusted(cx);
15520
15521 for selection in selections {
15522 let range = selection.range().sorted();
15523 let buffer_start_row = range.start.row;
15524
15525 if range.start.row != range.end.row {
15526 let mut found = false;
15527 for row in range.start.row..=range.end.row {
15528 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15529 found = true;
15530 to_fold.push(crease);
15531 }
15532 }
15533 if found {
15534 continue;
15535 }
15536 }
15537
15538 for row in (0..=range.start.row).rev() {
15539 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15540 if crease.range().end.row >= buffer_start_row {
15541 to_fold.push(crease);
15542 } else {
15543 break;
15544 }
15545 }
15546 }
15547 }
15548
15549 self.fold_creases(to_fold, true, window, cx);
15550 }
15551
15552 pub fn fold_at(
15553 &mut self,
15554 buffer_row: MultiBufferRow,
15555 window: &mut Window,
15556 cx: &mut Context<Self>,
15557 ) {
15558 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15559
15560 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15561 let autoscroll = self
15562 .selections
15563 .all::<Point>(cx)
15564 .iter()
15565 .any(|selection| crease.range().overlaps(&selection.range()));
15566
15567 self.fold_creases(vec![crease], autoscroll, window, cx);
15568 }
15569 }
15570
15571 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15572 if self.is_singleton(cx) {
15573 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15574 let buffer = &display_map.buffer_snapshot;
15575 let selections = self.selections.all::<Point>(cx);
15576 let ranges = selections
15577 .iter()
15578 .map(|s| {
15579 let range = s.display_range(&display_map).sorted();
15580 let mut start = range.start.to_point(&display_map);
15581 let mut end = range.end.to_point(&display_map);
15582 start.column = 0;
15583 end.column = buffer.line_len(MultiBufferRow(end.row));
15584 start..end
15585 })
15586 .collect::<Vec<_>>();
15587
15588 self.unfold_ranges(&ranges, true, true, cx);
15589 } else {
15590 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15591 let buffer_ids = self
15592 .selections
15593 .disjoint_anchor_ranges()
15594 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15595 .collect::<HashSet<_>>();
15596 for buffer_id in buffer_ids {
15597 self.unfold_buffer(buffer_id, cx);
15598 }
15599 }
15600 }
15601
15602 pub fn unfold_recursive(
15603 &mut self,
15604 _: &UnfoldRecursive,
15605 _window: &mut Window,
15606 cx: &mut Context<Self>,
15607 ) {
15608 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15609 let selections = self.selections.all::<Point>(cx);
15610 let ranges = selections
15611 .iter()
15612 .map(|s| {
15613 let mut range = s.display_range(&display_map).sorted();
15614 *range.start.column_mut() = 0;
15615 *range.end.column_mut() = display_map.line_len(range.end.row());
15616 let start = range.start.to_point(&display_map);
15617 let end = range.end.to_point(&display_map);
15618 start..end
15619 })
15620 .collect::<Vec<_>>();
15621
15622 self.unfold_ranges(&ranges, true, true, cx);
15623 }
15624
15625 pub fn unfold_at(
15626 &mut self,
15627 buffer_row: MultiBufferRow,
15628 _window: &mut Window,
15629 cx: &mut Context<Self>,
15630 ) {
15631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15632
15633 let intersection_range = Point::new(buffer_row.0, 0)
15634 ..Point::new(
15635 buffer_row.0,
15636 display_map.buffer_snapshot.line_len(buffer_row),
15637 );
15638
15639 let autoscroll = self
15640 .selections
15641 .all::<Point>(cx)
15642 .iter()
15643 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15644
15645 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15646 }
15647
15648 pub fn unfold_all(
15649 &mut self,
15650 _: &actions::UnfoldAll,
15651 _window: &mut Window,
15652 cx: &mut Context<Self>,
15653 ) {
15654 if self.buffer.read(cx).is_singleton() {
15655 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15656 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15657 } else {
15658 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15659 editor
15660 .update(cx, |editor, cx| {
15661 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15662 editor.unfold_buffer(buffer_id, cx);
15663 }
15664 })
15665 .ok();
15666 });
15667 }
15668 }
15669
15670 pub fn fold_selected_ranges(
15671 &mut self,
15672 _: &FoldSelectedRanges,
15673 window: &mut Window,
15674 cx: &mut Context<Self>,
15675 ) {
15676 let selections = self.selections.all_adjusted(cx);
15677 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15678 let ranges = selections
15679 .into_iter()
15680 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15681 .collect::<Vec<_>>();
15682 self.fold_creases(ranges, true, window, cx);
15683 }
15684
15685 pub fn fold_ranges<T: ToOffset + Clone>(
15686 &mut self,
15687 ranges: Vec<Range<T>>,
15688 auto_scroll: bool,
15689 window: &mut Window,
15690 cx: &mut Context<Self>,
15691 ) {
15692 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15693 let ranges = ranges
15694 .into_iter()
15695 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15696 .collect::<Vec<_>>();
15697 self.fold_creases(ranges, auto_scroll, window, cx);
15698 }
15699
15700 pub fn fold_creases<T: ToOffset + Clone>(
15701 &mut self,
15702 creases: Vec<Crease<T>>,
15703 auto_scroll: bool,
15704 _window: &mut Window,
15705 cx: &mut Context<Self>,
15706 ) {
15707 if creases.is_empty() {
15708 return;
15709 }
15710
15711 let mut buffers_affected = HashSet::default();
15712 let multi_buffer = self.buffer().read(cx);
15713 for crease in &creases {
15714 if let Some((_, buffer, _)) =
15715 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15716 {
15717 buffers_affected.insert(buffer.read(cx).remote_id());
15718 };
15719 }
15720
15721 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15722
15723 if auto_scroll {
15724 self.request_autoscroll(Autoscroll::fit(), cx);
15725 }
15726
15727 cx.notify();
15728
15729 self.scrollbar_marker_state.dirty = true;
15730 self.folds_did_change(cx);
15731 }
15732
15733 /// Removes any folds whose ranges intersect any of the given ranges.
15734 pub fn unfold_ranges<T: ToOffset + Clone>(
15735 &mut self,
15736 ranges: &[Range<T>],
15737 inclusive: bool,
15738 auto_scroll: bool,
15739 cx: &mut Context<Self>,
15740 ) {
15741 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15742 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15743 });
15744 self.folds_did_change(cx);
15745 }
15746
15747 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15748 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15749 return;
15750 }
15751 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15752 self.display_map.update(cx, |display_map, cx| {
15753 display_map.fold_buffers([buffer_id], cx)
15754 });
15755 cx.emit(EditorEvent::BufferFoldToggled {
15756 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15757 folded: true,
15758 });
15759 cx.notify();
15760 }
15761
15762 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15763 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15764 return;
15765 }
15766 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15767 self.display_map.update(cx, |display_map, cx| {
15768 display_map.unfold_buffers([buffer_id], cx);
15769 });
15770 cx.emit(EditorEvent::BufferFoldToggled {
15771 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15772 folded: false,
15773 });
15774 cx.notify();
15775 }
15776
15777 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15778 self.display_map.read(cx).is_buffer_folded(buffer)
15779 }
15780
15781 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15782 self.display_map.read(cx).folded_buffers()
15783 }
15784
15785 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15786 self.display_map.update(cx, |display_map, cx| {
15787 display_map.disable_header_for_buffer(buffer_id, cx);
15788 });
15789 cx.notify();
15790 }
15791
15792 /// Removes any folds with the given ranges.
15793 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15794 &mut self,
15795 ranges: &[Range<T>],
15796 type_id: TypeId,
15797 auto_scroll: bool,
15798 cx: &mut Context<Self>,
15799 ) {
15800 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15801 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15802 });
15803 self.folds_did_change(cx);
15804 }
15805
15806 fn remove_folds_with<T: ToOffset + Clone>(
15807 &mut self,
15808 ranges: &[Range<T>],
15809 auto_scroll: bool,
15810 cx: &mut Context<Self>,
15811 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15812 ) {
15813 if ranges.is_empty() {
15814 return;
15815 }
15816
15817 let mut buffers_affected = HashSet::default();
15818 let multi_buffer = self.buffer().read(cx);
15819 for range in ranges {
15820 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15821 buffers_affected.insert(buffer.read(cx).remote_id());
15822 };
15823 }
15824
15825 self.display_map.update(cx, update);
15826
15827 if auto_scroll {
15828 self.request_autoscroll(Autoscroll::fit(), cx);
15829 }
15830
15831 cx.notify();
15832 self.scrollbar_marker_state.dirty = true;
15833 self.active_indent_guides_state.dirty = true;
15834 }
15835
15836 pub fn update_fold_widths(
15837 &mut self,
15838 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15839 cx: &mut Context<Self>,
15840 ) -> bool {
15841 self.display_map
15842 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15843 }
15844
15845 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15846 self.display_map.read(cx).fold_placeholder.clone()
15847 }
15848
15849 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15850 self.buffer.update(cx, |buffer, cx| {
15851 buffer.set_all_diff_hunks_expanded(cx);
15852 });
15853 }
15854
15855 pub fn expand_all_diff_hunks(
15856 &mut self,
15857 _: &ExpandAllDiffHunks,
15858 _window: &mut Window,
15859 cx: &mut Context<Self>,
15860 ) {
15861 self.buffer.update(cx, |buffer, cx| {
15862 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15863 });
15864 }
15865
15866 pub fn toggle_selected_diff_hunks(
15867 &mut self,
15868 _: &ToggleSelectedDiffHunks,
15869 _window: &mut Window,
15870 cx: &mut Context<Self>,
15871 ) {
15872 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15873 self.toggle_diff_hunks_in_ranges(ranges, cx);
15874 }
15875
15876 pub fn diff_hunks_in_ranges<'a>(
15877 &'a self,
15878 ranges: &'a [Range<Anchor>],
15879 buffer: &'a MultiBufferSnapshot,
15880 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15881 ranges.iter().flat_map(move |range| {
15882 let end_excerpt_id = range.end.excerpt_id;
15883 let range = range.to_point(buffer);
15884 let mut peek_end = range.end;
15885 if range.end.row < buffer.max_row().0 {
15886 peek_end = Point::new(range.end.row + 1, 0);
15887 }
15888 buffer
15889 .diff_hunks_in_range(range.start..peek_end)
15890 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15891 })
15892 }
15893
15894 pub fn has_stageable_diff_hunks_in_ranges(
15895 &self,
15896 ranges: &[Range<Anchor>],
15897 snapshot: &MultiBufferSnapshot,
15898 ) -> bool {
15899 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15900 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15901 }
15902
15903 pub fn toggle_staged_selected_diff_hunks(
15904 &mut self,
15905 _: &::git::ToggleStaged,
15906 _: &mut Window,
15907 cx: &mut Context<Self>,
15908 ) {
15909 let snapshot = self.buffer.read(cx).snapshot(cx);
15910 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15911 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15912 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15913 }
15914
15915 pub fn set_render_diff_hunk_controls(
15916 &mut self,
15917 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15918 cx: &mut Context<Self>,
15919 ) {
15920 self.render_diff_hunk_controls = render_diff_hunk_controls;
15921 cx.notify();
15922 }
15923
15924 pub fn stage_and_next(
15925 &mut self,
15926 _: &::git::StageAndNext,
15927 window: &mut Window,
15928 cx: &mut Context<Self>,
15929 ) {
15930 self.do_stage_or_unstage_and_next(true, window, cx);
15931 }
15932
15933 pub fn unstage_and_next(
15934 &mut self,
15935 _: &::git::UnstageAndNext,
15936 window: &mut Window,
15937 cx: &mut Context<Self>,
15938 ) {
15939 self.do_stage_or_unstage_and_next(false, window, cx);
15940 }
15941
15942 pub fn stage_or_unstage_diff_hunks(
15943 &mut self,
15944 stage: bool,
15945 ranges: Vec<Range<Anchor>>,
15946 cx: &mut Context<Self>,
15947 ) {
15948 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15949 cx.spawn(async move |this, cx| {
15950 task.await?;
15951 this.update(cx, |this, cx| {
15952 let snapshot = this.buffer.read(cx).snapshot(cx);
15953 let chunk_by = this
15954 .diff_hunks_in_ranges(&ranges, &snapshot)
15955 .chunk_by(|hunk| hunk.buffer_id);
15956 for (buffer_id, hunks) in &chunk_by {
15957 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15958 }
15959 })
15960 })
15961 .detach_and_log_err(cx);
15962 }
15963
15964 fn save_buffers_for_ranges_if_needed(
15965 &mut self,
15966 ranges: &[Range<Anchor>],
15967 cx: &mut Context<Editor>,
15968 ) -> Task<Result<()>> {
15969 let multibuffer = self.buffer.read(cx);
15970 let snapshot = multibuffer.read(cx);
15971 let buffer_ids: HashSet<_> = ranges
15972 .iter()
15973 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15974 .collect();
15975 drop(snapshot);
15976
15977 let mut buffers = HashSet::default();
15978 for buffer_id in buffer_ids {
15979 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15980 let buffer = buffer_entity.read(cx);
15981 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15982 {
15983 buffers.insert(buffer_entity);
15984 }
15985 }
15986 }
15987
15988 if let Some(project) = &self.project {
15989 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15990 } else {
15991 Task::ready(Ok(()))
15992 }
15993 }
15994
15995 fn do_stage_or_unstage_and_next(
15996 &mut self,
15997 stage: bool,
15998 window: &mut Window,
15999 cx: &mut Context<Self>,
16000 ) {
16001 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
16002
16003 if ranges.iter().any(|range| range.start != range.end) {
16004 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16005 return;
16006 }
16007
16008 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
16009 let snapshot = self.snapshot(window, cx);
16010 let position = self.selections.newest::<Point>(cx).head();
16011 let mut row = snapshot
16012 .buffer_snapshot
16013 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
16014 .find(|hunk| hunk.row_range.start.0 > position.row)
16015 .map(|hunk| hunk.row_range.start);
16016
16017 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
16018 // Outside of the project diff editor, wrap around to the beginning.
16019 if !all_diff_hunks_expanded {
16020 row = row.or_else(|| {
16021 snapshot
16022 .buffer_snapshot
16023 .diff_hunks_in_range(Point::zero()..position)
16024 .find(|hunk| hunk.row_range.end.0 < position.row)
16025 .map(|hunk| hunk.row_range.start)
16026 });
16027 }
16028
16029 if let Some(row) = row {
16030 let destination = Point::new(row.0, 0);
16031 let autoscroll = Autoscroll::center();
16032
16033 self.unfold_ranges(&[destination..destination], false, false, cx);
16034 self.change_selections(Some(autoscroll), window, cx, |s| {
16035 s.select_ranges([destination..destination]);
16036 });
16037 }
16038 }
16039
16040 fn do_stage_or_unstage(
16041 &self,
16042 stage: bool,
16043 buffer_id: BufferId,
16044 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
16045 cx: &mut App,
16046 ) -> Option<()> {
16047 let project = self.project.as_ref()?;
16048 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
16049 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
16050 let buffer_snapshot = buffer.read(cx).snapshot();
16051 let file_exists = buffer_snapshot
16052 .file()
16053 .is_some_and(|file| file.disk_state().exists());
16054 diff.update(cx, |diff, cx| {
16055 diff.stage_or_unstage_hunks(
16056 stage,
16057 &hunks
16058 .map(|hunk| buffer_diff::DiffHunk {
16059 buffer_range: hunk.buffer_range,
16060 diff_base_byte_range: hunk.diff_base_byte_range,
16061 secondary_status: hunk.secondary_status,
16062 range: Point::zero()..Point::zero(), // unused
16063 })
16064 .collect::<Vec<_>>(),
16065 &buffer_snapshot,
16066 file_exists,
16067 cx,
16068 )
16069 });
16070 None
16071 }
16072
16073 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
16074 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
16075 self.buffer
16076 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
16077 }
16078
16079 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
16080 self.buffer.update(cx, |buffer, cx| {
16081 let ranges = vec![Anchor::min()..Anchor::max()];
16082 if !buffer.all_diff_hunks_expanded()
16083 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
16084 {
16085 buffer.collapse_diff_hunks(ranges, cx);
16086 true
16087 } else {
16088 false
16089 }
16090 })
16091 }
16092
16093 fn toggle_diff_hunks_in_ranges(
16094 &mut self,
16095 ranges: Vec<Range<Anchor>>,
16096 cx: &mut Context<Editor>,
16097 ) {
16098 self.buffer.update(cx, |buffer, cx| {
16099 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
16100 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
16101 })
16102 }
16103
16104 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
16105 self.buffer.update(cx, |buffer, cx| {
16106 let snapshot = buffer.snapshot(cx);
16107 let excerpt_id = range.end.excerpt_id;
16108 let point_range = range.to_point(&snapshot);
16109 let expand = !buffer.single_hunk_is_expanded(range, cx);
16110 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
16111 })
16112 }
16113
16114 pub(crate) fn apply_all_diff_hunks(
16115 &mut self,
16116 _: &ApplyAllDiffHunks,
16117 window: &mut Window,
16118 cx: &mut Context<Self>,
16119 ) {
16120 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16121
16122 let buffers = self.buffer.read(cx).all_buffers();
16123 for branch_buffer in buffers {
16124 branch_buffer.update(cx, |branch_buffer, cx| {
16125 branch_buffer.merge_into_base(Vec::new(), cx);
16126 });
16127 }
16128
16129 if let Some(project) = self.project.clone() {
16130 self.save(true, project, window, cx).detach_and_log_err(cx);
16131 }
16132 }
16133
16134 pub(crate) fn apply_selected_diff_hunks(
16135 &mut self,
16136 _: &ApplyDiffHunk,
16137 window: &mut Window,
16138 cx: &mut Context<Self>,
16139 ) {
16140 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16141 let snapshot = self.snapshot(window, cx);
16142 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
16143 let mut ranges_by_buffer = HashMap::default();
16144 self.transact(window, cx, |editor, _window, cx| {
16145 for hunk in hunks {
16146 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
16147 ranges_by_buffer
16148 .entry(buffer.clone())
16149 .or_insert_with(Vec::new)
16150 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
16151 }
16152 }
16153
16154 for (buffer, ranges) in ranges_by_buffer {
16155 buffer.update(cx, |buffer, cx| {
16156 buffer.merge_into_base(ranges, cx);
16157 });
16158 }
16159 });
16160
16161 if let Some(project) = self.project.clone() {
16162 self.save(true, project, window, cx).detach_and_log_err(cx);
16163 }
16164 }
16165
16166 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
16167 if hovered != self.gutter_hovered {
16168 self.gutter_hovered = hovered;
16169 cx.notify();
16170 }
16171 }
16172
16173 pub fn insert_blocks(
16174 &mut self,
16175 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
16176 autoscroll: Option<Autoscroll>,
16177 cx: &mut Context<Self>,
16178 ) -> Vec<CustomBlockId> {
16179 let blocks = self
16180 .display_map
16181 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
16182 if let Some(autoscroll) = autoscroll {
16183 self.request_autoscroll(autoscroll, cx);
16184 }
16185 cx.notify();
16186 blocks
16187 }
16188
16189 pub fn resize_blocks(
16190 &mut self,
16191 heights: HashMap<CustomBlockId, u32>,
16192 autoscroll: Option<Autoscroll>,
16193 cx: &mut Context<Self>,
16194 ) {
16195 self.display_map
16196 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
16197 if let Some(autoscroll) = autoscroll {
16198 self.request_autoscroll(autoscroll, cx);
16199 }
16200 cx.notify();
16201 }
16202
16203 pub fn replace_blocks(
16204 &mut self,
16205 renderers: HashMap<CustomBlockId, RenderBlock>,
16206 autoscroll: Option<Autoscroll>,
16207 cx: &mut Context<Self>,
16208 ) {
16209 self.display_map
16210 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
16211 if let Some(autoscroll) = autoscroll {
16212 self.request_autoscroll(autoscroll, cx);
16213 }
16214 cx.notify();
16215 }
16216
16217 pub fn remove_blocks(
16218 &mut self,
16219 block_ids: HashSet<CustomBlockId>,
16220 autoscroll: Option<Autoscroll>,
16221 cx: &mut Context<Self>,
16222 ) {
16223 self.display_map.update(cx, |display_map, cx| {
16224 display_map.remove_blocks(block_ids, cx)
16225 });
16226 if let Some(autoscroll) = autoscroll {
16227 self.request_autoscroll(autoscroll, cx);
16228 }
16229 cx.notify();
16230 }
16231
16232 pub fn row_for_block(
16233 &self,
16234 block_id: CustomBlockId,
16235 cx: &mut Context<Self>,
16236 ) -> Option<DisplayRow> {
16237 self.display_map
16238 .update(cx, |map, cx| map.row_for_block(block_id, cx))
16239 }
16240
16241 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
16242 self.focused_block = Some(focused_block);
16243 }
16244
16245 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
16246 self.focused_block.take()
16247 }
16248
16249 pub fn insert_creases(
16250 &mut self,
16251 creases: impl IntoIterator<Item = Crease<Anchor>>,
16252 cx: &mut Context<Self>,
16253 ) -> Vec<CreaseId> {
16254 self.display_map
16255 .update(cx, |map, cx| map.insert_creases(creases, cx))
16256 }
16257
16258 pub fn remove_creases(
16259 &mut self,
16260 ids: impl IntoIterator<Item = CreaseId>,
16261 cx: &mut Context<Self>,
16262 ) -> Vec<(CreaseId, Range<Anchor>)> {
16263 self.display_map
16264 .update(cx, |map, cx| map.remove_creases(ids, cx))
16265 }
16266
16267 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
16268 self.display_map
16269 .update(cx, |map, cx| map.snapshot(cx))
16270 .longest_row()
16271 }
16272
16273 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
16274 self.display_map
16275 .update(cx, |map, cx| map.snapshot(cx))
16276 .max_point()
16277 }
16278
16279 pub fn text(&self, cx: &App) -> String {
16280 self.buffer.read(cx).read(cx).text()
16281 }
16282
16283 pub fn is_empty(&self, cx: &App) -> bool {
16284 self.buffer.read(cx).read(cx).is_empty()
16285 }
16286
16287 pub fn text_option(&self, cx: &App) -> Option<String> {
16288 let text = self.text(cx);
16289 let text = text.trim();
16290
16291 if text.is_empty() {
16292 return None;
16293 }
16294
16295 Some(text.to_string())
16296 }
16297
16298 pub fn set_text(
16299 &mut self,
16300 text: impl Into<Arc<str>>,
16301 window: &mut Window,
16302 cx: &mut Context<Self>,
16303 ) {
16304 self.transact(window, cx, |this, _, cx| {
16305 this.buffer
16306 .read(cx)
16307 .as_singleton()
16308 .expect("you can only call set_text on editors for singleton buffers")
16309 .update(cx, |buffer, cx| buffer.set_text(text, cx));
16310 });
16311 }
16312
16313 pub fn display_text(&self, cx: &mut App) -> String {
16314 self.display_map
16315 .update(cx, |map, cx| map.snapshot(cx))
16316 .text()
16317 }
16318
16319 fn create_minimap(
16320 &self,
16321 minimap_settings: MinimapSettings,
16322 window: &mut Window,
16323 cx: &mut Context<Self>,
16324 ) -> Option<Entity<Self>> {
16325 (minimap_settings.minimap_enabled() && self.is_singleton(cx))
16326 .then(|| self.initialize_new_minimap(minimap_settings, window, cx))
16327 }
16328
16329 fn initialize_new_minimap(
16330 &self,
16331 minimap_settings: MinimapSettings,
16332 window: &mut Window,
16333 cx: &mut Context<Self>,
16334 ) -> Entity<Self> {
16335 const MINIMAP_FONT_WEIGHT: gpui::FontWeight = gpui::FontWeight::BLACK;
16336
16337 let mut minimap = Editor::new_internal(
16338 EditorMode::Minimap {
16339 parent: cx.weak_entity(),
16340 },
16341 self.buffer.clone(),
16342 self.project.clone(),
16343 Some(self.display_map.clone()),
16344 window,
16345 cx,
16346 );
16347 minimap.scroll_manager.clone_state(&self.scroll_manager);
16348 minimap.set_text_style_refinement(TextStyleRefinement {
16349 font_size: Some(MINIMAP_FONT_SIZE),
16350 font_weight: Some(MINIMAP_FONT_WEIGHT),
16351 ..Default::default()
16352 });
16353 minimap.update_minimap_configuration(minimap_settings, cx);
16354 cx.new(|_| minimap)
16355 }
16356
16357 fn update_minimap_configuration(&mut self, minimap_settings: MinimapSettings, cx: &App) {
16358 let current_line_highlight = minimap_settings
16359 .current_line_highlight
16360 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight);
16361 self.set_current_line_highlight(Some(current_line_highlight));
16362 }
16363
16364 pub fn minimap(&self) -> Option<&Entity<Self>> {
16365 self.minimap.as_ref().filter(|_| self.show_minimap)
16366 }
16367
16368 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
16369 let mut wrap_guides = smallvec::smallvec![];
16370
16371 if self.show_wrap_guides == Some(false) {
16372 return wrap_guides;
16373 }
16374
16375 let settings = self.buffer.read(cx).language_settings(cx);
16376 if settings.show_wrap_guides {
16377 match self.soft_wrap_mode(cx) {
16378 SoftWrap::Column(soft_wrap) => {
16379 wrap_guides.push((soft_wrap as usize, true));
16380 }
16381 SoftWrap::Bounded(soft_wrap) => {
16382 wrap_guides.push((soft_wrap as usize, true));
16383 }
16384 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
16385 }
16386 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
16387 }
16388
16389 wrap_guides
16390 }
16391
16392 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
16393 let settings = self.buffer.read(cx).language_settings(cx);
16394 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
16395 match mode {
16396 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
16397 SoftWrap::None
16398 }
16399 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
16400 language_settings::SoftWrap::PreferredLineLength => {
16401 SoftWrap::Column(settings.preferred_line_length)
16402 }
16403 language_settings::SoftWrap::Bounded => {
16404 SoftWrap::Bounded(settings.preferred_line_length)
16405 }
16406 }
16407 }
16408
16409 pub fn set_soft_wrap_mode(
16410 &mut self,
16411 mode: language_settings::SoftWrap,
16412
16413 cx: &mut Context<Self>,
16414 ) {
16415 self.soft_wrap_mode_override = Some(mode);
16416 cx.notify();
16417 }
16418
16419 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16420 self.hard_wrap = hard_wrap;
16421 cx.notify();
16422 }
16423
16424 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16425 self.text_style_refinement = Some(style);
16426 }
16427
16428 /// called by the Element so we know what style we were most recently rendered with.
16429 pub(crate) fn set_style(
16430 &mut self,
16431 style: EditorStyle,
16432 window: &mut Window,
16433 cx: &mut Context<Self>,
16434 ) {
16435 // We intentionally do not inform the display map about the minimap style
16436 // so that wrapping is not recalculated and stays consistent for the editor
16437 // and its linked minimap.
16438 if !self.mode.is_minimap() {
16439 let rem_size = window.rem_size();
16440 self.display_map.update(cx, |map, cx| {
16441 map.set_font(
16442 style.text.font(),
16443 style.text.font_size.to_pixels(rem_size),
16444 cx,
16445 )
16446 });
16447 }
16448 self.style = Some(style);
16449 }
16450
16451 pub fn style(&self) -> Option<&EditorStyle> {
16452 self.style.as_ref()
16453 }
16454
16455 // Called by the element. This method is not designed to be called outside of the editor
16456 // element's layout code because it does not notify when rewrapping is computed synchronously.
16457 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16458 self.display_map
16459 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16460 }
16461
16462 pub fn set_soft_wrap(&mut self) {
16463 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16464 }
16465
16466 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16467 if self.soft_wrap_mode_override.is_some() {
16468 self.soft_wrap_mode_override.take();
16469 } else {
16470 let soft_wrap = match self.soft_wrap_mode(cx) {
16471 SoftWrap::GitDiff => return,
16472 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16473 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16474 language_settings::SoftWrap::None
16475 }
16476 };
16477 self.soft_wrap_mode_override = Some(soft_wrap);
16478 }
16479 cx.notify();
16480 }
16481
16482 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16483 let Some(workspace) = self.workspace() else {
16484 return;
16485 };
16486 let fs = workspace.read(cx).app_state().fs.clone();
16487 let current_show = TabBarSettings::get_global(cx).show;
16488 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16489 setting.show = Some(!current_show);
16490 });
16491 }
16492
16493 pub fn toggle_indent_guides(
16494 &mut self,
16495 _: &ToggleIndentGuides,
16496 _: &mut Window,
16497 cx: &mut Context<Self>,
16498 ) {
16499 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16500 self.buffer
16501 .read(cx)
16502 .language_settings(cx)
16503 .indent_guides
16504 .enabled
16505 });
16506 self.show_indent_guides = Some(!currently_enabled);
16507 cx.notify();
16508 }
16509
16510 fn should_show_indent_guides(&self) -> Option<bool> {
16511 self.show_indent_guides
16512 }
16513
16514 pub fn toggle_line_numbers(
16515 &mut self,
16516 _: &ToggleLineNumbers,
16517 _: &mut Window,
16518 cx: &mut Context<Self>,
16519 ) {
16520 let mut editor_settings = EditorSettings::get_global(cx).clone();
16521 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16522 EditorSettings::override_global(editor_settings, cx);
16523 }
16524
16525 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16526 if let Some(show_line_numbers) = self.show_line_numbers {
16527 return show_line_numbers;
16528 }
16529 EditorSettings::get_global(cx).gutter.line_numbers
16530 }
16531
16532 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16533 self.use_relative_line_numbers
16534 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16535 }
16536
16537 pub fn toggle_relative_line_numbers(
16538 &mut self,
16539 _: &ToggleRelativeLineNumbers,
16540 _: &mut Window,
16541 cx: &mut Context<Self>,
16542 ) {
16543 let is_relative = self.should_use_relative_line_numbers(cx);
16544 self.set_relative_line_number(Some(!is_relative), cx)
16545 }
16546
16547 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16548 self.use_relative_line_numbers = is_relative;
16549 cx.notify();
16550 }
16551
16552 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16553 self.show_gutter = show_gutter;
16554 cx.notify();
16555 }
16556
16557 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16558 self.show_scrollbars = show_scrollbars;
16559 cx.notify();
16560 }
16561
16562 pub fn set_show_minimap(
16563 &mut self,
16564 show_minimap: bool,
16565 window: &mut Window,
16566 cx: &mut Context<Self>,
16567 ) {
16568 if self.show_minimap != show_minimap {
16569 self.show_minimap = show_minimap;
16570 if show_minimap {
16571 let minimap_settings = EditorSettings::get_global(cx).minimap;
16572 self.minimap = self.create_minimap(minimap_settings, window, cx);
16573 } else {
16574 self.minimap = None;
16575 }
16576 cx.notify();
16577 }
16578 }
16579
16580 pub fn disable_scrollbars_and_minimap(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16581 self.set_show_scrollbars(false, cx);
16582 self.set_show_minimap(false, window, cx);
16583 }
16584
16585 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16586 self.show_line_numbers = Some(show_line_numbers);
16587 cx.notify();
16588 }
16589
16590 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16591 self.disable_expand_excerpt_buttons = true;
16592 cx.notify();
16593 }
16594
16595 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16596 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16597 cx.notify();
16598 }
16599
16600 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16601 self.show_code_actions = Some(show_code_actions);
16602 cx.notify();
16603 }
16604
16605 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16606 self.show_runnables = Some(show_runnables);
16607 cx.notify();
16608 }
16609
16610 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16611 self.show_breakpoints = Some(show_breakpoints);
16612 cx.notify();
16613 }
16614
16615 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16616 if self.display_map.read(cx).masked != masked {
16617 self.display_map.update(cx, |map, _| map.masked = masked);
16618 }
16619 cx.notify()
16620 }
16621
16622 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16623 self.show_wrap_guides = Some(show_wrap_guides);
16624 cx.notify();
16625 }
16626
16627 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16628 self.show_indent_guides = Some(show_indent_guides);
16629 cx.notify();
16630 }
16631
16632 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16633 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16634 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16635 if let Some(dir) = file.abs_path(cx).parent() {
16636 return Some(dir.to_owned());
16637 }
16638 }
16639
16640 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16641 return Some(project_path.path.to_path_buf());
16642 }
16643 }
16644
16645 None
16646 }
16647
16648 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16649 self.active_excerpt(cx)?
16650 .1
16651 .read(cx)
16652 .file()
16653 .and_then(|f| f.as_local())
16654 }
16655
16656 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16657 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16658 let buffer = buffer.read(cx);
16659 if let Some(project_path) = buffer.project_path(cx) {
16660 let project = self.project.as_ref()?.read(cx);
16661 project.absolute_path(&project_path, cx)
16662 } else {
16663 buffer
16664 .file()
16665 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16666 }
16667 })
16668 }
16669
16670 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16671 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16672 let project_path = buffer.read(cx).project_path(cx)?;
16673 let project = self.project.as_ref()?.read(cx);
16674 let entry = project.entry_for_path(&project_path, cx)?;
16675 let path = entry.path.to_path_buf();
16676 Some(path)
16677 })
16678 }
16679
16680 pub fn reveal_in_finder(
16681 &mut self,
16682 _: &RevealInFileManager,
16683 _window: &mut Window,
16684 cx: &mut Context<Self>,
16685 ) {
16686 if let Some(target) = self.target_file(cx) {
16687 cx.reveal_path(&target.abs_path(cx));
16688 }
16689 }
16690
16691 pub fn copy_path(
16692 &mut self,
16693 _: &zed_actions::workspace::CopyPath,
16694 _window: &mut Window,
16695 cx: &mut Context<Self>,
16696 ) {
16697 if let Some(path) = self.target_file_abs_path(cx) {
16698 if let Some(path) = path.to_str() {
16699 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16700 }
16701 }
16702 }
16703
16704 pub fn copy_relative_path(
16705 &mut self,
16706 _: &zed_actions::workspace::CopyRelativePath,
16707 _window: &mut Window,
16708 cx: &mut Context<Self>,
16709 ) {
16710 if let Some(path) = self.target_file_path(cx) {
16711 if let Some(path) = path.to_str() {
16712 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16713 }
16714 }
16715 }
16716
16717 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16718 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16719 buffer.read(cx).project_path(cx)
16720 } else {
16721 None
16722 }
16723 }
16724
16725 // Returns true if the editor handled a go-to-line request
16726 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16727 maybe!({
16728 let breakpoint_store = self.breakpoint_store.as_ref()?;
16729
16730 let Some(active_stack_frame) = breakpoint_store.read(cx).active_position().cloned()
16731 else {
16732 self.clear_row_highlights::<ActiveDebugLine>();
16733 return None;
16734 };
16735
16736 let position = active_stack_frame.position;
16737 let buffer_id = position.buffer_id?;
16738 let snapshot = self
16739 .project
16740 .as_ref()?
16741 .read(cx)
16742 .buffer_for_id(buffer_id, cx)?
16743 .read(cx)
16744 .snapshot();
16745
16746 let mut handled = false;
16747 for (id, ExcerptRange { context, .. }) in
16748 self.buffer.read(cx).excerpts_for_buffer(buffer_id, cx)
16749 {
16750 if context.start.cmp(&position, &snapshot).is_ge()
16751 || context.end.cmp(&position, &snapshot).is_lt()
16752 {
16753 continue;
16754 }
16755 let snapshot = self.buffer.read(cx).snapshot(cx);
16756 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, position)?;
16757
16758 handled = true;
16759 self.clear_row_highlights::<ActiveDebugLine>();
16760 self.go_to_line::<ActiveDebugLine>(
16761 multibuffer_anchor,
16762 Some(cx.theme().colors().editor_debugger_active_line_background),
16763 window,
16764 cx,
16765 );
16766
16767 cx.notify();
16768 }
16769
16770 handled.then_some(())
16771 })
16772 .is_some()
16773 }
16774
16775 pub fn copy_file_name_without_extension(
16776 &mut self,
16777 _: &CopyFileNameWithoutExtension,
16778 _: &mut Window,
16779 cx: &mut Context<Self>,
16780 ) {
16781 if let Some(file) = self.target_file(cx) {
16782 if let Some(file_stem) = file.path().file_stem() {
16783 if let Some(name) = file_stem.to_str() {
16784 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16785 }
16786 }
16787 }
16788 }
16789
16790 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16791 if let Some(file) = self.target_file(cx) {
16792 if let Some(file_name) = file.path().file_name() {
16793 if let Some(name) = file_name.to_str() {
16794 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16795 }
16796 }
16797 }
16798 }
16799
16800 pub fn toggle_git_blame(
16801 &mut self,
16802 _: &::git::Blame,
16803 window: &mut Window,
16804 cx: &mut Context<Self>,
16805 ) {
16806 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16807
16808 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16809 self.start_git_blame(true, window, cx);
16810 }
16811
16812 cx.notify();
16813 }
16814
16815 pub fn toggle_git_blame_inline(
16816 &mut self,
16817 _: &ToggleGitBlameInline,
16818 window: &mut Window,
16819 cx: &mut Context<Self>,
16820 ) {
16821 self.toggle_git_blame_inline_internal(true, window, cx);
16822 cx.notify();
16823 }
16824
16825 pub fn open_git_blame_commit(
16826 &mut self,
16827 _: &OpenGitBlameCommit,
16828 window: &mut Window,
16829 cx: &mut Context<Self>,
16830 ) {
16831 self.open_git_blame_commit_internal(window, cx);
16832 }
16833
16834 fn open_git_blame_commit_internal(
16835 &mut self,
16836 window: &mut Window,
16837 cx: &mut Context<Self>,
16838 ) -> Option<()> {
16839 let blame = self.blame.as_ref()?;
16840 let snapshot = self.snapshot(window, cx);
16841 let cursor = self.selections.newest::<Point>(cx).head();
16842 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16843 let blame_entry = blame
16844 .update(cx, |blame, cx| {
16845 blame
16846 .blame_for_rows(
16847 &[RowInfo {
16848 buffer_id: Some(buffer.remote_id()),
16849 buffer_row: Some(point.row),
16850 ..Default::default()
16851 }],
16852 cx,
16853 )
16854 .next()
16855 })
16856 .flatten()?;
16857 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16858 let repo = blame.read(cx).repository(cx)?;
16859 let workspace = self.workspace()?.downgrade();
16860 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16861 None
16862 }
16863
16864 pub fn git_blame_inline_enabled(&self) -> bool {
16865 self.git_blame_inline_enabled
16866 }
16867
16868 pub fn toggle_selection_menu(
16869 &mut self,
16870 _: &ToggleSelectionMenu,
16871 _: &mut Window,
16872 cx: &mut Context<Self>,
16873 ) {
16874 self.show_selection_menu = self
16875 .show_selection_menu
16876 .map(|show_selections_menu| !show_selections_menu)
16877 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16878
16879 cx.notify();
16880 }
16881
16882 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16883 self.show_selection_menu
16884 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16885 }
16886
16887 fn start_git_blame(
16888 &mut self,
16889 user_triggered: bool,
16890 window: &mut Window,
16891 cx: &mut Context<Self>,
16892 ) {
16893 if let Some(project) = self.project.as_ref() {
16894 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16895 return;
16896 };
16897
16898 if buffer.read(cx).file().is_none() {
16899 return;
16900 }
16901
16902 let focused = self.focus_handle(cx).contains_focused(window, cx);
16903
16904 let project = project.clone();
16905 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16906 self.blame_subscription =
16907 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16908 self.blame = Some(blame);
16909 }
16910 }
16911
16912 fn toggle_git_blame_inline_internal(
16913 &mut self,
16914 user_triggered: bool,
16915 window: &mut Window,
16916 cx: &mut Context<Self>,
16917 ) {
16918 if self.git_blame_inline_enabled {
16919 self.git_blame_inline_enabled = false;
16920 self.show_git_blame_inline = false;
16921 self.show_git_blame_inline_delay_task.take();
16922 } else {
16923 self.git_blame_inline_enabled = true;
16924 self.start_git_blame_inline(user_triggered, window, cx);
16925 }
16926
16927 cx.notify();
16928 }
16929
16930 fn start_git_blame_inline(
16931 &mut self,
16932 user_triggered: bool,
16933 window: &mut Window,
16934 cx: &mut Context<Self>,
16935 ) {
16936 self.start_git_blame(user_triggered, window, cx);
16937
16938 if ProjectSettings::get_global(cx)
16939 .git
16940 .inline_blame_delay()
16941 .is_some()
16942 {
16943 self.start_inline_blame_timer(window, cx);
16944 } else {
16945 self.show_git_blame_inline = true
16946 }
16947 }
16948
16949 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16950 self.blame.as_ref()
16951 }
16952
16953 pub fn show_git_blame_gutter(&self) -> bool {
16954 self.show_git_blame_gutter
16955 }
16956
16957 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16958 !self.mode().is_minimap() && self.show_git_blame_gutter && self.has_blame_entries(cx)
16959 }
16960
16961 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16962 self.show_git_blame_inline
16963 && (self.focus_handle.is_focused(window) || self.inline_blame_popover.is_some())
16964 && !self.newest_selection_head_on_empty_line(cx)
16965 && self.has_blame_entries(cx)
16966 }
16967
16968 fn has_blame_entries(&self, cx: &App) -> bool {
16969 self.blame()
16970 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16971 }
16972
16973 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16974 let cursor_anchor = self.selections.newest_anchor().head();
16975
16976 let snapshot = self.buffer.read(cx).snapshot(cx);
16977 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16978
16979 snapshot.line_len(buffer_row) == 0
16980 }
16981
16982 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16983 let buffer_and_selection = maybe!({
16984 let selection = self.selections.newest::<Point>(cx);
16985 let selection_range = selection.range();
16986
16987 let multi_buffer = self.buffer().read(cx);
16988 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16989 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16990
16991 let (buffer, range, _) = if selection.reversed {
16992 buffer_ranges.first()
16993 } else {
16994 buffer_ranges.last()
16995 }?;
16996
16997 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16998 ..text::ToPoint::to_point(&range.end, &buffer).row;
16999 Some((
17000 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
17001 selection,
17002 ))
17003 });
17004
17005 let Some((buffer, selection)) = buffer_and_selection else {
17006 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
17007 };
17008
17009 let Some(project) = self.project.as_ref() else {
17010 return Task::ready(Err(anyhow!("editor does not have project")));
17011 };
17012
17013 project.update(cx, |project, cx| {
17014 project.get_permalink_to_line(&buffer, selection, cx)
17015 })
17016 }
17017
17018 pub fn copy_permalink_to_line(
17019 &mut self,
17020 _: &CopyPermalinkToLine,
17021 window: &mut Window,
17022 cx: &mut Context<Self>,
17023 ) {
17024 let permalink_task = self.get_permalink_to_line(cx);
17025 let workspace = self.workspace();
17026
17027 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
17028 Ok(permalink) => {
17029 cx.update(|_, cx| {
17030 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
17031 })
17032 .ok();
17033 }
17034 Err(err) => {
17035 let message = format!("Failed to copy permalink: {err}");
17036
17037 Err::<(), anyhow::Error>(err).log_err();
17038
17039 if let Some(workspace) = workspace {
17040 workspace
17041 .update_in(cx, |workspace, _, cx| {
17042 struct CopyPermalinkToLine;
17043
17044 workspace.show_toast(
17045 Toast::new(
17046 NotificationId::unique::<CopyPermalinkToLine>(),
17047 message,
17048 ),
17049 cx,
17050 )
17051 })
17052 .ok();
17053 }
17054 }
17055 })
17056 .detach();
17057 }
17058
17059 pub fn copy_file_location(
17060 &mut self,
17061 _: &CopyFileLocation,
17062 _: &mut Window,
17063 cx: &mut Context<Self>,
17064 ) {
17065 let selection = self.selections.newest::<Point>(cx).start.row + 1;
17066 if let Some(file) = self.target_file(cx) {
17067 if let Some(path) = file.path().to_str() {
17068 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
17069 }
17070 }
17071 }
17072
17073 pub fn open_permalink_to_line(
17074 &mut self,
17075 _: &OpenPermalinkToLine,
17076 window: &mut Window,
17077 cx: &mut Context<Self>,
17078 ) {
17079 let permalink_task = self.get_permalink_to_line(cx);
17080 let workspace = self.workspace();
17081
17082 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
17083 Ok(permalink) => {
17084 cx.update(|_, cx| {
17085 cx.open_url(permalink.as_ref());
17086 })
17087 .ok();
17088 }
17089 Err(err) => {
17090 let message = format!("Failed to open permalink: {err}");
17091
17092 Err::<(), anyhow::Error>(err).log_err();
17093
17094 if let Some(workspace) = workspace {
17095 workspace
17096 .update(cx, |workspace, cx| {
17097 struct OpenPermalinkToLine;
17098
17099 workspace.show_toast(
17100 Toast::new(
17101 NotificationId::unique::<OpenPermalinkToLine>(),
17102 message,
17103 ),
17104 cx,
17105 )
17106 })
17107 .ok();
17108 }
17109 }
17110 })
17111 .detach();
17112 }
17113
17114 pub fn insert_uuid_v4(
17115 &mut self,
17116 _: &InsertUuidV4,
17117 window: &mut Window,
17118 cx: &mut Context<Self>,
17119 ) {
17120 self.insert_uuid(UuidVersion::V4, window, cx);
17121 }
17122
17123 pub fn insert_uuid_v7(
17124 &mut self,
17125 _: &InsertUuidV7,
17126 window: &mut Window,
17127 cx: &mut Context<Self>,
17128 ) {
17129 self.insert_uuid(UuidVersion::V7, window, cx);
17130 }
17131
17132 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
17133 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
17134 self.transact(window, cx, |this, window, cx| {
17135 let edits = this
17136 .selections
17137 .all::<Point>(cx)
17138 .into_iter()
17139 .map(|selection| {
17140 let uuid = match version {
17141 UuidVersion::V4 => uuid::Uuid::new_v4(),
17142 UuidVersion::V7 => uuid::Uuid::now_v7(),
17143 };
17144
17145 (selection.range(), uuid.to_string())
17146 });
17147 this.edit(edits, cx);
17148 this.refresh_inline_completion(true, false, window, cx);
17149 });
17150 }
17151
17152 pub fn open_selections_in_multibuffer(
17153 &mut self,
17154 _: &OpenSelectionsInMultibuffer,
17155 window: &mut Window,
17156 cx: &mut Context<Self>,
17157 ) {
17158 let multibuffer = self.buffer.read(cx);
17159
17160 let Some(buffer) = multibuffer.as_singleton() else {
17161 return;
17162 };
17163
17164 let Some(workspace) = self.workspace() else {
17165 return;
17166 };
17167
17168 let locations = self
17169 .selections
17170 .disjoint_anchors()
17171 .iter()
17172 .map(|range| Location {
17173 buffer: buffer.clone(),
17174 range: range.start.text_anchor..range.end.text_anchor,
17175 })
17176 .collect::<Vec<_>>();
17177
17178 let title = multibuffer.title(cx).to_string();
17179
17180 cx.spawn_in(window, async move |_, cx| {
17181 workspace.update_in(cx, |workspace, window, cx| {
17182 Self::open_locations_in_multibuffer(
17183 workspace,
17184 locations,
17185 format!("Selections for '{title}'"),
17186 false,
17187 MultibufferSelectionMode::All,
17188 window,
17189 cx,
17190 );
17191 })
17192 })
17193 .detach();
17194 }
17195
17196 /// Adds a row highlight for the given range. If a row has multiple highlights, the
17197 /// last highlight added will be used.
17198 ///
17199 /// If the range ends at the beginning of a line, then that line will not be highlighted.
17200 pub fn highlight_rows<T: 'static>(
17201 &mut self,
17202 range: Range<Anchor>,
17203 color: Hsla,
17204 options: RowHighlightOptions,
17205 cx: &mut Context<Self>,
17206 ) {
17207 let snapshot = self.buffer().read(cx).snapshot(cx);
17208 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17209 let ix = row_highlights.binary_search_by(|highlight| {
17210 Ordering::Equal
17211 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
17212 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
17213 });
17214
17215 if let Err(mut ix) = ix {
17216 let index = post_inc(&mut self.highlight_order);
17217
17218 // If this range intersects with the preceding highlight, then merge it with
17219 // the preceding highlight. Otherwise insert a new highlight.
17220 let mut merged = false;
17221 if ix > 0 {
17222 let prev_highlight = &mut row_highlights[ix - 1];
17223 if prev_highlight
17224 .range
17225 .end
17226 .cmp(&range.start, &snapshot)
17227 .is_ge()
17228 {
17229 ix -= 1;
17230 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
17231 prev_highlight.range.end = range.end;
17232 }
17233 merged = true;
17234 prev_highlight.index = index;
17235 prev_highlight.color = color;
17236 prev_highlight.options = options;
17237 }
17238 }
17239
17240 if !merged {
17241 row_highlights.insert(
17242 ix,
17243 RowHighlight {
17244 range: range.clone(),
17245 index,
17246 color,
17247 options,
17248 type_id: TypeId::of::<T>(),
17249 },
17250 );
17251 }
17252
17253 // If any of the following highlights intersect with this one, merge them.
17254 while let Some(next_highlight) = row_highlights.get(ix + 1) {
17255 let highlight = &row_highlights[ix];
17256 if next_highlight
17257 .range
17258 .start
17259 .cmp(&highlight.range.end, &snapshot)
17260 .is_le()
17261 {
17262 if next_highlight
17263 .range
17264 .end
17265 .cmp(&highlight.range.end, &snapshot)
17266 .is_gt()
17267 {
17268 row_highlights[ix].range.end = next_highlight.range.end;
17269 }
17270 row_highlights.remove(ix + 1);
17271 } else {
17272 break;
17273 }
17274 }
17275 }
17276 }
17277
17278 /// Remove any highlighted row ranges of the given type that intersect the
17279 /// given ranges.
17280 pub fn remove_highlighted_rows<T: 'static>(
17281 &mut self,
17282 ranges_to_remove: Vec<Range<Anchor>>,
17283 cx: &mut Context<Self>,
17284 ) {
17285 let snapshot = self.buffer().read(cx).snapshot(cx);
17286 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
17287 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
17288 row_highlights.retain(|highlight| {
17289 while let Some(range_to_remove) = ranges_to_remove.peek() {
17290 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
17291 Ordering::Less | Ordering::Equal => {
17292 ranges_to_remove.next();
17293 }
17294 Ordering::Greater => {
17295 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
17296 Ordering::Less | Ordering::Equal => {
17297 return false;
17298 }
17299 Ordering::Greater => break,
17300 }
17301 }
17302 }
17303 }
17304
17305 true
17306 })
17307 }
17308
17309 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
17310 pub fn clear_row_highlights<T: 'static>(&mut self) {
17311 self.highlighted_rows.remove(&TypeId::of::<T>());
17312 }
17313
17314 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
17315 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
17316 self.highlighted_rows
17317 .get(&TypeId::of::<T>())
17318 .map_or(&[] as &[_], |vec| vec.as_slice())
17319 .iter()
17320 .map(|highlight| (highlight.range.clone(), highlight.color))
17321 }
17322
17323 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
17324 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
17325 /// Allows to ignore certain kinds of highlights.
17326 pub fn highlighted_display_rows(
17327 &self,
17328 window: &mut Window,
17329 cx: &mut App,
17330 ) -> BTreeMap<DisplayRow, LineHighlight> {
17331 let snapshot = self.snapshot(window, cx);
17332 let mut used_highlight_orders = HashMap::default();
17333 self.highlighted_rows
17334 .iter()
17335 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
17336 .fold(
17337 BTreeMap::<DisplayRow, LineHighlight>::new(),
17338 |mut unique_rows, highlight| {
17339 let start = highlight.range.start.to_display_point(&snapshot);
17340 let end = highlight.range.end.to_display_point(&snapshot);
17341 let start_row = start.row().0;
17342 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
17343 && end.column() == 0
17344 {
17345 end.row().0.saturating_sub(1)
17346 } else {
17347 end.row().0
17348 };
17349 for row in start_row..=end_row {
17350 let used_index =
17351 used_highlight_orders.entry(row).or_insert(highlight.index);
17352 if highlight.index >= *used_index {
17353 *used_index = highlight.index;
17354 unique_rows.insert(
17355 DisplayRow(row),
17356 LineHighlight {
17357 include_gutter: highlight.options.include_gutter,
17358 border: None,
17359 background: highlight.color.into(),
17360 type_id: Some(highlight.type_id),
17361 },
17362 );
17363 }
17364 }
17365 unique_rows
17366 },
17367 )
17368 }
17369
17370 pub fn highlighted_display_row_for_autoscroll(
17371 &self,
17372 snapshot: &DisplaySnapshot,
17373 ) -> Option<DisplayRow> {
17374 self.highlighted_rows
17375 .values()
17376 .flat_map(|highlighted_rows| highlighted_rows.iter())
17377 .filter_map(|highlight| {
17378 if highlight.options.autoscroll {
17379 Some(highlight.range.start.to_display_point(snapshot).row())
17380 } else {
17381 None
17382 }
17383 })
17384 .min()
17385 }
17386
17387 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
17388 self.highlight_background::<SearchWithinRange>(
17389 ranges,
17390 |colors| colors.editor_document_highlight_read_background,
17391 cx,
17392 )
17393 }
17394
17395 pub fn set_breadcrumb_header(&mut self, new_header: String) {
17396 self.breadcrumb_header = Some(new_header);
17397 }
17398
17399 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
17400 self.clear_background_highlights::<SearchWithinRange>(cx);
17401 }
17402
17403 pub fn highlight_background<T: 'static>(
17404 &mut self,
17405 ranges: &[Range<Anchor>],
17406 color_fetcher: fn(&ThemeColors) -> Hsla,
17407 cx: &mut Context<Self>,
17408 ) {
17409 self.background_highlights
17410 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17411 self.scrollbar_marker_state.dirty = true;
17412 cx.notify();
17413 }
17414
17415 pub fn clear_background_highlights<T: 'static>(
17416 &mut self,
17417 cx: &mut Context<Self>,
17418 ) -> Option<BackgroundHighlight> {
17419 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
17420 if !text_highlights.1.is_empty() {
17421 self.scrollbar_marker_state.dirty = true;
17422 cx.notify();
17423 }
17424 Some(text_highlights)
17425 }
17426
17427 pub fn highlight_gutter<T: 'static>(
17428 &mut self,
17429 ranges: &[Range<Anchor>],
17430 color_fetcher: fn(&App) -> Hsla,
17431 cx: &mut Context<Self>,
17432 ) {
17433 self.gutter_highlights
17434 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17435 cx.notify();
17436 }
17437
17438 pub fn clear_gutter_highlights<T: 'static>(
17439 &mut self,
17440 cx: &mut Context<Self>,
17441 ) -> Option<GutterHighlight> {
17442 cx.notify();
17443 self.gutter_highlights.remove(&TypeId::of::<T>())
17444 }
17445
17446 #[cfg(feature = "test-support")]
17447 pub fn all_text_background_highlights(
17448 &self,
17449 window: &mut Window,
17450 cx: &mut Context<Self>,
17451 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17452 let snapshot = self.snapshot(window, cx);
17453 let buffer = &snapshot.buffer_snapshot;
17454 let start = buffer.anchor_before(0);
17455 let end = buffer.anchor_after(buffer.len());
17456 let theme = cx.theme().colors();
17457 self.background_highlights_in_range(start..end, &snapshot, theme)
17458 }
17459
17460 #[cfg(feature = "test-support")]
17461 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17462 let snapshot = self.buffer().read(cx).snapshot(cx);
17463
17464 let highlights = self
17465 .background_highlights
17466 .get(&TypeId::of::<items::BufferSearchHighlights>());
17467
17468 if let Some((_color, ranges)) = highlights {
17469 ranges
17470 .iter()
17471 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17472 .collect_vec()
17473 } else {
17474 vec![]
17475 }
17476 }
17477
17478 fn document_highlights_for_position<'a>(
17479 &'a self,
17480 position: Anchor,
17481 buffer: &'a MultiBufferSnapshot,
17482 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17483 let read_highlights = self
17484 .background_highlights
17485 .get(&TypeId::of::<DocumentHighlightRead>())
17486 .map(|h| &h.1);
17487 let write_highlights = self
17488 .background_highlights
17489 .get(&TypeId::of::<DocumentHighlightWrite>())
17490 .map(|h| &h.1);
17491 let left_position = position.bias_left(buffer);
17492 let right_position = position.bias_right(buffer);
17493 read_highlights
17494 .into_iter()
17495 .chain(write_highlights)
17496 .flat_map(move |ranges| {
17497 let start_ix = match ranges.binary_search_by(|probe| {
17498 let cmp = probe.end.cmp(&left_position, buffer);
17499 if cmp.is_ge() {
17500 Ordering::Greater
17501 } else {
17502 Ordering::Less
17503 }
17504 }) {
17505 Ok(i) | Err(i) => i,
17506 };
17507
17508 ranges[start_ix..]
17509 .iter()
17510 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17511 })
17512 }
17513
17514 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17515 self.background_highlights
17516 .get(&TypeId::of::<T>())
17517 .map_or(false, |(_, highlights)| !highlights.is_empty())
17518 }
17519
17520 pub fn background_highlights_in_range(
17521 &self,
17522 search_range: Range<Anchor>,
17523 display_snapshot: &DisplaySnapshot,
17524 theme: &ThemeColors,
17525 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17526 let mut results = Vec::new();
17527 for (color_fetcher, ranges) in self.background_highlights.values() {
17528 let color = color_fetcher(theme);
17529 let start_ix = match ranges.binary_search_by(|probe| {
17530 let cmp = probe
17531 .end
17532 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17533 if cmp.is_gt() {
17534 Ordering::Greater
17535 } else {
17536 Ordering::Less
17537 }
17538 }) {
17539 Ok(i) | Err(i) => i,
17540 };
17541 for range in &ranges[start_ix..] {
17542 if range
17543 .start
17544 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17545 .is_ge()
17546 {
17547 break;
17548 }
17549
17550 let start = range.start.to_display_point(display_snapshot);
17551 let end = range.end.to_display_point(display_snapshot);
17552 results.push((start..end, color))
17553 }
17554 }
17555 results
17556 }
17557
17558 pub fn background_highlight_row_ranges<T: 'static>(
17559 &self,
17560 search_range: Range<Anchor>,
17561 display_snapshot: &DisplaySnapshot,
17562 count: usize,
17563 ) -> Vec<RangeInclusive<DisplayPoint>> {
17564 let mut results = Vec::new();
17565 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17566 return vec![];
17567 };
17568
17569 let start_ix = match ranges.binary_search_by(|probe| {
17570 let cmp = probe
17571 .end
17572 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17573 if cmp.is_gt() {
17574 Ordering::Greater
17575 } else {
17576 Ordering::Less
17577 }
17578 }) {
17579 Ok(i) | Err(i) => i,
17580 };
17581 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17582 if let (Some(start_display), Some(end_display)) = (start, end) {
17583 results.push(
17584 start_display.to_display_point(display_snapshot)
17585 ..=end_display.to_display_point(display_snapshot),
17586 );
17587 }
17588 };
17589 let mut start_row: Option<Point> = None;
17590 let mut end_row: Option<Point> = None;
17591 if ranges.len() > count {
17592 return Vec::new();
17593 }
17594 for range in &ranges[start_ix..] {
17595 if range
17596 .start
17597 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17598 .is_ge()
17599 {
17600 break;
17601 }
17602 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17603 if let Some(current_row) = &end_row {
17604 if end.row == current_row.row {
17605 continue;
17606 }
17607 }
17608 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17609 if start_row.is_none() {
17610 assert_eq!(end_row, None);
17611 start_row = Some(start);
17612 end_row = Some(end);
17613 continue;
17614 }
17615 if let Some(current_end) = end_row.as_mut() {
17616 if start.row > current_end.row + 1 {
17617 push_region(start_row, end_row);
17618 start_row = Some(start);
17619 end_row = Some(end);
17620 } else {
17621 // Merge two hunks.
17622 *current_end = end;
17623 }
17624 } else {
17625 unreachable!();
17626 }
17627 }
17628 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17629 push_region(start_row, end_row);
17630 results
17631 }
17632
17633 pub fn gutter_highlights_in_range(
17634 &self,
17635 search_range: Range<Anchor>,
17636 display_snapshot: &DisplaySnapshot,
17637 cx: &App,
17638 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17639 let mut results = Vec::new();
17640 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17641 let color = color_fetcher(cx);
17642 let start_ix = match ranges.binary_search_by(|probe| {
17643 let cmp = probe
17644 .end
17645 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17646 if cmp.is_gt() {
17647 Ordering::Greater
17648 } else {
17649 Ordering::Less
17650 }
17651 }) {
17652 Ok(i) | Err(i) => i,
17653 };
17654 for range in &ranges[start_ix..] {
17655 if range
17656 .start
17657 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17658 .is_ge()
17659 {
17660 break;
17661 }
17662
17663 let start = range.start.to_display_point(display_snapshot);
17664 let end = range.end.to_display_point(display_snapshot);
17665 results.push((start..end, color))
17666 }
17667 }
17668 results
17669 }
17670
17671 /// Get the text ranges corresponding to the redaction query
17672 pub fn redacted_ranges(
17673 &self,
17674 search_range: Range<Anchor>,
17675 display_snapshot: &DisplaySnapshot,
17676 cx: &App,
17677 ) -> Vec<Range<DisplayPoint>> {
17678 display_snapshot
17679 .buffer_snapshot
17680 .redacted_ranges(search_range, |file| {
17681 if let Some(file) = file {
17682 file.is_private()
17683 && EditorSettings::get(
17684 Some(SettingsLocation {
17685 worktree_id: file.worktree_id(cx),
17686 path: file.path().as_ref(),
17687 }),
17688 cx,
17689 )
17690 .redact_private_values
17691 } else {
17692 false
17693 }
17694 })
17695 .map(|range| {
17696 range.start.to_display_point(display_snapshot)
17697 ..range.end.to_display_point(display_snapshot)
17698 })
17699 .collect()
17700 }
17701
17702 pub fn highlight_text<T: 'static>(
17703 &mut self,
17704 ranges: Vec<Range<Anchor>>,
17705 style: HighlightStyle,
17706 cx: &mut Context<Self>,
17707 ) {
17708 self.display_map.update(cx, |map, _| {
17709 map.highlight_text(TypeId::of::<T>(), ranges, style)
17710 });
17711 cx.notify();
17712 }
17713
17714 pub(crate) fn highlight_inlays<T: 'static>(
17715 &mut self,
17716 highlights: Vec<InlayHighlight>,
17717 style: HighlightStyle,
17718 cx: &mut Context<Self>,
17719 ) {
17720 self.display_map.update(cx, |map, _| {
17721 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17722 });
17723 cx.notify();
17724 }
17725
17726 pub fn text_highlights<'a, T: 'static>(
17727 &'a self,
17728 cx: &'a App,
17729 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17730 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17731 }
17732
17733 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17734 let cleared = self
17735 .display_map
17736 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17737 if cleared {
17738 cx.notify();
17739 }
17740 }
17741
17742 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17743 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17744 && self.focus_handle.is_focused(window)
17745 }
17746
17747 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17748 self.show_cursor_when_unfocused = is_enabled;
17749 cx.notify();
17750 }
17751
17752 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17753 cx.notify();
17754 }
17755
17756 fn on_debug_session_event(
17757 &mut self,
17758 _session: Entity<Session>,
17759 event: &SessionEvent,
17760 cx: &mut Context<Self>,
17761 ) {
17762 match event {
17763 SessionEvent::InvalidateInlineValue => {
17764 self.refresh_inline_values(cx);
17765 }
17766 _ => {}
17767 }
17768 }
17769
17770 pub fn refresh_inline_values(&mut self, cx: &mut Context<Self>) {
17771 let Some(project) = self.project.clone() else {
17772 return;
17773 };
17774 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
17775 return;
17776 };
17777 if !self.inline_value_cache.enabled {
17778 let inlays = std::mem::take(&mut self.inline_value_cache.inlays);
17779 self.splice_inlays(&inlays, Vec::new(), cx);
17780 return;
17781 }
17782
17783 let current_execution_position = self
17784 .highlighted_rows
17785 .get(&TypeId::of::<ActiveDebugLine>())
17786 .and_then(|lines| lines.last().map(|line| line.range.start));
17787
17788 self.inline_value_cache.refresh_task = cx.spawn(async move |editor, cx| {
17789 let snapshot = editor
17790 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
17791 .ok()?;
17792
17793 let inline_values = editor
17794 .update(cx, |_, cx| {
17795 let Some(current_execution_position) = current_execution_position else {
17796 return Some(Task::ready(Ok(Vec::new())));
17797 };
17798
17799 // todo(debugger) when introducing multi buffer inline values check execution position's buffer id to make sure the text
17800 // anchor is in the same buffer
17801 let range =
17802 buffer.read(cx).anchor_before(0)..current_execution_position.text_anchor;
17803 project.inline_values(buffer, range, cx)
17804 })
17805 .ok()
17806 .flatten()?
17807 .await
17808 .context("refreshing debugger inlays")
17809 .log_err()?;
17810
17811 let (excerpt_id, buffer_id) = snapshot
17812 .excerpts()
17813 .next()
17814 .map(|excerpt| (excerpt.0, excerpt.1.remote_id()))?;
17815 editor
17816 .update(cx, |editor, cx| {
17817 let new_inlays = inline_values
17818 .into_iter()
17819 .map(|debugger_value| {
17820 Inlay::debugger_hint(
17821 post_inc(&mut editor.next_inlay_id),
17822 Anchor::in_buffer(excerpt_id, buffer_id, debugger_value.position),
17823 debugger_value.text(),
17824 )
17825 })
17826 .collect::<Vec<_>>();
17827 let mut inlay_ids = new_inlays.iter().map(|inlay| inlay.id).collect();
17828 std::mem::swap(&mut editor.inline_value_cache.inlays, &mut inlay_ids);
17829
17830 editor.splice_inlays(&inlay_ids, new_inlays, cx);
17831 })
17832 .ok()?;
17833 Some(())
17834 });
17835 }
17836
17837 fn on_buffer_event(
17838 &mut self,
17839 multibuffer: &Entity<MultiBuffer>,
17840 event: &multi_buffer::Event,
17841 window: &mut Window,
17842 cx: &mut Context<Self>,
17843 ) {
17844 match event {
17845 multi_buffer::Event::Edited {
17846 singleton_buffer_edited,
17847 edited_buffer: buffer_edited,
17848 } => {
17849 self.scrollbar_marker_state.dirty = true;
17850 self.active_indent_guides_state.dirty = true;
17851 self.refresh_active_diagnostics(cx);
17852 self.refresh_code_actions(window, cx);
17853 self.refresh_selected_text_highlights(true, window, cx);
17854 refresh_matching_bracket_highlights(self, window, cx);
17855 if self.has_active_inline_completion() {
17856 self.update_visible_inline_completion(window, cx);
17857 }
17858 if let Some(buffer) = buffer_edited {
17859 let buffer_id = buffer.read(cx).remote_id();
17860 if !self.registered_buffers.contains_key(&buffer_id) {
17861 if let Some(project) = self.project.as_ref() {
17862 project.update(cx, |project, cx| {
17863 self.registered_buffers.insert(
17864 buffer_id,
17865 project.register_buffer_with_language_servers(&buffer, cx),
17866 );
17867 })
17868 }
17869 }
17870 }
17871 cx.emit(EditorEvent::BufferEdited);
17872 cx.emit(SearchEvent::MatchesInvalidated);
17873 if *singleton_buffer_edited {
17874 if let Some(project) = &self.project {
17875 #[allow(clippy::mutable_key_type)]
17876 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17877 multibuffer
17878 .all_buffers()
17879 .into_iter()
17880 .filter_map(|buffer| {
17881 buffer.update(cx, |buffer, cx| {
17882 let language = buffer.language()?;
17883 let should_discard = project.update(cx, |project, cx| {
17884 project.is_local()
17885 && !project.has_language_servers_for(buffer, cx)
17886 });
17887 should_discard.not().then_some(language.clone())
17888 })
17889 })
17890 .collect::<HashSet<_>>()
17891 });
17892 if !languages_affected.is_empty() {
17893 self.refresh_inlay_hints(
17894 InlayHintRefreshReason::BufferEdited(languages_affected),
17895 cx,
17896 );
17897 }
17898 }
17899 }
17900
17901 let Some(project) = &self.project else { return };
17902 let (telemetry, is_via_ssh) = {
17903 let project = project.read(cx);
17904 let telemetry = project.client().telemetry().clone();
17905 let is_via_ssh = project.is_via_ssh();
17906 (telemetry, is_via_ssh)
17907 };
17908 refresh_linked_ranges(self, window, cx);
17909 telemetry.log_edit_event("editor", is_via_ssh);
17910 }
17911 multi_buffer::Event::ExcerptsAdded {
17912 buffer,
17913 predecessor,
17914 excerpts,
17915 } => {
17916 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17917 let buffer_id = buffer.read(cx).remote_id();
17918 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17919 if let Some(project) = &self.project {
17920 update_uncommitted_diff_for_buffer(
17921 cx.entity(),
17922 project,
17923 [buffer.clone()],
17924 self.buffer.clone(),
17925 cx,
17926 )
17927 .detach();
17928 }
17929 }
17930 cx.emit(EditorEvent::ExcerptsAdded {
17931 buffer: buffer.clone(),
17932 predecessor: *predecessor,
17933 excerpts: excerpts.clone(),
17934 });
17935 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17936 }
17937 multi_buffer::Event::ExcerptsRemoved {
17938 ids,
17939 removed_buffer_ids,
17940 } => {
17941 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17942 let buffer = self.buffer.read(cx);
17943 self.registered_buffers
17944 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17945 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17946 cx.emit(EditorEvent::ExcerptsRemoved {
17947 ids: ids.clone(),
17948 removed_buffer_ids: removed_buffer_ids.clone(),
17949 })
17950 }
17951 multi_buffer::Event::ExcerptsEdited {
17952 excerpt_ids,
17953 buffer_ids,
17954 } => {
17955 self.display_map.update(cx, |map, cx| {
17956 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17957 });
17958 cx.emit(EditorEvent::ExcerptsEdited {
17959 ids: excerpt_ids.clone(),
17960 })
17961 }
17962 multi_buffer::Event::ExcerptsExpanded { ids } => {
17963 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17964 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17965 }
17966 multi_buffer::Event::Reparsed(buffer_id) => {
17967 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17968 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17969
17970 cx.emit(EditorEvent::Reparsed(*buffer_id));
17971 }
17972 multi_buffer::Event::DiffHunksToggled => {
17973 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17974 }
17975 multi_buffer::Event::LanguageChanged(buffer_id) => {
17976 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17977 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17978 cx.emit(EditorEvent::Reparsed(*buffer_id));
17979 cx.notify();
17980 }
17981 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17982 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17983 multi_buffer::Event::FileHandleChanged
17984 | multi_buffer::Event::Reloaded
17985 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17986 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17987 multi_buffer::Event::DiagnosticsUpdated => {
17988 self.refresh_active_diagnostics(cx);
17989 self.refresh_inline_diagnostics(true, window, cx);
17990 self.scrollbar_marker_state.dirty = true;
17991 cx.notify();
17992 }
17993 _ => {}
17994 };
17995 }
17996
17997 pub fn start_temporary_diff_override(&mut self) {
17998 self.load_diff_task.take();
17999 self.temporary_diff_override = true;
18000 }
18001
18002 pub fn end_temporary_diff_override(&mut self, cx: &mut Context<Self>) {
18003 self.temporary_diff_override = false;
18004 self.set_render_diff_hunk_controls(Arc::new(render_diff_hunk_controls), cx);
18005 self.buffer.update(cx, |buffer, cx| {
18006 buffer.set_all_diff_hunks_collapsed(cx);
18007 });
18008
18009 if let Some(project) = self.project.clone() {
18010 self.load_diff_task = Some(
18011 update_uncommitted_diff_for_buffer(
18012 cx.entity(),
18013 &project,
18014 self.buffer.read(cx).all_buffers(),
18015 self.buffer.clone(),
18016 cx,
18017 )
18018 .shared(),
18019 );
18020 }
18021 }
18022
18023 fn on_display_map_changed(
18024 &mut self,
18025 _: Entity<DisplayMap>,
18026 _: &mut Window,
18027 cx: &mut Context<Self>,
18028 ) {
18029 cx.notify();
18030 }
18031
18032 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18033 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
18034 self.update_edit_prediction_settings(cx);
18035 self.refresh_inline_completion(true, false, window, cx);
18036 self.refresh_inlay_hints(
18037 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
18038 self.selections.newest_anchor().head(),
18039 &self.buffer.read(cx).snapshot(cx),
18040 cx,
18041 )),
18042 cx,
18043 );
18044
18045 let old_cursor_shape = self.cursor_shape;
18046
18047 {
18048 let editor_settings = EditorSettings::get_global(cx);
18049 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
18050 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
18051 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
18052 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
18053 }
18054
18055 if old_cursor_shape != self.cursor_shape {
18056 cx.emit(EditorEvent::CursorShapeChanged);
18057 }
18058
18059 let project_settings = ProjectSettings::get_global(cx);
18060 self.serialize_dirty_buffers =
18061 !self.mode.is_minimap() && project_settings.session.restore_unsaved_buffers;
18062
18063 if self.mode.is_full() {
18064 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
18065 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
18066 if self.show_inline_diagnostics != show_inline_diagnostics {
18067 self.show_inline_diagnostics = show_inline_diagnostics;
18068 self.refresh_inline_diagnostics(false, window, cx);
18069 }
18070
18071 if self.git_blame_inline_enabled != inline_blame_enabled {
18072 self.toggle_git_blame_inline_internal(false, window, cx);
18073 }
18074
18075 let minimap_settings = EditorSettings::get_global(cx).minimap;
18076 if self.show_minimap != minimap_settings.minimap_enabled() {
18077 self.set_show_minimap(!self.show_minimap, window, cx);
18078 } else if let Some(minimap_entity) = self.minimap.as_ref() {
18079 minimap_entity.update(cx, |minimap_editor, cx| {
18080 minimap_editor.update_minimap_configuration(minimap_settings, cx)
18081 })
18082 }
18083 }
18084
18085 cx.notify();
18086 }
18087
18088 pub fn set_searchable(&mut self, searchable: bool) {
18089 self.searchable = searchable;
18090 }
18091
18092 pub fn searchable(&self) -> bool {
18093 self.searchable
18094 }
18095
18096 fn open_proposed_changes_editor(
18097 &mut self,
18098 _: &OpenProposedChangesEditor,
18099 window: &mut Window,
18100 cx: &mut Context<Self>,
18101 ) {
18102 let Some(workspace) = self.workspace() else {
18103 cx.propagate();
18104 return;
18105 };
18106
18107 let selections = self.selections.all::<usize>(cx);
18108 let multi_buffer = self.buffer.read(cx);
18109 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
18110 let mut new_selections_by_buffer = HashMap::default();
18111 for selection in selections {
18112 for (buffer, range, _) in
18113 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
18114 {
18115 let mut range = range.to_point(buffer);
18116 range.start.column = 0;
18117 range.end.column = buffer.line_len(range.end.row);
18118 new_selections_by_buffer
18119 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
18120 .or_insert(Vec::new())
18121 .push(range)
18122 }
18123 }
18124
18125 let proposed_changes_buffers = new_selections_by_buffer
18126 .into_iter()
18127 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
18128 .collect::<Vec<_>>();
18129 let proposed_changes_editor = cx.new(|cx| {
18130 ProposedChangesEditor::new(
18131 "Proposed changes",
18132 proposed_changes_buffers,
18133 self.project.clone(),
18134 window,
18135 cx,
18136 )
18137 });
18138
18139 window.defer(cx, move |window, cx| {
18140 workspace.update(cx, |workspace, cx| {
18141 workspace.active_pane().update(cx, |pane, cx| {
18142 pane.add_item(
18143 Box::new(proposed_changes_editor),
18144 true,
18145 true,
18146 None,
18147 window,
18148 cx,
18149 );
18150 });
18151 });
18152 });
18153 }
18154
18155 pub fn open_excerpts_in_split(
18156 &mut self,
18157 _: &OpenExcerptsSplit,
18158 window: &mut Window,
18159 cx: &mut Context<Self>,
18160 ) {
18161 self.open_excerpts_common(None, true, window, cx)
18162 }
18163
18164 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
18165 self.open_excerpts_common(None, false, window, cx)
18166 }
18167
18168 fn open_excerpts_common(
18169 &mut self,
18170 jump_data: Option<JumpData>,
18171 split: bool,
18172 window: &mut Window,
18173 cx: &mut Context<Self>,
18174 ) {
18175 let Some(workspace) = self.workspace() else {
18176 cx.propagate();
18177 return;
18178 };
18179
18180 if self.buffer.read(cx).is_singleton() {
18181 cx.propagate();
18182 return;
18183 }
18184
18185 let mut new_selections_by_buffer = HashMap::default();
18186 match &jump_data {
18187 Some(JumpData::MultiBufferPoint {
18188 excerpt_id,
18189 position,
18190 anchor,
18191 line_offset_from_top,
18192 }) => {
18193 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
18194 if let Some(buffer) = multi_buffer_snapshot
18195 .buffer_id_for_excerpt(*excerpt_id)
18196 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
18197 {
18198 let buffer_snapshot = buffer.read(cx).snapshot();
18199 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
18200 language::ToPoint::to_point(anchor, &buffer_snapshot)
18201 } else {
18202 buffer_snapshot.clip_point(*position, Bias::Left)
18203 };
18204 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
18205 new_selections_by_buffer.insert(
18206 buffer,
18207 (
18208 vec![jump_to_offset..jump_to_offset],
18209 Some(*line_offset_from_top),
18210 ),
18211 );
18212 }
18213 }
18214 Some(JumpData::MultiBufferRow {
18215 row,
18216 line_offset_from_top,
18217 }) => {
18218 let point = MultiBufferPoint::new(row.0, 0);
18219 if let Some((buffer, buffer_point, _)) =
18220 self.buffer.read(cx).point_to_buffer_point(point, cx)
18221 {
18222 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
18223 new_selections_by_buffer
18224 .entry(buffer)
18225 .or_insert((Vec::new(), Some(*line_offset_from_top)))
18226 .0
18227 .push(buffer_offset..buffer_offset)
18228 }
18229 }
18230 None => {
18231 let selections = self.selections.all::<usize>(cx);
18232 let multi_buffer = self.buffer.read(cx);
18233 for selection in selections {
18234 for (snapshot, range, _, anchor) in multi_buffer
18235 .snapshot(cx)
18236 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
18237 {
18238 if let Some(anchor) = anchor {
18239 // selection is in a deleted hunk
18240 let Some(buffer_id) = anchor.buffer_id else {
18241 continue;
18242 };
18243 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
18244 continue;
18245 };
18246 let offset = text::ToOffset::to_offset(
18247 &anchor.text_anchor,
18248 &buffer_handle.read(cx).snapshot(),
18249 );
18250 let range = offset..offset;
18251 new_selections_by_buffer
18252 .entry(buffer_handle)
18253 .or_insert((Vec::new(), None))
18254 .0
18255 .push(range)
18256 } else {
18257 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
18258 else {
18259 continue;
18260 };
18261 new_selections_by_buffer
18262 .entry(buffer_handle)
18263 .or_insert((Vec::new(), None))
18264 .0
18265 .push(range)
18266 }
18267 }
18268 }
18269 }
18270 }
18271
18272 new_selections_by_buffer
18273 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
18274
18275 if new_selections_by_buffer.is_empty() {
18276 return;
18277 }
18278
18279 // We defer the pane interaction because we ourselves are a workspace item
18280 // and activating a new item causes the pane to call a method on us reentrantly,
18281 // which panics if we're on the stack.
18282 window.defer(cx, move |window, cx| {
18283 workspace.update(cx, |workspace, cx| {
18284 let pane = if split {
18285 workspace.adjacent_pane(window, cx)
18286 } else {
18287 workspace.active_pane().clone()
18288 };
18289
18290 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
18291 let editor = buffer
18292 .read(cx)
18293 .file()
18294 .is_none()
18295 .then(|| {
18296 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
18297 // so `workspace.open_project_item` will never find them, always opening a new editor.
18298 // Instead, we try to activate the existing editor in the pane first.
18299 let (editor, pane_item_index) =
18300 pane.read(cx).items().enumerate().find_map(|(i, item)| {
18301 let editor = item.downcast::<Editor>()?;
18302 let singleton_buffer =
18303 editor.read(cx).buffer().read(cx).as_singleton()?;
18304 if singleton_buffer == buffer {
18305 Some((editor, i))
18306 } else {
18307 None
18308 }
18309 })?;
18310 pane.update(cx, |pane, cx| {
18311 pane.activate_item(pane_item_index, true, true, window, cx)
18312 });
18313 Some(editor)
18314 })
18315 .flatten()
18316 .unwrap_or_else(|| {
18317 workspace.open_project_item::<Self>(
18318 pane.clone(),
18319 buffer,
18320 true,
18321 true,
18322 window,
18323 cx,
18324 )
18325 });
18326
18327 editor.update(cx, |editor, cx| {
18328 let autoscroll = match scroll_offset {
18329 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
18330 None => Autoscroll::newest(),
18331 };
18332 let nav_history = editor.nav_history.take();
18333 editor.change_selections(Some(autoscroll), window, cx, |s| {
18334 s.select_ranges(ranges);
18335 });
18336 editor.nav_history = nav_history;
18337 });
18338 }
18339 })
18340 });
18341 }
18342
18343 // For now, don't allow opening excerpts in buffers that aren't backed by
18344 // regular project files.
18345 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
18346 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
18347 }
18348
18349 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
18350 let snapshot = self.buffer.read(cx).read(cx);
18351 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
18352 Some(
18353 ranges
18354 .iter()
18355 .map(move |range| {
18356 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
18357 })
18358 .collect(),
18359 )
18360 }
18361
18362 fn selection_replacement_ranges(
18363 &self,
18364 range: Range<OffsetUtf16>,
18365 cx: &mut App,
18366 ) -> Vec<Range<OffsetUtf16>> {
18367 let selections = self.selections.all::<OffsetUtf16>(cx);
18368 let newest_selection = selections
18369 .iter()
18370 .max_by_key(|selection| selection.id)
18371 .unwrap();
18372 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
18373 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
18374 let snapshot = self.buffer.read(cx).read(cx);
18375 selections
18376 .into_iter()
18377 .map(|mut selection| {
18378 selection.start.0 =
18379 (selection.start.0 as isize).saturating_add(start_delta) as usize;
18380 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
18381 snapshot.clip_offset_utf16(selection.start, Bias::Left)
18382 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
18383 })
18384 .collect()
18385 }
18386
18387 fn report_editor_event(
18388 &self,
18389 event_type: &'static str,
18390 file_extension: Option<String>,
18391 cx: &App,
18392 ) {
18393 if cfg!(any(test, feature = "test-support")) {
18394 return;
18395 }
18396
18397 let Some(project) = &self.project else { return };
18398
18399 // If None, we are in a file without an extension
18400 let file = self
18401 .buffer
18402 .read(cx)
18403 .as_singleton()
18404 .and_then(|b| b.read(cx).file());
18405 let file_extension = file_extension.or(file
18406 .as_ref()
18407 .and_then(|file| Path::new(file.file_name(cx)).extension())
18408 .and_then(|e| e.to_str())
18409 .map(|a| a.to_string()));
18410
18411 let vim_mode = vim_enabled(cx);
18412
18413 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
18414 let copilot_enabled = edit_predictions_provider
18415 == language::language_settings::EditPredictionProvider::Copilot;
18416 let copilot_enabled_for_language = self
18417 .buffer
18418 .read(cx)
18419 .language_settings(cx)
18420 .show_edit_predictions;
18421
18422 let project = project.read(cx);
18423 telemetry::event!(
18424 event_type,
18425 file_extension,
18426 vim_mode,
18427 copilot_enabled,
18428 copilot_enabled_for_language,
18429 edit_predictions_provider,
18430 is_via_ssh = project.is_via_ssh(),
18431 );
18432 }
18433
18434 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
18435 /// with each line being an array of {text, highlight} objects.
18436 fn copy_highlight_json(
18437 &mut self,
18438 _: &CopyHighlightJson,
18439 window: &mut Window,
18440 cx: &mut Context<Self>,
18441 ) {
18442 #[derive(Serialize)]
18443 struct Chunk<'a> {
18444 text: String,
18445 highlight: Option<&'a str>,
18446 }
18447
18448 let snapshot = self.buffer.read(cx).snapshot(cx);
18449 let range = self
18450 .selected_text_range(false, window, cx)
18451 .and_then(|selection| {
18452 if selection.range.is_empty() {
18453 None
18454 } else {
18455 Some(selection.range)
18456 }
18457 })
18458 .unwrap_or_else(|| 0..snapshot.len());
18459
18460 let chunks = snapshot.chunks(range, true);
18461 let mut lines = Vec::new();
18462 let mut line: VecDeque<Chunk> = VecDeque::new();
18463
18464 let Some(style) = self.style.as_ref() else {
18465 return;
18466 };
18467
18468 for chunk in chunks {
18469 let highlight = chunk
18470 .syntax_highlight_id
18471 .and_then(|id| id.name(&style.syntax));
18472 let mut chunk_lines = chunk.text.split('\n').peekable();
18473 while let Some(text) = chunk_lines.next() {
18474 let mut merged_with_last_token = false;
18475 if let Some(last_token) = line.back_mut() {
18476 if last_token.highlight == highlight {
18477 last_token.text.push_str(text);
18478 merged_with_last_token = true;
18479 }
18480 }
18481
18482 if !merged_with_last_token {
18483 line.push_back(Chunk {
18484 text: text.into(),
18485 highlight,
18486 });
18487 }
18488
18489 if chunk_lines.peek().is_some() {
18490 if line.len() > 1 && line.front().unwrap().text.is_empty() {
18491 line.pop_front();
18492 }
18493 if line.len() > 1 && line.back().unwrap().text.is_empty() {
18494 line.pop_back();
18495 }
18496
18497 lines.push(mem::take(&mut line));
18498 }
18499 }
18500 }
18501
18502 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
18503 return;
18504 };
18505 cx.write_to_clipboard(ClipboardItem::new_string(lines));
18506 }
18507
18508 pub fn open_context_menu(
18509 &mut self,
18510 _: &OpenContextMenu,
18511 window: &mut Window,
18512 cx: &mut Context<Self>,
18513 ) {
18514 self.request_autoscroll(Autoscroll::newest(), cx);
18515 let position = self.selections.newest_display(cx).start;
18516 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
18517 }
18518
18519 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
18520 &self.inlay_hint_cache
18521 }
18522
18523 pub fn replay_insert_event(
18524 &mut self,
18525 text: &str,
18526 relative_utf16_range: Option<Range<isize>>,
18527 window: &mut Window,
18528 cx: &mut Context<Self>,
18529 ) {
18530 if !self.input_enabled {
18531 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18532 return;
18533 }
18534 if let Some(relative_utf16_range) = relative_utf16_range {
18535 let selections = self.selections.all::<OffsetUtf16>(cx);
18536 self.change_selections(None, window, cx, |s| {
18537 let new_ranges = selections.into_iter().map(|range| {
18538 let start = OffsetUtf16(
18539 range
18540 .head()
18541 .0
18542 .saturating_add_signed(relative_utf16_range.start),
18543 );
18544 let end = OffsetUtf16(
18545 range
18546 .head()
18547 .0
18548 .saturating_add_signed(relative_utf16_range.end),
18549 );
18550 start..end
18551 });
18552 s.select_ranges(new_ranges);
18553 });
18554 }
18555
18556 self.handle_input(text, window, cx);
18557 }
18558
18559 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18560 let Some(provider) = self.semantics_provider.as_ref() else {
18561 return false;
18562 };
18563
18564 let mut supports = false;
18565 self.buffer().update(cx, |this, cx| {
18566 this.for_each_buffer(|buffer| {
18567 supports |= provider.supports_inlay_hints(buffer, cx);
18568 });
18569 });
18570
18571 supports
18572 }
18573
18574 pub fn is_focused(&self, window: &Window) -> bool {
18575 self.focus_handle.is_focused(window)
18576 }
18577
18578 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18579 cx.emit(EditorEvent::Focused);
18580
18581 if let Some(descendant) = self
18582 .last_focused_descendant
18583 .take()
18584 .and_then(|descendant| descendant.upgrade())
18585 {
18586 window.focus(&descendant);
18587 } else {
18588 if let Some(blame) = self.blame.as_ref() {
18589 blame.update(cx, GitBlame::focus)
18590 }
18591
18592 self.blink_manager.update(cx, BlinkManager::enable);
18593 self.show_cursor_names(window, cx);
18594 self.buffer.update(cx, |buffer, cx| {
18595 buffer.finalize_last_transaction(cx);
18596 if self.leader_id.is_none() {
18597 buffer.set_active_selections(
18598 &self.selections.disjoint_anchors(),
18599 self.selections.line_mode,
18600 self.cursor_shape,
18601 cx,
18602 );
18603 }
18604 });
18605 }
18606 }
18607
18608 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18609 cx.emit(EditorEvent::FocusedIn)
18610 }
18611
18612 fn handle_focus_out(
18613 &mut self,
18614 event: FocusOutEvent,
18615 _window: &mut Window,
18616 cx: &mut Context<Self>,
18617 ) {
18618 if event.blurred != self.focus_handle {
18619 self.last_focused_descendant = Some(event.blurred);
18620 }
18621 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18622 }
18623
18624 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18625 self.blink_manager.update(cx, BlinkManager::disable);
18626 self.buffer
18627 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18628
18629 if let Some(blame) = self.blame.as_ref() {
18630 blame.update(cx, GitBlame::blur)
18631 }
18632 if !self.hover_state.focused(window, cx) {
18633 hide_hover(self, cx);
18634 }
18635 if !self
18636 .context_menu
18637 .borrow()
18638 .as_ref()
18639 .is_some_and(|context_menu| context_menu.focused(window, cx))
18640 {
18641 self.hide_context_menu(window, cx);
18642 }
18643 self.discard_inline_completion(false, cx);
18644 cx.emit(EditorEvent::Blurred);
18645 cx.notify();
18646 }
18647
18648 pub fn register_action<A: Action>(
18649 &mut self,
18650 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18651 ) -> Subscription {
18652 let id = self.next_editor_action_id.post_inc();
18653 let listener = Arc::new(listener);
18654 self.editor_actions.borrow_mut().insert(
18655 id,
18656 Box::new(move |window, _| {
18657 let listener = listener.clone();
18658 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18659 let action = action.downcast_ref().unwrap();
18660 if phase == DispatchPhase::Bubble {
18661 listener(action, window, cx)
18662 }
18663 })
18664 }),
18665 );
18666
18667 let editor_actions = self.editor_actions.clone();
18668 Subscription::new(move || {
18669 editor_actions.borrow_mut().remove(&id);
18670 })
18671 }
18672
18673 pub fn file_header_size(&self) -> u32 {
18674 FILE_HEADER_HEIGHT
18675 }
18676
18677 pub fn restore(
18678 &mut self,
18679 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18680 window: &mut Window,
18681 cx: &mut Context<Self>,
18682 ) {
18683 let workspace = self.workspace();
18684 let project = self.project.as_ref();
18685 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18686 let mut tasks = Vec::new();
18687 for (buffer_id, changes) in revert_changes {
18688 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18689 buffer.update(cx, |buffer, cx| {
18690 buffer.edit(
18691 changes
18692 .into_iter()
18693 .map(|(range, text)| (range, text.to_string())),
18694 None,
18695 cx,
18696 );
18697 });
18698
18699 if let Some(project) =
18700 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18701 {
18702 project.update(cx, |project, cx| {
18703 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18704 })
18705 }
18706 }
18707 }
18708 tasks
18709 });
18710 cx.spawn_in(window, async move |_, cx| {
18711 for (buffer, task) in save_tasks {
18712 let result = task.await;
18713 if result.is_err() {
18714 let Some(path) = buffer
18715 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18716 .ok()
18717 else {
18718 continue;
18719 };
18720 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18721 let Some(task) = cx
18722 .update_window_entity(&workspace, |workspace, window, cx| {
18723 workspace
18724 .open_path_preview(path, None, false, false, false, window, cx)
18725 })
18726 .ok()
18727 else {
18728 continue;
18729 };
18730 task.await.log_err();
18731 }
18732 }
18733 }
18734 })
18735 .detach();
18736 self.change_selections(None, window, cx, |selections| selections.refresh());
18737 }
18738
18739 pub fn to_pixel_point(
18740 &self,
18741 source: multi_buffer::Anchor,
18742 editor_snapshot: &EditorSnapshot,
18743 window: &mut Window,
18744 ) -> Option<gpui::Point<Pixels>> {
18745 let source_point = source.to_display_point(editor_snapshot);
18746 self.display_to_pixel_point(source_point, editor_snapshot, window)
18747 }
18748
18749 pub fn display_to_pixel_point(
18750 &self,
18751 source: DisplayPoint,
18752 editor_snapshot: &EditorSnapshot,
18753 window: &mut Window,
18754 ) -> Option<gpui::Point<Pixels>> {
18755 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18756 let text_layout_details = self.text_layout_details(window);
18757 let scroll_top = text_layout_details
18758 .scroll_anchor
18759 .scroll_position(editor_snapshot)
18760 .y;
18761
18762 if source.row().as_f32() < scroll_top.floor() {
18763 return None;
18764 }
18765 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18766 let source_y = line_height * (source.row().as_f32() - scroll_top);
18767 Some(gpui::Point::new(source_x, source_y))
18768 }
18769
18770 pub fn has_visible_completions_menu(&self) -> bool {
18771 !self.edit_prediction_preview_is_active()
18772 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18773 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18774 })
18775 }
18776
18777 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18778 if self.mode.is_minimap() {
18779 return;
18780 }
18781 self.addons
18782 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18783 }
18784
18785 pub fn unregister_addon<T: Addon>(&mut self) {
18786 self.addons.remove(&std::any::TypeId::of::<T>());
18787 }
18788
18789 pub fn addon<T: Addon>(&self) -> Option<&T> {
18790 let type_id = std::any::TypeId::of::<T>();
18791 self.addons
18792 .get(&type_id)
18793 .and_then(|item| item.to_any().downcast_ref::<T>())
18794 }
18795
18796 pub fn addon_mut<T: Addon>(&mut self) -> Option<&mut T> {
18797 let type_id = std::any::TypeId::of::<T>();
18798 self.addons
18799 .get_mut(&type_id)
18800 .and_then(|item| item.to_any_mut()?.downcast_mut::<T>())
18801 }
18802
18803 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18804 let text_layout_details = self.text_layout_details(window);
18805 let style = &text_layout_details.editor_style;
18806 let font_id = window.text_system().resolve_font(&style.text.font());
18807 let font_size = style.text.font_size.to_pixels(window.rem_size());
18808 let line_height = style.text.line_height_in_pixels(window.rem_size());
18809 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18810
18811 gpui::Size::new(em_width, line_height)
18812 }
18813
18814 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18815 self.load_diff_task.clone()
18816 }
18817
18818 fn read_metadata_from_db(
18819 &mut self,
18820 item_id: u64,
18821 workspace_id: WorkspaceId,
18822 window: &mut Window,
18823 cx: &mut Context<Editor>,
18824 ) {
18825 if self.is_singleton(cx)
18826 && !self.mode.is_minimap()
18827 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18828 {
18829 let buffer_snapshot = OnceCell::new();
18830
18831 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18832 if !folds.is_empty() {
18833 let snapshot =
18834 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18835 self.fold_ranges(
18836 folds
18837 .into_iter()
18838 .map(|(start, end)| {
18839 snapshot.clip_offset(start, Bias::Left)
18840 ..snapshot.clip_offset(end, Bias::Right)
18841 })
18842 .collect(),
18843 false,
18844 window,
18845 cx,
18846 );
18847 }
18848 }
18849
18850 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18851 if !selections.is_empty() {
18852 let snapshot =
18853 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18854 self.change_selections(None, window, cx, |s| {
18855 s.select_ranges(selections.into_iter().map(|(start, end)| {
18856 snapshot.clip_offset(start, Bias::Left)
18857 ..snapshot.clip_offset(end, Bias::Right)
18858 }));
18859 });
18860 }
18861 };
18862 }
18863
18864 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18865 }
18866}
18867
18868fn vim_enabled(cx: &App) -> bool {
18869 cx.global::<SettingsStore>()
18870 .raw_user_settings()
18871 .get("vim_mode")
18872 == Some(&serde_json::Value::Bool(true))
18873}
18874
18875// Consider user intent and default settings
18876fn choose_completion_range(
18877 completion: &Completion,
18878 intent: CompletionIntent,
18879 buffer: &Entity<Buffer>,
18880 cx: &mut Context<Editor>,
18881) -> Range<usize> {
18882 fn should_replace(
18883 completion: &Completion,
18884 insert_range: &Range<text::Anchor>,
18885 intent: CompletionIntent,
18886 completion_mode_setting: LspInsertMode,
18887 buffer: &Buffer,
18888 ) -> bool {
18889 // specific actions take precedence over settings
18890 match intent {
18891 CompletionIntent::CompleteWithInsert => return false,
18892 CompletionIntent::CompleteWithReplace => return true,
18893 CompletionIntent::Complete | CompletionIntent::Compose => {}
18894 }
18895
18896 match completion_mode_setting {
18897 LspInsertMode::Insert => false,
18898 LspInsertMode::Replace => true,
18899 LspInsertMode::ReplaceSubsequence => {
18900 let mut text_to_replace = buffer.chars_for_range(
18901 buffer.anchor_before(completion.replace_range.start)
18902 ..buffer.anchor_after(completion.replace_range.end),
18903 );
18904 let mut completion_text = completion.new_text.chars();
18905
18906 // is `text_to_replace` a subsequence of `completion_text`
18907 text_to_replace
18908 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18909 }
18910 LspInsertMode::ReplaceSuffix => {
18911 let range_after_cursor = insert_range.end..completion.replace_range.end;
18912
18913 let text_after_cursor = buffer
18914 .text_for_range(
18915 buffer.anchor_before(range_after_cursor.start)
18916 ..buffer.anchor_after(range_after_cursor.end),
18917 )
18918 .collect::<String>();
18919 completion.new_text.ends_with(&text_after_cursor)
18920 }
18921 }
18922 }
18923
18924 let buffer = buffer.read(cx);
18925
18926 if let CompletionSource::Lsp {
18927 insert_range: Some(insert_range),
18928 ..
18929 } = &completion.source
18930 {
18931 let completion_mode_setting =
18932 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18933 .completions
18934 .lsp_insert_mode;
18935
18936 if !should_replace(
18937 completion,
18938 &insert_range,
18939 intent,
18940 completion_mode_setting,
18941 buffer,
18942 ) {
18943 return insert_range.to_offset(buffer);
18944 }
18945 }
18946
18947 completion.replace_range.to_offset(buffer)
18948}
18949
18950fn insert_extra_newline_brackets(
18951 buffer: &MultiBufferSnapshot,
18952 range: Range<usize>,
18953 language: &language::LanguageScope,
18954) -> bool {
18955 let leading_whitespace_len = buffer
18956 .reversed_chars_at(range.start)
18957 .take_while(|c| c.is_whitespace() && *c != '\n')
18958 .map(|c| c.len_utf8())
18959 .sum::<usize>();
18960 let trailing_whitespace_len = buffer
18961 .chars_at(range.end)
18962 .take_while(|c| c.is_whitespace() && *c != '\n')
18963 .map(|c| c.len_utf8())
18964 .sum::<usize>();
18965 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18966
18967 language.brackets().any(|(pair, enabled)| {
18968 let pair_start = pair.start.trim_end();
18969 let pair_end = pair.end.trim_start();
18970
18971 enabled
18972 && pair.newline
18973 && buffer.contains_str_at(range.end, pair_end)
18974 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18975 })
18976}
18977
18978fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18979 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18980 [(buffer, range, _)] => (*buffer, range.clone()),
18981 _ => return false,
18982 };
18983 let pair = {
18984 let mut result: Option<BracketMatch> = None;
18985
18986 for pair in buffer
18987 .all_bracket_ranges(range.clone())
18988 .filter(move |pair| {
18989 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18990 })
18991 {
18992 let len = pair.close_range.end - pair.open_range.start;
18993
18994 if let Some(existing) = &result {
18995 let existing_len = existing.close_range.end - existing.open_range.start;
18996 if len > existing_len {
18997 continue;
18998 }
18999 }
19000
19001 result = Some(pair);
19002 }
19003
19004 result
19005 };
19006 let Some(pair) = pair else {
19007 return false;
19008 };
19009 pair.newline_only
19010 && buffer
19011 .chars_for_range(pair.open_range.end..range.start)
19012 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
19013 .all(|c| c.is_whitespace() && c != '\n')
19014}
19015
19016fn update_uncommitted_diff_for_buffer(
19017 editor: Entity<Editor>,
19018 project: &Entity<Project>,
19019 buffers: impl IntoIterator<Item = Entity<Buffer>>,
19020 buffer: Entity<MultiBuffer>,
19021 cx: &mut App,
19022) -> Task<()> {
19023 let mut tasks = Vec::new();
19024 project.update(cx, |project, cx| {
19025 for buffer in buffers {
19026 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
19027 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
19028 }
19029 }
19030 });
19031 cx.spawn(async move |cx| {
19032 let diffs = future::join_all(tasks).await;
19033 if editor
19034 .read_with(cx, |editor, _cx| editor.temporary_diff_override)
19035 .unwrap_or(false)
19036 {
19037 return;
19038 }
19039
19040 buffer
19041 .update(cx, |buffer, cx| {
19042 for diff in diffs.into_iter().flatten() {
19043 buffer.add_diff(diff, cx);
19044 }
19045 })
19046 .ok();
19047 })
19048}
19049
19050fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
19051 let tab_size = tab_size.get() as usize;
19052 let mut width = offset;
19053
19054 for ch in text.chars() {
19055 width += if ch == '\t' {
19056 tab_size - (width % tab_size)
19057 } else {
19058 1
19059 };
19060 }
19061
19062 width - offset
19063}
19064
19065#[cfg(test)]
19066mod tests {
19067 use super::*;
19068
19069 #[test]
19070 fn test_string_size_with_expanded_tabs() {
19071 let nz = |val| NonZeroU32::new(val).unwrap();
19072 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
19073 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
19074 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
19075 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
19076 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
19077 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
19078 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
19079 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
19080 }
19081}
19082
19083/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
19084struct WordBreakingTokenizer<'a> {
19085 input: &'a str,
19086}
19087
19088impl<'a> WordBreakingTokenizer<'a> {
19089 fn new(input: &'a str) -> Self {
19090 Self { input }
19091 }
19092}
19093
19094fn is_char_ideographic(ch: char) -> bool {
19095 use unicode_script::Script::*;
19096 use unicode_script::UnicodeScript;
19097 matches!(ch.script(), Han | Tangut | Yi)
19098}
19099
19100fn is_grapheme_ideographic(text: &str) -> bool {
19101 text.chars().any(is_char_ideographic)
19102}
19103
19104fn is_grapheme_whitespace(text: &str) -> bool {
19105 text.chars().any(|x| x.is_whitespace())
19106}
19107
19108fn should_stay_with_preceding_ideograph(text: &str) -> bool {
19109 text.chars().next().map_or(false, |ch| {
19110 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
19111 })
19112}
19113
19114#[derive(PartialEq, Eq, Debug, Clone, Copy)]
19115enum WordBreakToken<'a> {
19116 Word { token: &'a str, grapheme_len: usize },
19117 InlineWhitespace { token: &'a str, grapheme_len: usize },
19118 Newline,
19119}
19120
19121impl<'a> Iterator for WordBreakingTokenizer<'a> {
19122 /// Yields a span, the count of graphemes in the token, and whether it was
19123 /// whitespace. Note that it also breaks at word boundaries.
19124 type Item = WordBreakToken<'a>;
19125
19126 fn next(&mut self) -> Option<Self::Item> {
19127 use unicode_segmentation::UnicodeSegmentation;
19128 if self.input.is_empty() {
19129 return None;
19130 }
19131
19132 let mut iter = self.input.graphemes(true).peekable();
19133 let mut offset = 0;
19134 let mut grapheme_len = 0;
19135 if let Some(first_grapheme) = iter.next() {
19136 let is_newline = first_grapheme == "\n";
19137 let is_whitespace = is_grapheme_whitespace(first_grapheme);
19138 offset += first_grapheme.len();
19139 grapheme_len += 1;
19140 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
19141 if let Some(grapheme) = iter.peek().copied() {
19142 if should_stay_with_preceding_ideograph(grapheme) {
19143 offset += grapheme.len();
19144 grapheme_len += 1;
19145 }
19146 }
19147 } else {
19148 let mut words = self.input[offset..].split_word_bound_indices().peekable();
19149 let mut next_word_bound = words.peek().copied();
19150 if next_word_bound.map_or(false, |(i, _)| i == 0) {
19151 next_word_bound = words.next();
19152 }
19153 while let Some(grapheme) = iter.peek().copied() {
19154 if next_word_bound.map_or(false, |(i, _)| i == offset) {
19155 break;
19156 };
19157 if is_grapheme_whitespace(grapheme) != is_whitespace
19158 || (grapheme == "\n") != is_newline
19159 {
19160 break;
19161 };
19162 offset += grapheme.len();
19163 grapheme_len += 1;
19164 iter.next();
19165 }
19166 }
19167 let token = &self.input[..offset];
19168 self.input = &self.input[offset..];
19169 if token == "\n" {
19170 Some(WordBreakToken::Newline)
19171 } else if is_whitespace {
19172 Some(WordBreakToken::InlineWhitespace {
19173 token,
19174 grapheme_len,
19175 })
19176 } else {
19177 Some(WordBreakToken::Word {
19178 token,
19179 grapheme_len,
19180 })
19181 }
19182 } else {
19183 None
19184 }
19185 }
19186}
19187
19188#[test]
19189fn test_word_breaking_tokenizer() {
19190 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
19191 ("", &[]),
19192 (" ", &[whitespace(" ", 2)]),
19193 ("Ʒ", &[word("Ʒ", 1)]),
19194 ("Ǽ", &[word("Ǽ", 1)]),
19195 ("⋑", &[word("⋑", 1)]),
19196 ("⋑⋑", &[word("⋑⋑", 2)]),
19197 (
19198 "原理,进而",
19199 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
19200 ),
19201 (
19202 "hello world",
19203 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
19204 ),
19205 (
19206 "hello, world",
19207 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
19208 ),
19209 (
19210 " hello world",
19211 &[
19212 whitespace(" ", 2),
19213 word("hello", 5),
19214 whitespace(" ", 1),
19215 word("world", 5),
19216 ],
19217 ),
19218 (
19219 "这是什么 \n 钢笔",
19220 &[
19221 word("这", 1),
19222 word("是", 1),
19223 word("什", 1),
19224 word("么", 1),
19225 whitespace(" ", 1),
19226 newline(),
19227 whitespace(" ", 1),
19228 word("钢", 1),
19229 word("笔", 1),
19230 ],
19231 ),
19232 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
19233 ];
19234
19235 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19236 WordBreakToken::Word {
19237 token,
19238 grapheme_len,
19239 }
19240 }
19241
19242 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
19243 WordBreakToken::InlineWhitespace {
19244 token,
19245 grapheme_len,
19246 }
19247 }
19248
19249 fn newline() -> WordBreakToken<'static> {
19250 WordBreakToken::Newline
19251 }
19252
19253 for (input, result) in tests {
19254 assert_eq!(
19255 WordBreakingTokenizer::new(input)
19256 .collect::<Vec<_>>()
19257 .as_slice(),
19258 *result,
19259 );
19260 }
19261}
19262
19263fn wrap_with_prefix(
19264 line_prefix: String,
19265 unwrapped_text: String,
19266 wrap_column: usize,
19267 tab_size: NonZeroU32,
19268 preserve_existing_whitespace: bool,
19269) -> String {
19270 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
19271 let mut wrapped_text = String::new();
19272 let mut current_line = line_prefix.clone();
19273
19274 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
19275 let mut current_line_len = line_prefix_len;
19276 let mut in_whitespace = false;
19277 for token in tokenizer {
19278 let have_preceding_whitespace = in_whitespace;
19279 match token {
19280 WordBreakToken::Word {
19281 token,
19282 grapheme_len,
19283 } => {
19284 in_whitespace = false;
19285 if current_line_len + grapheme_len > wrap_column
19286 && current_line_len != line_prefix_len
19287 {
19288 wrapped_text.push_str(current_line.trim_end());
19289 wrapped_text.push('\n');
19290 current_line.truncate(line_prefix.len());
19291 current_line_len = line_prefix_len;
19292 }
19293 current_line.push_str(token);
19294 current_line_len += grapheme_len;
19295 }
19296 WordBreakToken::InlineWhitespace {
19297 mut token,
19298 mut grapheme_len,
19299 } => {
19300 in_whitespace = true;
19301 if have_preceding_whitespace && !preserve_existing_whitespace {
19302 continue;
19303 }
19304 if !preserve_existing_whitespace {
19305 token = " ";
19306 grapheme_len = 1;
19307 }
19308 if current_line_len + grapheme_len > wrap_column {
19309 wrapped_text.push_str(current_line.trim_end());
19310 wrapped_text.push('\n');
19311 current_line.truncate(line_prefix.len());
19312 current_line_len = line_prefix_len;
19313 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
19314 current_line.push_str(token);
19315 current_line_len += grapheme_len;
19316 }
19317 }
19318 WordBreakToken::Newline => {
19319 in_whitespace = true;
19320 if preserve_existing_whitespace {
19321 wrapped_text.push_str(current_line.trim_end());
19322 wrapped_text.push('\n');
19323 current_line.truncate(line_prefix.len());
19324 current_line_len = line_prefix_len;
19325 } else if have_preceding_whitespace {
19326 continue;
19327 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
19328 {
19329 wrapped_text.push_str(current_line.trim_end());
19330 wrapped_text.push('\n');
19331 current_line.truncate(line_prefix.len());
19332 current_line_len = line_prefix_len;
19333 } else if current_line_len != line_prefix_len {
19334 current_line.push(' ');
19335 current_line_len += 1;
19336 }
19337 }
19338 }
19339 }
19340
19341 if !current_line.is_empty() {
19342 wrapped_text.push_str(¤t_line);
19343 }
19344 wrapped_text
19345}
19346
19347#[test]
19348fn test_wrap_with_prefix() {
19349 assert_eq!(
19350 wrap_with_prefix(
19351 "# ".to_string(),
19352 "abcdefg".to_string(),
19353 4,
19354 NonZeroU32::new(4).unwrap(),
19355 false,
19356 ),
19357 "# abcdefg"
19358 );
19359 assert_eq!(
19360 wrap_with_prefix(
19361 "".to_string(),
19362 "\thello world".to_string(),
19363 8,
19364 NonZeroU32::new(4).unwrap(),
19365 false,
19366 ),
19367 "hello\nworld"
19368 );
19369 assert_eq!(
19370 wrap_with_prefix(
19371 "// ".to_string(),
19372 "xx \nyy zz aa bb cc".to_string(),
19373 12,
19374 NonZeroU32::new(4).unwrap(),
19375 false,
19376 ),
19377 "// xx yy zz\n// aa bb cc"
19378 );
19379 assert_eq!(
19380 wrap_with_prefix(
19381 String::new(),
19382 "这是什么 \n 钢笔".to_string(),
19383 3,
19384 NonZeroU32::new(4).unwrap(),
19385 false,
19386 ),
19387 "这是什\n么 钢\n笔"
19388 );
19389}
19390
19391pub trait CollaborationHub {
19392 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
19393 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
19394 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
19395}
19396
19397impl CollaborationHub for Entity<Project> {
19398 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
19399 self.read(cx).collaborators()
19400 }
19401
19402 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
19403 self.read(cx).user_store().read(cx).participant_indices()
19404 }
19405
19406 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
19407 let this = self.read(cx);
19408 let user_ids = this.collaborators().values().map(|c| c.user_id);
19409 this.user_store().read_with(cx, |user_store, cx| {
19410 user_store.participant_names(user_ids, cx)
19411 })
19412 }
19413}
19414
19415pub trait SemanticsProvider {
19416 fn hover(
19417 &self,
19418 buffer: &Entity<Buffer>,
19419 position: text::Anchor,
19420 cx: &mut App,
19421 ) -> Option<Task<Vec<project::Hover>>>;
19422
19423 fn inline_values(
19424 &self,
19425 buffer_handle: Entity<Buffer>,
19426 range: Range<text::Anchor>,
19427 cx: &mut App,
19428 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19429
19430 fn inlay_hints(
19431 &self,
19432 buffer_handle: Entity<Buffer>,
19433 range: Range<text::Anchor>,
19434 cx: &mut App,
19435 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
19436
19437 fn resolve_inlay_hint(
19438 &self,
19439 hint: InlayHint,
19440 buffer_handle: Entity<Buffer>,
19441 server_id: LanguageServerId,
19442 cx: &mut App,
19443 ) -> Option<Task<anyhow::Result<InlayHint>>>;
19444
19445 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
19446
19447 fn document_highlights(
19448 &self,
19449 buffer: &Entity<Buffer>,
19450 position: text::Anchor,
19451 cx: &mut App,
19452 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
19453
19454 fn definitions(
19455 &self,
19456 buffer: &Entity<Buffer>,
19457 position: text::Anchor,
19458 kind: GotoDefinitionKind,
19459 cx: &mut App,
19460 ) -> Option<Task<Result<Vec<LocationLink>>>>;
19461
19462 fn range_for_rename(
19463 &self,
19464 buffer: &Entity<Buffer>,
19465 position: text::Anchor,
19466 cx: &mut App,
19467 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
19468
19469 fn perform_rename(
19470 &self,
19471 buffer: &Entity<Buffer>,
19472 position: text::Anchor,
19473 new_name: String,
19474 cx: &mut App,
19475 ) -> Option<Task<Result<ProjectTransaction>>>;
19476}
19477
19478pub trait CompletionProvider {
19479 fn completions(
19480 &self,
19481 excerpt_id: ExcerptId,
19482 buffer: &Entity<Buffer>,
19483 buffer_position: text::Anchor,
19484 trigger: CompletionContext,
19485 window: &mut Window,
19486 cx: &mut Context<Editor>,
19487 ) -> Task<Result<Option<Vec<Completion>>>>;
19488
19489 fn resolve_completions(
19490 &self,
19491 buffer: Entity<Buffer>,
19492 completion_indices: Vec<usize>,
19493 completions: Rc<RefCell<Box<[Completion]>>>,
19494 cx: &mut Context<Editor>,
19495 ) -> Task<Result<bool>>;
19496
19497 fn apply_additional_edits_for_completion(
19498 &self,
19499 _buffer: Entity<Buffer>,
19500 _completions: Rc<RefCell<Box<[Completion]>>>,
19501 _completion_index: usize,
19502 _push_to_history: bool,
19503 _cx: &mut Context<Editor>,
19504 ) -> Task<Result<Option<language::Transaction>>> {
19505 Task::ready(Ok(None))
19506 }
19507
19508 fn is_completion_trigger(
19509 &self,
19510 buffer: &Entity<Buffer>,
19511 position: language::Anchor,
19512 text: &str,
19513 trigger_in_words: bool,
19514 cx: &mut Context<Editor>,
19515 ) -> bool;
19516
19517 fn sort_completions(&self) -> bool {
19518 true
19519 }
19520
19521 fn filter_completions(&self) -> bool {
19522 true
19523 }
19524}
19525
19526pub trait CodeActionProvider {
19527 fn id(&self) -> Arc<str>;
19528
19529 fn code_actions(
19530 &self,
19531 buffer: &Entity<Buffer>,
19532 range: Range<text::Anchor>,
19533 window: &mut Window,
19534 cx: &mut App,
19535 ) -> Task<Result<Vec<CodeAction>>>;
19536
19537 fn apply_code_action(
19538 &self,
19539 buffer_handle: Entity<Buffer>,
19540 action: CodeAction,
19541 excerpt_id: ExcerptId,
19542 push_to_history: bool,
19543 window: &mut Window,
19544 cx: &mut App,
19545 ) -> Task<Result<ProjectTransaction>>;
19546}
19547
19548impl CodeActionProvider for Entity<Project> {
19549 fn id(&self) -> Arc<str> {
19550 "project".into()
19551 }
19552
19553 fn code_actions(
19554 &self,
19555 buffer: &Entity<Buffer>,
19556 range: Range<text::Anchor>,
19557 _window: &mut Window,
19558 cx: &mut App,
19559 ) -> Task<Result<Vec<CodeAction>>> {
19560 self.update(cx, |project, cx| {
19561 let code_lens = project.code_lens(buffer, range.clone(), cx);
19562 let code_actions = project.code_actions(buffer, range, None, cx);
19563 cx.background_spawn(async move {
19564 let (code_lens, code_actions) = join(code_lens, code_actions).await;
19565 Ok(code_lens
19566 .context("code lens fetch")?
19567 .into_iter()
19568 .chain(code_actions.context("code action fetch")?)
19569 .collect())
19570 })
19571 })
19572 }
19573
19574 fn apply_code_action(
19575 &self,
19576 buffer_handle: Entity<Buffer>,
19577 action: CodeAction,
19578 _excerpt_id: ExcerptId,
19579 push_to_history: bool,
19580 _window: &mut Window,
19581 cx: &mut App,
19582 ) -> Task<Result<ProjectTransaction>> {
19583 self.update(cx, |project, cx| {
19584 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19585 })
19586 }
19587}
19588
19589fn snippet_completions(
19590 project: &Project,
19591 buffer: &Entity<Buffer>,
19592 buffer_position: text::Anchor,
19593 cx: &mut App,
19594) -> Task<Result<Vec<Completion>>> {
19595 let languages = buffer.read(cx).languages_at(buffer_position);
19596 let snippet_store = project.snippets().read(cx);
19597
19598 let scopes: Vec<_> = languages
19599 .iter()
19600 .filter_map(|language| {
19601 let language_name = language.lsp_id();
19602 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19603
19604 if snippets.is_empty() {
19605 None
19606 } else {
19607 Some((language.default_scope(), snippets))
19608 }
19609 })
19610 .collect();
19611
19612 if scopes.is_empty() {
19613 return Task::ready(Ok(vec![]));
19614 }
19615
19616 let snapshot = buffer.read(cx).text_snapshot();
19617 let chars: String = snapshot
19618 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19619 .collect();
19620 let executor = cx.background_executor().clone();
19621
19622 cx.background_spawn(async move {
19623 let mut all_results: Vec<Completion> = Vec::new();
19624 for (scope, snippets) in scopes.into_iter() {
19625 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19626 let mut last_word = chars
19627 .chars()
19628 .take_while(|c| classifier.is_word(*c))
19629 .collect::<String>();
19630 last_word = last_word.chars().rev().collect();
19631
19632 if last_word.is_empty() {
19633 return Ok(vec![]);
19634 }
19635
19636 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19637 let to_lsp = |point: &text::Anchor| {
19638 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19639 point_to_lsp(end)
19640 };
19641 let lsp_end = to_lsp(&buffer_position);
19642
19643 let candidates = snippets
19644 .iter()
19645 .enumerate()
19646 .flat_map(|(ix, snippet)| {
19647 snippet
19648 .prefix
19649 .iter()
19650 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19651 })
19652 .collect::<Vec<StringMatchCandidate>>();
19653
19654 let mut matches = fuzzy::match_strings(
19655 &candidates,
19656 &last_word,
19657 last_word.chars().any(|c| c.is_uppercase()),
19658 100,
19659 &Default::default(),
19660 executor.clone(),
19661 )
19662 .await;
19663
19664 // Remove all candidates where the query's start does not match the start of any word in the candidate
19665 if let Some(query_start) = last_word.chars().next() {
19666 matches.retain(|string_match| {
19667 split_words(&string_match.string).any(|word| {
19668 // Check that the first codepoint of the word as lowercase matches the first
19669 // codepoint of the query as lowercase
19670 word.chars()
19671 .flat_map(|codepoint| codepoint.to_lowercase())
19672 .zip(query_start.to_lowercase())
19673 .all(|(word_cp, query_cp)| word_cp == query_cp)
19674 })
19675 });
19676 }
19677
19678 let matched_strings = matches
19679 .into_iter()
19680 .map(|m| m.string)
19681 .collect::<HashSet<_>>();
19682
19683 let mut result: Vec<Completion> = snippets
19684 .iter()
19685 .filter_map(|snippet| {
19686 let matching_prefix = snippet
19687 .prefix
19688 .iter()
19689 .find(|prefix| matched_strings.contains(*prefix))?;
19690 let start = as_offset - last_word.len();
19691 let start = snapshot.anchor_before(start);
19692 let range = start..buffer_position;
19693 let lsp_start = to_lsp(&start);
19694 let lsp_range = lsp::Range {
19695 start: lsp_start,
19696 end: lsp_end,
19697 };
19698 Some(Completion {
19699 replace_range: range,
19700 new_text: snippet.body.clone(),
19701 source: CompletionSource::Lsp {
19702 insert_range: None,
19703 server_id: LanguageServerId(usize::MAX),
19704 resolved: true,
19705 lsp_completion: Box::new(lsp::CompletionItem {
19706 label: snippet.prefix.first().unwrap().clone(),
19707 kind: Some(CompletionItemKind::SNIPPET),
19708 label_details: snippet.description.as_ref().map(|description| {
19709 lsp::CompletionItemLabelDetails {
19710 detail: Some(description.clone()),
19711 description: None,
19712 }
19713 }),
19714 insert_text_format: Some(InsertTextFormat::SNIPPET),
19715 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19716 lsp::InsertReplaceEdit {
19717 new_text: snippet.body.clone(),
19718 insert: lsp_range,
19719 replace: lsp_range,
19720 },
19721 )),
19722 filter_text: Some(snippet.body.clone()),
19723 sort_text: Some(char::MAX.to_string()),
19724 ..lsp::CompletionItem::default()
19725 }),
19726 lsp_defaults: None,
19727 },
19728 label: CodeLabel {
19729 text: matching_prefix.clone(),
19730 runs: Vec::new(),
19731 filter_range: 0..matching_prefix.len(),
19732 },
19733 icon_path: None,
19734 documentation: snippet.description.clone().map(|description| {
19735 CompletionDocumentation::SingleLine(description.into())
19736 }),
19737 insert_text_mode: None,
19738 confirm: None,
19739 })
19740 })
19741 .collect();
19742
19743 all_results.append(&mut result);
19744 }
19745
19746 Ok(all_results)
19747 })
19748}
19749
19750impl CompletionProvider for Entity<Project> {
19751 fn completions(
19752 &self,
19753 _excerpt_id: ExcerptId,
19754 buffer: &Entity<Buffer>,
19755 buffer_position: text::Anchor,
19756 options: CompletionContext,
19757 _window: &mut Window,
19758 cx: &mut Context<Editor>,
19759 ) -> Task<Result<Option<Vec<Completion>>>> {
19760 self.update(cx, |project, cx| {
19761 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19762 let project_completions = project.completions(buffer, buffer_position, options, cx);
19763 cx.background_spawn(async move {
19764 let snippets_completions = snippets.await?;
19765 match project_completions.await? {
19766 Some(mut completions) => {
19767 completions.extend(snippets_completions);
19768 Ok(Some(completions))
19769 }
19770 None => {
19771 if snippets_completions.is_empty() {
19772 Ok(None)
19773 } else {
19774 Ok(Some(snippets_completions))
19775 }
19776 }
19777 }
19778 })
19779 })
19780 }
19781
19782 fn resolve_completions(
19783 &self,
19784 buffer: Entity<Buffer>,
19785 completion_indices: Vec<usize>,
19786 completions: Rc<RefCell<Box<[Completion]>>>,
19787 cx: &mut Context<Editor>,
19788 ) -> Task<Result<bool>> {
19789 self.update(cx, |project, cx| {
19790 project.lsp_store().update(cx, |lsp_store, cx| {
19791 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19792 })
19793 })
19794 }
19795
19796 fn apply_additional_edits_for_completion(
19797 &self,
19798 buffer: Entity<Buffer>,
19799 completions: Rc<RefCell<Box<[Completion]>>>,
19800 completion_index: usize,
19801 push_to_history: bool,
19802 cx: &mut Context<Editor>,
19803 ) -> Task<Result<Option<language::Transaction>>> {
19804 self.update(cx, |project, cx| {
19805 project.lsp_store().update(cx, |lsp_store, cx| {
19806 lsp_store.apply_additional_edits_for_completion(
19807 buffer,
19808 completions,
19809 completion_index,
19810 push_to_history,
19811 cx,
19812 )
19813 })
19814 })
19815 }
19816
19817 fn is_completion_trigger(
19818 &self,
19819 buffer: &Entity<Buffer>,
19820 position: language::Anchor,
19821 text: &str,
19822 trigger_in_words: bool,
19823 cx: &mut Context<Editor>,
19824 ) -> bool {
19825 let mut chars = text.chars();
19826 let char = if let Some(char) = chars.next() {
19827 char
19828 } else {
19829 return false;
19830 };
19831 if chars.next().is_some() {
19832 return false;
19833 }
19834
19835 let buffer = buffer.read(cx);
19836 let snapshot = buffer.snapshot();
19837 if !snapshot.settings_at(position, cx).show_completions_on_input {
19838 return false;
19839 }
19840 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19841 if trigger_in_words && classifier.is_word(char) {
19842 return true;
19843 }
19844
19845 buffer.completion_triggers().contains(text)
19846 }
19847}
19848
19849impl SemanticsProvider for Entity<Project> {
19850 fn hover(
19851 &self,
19852 buffer: &Entity<Buffer>,
19853 position: text::Anchor,
19854 cx: &mut App,
19855 ) -> Option<Task<Vec<project::Hover>>> {
19856 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19857 }
19858
19859 fn document_highlights(
19860 &self,
19861 buffer: &Entity<Buffer>,
19862 position: text::Anchor,
19863 cx: &mut App,
19864 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19865 Some(self.update(cx, |project, cx| {
19866 project.document_highlights(buffer, position, cx)
19867 }))
19868 }
19869
19870 fn definitions(
19871 &self,
19872 buffer: &Entity<Buffer>,
19873 position: text::Anchor,
19874 kind: GotoDefinitionKind,
19875 cx: &mut App,
19876 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19877 Some(self.update(cx, |project, cx| match kind {
19878 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19879 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19880 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19881 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19882 }))
19883 }
19884
19885 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19886 // TODO: make this work for remote projects
19887 self.update(cx, |project, cx| {
19888 if project
19889 .active_debug_session(cx)
19890 .is_some_and(|(session, _)| session.read(cx).any_stopped_thread())
19891 {
19892 return true;
19893 }
19894
19895 buffer.update(cx, |buffer, cx| {
19896 project.any_language_server_supports_inlay_hints(buffer, cx)
19897 })
19898 })
19899 }
19900
19901 fn inline_values(
19902 &self,
19903 buffer_handle: Entity<Buffer>,
19904 range: Range<text::Anchor>,
19905 cx: &mut App,
19906 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19907 self.update(cx, |project, cx| {
19908 let (session, active_stack_frame) = project.active_debug_session(cx)?;
19909
19910 Some(project.inline_values(session, active_stack_frame, buffer_handle, range, cx))
19911 })
19912 }
19913
19914 fn inlay_hints(
19915 &self,
19916 buffer_handle: Entity<Buffer>,
19917 range: Range<text::Anchor>,
19918 cx: &mut App,
19919 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19920 Some(self.update(cx, |project, cx| {
19921 project.inlay_hints(buffer_handle, range, cx)
19922 }))
19923 }
19924
19925 fn resolve_inlay_hint(
19926 &self,
19927 hint: InlayHint,
19928 buffer_handle: Entity<Buffer>,
19929 server_id: LanguageServerId,
19930 cx: &mut App,
19931 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19932 Some(self.update(cx, |project, cx| {
19933 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19934 }))
19935 }
19936
19937 fn range_for_rename(
19938 &self,
19939 buffer: &Entity<Buffer>,
19940 position: text::Anchor,
19941 cx: &mut App,
19942 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19943 Some(self.update(cx, |project, cx| {
19944 let buffer = buffer.clone();
19945 let task = project.prepare_rename(buffer.clone(), position, cx);
19946 cx.spawn(async move |_, cx| {
19947 Ok(match task.await? {
19948 PrepareRenameResponse::Success(range) => Some(range),
19949 PrepareRenameResponse::InvalidPosition => None,
19950 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19951 // Fallback on using TreeSitter info to determine identifier range
19952 buffer.update(cx, |buffer, _| {
19953 let snapshot = buffer.snapshot();
19954 let (range, kind) = snapshot.surrounding_word(position);
19955 if kind != Some(CharKind::Word) {
19956 return None;
19957 }
19958 Some(
19959 snapshot.anchor_before(range.start)
19960 ..snapshot.anchor_after(range.end),
19961 )
19962 })?
19963 }
19964 })
19965 })
19966 }))
19967 }
19968
19969 fn perform_rename(
19970 &self,
19971 buffer: &Entity<Buffer>,
19972 position: text::Anchor,
19973 new_name: String,
19974 cx: &mut App,
19975 ) -> Option<Task<Result<ProjectTransaction>>> {
19976 Some(self.update(cx, |project, cx| {
19977 project.perform_rename(buffer.clone(), position, new_name, cx)
19978 }))
19979 }
19980}
19981
19982fn inlay_hint_settings(
19983 location: Anchor,
19984 snapshot: &MultiBufferSnapshot,
19985 cx: &mut Context<Editor>,
19986) -> InlayHintSettings {
19987 let file = snapshot.file_at(location);
19988 let language = snapshot.language_at(location).map(|l| l.name());
19989 language_settings(language, file, cx).inlay_hints
19990}
19991
19992fn consume_contiguous_rows(
19993 contiguous_row_selections: &mut Vec<Selection<Point>>,
19994 selection: &Selection<Point>,
19995 display_map: &DisplaySnapshot,
19996 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19997) -> (MultiBufferRow, MultiBufferRow) {
19998 contiguous_row_selections.push(selection.clone());
19999 let start_row = MultiBufferRow(selection.start.row);
20000 let mut end_row = ending_row(selection, display_map);
20001
20002 while let Some(next_selection) = selections.peek() {
20003 if next_selection.start.row <= end_row.0 {
20004 end_row = ending_row(next_selection, display_map);
20005 contiguous_row_selections.push(selections.next().unwrap().clone());
20006 } else {
20007 break;
20008 }
20009 }
20010 (start_row, end_row)
20011}
20012
20013fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
20014 if next_selection.end.column > 0 || next_selection.is_empty() {
20015 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
20016 } else {
20017 MultiBufferRow(next_selection.end.row)
20018 }
20019}
20020
20021impl EditorSnapshot {
20022 pub fn remote_selections_in_range<'a>(
20023 &'a self,
20024 range: &'a Range<Anchor>,
20025 collaboration_hub: &dyn CollaborationHub,
20026 cx: &'a App,
20027 ) -> impl 'a + Iterator<Item = RemoteSelection> {
20028 let participant_names = collaboration_hub.user_names(cx);
20029 let participant_indices = collaboration_hub.user_participant_indices(cx);
20030 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
20031 let collaborators_by_replica_id = collaborators_by_peer_id
20032 .iter()
20033 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
20034 .collect::<HashMap<_, _>>();
20035 self.buffer_snapshot
20036 .selections_in_range(range, false)
20037 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
20038 if replica_id == AGENT_REPLICA_ID {
20039 Some(RemoteSelection {
20040 replica_id,
20041 selection,
20042 cursor_shape,
20043 line_mode,
20044 collaborator_id: CollaboratorId::Agent,
20045 user_name: Some("Agent".into()),
20046 color: cx.theme().players().agent(),
20047 })
20048 } else {
20049 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
20050 let participant_index = participant_indices.get(&collaborator.user_id).copied();
20051 let user_name = participant_names.get(&collaborator.user_id).cloned();
20052 Some(RemoteSelection {
20053 replica_id,
20054 selection,
20055 cursor_shape,
20056 line_mode,
20057 collaborator_id: CollaboratorId::PeerId(collaborator.peer_id),
20058 user_name,
20059 color: if let Some(index) = participant_index {
20060 cx.theme().players().color_for_participant(index.0)
20061 } else {
20062 cx.theme().players().absent()
20063 },
20064 })
20065 }
20066 })
20067 }
20068
20069 pub fn hunks_for_ranges(
20070 &self,
20071 ranges: impl IntoIterator<Item = Range<Point>>,
20072 ) -> Vec<MultiBufferDiffHunk> {
20073 let mut hunks = Vec::new();
20074 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
20075 HashMap::default();
20076 for query_range in ranges {
20077 let query_rows =
20078 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
20079 for hunk in self.buffer_snapshot.diff_hunks_in_range(
20080 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
20081 ) {
20082 // Include deleted hunks that are adjacent to the query range, because
20083 // otherwise they would be missed.
20084 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
20085 if hunk.status().is_deleted() {
20086 intersects_range |= hunk.row_range.start == query_rows.end;
20087 intersects_range |= hunk.row_range.end == query_rows.start;
20088 }
20089 if intersects_range {
20090 if !processed_buffer_rows
20091 .entry(hunk.buffer_id)
20092 .or_default()
20093 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
20094 {
20095 continue;
20096 }
20097 hunks.push(hunk);
20098 }
20099 }
20100 }
20101
20102 hunks
20103 }
20104
20105 fn display_diff_hunks_for_rows<'a>(
20106 &'a self,
20107 display_rows: Range<DisplayRow>,
20108 folded_buffers: &'a HashSet<BufferId>,
20109 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
20110 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
20111 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
20112
20113 self.buffer_snapshot
20114 .diff_hunks_in_range(buffer_start..buffer_end)
20115 .filter_map(|hunk| {
20116 if folded_buffers.contains(&hunk.buffer_id) {
20117 return None;
20118 }
20119
20120 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
20121 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
20122
20123 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
20124 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
20125
20126 let display_hunk = if hunk_display_start.column() != 0 {
20127 DisplayDiffHunk::Folded {
20128 display_row: hunk_display_start.row(),
20129 }
20130 } else {
20131 let mut end_row = hunk_display_end.row();
20132 if hunk_display_end.column() > 0 {
20133 end_row.0 += 1;
20134 }
20135 let is_created_file = hunk.is_created_file();
20136 DisplayDiffHunk::Unfolded {
20137 status: hunk.status(),
20138 diff_base_byte_range: hunk.diff_base_byte_range,
20139 display_row_range: hunk_display_start.row()..end_row,
20140 multi_buffer_range: Anchor::range_in_buffer(
20141 hunk.excerpt_id,
20142 hunk.buffer_id,
20143 hunk.buffer_range,
20144 ),
20145 is_created_file,
20146 }
20147 };
20148
20149 Some(display_hunk)
20150 })
20151 }
20152
20153 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
20154 self.display_snapshot.buffer_snapshot.language_at(position)
20155 }
20156
20157 pub fn is_focused(&self) -> bool {
20158 self.is_focused
20159 }
20160
20161 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
20162 self.placeholder_text.as_ref()
20163 }
20164
20165 pub fn scroll_position(&self) -> gpui::Point<f32> {
20166 self.scroll_anchor.scroll_position(&self.display_snapshot)
20167 }
20168
20169 fn gutter_dimensions(
20170 &self,
20171 font_id: FontId,
20172 font_size: Pixels,
20173 max_line_number_width: Pixels,
20174 cx: &App,
20175 ) -> Option<GutterDimensions> {
20176 if !self.show_gutter {
20177 return None;
20178 }
20179
20180 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
20181 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
20182
20183 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
20184 matches!(
20185 ProjectSettings::get_global(cx).git.git_gutter,
20186 Some(GitGutterSetting::TrackedFiles)
20187 )
20188 });
20189 let gutter_settings = EditorSettings::get_global(cx).gutter;
20190 let show_line_numbers = self
20191 .show_line_numbers
20192 .unwrap_or(gutter_settings.line_numbers);
20193 let line_gutter_width = if show_line_numbers {
20194 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
20195 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
20196 max_line_number_width.max(min_width_for_number_on_gutter)
20197 } else {
20198 0.0.into()
20199 };
20200
20201 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
20202 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
20203
20204 let git_blame_entries_width =
20205 self.git_blame_gutter_max_author_length
20206 .map(|max_author_length| {
20207 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
20208 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
20209
20210 /// The number of characters to dedicate to gaps and margins.
20211 const SPACING_WIDTH: usize = 4;
20212
20213 let max_char_count = max_author_length.min(renderer.max_author_length())
20214 + ::git::SHORT_SHA_LENGTH
20215 + MAX_RELATIVE_TIMESTAMP.len()
20216 + SPACING_WIDTH;
20217
20218 em_advance * max_char_count
20219 });
20220
20221 let is_singleton = self.buffer_snapshot.is_singleton();
20222
20223 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
20224 left_padding += if !is_singleton {
20225 em_width * 4.0
20226 } else if show_runnables || show_breakpoints {
20227 em_width * 3.0
20228 } else if show_git_gutter && show_line_numbers {
20229 em_width * 2.0
20230 } else if show_git_gutter || show_line_numbers {
20231 em_width
20232 } else {
20233 px(0.)
20234 };
20235
20236 let shows_folds = is_singleton && gutter_settings.folds;
20237
20238 let right_padding = if shows_folds && show_line_numbers {
20239 em_width * 4.0
20240 } else if shows_folds || (!is_singleton && show_line_numbers) {
20241 em_width * 3.0
20242 } else if show_line_numbers {
20243 em_width
20244 } else {
20245 px(0.)
20246 };
20247
20248 Some(GutterDimensions {
20249 left_padding,
20250 right_padding,
20251 width: line_gutter_width + left_padding + right_padding,
20252 margin: GutterDimensions::default_gutter_margin(font_id, font_size, cx),
20253 git_blame_entries_width,
20254 })
20255 }
20256
20257 pub fn render_crease_toggle(
20258 &self,
20259 buffer_row: MultiBufferRow,
20260 row_contains_cursor: bool,
20261 editor: Entity<Editor>,
20262 window: &mut Window,
20263 cx: &mut App,
20264 ) -> Option<AnyElement> {
20265 let folded = self.is_line_folded(buffer_row);
20266 let mut is_foldable = false;
20267
20268 if let Some(crease) = self
20269 .crease_snapshot
20270 .query_row(buffer_row, &self.buffer_snapshot)
20271 {
20272 is_foldable = true;
20273 match crease {
20274 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
20275 if let Some(render_toggle) = render_toggle {
20276 let toggle_callback =
20277 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
20278 if folded {
20279 editor.update(cx, |editor, cx| {
20280 editor.fold_at(buffer_row, window, cx)
20281 });
20282 } else {
20283 editor.update(cx, |editor, cx| {
20284 editor.unfold_at(buffer_row, window, cx)
20285 });
20286 }
20287 });
20288 return Some((render_toggle)(
20289 buffer_row,
20290 folded,
20291 toggle_callback,
20292 window,
20293 cx,
20294 ));
20295 }
20296 }
20297 }
20298 }
20299
20300 is_foldable |= self.starts_indent(buffer_row);
20301
20302 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
20303 Some(
20304 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
20305 .toggle_state(folded)
20306 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
20307 if folded {
20308 this.unfold_at(buffer_row, window, cx);
20309 } else {
20310 this.fold_at(buffer_row, window, cx);
20311 }
20312 }))
20313 .into_any_element(),
20314 )
20315 } else {
20316 None
20317 }
20318 }
20319
20320 pub fn render_crease_trailer(
20321 &self,
20322 buffer_row: MultiBufferRow,
20323 window: &mut Window,
20324 cx: &mut App,
20325 ) -> Option<AnyElement> {
20326 let folded = self.is_line_folded(buffer_row);
20327 if let Crease::Inline { render_trailer, .. } = self
20328 .crease_snapshot
20329 .query_row(buffer_row, &self.buffer_snapshot)?
20330 {
20331 let render_trailer = render_trailer.as_ref()?;
20332 Some(render_trailer(buffer_row, folded, window, cx))
20333 } else {
20334 None
20335 }
20336 }
20337}
20338
20339impl Deref for EditorSnapshot {
20340 type Target = DisplaySnapshot;
20341
20342 fn deref(&self) -> &Self::Target {
20343 &self.display_snapshot
20344 }
20345}
20346
20347#[derive(Clone, Debug, PartialEq, Eq)]
20348pub enum EditorEvent {
20349 InputIgnored {
20350 text: Arc<str>,
20351 },
20352 InputHandled {
20353 utf16_range_to_replace: Option<Range<isize>>,
20354 text: Arc<str>,
20355 },
20356 ExcerptsAdded {
20357 buffer: Entity<Buffer>,
20358 predecessor: ExcerptId,
20359 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
20360 },
20361 ExcerptsRemoved {
20362 ids: Vec<ExcerptId>,
20363 removed_buffer_ids: Vec<BufferId>,
20364 },
20365 BufferFoldToggled {
20366 ids: Vec<ExcerptId>,
20367 folded: bool,
20368 },
20369 ExcerptsEdited {
20370 ids: Vec<ExcerptId>,
20371 },
20372 ExcerptsExpanded {
20373 ids: Vec<ExcerptId>,
20374 },
20375 BufferEdited,
20376 Edited {
20377 transaction_id: clock::Lamport,
20378 },
20379 Reparsed(BufferId),
20380 Focused,
20381 FocusedIn,
20382 Blurred,
20383 DirtyChanged,
20384 Saved,
20385 TitleChanged,
20386 DiffBaseChanged,
20387 SelectionsChanged {
20388 local: bool,
20389 },
20390 ScrollPositionChanged {
20391 local: bool,
20392 autoscroll: bool,
20393 },
20394 Closed,
20395 TransactionUndone {
20396 transaction_id: clock::Lamport,
20397 },
20398 TransactionBegun {
20399 transaction_id: clock::Lamport,
20400 },
20401 Reloaded,
20402 CursorShapeChanged,
20403 PushedToNavHistory {
20404 anchor: Anchor,
20405 is_deactivate: bool,
20406 },
20407}
20408
20409impl EventEmitter<EditorEvent> for Editor {}
20410
20411impl Focusable for Editor {
20412 fn focus_handle(&self, _cx: &App) -> FocusHandle {
20413 self.focus_handle.clone()
20414 }
20415}
20416
20417impl Render for Editor {
20418 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20419 let settings = ThemeSettings::get_global(cx);
20420
20421 let mut text_style = match self.mode {
20422 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
20423 color: cx.theme().colors().editor_foreground,
20424 font_family: settings.ui_font.family.clone(),
20425 font_features: settings.ui_font.features.clone(),
20426 font_fallbacks: settings.ui_font.fallbacks.clone(),
20427 font_size: rems(0.875).into(),
20428 font_weight: settings.ui_font.weight,
20429 line_height: relative(settings.buffer_line_height.value()),
20430 ..Default::default()
20431 },
20432 EditorMode::Full { .. } | EditorMode::Minimap { .. } => TextStyle {
20433 color: cx.theme().colors().editor_foreground,
20434 font_family: settings.buffer_font.family.clone(),
20435 font_features: settings.buffer_font.features.clone(),
20436 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20437 font_size: settings.buffer_font_size(cx).into(),
20438 font_weight: settings.buffer_font.weight,
20439 line_height: relative(settings.buffer_line_height.value()),
20440 ..Default::default()
20441 },
20442 };
20443 if let Some(text_style_refinement) = &self.text_style_refinement {
20444 text_style.refine(text_style_refinement)
20445 }
20446
20447 let background = match self.mode {
20448 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
20449 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
20450 EditorMode::Full { .. } => cx.theme().colors().editor_background,
20451 EditorMode::Minimap { .. } => cx.theme().colors().editor_background.opacity(0.7),
20452 };
20453
20454 let show_underlines = !self.mode.is_minimap();
20455
20456 EditorElement::new(
20457 &cx.entity(),
20458 EditorStyle {
20459 background,
20460 local_player: cx.theme().players().local(),
20461 text: text_style,
20462 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
20463 syntax: cx.theme().syntax().clone(),
20464 status: cx.theme().status().clone(),
20465 inlay_hints_style: make_inlay_hints_style(cx),
20466 inline_completion_styles: make_suggestion_styles(cx),
20467 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
20468 show_underlines,
20469 },
20470 )
20471 }
20472}
20473
20474impl EntityInputHandler for Editor {
20475 fn text_for_range(
20476 &mut self,
20477 range_utf16: Range<usize>,
20478 adjusted_range: &mut Option<Range<usize>>,
20479 _: &mut Window,
20480 cx: &mut Context<Self>,
20481 ) -> Option<String> {
20482 let snapshot = self.buffer.read(cx).read(cx);
20483 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
20484 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
20485 if (start.0..end.0) != range_utf16 {
20486 adjusted_range.replace(start.0..end.0);
20487 }
20488 Some(snapshot.text_for_range(start..end).collect())
20489 }
20490
20491 fn selected_text_range(
20492 &mut self,
20493 ignore_disabled_input: bool,
20494 _: &mut Window,
20495 cx: &mut Context<Self>,
20496 ) -> Option<UTF16Selection> {
20497 // Prevent the IME menu from appearing when holding down an alphabetic key
20498 // while input is disabled.
20499 if !ignore_disabled_input && !self.input_enabled {
20500 return None;
20501 }
20502
20503 let selection = self.selections.newest::<OffsetUtf16>(cx);
20504 let range = selection.range();
20505
20506 Some(UTF16Selection {
20507 range: range.start.0..range.end.0,
20508 reversed: selection.reversed,
20509 })
20510 }
20511
20512 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
20513 let snapshot = self.buffer.read(cx).read(cx);
20514 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
20515 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
20516 }
20517
20518 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
20519 self.clear_highlights::<InputComposition>(cx);
20520 self.ime_transaction.take();
20521 }
20522
20523 fn replace_text_in_range(
20524 &mut self,
20525 range_utf16: Option<Range<usize>>,
20526 text: &str,
20527 window: &mut Window,
20528 cx: &mut Context<Self>,
20529 ) {
20530 if !self.input_enabled {
20531 cx.emit(EditorEvent::InputIgnored { text: text.into() });
20532 return;
20533 }
20534
20535 self.transact(window, cx, |this, window, cx| {
20536 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
20537 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20538 Some(this.selection_replacement_ranges(range_utf16, cx))
20539 } else {
20540 this.marked_text_ranges(cx)
20541 };
20542
20543 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
20544 let newest_selection_id = this.selections.newest_anchor().id;
20545 this.selections
20546 .all::<OffsetUtf16>(cx)
20547 .iter()
20548 .zip(ranges_to_replace.iter())
20549 .find_map(|(selection, range)| {
20550 if selection.id == newest_selection_id {
20551 Some(
20552 (range.start.0 as isize - selection.head().0 as isize)
20553 ..(range.end.0 as isize - selection.head().0 as isize),
20554 )
20555 } else {
20556 None
20557 }
20558 })
20559 });
20560
20561 cx.emit(EditorEvent::InputHandled {
20562 utf16_range_to_replace: range_to_replace,
20563 text: text.into(),
20564 });
20565
20566 if let Some(new_selected_ranges) = new_selected_ranges {
20567 this.change_selections(None, window, cx, |selections| {
20568 selections.select_ranges(new_selected_ranges)
20569 });
20570 this.backspace(&Default::default(), window, cx);
20571 }
20572
20573 this.handle_input(text, window, cx);
20574 });
20575
20576 if let Some(transaction) = self.ime_transaction {
20577 self.buffer.update(cx, |buffer, cx| {
20578 buffer.group_until_transaction(transaction, cx);
20579 });
20580 }
20581
20582 self.unmark_text(window, cx);
20583 }
20584
20585 fn replace_and_mark_text_in_range(
20586 &mut self,
20587 range_utf16: Option<Range<usize>>,
20588 text: &str,
20589 new_selected_range_utf16: Option<Range<usize>>,
20590 window: &mut Window,
20591 cx: &mut Context<Self>,
20592 ) {
20593 if !self.input_enabled {
20594 return;
20595 }
20596
20597 let transaction = self.transact(window, cx, |this, window, cx| {
20598 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
20599 let snapshot = this.buffer.read(cx).read(cx);
20600 if let Some(relative_range_utf16) = range_utf16.as_ref() {
20601 for marked_range in &mut marked_ranges {
20602 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
20603 marked_range.start.0 += relative_range_utf16.start;
20604 marked_range.start =
20605 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
20606 marked_range.end =
20607 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
20608 }
20609 }
20610 Some(marked_ranges)
20611 } else if let Some(range_utf16) = range_utf16 {
20612 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
20613 Some(this.selection_replacement_ranges(range_utf16, cx))
20614 } else {
20615 None
20616 };
20617
20618 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20619 let newest_selection_id = this.selections.newest_anchor().id;
20620 this.selections
20621 .all::<OffsetUtf16>(cx)
20622 .iter()
20623 .zip(ranges_to_replace.iter())
20624 .find_map(|(selection, range)| {
20625 if selection.id == newest_selection_id {
20626 Some(
20627 (range.start.0 as isize - selection.head().0 as isize)
20628 ..(range.end.0 as isize - selection.head().0 as isize),
20629 )
20630 } else {
20631 None
20632 }
20633 })
20634 });
20635
20636 cx.emit(EditorEvent::InputHandled {
20637 utf16_range_to_replace: range_to_replace,
20638 text: text.into(),
20639 });
20640
20641 if let Some(ranges) = ranges_to_replace {
20642 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20643 }
20644
20645 let marked_ranges = {
20646 let snapshot = this.buffer.read(cx).read(cx);
20647 this.selections
20648 .disjoint_anchors()
20649 .iter()
20650 .map(|selection| {
20651 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20652 })
20653 .collect::<Vec<_>>()
20654 };
20655
20656 if text.is_empty() {
20657 this.unmark_text(window, cx);
20658 } else {
20659 this.highlight_text::<InputComposition>(
20660 marked_ranges.clone(),
20661 HighlightStyle {
20662 underline: Some(UnderlineStyle {
20663 thickness: px(1.),
20664 color: None,
20665 wavy: false,
20666 }),
20667 ..Default::default()
20668 },
20669 cx,
20670 );
20671 }
20672
20673 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20674 let use_autoclose = this.use_autoclose;
20675 let use_auto_surround = this.use_auto_surround;
20676 this.set_use_autoclose(false);
20677 this.set_use_auto_surround(false);
20678 this.handle_input(text, window, cx);
20679 this.set_use_autoclose(use_autoclose);
20680 this.set_use_auto_surround(use_auto_surround);
20681
20682 if let Some(new_selected_range) = new_selected_range_utf16 {
20683 let snapshot = this.buffer.read(cx).read(cx);
20684 let new_selected_ranges = marked_ranges
20685 .into_iter()
20686 .map(|marked_range| {
20687 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20688 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20689 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20690 snapshot.clip_offset_utf16(new_start, Bias::Left)
20691 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20692 })
20693 .collect::<Vec<_>>();
20694
20695 drop(snapshot);
20696 this.change_selections(None, window, cx, |selections| {
20697 selections.select_ranges(new_selected_ranges)
20698 });
20699 }
20700 });
20701
20702 self.ime_transaction = self.ime_transaction.or(transaction);
20703 if let Some(transaction) = self.ime_transaction {
20704 self.buffer.update(cx, |buffer, cx| {
20705 buffer.group_until_transaction(transaction, cx);
20706 });
20707 }
20708
20709 if self.text_highlights::<InputComposition>(cx).is_none() {
20710 self.ime_transaction.take();
20711 }
20712 }
20713
20714 fn bounds_for_range(
20715 &mut self,
20716 range_utf16: Range<usize>,
20717 element_bounds: gpui::Bounds<Pixels>,
20718 window: &mut Window,
20719 cx: &mut Context<Self>,
20720 ) -> Option<gpui::Bounds<Pixels>> {
20721 let text_layout_details = self.text_layout_details(window);
20722 let gpui::Size {
20723 width: em_width,
20724 height: line_height,
20725 } = self.character_size(window);
20726
20727 let snapshot = self.snapshot(window, cx);
20728 let scroll_position = snapshot.scroll_position();
20729 let scroll_left = scroll_position.x * em_width;
20730
20731 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20732 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20733 + self.gutter_dimensions.width
20734 + self.gutter_dimensions.margin;
20735 let y = line_height * (start.row().as_f32() - scroll_position.y);
20736
20737 Some(Bounds {
20738 origin: element_bounds.origin + point(x, y),
20739 size: size(em_width, line_height),
20740 })
20741 }
20742
20743 fn character_index_for_point(
20744 &mut self,
20745 point: gpui::Point<Pixels>,
20746 _window: &mut Window,
20747 _cx: &mut Context<Self>,
20748 ) -> Option<usize> {
20749 let position_map = self.last_position_map.as_ref()?;
20750 if !position_map.text_hitbox.contains(&point) {
20751 return None;
20752 }
20753 let display_point = position_map.point_for_position(point).previous_valid;
20754 let anchor = position_map
20755 .snapshot
20756 .display_point_to_anchor(display_point, Bias::Left);
20757 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20758 Some(utf16_offset.0)
20759 }
20760}
20761
20762trait SelectionExt {
20763 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20764 fn spanned_rows(
20765 &self,
20766 include_end_if_at_line_start: bool,
20767 map: &DisplaySnapshot,
20768 ) -> Range<MultiBufferRow>;
20769}
20770
20771impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20772 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20773 let start = self
20774 .start
20775 .to_point(&map.buffer_snapshot)
20776 .to_display_point(map);
20777 let end = self
20778 .end
20779 .to_point(&map.buffer_snapshot)
20780 .to_display_point(map);
20781 if self.reversed {
20782 end..start
20783 } else {
20784 start..end
20785 }
20786 }
20787
20788 fn spanned_rows(
20789 &self,
20790 include_end_if_at_line_start: bool,
20791 map: &DisplaySnapshot,
20792 ) -> Range<MultiBufferRow> {
20793 let start = self.start.to_point(&map.buffer_snapshot);
20794 let mut end = self.end.to_point(&map.buffer_snapshot);
20795 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20796 end.row -= 1;
20797 }
20798
20799 let buffer_start = map.prev_line_boundary(start).0;
20800 let buffer_end = map.next_line_boundary(end).0;
20801 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20802 }
20803}
20804
20805impl<T: InvalidationRegion> InvalidationStack<T> {
20806 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20807 where
20808 S: Clone + ToOffset,
20809 {
20810 while let Some(region) = self.last() {
20811 let all_selections_inside_invalidation_ranges =
20812 if selections.len() == region.ranges().len() {
20813 selections
20814 .iter()
20815 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20816 .all(|(selection, invalidation_range)| {
20817 let head = selection.head().to_offset(buffer);
20818 invalidation_range.start <= head && invalidation_range.end >= head
20819 })
20820 } else {
20821 false
20822 };
20823
20824 if all_selections_inside_invalidation_ranges {
20825 break;
20826 } else {
20827 self.pop();
20828 }
20829 }
20830 }
20831}
20832
20833impl<T> Default for InvalidationStack<T> {
20834 fn default() -> Self {
20835 Self(Default::default())
20836 }
20837}
20838
20839impl<T> Deref for InvalidationStack<T> {
20840 type Target = Vec<T>;
20841
20842 fn deref(&self) -> &Self::Target {
20843 &self.0
20844 }
20845}
20846
20847impl<T> DerefMut for InvalidationStack<T> {
20848 fn deref_mut(&mut self) -> &mut Self::Target {
20849 &mut self.0
20850 }
20851}
20852
20853impl InvalidationRegion for SnippetState {
20854 fn ranges(&self) -> &[Range<Anchor>] {
20855 &self.ranges[self.active_index]
20856 }
20857}
20858
20859fn inline_completion_edit_text(
20860 current_snapshot: &BufferSnapshot,
20861 edits: &[(Range<Anchor>, String)],
20862 edit_preview: &EditPreview,
20863 include_deletions: bool,
20864 cx: &App,
20865) -> HighlightedText {
20866 let edits = edits
20867 .iter()
20868 .map(|(anchor, text)| {
20869 (
20870 anchor.start.text_anchor..anchor.end.text_anchor,
20871 text.clone(),
20872 )
20873 })
20874 .collect::<Vec<_>>();
20875
20876 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20877}
20878
20879pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20880 match severity {
20881 DiagnosticSeverity::ERROR => colors.error,
20882 DiagnosticSeverity::WARNING => colors.warning,
20883 DiagnosticSeverity::INFORMATION => colors.info,
20884 DiagnosticSeverity::HINT => colors.info,
20885 _ => colors.ignored,
20886 }
20887}
20888
20889pub fn styled_runs_for_code_label<'a>(
20890 label: &'a CodeLabel,
20891 syntax_theme: &'a theme::SyntaxTheme,
20892) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20893 let fade_out = HighlightStyle {
20894 fade_out: Some(0.35),
20895 ..Default::default()
20896 };
20897
20898 let mut prev_end = label.filter_range.end;
20899 label
20900 .runs
20901 .iter()
20902 .enumerate()
20903 .flat_map(move |(ix, (range, highlight_id))| {
20904 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20905 style
20906 } else {
20907 return Default::default();
20908 };
20909 let mut muted_style = style;
20910 muted_style.highlight(fade_out);
20911
20912 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20913 if range.start >= label.filter_range.end {
20914 if range.start > prev_end {
20915 runs.push((prev_end..range.start, fade_out));
20916 }
20917 runs.push((range.clone(), muted_style));
20918 } else if range.end <= label.filter_range.end {
20919 runs.push((range.clone(), style));
20920 } else {
20921 runs.push((range.start..label.filter_range.end, style));
20922 runs.push((label.filter_range.end..range.end, muted_style));
20923 }
20924 prev_end = cmp::max(prev_end, range.end);
20925
20926 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20927 runs.push((prev_end..label.text.len(), fade_out));
20928 }
20929
20930 runs
20931 })
20932}
20933
20934pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20935 let mut prev_index = 0;
20936 let mut prev_codepoint: Option<char> = None;
20937 text.char_indices()
20938 .chain([(text.len(), '\0')])
20939 .filter_map(move |(index, codepoint)| {
20940 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20941 let is_boundary = index == text.len()
20942 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20943 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20944 if is_boundary {
20945 let chunk = &text[prev_index..index];
20946 prev_index = index;
20947 Some(chunk)
20948 } else {
20949 None
20950 }
20951 })
20952}
20953
20954pub trait RangeToAnchorExt: Sized {
20955 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20956
20957 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20958 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20959 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20960 }
20961}
20962
20963impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20964 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20965 let start_offset = self.start.to_offset(snapshot);
20966 let end_offset = self.end.to_offset(snapshot);
20967 if start_offset == end_offset {
20968 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20969 } else {
20970 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20971 }
20972 }
20973}
20974
20975pub trait RowExt {
20976 fn as_f32(&self) -> f32;
20977
20978 fn next_row(&self) -> Self;
20979
20980 fn previous_row(&self) -> Self;
20981
20982 fn minus(&self, other: Self) -> u32;
20983}
20984
20985impl RowExt for DisplayRow {
20986 fn as_f32(&self) -> f32 {
20987 self.0 as f32
20988 }
20989
20990 fn next_row(&self) -> Self {
20991 Self(self.0 + 1)
20992 }
20993
20994 fn previous_row(&self) -> Self {
20995 Self(self.0.saturating_sub(1))
20996 }
20997
20998 fn minus(&self, other: Self) -> u32 {
20999 self.0 - other.0
21000 }
21001}
21002
21003impl RowExt for MultiBufferRow {
21004 fn as_f32(&self) -> f32 {
21005 self.0 as f32
21006 }
21007
21008 fn next_row(&self) -> Self {
21009 Self(self.0 + 1)
21010 }
21011
21012 fn previous_row(&self) -> Self {
21013 Self(self.0.saturating_sub(1))
21014 }
21015
21016 fn minus(&self, other: Self) -> u32 {
21017 self.0 - other.0
21018 }
21019}
21020
21021trait RowRangeExt {
21022 type Row;
21023
21024 fn len(&self) -> usize;
21025
21026 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
21027}
21028
21029impl RowRangeExt for Range<MultiBufferRow> {
21030 type Row = MultiBufferRow;
21031
21032 fn len(&self) -> usize {
21033 (self.end.0 - self.start.0) as usize
21034 }
21035
21036 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
21037 (self.start.0..self.end.0).map(MultiBufferRow)
21038 }
21039}
21040
21041impl RowRangeExt for Range<DisplayRow> {
21042 type Row = DisplayRow;
21043
21044 fn len(&self) -> usize {
21045 (self.end.0 - self.start.0) as usize
21046 }
21047
21048 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
21049 (self.start.0..self.end.0).map(DisplayRow)
21050 }
21051}
21052
21053/// If select range has more than one line, we
21054/// just point the cursor to range.start.
21055fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
21056 if range.start.row == range.end.row {
21057 range
21058 } else {
21059 range.start..range.start
21060 }
21061}
21062pub struct KillRing(ClipboardItem);
21063impl Global for KillRing {}
21064
21065const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
21066
21067enum BreakpointPromptEditAction {
21068 Log,
21069 Condition,
21070 HitCondition,
21071}
21072
21073struct BreakpointPromptEditor {
21074 pub(crate) prompt: Entity<Editor>,
21075 editor: WeakEntity<Editor>,
21076 breakpoint_anchor: Anchor,
21077 breakpoint: Breakpoint,
21078 edit_action: BreakpointPromptEditAction,
21079 block_ids: HashSet<CustomBlockId>,
21080 editor_margins: Arc<Mutex<EditorMargins>>,
21081 _subscriptions: Vec<Subscription>,
21082}
21083
21084impl BreakpointPromptEditor {
21085 const MAX_LINES: u8 = 4;
21086
21087 fn new(
21088 editor: WeakEntity<Editor>,
21089 breakpoint_anchor: Anchor,
21090 breakpoint: Breakpoint,
21091 edit_action: BreakpointPromptEditAction,
21092 window: &mut Window,
21093 cx: &mut Context<Self>,
21094 ) -> Self {
21095 let base_text = match edit_action {
21096 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
21097 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
21098 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
21099 }
21100 .map(|msg| msg.to_string())
21101 .unwrap_or_default();
21102
21103 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
21104 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
21105
21106 let prompt = cx.new(|cx| {
21107 let mut prompt = Editor::new(
21108 EditorMode::AutoHeight {
21109 max_lines: Self::MAX_LINES as usize,
21110 },
21111 buffer,
21112 None,
21113 window,
21114 cx,
21115 );
21116 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
21117 prompt.set_show_cursor_when_unfocused(false, cx);
21118 prompt.set_placeholder_text(
21119 match edit_action {
21120 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
21121 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
21122 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
21123 },
21124 cx,
21125 );
21126
21127 prompt
21128 });
21129
21130 Self {
21131 prompt,
21132 editor,
21133 breakpoint_anchor,
21134 breakpoint,
21135 edit_action,
21136 editor_margins: Arc::new(Mutex::new(EditorMargins::default())),
21137 block_ids: Default::default(),
21138 _subscriptions: vec![],
21139 }
21140 }
21141
21142 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
21143 self.block_ids.extend(block_ids)
21144 }
21145
21146 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
21147 if let Some(editor) = self.editor.upgrade() {
21148 let message = self
21149 .prompt
21150 .read(cx)
21151 .buffer
21152 .read(cx)
21153 .as_singleton()
21154 .expect("A multi buffer in breakpoint prompt isn't possible")
21155 .read(cx)
21156 .as_rope()
21157 .to_string();
21158
21159 editor.update(cx, |editor, cx| {
21160 editor.edit_breakpoint_at_anchor(
21161 self.breakpoint_anchor,
21162 self.breakpoint.clone(),
21163 match self.edit_action {
21164 BreakpointPromptEditAction::Log => {
21165 BreakpointEditAction::EditLogMessage(message.into())
21166 }
21167 BreakpointPromptEditAction::Condition => {
21168 BreakpointEditAction::EditCondition(message.into())
21169 }
21170 BreakpointPromptEditAction::HitCondition => {
21171 BreakpointEditAction::EditHitCondition(message.into())
21172 }
21173 },
21174 cx,
21175 );
21176
21177 editor.remove_blocks(self.block_ids.clone(), None, cx);
21178 cx.focus_self(window);
21179 });
21180 }
21181 }
21182
21183 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
21184 self.editor
21185 .update(cx, |editor, cx| {
21186 editor.remove_blocks(self.block_ids.clone(), None, cx);
21187 window.focus(&editor.focus_handle);
21188 })
21189 .log_err();
21190 }
21191
21192 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
21193 let settings = ThemeSettings::get_global(cx);
21194 let text_style = TextStyle {
21195 color: if self.prompt.read(cx).read_only(cx) {
21196 cx.theme().colors().text_disabled
21197 } else {
21198 cx.theme().colors().text
21199 },
21200 font_family: settings.buffer_font.family.clone(),
21201 font_fallbacks: settings.buffer_font.fallbacks.clone(),
21202 font_size: settings.buffer_font_size(cx).into(),
21203 font_weight: settings.buffer_font.weight,
21204 line_height: relative(settings.buffer_line_height.value()),
21205 ..Default::default()
21206 };
21207 EditorElement::new(
21208 &self.prompt,
21209 EditorStyle {
21210 background: cx.theme().colors().editor_background,
21211 local_player: cx.theme().players().local(),
21212 text: text_style,
21213 ..Default::default()
21214 },
21215 )
21216 }
21217}
21218
21219impl Render for BreakpointPromptEditor {
21220 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21221 let editor_margins = *self.editor_margins.lock();
21222 let gutter_dimensions = editor_margins.gutter;
21223 h_flex()
21224 .key_context("Editor")
21225 .bg(cx.theme().colors().editor_background)
21226 .border_y_1()
21227 .border_color(cx.theme().status().info_border)
21228 .size_full()
21229 .py(window.line_height() / 2.5)
21230 .on_action(cx.listener(Self::confirm))
21231 .on_action(cx.listener(Self::cancel))
21232 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
21233 .child(div().flex_1().child(self.render_prompt_editor(cx)))
21234 }
21235}
21236
21237impl Focusable for BreakpointPromptEditor {
21238 fn focus_handle(&self, cx: &App) -> FocusHandle {
21239 self.prompt.focus_handle(cx)
21240 }
21241}
21242
21243fn all_edits_insertions_or_deletions(
21244 edits: &Vec<(Range<Anchor>, String)>,
21245 snapshot: &MultiBufferSnapshot,
21246) -> bool {
21247 let mut all_insertions = true;
21248 let mut all_deletions = true;
21249
21250 for (range, new_text) in edits.iter() {
21251 let range_is_empty = range.to_offset(&snapshot).is_empty();
21252 let text_is_empty = new_text.is_empty();
21253
21254 if range_is_empty != text_is_empty {
21255 if range_is_empty {
21256 all_deletions = false;
21257 } else {
21258 all_insertions = false;
21259 }
21260 } else {
21261 return false;
21262 }
21263
21264 if !all_insertions && !all_deletions {
21265 return false;
21266 }
21267 }
21268 all_insertions || all_deletions
21269}
21270
21271struct MissingEditPredictionKeybindingTooltip;
21272
21273impl Render for MissingEditPredictionKeybindingTooltip {
21274 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
21275 ui::tooltip_container(window, cx, |container, _, cx| {
21276 container
21277 .flex_shrink_0()
21278 .max_w_80()
21279 .min_h(rems_from_px(124.))
21280 .justify_between()
21281 .child(
21282 v_flex()
21283 .flex_1()
21284 .text_ui_sm(cx)
21285 .child(Label::new("Conflict with Accept Keybinding"))
21286 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
21287 )
21288 .child(
21289 h_flex()
21290 .pb_1()
21291 .gap_1()
21292 .items_end()
21293 .w_full()
21294 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
21295 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
21296 }))
21297 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
21298 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
21299 })),
21300 )
21301 })
21302 }
21303}
21304
21305#[derive(Debug, Clone, Copy, PartialEq)]
21306pub struct LineHighlight {
21307 pub background: Background,
21308 pub border: Option<gpui::Hsla>,
21309 pub include_gutter: bool,
21310 pub type_id: Option<TypeId>,
21311}
21312
21313fn render_diff_hunk_controls(
21314 row: u32,
21315 status: &DiffHunkStatus,
21316 hunk_range: Range<Anchor>,
21317 is_created_file: bool,
21318 line_height: Pixels,
21319 editor: &Entity<Editor>,
21320 _window: &mut Window,
21321 cx: &mut App,
21322) -> AnyElement {
21323 h_flex()
21324 .h(line_height)
21325 .mr_1()
21326 .gap_1()
21327 .px_0p5()
21328 .pb_1()
21329 .border_x_1()
21330 .border_b_1()
21331 .border_color(cx.theme().colors().border_variant)
21332 .rounded_b_lg()
21333 .bg(cx.theme().colors().editor_background)
21334 .gap_1()
21335 .occlude()
21336 .shadow_md()
21337 .child(if status.has_secondary_hunk() {
21338 Button::new(("stage", row as u64), "Stage")
21339 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21340 .tooltip({
21341 let focus_handle = editor.focus_handle(cx);
21342 move |window, cx| {
21343 Tooltip::for_action_in(
21344 "Stage Hunk",
21345 &::git::ToggleStaged,
21346 &focus_handle,
21347 window,
21348 cx,
21349 )
21350 }
21351 })
21352 .on_click({
21353 let editor = editor.clone();
21354 move |_event, _window, cx| {
21355 editor.update(cx, |editor, cx| {
21356 editor.stage_or_unstage_diff_hunks(
21357 true,
21358 vec![hunk_range.start..hunk_range.start],
21359 cx,
21360 );
21361 });
21362 }
21363 })
21364 } else {
21365 Button::new(("unstage", row as u64), "Unstage")
21366 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
21367 .tooltip({
21368 let focus_handle = editor.focus_handle(cx);
21369 move |window, cx| {
21370 Tooltip::for_action_in(
21371 "Unstage Hunk",
21372 &::git::ToggleStaged,
21373 &focus_handle,
21374 window,
21375 cx,
21376 )
21377 }
21378 })
21379 .on_click({
21380 let editor = editor.clone();
21381 move |_event, _window, cx| {
21382 editor.update(cx, |editor, cx| {
21383 editor.stage_or_unstage_diff_hunks(
21384 false,
21385 vec![hunk_range.start..hunk_range.start],
21386 cx,
21387 );
21388 });
21389 }
21390 })
21391 })
21392 .child(
21393 Button::new(("restore", row as u64), "Restore")
21394 .tooltip({
21395 let focus_handle = editor.focus_handle(cx);
21396 move |window, cx| {
21397 Tooltip::for_action_in(
21398 "Restore Hunk",
21399 &::git::Restore,
21400 &focus_handle,
21401 window,
21402 cx,
21403 )
21404 }
21405 })
21406 .on_click({
21407 let editor = editor.clone();
21408 move |_event, window, cx| {
21409 editor.update(cx, |editor, cx| {
21410 let snapshot = editor.snapshot(window, cx);
21411 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
21412 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
21413 });
21414 }
21415 })
21416 .disabled(is_created_file),
21417 )
21418 .when(
21419 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
21420 |el| {
21421 el.child(
21422 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
21423 .shape(IconButtonShape::Square)
21424 .icon_size(IconSize::Small)
21425 // .disabled(!has_multiple_hunks)
21426 .tooltip({
21427 let focus_handle = editor.focus_handle(cx);
21428 move |window, cx| {
21429 Tooltip::for_action_in(
21430 "Next Hunk",
21431 &GoToHunk,
21432 &focus_handle,
21433 window,
21434 cx,
21435 )
21436 }
21437 })
21438 .on_click({
21439 let editor = editor.clone();
21440 move |_event, window, cx| {
21441 editor.update(cx, |editor, cx| {
21442 let snapshot = editor.snapshot(window, cx);
21443 let position =
21444 hunk_range.end.to_point(&snapshot.buffer_snapshot);
21445 editor.go_to_hunk_before_or_after_position(
21446 &snapshot,
21447 position,
21448 Direction::Next,
21449 window,
21450 cx,
21451 );
21452 editor.expand_selected_diff_hunks(cx);
21453 });
21454 }
21455 }),
21456 )
21457 .child(
21458 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
21459 .shape(IconButtonShape::Square)
21460 .icon_size(IconSize::Small)
21461 // .disabled(!has_multiple_hunks)
21462 .tooltip({
21463 let focus_handle = editor.focus_handle(cx);
21464 move |window, cx| {
21465 Tooltip::for_action_in(
21466 "Previous Hunk",
21467 &GoToPreviousHunk,
21468 &focus_handle,
21469 window,
21470 cx,
21471 )
21472 }
21473 })
21474 .on_click({
21475 let editor = editor.clone();
21476 move |_event, window, cx| {
21477 editor.update(cx, |editor, cx| {
21478 let snapshot = editor.snapshot(window, cx);
21479 let point =
21480 hunk_range.start.to_point(&snapshot.buffer_snapshot);
21481 editor.go_to_hunk_before_or_after_position(
21482 &snapshot,
21483 point,
21484 Direction::Prev,
21485 window,
21486 cx,
21487 );
21488 editor.expand_selected_diff_hunks(cx);
21489 });
21490 }
21491 }),
21492 )
21493 },
21494 )
21495 .into_any_element()
21496}