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;
26mod hover_popover;
27mod indent_guides;
28mod inlay_hint_cache;
29pub mod items;
30mod jsx_tag_auto_close;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{Context as _, Result, anyhow};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
62use editor_settings::GoToDefinitionFallback;
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
65 ShowScrollbar,
66};
67pub use editor_settings_controls::*;
68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
69pub use element::{
70 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
71};
72use feature_flags::{Debugger, FeatureFlagAppExt};
73use futures::{
74 FutureExt,
75 future::{self, Shared, join},
76};
77use fuzzy::StringMatchCandidate;
78
79use ::git::Restore;
80use code_context_menus::{
81 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
82 CompletionsMenu, ContextMenuOrigin,
83};
84use git::blame::{GitBlame, GlobalBlameRenderer};
85use gpui::{
86 Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
87 AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
88 ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
89 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
90 KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
91 SharedString, Size, Stateful, Styled, StyledText, Subscription, Task, TextStyle,
92 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
93 WeakFocusHandle, Window, div, impl_actions, point, prelude::*, pulsating_between, px, relative,
94 size,
95};
96use highlight_matching_bracket::refresh_matching_bracket_highlights;
97use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
98pub use hover_popover::hover_markdown_style;
99use hover_popover::{HoverState, hide_hover};
100use indent_guides::ActiveIndentGuidesState;
101use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
102pub use inline_completion::Direction;
103use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
104pub use items::MAX_TAB_TITLE_LEN;
105use itertools::Itertools;
106use language::{
107 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
108 CursorShape, Diagnostic, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
109 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
110 TransactionId, TreeSitterOptions, WordsQuery,
111 language_settings::{
112 self, InlayHintSettings, RewrapBehavior, WordsCompletionMode, all_language_settings,
113 language_settings,
114 },
115 point_from_lsp, text_diff_with_options,
116};
117use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
118use linked_editing_ranges::refresh_linked_ranges;
119use mouse_context_menu::MouseContextMenu;
120use persistence::DB;
121use project::{
122 ProjectPath,
123 debugger::breakpoint_store::{
124 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
125 },
126};
127
128pub use git::blame::BlameRenderer;
129pub use proposed_changes_editor::{
130 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
131};
132use smallvec::smallvec;
133use std::{cell::OnceCell, iter::Peekable};
134use task::{ResolvedTask, TaskTemplate, TaskVariables};
135
136pub use lsp::CompletionContext;
137use lsp::{
138 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
139 InsertTextFormat, LanguageServerId, LanguageServerName,
140};
141
142use language::BufferSnapshot;
143use movement::TextLayoutDetails;
144pub use multi_buffer::{
145 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
146 ToOffset, ToPoint,
147};
148use multi_buffer::{
149 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
150 MultiOrSingleBufferOffsetRange, PathKey, ToOffsetUtf16,
151};
152use parking_lot::Mutex;
153use project::{
154 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
155 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
156 TaskSourceKind,
157 debugger::breakpoint_store::Breakpoint,
158 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
159 project_settings::{GitGutterSetting, ProjectSettings},
160};
161use rand::prelude::*;
162use rpc::{ErrorExt, proto::*};
163use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
164use selections_collection::{
165 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
166};
167use serde::{Deserialize, Serialize};
168use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
169use smallvec::SmallVec;
170use snippet::Snippet;
171use std::sync::Arc;
172use std::{
173 any::TypeId,
174 borrow::Cow,
175 cell::RefCell,
176 cmp::{self, Ordering, Reverse},
177 mem,
178 num::NonZeroU32,
179 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
180 path::{Path, PathBuf},
181 rc::Rc,
182 time::{Duration, Instant},
183};
184pub use sum_tree::Bias;
185use sum_tree::TreeMap;
186use text::{BufferId, OffsetUtf16, Rope};
187use theme::{
188 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
189 observe_buffer_font_size_adjustment,
190};
191use ui::{
192 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
193 IconSize, Key, Tooltip, h_flex, prelude::*,
194};
195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
196use workspace::{
197 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
198 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
199 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
200 item::{ItemHandle, PreviewTabsSettings},
201 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
202 searchable::SearchEvent,
203};
204
205use crate::hover_links::{find_url, find_url_from_range};
206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
207
208pub const FILE_HEADER_HEIGHT: u32 = 2;
209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
212const MAX_LINE_LEN: usize = 1024;
213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
216#[doc(hidden)]
217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
218
219pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
220pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
221pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
222
223pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
224pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
225pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
226
227pub type RenderDiffHunkControlsFn = Arc<
228 dyn Fn(
229 u32,
230 &DiffHunkStatus,
231 Range<Anchor>,
232 bool,
233 Pixels,
234 &Entity<Editor>,
235 &mut Window,
236 &mut App,
237 ) -> AnyElement,
238>;
239
240const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
241 alt: true,
242 shift: true,
243 control: false,
244 platform: false,
245 function: false,
246};
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
249pub enum InlayId {
250 InlineCompletion(usize),
251 Hint(usize),
252}
253
254impl InlayId {
255 fn id(&self) -> usize {
256 match self {
257 Self::InlineCompletion(id) => *id,
258 Self::Hint(id) => *id,
259 }
260 }
261}
262
263pub enum DebugCurrentRowHighlight {}
264enum DocumentHighlightRead {}
265enum DocumentHighlightWrite {}
266enum InputComposition {}
267enum SelectedTextHighlight {}
268
269#[derive(Debug, Copy, Clone, PartialEq, Eq)]
270pub enum Navigated {
271 Yes,
272 No,
273}
274
275impl Navigated {
276 pub fn from_bool(yes: bool) -> Navigated {
277 if yes { Navigated::Yes } else { Navigated::No }
278 }
279}
280
281#[derive(Debug, Clone, PartialEq, Eq)]
282enum DisplayDiffHunk {
283 Folded {
284 display_row: DisplayRow,
285 },
286 Unfolded {
287 is_created_file: bool,
288 diff_base_byte_range: Range<usize>,
289 display_row_range: Range<DisplayRow>,
290 multi_buffer_range: Range<Anchor>,
291 status: DiffHunkStatus,
292 },
293}
294
295pub enum HideMouseCursorOrigin {
296 TypingAction,
297 MovementAction,
298}
299
300pub fn init_settings(cx: &mut App) {
301 EditorSettings::register(cx);
302}
303
304pub fn init(cx: &mut App) {
305 init_settings(cx);
306
307 cx.set_global(GlobalBlameRenderer(Arc::new(())));
308
309 workspace::register_project_item::<Editor>(cx);
310 workspace::FollowableViewRegistry::register::<Editor>(cx);
311 workspace::register_serializable_item::<Editor>(cx);
312
313 cx.observe_new(
314 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
315 workspace.register_action(Editor::new_file);
316 workspace.register_action(Editor::new_file_vertical);
317 workspace.register_action(Editor::new_file_horizontal);
318 workspace.register_action(Editor::cancel_language_server_work);
319 },
320 )
321 .detach();
322
323 cx.on_action(move |_: &workspace::NewFile, cx| {
324 let app_state = workspace::AppState::global(cx);
325 if let Some(app_state) = app_state.upgrade() {
326 workspace::open_new(
327 Default::default(),
328 app_state,
329 cx,
330 |workspace, window, cx| {
331 Editor::new_file(workspace, &Default::default(), window, cx)
332 },
333 )
334 .detach();
335 }
336 });
337 cx.on_action(move |_: &workspace::NewWindow, cx| {
338 let app_state = workspace::AppState::global(cx);
339 if let Some(app_state) = app_state.upgrade() {
340 workspace::open_new(
341 Default::default(),
342 app_state,
343 cx,
344 |workspace, window, cx| {
345 cx.activate(true);
346 Editor::new_file(workspace, &Default::default(), window, cx)
347 },
348 )
349 .detach();
350 }
351 });
352}
353
354pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
355 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
356}
357
358pub struct SearchWithinRange;
359
360trait InvalidationRegion {
361 fn ranges(&self) -> &[Range<Anchor>];
362}
363
364#[derive(Clone, Debug, PartialEq)]
365pub enum SelectPhase {
366 Begin {
367 position: DisplayPoint,
368 add: bool,
369 click_count: usize,
370 },
371 BeginColumnar {
372 position: DisplayPoint,
373 reset: bool,
374 goal_column: u32,
375 },
376 Extend {
377 position: DisplayPoint,
378 click_count: usize,
379 },
380 Update {
381 position: DisplayPoint,
382 goal_column: u32,
383 scroll_delta: gpui::Point<f32>,
384 },
385 End,
386}
387
388#[derive(Clone, Debug)]
389pub enum SelectMode {
390 Character,
391 Word(Range<Anchor>),
392 Line(Range<Anchor>),
393 All,
394}
395
396#[derive(Copy, Clone, PartialEq, Eq, Debug)]
397pub enum EditorMode {
398 SingleLine { auto_width: bool },
399 AutoHeight { max_lines: usize },
400 Full,
401}
402
403#[derive(Copy, Clone, Debug)]
404pub enum SoftWrap {
405 /// Prefer not to wrap at all.
406 ///
407 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
408 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
409 GitDiff,
410 /// Prefer a single line generally, unless an overly long line is encountered.
411 None,
412 /// Soft wrap lines that exceed the editor width.
413 EditorWidth,
414 /// Soft wrap lines at the preferred line length.
415 Column(u32),
416 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
417 Bounded(u32),
418}
419
420#[derive(Clone)]
421pub struct EditorStyle {
422 pub background: Hsla,
423 pub local_player: PlayerColor,
424 pub text: TextStyle,
425 pub scrollbar_width: Pixels,
426 pub syntax: Arc<SyntaxTheme>,
427 pub status: StatusColors,
428 pub inlay_hints_style: HighlightStyle,
429 pub inline_completion_styles: InlineCompletionStyles,
430 pub unnecessary_code_fade: f32,
431}
432
433impl Default for EditorStyle {
434 fn default() -> Self {
435 Self {
436 background: Hsla::default(),
437 local_player: PlayerColor::default(),
438 text: TextStyle::default(),
439 scrollbar_width: Pixels::default(),
440 syntax: Default::default(),
441 // HACK: Status colors don't have a real default.
442 // We should look into removing the status colors from the editor
443 // style and retrieve them directly from the theme.
444 status: StatusColors::dark(),
445 inlay_hints_style: HighlightStyle::default(),
446 inline_completion_styles: InlineCompletionStyles {
447 insertion: HighlightStyle::default(),
448 whitespace: HighlightStyle::default(),
449 },
450 unnecessary_code_fade: Default::default(),
451 }
452 }
453}
454
455pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
456 let show_background = language_settings::language_settings(None, None, cx)
457 .inlay_hints
458 .show_background;
459
460 HighlightStyle {
461 color: Some(cx.theme().status().hint),
462 background_color: show_background.then(|| cx.theme().status().hint_background),
463 ..HighlightStyle::default()
464 }
465}
466
467pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
468 InlineCompletionStyles {
469 insertion: HighlightStyle {
470 color: Some(cx.theme().status().predictive),
471 ..HighlightStyle::default()
472 },
473 whitespace: HighlightStyle {
474 background_color: Some(cx.theme().status().created_background),
475 ..HighlightStyle::default()
476 },
477 }
478}
479
480type CompletionId = usize;
481
482pub(crate) enum EditDisplayMode {
483 TabAccept,
484 DiffPopover,
485 Inline,
486}
487
488enum InlineCompletion {
489 Edit {
490 edits: Vec<(Range<Anchor>, String)>,
491 edit_preview: Option<EditPreview>,
492 display_mode: EditDisplayMode,
493 snapshot: BufferSnapshot,
494 },
495 Move {
496 target: Anchor,
497 snapshot: BufferSnapshot,
498 },
499}
500
501struct InlineCompletionState {
502 inlay_ids: Vec<InlayId>,
503 completion: InlineCompletion,
504 completion_id: Option<SharedString>,
505 invalidation_range: Range<Anchor>,
506}
507
508enum EditPredictionSettings {
509 Disabled,
510 Enabled {
511 show_in_menu: bool,
512 preview_requires_modifier: bool,
513 },
514}
515
516enum InlineCompletionHighlight {}
517
518#[derive(Debug, Clone)]
519struct InlineDiagnostic {
520 message: SharedString,
521 group_id: usize,
522 is_primary: bool,
523 start: Point,
524 severity: DiagnosticSeverity,
525}
526
527pub enum MenuInlineCompletionsPolicy {
528 Never,
529 ByProvider,
530}
531
532pub enum EditPredictionPreview {
533 /// Modifier is not pressed
534 Inactive { released_too_fast: bool },
535 /// Modifier pressed
536 Active {
537 since: Instant,
538 previous_scroll_position: Option<ScrollAnchor>,
539 },
540}
541
542impl EditPredictionPreview {
543 pub fn released_too_fast(&self) -> bool {
544 match self {
545 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
546 EditPredictionPreview::Active { .. } => false,
547 }
548 }
549
550 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
551 if let EditPredictionPreview::Active {
552 previous_scroll_position,
553 ..
554 } = self
555 {
556 *previous_scroll_position = scroll_position;
557 }
558 }
559}
560
561pub struct ContextMenuOptions {
562 pub min_entries_visible: usize,
563 pub max_entries_visible: usize,
564 pub placement: Option<ContextMenuPlacement>,
565}
566
567#[derive(Debug, Clone, PartialEq, Eq)]
568pub enum ContextMenuPlacement {
569 Above,
570 Below,
571}
572
573#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
574struct EditorActionId(usize);
575
576impl EditorActionId {
577 pub fn post_inc(&mut self) -> Self {
578 let answer = self.0;
579
580 *self = Self(answer + 1);
581
582 Self(answer)
583 }
584}
585
586// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
587// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
588
589type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
590type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
591
592#[derive(Default)]
593struct ScrollbarMarkerState {
594 scrollbar_size: Size<Pixels>,
595 dirty: bool,
596 markers: Arc<[PaintQuad]>,
597 pending_refresh: Option<Task<Result<()>>>,
598}
599
600impl ScrollbarMarkerState {
601 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
602 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
603 }
604}
605
606#[derive(Clone, Debug)]
607struct RunnableTasks {
608 templates: Vec<(TaskSourceKind, TaskTemplate)>,
609 offset: multi_buffer::Anchor,
610 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
611 column: u32,
612 // Values of all named captures, including those starting with '_'
613 extra_variables: HashMap<String, String>,
614 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
615 context_range: Range<BufferOffset>,
616}
617
618impl RunnableTasks {
619 fn resolve<'a>(
620 &'a self,
621 cx: &'a task::TaskContext,
622 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
623 self.templates.iter().filter_map(|(kind, template)| {
624 template
625 .resolve_task(&kind.to_id_base(), cx)
626 .map(|task| (kind.clone(), task))
627 })
628 }
629}
630
631#[derive(Clone)]
632struct ResolvedTasks {
633 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
634 position: Anchor,
635}
636
637#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
638struct BufferOffset(usize);
639
640// Addons allow storing per-editor state in other crates (e.g. Vim)
641pub trait Addon: 'static {
642 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
643
644 fn render_buffer_header_controls(
645 &self,
646 _: &ExcerptInfo,
647 _: &Window,
648 _: &App,
649 ) -> Option<AnyElement> {
650 None
651 }
652
653 fn to_any(&self) -> &dyn std::any::Any;
654}
655
656/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
657///
658/// See the [module level documentation](self) for more information.
659pub struct Editor {
660 focus_handle: FocusHandle,
661 last_focused_descendant: Option<WeakFocusHandle>,
662 /// The text buffer being edited
663 buffer: Entity<MultiBuffer>,
664 /// Map of how text in the buffer should be displayed.
665 /// Handles soft wraps, folds, fake inlay text insertions, etc.
666 pub display_map: Entity<DisplayMap>,
667 pub selections: SelectionsCollection,
668 pub scroll_manager: ScrollManager,
669 /// When inline assist editors are linked, they all render cursors because
670 /// typing enters text into each of them, even the ones that aren't focused.
671 pub(crate) show_cursor_when_unfocused: bool,
672 columnar_selection_tail: Option<Anchor>,
673 add_selections_state: Option<AddSelectionsState>,
674 select_next_state: Option<SelectNextState>,
675 select_prev_state: Option<SelectNextState>,
676 selection_history: SelectionHistory,
677 autoclose_regions: Vec<AutocloseRegion>,
678 snippet_stack: InvalidationStack<SnippetState>,
679 select_syntax_node_history: SelectSyntaxNodeHistory,
680 ime_transaction: Option<TransactionId>,
681 active_diagnostics: Option<ActiveDiagnosticGroup>,
682 show_inline_diagnostics: bool,
683 inline_diagnostics_update: Task<()>,
684 inline_diagnostics_enabled: bool,
685 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
686 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
687 hard_wrap: Option<usize>,
688
689 // TODO: make this a access method
690 pub project: Option<Entity<Project>>,
691 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
692 completion_provider: Option<Box<dyn CompletionProvider>>,
693 collaboration_hub: Option<Box<dyn CollaborationHub>>,
694 blink_manager: Entity<BlinkManager>,
695 show_cursor_names: bool,
696 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
697 pub show_local_selections: bool,
698 mode: EditorMode,
699 show_breadcrumbs: bool,
700 show_gutter: bool,
701 show_scrollbars: bool,
702 show_line_numbers: Option<bool>,
703 use_relative_line_numbers: Option<bool>,
704 show_git_diff_gutter: Option<bool>,
705 show_code_actions: Option<bool>,
706 show_runnables: Option<bool>,
707 show_breakpoints: Option<bool>,
708 show_wrap_guides: Option<bool>,
709 show_indent_guides: Option<bool>,
710 placeholder_text: Option<Arc<str>>,
711 highlight_order: usize,
712 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
713 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
714 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
715 scrollbar_marker_state: ScrollbarMarkerState,
716 active_indent_guides_state: ActiveIndentGuidesState,
717 nav_history: Option<ItemNavHistory>,
718 context_menu: RefCell<Option<CodeContextMenu>>,
719 context_menu_options: Option<ContextMenuOptions>,
720 mouse_context_menu: Option<MouseContextMenu>,
721 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
722 signature_help_state: SignatureHelpState,
723 auto_signature_help: Option<bool>,
724 find_all_references_task_sources: Vec<Anchor>,
725 next_completion_id: CompletionId,
726 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
727 code_actions_task: Option<Task<Result<()>>>,
728 selection_highlight_task: Option<Task<()>>,
729 document_highlights_task: Option<Task<()>>,
730 linked_editing_range_task: Option<Task<Option<()>>>,
731 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
732 pending_rename: Option<RenameState>,
733 searchable: bool,
734 cursor_shape: CursorShape,
735 current_line_highlight: Option<CurrentLineHighlight>,
736 collapse_matches: bool,
737 autoindent_mode: Option<AutoindentMode>,
738 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
739 input_enabled: bool,
740 use_modal_editing: bool,
741 read_only: bool,
742 leader_peer_id: Option<PeerId>,
743 remote_id: Option<ViewId>,
744 hover_state: HoverState,
745 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
746 gutter_hovered: bool,
747 hovered_link_state: Option<HoveredLinkState>,
748 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
749 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
750 active_inline_completion: Option<InlineCompletionState>,
751 /// Used to prevent flickering as the user types while the menu is open
752 stale_inline_completion_in_menu: Option<InlineCompletionState>,
753 edit_prediction_settings: EditPredictionSettings,
754 inline_completions_hidden_for_vim_mode: bool,
755 show_inline_completions_override: Option<bool>,
756 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
757 edit_prediction_preview: EditPredictionPreview,
758 edit_prediction_indent_conflict: bool,
759 edit_prediction_requires_modifier_in_indent_conflict: bool,
760 inlay_hint_cache: InlayHintCache,
761 next_inlay_id: usize,
762 _subscriptions: Vec<Subscription>,
763 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
764 gutter_dimensions: GutterDimensions,
765 style: Option<EditorStyle>,
766 text_style_refinement: Option<TextStyleRefinement>,
767 next_editor_action_id: EditorActionId,
768 editor_actions:
769 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
770 use_autoclose: bool,
771 use_auto_surround: bool,
772 auto_replace_emoji_shortcode: bool,
773 jsx_tag_auto_close_enabled_in_any_buffer: bool,
774 show_git_blame_gutter: bool,
775 show_git_blame_inline: bool,
776 show_git_blame_inline_delay_task: Option<Task<()>>,
777 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
778 git_blame_inline_enabled: bool,
779 render_diff_hunk_controls: RenderDiffHunkControlsFn,
780 serialize_dirty_buffers: bool,
781 show_selection_menu: Option<bool>,
782 blame: Option<Entity<GitBlame>>,
783 blame_subscription: Option<Subscription>,
784 custom_context_menu: Option<
785 Box<
786 dyn 'static
787 + Fn(
788 &mut Self,
789 DisplayPoint,
790 &mut Window,
791 &mut Context<Self>,
792 ) -> Option<Entity<ui::ContextMenu>>,
793 >,
794 >,
795 last_bounds: Option<Bounds<Pixels>>,
796 last_position_map: Option<Rc<PositionMap>>,
797 expect_bounds_change: Option<Bounds<Pixels>>,
798 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
799 tasks_update_task: Option<Task<()>>,
800 breakpoint_store: Option<Entity<BreakpointStore>>,
801 /// Allow's a user to create a breakpoint by selecting this indicator
802 /// It should be None while a user is not hovering over the gutter
803 /// Otherwise it represents the point that the breakpoint will be shown
804 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
805 in_project_search: bool,
806 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
807 breadcrumb_header: Option<String>,
808 focused_block: Option<FocusedBlock>,
809 next_scroll_position: NextScrollCursorCenterTopBottom,
810 addons: HashMap<TypeId, Box<dyn Addon>>,
811 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
812 load_diff_task: Option<Shared<Task<()>>>,
813 selection_mark_mode: bool,
814 toggle_fold_multiple_buffers: Task<()>,
815 _scroll_cursor_center_top_bottom_task: Task<()>,
816 serialize_selections: Task<()>,
817 serialize_folds: Task<()>,
818 mouse_cursor_hidden: bool,
819 hide_mouse_mode: HideMouseMode,
820}
821
822#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
823enum NextScrollCursorCenterTopBottom {
824 #[default]
825 Center,
826 Top,
827 Bottom,
828}
829
830impl NextScrollCursorCenterTopBottom {
831 fn next(&self) -> Self {
832 match self {
833 Self::Center => Self::Top,
834 Self::Top => Self::Bottom,
835 Self::Bottom => Self::Center,
836 }
837 }
838}
839
840#[derive(Clone)]
841pub struct EditorSnapshot {
842 pub mode: EditorMode,
843 show_gutter: bool,
844 show_line_numbers: Option<bool>,
845 show_git_diff_gutter: Option<bool>,
846 show_code_actions: Option<bool>,
847 show_runnables: Option<bool>,
848 show_breakpoints: Option<bool>,
849 git_blame_gutter_max_author_length: Option<usize>,
850 pub display_snapshot: DisplaySnapshot,
851 pub placeholder_text: Option<Arc<str>>,
852 is_focused: bool,
853 scroll_anchor: ScrollAnchor,
854 ongoing_scroll: OngoingScroll,
855 current_line_highlight: CurrentLineHighlight,
856 gutter_hovered: bool,
857}
858
859#[derive(Default, Debug, Clone, Copy)]
860pub struct GutterDimensions {
861 pub left_padding: Pixels,
862 pub right_padding: Pixels,
863 pub width: Pixels,
864 pub margin: Pixels,
865 pub git_blame_entries_width: Option<Pixels>,
866}
867
868impl GutterDimensions {
869 /// The full width of the space taken up by the gutter.
870 pub fn full_width(&self) -> Pixels {
871 self.margin + self.width
872 }
873
874 /// The width of the space reserved for the fold indicators,
875 /// use alongside 'justify_end' and `gutter_width` to
876 /// right align content with the line numbers
877 pub fn fold_area_width(&self) -> Pixels {
878 self.margin + self.right_padding
879 }
880}
881
882#[derive(Debug)]
883pub struct RemoteSelection {
884 pub replica_id: ReplicaId,
885 pub selection: Selection<Anchor>,
886 pub cursor_shape: CursorShape,
887 pub peer_id: PeerId,
888 pub line_mode: bool,
889 pub participant_index: Option<ParticipantIndex>,
890 pub user_name: Option<SharedString>,
891}
892
893#[derive(Clone, Debug)]
894struct SelectionHistoryEntry {
895 selections: Arc<[Selection<Anchor>]>,
896 select_next_state: Option<SelectNextState>,
897 select_prev_state: Option<SelectNextState>,
898 add_selections_state: Option<AddSelectionsState>,
899}
900
901enum SelectionHistoryMode {
902 Normal,
903 Undoing,
904 Redoing,
905}
906
907#[derive(Clone, PartialEq, Eq, Hash)]
908struct HoveredCursor {
909 replica_id: u16,
910 selection_id: usize,
911}
912
913impl Default for SelectionHistoryMode {
914 fn default() -> Self {
915 Self::Normal
916 }
917}
918
919#[derive(Default)]
920struct SelectionHistory {
921 #[allow(clippy::type_complexity)]
922 selections_by_transaction:
923 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
924 mode: SelectionHistoryMode,
925 undo_stack: VecDeque<SelectionHistoryEntry>,
926 redo_stack: VecDeque<SelectionHistoryEntry>,
927}
928
929impl SelectionHistory {
930 fn insert_transaction(
931 &mut self,
932 transaction_id: TransactionId,
933 selections: Arc<[Selection<Anchor>]>,
934 ) {
935 self.selections_by_transaction
936 .insert(transaction_id, (selections, None));
937 }
938
939 #[allow(clippy::type_complexity)]
940 fn transaction(
941 &self,
942 transaction_id: TransactionId,
943 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
944 self.selections_by_transaction.get(&transaction_id)
945 }
946
947 #[allow(clippy::type_complexity)]
948 fn transaction_mut(
949 &mut self,
950 transaction_id: TransactionId,
951 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
952 self.selections_by_transaction.get_mut(&transaction_id)
953 }
954
955 fn push(&mut self, entry: SelectionHistoryEntry) {
956 if !entry.selections.is_empty() {
957 match self.mode {
958 SelectionHistoryMode::Normal => {
959 self.push_undo(entry);
960 self.redo_stack.clear();
961 }
962 SelectionHistoryMode::Undoing => self.push_redo(entry),
963 SelectionHistoryMode::Redoing => self.push_undo(entry),
964 }
965 }
966 }
967
968 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
969 if self
970 .undo_stack
971 .back()
972 .map_or(true, |e| e.selections != entry.selections)
973 {
974 self.undo_stack.push_back(entry);
975 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
976 self.undo_stack.pop_front();
977 }
978 }
979 }
980
981 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
982 if self
983 .redo_stack
984 .back()
985 .map_or(true, |e| e.selections != entry.selections)
986 {
987 self.redo_stack.push_back(entry);
988 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
989 self.redo_stack.pop_front();
990 }
991 }
992 }
993}
994
995struct RowHighlight {
996 index: usize,
997 range: Range<Anchor>,
998 color: Hsla,
999 should_autoscroll: bool,
1000}
1001
1002#[derive(Clone, Debug)]
1003struct AddSelectionsState {
1004 above: bool,
1005 stack: Vec<usize>,
1006}
1007
1008#[derive(Clone)]
1009struct SelectNextState {
1010 query: AhoCorasick,
1011 wordwise: bool,
1012 done: bool,
1013}
1014
1015impl std::fmt::Debug for SelectNextState {
1016 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1017 f.debug_struct(std::any::type_name::<Self>())
1018 .field("wordwise", &self.wordwise)
1019 .field("done", &self.done)
1020 .finish()
1021 }
1022}
1023
1024#[derive(Debug)]
1025struct AutocloseRegion {
1026 selection_id: usize,
1027 range: Range<Anchor>,
1028 pair: BracketPair,
1029}
1030
1031#[derive(Debug)]
1032struct SnippetState {
1033 ranges: Vec<Vec<Range<Anchor>>>,
1034 active_index: usize,
1035 choices: Vec<Option<Vec<String>>>,
1036}
1037
1038#[doc(hidden)]
1039pub struct RenameState {
1040 pub range: Range<Anchor>,
1041 pub old_name: Arc<str>,
1042 pub editor: Entity<Editor>,
1043 block_id: CustomBlockId,
1044}
1045
1046struct InvalidationStack<T>(Vec<T>);
1047
1048struct RegisteredInlineCompletionProvider {
1049 provider: Arc<dyn InlineCompletionProviderHandle>,
1050 _subscription: Subscription,
1051}
1052
1053#[derive(Debug, PartialEq, Eq)]
1054struct ActiveDiagnosticGroup {
1055 primary_range: Range<Anchor>,
1056 primary_message: String,
1057 group_id: usize,
1058 blocks: HashMap<CustomBlockId, Diagnostic>,
1059 is_valid: bool,
1060}
1061
1062#[derive(Serialize, Deserialize, Clone, Debug)]
1063pub struct ClipboardSelection {
1064 /// The number of bytes in this selection.
1065 pub len: usize,
1066 /// Whether this was a full-line selection.
1067 pub is_entire_line: bool,
1068 /// The indentation of the first line when this content was originally copied.
1069 pub first_line_indent: u32,
1070}
1071
1072// selections, scroll behavior, was newest selection reversed
1073type SelectSyntaxNodeHistoryState = (
1074 Box<[Selection<usize>]>,
1075 SelectSyntaxNodeScrollBehavior,
1076 bool,
1077);
1078
1079#[derive(Default)]
1080struct SelectSyntaxNodeHistory {
1081 stack: Vec<SelectSyntaxNodeHistoryState>,
1082 // disable temporarily to allow changing selections without losing the stack
1083 pub disable_clearing: bool,
1084}
1085
1086impl SelectSyntaxNodeHistory {
1087 pub fn try_clear(&mut self) {
1088 if !self.disable_clearing {
1089 self.stack.clear();
1090 }
1091 }
1092
1093 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1094 self.stack.push(selection);
1095 }
1096
1097 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1098 self.stack.pop()
1099 }
1100}
1101
1102enum SelectSyntaxNodeScrollBehavior {
1103 CursorTop,
1104 CenterSelection,
1105 CursorBottom,
1106}
1107
1108#[derive(Debug)]
1109pub(crate) struct NavigationData {
1110 cursor_anchor: Anchor,
1111 cursor_position: Point,
1112 scroll_anchor: ScrollAnchor,
1113 scroll_top_row: u32,
1114}
1115
1116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1117pub enum GotoDefinitionKind {
1118 Symbol,
1119 Declaration,
1120 Type,
1121 Implementation,
1122}
1123
1124#[derive(Debug, Clone)]
1125enum InlayHintRefreshReason {
1126 ModifiersChanged(bool),
1127 Toggle(bool),
1128 SettingsChange(InlayHintSettings),
1129 NewLinesShown,
1130 BufferEdited(HashSet<Arc<Language>>),
1131 RefreshRequested,
1132 ExcerptsRemoved(Vec<ExcerptId>),
1133}
1134
1135impl InlayHintRefreshReason {
1136 fn description(&self) -> &'static str {
1137 match self {
1138 Self::ModifiersChanged(_) => "modifiers changed",
1139 Self::Toggle(_) => "toggle",
1140 Self::SettingsChange(_) => "settings change",
1141 Self::NewLinesShown => "new lines shown",
1142 Self::BufferEdited(_) => "buffer edited",
1143 Self::RefreshRequested => "refresh requested",
1144 Self::ExcerptsRemoved(_) => "excerpts removed",
1145 }
1146 }
1147}
1148
1149pub enum FormatTarget {
1150 Buffers,
1151 Ranges(Vec<Range<MultiBufferPoint>>),
1152}
1153
1154pub(crate) struct FocusedBlock {
1155 id: BlockId,
1156 focus_handle: WeakFocusHandle,
1157}
1158
1159#[derive(Clone)]
1160enum JumpData {
1161 MultiBufferRow {
1162 row: MultiBufferRow,
1163 line_offset_from_top: u32,
1164 },
1165 MultiBufferPoint {
1166 excerpt_id: ExcerptId,
1167 position: Point,
1168 anchor: text::Anchor,
1169 line_offset_from_top: u32,
1170 },
1171}
1172
1173pub enum MultibufferSelectionMode {
1174 First,
1175 All,
1176}
1177
1178#[derive(Clone, Copy, Debug, Default)]
1179pub struct RewrapOptions {
1180 pub override_language_settings: bool,
1181 pub preserve_existing_whitespace: bool,
1182}
1183
1184impl Editor {
1185 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1186 let buffer = cx.new(|cx| Buffer::local("", cx));
1187 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1188 Self::new(
1189 EditorMode::SingleLine { auto_width: false },
1190 buffer,
1191 None,
1192 window,
1193 cx,
1194 )
1195 }
1196
1197 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1198 let buffer = cx.new(|cx| Buffer::local("", cx));
1199 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1200 Self::new(EditorMode::Full, buffer, None, window, cx)
1201 }
1202
1203 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1204 let buffer = cx.new(|cx| Buffer::local("", cx));
1205 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1206 Self::new(
1207 EditorMode::SingleLine { auto_width: true },
1208 buffer,
1209 None,
1210 window,
1211 cx,
1212 )
1213 }
1214
1215 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1216 let buffer = cx.new(|cx| Buffer::local("", cx));
1217 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1218 Self::new(
1219 EditorMode::AutoHeight { max_lines },
1220 buffer,
1221 None,
1222 window,
1223 cx,
1224 )
1225 }
1226
1227 pub fn for_buffer(
1228 buffer: Entity<Buffer>,
1229 project: Option<Entity<Project>>,
1230 window: &mut Window,
1231 cx: &mut Context<Self>,
1232 ) -> Self {
1233 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1234 Self::new(EditorMode::Full, buffer, project, window, cx)
1235 }
1236
1237 pub fn for_multibuffer(
1238 buffer: Entity<MultiBuffer>,
1239 project: Option<Entity<Project>>,
1240 window: &mut Window,
1241 cx: &mut Context<Self>,
1242 ) -> Self {
1243 Self::new(EditorMode::Full, buffer, project, window, cx)
1244 }
1245
1246 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1247 let mut clone = Self::new(
1248 self.mode,
1249 self.buffer.clone(),
1250 self.project.clone(),
1251 window,
1252 cx,
1253 );
1254 self.display_map.update(cx, |display_map, cx| {
1255 let snapshot = display_map.snapshot(cx);
1256 clone.display_map.update(cx, |display_map, cx| {
1257 display_map.set_state(&snapshot, cx);
1258 });
1259 });
1260 clone.folds_did_change(cx);
1261 clone.selections.clone_state(&self.selections);
1262 clone.scroll_manager.clone_state(&self.scroll_manager);
1263 clone.searchable = self.searchable;
1264 clone
1265 }
1266
1267 pub fn new(
1268 mode: EditorMode,
1269 buffer: Entity<MultiBuffer>,
1270 project: Option<Entity<Project>>,
1271 window: &mut Window,
1272 cx: &mut Context<Self>,
1273 ) -> Self {
1274 let style = window.text_style();
1275 let font_size = style.font_size.to_pixels(window.rem_size());
1276 let editor = cx.entity().downgrade();
1277 let fold_placeholder = FoldPlaceholder {
1278 constrain_width: true,
1279 render: Arc::new(move |fold_id, fold_range, cx| {
1280 let editor = editor.clone();
1281 div()
1282 .id(fold_id)
1283 .bg(cx.theme().colors().ghost_element_background)
1284 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1285 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1286 .rounded_xs()
1287 .size_full()
1288 .cursor_pointer()
1289 .child("⋯")
1290 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1291 .on_click(move |_, _window, cx| {
1292 editor
1293 .update(cx, |editor, cx| {
1294 editor.unfold_ranges(
1295 &[fold_range.start..fold_range.end],
1296 true,
1297 false,
1298 cx,
1299 );
1300 cx.stop_propagation();
1301 })
1302 .ok();
1303 })
1304 .into_any()
1305 }),
1306 merge_adjacent: true,
1307 ..Default::default()
1308 };
1309 let display_map = cx.new(|cx| {
1310 DisplayMap::new(
1311 buffer.clone(),
1312 style.font(),
1313 font_size,
1314 None,
1315 FILE_HEADER_HEIGHT,
1316 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1317 fold_placeholder,
1318 cx,
1319 )
1320 });
1321
1322 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1323
1324 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1325
1326 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1327 .then(|| language_settings::SoftWrap::None);
1328
1329 let mut project_subscriptions = Vec::new();
1330 if mode == EditorMode::Full {
1331 if let Some(project) = project.as_ref() {
1332 project_subscriptions.push(cx.subscribe_in(
1333 project,
1334 window,
1335 |editor, _, event, window, cx| match event {
1336 project::Event::RefreshCodeLens => {
1337 // we always query lens with actions, without storing them, always refreshing them
1338 }
1339 project::Event::RefreshInlayHints => {
1340 editor
1341 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1342 }
1343 project::Event::SnippetEdit(id, snippet_edits) => {
1344 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1345 let focus_handle = editor.focus_handle(cx);
1346 if focus_handle.is_focused(window) {
1347 let snapshot = buffer.read(cx).snapshot();
1348 for (range, snippet) in snippet_edits {
1349 let editor_range =
1350 language::range_from_lsp(*range).to_offset(&snapshot);
1351 editor
1352 .insert_snippet(
1353 &[editor_range],
1354 snippet.clone(),
1355 window,
1356 cx,
1357 )
1358 .ok();
1359 }
1360 }
1361 }
1362 }
1363 _ => {}
1364 },
1365 ));
1366 if let Some(task_inventory) = project
1367 .read(cx)
1368 .task_store()
1369 .read(cx)
1370 .task_inventory()
1371 .cloned()
1372 {
1373 project_subscriptions.push(cx.observe_in(
1374 &task_inventory,
1375 window,
1376 |editor, _, window, cx| {
1377 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1378 },
1379 ));
1380 };
1381
1382 project_subscriptions.push(cx.subscribe_in(
1383 &project.read(cx).breakpoint_store(),
1384 window,
1385 |editor, _, event, window, cx| match event {
1386 BreakpointStoreEvent::ActiveDebugLineChanged => {
1387 editor.go_to_active_debug_line(window, cx);
1388 }
1389 _ => {}
1390 },
1391 ));
1392 }
1393 }
1394
1395 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1396
1397 let inlay_hint_settings =
1398 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1399 let focus_handle = cx.focus_handle();
1400 cx.on_focus(&focus_handle, window, Self::handle_focus)
1401 .detach();
1402 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1403 .detach();
1404 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1405 .detach();
1406 cx.on_blur(&focus_handle, window, Self::handle_blur)
1407 .detach();
1408
1409 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1410 Some(false)
1411 } else {
1412 None
1413 };
1414
1415 let breakpoint_store = match (mode, project.as_ref()) {
1416 (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
1417 _ => None,
1418 };
1419
1420 let mut code_action_providers = Vec::new();
1421 let mut load_uncommitted_diff = None;
1422 if let Some(project) = project.clone() {
1423 load_uncommitted_diff = Some(
1424 get_uncommitted_diff_for_buffer(
1425 &project,
1426 buffer.read(cx).all_buffers(),
1427 buffer.clone(),
1428 cx,
1429 )
1430 .shared(),
1431 );
1432 code_action_providers.push(Rc::new(project) as Rc<_>);
1433 }
1434
1435 let mut this = Self {
1436 focus_handle,
1437 show_cursor_when_unfocused: false,
1438 last_focused_descendant: None,
1439 buffer: buffer.clone(),
1440 display_map: display_map.clone(),
1441 selections,
1442 scroll_manager: ScrollManager::new(cx),
1443 columnar_selection_tail: None,
1444 add_selections_state: None,
1445 select_next_state: None,
1446 select_prev_state: None,
1447 selection_history: Default::default(),
1448 autoclose_regions: Default::default(),
1449 snippet_stack: Default::default(),
1450 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1451 ime_transaction: Default::default(),
1452 active_diagnostics: None,
1453 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1454 inline_diagnostics_update: Task::ready(()),
1455 inline_diagnostics: Vec::new(),
1456 soft_wrap_mode_override,
1457 hard_wrap: None,
1458 completion_provider: project.clone().map(|project| Box::new(project) as _),
1459 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1460 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1461 project,
1462 blink_manager: blink_manager.clone(),
1463 show_local_selections: true,
1464 show_scrollbars: true,
1465 mode,
1466 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1467 show_gutter: mode == EditorMode::Full,
1468 show_line_numbers: None,
1469 use_relative_line_numbers: None,
1470 show_git_diff_gutter: None,
1471 show_code_actions: None,
1472 show_runnables: None,
1473 show_breakpoints: None,
1474 show_wrap_guides: None,
1475 show_indent_guides,
1476 placeholder_text: None,
1477 highlight_order: 0,
1478 highlighted_rows: HashMap::default(),
1479 background_highlights: Default::default(),
1480 gutter_highlights: TreeMap::default(),
1481 scrollbar_marker_state: ScrollbarMarkerState::default(),
1482 active_indent_guides_state: ActiveIndentGuidesState::default(),
1483 nav_history: None,
1484 context_menu: RefCell::new(None),
1485 context_menu_options: None,
1486 mouse_context_menu: None,
1487 completion_tasks: Default::default(),
1488 signature_help_state: SignatureHelpState::default(),
1489 auto_signature_help: None,
1490 find_all_references_task_sources: Vec::new(),
1491 next_completion_id: 0,
1492 next_inlay_id: 0,
1493 code_action_providers,
1494 available_code_actions: Default::default(),
1495 code_actions_task: Default::default(),
1496 selection_highlight_task: Default::default(),
1497 document_highlights_task: Default::default(),
1498 linked_editing_range_task: Default::default(),
1499 pending_rename: Default::default(),
1500 searchable: true,
1501 cursor_shape: EditorSettings::get_global(cx)
1502 .cursor_shape
1503 .unwrap_or_default(),
1504 current_line_highlight: None,
1505 autoindent_mode: Some(AutoindentMode::EachLine),
1506 collapse_matches: false,
1507 workspace: None,
1508 input_enabled: true,
1509 use_modal_editing: mode == EditorMode::Full,
1510 read_only: false,
1511 use_autoclose: true,
1512 use_auto_surround: true,
1513 auto_replace_emoji_shortcode: false,
1514 jsx_tag_auto_close_enabled_in_any_buffer: false,
1515 leader_peer_id: None,
1516 remote_id: None,
1517 hover_state: Default::default(),
1518 pending_mouse_down: None,
1519 hovered_link_state: Default::default(),
1520 edit_prediction_provider: None,
1521 active_inline_completion: None,
1522 stale_inline_completion_in_menu: None,
1523 edit_prediction_preview: EditPredictionPreview::Inactive {
1524 released_too_fast: false,
1525 },
1526 inline_diagnostics_enabled: mode == EditorMode::Full,
1527 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1528
1529 gutter_hovered: false,
1530 pixel_position_of_newest_cursor: None,
1531 last_bounds: None,
1532 last_position_map: None,
1533 expect_bounds_change: None,
1534 gutter_dimensions: GutterDimensions::default(),
1535 style: None,
1536 show_cursor_names: false,
1537 hovered_cursors: Default::default(),
1538 next_editor_action_id: EditorActionId::default(),
1539 editor_actions: Rc::default(),
1540 inline_completions_hidden_for_vim_mode: false,
1541 show_inline_completions_override: None,
1542 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1543 edit_prediction_settings: EditPredictionSettings::Disabled,
1544 edit_prediction_indent_conflict: false,
1545 edit_prediction_requires_modifier_in_indent_conflict: true,
1546 custom_context_menu: None,
1547 show_git_blame_gutter: false,
1548 show_git_blame_inline: false,
1549 show_selection_menu: None,
1550 show_git_blame_inline_delay_task: None,
1551 git_blame_inline_tooltip: None,
1552 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1553 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1554 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1555 .session
1556 .restore_unsaved_buffers,
1557 blame: None,
1558 blame_subscription: None,
1559 tasks: Default::default(),
1560
1561 breakpoint_store,
1562 gutter_breakpoint_indicator: (None, None),
1563 _subscriptions: vec![
1564 cx.observe(&buffer, Self::on_buffer_changed),
1565 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1566 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1567 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1568 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1569 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1570 cx.observe_window_activation(window, |editor, window, cx| {
1571 let active = window.is_window_active();
1572 editor.blink_manager.update(cx, |blink_manager, cx| {
1573 if active {
1574 blink_manager.enable(cx);
1575 } else {
1576 blink_manager.disable(cx);
1577 }
1578 });
1579 }),
1580 ],
1581 tasks_update_task: None,
1582 linked_edit_ranges: Default::default(),
1583 in_project_search: false,
1584 previous_search_ranges: None,
1585 breadcrumb_header: None,
1586 focused_block: None,
1587 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1588 addons: HashMap::default(),
1589 registered_buffers: HashMap::default(),
1590 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1591 selection_mark_mode: false,
1592 toggle_fold_multiple_buffers: Task::ready(()),
1593 serialize_selections: Task::ready(()),
1594 serialize_folds: Task::ready(()),
1595 text_style_refinement: None,
1596 load_diff_task: load_uncommitted_diff,
1597 mouse_cursor_hidden: false,
1598 hide_mouse_mode: EditorSettings::get_global(cx)
1599 .hide_mouse
1600 .unwrap_or_default(),
1601 };
1602 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1603 this._subscriptions
1604 .push(cx.observe(breakpoints, |_, _, cx| {
1605 cx.notify();
1606 }));
1607 }
1608 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1609 this._subscriptions.extend(project_subscriptions);
1610
1611 this._subscriptions.push(cx.subscribe_in(
1612 &cx.entity(),
1613 window,
1614 |editor, _, e: &EditorEvent, window, cx| {
1615 if let EditorEvent::SelectionsChanged { local } = e {
1616 if *local {
1617 let new_anchor = editor.scroll_manager.anchor();
1618 let snapshot = editor.snapshot(window, cx);
1619 editor.update_restoration_data(cx, move |data| {
1620 data.scroll_position = (
1621 new_anchor.top_row(&snapshot.buffer_snapshot),
1622 new_anchor.offset,
1623 );
1624 });
1625 }
1626 }
1627 },
1628 ));
1629
1630 this.end_selection(window, cx);
1631 this.scroll_manager.show_scrollbars(window, cx);
1632 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1633
1634 if mode == EditorMode::Full {
1635 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1636 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1637
1638 if this.git_blame_inline_enabled {
1639 this.git_blame_inline_enabled = true;
1640 this.start_git_blame_inline(false, window, cx);
1641 }
1642
1643 this.go_to_active_debug_line(window, cx);
1644
1645 if let Some(buffer) = buffer.read(cx).as_singleton() {
1646 if let Some(project) = this.project.as_ref() {
1647 let handle = project.update(cx, |project, cx| {
1648 project.register_buffer_with_language_servers(&buffer, cx)
1649 });
1650 this.registered_buffers
1651 .insert(buffer.read(cx).remote_id(), handle);
1652 }
1653 }
1654 }
1655
1656 this.report_editor_event("Editor Opened", None, cx);
1657 this
1658 }
1659
1660 pub fn deploy_mouse_context_menu(
1661 &mut self,
1662 position: gpui::Point<Pixels>,
1663 context_menu: Entity<ContextMenu>,
1664 window: &mut Window,
1665 cx: &mut Context<Self>,
1666 ) {
1667 self.mouse_context_menu = Some(MouseContextMenu::new(
1668 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1669 context_menu,
1670 window,
1671 cx,
1672 ));
1673 }
1674
1675 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1676 self.mouse_context_menu
1677 .as_ref()
1678 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1679 }
1680
1681 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1682 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1683 }
1684
1685 fn key_context_internal(
1686 &self,
1687 has_active_edit_prediction: bool,
1688 window: &Window,
1689 cx: &App,
1690 ) -> KeyContext {
1691 let mut key_context = KeyContext::new_with_defaults();
1692 key_context.add("Editor");
1693 let mode = match self.mode {
1694 EditorMode::SingleLine { .. } => "single_line",
1695 EditorMode::AutoHeight { .. } => "auto_height",
1696 EditorMode::Full => "full",
1697 };
1698
1699 if EditorSettings::jupyter_enabled(cx) {
1700 key_context.add("jupyter");
1701 }
1702
1703 key_context.set("mode", mode);
1704 if self.pending_rename.is_some() {
1705 key_context.add("renaming");
1706 }
1707
1708 match self.context_menu.borrow().as_ref() {
1709 Some(CodeContextMenu::Completions(_)) => {
1710 key_context.add("menu");
1711 key_context.add("showing_completions");
1712 }
1713 Some(CodeContextMenu::CodeActions(_)) => {
1714 key_context.add("menu");
1715 key_context.add("showing_code_actions")
1716 }
1717 None => {}
1718 }
1719
1720 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1721 if !self.focus_handle(cx).contains_focused(window, cx)
1722 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1723 {
1724 for addon in self.addons.values() {
1725 addon.extend_key_context(&mut key_context, cx)
1726 }
1727 }
1728
1729 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1730 if let Some(extension) = singleton_buffer
1731 .read(cx)
1732 .file()
1733 .and_then(|file| file.path().extension()?.to_str())
1734 {
1735 key_context.set("extension", extension.to_string());
1736 }
1737 } else {
1738 key_context.add("multibuffer");
1739 }
1740
1741 if has_active_edit_prediction {
1742 if self.edit_prediction_in_conflict() {
1743 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1744 } else {
1745 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1746 key_context.add("copilot_suggestion");
1747 }
1748 }
1749
1750 if self.selection_mark_mode {
1751 key_context.add("selection_mode");
1752 }
1753
1754 key_context
1755 }
1756
1757 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1758 self.mouse_cursor_hidden = match origin {
1759 HideMouseCursorOrigin::TypingAction => {
1760 matches!(
1761 self.hide_mouse_mode,
1762 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1763 )
1764 }
1765 HideMouseCursorOrigin::MovementAction => {
1766 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1767 }
1768 };
1769 }
1770
1771 pub fn edit_prediction_in_conflict(&self) -> bool {
1772 if !self.show_edit_predictions_in_menu() {
1773 return false;
1774 }
1775
1776 let showing_completions = self
1777 .context_menu
1778 .borrow()
1779 .as_ref()
1780 .map_or(false, |context| {
1781 matches!(context, CodeContextMenu::Completions(_))
1782 });
1783
1784 showing_completions
1785 || self.edit_prediction_requires_modifier()
1786 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1787 // bindings to insert tab characters.
1788 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1789 }
1790
1791 pub fn accept_edit_prediction_keybind(
1792 &self,
1793 window: &Window,
1794 cx: &App,
1795 ) -> AcceptEditPredictionBinding {
1796 let key_context = self.key_context_internal(true, window, cx);
1797 let in_conflict = self.edit_prediction_in_conflict();
1798
1799 AcceptEditPredictionBinding(
1800 window
1801 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1802 .into_iter()
1803 .filter(|binding| {
1804 !in_conflict
1805 || binding
1806 .keystrokes()
1807 .first()
1808 .map_or(false, |keystroke| keystroke.modifiers.modified())
1809 })
1810 .rev()
1811 .min_by_key(|binding| {
1812 binding
1813 .keystrokes()
1814 .first()
1815 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1816 }),
1817 )
1818 }
1819
1820 pub fn new_file(
1821 workspace: &mut Workspace,
1822 _: &workspace::NewFile,
1823 window: &mut Window,
1824 cx: &mut Context<Workspace>,
1825 ) {
1826 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1827 "Failed to create buffer",
1828 window,
1829 cx,
1830 |e, _, _| match e.error_code() {
1831 ErrorCode::RemoteUpgradeRequired => Some(format!(
1832 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1833 e.error_tag("required").unwrap_or("the latest version")
1834 )),
1835 _ => None,
1836 },
1837 );
1838 }
1839
1840 pub fn new_in_workspace(
1841 workspace: &mut Workspace,
1842 window: &mut Window,
1843 cx: &mut Context<Workspace>,
1844 ) -> Task<Result<Entity<Editor>>> {
1845 let project = workspace.project().clone();
1846 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1847
1848 cx.spawn_in(window, async move |workspace, cx| {
1849 let buffer = create.await?;
1850 workspace.update_in(cx, |workspace, window, cx| {
1851 let editor =
1852 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1853 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1854 editor
1855 })
1856 })
1857 }
1858
1859 fn new_file_vertical(
1860 workspace: &mut Workspace,
1861 _: &workspace::NewFileSplitVertical,
1862 window: &mut Window,
1863 cx: &mut Context<Workspace>,
1864 ) {
1865 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1866 }
1867
1868 fn new_file_horizontal(
1869 workspace: &mut Workspace,
1870 _: &workspace::NewFileSplitHorizontal,
1871 window: &mut Window,
1872 cx: &mut Context<Workspace>,
1873 ) {
1874 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1875 }
1876
1877 fn new_file_in_direction(
1878 workspace: &mut Workspace,
1879 direction: SplitDirection,
1880 window: &mut Window,
1881 cx: &mut Context<Workspace>,
1882 ) {
1883 let project = workspace.project().clone();
1884 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1885
1886 cx.spawn_in(window, async move |workspace, cx| {
1887 let buffer = create.await?;
1888 workspace.update_in(cx, move |workspace, window, cx| {
1889 workspace.split_item(
1890 direction,
1891 Box::new(
1892 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1893 ),
1894 window,
1895 cx,
1896 )
1897 })?;
1898 anyhow::Ok(())
1899 })
1900 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1901 match e.error_code() {
1902 ErrorCode::RemoteUpgradeRequired => Some(format!(
1903 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1904 e.error_tag("required").unwrap_or("the latest version")
1905 )),
1906 _ => None,
1907 }
1908 });
1909 }
1910
1911 pub fn leader_peer_id(&self) -> Option<PeerId> {
1912 self.leader_peer_id
1913 }
1914
1915 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1916 &self.buffer
1917 }
1918
1919 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1920 self.workspace.as_ref()?.0.upgrade()
1921 }
1922
1923 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1924 self.buffer().read(cx).title(cx)
1925 }
1926
1927 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1928 let git_blame_gutter_max_author_length = self
1929 .render_git_blame_gutter(cx)
1930 .then(|| {
1931 if let Some(blame) = self.blame.as_ref() {
1932 let max_author_length =
1933 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1934 Some(max_author_length)
1935 } else {
1936 None
1937 }
1938 })
1939 .flatten();
1940
1941 EditorSnapshot {
1942 mode: self.mode,
1943 show_gutter: self.show_gutter,
1944 show_line_numbers: self.show_line_numbers,
1945 show_git_diff_gutter: self.show_git_diff_gutter,
1946 show_code_actions: self.show_code_actions,
1947 show_runnables: self.show_runnables,
1948 show_breakpoints: self.show_breakpoints,
1949 git_blame_gutter_max_author_length,
1950 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1951 scroll_anchor: self.scroll_manager.anchor(),
1952 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1953 placeholder_text: self.placeholder_text.clone(),
1954 is_focused: self.focus_handle.is_focused(window),
1955 current_line_highlight: self
1956 .current_line_highlight
1957 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1958 gutter_hovered: self.gutter_hovered,
1959 }
1960 }
1961
1962 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1963 self.buffer.read(cx).language_at(point, cx)
1964 }
1965
1966 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1967 self.buffer.read(cx).read(cx).file_at(point).cloned()
1968 }
1969
1970 pub fn active_excerpt(
1971 &self,
1972 cx: &App,
1973 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1974 self.buffer
1975 .read(cx)
1976 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1977 }
1978
1979 pub fn mode(&self) -> EditorMode {
1980 self.mode
1981 }
1982
1983 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1984 self.collaboration_hub.as_deref()
1985 }
1986
1987 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1988 self.collaboration_hub = Some(hub);
1989 }
1990
1991 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1992 self.in_project_search = in_project_search;
1993 }
1994
1995 pub fn set_custom_context_menu(
1996 &mut self,
1997 f: impl 'static
1998 + Fn(
1999 &mut Self,
2000 DisplayPoint,
2001 &mut Window,
2002 &mut Context<Self>,
2003 ) -> Option<Entity<ui::ContextMenu>>,
2004 ) {
2005 self.custom_context_menu = Some(Box::new(f))
2006 }
2007
2008 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2009 self.completion_provider = provider;
2010 }
2011
2012 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2013 self.semantics_provider.clone()
2014 }
2015
2016 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2017 self.semantics_provider = provider;
2018 }
2019
2020 pub fn set_edit_prediction_provider<T>(
2021 &mut self,
2022 provider: Option<Entity<T>>,
2023 window: &mut Window,
2024 cx: &mut Context<Self>,
2025 ) where
2026 T: EditPredictionProvider,
2027 {
2028 self.edit_prediction_provider =
2029 provider.map(|provider| RegisteredInlineCompletionProvider {
2030 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2031 if this.focus_handle.is_focused(window) {
2032 this.update_visible_inline_completion(window, cx);
2033 }
2034 }),
2035 provider: Arc::new(provider),
2036 });
2037 self.update_edit_prediction_settings(cx);
2038 self.refresh_inline_completion(false, false, window, cx);
2039 }
2040
2041 pub fn placeholder_text(&self) -> Option<&str> {
2042 self.placeholder_text.as_deref()
2043 }
2044
2045 pub fn set_placeholder_text(
2046 &mut self,
2047 placeholder_text: impl Into<Arc<str>>,
2048 cx: &mut Context<Self>,
2049 ) {
2050 let placeholder_text = Some(placeholder_text.into());
2051 if self.placeholder_text != placeholder_text {
2052 self.placeholder_text = placeholder_text;
2053 cx.notify();
2054 }
2055 }
2056
2057 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2058 self.cursor_shape = cursor_shape;
2059
2060 // Disrupt blink for immediate user feedback that the cursor shape has changed
2061 self.blink_manager.update(cx, BlinkManager::show_cursor);
2062
2063 cx.notify();
2064 }
2065
2066 pub fn set_current_line_highlight(
2067 &mut self,
2068 current_line_highlight: Option<CurrentLineHighlight>,
2069 ) {
2070 self.current_line_highlight = current_line_highlight;
2071 }
2072
2073 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2074 self.collapse_matches = collapse_matches;
2075 }
2076
2077 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2078 let buffers = self.buffer.read(cx).all_buffers();
2079 let Some(project) = self.project.as_ref() else {
2080 return;
2081 };
2082 project.update(cx, |project, cx| {
2083 for buffer in buffers {
2084 self.registered_buffers
2085 .entry(buffer.read(cx).remote_id())
2086 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2087 }
2088 })
2089 }
2090
2091 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2092 if self.collapse_matches {
2093 return range.start..range.start;
2094 }
2095 range.clone()
2096 }
2097
2098 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2099 if self.display_map.read(cx).clip_at_line_ends != clip {
2100 self.display_map
2101 .update(cx, |map, _| map.clip_at_line_ends = clip);
2102 }
2103 }
2104
2105 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2106 self.input_enabled = input_enabled;
2107 }
2108
2109 pub fn set_inline_completions_hidden_for_vim_mode(
2110 &mut self,
2111 hidden: bool,
2112 window: &mut Window,
2113 cx: &mut Context<Self>,
2114 ) {
2115 if hidden != self.inline_completions_hidden_for_vim_mode {
2116 self.inline_completions_hidden_for_vim_mode = hidden;
2117 if hidden {
2118 self.update_visible_inline_completion(window, cx);
2119 } else {
2120 self.refresh_inline_completion(true, false, window, cx);
2121 }
2122 }
2123 }
2124
2125 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2126 self.menu_inline_completions_policy = value;
2127 }
2128
2129 pub fn set_autoindent(&mut self, autoindent: bool) {
2130 if autoindent {
2131 self.autoindent_mode = Some(AutoindentMode::EachLine);
2132 } else {
2133 self.autoindent_mode = None;
2134 }
2135 }
2136
2137 pub fn read_only(&self, cx: &App) -> bool {
2138 self.read_only || self.buffer.read(cx).read_only()
2139 }
2140
2141 pub fn set_read_only(&mut self, read_only: bool) {
2142 self.read_only = read_only;
2143 }
2144
2145 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2146 self.use_autoclose = autoclose;
2147 }
2148
2149 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2150 self.use_auto_surround = auto_surround;
2151 }
2152
2153 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2154 self.auto_replace_emoji_shortcode = auto_replace;
2155 }
2156
2157 pub fn toggle_edit_predictions(
2158 &mut self,
2159 _: &ToggleEditPrediction,
2160 window: &mut Window,
2161 cx: &mut Context<Self>,
2162 ) {
2163 if self.show_inline_completions_override.is_some() {
2164 self.set_show_edit_predictions(None, window, cx);
2165 } else {
2166 let show_edit_predictions = !self.edit_predictions_enabled();
2167 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2168 }
2169 }
2170
2171 pub fn set_show_edit_predictions(
2172 &mut self,
2173 show_edit_predictions: Option<bool>,
2174 window: &mut Window,
2175 cx: &mut Context<Self>,
2176 ) {
2177 self.show_inline_completions_override = show_edit_predictions;
2178 self.update_edit_prediction_settings(cx);
2179
2180 if let Some(false) = show_edit_predictions {
2181 self.discard_inline_completion(false, cx);
2182 } else {
2183 self.refresh_inline_completion(false, true, window, cx);
2184 }
2185 }
2186
2187 fn inline_completions_disabled_in_scope(
2188 &self,
2189 buffer: &Entity<Buffer>,
2190 buffer_position: language::Anchor,
2191 cx: &App,
2192 ) -> bool {
2193 let snapshot = buffer.read(cx).snapshot();
2194 let settings = snapshot.settings_at(buffer_position, cx);
2195
2196 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2197 return false;
2198 };
2199
2200 scope.override_name().map_or(false, |scope_name| {
2201 settings
2202 .edit_predictions_disabled_in
2203 .iter()
2204 .any(|s| s == scope_name)
2205 })
2206 }
2207
2208 pub fn set_use_modal_editing(&mut self, to: bool) {
2209 self.use_modal_editing = to;
2210 }
2211
2212 pub fn use_modal_editing(&self) -> bool {
2213 self.use_modal_editing
2214 }
2215
2216 fn selections_did_change(
2217 &mut self,
2218 local: bool,
2219 old_cursor_position: &Anchor,
2220 show_completions: bool,
2221 window: &mut Window,
2222 cx: &mut Context<Self>,
2223 ) {
2224 window.invalidate_character_coordinates();
2225
2226 // Copy selections to primary selection buffer
2227 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2228 if local {
2229 let selections = self.selections.all::<usize>(cx);
2230 let buffer_handle = self.buffer.read(cx).read(cx);
2231
2232 let mut text = String::new();
2233 for (index, selection) in selections.iter().enumerate() {
2234 let text_for_selection = buffer_handle
2235 .text_for_range(selection.start..selection.end)
2236 .collect::<String>();
2237
2238 text.push_str(&text_for_selection);
2239 if index != selections.len() - 1 {
2240 text.push('\n');
2241 }
2242 }
2243
2244 if !text.is_empty() {
2245 cx.write_to_primary(ClipboardItem::new_string(text));
2246 }
2247 }
2248
2249 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2250 self.buffer.update(cx, |buffer, cx| {
2251 buffer.set_active_selections(
2252 &self.selections.disjoint_anchors(),
2253 self.selections.line_mode,
2254 self.cursor_shape,
2255 cx,
2256 )
2257 });
2258 }
2259 let display_map = self
2260 .display_map
2261 .update(cx, |display_map, cx| display_map.snapshot(cx));
2262 let buffer = &display_map.buffer_snapshot;
2263 self.add_selections_state = None;
2264 self.select_next_state = None;
2265 self.select_prev_state = None;
2266 self.select_syntax_node_history.try_clear();
2267 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2268 self.snippet_stack
2269 .invalidate(&self.selections.disjoint_anchors(), buffer);
2270 self.take_rename(false, window, cx);
2271
2272 let new_cursor_position = self.selections.newest_anchor().head();
2273
2274 self.push_to_nav_history(
2275 *old_cursor_position,
2276 Some(new_cursor_position.to_point(buffer)),
2277 false,
2278 cx,
2279 );
2280
2281 if local {
2282 let new_cursor_position = self.selections.newest_anchor().head();
2283 let mut context_menu = self.context_menu.borrow_mut();
2284 let completion_menu = match context_menu.as_ref() {
2285 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2286 _ => {
2287 *context_menu = None;
2288 None
2289 }
2290 };
2291 if let Some(buffer_id) = new_cursor_position.buffer_id {
2292 if !self.registered_buffers.contains_key(&buffer_id) {
2293 if let Some(project) = self.project.as_ref() {
2294 project.update(cx, |project, cx| {
2295 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2296 return;
2297 };
2298 self.registered_buffers.insert(
2299 buffer_id,
2300 project.register_buffer_with_language_servers(&buffer, cx),
2301 );
2302 })
2303 }
2304 }
2305 }
2306
2307 if let Some(completion_menu) = completion_menu {
2308 let cursor_position = new_cursor_position.to_offset(buffer);
2309 let (word_range, kind) =
2310 buffer.surrounding_word(completion_menu.initial_position, true);
2311 if kind == Some(CharKind::Word)
2312 && word_range.to_inclusive().contains(&cursor_position)
2313 {
2314 let mut completion_menu = completion_menu.clone();
2315 drop(context_menu);
2316
2317 let query = Self::completion_query(buffer, cursor_position);
2318 cx.spawn(async move |this, cx| {
2319 completion_menu
2320 .filter(query.as_deref(), cx.background_executor().clone())
2321 .await;
2322
2323 this.update(cx, |this, cx| {
2324 let mut context_menu = this.context_menu.borrow_mut();
2325 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2326 else {
2327 return;
2328 };
2329
2330 if menu.id > completion_menu.id {
2331 return;
2332 }
2333
2334 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2335 drop(context_menu);
2336 cx.notify();
2337 })
2338 })
2339 .detach();
2340
2341 if show_completions {
2342 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2343 }
2344 } else {
2345 drop(context_menu);
2346 self.hide_context_menu(window, cx);
2347 }
2348 } else {
2349 drop(context_menu);
2350 }
2351
2352 hide_hover(self, cx);
2353
2354 if old_cursor_position.to_display_point(&display_map).row()
2355 != new_cursor_position.to_display_point(&display_map).row()
2356 {
2357 self.available_code_actions.take();
2358 }
2359 self.refresh_code_actions(window, cx);
2360 self.refresh_document_highlights(cx);
2361 self.refresh_selected_text_highlights(window, cx);
2362 refresh_matching_bracket_highlights(self, window, cx);
2363 self.update_visible_inline_completion(window, cx);
2364 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2365 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2366 if self.git_blame_inline_enabled {
2367 self.start_inline_blame_timer(window, cx);
2368 }
2369 }
2370
2371 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2372 cx.emit(EditorEvent::SelectionsChanged { local });
2373
2374 let selections = &self.selections.disjoint;
2375 if selections.len() == 1 {
2376 cx.emit(SearchEvent::ActiveMatchChanged)
2377 }
2378 if local {
2379 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2380 let inmemory_selections = selections
2381 .iter()
2382 .map(|s| {
2383 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2384 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2385 })
2386 .collect();
2387 self.update_restoration_data(cx, |data| {
2388 data.selections = inmemory_selections;
2389 });
2390
2391 if WorkspaceSettings::get(None, cx).restore_on_startup
2392 != RestoreOnStartupBehavior::None
2393 {
2394 if let Some(workspace_id) =
2395 self.workspace.as_ref().and_then(|workspace| workspace.1)
2396 {
2397 let snapshot = self.buffer().read(cx).snapshot(cx);
2398 let selections = selections.clone();
2399 let background_executor = cx.background_executor().clone();
2400 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2401 self.serialize_selections = cx.background_spawn(async move {
2402 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2403 let db_selections = selections
2404 .iter()
2405 .map(|selection| {
2406 (
2407 selection.start.to_offset(&snapshot),
2408 selection.end.to_offset(&snapshot),
2409 )
2410 })
2411 .collect();
2412
2413 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2414 .await
2415 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2416 .log_err();
2417 });
2418 }
2419 }
2420 }
2421 }
2422
2423 cx.notify();
2424 }
2425
2426 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2427 use text::ToOffset as _;
2428 use text::ToPoint as _;
2429
2430 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2431 return;
2432 }
2433
2434 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2435 return;
2436 };
2437
2438 let snapshot = singleton.read(cx).snapshot();
2439 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2440 let display_snapshot = display_map.snapshot(cx);
2441
2442 display_snapshot
2443 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2444 .map(|fold| {
2445 fold.range.start.text_anchor.to_point(&snapshot)
2446 ..fold.range.end.text_anchor.to_point(&snapshot)
2447 })
2448 .collect()
2449 });
2450 self.update_restoration_data(cx, |data| {
2451 data.folds = inmemory_folds;
2452 });
2453
2454 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2455 return;
2456 };
2457 let background_executor = cx.background_executor().clone();
2458 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2459 let db_folds = self.display_map.update(cx, |display_map, cx| {
2460 display_map
2461 .snapshot(cx)
2462 .folds_in_range(0..snapshot.len())
2463 .map(|fold| {
2464 (
2465 fold.range.start.text_anchor.to_offset(&snapshot),
2466 fold.range.end.text_anchor.to_offset(&snapshot),
2467 )
2468 })
2469 .collect()
2470 });
2471 self.serialize_folds = cx.background_spawn(async move {
2472 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2473 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2474 .await
2475 .with_context(|| {
2476 format!(
2477 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2478 )
2479 })
2480 .log_err();
2481 });
2482 }
2483
2484 pub fn sync_selections(
2485 &mut self,
2486 other: Entity<Editor>,
2487 cx: &mut Context<Self>,
2488 ) -> gpui::Subscription {
2489 let other_selections = other.read(cx).selections.disjoint.to_vec();
2490 self.selections.change_with(cx, |selections| {
2491 selections.select_anchors(other_selections);
2492 });
2493
2494 let other_subscription =
2495 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2496 EditorEvent::SelectionsChanged { local: true } => {
2497 let other_selections = other.read(cx).selections.disjoint.to_vec();
2498 if other_selections.is_empty() {
2499 return;
2500 }
2501 this.selections.change_with(cx, |selections| {
2502 selections.select_anchors(other_selections);
2503 });
2504 }
2505 _ => {}
2506 });
2507
2508 let this_subscription =
2509 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2510 EditorEvent::SelectionsChanged { local: true } => {
2511 let these_selections = this.selections.disjoint.to_vec();
2512 if these_selections.is_empty() {
2513 return;
2514 }
2515 other.update(cx, |other_editor, cx| {
2516 other_editor.selections.change_with(cx, |selections| {
2517 selections.select_anchors(these_selections);
2518 })
2519 });
2520 }
2521 _ => {}
2522 });
2523
2524 Subscription::join(other_subscription, this_subscription)
2525 }
2526
2527 pub fn change_selections<R>(
2528 &mut self,
2529 autoscroll: Option<Autoscroll>,
2530 window: &mut Window,
2531 cx: &mut Context<Self>,
2532 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2533 ) -> R {
2534 self.change_selections_inner(autoscroll, true, window, cx, change)
2535 }
2536
2537 fn change_selections_inner<R>(
2538 &mut self,
2539 autoscroll: Option<Autoscroll>,
2540 request_completions: bool,
2541 window: &mut Window,
2542 cx: &mut Context<Self>,
2543 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2544 ) -> R {
2545 let old_cursor_position = self.selections.newest_anchor().head();
2546 self.push_to_selection_history();
2547
2548 let (changed, result) = self.selections.change_with(cx, change);
2549
2550 if changed {
2551 if let Some(autoscroll) = autoscroll {
2552 self.request_autoscroll(autoscroll, cx);
2553 }
2554 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2555
2556 if self.should_open_signature_help_automatically(
2557 &old_cursor_position,
2558 self.signature_help_state.backspace_pressed(),
2559 cx,
2560 ) {
2561 self.show_signature_help(&ShowSignatureHelp, window, cx);
2562 }
2563 self.signature_help_state.set_backspace_pressed(false);
2564 }
2565
2566 result
2567 }
2568
2569 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2570 where
2571 I: IntoIterator<Item = (Range<S>, T)>,
2572 S: ToOffset,
2573 T: Into<Arc<str>>,
2574 {
2575 if self.read_only(cx) {
2576 return;
2577 }
2578
2579 self.buffer
2580 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2581 }
2582
2583 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2584 where
2585 I: IntoIterator<Item = (Range<S>, T)>,
2586 S: ToOffset,
2587 T: Into<Arc<str>>,
2588 {
2589 if self.read_only(cx) {
2590 return;
2591 }
2592
2593 self.buffer.update(cx, |buffer, cx| {
2594 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2595 });
2596 }
2597
2598 pub fn edit_with_block_indent<I, S, T>(
2599 &mut self,
2600 edits: I,
2601 original_indent_columns: Vec<Option<u32>>,
2602 cx: &mut Context<Self>,
2603 ) where
2604 I: IntoIterator<Item = (Range<S>, T)>,
2605 S: ToOffset,
2606 T: Into<Arc<str>>,
2607 {
2608 if self.read_only(cx) {
2609 return;
2610 }
2611
2612 self.buffer.update(cx, |buffer, cx| {
2613 buffer.edit(
2614 edits,
2615 Some(AutoindentMode::Block {
2616 original_indent_columns,
2617 }),
2618 cx,
2619 )
2620 });
2621 }
2622
2623 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2624 self.hide_context_menu(window, cx);
2625
2626 match phase {
2627 SelectPhase::Begin {
2628 position,
2629 add,
2630 click_count,
2631 } => self.begin_selection(position, add, click_count, window, cx),
2632 SelectPhase::BeginColumnar {
2633 position,
2634 goal_column,
2635 reset,
2636 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2637 SelectPhase::Extend {
2638 position,
2639 click_count,
2640 } => self.extend_selection(position, click_count, window, cx),
2641 SelectPhase::Update {
2642 position,
2643 goal_column,
2644 scroll_delta,
2645 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2646 SelectPhase::End => self.end_selection(window, cx),
2647 }
2648 }
2649
2650 fn extend_selection(
2651 &mut self,
2652 position: DisplayPoint,
2653 click_count: usize,
2654 window: &mut Window,
2655 cx: &mut Context<Self>,
2656 ) {
2657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2658 let tail = self.selections.newest::<usize>(cx).tail();
2659 self.begin_selection(position, false, click_count, window, cx);
2660
2661 let position = position.to_offset(&display_map, Bias::Left);
2662 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2663
2664 let mut pending_selection = self
2665 .selections
2666 .pending_anchor()
2667 .expect("extend_selection not called with pending selection");
2668 if position >= tail {
2669 pending_selection.start = tail_anchor;
2670 } else {
2671 pending_selection.end = tail_anchor;
2672 pending_selection.reversed = true;
2673 }
2674
2675 let mut pending_mode = self.selections.pending_mode().unwrap();
2676 match &mut pending_mode {
2677 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2678 _ => {}
2679 }
2680
2681 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2682 s.set_pending(pending_selection, pending_mode)
2683 });
2684 }
2685
2686 fn begin_selection(
2687 &mut self,
2688 position: DisplayPoint,
2689 add: bool,
2690 click_count: usize,
2691 window: &mut Window,
2692 cx: &mut Context<Self>,
2693 ) {
2694 if !self.focus_handle.is_focused(window) {
2695 self.last_focused_descendant = None;
2696 window.focus(&self.focus_handle);
2697 }
2698
2699 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2700 let buffer = &display_map.buffer_snapshot;
2701 let newest_selection = self.selections.newest_anchor().clone();
2702 let position = display_map.clip_point(position, Bias::Left);
2703
2704 let start;
2705 let end;
2706 let mode;
2707 let mut auto_scroll;
2708 match click_count {
2709 1 => {
2710 start = buffer.anchor_before(position.to_point(&display_map));
2711 end = start;
2712 mode = SelectMode::Character;
2713 auto_scroll = true;
2714 }
2715 2 => {
2716 let range = movement::surrounding_word(&display_map, position);
2717 start = buffer.anchor_before(range.start.to_point(&display_map));
2718 end = buffer.anchor_before(range.end.to_point(&display_map));
2719 mode = SelectMode::Word(start..end);
2720 auto_scroll = true;
2721 }
2722 3 => {
2723 let position = display_map
2724 .clip_point(position, Bias::Left)
2725 .to_point(&display_map);
2726 let line_start = display_map.prev_line_boundary(position).0;
2727 let next_line_start = buffer.clip_point(
2728 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2729 Bias::Left,
2730 );
2731 start = buffer.anchor_before(line_start);
2732 end = buffer.anchor_before(next_line_start);
2733 mode = SelectMode::Line(start..end);
2734 auto_scroll = true;
2735 }
2736 _ => {
2737 start = buffer.anchor_before(0);
2738 end = buffer.anchor_before(buffer.len());
2739 mode = SelectMode::All;
2740 auto_scroll = false;
2741 }
2742 }
2743 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2744
2745 let point_to_delete: Option<usize> = {
2746 let selected_points: Vec<Selection<Point>> =
2747 self.selections.disjoint_in_range(start..end, cx);
2748
2749 if !add || click_count > 1 {
2750 None
2751 } else if !selected_points.is_empty() {
2752 Some(selected_points[0].id)
2753 } else {
2754 let clicked_point_already_selected =
2755 self.selections.disjoint.iter().find(|selection| {
2756 selection.start.to_point(buffer) == start.to_point(buffer)
2757 || selection.end.to_point(buffer) == end.to_point(buffer)
2758 });
2759
2760 clicked_point_already_selected.map(|selection| selection.id)
2761 }
2762 };
2763
2764 let selections_count = self.selections.count();
2765
2766 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2767 if let Some(point_to_delete) = point_to_delete {
2768 s.delete(point_to_delete);
2769
2770 if selections_count == 1 {
2771 s.set_pending_anchor_range(start..end, mode);
2772 }
2773 } else {
2774 if !add {
2775 s.clear_disjoint();
2776 } else if click_count > 1 {
2777 s.delete(newest_selection.id)
2778 }
2779
2780 s.set_pending_anchor_range(start..end, mode);
2781 }
2782 });
2783 }
2784
2785 fn begin_columnar_selection(
2786 &mut self,
2787 position: DisplayPoint,
2788 goal_column: u32,
2789 reset: bool,
2790 window: &mut Window,
2791 cx: &mut Context<Self>,
2792 ) {
2793 if !self.focus_handle.is_focused(window) {
2794 self.last_focused_descendant = None;
2795 window.focus(&self.focus_handle);
2796 }
2797
2798 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2799
2800 if reset {
2801 let pointer_position = display_map
2802 .buffer_snapshot
2803 .anchor_before(position.to_point(&display_map));
2804
2805 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2806 s.clear_disjoint();
2807 s.set_pending_anchor_range(
2808 pointer_position..pointer_position,
2809 SelectMode::Character,
2810 );
2811 });
2812 }
2813
2814 let tail = self.selections.newest::<Point>(cx).tail();
2815 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2816
2817 if !reset {
2818 self.select_columns(
2819 tail.to_display_point(&display_map),
2820 position,
2821 goal_column,
2822 &display_map,
2823 window,
2824 cx,
2825 );
2826 }
2827 }
2828
2829 fn update_selection(
2830 &mut self,
2831 position: DisplayPoint,
2832 goal_column: u32,
2833 scroll_delta: gpui::Point<f32>,
2834 window: &mut Window,
2835 cx: &mut Context<Self>,
2836 ) {
2837 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2838
2839 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2840 let tail = tail.to_display_point(&display_map);
2841 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2842 } else if let Some(mut pending) = self.selections.pending_anchor() {
2843 let buffer = self.buffer.read(cx).snapshot(cx);
2844 let head;
2845 let tail;
2846 let mode = self.selections.pending_mode().unwrap();
2847 match &mode {
2848 SelectMode::Character => {
2849 head = position.to_point(&display_map);
2850 tail = pending.tail().to_point(&buffer);
2851 }
2852 SelectMode::Word(original_range) => {
2853 let original_display_range = original_range.start.to_display_point(&display_map)
2854 ..original_range.end.to_display_point(&display_map);
2855 let original_buffer_range = original_display_range.start.to_point(&display_map)
2856 ..original_display_range.end.to_point(&display_map);
2857 if movement::is_inside_word(&display_map, position)
2858 || original_display_range.contains(&position)
2859 {
2860 let word_range = movement::surrounding_word(&display_map, position);
2861 if word_range.start < original_display_range.start {
2862 head = word_range.start.to_point(&display_map);
2863 } else {
2864 head = word_range.end.to_point(&display_map);
2865 }
2866 } else {
2867 head = position.to_point(&display_map);
2868 }
2869
2870 if head <= original_buffer_range.start {
2871 tail = original_buffer_range.end;
2872 } else {
2873 tail = original_buffer_range.start;
2874 }
2875 }
2876 SelectMode::Line(original_range) => {
2877 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2878
2879 let position = display_map
2880 .clip_point(position, Bias::Left)
2881 .to_point(&display_map);
2882 let line_start = display_map.prev_line_boundary(position).0;
2883 let next_line_start = buffer.clip_point(
2884 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2885 Bias::Left,
2886 );
2887
2888 if line_start < original_range.start {
2889 head = line_start
2890 } else {
2891 head = next_line_start
2892 }
2893
2894 if head <= original_range.start {
2895 tail = original_range.end;
2896 } else {
2897 tail = original_range.start;
2898 }
2899 }
2900 SelectMode::All => {
2901 return;
2902 }
2903 };
2904
2905 if head < tail {
2906 pending.start = buffer.anchor_before(head);
2907 pending.end = buffer.anchor_before(tail);
2908 pending.reversed = true;
2909 } else {
2910 pending.start = buffer.anchor_before(tail);
2911 pending.end = buffer.anchor_before(head);
2912 pending.reversed = false;
2913 }
2914
2915 self.change_selections(None, window, cx, |s| {
2916 s.set_pending(pending, mode);
2917 });
2918 } else {
2919 log::error!("update_selection dispatched with no pending selection");
2920 return;
2921 }
2922
2923 self.apply_scroll_delta(scroll_delta, window, cx);
2924 cx.notify();
2925 }
2926
2927 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2928 self.columnar_selection_tail.take();
2929 if self.selections.pending_anchor().is_some() {
2930 let selections = self.selections.all::<usize>(cx);
2931 self.change_selections(None, window, cx, |s| {
2932 s.select(selections);
2933 s.clear_pending();
2934 });
2935 }
2936 }
2937
2938 fn select_columns(
2939 &mut self,
2940 tail: DisplayPoint,
2941 head: DisplayPoint,
2942 goal_column: u32,
2943 display_map: &DisplaySnapshot,
2944 window: &mut Window,
2945 cx: &mut Context<Self>,
2946 ) {
2947 let start_row = cmp::min(tail.row(), head.row());
2948 let end_row = cmp::max(tail.row(), head.row());
2949 let start_column = cmp::min(tail.column(), goal_column);
2950 let end_column = cmp::max(tail.column(), goal_column);
2951 let reversed = start_column < tail.column();
2952
2953 let selection_ranges = (start_row.0..=end_row.0)
2954 .map(DisplayRow)
2955 .filter_map(|row| {
2956 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2957 let start = display_map
2958 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2959 .to_point(display_map);
2960 let end = display_map
2961 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2962 .to_point(display_map);
2963 if reversed {
2964 Some(end..start)
2965 } else {
2966 Some(start..end)
2967 }
2968 } else {
2969 None
2970 }
2971 })
2972 .collect::<Vec<_>>();
2973
2974 self.change_selections(None, window, cx, |s| {
2975 s.select_ranges(selection_ranges);
2976 });
2977 cx.notify();
2978 }
2979
2980 pub fn has_pending_nonempty_selection(&self) -> bool {
2981 let pending_nonempty_selection = match self.selections.pending_anchor() {
2982 Some(Selection { start, end, .. }) => start != end,
2983 None => false,
2984 };
2985
2986 pending_nonempty_selection
2987 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2988 }
2989
2990 pub fn has_pending_selection(&self) -> bool {
2991 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2992 }
2993
2994 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2995 self.selection_mark_mode = false;
2996
2997 if self.clear_expanded_diff_hunks(cx) {
2998 cx.notify();
2999 return;
3000 }
3001 if self.dismiss_menus_and_popups(true, window, cx) {
3002 return;
3003 }
3004
3005 if self.mode == EditorMode::Full
3006 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3007 {
3008 return;
3009 }
3010
3011 cx.propagate();
3012 }
3013
3014 pub fn dismiss_menus_and_popups(
3015 &mut self,
3016 is_user_requested: bool,
3017 window: &mut Window,
3018 cx: &mut Context<Self>,
3019 ) -> bool {
3020 if self.take_rename(false, window, cx).is_some() {
3021 return true;
3022 }
3023
3024 if hide_hover(self, cx) {
3025 return true;
3026 }
3027
3028 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3029 return true;
3030 }
3031
3032 if self.hide_context_menu(window, cx).is_some() {
3033 return true;
3034 }
3035
3036 if self.mouse_context_menu.take().is_some() {
3037 return true;
3038 }
3039
3040 if is_user_requested && self.discard_inline_completion(true, cx) {
3041 return true;
3042 }
3043
3044 if self.snippet_stack.pop().is_some() {
3045 return true;
3046 }
3047
3048 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3049 self.dismiss_diagnostics(cx);
3050 return true;
3051 }
3052
3053 false
3054 }
3055
3056 fn linked_editing_ranges_for(
3057 &self,
3058 selection: Range<text::Anchor>,
3059 cx: &App,
3060 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3061 if self.linked_edit_ranges.is_empty() {
3062 return None;
3063 }
3064 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3065 selection.end.buffer_id.and_then(|end_buffer_id| {
3066 if selection.start.buffer_id != Some(end_buffer_id) {
3067 return None;
3068 }
3069 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3070 let snapshot = buffer.read(cx).snapshot();
3071 self.linked_edit_ranges
3072 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3073 .map(|ranges| (ranges, snapshot, buffer))
3074 })?;
3075 use text::ToOffset as TO;
3076 // find offset from the start of current range to current cursor position
3077 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3078
3079 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3080 let start_difference = start_offset - start_byte_offset;
3081 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3082 let end_difference = end_offset - start_byte_offset;
3083 // Current range has associated linked ranges.
3084 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3085 for range in linked_ranges.iter() {
3086 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3087 let end_offset = start_offset + end_difference;
3088 let start_offset = start_offset + start_difference;
3089 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3090 continue;
3091 }
3092 if self.selections.disjoint_anchor_ranges().any(|s| {
3093 if s.start.buffer_id != selection.start.buffer_id
3094 || s.end.buffer_id != selection.end.buffer_id
3095 {
3096 return false;
3097 }
3098 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3099 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3100 }) {
3101 continue;
3102 }
3103 let start = buffer_snapshot.anchor_after(start_offset);
3104 let end = buffer_snapshot.anchor_after(end_offset);
3105 linked_edits
3106 .entry(buffer.clone())
3107 .or_default()
3108 .push(start..end);
3109 }
3110 Some(linked_edits)
3111 }
3112
3113 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3114 let text: Arc<str> = text.into();
3115
3116 if self.read_only(cx) {
3117 return;
3118 }
3119
3120 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3121
3122 let selections = self.selections.all_adjusted(cx);
3123 let mut bracket_inserted = false;
3124 let mut edits = Vec::new();
3125 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3126 let mut new_selections = Vec::with_capacity(selections.len());
3127 let mut new_autoclose_regions = Vec::new();
3128 let snapshot = self.buffer.read(cx).read(cx);
3129
3130 for (selection, autoclose_region) in
3131 self.selections_with_autoclose_regions(selections, &snapshot)
3132 {
3133 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3134 // Determine if the inserted text matches the opening or closing
3135 // bracket of any of this language's bracket pairs.
3136 let mut bracket_pair = None;
3137 let mut is_bracket_pair_start = false;
3138 let mut is_bracket_pair_end = false;
3139 if !text.is_empty() {
3140 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3141 // and they are removing the character that triggered IME popup.
3142 for (pair, enabled) in scope.brackets() {
3143 if !pair.close && !pair.surround {
3144 continue;
3145 }
3146
3147 if enabled && pair.start.ends_with(text.as_ref()) {
3148 let prefix_len = pair.start.len() - text.len();
3149 let preceding_text_matches_prefix = prefix_len == 0
3150 || (selection.start.column >= (prefix_len as u32)
3151 && snapshot.contains_str_at(
3152 Point::new(
3153 selection.start.row,
3154 selection.start.column - (prefix_len as u32),
3155 ),
3156 &pair.start[..prefix_len],
3157 ));
3158 if preceding_text_matches_prefix {
3159 bracket_pair = Some(pair.clone());
3160 is_bracket_pair_start = true;
3161 break;
3162 }
3163 }
3164 if pair.end.as_str() == text.as_ref() {
3165 bracket_pair = Some(pair.clone());
3166 is_bracket_pair_end = true;
3167 break;
3168 }
3169 }
3170 }
3171
3172 if let Some(bracket_pair) = bracket_pair {
3173 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3174 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3175 let auto_surround =
3176 self.use_auto_surround && snapshot_settings.use_auto_surround;
3177 if selection.is_empty() {
3178 if is_bracket_pair_start {
3179 // If the inserted text is a suffix of an opening bracket and the
3180 // selection is preceded by the rest of the opening bracket, then
3181 // insert the closing bracket.
3182 let following_text_allows_autoclose = snapshot
3183 .chars_at(selection.start)
3184 .next()
3185 .map_or(true, |c| scope.should_autoclose_before(c));
3186
3187 let preceding_text_allows_autoclose = selection.start.column == 0
3188 || snapshot.reversed_chars_at(selection.start).next().map_or(
3189 true,
3190 |c| {
3191 bracket_pair.start != bracket_pair.end
3192 || !snapshot
3193 .char_classifier_at(selection.start)
3194 .is_word(c)
3195 },
3196 );
3197
3198 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3199 && bracket_pair.start.len() == 1
3200 {
3201 let target = bracket_pair.start.chars().next().unwrap();
3202 let current_line_count = snapshot
3203 .reversed_chars_at(selection.start)
3204 .take_while(|&c| c != '\n')
3205 .filter(|&c| c == target)
3206 .count();
3207 current_line_count % 2 == 1
3208 } else {
3209 false
3210 };
3211
3212 if autoclose
3213 && bracket_pair.close
3214 && following_text_allows_autoclose
3215 && preceding_text_allows_autoclose
3216 && !is_closing_quote
3217 {
3218 let anchor = snapshot.anchor_before(selection.end);
3219 new_selections.push((selection.map(|_| anchor), text.len()));
3220 new_autoclose_regions.push((
3221 anchor,
3222 text.len(),
3223 selection.id,
3224 bracket_pair.clone(),
3225 ));
3226 edits.push((
3227 selection.range(),
3228 format!("{}{}", text, bracket_pair.end).into(),
3229 ));
3230 bracket_inserted = true;
3231 continue;
3232 }
3233 }
3234
3235 if let Some(region) = autoclose_region {
3236 // If the selection is followed by an auto-inserted closing bracket,
3237 // then don't insert that closing bracket again; just move the selection
3238 // past the closing bracket.
3239 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3240 && text.as_ref() == region.pair.end.as_str();
3241 if should_skip {
3242 let anchor = snapshot.anchor_after(selection.end);
3243 new_selections
3244 .push((selection.map(|_| anchor), region.pair.end.len()));
3245 continue;
3246 }
3247 }
3248
3249 let always_treat_brackets_as_autoclosed = snapshot
3250 .language_settings_at(selection.start, cx)
3251 .always_treat_brackets_as_autoclosed;
3252 if always_treat_brackets_as_autoclosed
3253 && is_bracket_pair_end
3254 && snapshot.contains_str_at(selection.end, text.as_ref())
3255 {
3256 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3257 // and the inserted text is a closing bracket and the selection is followed
3258 // by the closing bracket then move the selection past the closing bracket.
3259 let anchor = snapshot.anchor_after(selection.end);
3260 new_selections.push((selection.map(|_| anchor), text.len()));
3261 continue;
3262 }
3263 }
3264 // If an opening bracket is 1 character long and is typed while
3265 // text is selected, then surround that text with the bracket pair.
3266 else if auto_surround
3267 && bracket_pair.surround
3268 && is_bracket_pair_start
3269 && bracket_pair.start.chars().count() == 1
3270 {
3271 edits.push((selection.start..selection.start, text.clone()));
3272 edits.push((
3273 selection.end..selection.end,
3274 bracket_pair.end.as_str().into(),
3275 ));
3276 bracket_inserted = true;
3277 new_selections.push((
3278 Selection {
3279 id: selection.id,
3280 start: snapshot.anchor_after(selection.start),
3281 end: snapshot.anchor_before(selection.end),
3282 reversed: selection.reversed,
3283 goal: selection.goal,
3284 },
3285 0,
3286 ));
3287 continue;
3288 }
3289 }
3290 }
3291
3292 if self.auto_replace_emoji_shortcode
3293 && selection.is_empty()
3294 && text.as_ref().ends_with(':')
3295 {
3296 if let Some(possible_emoji_short_code) =
3297 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3298 {
3299 if !possible_emoji_short_code.is_empty() {
3300 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3301 let emoji_shortcode_start = Point::new(
3302 selection.start.row,
3303 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3304 );
3305
3306 // Remove shortcode from buffer
3307 edits.push((
3308 emoji_shortcode_start..selection.start,
3309 "".to_string().into(),
3310 ));
3311 new_selections.push((
3312 Selection {
3313 id: selection.id,
3314 start: snapshot.anchor_after(emoji_shortcode_start),
3315 end: snapshot.anchor_before(selection.start),
3316 reversed: selection.reversed,
3317 goal: selection.goal,
3318 },
3319 0,
3320 ));
3321
3322 // Insert emoji
3323 let selection_start_anchor = snapshot.anchor_after(selection.start);
3324 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3325 edits.push((selection.start..selection.end, emoji.to_string().into()));
3326
3327 continue;
3328 }
3329 }
3330 }
3331 }
3332
3333 // If not handling any auto-close operation, then just replace the selected
3334 // text with the given input and move the selection to the end of the
3335 // newly inserted text.
3336 let anchor = snapshot.anchor_after(selection.end);
3337 if !self.linked_edit_ranges.is_empty() {
3338 let start_anchor = snapshot.anchor_before(selection.start);
3339
3340 let is_word_char = text.chars().next().map_or(true, |char| {
3341 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3342 classifier.is_word(char)
3343 });
3344
3345 if is_word_char {
3346 if let Some(ranges) = self
3347 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3348 {
3349 for (buffer, edits) in ranges {
3350 linked_edits
3351 .entry(buffer.clone())
3352 .or_default()
3353 .extend(edits.into_iter().map(|range| (range, text.clone())));
3354 }
3355 }
3356 }
3357 }
3358
3359 new_selections.push((selection.map(|_| anchor), 0));
3360 edits.push((selection.start..selection.end, text.clone()));
3361 }
3362
3363 drop(snapshot);
3364
3365 self.transact(window, cx, |this, window, cx| {
3366 let initial_buffer_versions =
3367 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3368
3369 this.buffer.update(cx, |buffer, cx| {
3370 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3371 });
3372 for (buffer, edits) in linked_edits {
3373 buffer.update(cx, |buffer, cx| {
3374 let snapshot = buffer.snapshot();
3375 let edits = edits
3376 .into_iter()
3377 .map(|(range, text)| {
3378 use text::ToPoint as TP;
3379 let end_point = TP::to_point(&range.end, &snapshot);
3380 let start_point = TP::to_point(&range.start, &snapshot);
3381 (start_point..end_point, text)
3382 })
3383 .sorted_by_key(|(range, _)| range.start);
3384 buffer.edit(edits, None, cx);
3385 })
3386 }
3387 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3388 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3389 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3390 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3391 .zip(new_selection_deltas)
3392 .map(|(selection, delta)| Selection {
3393 id: selection.id,
3394 start: selection.start + delta,
3395 end: selection.end + delta,
3396 reversed: selection.reversed,
3397 goal: SelectionGoal::None,
3398 })
3399 .collect::<Vec<_>>();
3400
3401 let mut i = 0;
3402 for (position, delta, selection_id, pair) in new_autoclose_regions {
3403 let position = position.to_offset(&map.buffer_snapshot) + delta;
3404 let start = map.buffer_snapshot.anchor_before(position);
3405 let end = map.buffer_snapshot.anchor_after(position);
3406 while let Some(existing_state) = this.autoclose_regions.get(i) {
3407 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3408 Ordering::Less => i += 1,
3409 Ordering::Greater => break,
3410 Ordering::Equal => {
3411 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3412 Ordering::Less => i += 1,
3413 Ordering::Equal => break,
3414 Ordering::Greater => break,
3415 }
3416 }
3417 }
3418 }
3419 this.autoclose_regions.insert(
3420 i,
3421 AutocloseRegion {
3422 selection_id,
3423 range: start..end,
3424 pair,
3425 },
3426 );
3427 }
3428
3429 let had_active_inline_completion = this.has_active_inline_completion();
3430 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3431 s.select(new_selections)
3432 });
3433
3434 if !bracket_inserted {
3435 if let Some(on_type_format_task) =
3436 this.trigger_on_type_formatting(text.to_string(), window, cx)
3437 {
3438 on_type_format_task.detach_and_log_err(cx);
3439 }
3440 }
3441
3442 let editor_settings = EditorSettings::get_global(cx);
3443 if bracket_inserted
3444 && (editor_settings.auto_signature_help
3445 || editor_settings.show_signature_help_after_edits)
3446 {
3447 this.show_signature_help(&ShowSignatureHelp, window, cx);
3448 }
3449
3450 let trigger_in_words =
3451 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3452 if this.hard_wrap.is_some() {
3453 let latest: Range<Point> = this.selections.newest(cx).range();
3454 if latest.is_empty()
3455 && this
3456 .buffer()
3457 .read(cx)
3458 .snapshot(cx)
3459 .line_len(MultiBufferRow(latest.start.row))
3460 == latest.start.column
3461 {
3462 this.rewrap_impl(
3463 RewrapOptions {
3464 override_language_settings: true,
3465 preserve_existing_whitespace: true,
3466 },
3467 cx,
3468 )
3469 }
3470 }
3471 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3472 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3473 this.refresh_inline_completion(true, false, window, cx);
3474 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3475 });
3476 }
3477
3478 fn find_possible_emoji_shortcode_at_position(
3479 snapshot: &MultiBufferSnapshot,
3480 position: Point,
3481 ) -> Option<String> {
3482 let mut chars = Vec::new();
3483 let mut found_colon = false;
3484 for char in snapshot.reversed_chars_at(position).take(100) {
3485 // Found a possible emoji shortcode in the middle of the buffer
3486 if found_colon {
3487 if char.is_whitespace() {
3488 chars.reverse();
3489 return Some(chars.iter().collect());
3490 }
3491 // If the previous character is not a whitespace, we are in the middle of a word
3492 // and we only want to complete the shortcode if the word is made up of other emojis
3493 let mut containing_word = String::new();
3494 for ch in snapshot
3495 .reversed_chars_at(position)
3496 .skip(chars.len() + 1)
3497 .take(100)
3498 {
3499 if ch.is_whitespace() {
3500 break;
3501 }
3502 containing_word.push(ch);
3503 }
3504 let containing_word = containing_word.chars().rev().collect::<String>();
3505 if util::word_consists_of_emojis(containing_word.as_str()) {
3506 chars.reverse();
3507 return Some(chars.iter().collect());
3508 }
3509 }
3510
3511 if char.is_whitespace() || !char.is_ascii() {
3512 return None;
3513 }
3514 if char == ':' {
3515 found_colon = true;
3516 } else {
3517 chars.push(char);
3518 }
3519 }
3520 // Found a possible emoji shortcode at the beginning of the buffer
3521 chars.reverse();
3522 Some(chars.iter().collect())
3523 }
3524
3525 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3526 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3527 self.transact(window, cx, |this, window, cx| {
3528 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3529 let selections = this.selections.all::<usize>(cx);
3530 let multi_buffer = this.buffer.read(cx);
3531 let buffer = multi_buffer.snapshot(cx);
3532 selections
3533 .iter()
3534 .map(|selection| {
3535 let start_point = selection.start.to_point(&buffer);
3536 let mut indent =
3537 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3538 indent.len = cmp::min(indent.len, start_point.column);
3539 let start = selection.start;
3540 let end = selection.end;
3541 let selection_is_empty = start == end;
3542 let language_scope = buffer.language_scope_at(start);
3543 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3544 &language_scope
3545 {
3546 let insert_extra_newline =
3547 insert_extra_newline_brackets(&buffer, start..end, language)
3548 || insert_extra_newline_tree_sitter(&buffer, start..end);
3549
3550 // Comment extension on newline is allowed only for cursor selections
3551 let comment_delimiter = maybe!({
3552 if !selection_is_empty {
3553 return None;
3554 }
3555
3556 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3557 return None;
3558 }
3559
3560 let delimiters = language.line_comment_prefixes();
3561 let max_len_of_delimiter =
3562 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3563 let (snapshot, range) =
3564 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3565
3566 let mut index_of_first_non_whitespace = 0;
3567 let comment_candidate = snapshot
3568 .chars_for_range(range)
3569 .skip_while(|c| {
3570 let should_skip = c.is_whitespace();
3571 if should_skip {
3572 index_of_first_non_whitespace += 1;
3573 }
3574 should_skip
3575 })
3576 .take(max_len_of_delimiter)
3577 .collect::<String>();
3578 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3579 comment_candidate.starts_with(comment_prefix.as_ref())
3580 })?;
3581 let cursor_is_placed_after_comment_marker =
3582 index_of_first_non_whitespace + comment_prefix.len()
3583 <= start_point.column as usize;
3584 if cursor_is_placed_after_comment_marker {
3585 Some(comment_prefix.clone())
3586 } else {
3587 None
3588 }
3589 });
3590 (comment_delimiter, insert_extra_newline)
3591 } else {
3592 (None, false)
3593 };
3594
3595 let capacity_for_delimiter = comment_delimiter
3596 .as_deref()
3597 .map(str::len)
3598 .unwrap_or_default();
3599 let mut new_text =
3600 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3601 new_text.push('\n');
3602 new_text.extend(indent.chars());
3603 if let Some(delimiter) = &comment_delimiter {
3604 new_text.push_str(delimiter);
3605 }
3606 if insert_extra_newline {
3607 new_text = new_text.repeat(2);
3608 }
3609
3610 let anchor = buffer.anchor_after(end);
3611 let new_selection = selection.map(|_| anchor);
3612 (
3613 (start..end, new_text),
3614 (insert_extra_newline, new_selection),
3615 )
3616 })
3617 .unzip()
3618 };
3619
3620 this.edit_with_autoindent(edits, cx);
3621 let buffer = this.buffer.read(cx).snapshot(cx);
3622 let new_selections = selection_fixup_info
3623 .into_iter()
3624 .map(|(extra_newline_inserted, new_selection)| {
3625 let mut cursor = new_selection.end.to_point(&buffer);
3626 if extra_newline_inserted {
3627 cursor.row -= 1;
3628 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3629 }
3630 new_selection.map(|_| cursor)
3631 })
3632 .collect();
3633
3634 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3635 s.select(new_selections)
3636 });
3637 this.refresh_inline_completion(true, false, window, cx);
3638 });
3639 }
3640
3641 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3642 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3643
3644 let buffer = self.buffer.read(cx);
3645 let snapshot = buffer.snapshot(cx);
3646
3647 let mut edits = Vec::new();
3648 let mut rows = Vec::new();
3649
3650 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3651 let cursor = selection.head();
3652 let row = cursor.row;
3653
3654 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3655
3656 let newline = "\n".to_string();
3657 edits.push((start_of_line..start_of_line, newline));
3658
3659 rows.push(row + rows_inserted as u32);
3660 }
3661
3662 self.transact(window, cx, |editor, window, cx| {
3663 editor.edit(edits, cx);
3664
3665 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3666 let mut index = 0;
3667 s.move_cursors_with(|map, _, _| {
3668 let row = rows[index];
3669 index += 1;
3670
3671 let point = Point::new(row, 0);
3672 let boundary = map.next_line_boundary(point).1;
3673 let clipped = map.clip_point(boundary, Bias::Left);
3674
3675 (clipped, SelectionGoal::None)
3676 });
3677 });
3678
3679 let mut indent_edits = Vec::new();
3680 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3681 for row in rows {
3682 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3683 for (row, indent) in indents {
3684 if indent.len == 0 {
3685 continue;
3686 }
3687
3688 let text = match indent.kind {
3689 IndentKind::Space => " ".repeat(indent.len as usize),
3690 IndentKind::Tab => "\t".repeat(indent.len as usize),
3691 };
3692 let point = Point::new(row.0, 0);
3693 indent_edits.push((point..point, text));
3694 }
3695 }
3696 editor.edit(indent_edits, cx);
3697 });
3698 }
3699
3700 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3701 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3702
3703 let buffer = self.buffer.read(cx);
3704 let snapshot = buffer.snapshot(cx);
3705
3706 let mut edits = Vec::new();
3707 let mut rows = Vec::new();
3708 let mut rows_inserted = 0;
3709
3710 for selection in self.selections.all_adjusted(cx) {
3711 let cursor = selection.head();
3712 let row = cursor.row;
3713
3714 let point = Point::new(row + 1, 0);
3715 let start_of_line = snapshot.clip_point(point, Bias::Left);
3716
3717 let newline = "\n".to_string();
3718 edits.push((start_of_line..start_of_line, newline));
3719
3720 rows_inserted += 1;
3721 rows.push(row + rows_inserted);
3722 }
3723
3724 self.transact(window, cx, |editor, window, cx| {
3725 editor.edit(edits, cx);
3726
3727 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3728 let mut index = 0;
3729 s.move_cursors_with(|map, _, _| {
3730 let row = rows[index];
3731 index += 1;
3732
3733 let point = Point::new(row, 0);
3734 let boundary = map.next_line_boundary(point).1;
3735 let clipped = map.clip_point(boundary, Bias::Left);
3736
3737 (clipped, SelectionGoal::None)
3738 });
3739 });
3740
3741 let mut indent_edits = Vec::new();
3742 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3743 for row in rows {
3744 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3745 for (row, indent) in indents {
3746 if indent.len == 0 {
3747 continue;
3748 }
3749
3750 let text = match indent.kind {
3751 IndentKind::Space => " ".repeat(indent.len as usize),
3752 IndentKind::Tab => "\t".repeat(indent.len as usize),
3753 };
3754 let point = Point::new(row.0, 0);
3755 indent_edits.push((point..point, text));
3756 }
3757 }
3758 editor.edit(indent_edits, cx);
3759 });
3760 }
3761
3762 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3763 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3764 original_indent_columns: Vec::new(),
3765 });
3766 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3767 }
3768
3769 fn insert_with_autoindent_mode(
3770 &mut self,
3771 text: &str,
3772 autoindent_mode: Option<AutoindentMode>,
3773 window: &mut Window,
3774 cx: &mut Context<Self>,
3775 ) {
3776 if self.read_only(cx) {
3777 return;
3778 }
3779
3780 let text: Arc<str> = text.into();
3781 self.transact(window, cx, |this, window, cx| {
3782 let old_selections = this.selections.all_adjusted(cx);
3783 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3784 let anchors = {
3785 let snapshot = buffer.read(cx);
3786 old_selections
3787 .iter()
3788 .map(|s| {
3789 let anchor = snapshot.anchor_after(s.head());
3790 s.map(|_| anchor)
3791 })
3792 .collect::<Vec<_>>()
3793 };
3794 buffer.edit(
3795 old_selections
3796 .iter()
3797 .map(|s| (s.start..s.end, text.clone())),
3798 autoindent_mode,
3799 cx,
3800 );
3801 anchors
3802 });
3803
3804 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3805 s.select_anchors(selection_anchors);
3806 });
3807
3808 cx.notify();
3809 });
3810 }
3811
3812 fn trigger_completion_on_input(
3813 &mut self,
3814 text: &str,
3815 trigger_in_words: bool,
3816 window: &mut Window,
3817 cx: &mut Context<Self>,
3818 ) {
3819 let ignore_completion_provider = self
3820 .context_menu
3821 .borrow()
3822 .as_ref()
3823 .map(|menu| match menu {
3824 CodeContextMenu::Completions(completions_menu) => {
3825 completions_menu.ignore_completion_provider
3826 }
3827 CodeContextMenu::CodeActions(_) => false,
3828 })
3829 .unwrap_or(false);
3830
3831 if ignore_completion_provider {
3832 self.show_word_completions(&ShowWordCompletions, window, cx);
3833 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3834 self.show_completions(
3835 &ShowCompletions {
3836 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3837 },
3838 window,
3839 cx,
3840 );
3841 } else {
3842 self.hide_context_menu(window, cx);
3843 }
3844 }
3845
3846 fn is_completion_trigger(
3847 &self,
3848 text: &str,
3849 trigger_in_words: bool,
3850 cx: &mut Context<Self>,
3851 ) -> bool {
3852 let position = self.selections.newest_anchor().head();
3853 let multibuffer = self.buffer.read(cx);
3854 let Some(buffer) = position
3855 .buffer_id
3856 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3857 else {
3858 return false;
3859 };
3860
3861 if let Some(completion_provider) = &self.completion_provider {
3862 completion_provider.is_completion_trigger(
3863 &buffer,
3864 position.text_anchor,
3865 text,
3866 trigger_in_words,
3867 cx,
3868 )
3869 } else {
3870 false
3871 }
3872 }
3873
3874 /// If any empty selections is touching the start of its innermost containing autoclose
3875 /// region, expand it to select the brackets.
3876 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3877 let selections = self.selections.all::<usize>(cx);
3878 let buffer = self.buffer.read(cx).read(cx);
3879 let new_selections = self
3880 .selections_with_autoclose_regions(selections, &buffer)
3881 .map(|(mut selection, region)| {
3882 if !selection.is_empty() {
3883 return selection;
3884 }
3885
3886 if let Some(region) = region {
3887 let mut range = region.range.to_offset(&buffer);
3888 if selection.start == range.start && range.start >= region.pair.start.len() {
3889 range.start -= region.pair.start.len();
3890 if buffer.contains_str_at(range.start, ®ion.pair.start)
3891 && buffer.contains_str_at(range.end, ®ion.pair.end)
3892 {
3893 range.end += region.pair.end.len();
3894 selection.start = range.start;
3895 selection.end = range.end;
3896
3897 return selection;
3898 }
3899 }
3900 }
3901
3902 let always_treat_brackets_as_autoclosed = buffer
3903 .language_settings_at(selection.start, cx)
3904 .always_treat_brackets_as_autoclosed;
3905
3906 if !always_treat_brackets_as_autoclosed {
3907 return selection;
3908 }
3909
3910 if let Some(scope) = buffer.language_scope_at(selection.start) {
3911 for (pair, enabled) in scope.brackets() {
3912 if !enabled || !pair.close {
3913 continue;
3914 }
3915
3916 if buffer.contains_str_at(selection.start, &pair.end) {
3917 let pair_start_len = pair.start.len();
3918 if buffer.contains_str_at(
3919 selection.start.saturating_sub(pair_start_len),
3920 &pair.start,
3921 ) {
3922 selection.start -= pair_start_len;
3923 selection.end += pair.end.len();
3924
3925 return selection;
3926 }
3927 }
3928 }
3929 }
3930
3931 selection
3932 })
3933 .collect();
3934
3935 drop(buffer);
3936 self.change_selections(None, window, cx, |selections| {
3937 selections.select(new_selections)
3938 });
3939 }
3940
3941 /// Iterate the given selections, and for each one, find the smallest surrounding
3942 /// autoclose region. This uses the ordering of the selections and the autoclose
3943 /// regions to avoid repeated comparisons.
3944 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3945 &'a self,
3946 selections: impl IntoIterator<Item = Selection<D>>,
3947 buffer: &'a MultiBufferSnapshot,
3948 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3949 let mut i = 0;
3950 let mut regions = self.autoclose_regions.as_slice();
3951 selections.into_iter().map(move |selection| {
3952 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3953
3954 let mut enclosing = None;
3955 while let Some(pair_state) = regions.get(i) {
3956 if pair_state.range.end.to_offset(buffer) < range.start {
3957 regions = ®ions[i + 1..];
3958 i = 0;
3959 } else if pair_state.range.start.to_offset(buffer) > range.end {
3960 break;
3961 } else {
3962 if pair_state.selection_id == selection.id {
3963 enclosing = Some(pair_state);
3964 }
3965 i += 1;
3966 }
3967 }
3968
3969 (selection, enclosing)
3970 })
3971 }
3972
3973 /// Remove any autoclose regions that no longer contain their selection.
3974 fn invalidate_autoclose_regions(
3975 &mut self,
3976 mut selections: &[Selection<Anchor>],
3977 buffer: &MultiBufferSnapshot,
3978 ) {
3979 self.autoclose_regions.retain(|state| {
3980 let mut i = 0;
3981 while let Some(selection) = selections.get(i) {
3982 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3983 selections = &selections[1..];
3984 continue;
3985 }
3986 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3987 break;
3988 }
3989 if selection.id == state.selection_id {
3990 return true;
3991 } else {
3992 i += 1;
3993 }
3994 }
3995 false
3996 });
3997 }
3998
3999 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4000 let offset = position.to_offset(buffer);
4001 let (word_range, kind) = buffer.surrounding_word(offset, true);
4002 if offset > word_range.start && kind == Some(CharKind::Word) {
4003 Some(
4004 buffer
4005 .text_for_range(word_range.start..offset)
4006 .collect::<String>(),
4007 )
4008 } else {
4009 None
4010 }
4011 }
4012
4013 pub fn toggle_inlay_hints(
4014 &mut self,
4015 _: &ToggleInlayHints,
4016 _: &mut Window,
4017 cx: &mut Context<Self>,
4018 ) {
4019 self.refresh_inlay_hints(
4020 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4021 cx,
4022 );
4023 }
4024
4025 pub fn inlay_hints_enabled(&self) -> bool {
4026 self.inlay_hint_cache.enabled
4027 }
4028
4029 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4030 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4031 return;
4032 }
4033
4034 let reason_description = reason.description();
4035 let ignore_debounce = matches!(
4036 reason,
4037 InlayHintRefreshReason::SettingsChange(_)
4038 | InlayHintRefreshReason::Toggle(_)
4039 | InlayHintRefreshReason::ExcerptsRemoved(_)
4040 | InlayHintRefreshReason::ModifiersChanged(_)
4041 );
4042 let (invalidate_cache, required_languages) = match reason {
4043 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4044 match self.inlay_hint_cache.modifiers_override(enabled) {
4045 Some(enabled) => {
4046 if enabled {
4047 (InvalidationStrategy::RefreshRequested, None)
4048 } else {
4049 self.splice_inlays(
4050 &self
4051 .visible_inlay_hints(cx)
4052 .iter()
4053 .map(|inlay| inlay.id)
4054 .collect::<Vec<InlayId>>(),
4055 Vec::new(),
4056 cx,
4057 );
4058 return;
4059 }
4060 }
4061 None => return,
4062 }
4063 }
4064 InlayHintRefreshReason::Toggle(enabled) => {
4065 if self.inlay_hint_cache.toggle(enabled) {
4066 if enabled {
4067 (InvalidationStrategy::RefreshRequested, None)
4068 } else {
4069 self.splice_inlays(
4070 &self
4071 .visible_inlay_hints(cx)
4072 .iter()
4073 .map(|inlay| inlay.id)
4074 .collect::<Vec<InlayId>>(),
4075 Vec::new(),
4076 cx,
4077 );
4078 return;
4079 }
4080 } else {
4081 return;
4082 }
4083 }
4084 InlayHintRefreshReason::SettingsChange(new_settings) => {
4085 match self.inlay_hint_cache.update_settings(
4086 &self.buffer,
4087 new_settings,
4088 self.visible_inlay_hints(cx),
4089 cx,
4090 ) {
4091 ControlFlow::Break(Some(InlaySplice {
4092 to_remove,
4093 to_insert,
4094 })) => {
4095 self.splice_inlays(&to_remove, to_insert, cx);
4096 return;
4097 }
4098 ControlFlow::Break(None) => return,
4099 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4100 }
4101 }
4102 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4103 if let Some(InlaySplice {
4104 to_remove,
4105 to_insert,
4106 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4107 {
4108 self.splice_inlays(&to_remove, to_insert, cx);
4109 }
4110 return;
4111 }
4112 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4113 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4114 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4115 }
4116 InlayHintRefreshReason::RefreshRequested => {
4117 (InvalidationStrategy::RefreshRequested, None)
4118 }
4119 };
4120
4121 if let Some(InlaySplice {
4122 to_remove,
4123 to_insert,
4124 }) = self.inlay_hint_cache.spawn_hint_refresh(
4125 reason_description,
4126 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4127 invalidate_cache,
4128 ignore_debounce,
4129 cx,
4130 ) {
4131 self.splice_inlays(&to_remove, to_insert, cx);
4132 }
4133 }
4134
4135 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4136 self.display_map
4137 .read(cx)
4138 .current_inlays()
4139 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4140 .cloned()
4141 .collect()
4142 }
4143
4144 pub fn excerpts_for_inlay_hints_query(
4145 &self,
4146 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4147 cx: &mut Context<Editor>,
4148 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4149 let Some(project) = self.project.as_ref() else {
4150 return HashMap::default();
4151 };
4152 let project = project.read(cx);
4153 let multi_buffer = self.buffer().read(cx);
4154 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4155 let multi_buffer_visible_start = self
4156 .scroll_manager
4157 .anchor()
4158 .anchor
4159 .to_point(&multi_buffer_snapshot);
4160 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4161 multi_buffer_visible_start
4162 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4163 Bias::Left,
4164 );
4165 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4166 multi_buffer_snapshot
4167 .range_to_buffer_ranges(multi_buffer_visible_range)
4168 .into_iter()
4169 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4170 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4171 let buffer_file = project::File::from_dyn(buffer.file())?;
4172 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4173 let worktree_entry = buffer_worktree
4174 .read(cx)
4175 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4176 if worktree_entry.is_ignored {
4177 return None;
4178 }
4179
4180 let language = buffer.language()?;
4181 if let Some(restrict_to_languages) = restrict_to_languages {
4182 if !restrict_to_languages.contains(language) {
4183 return None;
4184 }
4185 }
4186 Some((
4187 excerpt_id,
4188 (
4189 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4190 buffer.version().clone(),
4191 excerpt_visible_range,
4192 ),
4193 ))
4194 })
4195 .collect()
4196 }
4197
4198 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4199 TextLayoutDetails {
4200 text_system: window.text_system().clone(),
4201 editor_style: self.style.clone().unwrap(),
4202 rem_size: window.rem_size(),
4203 scroll_anchor: self.scroll_manager.anchor(),
4204 visible_rows: self.visible_line_count(),
4205 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4206 }
4207 }
4208
4209 pub fn splice_inlays(
4210 &self,
4211 to_remove: &[InlayId],
4212 to_insert: Vec<Inlay>,
4213 cx: &mut Context<Self>,
4214 ) {
4215 self.display_map.update(cx, |display_map, cx| {
4216 display_map.splice_inlays(to_remove, to_insert, cx)
4217 });
4218 cx.notify();
4219 }
4220
4221 fn trigger_on_type_formatting(
4222 &self,
4223 input: String,
4224 window: &mut Window,
4225 cx: &mut Context<Self>,
4226 ) -> Option<Task<Result<()>>> {
4227 if input.len() != 1 {
4228 return None;
4229 }
4230
4231 let project = self.project.as_ref()?;
4232 let position = self.selections.newest_anchor().head();
4233 let (buffer, buffer_position) = self
4234 .buffer
4235 .read(cx)
4236 .text_anchor_for_position(position, cx)?;
4237
4238 let settings = language_settings::language_settings(
4239 buffer
4240 .read(cx)
4241 .language_at(buffer_position)
4242 .map(|l| l.name()),
4243 buffer.read(cx).file(),
4244 cx,
4245 );
4246 if !settings.use_on_type_format {
4247 return None;
4248 }
4249
4250 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4251 // hence we do LSP request & edit on host side only — add formats to host's history.
4252 let push_to_lsp_host_history = true;
4253 // If this is not the host, append its history with new edits.
4254 let push_to_client_history = project.read(cx).is_via_collab();
4255
4256 let on_type_formatting = project.update(cx, |project, cx| {
4257 project.on_type_format(
4258 buffer.clone(),
4259 buffer_position,
4260 input,
4261 push_to_lsp_host_history,
4262 cx,
4263 )
4264 });
4265 Some(cx.spawn_in(window, async move |editor, cx| {
4266 if let Some(transaction) = on_type_formatting.await? {
4267 if push_to_client_history {
4268 buffer
4269 .update(cx, |buffer, _| {
4270 buffer.push_transaction(transaction, Instant::now());
4271 })
4272 .ok();
4273 }
4274 editor.update(cx, |editor, cx| {
4275 editor.refresh_document_highlights(cx);
4276 })?;
4277 }
4278 Ok(())
4279 }))
4280 }
4281
4282 pub fn show_word_completions(
4283 &mut self,
4284 _: &ShowWordCompletions,
4285 window: &mut Window,
4286 cx: &mut Context<Self>,
4287 ) {
4288 self.open_completions_menu(true, None, window, cx);
4289 }
4290
4291 pub fn show_completions(
4292 &mut self,
4293 options: &ShowCompletions,
4294 window: &mut Window,
4295 cx: &mut Context<Self>,
4296 ) {
4297 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4298 }
4299
4300 fn open_completions_menu(
4301 &mut self,
4302 ignore_completion_provider: bool,
4303 trigger: Option<&str>,
4304 window: &mut Window,
4305 cx: &mut Context<Self>,
4306 ) {
4307 if self.pending_rename.is_some() {
4308 return;
4309 }
4310 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4311 return;
4312 }
4313
4314 let position = self.selections.newest_anchor().head();
4315 if position.diff_base_anchor.is_some() {
4316 return;
4317 }
4318 let (buffer, buffer_position) =
4319 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4320 output
4321 } else {
4322 return;
4323 };
4324 let buffer_snapshot = buffer.read(cx).snapshot();
4325 let show_completion_documentation = buffer_snapshot
4326 .settings_at(buffer_position, cx)
4327 .show_completion_documentation;
4328
4329 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4330
4331 let trigger_kind = match trigger {
4332 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4333 CompletionTriggerKind::TRIGGER_CHARACTER
4334 }
4335 _ => CompletionTriggerKind::INVOKED,
4336 };
4337 let completion_context = CompletionContext {
4338 trigger_character: trigger.and_then(|trigger| {
4339 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4340 Some(String::from(trigger))
4341 } else {
4342 None
4343 }
4344 }),
4345 trigger_kind,
4346 };
4347
4348 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4349 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4350 let word_to_exclude = buffer_snapshot
4351 .text_for_range(old_range.clone())
4352 .collect::<String>();
4353 (
4354 buffer_snapshot.anchor_before(old_range.start)
4355 ..buffer_snapshot.anchor_after(old_range.end),
4356 Some(word_to_exclude),
4357 )
4358 } else {
4359 (buffer_position..buffer_position, None)
4360 };
4361
4362 let completion_settings = language_settings(
4363 buffer_snapshot
4364 .language_at(buffer_position)
4365 .map(|language| language.name()),
4366 buffer_snapshot.file(),
4367 cx,
4368 )
4369 .completions;
4370
4371 // The document can be large, so stay in reasonable bounds when searching for words,
4372 // otherwise completion pop-up might be slow to appear.
4373 const WORD_LOOKUP_ROWS: u32 = 5_000;
4374 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4375 let min_word_search = buffer_snapshot.clip_point(
4376 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4377 Bias::Left,
4378 );
4379 let max_word_search = buffer_snapshot.clip_point(
4380 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4381 Bias::Right,
4382 );
4383 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4384 ..buffer_snapshot.point_to_offset(max_word_search);
4385
4386 let provider = self
4387 .completion_provider
4388 .as_ref()
4389 .filter(|_| !ignore_completion_provider);
4390 let skip_digits = query
4391 .as_ref()
4392 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4393
4394 let (mut words, provided_completions) = match provider {
4395 Some(provider) => {
4396 let completions = provider.completions(
4397 position.excerpt_id,
4398 &buffer,
4399 buffer_position,
4400 completion_context,
4401 window,
4402 cx,
4403 );
4404
4405 let words = match completion_settings.words {
4406 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4407 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4408 .background_spawn(async move {
4409 buffer_snapshot.words_in_range(WordsQuery {
4410 fuzzy_contents: None,
4411 range: word_search_range,
4412 skip_digits,
4413 })
4414 }),
4415 };
4416
4417 (words, completions)
4418 }
4419 None => (
4420 cx.background_spawn(async move {
4421 buffer_snapshot.words_in_range(WordsQuery {
4422 fuzzy_contents: None,
4423 range: word_search_range,
4424 skip_digits,
4425 })
4426 }),
4427 Task::ready(Ok(None)),
4428 ),
4429 };
4430
4431 let sort_completions = provider
4432 .as_ref()
4433 .map_or(true, |provider| provider.sort_completions());
4434
4435 let filter_completions = provider
4436 .as_ref()
4437 .map_or(true, |provider| provider.filter_completions());
4438
4439 let id = post_inc(&mut self.next_completion_id);
4440 let task = cx.spawn_in(window, async move |editor, cx| {
4441 async move {
4442 editor.update(cx, |this, _| {
4443 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4444 })?;
4445
4446 let mut completions = Vec::new();
4447 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4448 completions.extend(provided_completions);
4449 if completion_settings.words == WordsCompletionMode::Fallback {
4450 words = Task::ready(HashMap::default());
4451 }
4452 }
4453
4454 let mut words = words.await;
4455 if let Some(word_to_exclude) = &word_to_exclude {
4456 words.remove(word_to_exclude);
4457 }
4458 for lsp_completion in &completions {
4459 words.remove(&lsp_completion.new_text);
4460 }
4461 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4462 old_range: old_range.clone(),
4463 new_text: word.clone(),
4464 label: CodeLabel::plain(word, None),
4465 icon_path: None,
4466 documentation: None,
4467 source: CompletionSource::BufferWord {
4468 word_range,
4469 resolved: false,
4470 },
4471 confirm: None,
4472 }));
4473
4474 let menu = if completions.is_empty() {
4475 None
4476 } else {
4477 let mut menu = CompletionsMenu::new(
4478 id,
4479 sort_completions,
4480 show_completion_documentation,
4481 ignore_completion_provider,
4482 position,
4483 buffer.clone(),
4484 completions.into(),
4485 );
4486
4487 menu.filter(
4488 if filter_completions {
4489 query.as_deref()
4490 } else {
4491 None
4492 },
4493 cx.background_executor().clone(),
4494 )
4495 .await;
4496
4497 menu.visible().then_some(menu)
4498 };
4499
4500 editor.update_in(cx, |editor, window, cx| {
4501 match editor.context_menu.borrow().as_ref() {
4502 None => {}
4503 Some(CodeContextMenu::Completions(prev_menu)) => {
4504 if prev_menu.id > id {
4505 return;
4506 }
4507 }
4508 _ => return,
4509 }
4510
4511 if editor.focus_handle.is_focused(window) && menu.is_some() {
4512 let mut menu = menu.unwrap();
4513 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4514
4515 *editor.context_menu.borrow_mut() =
4516 Some(CodeContextMenu::Completions(menu));
4517
4518 if editor.show_edit_predictions_in_menu() {
4519 editor.update_visible_inline_completion(window, cx);
4520 } else {
4521 editor.discard_inline_completion(false, cx);
4522 }
4523
4524 cx.notify();
4525 } else if editor.completion_tasks.len() <= 1 {
4526 // If there are no more completion tasks and the last menu was
4527 // empty, we should hide it.
4528 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4529 // If it was already hidden and we don't show inline
4530 // completions in the menu, we should also show the
4531 // inline-completion when available.
4532 if was_hidden && editor.show_edit_predictions_in_menu() {
4533 editor.update_visible_inline_completion(window, cx);
4534 }
4535 }
4536 })?;
4537
4538 anyhow::Ok(())
4539 }
4540 .log_err()
4541 .await
4542 });
4543
4544 self.completion_tasks.push((id, task));
4545 }
4546
4547 #[cfg(feature = "test-support")]
4548 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4549 let menu = self.context_menu.borrow();
4550 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4551 let completions = menu.completions.borrow();
4552 Some(completions.to_vec())
4553 } else {
4554 None
4555 }
4556 }
4557
4558 pub fn confirm_completion(
4559 &mut self,
4560 action: &ConfirmCompletion,
4561 window: &mut Window,
4562 cx: &mut Context<Self>,
4563 ) -> Option<Task<Result<()>>> {
4564 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4565 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4566 }
4567
4568 pub fn compose_completion(
4569 &mut self,
4570 action: &ComposeCompletion,
4571 window: &mut Window,
4572 cx: &mut Context<Self>,
4573 ) -> Option<Task<Result<()>>> {
4574 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4575 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4576 }
4577
4578 fn do_completion(
4579 &mut self,
4580 item_ix: Option<usize>,
4581 intent: CompletionIntent,
4582 window: &mut Window,
4583 cx: &mut Context<Editor>,
4584 ) -> Option<Task<Result<()>>> {
4585 use language::ToOffset as _;
4586
4587 let completions_menu =
4588 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4589 menu
4590 } else {
4591 return None;
4592 };
4593
4594 let candidate_id = {
4595 let entries = completions_menu.entries.borrow();
4596 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4597 if self.show_edit_predictions_in_menu() {
4598 self.discard_inline_completion(true, cx);
4599 }
4600 mat.candidate_id
4601 };
4602
4603 let buffer_handle = completions_menu.buffer;
4604 let completion = completions_menu
4605 .completions
4606 .borrow()
4607 .get(candidate_id)?
4608 .clone();
4609 cx.stop_propagation();
4610
4611 let snippet;
4612 let new_text;
4613 if completion.is_snippet() {
4614 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4615 new_text = snippet.as_ref().unwrap().text.clone();
4616 } else {
4617 snippet = None;
4618 new_text = completion.new_text.clone();
4619 };
4620 let selections = self.selections.all::<usize>(cx);
4621 let buffer = buffer_handle.read(cx);
4622 let old_range = completion.old_range.to_offset(buffer);
4623 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4624
4625 let newest_selection = self.selections.newest_anchor();
4626 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4627 return None;
4628 }
4629
4630 let lookbehind = newest_selection
4631 .start
4632 .text_anchor
4633 .to_offset(buffer)
4634 .saturating_sub(old_range.start);
4635 let lookahead = old_range
4636 .end
4637 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4638 let mut common_prefix_len = 0;
4639 for (a, b) in old_text.chars().zip(new_text.chars()) {
4640 if a == b {
4641 common_prefix_len += a.len_utf8();
4642 } else {
4643 break;
4644 }
4645 }
4646
4647 let snapshot = self.buffer.read(cx).snapshot(cx);
4648 let mut range_to_replace: Option<Range<usize>> = None;
4649 let mut ranges = Vec::new();
4650 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4651 for selection in &selections {
4652 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4653 let start = selection.start.saturating_sub(lookbehind);
4654 let end = selection.end + lookahead;
4655 if selection.id == newest_selection.id {
4656 range_to_replace = Some(start + common_prefix_len..end);
4657 }
4658 ranges.push(start + common_prefix_len..end);
4659 } else {
4660 common_prefix_len = 0;
4661 ranges.clear();
4662 ranges.extend(selections.iter().map(|s| {
4663 if s.id == newest_selection.id {
4664 range_to_replace = Some(old_range.clone());
4665 old_range.clone()
4666 } else {
4667 s.start..s.end
4668 }
4669 }));
4670 break;
4671 }
4672 if !self.linked_edit_ranges.is_empty() {
4673 let start_anchor = snapshot.anchor_before(selection.head());
4674 let end_anchor = snapshot.anchor_after(selection.tail());
4675 if let Some(ranges) = self
4676 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4677 {
4678 for (buffer, edits) in ranges {
4679 linked_edits.entry(buffer.clone()).or_default().extend(
4680 edits
4681 .into_iter()
4682 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4683 );
4684 }
4685 }
4686 }
4687 }
4688 let text = &new_text[common_prefix_len..];
4689
4690 let utf16_range_to_replace = range_to_replace.map(|range| {
4691 let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
4692 let selection_start_utf16 = newest_selection.start.0 as isize;
4693
4694 range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4695 ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4696 });
4697 cx.emit(EditorEvent::InputHandled {
4698 utf16_range_to_replace,
4699 text: text.into(),
4700 });
4701
4702 self.transact(window, cx, |this, window, cx| {
4703 if let Some(mut snippet) = snippet {
4704 snippet.text = text.to_string();
4705 for tabstop in snippet
4706 .tabstops
4707 .iter_mut()
4708 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4709 {
4710 tabstop.start -= common_prefix_len as isize;
4711 tabstop.end -= common_prefix_len as isize;
4712 }
4713
4714 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4715 } else {
4716 this.buffer.update(cx, |buffer, cx| {
4717 let edits = ranges.iter().map(|range| (range.clone(), text));
4718 buffer.edit(edits, this.autoindent_mode.clone(), cx);
4719 });
4720 }
4721 for (buffer, edits) in linked_edits {
4722 buffer.update(cx, |buffer, cx| {
4723 let snapshot = buffer.snapshot();
4724 let edits = edits
4725 .into_iter()
4726 .map(|(range, text)| {
4727 use text::ToPoint as TP;
4728 let end_point = TP::to_point(&range.end, &snapshot);
4729 let start_point = TP::to_point(&range.start, &snapshot);
4730 (start_point..end_point, text)
4731 })
4732 .sorted_by_key(|(range, _)| range.start);
4733 buffer.edit(edits, None, cx);
4734 })
4735 }
4736
4737 this.refresh_inline_completion(true, false, window, cx);
4738 });
4739
4740 let show_new_completions_on_confirm = completion
4741 .confirm
4742 .as_ref()
4743 .map_or(false, |confirm| confirm(intent, window, cx));
4744 if show_new_completions_on_confirm {
4745 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4746 }
4747
4748 let provider = self.completion_provider.as_ref()?;
4749 drop(completion);
4750 let apply_edits = provider.apply_additional_edits_for_completion(
4751 buffer_handle,
4752 completions_menu.completions.clone(),
4753 candidate_id,
4754 true,
4755 cx,
4756 );
4757
4758 let editor_settings = EditorSettings::get_global(cx);
4759 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4760 // After the code completion is finished, users often want to know what signatures are needed.
4761 // so we should automatically call signature_help
4762 self.show_signature_help(&ShowSignatureHelp, window, cx);
4763 }
4764
4765 Some(cx.foreground_executor().spawn(async move {
4766 apply_edits.await?;
4767 Ok(())
4768 }))
4769 }
4770
4771 pub fn toggle_code_actions(
4772 &mut self,
4773 action: &ToggleCodeActions,
4774 window: &mut Window,
4775 cx: &mut Context<Self>,
4776 ) {
4777 let mut context_menu = self.context_menu.borrow_mut();
4778 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4779 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4780 // Toggle if we're selecting the same one
4781 *context_menu = None;
4782 cx.notify();
4783 return;
4784 } else {
4785 // Otherwise, clear it and start a new one
4786 *context_menu = None;
4787 cx.notify();
4788 }
4789 }
4790 drop(context_menu);
4791 let snapshot = self.snapshot(window, cx);
4792 let deployed_from_indicator = action.deployed_from_indicator;
4793 let mut task = self.code_actions_task.take();
4794 let action = action.clone();
4795 cx.spawn_in(window, async move |editor, cx| {
4796 while let Some(prev_task) = task {
4797 prev_task.await.log_err();
4798 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4799 }
4800
4801 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4802 if editor.focus_handle.is_focused(window) {
4803 let multibuffer_point = action
4804 .deployed_from_indicator
4805 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4806 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4807 let (buffer, buffer_row) = snapshot
4808 .buffer_snapshot
4809 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4810 .and_then(|(buffer_snapshot, range)| {
4811 editor
4812 .buffer
4813 .read(cx)
4814 .buffer(buffer_snapshot.remote_id())
4815 .map(|buffer| (buffer, range.start.row))
4816 })?;
4817 let (_, code_actions) = editor
4818 .available_code_actions
4819 .clone()
4820 .and_then(|(location, code_actions)| {
4821 let snapshot = location.buffer.read(cx).snapshot();
4822 let point_range = location.range.to_point(&snapshot);
4823 let point_range = point_range.start.row..=point_range.end.row;
4824 if point_range.contains(&buffer_row) {
4825 Some((location, code_actions))
4826 } else {
4827 None
4828 }
4829 })
4830 .unzip();
4831 let buffer_id = buffer.read(cx).remote_id();
4832 let tasks = editor
4833 .tasks
4834 .get(&(buffer_id, buffer_row))
4835 .map(|t| Arc::new(t.to_owned()));
4836 if tasks.is_none() && code_actions.is_none() {
4837 return None;
4838 }
4839
4840 editor.completion_tasks.clear();
4841 editor.discard_inline_completion(false, cx);
4842 let task_context =
4843 tasks
4844 .as_ref()
4845 .zip(editor.project.clone())
4846 .map(|(tasks, project)| {
4847 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4848 });
4849
4850 let debugger_flag = cx.has_flag::<Debugger>();
4851
4852 Some(cx.spawn_in(window, async move |editor, cx| {
4853 let task_context = match task_context {
4854 Some(task_context) => task_context.await,
4855 None => None,
4856 };
4857 let resolved_tasks =
4858 tasks.zip(task_context).map(|(tasks, task_context)| {
4859 Rc::new(ResolvedTasks {
4860 templates: tasks.resolve(&task_context).collect(),
4861 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4862 multibuffer_point.row,
4863 tasks.column,
4864 )),
4865 })
4866 });
4867 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
4868 tasks
4869 .templates
4870 .iter()
4871 .filter(|task| {
4872 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4873 debugger_flag
4874 } else {
4875 true
4876 }
4877 })
4878 .count()
4879 == 1
4880 }) && code_actions
4881 .as_ref()
4882 .map_or(true, |actions| actions.is_empty());
4883 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4884 *editor.context_menu.borrow_mut() =
4885 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4886 buffer,
4887 actions: CodeActionContents {
4888 tasks: resolved_tasks,
4889 actions: code_actions,
4890 },
4891 selected_item: Default::default(),
4892 scroll_handle: UniformListScrollHandle::default(),
4893 deployed_from_indicator,
4894 }));
4895 if spawn_straight_away {
4896 if let Some(task) = editor.confirm_code_action(
4897 &ConfirmCodeAction { item_ix: Some(0) },
4898 window,
4899 cx,
4900 ) {
4901 cx.notify();
4902 return task;
4903 }
4904 }
4905 cx.notify();
4906 Task::ready(Ok(()))
4907 }) {
4908 task.await
4909 } else {
4910 Ok(())
4911 }
4912 }))
4913 } else {
4914 Some(Task::ready(Ok(())))
4915 }
4916 })?;
4917 if let Some(task) = spawned_test_task {
4918 task.await?;
4919 }
4920
4921 Ok::<_, anyhow::Error>(())
4922 })
4923 .detach_and_log_err(cx);
4924 }
4925
4926 pub fn confirm_code_action(
4927 &mut self,
4928 action: &ConfirmCodeAction,
4929 window: &mut Window,
4930 cx: &mut Context<Self>,
4931 ) -> Option<Task<Result<()>>> {
4932 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4933
4934 let actions_menu =
4935 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4936 menu
4937 } else {
4938 return None;
4939 };
4940
4941 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4942 let action = actions_menu.actions.get(action_ix)?;
4943 let title = action.label();
4944 let buffer = actions_menu.buffer;
4945 let workspace = self.workspace()?;
4946
4947 match action {
4948 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4949 match resolved_task.task_type() {
4950 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
4951 workspace::tasks::schedule_resolved_task(
4952 workspace,
4953 task_source_kind,
4954 resolved_task,
4955 false,
4956 cx,
4957 );
4958
4959 Some(Task::ready(Ok(())))
4960 }),
4961 task::TaskType::Debug(debug_args) => {
4962 if debug_args.locator.is_some() {
4963 workspace.update(cx, |workspace, cx| {
4964 workspace::tasks::schedule_resolved_task(
4965 workspace,
4966 task_source_kind,
4967 resolved_task,
4968 false,
4969 cx,
4970 );
4971 });
4972
4973 return Some(Task::ready(Ok(())));
4974 }
4975
4976 if let Some(project) = self.project.as_ref() {
4977 project
4978 .update(cx, |project, cx| {
4979 project.start_debug_session(
4980 resolved_task.resolved_debug_adapter_config().unwrap(),
4981 cx,
4982 )
4983 })
4984 .detach_and_log_err(cx);
4985 Some(Task::ready(Ok(())))
4986 } else {
4987 Some(Task::ready(Ok(())))
4988 }
4989 }
4990 }
4991 }
4992 CodeActionsItem::CodeAction {
4993 excerpt_id,
4994 action,
4995 provider,
4996 } => {
4997 let apply_code_action =
4998 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4999 let workspace = workspace.downgrade();
5000 Some(cx.spawn_in(window, async move |editor, cx| {
5001 let project_transaction = apply_code_action.await?;
5002 Self::open_project_transaction(
5003 &editor,
5004 workspace,
5005 project_transaction,
5006 title,
5007 cx,
5008 )
5009 .await
5010 }))
5011 }
5012 }
5013 }
5014
5015 pub async fn open_project_transaction(
5016 this: &WeakEntity<Editor>,
5017 workspace: WeakEntity<Workspace>,
5018 transaction: ProjectTransaction,
5019 title: String,
5020 cx: &mut AsyncWindowContext,
5021 ) -> Result<()> {
5022 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5023 cx.update(|_, cx| {
5024 entries.sort_unstable_by_key(|(buffer, _)| {
5025 buffer.read(cx).file().map(|f| f.path().clone())
5026 });
5027 })?;
5028
5029 // If the project transaction's edits are all contained within this editor, then
5030 // avoid opening a new editor to display them.
5031
5032 if let Some((buffer, transaction)) = entries.first() {
5033 if entries.len() == 1 {
5034 let excerpt = this.update(cx, |editor, cx| {
5035 editor
5036 .buffer()
5037 .read(cx)
5038 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5039 })?;
5040 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5041 if excerpted_buffer == *buffer {
5042 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5043 let excerpt_range = excerpt_range.to_offset(buffer);
5044 buffer
5045 .edited_ranges_for_transaction::<usize>(transaction)
5046 .all(|range| {
5047 excerpt_range.start <= range.start
5048 && excerpt_range.end >= range.end
5049 })
5050 })?;
5051
5052 if all_edits_within_excerpt {
5053 return Ok(());
5054 }
5055 }
5056 }
5057 }
5058 } else {
5059 return Ok(());
5060 }
5061
5062 let mut ranges_to_highlight = Vec::new();
5063 let excerpt_buffer = cx.new(|cx| {
5064 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5065 for (buffer_handle, transaction) in &entries {
5066 let edited_ranges = buffer_handle
5067 .read(cx)
5068 .edited_ranges_for_transaction::<Point>(transaction)
5069 .collect::<Vec<_>>();
5070 let (ranges, _) = multibuffer.set_excerpts_for_path(
5071 PathKey::for_buffer(buffer_handle, cx),
5072 buffer_handle.clone(),
5073 edited_ranges,
5074 DEFAULT_MULTIBUFFER_CONTEXT,
5075 cx,
5076 );
5077
5078 ranges_to_highlight.extend(ranges);
5079 }
5080 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5081 multibuffer
5082 })?;
5083
5084 workspace.update_in(cx, |workspace, window, cx| {
5085 let project = workspace.project().clone();
5086 let editor =
5087 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5088 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5089 editor.update(cx, |editor, cx| {
5090 editor.highlight_background::<Self>(
5091 &ranges_to_highlight,
5092 |theme| theme.editor_highlighted_line_background,
5093 cx,
5094 );
5095 });
5096 })?;
5097
5098 Ok(())
5099 }
5100
5101 pub fn clear_code_action_providers(&mut self) {
5102 self.code_action_providers.clear();
5103 self.available_code_actions.take();
5104 }
5105
5106 pub fn add_code_action_provider(
5107 &mut self,
5108 provider: Rc<dyn CodeActionProvider>,
5109 window: &mut Window,
5110 cx: &mut Context<Self>,
5111 ) {
5112 if self
5113 .code_action_providers
5114 .iter()
5115 .any(|existing_provider| existing_provider.id() == provider.id())
5116 {
5117 return;
5118 }
5119
5120 self.code_action_providers.push(provider);
5121 self.refresh_code_actions(window, cx);
5122 }
5123
5124 pub fn remove_code_action_provider(
5125 &mut self,
5126 id: Arc<str>,
5127 window: &mut Window,
5128 cx: &mut Context<Self>,
5129 ) {
5130 self.code_action_providers
5131 .retain(|provider| provider.id() != id);
5132 self.refresh_code_actions(window, cx);
5133 }
5134
5135 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5136 let buffer = self.buffer.read(cx);
5137 let newest_selection = self.selections.newest_anchor().clone();
5138 if newest_selection.head().diff_base_anchor.is_some() {
5139 return None;
5140 }
5141 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5142 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5143 if start_buffer != end_buffer {
5144 return None;
5145 }
5146
5147 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5148 cx.background_executor()
5149 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5150 .await;
5151
5152 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5153 let providers = this.code_action_providers.clone();
5154 let tasks = this
5155 .code_action_providers
5156 .iter()
5157 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5158 .collect::<Vec<_>>();
5159 (providers, tasks)
5160 })?;
5161
5162 let mut actions = Vec::new();
5163 for (provider, provider_actions) in
5164 providers.into_iter().zip(future::join_all(tasks).await)
5165 {
5166 if let Some(provider_actions) = provider_actions.log_err() {
5167 actions.extend(provider_actions.into_iter().map(|action| {
5168 AvailableCodeAction {
5169 excerpt_id: newest_selection.start.excerpt_id,
5170 action,
5171 provider: provider.clone(),
5172 }
5173 }));
5174 }
5175 }
5176
5177 this.update(cx, |this, cx| {
5178 this.available_code_actions = if actions.is_empty() {
5179 None
5180 } else {
5181 Some((
5182 Location {
5183 buffer: start_buffer,
5184 range: start..end,
5185 },
5186 actions.into(),
5187 ))
5188 };
5189 cx.notify();
5190 })
5191 }));
5192 None
5193 }
5194
5195 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5196 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5197 self.show_git_blame_inline = false;
5198
5199 self.show_git_blame_inline_delay_task =
5200 Some(cx.spawn_in(window, async move |this, cx| {
5201 cx.background_executor().timer(delay).await;
5202
5203 this.update(cx, |this, cx| {
5204 this.show_git_blame_inline = true;
5205 cx.notify();
5206 })
5207 .log_err();
5208 }));
5209 }
5210 }
5211
5212 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5213 if self.pending_rename.is_some() {
5214 return None;
5215 }
5216
5217 let provider = self.semantics_provider.clone()?;
5218 let buffer = self.buffer.read(cx);
5219 let newest_selection = self.selections.newest_anchor().clone();
5220 let cursor_position = newest_selection.head();
5221 let (cursor_buffer, cursor_buffer_position) =
5222 buffer.text_anchor_for_position(cursor_position, cx)?;
5223 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5224 if cursor_buffer != tail_buffer {
5225 return None;
5226 }
5227 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5228 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5229 cx.background_executor()
5230 .timer(Duration::from_millis(debounce))
5231 .await;
5232
5233 let highlights = if let Some(highlights) = cx
5234 .update(|cx| {
5235 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5236 })
5237 .ok()
5238 .flatten()
5239 {
5240 highlights.await.log_err()
5241 } else {
5242 None
5243 };
5244
5245 if let Some(highlights) = highlights {
5246 this.update(cx, |this, cx| {
5247 if this.pending_rename.is_some() {
5248 return;
5249 }
5250
5251 let buffer_id = cursor_position.buffer_id;
5252 let buffer = this.buffer.read(cx);
5253 if !buffer
5254 .text_anchor_for_position(cursor_position, cx)
5255 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5256 {
5257 return;
5258 }
5259
5260 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5261 let mut write_ranges = Vec::new();
5262 let mut read_ranges = Vec::new();
5263 for highlight in highlights {
5264 for (excerpt_id, excerpt_range) in
5265 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5266 {
5267 let start = highlight
5268 .range
5269 .start
5270 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5271 let end = highlight
5272 .range
5273 .end
5274 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5275 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5276 continue;
5277 }
5278
5279 let range = Anchor {
5280 buffer_id,
5281 excerpt_id,
5282 text_anchor: start,
5283 diff_base_anchor: None,
5284 }..Anchor {
5285 buffer_id,
5286 excerpt_id,
5287 text_anchor: end,
5288 diff_base_anchor: None,
5289 };
5290 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5291 write_ranges.push(range);
5292 } else {
5293 read_ranges.push(range);
5294 }
5295 }
5296 }
5297
5298 this.highlight_background::<DocumentHighlightRead>(
5299 &read_ranges,
5300 |theme| theme.editor_document_highlight_read_background,
5301 cx,
5302 );
5303 this.highlight_background::<DocumentHighlightWrite>(
5304 &write_ranges,
5305 |theme| theme.editor_document_highlight_write_background,
5306 cx,
5307 );
5308 cx.notify();
5309 })
5310 .log_err();
5311 }
5312 }));
5313 None
5314 }
5315
5316 pub fn refresh_selected_text_highlights(
5317 &mut self,
5318 window: &mut Window,
5319 cx: &mut Context<Editor>,
5320 ) {
5321 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5322 return;
5323 }
5324 self.selection_highlight_task.take();
5325 if !EditorSettings::get_global(cx).selection_highlight {
5326 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5327 return;
5328 }
5329 if self.selections.count() != 1 || self.selections.line_mode {
5330 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5331 return;
5332 }
5333 let selection = self.selections.newest::<Point>(cx);
5334 if selection.is_empty() || selection.start.row != selection.end.row {
5335 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5336 return;
5337 }
5338 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5339 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5340 cx.background_executor()
5341 .timer(Duration::from_millis(debounce))
5342 .await;
5343 let Some(Some(matches_task)) = editor
5344 .update_in(cx, |editor, _, cx| {
5345 if editor.selections.count() != 1 || editor.selections.line_mode {
5346 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5347 return None;
5348 }
5349 let selection = editor.selections.newest::<Point>(cx);
5350 if selection.is_empty() || selection.start.row != selection.end.row {
5351 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5352 return None;
5353 }
5354 let buffer = editor.buffer().read(cx).snapshot(cx);
5355 let query = buffer.text_for_range(selection.range()).collect::<String>();
5356 if query.trim().is_empty() {
5357 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5358 return None;
5359 }
5360 Some(cx.background_spawn(async move {
5361 let mut ranges = Vec::new();
5362 let selection_anchors = selection.range().to_anchors(&buffer);
5363 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5364 for (search_buffer, search_range, excerpt_id) in
5365 buffer.range_to_buffer_ranges(range)
5366 {
5367 ranges.extend(
5368 project::search::SearchQuery::text(
5369 query.clone(),
5370 false,
5371 false,
5372 false,
5373 Default::default(),
5374 Default::default(),
5375 None,
5376 )
5377 .unwrap()
5378 .search(search_buffer, Some(search_range.clone()))
5379 .await
5380 .into_iter()
5381 .filter_map(
5382 |match_range| {
5383 let start = search_buffer.anchor_after(
5384 search_range.start + match_range.start,
5385 );
5386 let end = search_buffer.anchor_before(
5387 search_range.start + match_range.end,
5388 );
5389 let range = Anchor::range_in_buffer(
5390 excerpt_id,
5391 search_buffer.remote_id(),
5392 start..end,
5393 );
5394 (range != selection_anchors).then_some(range)
5395 },
5396 ),
5397 );
5398 }
5399 }
5400 ranges
5401 }))
5402 })
5403 .log_err()
5404 else {
5405 return;
5406 };
5407 let matches = matches_task.await;
5408 editor
5409 .update_in(cx, |editor, _, cx| {
5410 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5411 if !matches.is_empty() {
5412 editor.highlight_background::<SelectedTextHighlight>(
5413 &matches,
5414 |theme| theme.editor_document_highlight_bracket_background,
5415 cx,
5416 )
5417 }
5418 })
5419 .log_err();
5420 }));
5421 }
5422
5423 pub fn refresh_inline_completion(
5424 &mut self,
5425 debounce: bool,
5426 user_requested: bool,
5427 window: &mut Window,
5428 cx: &mut Context<Self>,
5429 ) -> Option<()> {
5430 let provider = self.edit_prediction_provider()?;
5431 let cursor = self.selections.newest_anchor().head();
5432 let (buffer, cursor_buffer_position) =
5433 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5434
5435 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5436 self.discard_inline_completion(false, cx);
5437 return None;
5438 }
5439
5440 if !user_requested
5441 && (!self.should_show_edit_predictions()
5442 || !self.is_focused(window)
5443 || buffer.read(cx).is_empty())
5444 {
5445 self.discard_inline_completion(false, cx);
5446 return None;
5447 }
5448
5449 self.update_visible_inline_completion(window, cx);
5450 provider.refresh(
5451 self.project.clone(),
5452 buffer,
5453 cursor_buffer_position,
5454 debounce,
5455 cx,
5456 );
5457 Some(())
5458 }
5459
5460 fn show_edit_predictions_in_menu(&self) -> bool {
5461 match self.edit_prediction_settings {
5462 EditPredictionSettings::Disabled => false,
5463 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5464 }
5465 }
5466
5467 pub fn edit_predictions_enabled(&self) -> bool {
5468 match self.edit_prediction_settings {
5469 EditPredictionSettings::Disabled => false,
5470 EditPredictionSettings::Enabled { .. } => true,
5471 }
5472 }
5473
5474 fn edit_prediction_requires_modifier(&self) -> bool {
5475 match self.edit_prediction_settings {
5476 EditPredictionSettings::Disabled => false,
5477 EditPredictionSettings::Enabled {
5478 preview_requires_modifier,
5479 ..
5480 } => preview_requires_modifier,
5481 }
5482 }
5483
5484 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5485 if self.edit_prediction_provider.is_none() {
5486 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5487 } else {
5488 let selection = self.selections.newest_anchor();
5489 let cursor = selection.head();
5490
5491 if let Some((buffer, cursor_buffer_position)) =
5492 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5493 {
5494 self.edit_prediction_settings =
5495 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5496 }
5497 }
5498 }
5499
5500 fn edit_prediction_settings_at_position(
5501 &self,
5502 buffer: &Entity<Buffer>,
5503 buffer_position: language::Anchor,
5504 cx: &App,
5505 ) -> EditPredictionSettings {
5506 if self.mode != EditorMode::Full
5507 || !self.show_inline_completions_override.unwrap_or(true)
5508 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5509 {
5510 return EditPredictionSettings::Disabled;
5511 }
5512
5513 let buffer = buffer.read(cx);
5514
5515 let file = buffer.file();
5516
5517 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5518 return EditPredictionSettings::Disabled;
5519 };
5520
5521 let by_provider = matches!(
5522 self.menu_inline_completions_policy,
5523 MenuInlineCompletionsPolicy::ByProvider
5524 );
5525
5526 let show_in_menu = by_provider
5527 && self
5528 .edit_prediction_provider
5529 .as_ref()
5530 .map_or(false, |provider| {
5531 provider.provider.show_completions_in_menu()
5532 });
5533
5534 let preview_requires_modifier =
5535 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5536
5537 EditPredictionSettings::Enabled {
5538 show_in_menu,
5539 preview_requires_modifier,
5540 }
5541 }
5542
5543 fn should_show_edit_predictions(&self) -> bool {
5544 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5545 }
5546
5547 pub fn edit_prediction_preview_is_active(&self) -> bool {
5548 matches!(
5549 self.edit_prediction_preview,
5550 EditPredictionPreview::Active { .. }
5551 )
5552 }
5553
5554 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5555 let cursor = self.selections.newest_anchor().head();
5556 if let Some((buffer, cursor_position)) =
5557 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5558 {
5559 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5560 } else {
5561 false
5562 }
5563 }
5564
5565 fn edit_predictions_enabled_in_buffer(
5566 &self,
5567 buffer: &Entity<Buffer>,
5568 buffer_position: language::Anchor,
5569 cx: &App,
5570 ) -> bool {
5571 maybe!({
5572 if self.read_only(cx) {
5573 return Some(false);
5574 }
5575 let provider = self.edit_prediction_provider()?;
5576 if !provider.is_enabled(&buffer, buffer_position, cx) {
5577 return Some(false);
5578 }
5579 let buffer = buffer.read(cx);
5580 let Some(file) = buffer.file() else {
5581 return Some(true);
5582 };
5583 let settings = all_language_settings(Some(file), cx);
5584 Some(settings.edit_predictions_enabled_for_file(file, cx))
5585 })
5586 .unwrap_or(false)
5587 }
5588
5589 fn cycle_inline_completion(
5590 &mut self,
5591 direction: Direction,
5592 window: &mut Window,
5593 cx: &mut Context<Self>,
5594 ) -> Option<()> {
5595 let provider = self.edit_prediction_provider()?;
5596 let cursor = self.selections.newest_anchor().head();
5597 let (buffer, cursor_buffer_position) =
5598 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5599 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5600 return None;
5601 }
5602
5603 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5604 self.update_visible_inline_completion(window, cx);
5605
5606 Some(())
5607 }
5608
5609 pub fn show_inline_completion(
5610 &mut self,
5611 _: &ShowEditPrediction,
5612 window: &mut Window,
5613 cx: &mut Context<Self>,
5614 ) {
5615 if !self.has_active_inline_completion() {
5616 self.refresh_inline_completion(false, true, window, cx);
5617 return;
5618 }
5619
5620 self.update_visible_inline_completion(window, cx);
5621 }
5622
5623 pub fn display_cursor_names(
5624 &mut self,
5625 _: &DisplayCursorNames,
5626 window: &mut Window,
5627 cx: &mut Context<Self>,
5628 ) {
5629 self.show_cursor_names(window, cx);
5630 }
5631
5632 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5633 self.show_cursor_names = true;
5634 cx.notify();
5635 cx.spawn_in(window, async move |this, cx| {
5636 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5637 this.update(cx, |this, cx| {
5638 this.show_cursor_names = false;
5639 cx.notify()
5640 })
5641 .ok()
5642 })
5643 .detach();
5644 }
5645
5646 pub fn next_edit_prediction(
5647 &mut self,
5648 _: &NextEditPrediction,
5649 window: &mut Window,
5650 cx: &mut Context<Self>,
5651 ) {
5652 if self.has_active_inline_completion() {
5653 self.cycle_inline_completion(Direction::Next, window, cx);
5654 } else {
5655 let is_copilot_disabled = self
5656 .refresh_inline_completion(false, true, window, cx)
5657 .is_none();
5658 if is_copilot_disabled {
5659 cx.propagate();
5660 }
5661 }
5662 }
5663
5664 pub fn previous_edit_prediction(
5665 &mut self,
5666 _: &PreviousEditPrediction,
5667 window: &mut Window,
5668 cx: &mut Context<Self>,
5669 ) {
5670 if self.has_active_inline_completion() {
5671 self.cycle_inline_completion(Direction::Prev, window, cx);
5672 } else {
5673 let is_copilot_disabled = self
5674 .refresh_inline_completion(false, true, window, cx)
5675 .is_none();
5676 if is_copilot_disabled {
5677 cx.propagate();
5678 }
5679 }
5680 }
5681
5682 pub fn accept_edit_prediction(
5683 &mut self,
5684 _: &AcceptEditPrediction,
5685 window: &mut Window,
5686 cx: &mut Context<Self>,
5687 ) {
5688 if self.show_edit_predictions_in_menu() {
5689 self.hide_context_menu(window, cx);
5690 }
5691
5692 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5693 return;
5694 };
5695
5696 self.report_inline_completion_event(
5697 active_inline_completion.completion_id.clone(),
5698 true,
5699 cx,
5700 );
5701
5702 match &active_inline_completion.completion {
5703 InlineCompletion::Move { target, .. } => {
5704 let target = *target;
5705
5706 if let Some(position_map) = &self.last_position_map {
5707 if position_map
5708 .visible_row_range
5709 .contains(&target.to_display_point(&position_map.snapshot).row())
5710 || !self.edit_prediction_requires_modifier()
5711 {
5712 self.unfold_ranges(&[target..target], true, false, cx);
5713 // Note that this is also done in vim's handler of the Tab action.
5714 self.change_selections(
5715 Some(Autoscroll::newest()),
5716 window,
5717 cx,
5718 |selections| {
5719 selections.select_anchor_ranges([target..target]);
5720 },
5721 );
5722 self.clear_row_highlights::<EditPredictionPreview>();
5723
5724 self.edit_prediction_preview
5725 .set_previous_scroll_position(None);
5726 } else {
5727 self.edit_prediction_preview
5728 .set_previous_scroll_position(Some(
5729 position_map.snapshot.scroll_anchor,
5730 ));
5731
5732 self.highlight_rows::<EditPredictionPreview>(
5733 target..target,
5734 cx.theme().colors().editor_highlighted_line_background,
5735 true,
5736 cx,
5737 );
5738 self.request_autoscroll(Autoscroll::fit(), cx);
5739 }
5740 }
5741 }
5742 InlineCompletion::Edit { edits, .. } => {
5743 if let Some(provider) = self.edit_prediction_provider() {
5744 provider.accept(cx);
5745 }
5746
5747 let snapshot = self.buffer.read(cx).snapshot(cx);
5748 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5749
5750 self.buffer.update(cx, |buffer, cx| {
5751 buffer.edit(edits.iter().cloned(), None, cx)
5752 });
5753
5754 self.change_selections(None, window, cx, |s| {
5755 s.select_anchor_ranges([last_edit_end..last_edit_end])
5756 });
5757
5758 self.update_visible_inline_completion(window, cx);
5759 if self.active_inline_completion.is_none() {
5760 self.refresh_inline_completion(true, true, window, cx);
5761 }
5762
5763 cx.notify();
5764 }
5765 }
5766
5767 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5768 }
5769
5770 pub fn accept_partial_inline_completion(
5771 &mut self,
5772 _: &AcceptPartialEditPrediction,
5773 window: &mut Window,
5774 cx: &mut Context<Self>,
5775 ) {
5776 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5777 return;
5778 };
5779 if self.selections.count() != 1 {
5780 return;
5781 }
5782
5783 self.report_inline_completion_event(
5784 active_inline_completion.completion_id.clone(),
5785 true,
5786 cx,
5787 );
5788
5789 match &active_inline_completion.completion {
5790 InlineCompletion::Move { target, .. } => {
5791 let target = *target;
5792 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5793 selections.select_anchor_ranges([target..target]);
5794 });
5795 }
5796 InlineCompletion::Edit { edits, .. } => {
5797 // Find an insertion that starts at the cursor position.
5798 let snapshot = self.buffer.read(cx).snapshot(cx);
5799 let cursor_offset = self.selections.newest::<usize>(cx).head();
5800 let insertion = edits.iter().find_map(|(range, text)| {
5801 let range = range.to_offset(&snapshot);
5802 if range.is_empty() && range.start == cursor_offset {
5803 Some(text)
5804 } else {
5805 None
5806 }
5807 });
5808
5809 if let Some(text) = insertion {
5810 let mut partial_completion = text
5811 .chars()
5812 .by_ref()
5813 .take_while(|c| c.is_alphabetic())
5814 .collect::<String>();
5815 if partial_completion.is_empty() {
5816 partial_completion = text
5817 .chars()
5818 .by_ref()
5819 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5820 .collect::<String>();
5821 }
5822
5823 cx.emit(EditorEvent::InputHandled {
5824 utf16_range_to_replace: None,
5825 text: partial_completion.clone().into(),
5826 });
5827
5828 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5829
5830 self.refresh_inline_completion(true, true, window, cx);
5831 cx.notify();
5832 } else {
5833 self.accept_edit_prediction(&Default::default(), window, cx);
5834 }
5835 }
5836 }
5837 }
5838
5839 fn discard_inline_completion(
5840 &mut self,
5841 should_report_inline_completion_event: bool,
5842 cx: &mut Context<Self>,
5843 ) -> bool {
5844 if should_report_inline_completion_event {
5845 let completion_id = self
5846 .active_inline_completion
5847 .as_ref()
5848 .and_then(|active_completion| active_completion.completion_id.clone());
5849
5850 self.report_inline_completion_event(completion_id, false, cx);
5851 }
5852
5853 if let Some(provider) = self.edit_prediction_provider() {
5854 provider.discard(cx);
5855 }
5856
5857 self.take_active_inline_completion(cx)
5858 }
5859
5860 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5861 let Some(provider) = self.edit_prediction_provider() else {
5862 return;
5863 };
5864
5865 let Some((_, buffer, _)) = self
5866 .buffer
5867 .read(cx)
5868 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5869 else {
5870 return;
5871 };
5872
5873 let extension = buffer
5874 .read(cx)
5875 .file()
5876 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5877
5878 let event_type = match accepted {
5879 true => "Edit Prediction Accepted",
5880 false => "Edit Prediction Discarded",
5881 };
5882 telemetry::event!(
5883 event_type,
5884 provider = provider.name(),
5885 prediction_id = id,
5886 suggestion_accepted = accepted,
5887 file_extension = extension,
5888 );
5889 }
5890
5891 pub fn has_active_inline_completion(&self) -> bool {
5892 self.active_inline_completion.is_some()
5893 }
5894
5895 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5896 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5897 return false;
5898 };
5899
5900 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5901 self.clear_highlights::<InlineCompletionHighlight>(cx);
5902 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5903 true
5904 }
5905
5906 /// Returns true when we're displaying the edit prediction popover below the cursor
5907 /// like we are not previewing and the LSP autocomplete menu is visible
5908 /// or we are in `when_holding_modifier` mode.
5909 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5910 if self.edit_prediction_preview_is_active()
5911 || !self.show_edit_predictions_in_menu()
5912 || !self.edit_predictions_enabled()
5913 {
5914 return false;
5915 }
5916
5917 if self.has_visible_completions_menu() {
5918 return true;
5919 }
5920
5921 has_completion && self.edit_prediction_requires_modifier()
5922 }
5923
5924 fn handle_modifiers_changed(
5925 &mut self,
5926 modifiers: Modifiers,
5927 position_map: &PositionMap,
5928 window: &mut Window,
5929 cx: &mut Context<Self>,
5930 ) {
5931 if self.show_edit_predictions_in_menu() {
5932 self.update_edit_prediction_preview(&modifiers, window, cx);
5933 }
5934
5935 self.update_selection_mode(&modifiers, position_map, window, cx);
5936
5937 let mouse_position = window.mouse_position();
5938 if !position_map.text_hitbox.is_hovered(window) {
5939 return;
5940 }
5941
5942 self.update_hovered_link(
5943 position_map.point_for_position(mouse_position),
5944 &position_map.snapshot,
5945 modifiers,
5946 window,
5947 cx,
5948 )
5949 }
5950
5951 fn update_selection_mode(
5952 &mut self,
5953 modifiers: &Modifiers,
5954 position_map: &PositionMap,
5955 window: &mut Window,
5956 cx: &mut Context<Self>,
5957 ) {
5958 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5959 return;
5960 }
5961
5962 let mouse_position = window.mouse_position();
5963 let point_for_position = position_map.point_for_position(mouse_position);
5964 let position = point_for_position.previous_valid;
5965
5966 self.select(
5967 SelectPhase::BeginColumnar {
5968 position,
5969 reset: false,
5970 goal_column: point_for_position.exact_unclipped.column(),
5971 },
5972 window,
5973 cx,
5974 );
5975 }
5976
5977 fn update_edit_prediction_preview(
5978 &mut self,
5979 modifiers: &Modifiers,
5980 window: &mut Window,
5981 cx: &mut Context<Self>,
5982 ) {
5983 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5984 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5985 return;
5986 };
5987
5988 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5989 if matches!(
5990 self.edit_prediction_preview,
5991 EditPredictionPreview::Inactive { .. }
5992 ) {
5993 self.edit_prediction_preview = EditPredictionPreview::Active {
5994 previous_scroll_position: None,
5995 since: Instant::now(),
5996 };
5997
5998 self.update_visible_inline_completion(window, cx);
5999 cx.notify();
6000 }
6001 } else if let EditPredictionPreview::Active {
6002 previous_scroll_position,
6003 since,
6004 } = self.edit_prediction_preview
6005 {
6006 if let (Some(previous_scroll_position), Some(position_map)) =
6007 (previous_scroll_position, self.last_position_map.as_ref())
6008 {
6009 self.set_scroll_position(
6010 previous_scroll_position
6011 .scroll_position(&position_map.snapshot.display_snapshot),
6012 window,
6013 cx,
6014 );
6015 }
6016
6017 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6018 released_too_fast: since.elapsed() < Duration::from_millis(200),
6019 };
6020 self.clear_row_highlights::<EditPredictionPreview>();
6021 self.update_visible_inline_completion(window, cx);
6022 cx.notify();
6023 }
6024 }
6025
6026 fn update_visible_inline_completion(
6027 &mut self,
6028 _window: &mut Window,
6029 cx: &mut Context<Self>,
6030 ) -> Option<()> {
6031 let selection = self.selections.newest_anchor();
6032 let cursor = selection.head();
6033 let multibuffer = self.buffer.read(cx).snapshot(cx);
6034 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6035 let excerpt_id = cursor.excerpt_id;
6036
6037 let show_in_menu = self.show_edit_predictions_in_menu();
6038 let completions_menu_has_precedence = !show_in_menu
6039 && (self.context_menu.borrow().is_some()
6040 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6041
6042 if completions_menu_has_precedence
6043 || !offset_selection.is_empty()
6044 || self
6045 .active_inline_completion
6046 .as_ref()
6047 .map_or(false, |completion| {
6048 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6049 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6050 !invalidation_range.contains(&offset_selection.head())
6051 })
6052 {
6053 self.discard_inline_completion(false, cx);
6054 return None;
6055 }
6056
6057 self.take_active_inline_completion(cx);
6058 let Some(provider) = self.edit_prediction_provider() else {
6059 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6060 return None;
6061 };
6062
6063 let (buffer, cursor_buffer_position) =
6064 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6065
6066 self.edit_prediction_settings =
6067 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6068
6069 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6070
6071 if self.edit_prediction_indent_conflict {
6072 let cursor_point = cursor.to_point(&multibuffer);
6073
6074 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6075
6076 if let Some((_, indent)) = indents.iter().next() {
6077 if indent.len == cursor_point.column {
6078 self.edit_prediction_indent_conflict = false;
6079 }
6080 }
6081 }
6082
6083 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6084 let edits = inline_completion
6085 .edits
6086 .into_iter()
6087 .flat_map(|(range, new_text)| {
6088 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6089 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6090 Some((start..end, new_text))
6091 })
6092 .collect::<Vec<_>>();
6093 if edits.is_empty() {
6094 return None;
6095 }
6096
6097 let first_edit_start = edits.first().unwrap().0.start;
6098 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6099 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6100
6101 let last_edit_end = edits.last().unwrap().0.end;
6102 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6103 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6104
6105 let cursor_row = cursor.to_point(&multibuffer).row;
6106
6107 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6108
6109 let mut inlay_ids = Vec::new();
6110 let invalidation_row_range;
6111 let move_invalidation_row_range = if cursor_row < edit_start_row {
6112 Some(cursor_row..edit_end_row)
6113 } else if cursor_row > edit_end_row {
6114 Some(edit_start_row..cursor_row)
6115 } else {
6116 None
6117 };
6118 let is_move =
6119 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6120 let completion = if is_move {
6121 invalidation_row_range =
6122 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6123 let target = first_edit_start;
6124 InlineCompletion::Move { target, snapshot }
6125 } else {
6126 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6127 && !self.inline_completions_hidden_for_vim_mode;
6128
6129 if show_completions_in_buffer {
6130 if edits
6131 .iter()
6132 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6133 {
6134 let mut inlays = Vec::new();
6135 for (range, new_text) in &edits {
6136 let inlay = Inlay::inline_completion(
6137 post_inc(&mut self.next_inlay_id),
6138 range.start,
6139 new_text.as_str(),
6140 );
6141 inlay_ids.push(inlay.id);
6142 inlays.push(inlay);
6143 }
6144
6145 self.splice_inlays(&[], inlays, cx);
6146 } else {
6147 let background_color = cx.theme().status().deleted_background;
6148 self.highlight_text::<InlineCompletionHighlight>(
6149 edits.iter().map(|(range, _)| range.clone()).collect(),
6150 HighlightStyle {
6151 background_color: Some(background_color),
6152 ..Default::default()
6153 },
6154 cx,
6155 );
6156 }
6157 }
6158
6159 invalidation_row_range = edit_start_row..edit_end_row;
6160
6161 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6162 if provider.show_tab_accept_marker() {
6163 EditDisplayMode::TabAccept
6164 } else {
6165 EditDisplayMode::Inline
6166 }
6167 } else {
6168 EditDisplayMode::DiffPopover
6169 };
6170
6171 InlineCompletion::Edit {
6172 edits,
6173 edit_preview: inline_completion.edit_preview,
6174 display_mode,
6175 snapshot,
6176 }
6177 };
6178
6179 let invalidation_range = multibuffer
6180 .anchor_before(Point::new(invalidation_row_range.start, 0))
6181 ..multibuffer.anchor_after(Point::new(
6182 invalidation_row_range.end,
6183 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6184 ));
6185
6186 self.stale_inline_completion_in_menu = None;
6187 self.active_inline_completion = Some(InlineCompletionState {
6188 inlay_ids,
6189 completion,
6190 completion_id: inline_completion.id,
6191 invalidation_range,
6192 });
6193
6194 cx.notify();
6195
6196 Some(())
6197 }
6198
6199 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6200 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6201 }
6202
6203 fn render_code_actions_indicator(
6204 &self,
6205 _style: &EditorStyle,
6206 row: DisplayRow,
6207 is_active: bool,
6208 breakpoint: Option<&(Anchor, Breakpoint)>,
6209 cx: &mut Context<Self>,
6210 ) -> Option<IconButton> {
6211 let color = Color::Muted;
6212 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6213 let show_tooltip = !self.context_menu_visible();
6214
6215 if self.available_code_actions.is_some() {
6216 Some(
6217 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6218 .shape(ui::IconButtonShape::Square)
6219 .icon_size(IconSize::XSmall)
6220 .icon_color(color)
6221 .toggle_state(is_active)
6222 .when(show_tooltip, |this| {
6223 this.tooltip({
6224 let focus_handle = self.focus_handle.clone();
6225 move |window, cx| {
6226 Tooltip::for_action_in(
6227 "Toggle Code Actions",
6228 &ToggleCodeActions {
6229 deployed_from_indicator: None,
6230 },
6231 &focus_handle,
6232 window,
6233 cx,
6234 )
6235 }
6236 })
6237 })
6238 .on_click(cx.listener(move |editor, _e, window, cx| {
6239 window.focus(&editor.focus_handle(cx));
6240 editor.toggle_code_actions(
6241 &ToggleCodeActions {
6242 deployed_from_indicator: Some(row),
6243 },
6244 window,
6245 cx,
6246 );
6247 }))
6248 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6249 editor.set_breakpoint_context_menu(
6250 row,
6251 position,
6252 event.down.position,
6253 window,
6254 cx,
6255 );
6256 })),
6257 )
6258 } else {
6259 None
6260 }
6261 }
6262
6263 fn clear_tasks(&mut self) {
6264 self.tasks.clear()
6265 }
6266
6267 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6268 if self.tasks.insert(key, value).is_some() {
6269 // This case should hopefully be rare, but just in case...
6270 log::error!(
6271 "multiple different run targets found on a single line, only the last target will be rendered"
6272 )
6273 }
6274 }
6275
6276 /// Get all display points of breakpoints that will be rendered within editor
6277 ///
6278 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6279 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6280 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6281 fn active_breakpoints(
6282 &self,
6283 range: Range<DisplayRow>,
6284 window: &mut Window,
6285 cx: &mut Context<Self>,
6286 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6287 let mut breakpoint_display_points = HashMap::default();
6288
6289 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6290 return breakpoint_display_points;
6291 };
6292
6293 let snapshot = self.snapshot(window, cx);
6294
6295 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6296 let Some(project) = self.project.as_ref() else {
6297 return breakpoint_display_points;
6298 };
6299
6300 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6301 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6302
6303 for (buffer_snapshot, range, excerpt_id) in
6304 multi_buffer_snapshot.range_to_buffer_ranges(range)
6305 {
6306 let Some(buffer) = project.read_with(cx, |this, cx| {
6307 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6308 }) else {
6309 continue;
6310 };
6311 let breakpoints = breakpoint_store.read(cx).breakpoints(
6312 &buffer,
6313 Some(
6314 buffer_snapshot.anchor_before(range.start)
6315 ..buffer_snapshot.anchor_after(range.end),
6316 ),
6317 buffer_snapshot,
6318 cx,
6319 );
6320 for (anchor, breakpoint) in breakpoints {
6321 let multi_buffer_anchor =
6322 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6323 let position = multi_buffer_anchor
6324 .to_point(&multi_buffer_snapshot)
6325 .to_display_point(&snapshot);
6326
6327 breakpoint_display_points
6328 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6329 }
6330 }
6331
6332 breakpoint_display_points
6333 }
6334
6335 fn breakpoint_context_menu(
6336 &self,
6337 anchor: Anchor,
6338 window: &mut Window,
6339 cx: &mut Context<Self>,
6340 ) -> Entity<ui::ContextMenu> {
6341 let weak_editor = cx.weak_entity();
6342 let focus_handle = self.focus_handle(cx);
6343
6344 let row = self
6345 .buffer
6346 .read(cx)
6347 .snapshot(cx)
6348 .summary_for_anchor::<Point>(&anchor)
6349 .row;
6350
6351 let breakpoint = self
6352 .breakpoint_at_row(row, window, cx)
6353 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6354
6355 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6356 "Edit Log Breakpoint"
6357 } else {
6358 "Set Log Breakpoint"
6359 };
6360
6361 let condition_breakpoint_msg = if breakpoint
6362 .as_ref()
6363 .is_some_and(|bp| bp.1.condition.is_some())
6364 {
6365 "Edit Condition Breakpoint"
6366 } else {
6367 "Set Condition Breakpoint"
6368 };
6369
6370 let hit_condition_breakpoint_msg = if breakpoint
6371 .as_ref()
6372 .is_some_and(|bp| bp.1.hit_condition.is_some())
6373 {
6374 "Edit Hit Condition Breakpoint"
6375 } else {
6376 "Set Hit Condition Breakpoint"
6377 };
6378
6379 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6380 "Unset Breakpoint"
6381 } else {
6382 "Set Breakpoint"
6383 };
6384
6385 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6386 BreakpointState::Enabled => Some("Disable"),
6387 BreakpointState::Disabled => Some("Enable"),
6388 });
6389
6390 let (anchor, breakpoint) =
6391 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6392
6393 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6394 menu.on_blur_subscription(Subscription::new(|| {}))
6395 .context(focus_handle)
6396 .when_some(toggle_state_msg, |this, msg| {
6397 this.entry(msg, None, {
6398 let weak_editor = weak_editor.clone();
6399 let breakpoint = breakpoint.clone();
6400 move |_window, cx| {
6401 weak_editor
6402 .update(cx, |this, cx| {
6403 this.edit_breakpoint_at_anchor(
6404 anchor,
6405 breakpoint.as_ref().clone(),
6406 BreakpointEditAction::InvertState,
6407 cx,
6408 );
6409 })
6410 .log_err();
6411 }
6412 })
6413 })
6414 .entry(set_breakpoint_msg, None, {
6415 let weak_editor = weak_editor.clone();
6416 let breakpoint = breakpoint.clone();
6417 move |_window, cx| {
6418 weak_editor
6419 .update(cx, |this, cx| {
6420 this.edit_breakpoint_at_anchor(
6421 anchor,
6422 breakpoint.as_ref().clone(),
6423 BreakpointEditAction::Toggle,
6424 cx,
6425 );
6426 })
6427 .log_err();
6428 }
6429 })
6430 .entry(log_breakpoint_msg, None, {
6431 let breakpoint = breakpoint.clone();
6432 let weak_editor = weak_editor.clone();
6433 move |window, cx| {
6434 weak_editor
6435 .update(cx, |this, cx| {
6436 this.add_edit_breakpoint_block(
6437 anchor,
6438 breakpoint.as_ref(),
6439 BreakpointPromptEditAction::Log,
6440 window,
6441 cx,
6442 );
6443 })
6444 .log_err();
6445 }
6446 })
6447 .entry(condition_breakpoint_msg, None, {
6448 let breakpoint = breakpoint.clone();
6449 let weak_editor = weak_editor.clone();
6450 move |window, cx| {
6451 weak_editor
6452 .update(cx, |this, cx| {
6453 this.add_edit_breakpoint_block(
6454 anchor,
6455 breakpoint.as_ref(),
6456 BreakpointPromptEditAction::Condition,
6457 window,
6458 cx,
6459 );
6460 })
6461 .log_err();
6462 }
6463 })
6464 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6465 weak_editor
6466 .update(cx, |this, cx| {
6467 this.add_edit_breakpoint_block(
6468 anchor,
6469 breakpoint.as_ref(),
6470 BreakpointPromptEditAction::HitCondition,
6471 window,
6472 cx,
6473 );
6474 })
6475 .log_err();
6476 })
6477 })
6478 }
6479
6480 fn render_breakpoint(
6481 &self,
6482 position: Anchor,
6483 row: DisplayRow,
6484 breakpoint: &Breakpoint,
6485 cx: &mut Context<Self>,
6486 ) -> IconButton {
6487 let (color, icon) = {
6488 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6489 (false, false) => ui::IconName::DebugBreakpoint,
6490 (true, false) => ui::IconName::DebugLogBreakpoint,
6491 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6492 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6493 };
6494
6495 let color = if self
6496 .gutter_breakpoint_indicator
6497 .0
6498 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6499 {
6500 Color::Hint
6501 } else {
6502 Color::Debugger
6503 };
6504
6505 (color, icon)
6506 };
6507
6508 let breakpoint = Arc::from(breakpoint.clone());
6509
6510 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6511 .icon_size(IconSize::XSmall)
6512 .size(ui::ButtonSize::None)
6513 .icon_color(color)
6514 .style(ButtonStyle::Transparent)
6515 .on_click(cx.listener({
6516 let breakpoint = breakpoint.clone();
6517
6518 move |editor, event: &ClickEvent, window, cx| {
6519 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6520 BreakpointEditAction::InvertState
6521 } else {
6522 BreakpointEditAction::Toggle
6523 };
6524
6525 window.focus(&editor.focus_handle(cx));
6526 editor.edit_breakpoint_at_anchor(
6527 position,
6528 breakpoint.as_ref().clone(),
6529 edit_action,
6530 cx,
6531 );
6532 }
6533 }))
6534 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6535 editor.set_breakpoint_context_menu(
6536 row,
6537 Some(position),
6538 event.down.position,
6539 window,
6540 cx,
6541 );
6542 }))
6543 }
6544
6545 fn build_tasks_context(
6546 project: &Entity<Project>,
6547 buffer: &Entity<Buffer>,
6548 buffer_row: u32,
6549 tasks: &Arc<RunnableTasks>,
6550 cx: &mut Context<Self>,
6551 ) -> Task<Option<task::TaskContext>> {
6552 let position = Point::new(buffer_row, tasks.column);
6553 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6554 let location = Location {
6555 buffer: buffer.clone(),
6556 range: range_start..range_start,
6557 };
6558 // Fill in the environmental variables from the tree-sitter captures
6559 let mut captured_task_variables = TaskVariables::default();
6560 for (capture_name, value) in tasks.extra_variables.clone() {
6561 captured_task_variables.insert(
6562 task::VariableName::Custom(capture_name.into()),
6563 value.clone(),
6564 );
6565 }
6566 project.update(cx, |project, cx| {
6567 project.task_store().update(cx, |task_store, cx| {
6568 task_store.task_context_for_location(captured_task_variables, location, cx)
6569 })
6570 })
6571 }
6572
6573 pub fn spawn_nearest_task(
6574 &mut self,
6575 action: &SpawnNearestTask,
6576 window: &mut Window,
6577 cx: &mut Context<Self>,
6578 ) {
6579 let Some((workspace, _)) = self.workspace.clone() else {
6580 return;
6581 };
6582 let Some(project) = self.project.clone() else {
6583 return;
6584 };
6585
6586 // Try to find a closest, enclosing node using tree-sitter that has a
6587 // task
6588 let Some((buffer, buffer_row, tasks)) = self
6589 .find_enclosing_node_task(cx)
6590 // Or find the task that's closest in row-distance.
6591 .or_else(|| self.find_closest_task(cx))
6592 else {
6593 return;
6594 };
6595
6596 let reveal_strategy = action.reveal;
6597 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6598 cx.spawn_in(window, async move |_, cx| {
6599 let context = task_context.await?;
6600 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6601
6602 let resolved = resolved_task.resolved.as_mut()?;
6603 resolved.reveal = reveal_strategy;
6604
6605 workspace
6606 .update(cx, |workspace, cx| {
6607 workspace::tasks::schedule_resolved_task(
6608 workspace,
6609 task_source_kind,
6610 resolved_task,
6611 false,
6612 cx,
6613 );
6614 })
6615 .ok()
6616 })
6617 .detach();
6618 }
6619
6620 fn find_closest_task(
6621 &mut self,
6622 cx: &mut Context<Self>,
6623 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6624 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6625
6626 let ((buffer_id, row), tasks) = self
6627 .tasks
6628 .iter()
6629 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6630
6631 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6632 let tasks = Arc::new(tasks.to_owned());
6633 Some((buffer, *row, tasks))
6634 }
6635
6636 fn find_enclosing_node_task(
6637 &mut self,
6638 cx: &mut Context<Self>,
6639 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6640 let snapshot = self.buffer.read(cx).snapshot(cx);
6641 let offset = self.selections.newest::<usize>(cx).head();
6642 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6643 let buffer_id = excerpt.buffer().remote_id();
6644
6645 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6646 let mut cursor = layer.node().walk();
6647
6648 while cursor.goto_first_child_for_byte(offset).is_some() {
6649 if cursor.node().end_byte() == offset {
6650 cursor.goto_next_sibling();
6651 }
6652 }
6653
6654 // Ascend to the smallest ancestor that contains the range and has a task.
6655 loop {
6656 let node = cursor.node();
6657 let node_range = node.byte_range();
6658 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6659
6660 // Check if this node contains our offset
6661 if node_range.start <= offset && node_range.end >= offset {
6662 // If it contains offset, check for task
6663 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6664 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6665 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6666 }
6667 }
6668
6669 if !cursor.goto_parent() {
6670 break;
6671 }
6672 }
6673 None
6674 }
6675
6676 fn render_run_indicator(
6677 &self,
6678 _style: &EditorStyle,
6679 is_active: bool,
6680 row: DisplayRow,
6681 breakpoint: Option<(Anchor, Breakpoint)>,
6682 cx: &mut Context<Self>,
6683 ) -> IconButton {
6684 let color = Color::Muted;
6685 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6686
6687 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6688 .shape(ui::IconButtonShape::Square)
6689 .icon_size(IconSize::XSmall)
6690 .icon_color(color)
6691 .toggle_state(is_active)
6692 .on_click(cx.listener(move |editor, _e, window, cx| {
6693 window.focus(&editor.focus_handle(cx));
6694 editor.toggle_code_actions(
6695 &ToggleCodeActions {
6696 deployed_from_indicator: Some(row),
6697 },
6698 window,
6699 cx,
6700 );
6701 }))
6702 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6703 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6704 }))
6705 }
6706
6707 pub fn context_menu_visible(&self) -> bool {
6708 !self.edit_prediction_preview_is_active()
6709 && self
6710 .context_menu
6711 .borrow()
6712 .as_ref()
6713 .map_or(false, |menu| menu.visible())
6714 }
6715
6716 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6717 self.context_menu
6718 .borrow()
6719 .as_ref()
6720 .map(|menu| menu.origin())
6721 }
6722
6723 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6724 self.context_menu_options = Some(options);
6725 }
6726
6727 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6728 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6729
6730 fn render_edit_prediction_popover(
6731 &mut self,
6732 text_bounds: &Bounds<Pixels>,
6733 content_origin: gpui::Point<Pixels>,
6734 editor_snapshot: &EditorSnapshot,
6735 visible_row_range: Range<DisplayRow>,
6736 scroll_top: f32,
6737 scroll_bottom: f32,
6738 line_layouts: &[LineWithInvisibles],
6739 line_height: Pixels,
6740 scroll_pixel_position: gpui::Point<Pixels>,
6741 newest_selection_head: Option<DisplayPoint>,
6742 editor_width: Pixels,
6743 style: &EditorStyle,
6744 window: &mut Window,
6745 cx: &mut App,
6746 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6747 let active_inline_completion = self.active_inline_completion.as_ref()?;
6748
6749 if self.edit_prediction_visible_in_cursor_popover(true) {
6750 return None;
6751 }
6752
6753 match &active_inline_completion.completion {
6754 InlineCompletion::Move { target, .. } => {
6755 let target_display_point = target.to_display_point(editor_snapshot);
6756
6757 if self.edit_prediction_requires_modifier() {
6758 if !self.edit_prediction_preview_is_active() {
6759 return None;
6760 }
6761
6762 self.render_edit_prediction_modifier_jump_popover(
6763 text_bounds,
6764 content_origin,
6765 visible_row_range,
6766 line_layouts,
6767 line_height,
6768 scroll_pixel_position,
6769 newest_selection_head,
6770 target_display_point,
6771 window,
6772 cx,
6773 )
6774 } else {
6775 self.render_edit_prediction_eager_jump_popover(
6776 text_bounds,
6777 content_origin,
6778 editor_snapshot,
6779 visible_row_range,
6780 scroll_top,
6781 scroll_bottom,
6782 line_height,
6783 scroll_pixel_position,
6784 target_display_point,
6785 editor_width,
6786 window,
6787 cx,
6788 )
6789 }
6790 }
6791 InlineCompletion::Edit {
6792 display_mode: EditDisplayMode::Inline,
6793 ..
6794 } => None,
6795 InlineCompletion::Edit {
6796 display_mode: EditDisplayMode::TabAccept,
6797 edits,
6798 ..
6799 } => {
6800 let range = &edits.first()?.0;
6801 let target_display_point = range.end.to_display_point(editor_snapshot);
6802
6803 self.render_edit_prediction_end_of_line_popover(
6804 "Accept",
6805 editor_snapshot,
6806 visible_row_range,
6807 target_display_point,
6808 line_height,
6809 scroll_pixel_position,
6810 content_origin,
6811 editor_width,
6812 window,
6813 cx,
6814 )
6815 }
6816 InlineCompletion::Edit {
6817 edits,
6818 edit_preview,
6819 display_mode: EditDisplayMode::DiffPopover,
6820 snapshot,
6821 } => self.render_edit_prediction_diff_popover(
6822 text_bounds,
6823 content_origin,
6824 editor_snapshot,
6825 visible_row_range,
6826 line_layouts,
6827 line_height,
6828 scroll_pixel_position,
6829 newest_selection_head,
6830 editor_width,
6831 style,
6832 edits,
6833 edit_preview,
6834 snapshot,
6835 window,
6836 cx,
6837 ),
6838 }
6839 }
6840
6841 fn render_edit_prediction_modifier_jump_popover(
6842 &mut self,
6843 text_bounds: &Bounds<Pixels>,
6844 content_origin: gpui::Point<Pixels>,
6845 visible_row_range: Range<DisplayRow>,
6846 line_layouts: &[LineWithInvisibles],
6847 line_height: Pixels,
6848 scroll_pixel_position: gpui::Point<Pixels>,
6849 newest_selection_head: Option<DisplayPoint>,
6850 target_display_point: DisplayPoint,
6851 window: &mut Window,
6852 cx: &mut App,
6853 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6854 let scrolled_content_origin =
6855 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6856
6857 const SCROLL_PADDING_Y: Pixels = px(12.);
6858
6859 if target_display_point.row() < visible_row_range.start {
6860 return self.render_edit_prediction_scroll_popover(
6861 |_| SCROLL_PADDING_Y,
6862 IconName::ArrowUp,
6863 visible_row_range,
6864 line_layouts,
6865 newest_selection_head,
6866 scrolled_content_origin,
6867 window,
6868 cx,
6869 );
6870 } else if target_display_point.row() >= visible_row_range.end {
6871 return self.render_edit_prediction_scroll_popover(
6872 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6873 IconName::ArrowDown,
6874 visible_row_range,
6875 line_layouts,
6876 newest_selection_head,
6877 scrolled_content_origin,
6878 window,
6879 cx,
6880 );
6881 }
6882
6883 const POLE_WIDTH: Pixels = px(2.);
6884
6885 let line_layout =
6886 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6887 let target_column = target_display_point.column() as usize;
6888
6889 let target_x = line_layout.x_for_index(target_column);
6890 let target_y =
6891 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6892
6893 let flag_on_right = target_x < text_bounds.size.width / 2.;
6894
6895 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6896 border_color.l += 0.001;
6897
6898 let mut element = v_flex()
6899 .items_end()
6900 .when(flag_on_right, |el| el.items_start())
6901 .child(if flag_on_right {
6902 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6903 .rounded_bl(px(0.))
6904 .rounded_tl(px(0.))
6905 .border_l_2()
6906 .border_color(border_color)
6907 } else {
6908 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6909 .rounded_br(px(0.))
6910 .rounded_tr(px(0.))
6911 .border_r_2()
6912 .border_color(border_color)
6913 })
6914 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6915 .into_any();
6916
6917 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6918
6919 let mut origin = scrolled_content_origin + point(target_x, target_y)
6920 - point(
6921 if flag_on_right {
6922 POLE_WIDTH
6923 } else {
6924 size.width - POLE_WIDTH
6925 },
6926 size.height - line_height,
6927 );
6928
6929 origin.x = origin.x.max(content_origin.x);
6930
6931 element.prepaint_at(origin, window, cx);
6932
6933 Some((element, origin))
6934 }
6935
6936 fn render_edit_prediction_scroll_popover(
6937 &mut self,
6938 to_y: impl Fn(Size<Pixels>) -> Pixels,
6939 scroll_icon: IconName,
6940 visible_row_range: Range<DisplayRow>,
6941 line_layouts: &[LineWithInvisibles],
6942 newest_selection_head: Option<DisplayPoint>,
6943 scrolled_content_origin: gpui::Point<Pixels>,
6944 window: &mut Window,
6945 cx: &mut App,
6946 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6947 let mut element = self
6948 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6949 .into_any();
6950
6951 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6952
6953 let cursor = newest_selection_head?;
6954 let cursor_row_layout =
6955 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6956 let cursor_column = cursor.column() as usize;
6957
6958 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6959
6960 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6961
6962 element.prepaint_at(origin, window, cx);
6963 Some((element, origin))
6964 }
6965
6966 fn render_edit_prediction_eager_jump_popover(
6967 &mut self,
6968 text_bounds: &Bounds<Pixels>,
6969 content_origin: gpui::Point<Pixels>,
6970 editor_snapshot: &EditorSnapshot,
6971 visible_row_range: Range<DisplayRow>,
6972 scroll_top: f32,
6973 scroll_bottom: f32,
6974 line_height: Pixels,
6975 scroll_pixel_position: gpui::Point<Pixels>,
6976 target_display_point: DisplayPoint,
6977 editor_width: Pixels,
6978 window: &mut Window,
6979 cx: &mut App,
6980 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6981 if target_display_point.row().as_f32() < scroll_top {
6982 let mut element = self
6983 .render_edit_prediction_line_popover(
6984 "Jump to Edit",
6985 Some(IconName::ArrowUp),
6986 window,
6987 cx,
6988 )?
6989 .into_any();
6990
6991 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6992 let offset = point(
6993 (text_bounds.size.width - size.width) / 2.,
6994 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6995 );
6996
6997 let origin = text_bounds.origin + offset;
6998 element.prepaint_at(origin, window, cx);
6999 Some((element, origin))
7000 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7001 let mut element = self
7002 .render_edit_prediction_line_popover(
7003 "Jump to Edit",
7004 Some(IconName::ArrowDown),
7005 window,
7006 cx,
7007 )?
7008 .into_any();
7009
7010 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7011 let offset = point(
7012 (text_bounds.size.width - size.width) / 2.,
7013 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7014 );
7015
7016 let origin = text_bounds.origin + offset;
7017 element.prepaint_at(origin, window, cx);
7018 Some((element, origin))
7019 } else {
7020 self.render_edit_prediction_end_of_line_popover(
7021 "Jump to Edit",
7022 editor_snapshot,
7023 visible_row_range,
7024 target_display_point,
7025 line_height,
7026 scroll_pixel_position,
7027 content_origin,
7028 editor_width,
7029 window,
7030 cx,
7031 )
7032 }
7033 }
7034
7035 fn render_edit_prediction_end_of_line_popover(
7036 self: &mut Editor,
7037 label: &'static str,
7038 editor_snapshot: &EditorSnapshot,
7039 visible_row_range: Range<DisplayRow>,
7040 target_display_point: DisplayPoint,
7041 line_height: Pixels,
7042 scroll_pixel_position: gpui::Point<Pixels>,
7043 content_origin: gpui::Point<Pixels>,
7044 editor_width: Pixels,
7045 window: &mut Window,
7046 cx: &mut App,
7047 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7048 let target_line_end = DisplayPoint::new(
7049 target_display_point.row(),
7050 editor_snapshot.line_len(target_display_point.row()),
7051 );
7052
7053 let mut element = self
7054 .render_edit_prediction_line_popover(label, None, window, cx)?
7055 .into_any();
7056
7057 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7058
7059 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7060
7061 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7062 let mut origin = start_point
7063 + line_origin
7064 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7065 origin.x = origin.x.max(content_origin.x);
7066
7067 let max_x = content_origin.x + editor_width - size.width;
7068
7069 if origin.x > max_x {
7070 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7071
7072 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7073 origin.y += offset;
7074 IconName::ArrowUp
7075 } else {
7076 origin.y -= offset;
7077 IconName::ArrowDown
7078 };
7079
7080 element = self
7081 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7082 .into_any();
7083
7084 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7085
7086 origin.x = content_origin.x + editor_width - size.width - px(2.);
7087 }
7088
7089 element.prepaint_at(origin, window, cx);
7090 Some((element, origin))
7091 }
7092
7093 fn render_edit_prediction_diff_popover(
7094 self: &Editor,
7095 text_bounds: &Bounds<Pixels>,
7096 content_origin: gpui::Point<Pixels>,
7097 editor_snapshot: &EditorSnapshot,
7098 visible_row_range: Range<DisplayRow>,
7099 line_layouts: &[LineWithInvisibles],
7100 line_height: Pixels,
7101 scroll_pixel_position: gpui::Point<Pixels>,
7102 newest_selection_head: Option<DisplayPoint>,
7103 editor_width: Pixels,
7104 style: &EditorStyle,
7105 edits: &Vec<(Range<Anchor>, String)>,
7106 edit_preview: &Option<language::EditPreview>,
7107 snapshot: &language::BufferSnapshot,
7108 window: &mut Window,
7109 cx: &mut App,
7110 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7111 let edit_start = edits
7112 .first()
7113 .unwrap()
7114 .0
7115 .start
7116 .to_display_point(editor_snapshot);
7117 let edit_end = edits
7118 .last()
7119 .unwrap()
7120 .0
7121 .end
7122 .to_display_point(editor_snapshot);
7123
7124 let is_visible = visible_row_range.contains(&edit_start.row())
7125 || visible_row_range.contains(&edit_end.row());
7126 if !is_visible {
7127 return None;
7128 }
7129
7130 let highlighted_edits =
7131 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7132
7133 let styled_text = highlighted_edits.to_styled_text(&style.text);
7134 let line_count = highlighted_edits.text.lines().count();
7135
7136 const BORDER_WIDTH: Pixels = px(1.);
7137
7138 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7139 let has_keybind = keybind.is_some();
7140
7141 let mut element = h_flex()
7142 .items_start()
7143 .child(
7144 h_flex()
7145 .bg(cx.theme().colors().editor_background)
7146 .border(BORDER_WIDTH)
7147 .shadow_sm()
7148 .border_color(cx.theme().colors().border)
7149 .rounded_l_lg()
7150 .when(line_count > 1, |el| el.rounded_br_lg())
7151 .pr_1()
7152 .child(styled_text),
7153 )
7154 .child(
7155 h_flex()
7156 .h(line_height + BORDER_WIDTH * 2.)
7157 .px_1p5()
7158 .gap_1()
7159 // Workaround: For some reason, there's a gap if we don't do this
7160 .ml(-BORDER_WIDTH)
7161 .shadow(smallvec![gpui::BoxShadow {
7162 color: gpui::black().opacity(0.05),
7163 offset: point(px(1.), px(1.)),
7164 blur_radius: px(2.),
7165 spread_radius: px(0.),
7166 }])
7167 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7168 .border(BORDER_WIDTH)
7169 .border_color(cx.theme().colors().border)
7170 .rounded_r_lg()
7171 .id("edit_prediction_diff_popover_keybind")
7172 .when(!has_keybind, |el| {
7173 let status_colors = cx.theme().status();
7174
7175 el.bg(status_colors.error_background)
7176 .border_color(status_colors.error.opacity(0.6))
7177 .child(Icon::new(IconName::Info).color(Color::Error))
7178 .cursor_default()
7179 .hoverable_tooltip(move |_window, cx| {
7180 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7181 })
7182 })
7183 .children(keybind),
7184 )
7185 .into_any();
7186
7187 let longest_row =
7188 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7189 let longest_line_width = if visible_row_range.contains(&longest_row) {
7190 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7191 } else {
7192 layout_line(
7193 longest_row,
7194 editor_snapshot,
7195 style,
7196 editor_width,
7197 |_| false,
7198 window,
7199 cx,
7200 )
7201 .width
7202 };
7203
7204 let viewport_bounds =
7205 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7206 right: -EditorElement::SCROLLBAR_WIDTH,
7207 ..Default::default()
7208 });
7209
7210 let x_after_longest =
7211 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7212 - scroll_pixel_position.x;
7213
7214 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7215
7216 // Fully visible if it can be displayed within the window (allow overlapping other
7217 // panes). However, this is only allowed if the popover starts within text_bounds.
7218 let can_position_to_the_right = x_after_longest < text_bounds.right()
7219 && x_after_longest + element_bounds.width < viewport_bounds.right();
7220
7221 let mut origin = if can_position_to_the_right {
7222 point(
7223 x_after_longest,
7224 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7225 - scroll_pixel_position.y,
7226 )
7227 } else {
7228 let cursor_row = newest_selection_head.map(|head| head.row());
7229 let above_edit = edit_start
7230 .row()
7231 .0
7232 .checked_sub(line_count as u32)
7233 .map(DisplayRow);
7234 let below_edit = Some(edit_end.row() + 1);
7235 let above_cursor =
7236 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7237 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7238
7239 // Place the edit popover adjacent to the edit if there is a location
7240 // available that is onscreen and does not obscure the cursor. Otherwise,
7241 // place it adjacent to the cursor.
7242 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7243 .into_iter()
7244 .flatten()
7245 .find(|&start_row| {
7246 let end_row = start_row + line_count as u32;
7247 visible_row_range.contains(&start_row)
7248 && visible_row_range.contains(&end_row)
7249 && cursor_row.map_or(true, |cursor_row| {
7250 !((start_row..end_row).contains(&cursor_row))
7251 })
7252 })?;
7253
7254 content_origin
7255 + point(
7256 -scroll_pixel_position.x,
7257 row_target.as_f32() * line_height - scroll_pixel_position.y,
7258 )
7259 };
7260
7261 origin.x -= BORDER_WIDTH;
7262
7263 window.defer_draw(element, origin, 1);
7264
7265 // Do not return an element, since it will already be drawn due to defer_draw.
7266 None
7267 }
7268
7269 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7270 px(30.)
7271 }
7272
7273 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7274 if self.read_only(cx) {
7275 cx.theme().players().read_only()
7276 } else {
7277 self.style.as_ref().unwrap().local_player
7278 }
7279 }
7280
7281 fn render_edit_prediction_accept_keybind(
7282 &self,
7283 window: &mut Window,
7284 cx: &App,
7285 ) -> Option<AnyElement> {
7286 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7287 let accept_keystroke = accept_binding.keystroke()?;
7288
7289 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7290
7291 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7292 Color::Accent
7293 } else {
7294 Color::Muted
7295 };
7296
7297 h_flex()
7298 .px_0p5()
7299 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7300 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7301 .text_size(TextSize::XSmall.rems(cx))
7302 .child(h_flex().children(ui::render_modifiers(
7303 &accept_keystroke.modifiers,
7304 PlatformStyle::platform(),
7305 Some(modifiers_color),
7306 Some(IconSize::XSmall.rems().into()),
7307 true,
7308 )))
7309 .when(is_platform_style_mac, |parent| {
7310 parent.child(accept_keystroke.key.clone())
7311 })
7312 .when(!is_platform_style_mac, |parent| {
7313 parent.child(
7314 Key::new(
7315 util::capitalize(&accept_keystroke.key),
7316 Some(Color::Default),
7317 )
7318 .size(Some(IconSize::XSmall.rems().into())),
7319 )
7320 })
7321 .into_any()
7322 .into()
7323 }
7324
7325 fn render_edit_prediction_line_popover(
7326 &self,
7327 label: impl Into<SharedString>,
7328 icon: Option<IconName>,
7329 window: &mut Window,
7330 cx: &App,
7331 ) -> Option<Stateful<Div>> {
7332 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7333
7334 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7335 let has_keybind = keybind.is_some();
7336
7337 let result = h_flex()
7338 .id("ep-line-popover")
7339 .py_0p5()
7340 .pl_1()
7341 .pr(padding_right)
7342 .gap_1()
7343 .rounded_md()
7344 .border_1()
7345 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7346 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7347 .shadow_sm()
7348 .when(!has_keybind, |el| {
7349 let status_colors = cx.theme().status();
7350
7351 el.bg(status_colors.error_background)
7352 .border_color(status_colors.error.opacity(0.6))
7353 .pl_2()
7354 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7355 .cursor_default()
7356 .hoverable_tooltip(move |_window, cx| {
7357 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7358 })
7359 })
7360 .children(keybind)
7361 .child(
7362 Label::new(label)
7363 .size(LabelSize::Small)
7364 .when(!has_keybind, |el| {
7365 el.color(cx.theme().status().error.into()).strikethrough()
7366 }),
7367 )
7368 .when(!has_keybind, |el| {
7369 el.child(
7370 h_flex().ml_1().child(
7371 Icon::new(IconName::Info)
7372 .size(IconSize::Small)
7373 .color(cx.theme().status().error.into()),
7374 ),
7375 )
7376 })
7377 .when_some(icon, |element, icon| {
7378 element.child(
7379 div()
7380 .mt(px(1.5))
7381 .child(Icon::new(icon).size(IconSize::Small)),
7382 )
7383 });
7384
7385 Some(result)
7386 }
7387
7388 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7389 let accent_color = cx.theme().colors().text_accent;
7390 let editor_bg_color = cx.theme().colors().editor_background;
7391 editor_bg_color.blend(accent_color.opacity(0.1))
7392 }
7393
7394 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7395 let accent_color = cx.theme().colors().text_accent;
7396 let editor_bg_color = cx.theme().colors().editor_background;
7397 editor_bg_color.blend(accent_color.opacity(0.6))
7398 }
7399
7400 fn render_edit_prediction_cursor_popover(
7401 &self,
7402 min_width: Pixels,
7403 max_width: Pixels,
7404 cursor_point: Point,
7405 style: &EditorStyle,
7406 accept_keystroke: Option<&gpui::Keystroke>,
7407 _window: &Window,
7408 cx: &mut Context<Editor>,
7409 ) -> Option<AnyElement> {
7410 let provider = self.edit_prediction_provider.as_ref()?;
7411
7412 if provider.provider.needs_terms_acceptance(cx) {
7413 return Some(
7414 h_flex()
7415 .min_w(min_width)
7416 .flex_1()
7417 .px_2()
7418 .py_1()
7419 .gap_3()
7420 .elevation_2(cx)
7421 .hover(|style| style.bg(cx.theme().colors().element_hover))
7422 .id("accept-terms")
7423 .cursor_pointer()
7424 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7425 .on_click(cx.listener(|this, _event, window, cx| {
7426 cx.stop_propagation();
7427 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7428 window.dispatch_action(
7429 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7430 cx,
7431 );
7432 }))
7433 .child(
7434 h_flex()
7435 .flex_1()
7436 .gap_2()
7437 .child(Icon::new(IconName::ZedPredict))
7438 .child(Label::new("Accept Terms of Service"))
7439 .child(div().w_full())
7440 .child(
7441 Icon::new(IconName::ArrowUpRight)
7442 .color(Color::Muted)
7443 .size(IconSize::Small),
7444 )
7445 .into_any_element(),
7446 )
7447 .into_any(),
7448 );
7449 }
7450
7451 let is_refreshing = provider.provider.is_refreshing(cx);
7452
7453 fn pending_completion_container() -> Div {
7454 h_flex()
7455 .h_full()
7456 .flex_1()
7457 .gap_2()
7458 .child(Icon::new(IconName::ZedPredict))
7459 }
7460
7461 let completion = match &self.active_inline_completion {
7462 Some(prediction) => {
7463 if !self.has_visible_completions_menu() {
7464 const RADIUS: Pixels = px(6.);
7465 const BORDER_WIDTH: Pixels = px(1.);
7466
7467 return Some(
7468 h_flex()
7469 .elevation_2(cx)
7470 .border(BORDER_WIDTH)
7471 .border_color(cx.theme().colors().border)
7472 .when(accept_keystroke.is_none(), |el| {
7473 el.border_color(cx.theme().status().error)
7474 })
7475 .rounded(RADIUS)
7476 .rounded_tl(px(0.))
7477 .overflow_hidden()
7478 .child(div().px_1p5().child(match &prediction.completion {
7479 InlineCompletion::Move { target, snapshot } => {
7480 use text::ToPoint as _;
7481 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7482 {
7483 Icon::new(IconName::ZedPredictDown)
7484 } else {
7485 Icon::new(IconName::ZedPredictUp)
7486 }
7487 }
7488 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7489 }))
7490 .child(
7491 h_flex()
7492 .gap_1()
7493 .py_1()
7494 .px_2()
7495 .rounded_r(RADIUS - BORDER_WIDTH)
7496 .border_l_1()
7497 .border_color(cx.theme().colors().border)
7498 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7499 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7500 el.child(
7501 Label::new("Hold")
7502 .size(LabelSize::Small)
7503 .when(accept_keystroke.is_none(), |el| {
7504 el.strikethrough()
7505 })
7506 .line_height_style(LineHeightStyle::UiLabel),
7507 )
7508 })
7509 .id("edit_prediction_cursor_popover_keybind")
7510 .when(accept_keystroke.is_none(), |el| {
7511 let status_colors = cx.theme().status();
7512
7513 el.bg(status_colors.error_background)
7514 .border_color(status_colors.error.opacity(0.6))
7515 .child(Icon::new(IconName::Info).color(Color::Error))
7516 .cursor_default()
7517 .hoverable_tooltip(move |_window, cx| {
7518 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7519 .into()
7520 })
7521 })
7522 .when_some(
7523 accept_keystroke.as_ref(),
7524 |el, accept_keystroke| {
7525 el.child(h_flex().children(ui::render_modifiers(
7526 &accept_keystroke.modifiers,
7527 PlatformStyle::platform(),
7528 Some(Color::Default),
7529 Some(IconSize::XSmall.rems().into()),
7530 false,
7531 )))
7532 },
7533 ),
7534 )
7535 .into_any(),
7536 );
7537 }
7538
7539 self.render_edit_prediction_cursor_popover_preview(
7540 prediction,
7541 cursor_point,
7542 style,
7543 cx,
7544 )?
7545 }
7546
7547 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7548 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7549 stale_completion,
7550 cursor_point,
7551 style,
7552 cx,
7553 )?,
7554
7555 None => {
7556 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7557 }
7558 },
7559
7560 None => pending_completion_container().child(Label::new("No Prediction")),
7561 };
7562
7563 let completion = if is_refreshing {
7564 completion
7565 .with_animation(
7566 "loading-completion",
7567 Animation::new(Duration::from_secs(2))
7568 .repeat()
7569 .with_easing(pulsating_between(0.4, 0.8)),
7570 |label, delta| label.opacity(delta),
7571 )
7572 .into_any_element()
7573 } else {
7574 completion.into_any_element()
7575 };
7576
7577 let has_completion = self.active_inline_completion.is_some();
7578
7579 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7580 Some(
7581 h_flex()
7582 .min_w(min_width)
7583 .max_w(max_width)
7584 .flex_1()
7585 .elevation_2(cx)
7586 .border_color(cx.theme().colors().border)
7587 .child(
7588 div()
7589 .flex_1()
7590 .py_1()
7591 .px_2()
7592 .overflow_hidden()
7593 .child(completion),
7594 )
7595 .when_some(accept_keystroke, |el, accept_keystroke| {
7596 if !accept_keystroke.modifiers.modified() {
7597 return el;
7598 }
7599
7600 el.child(
7601 h_flex()
7602 .h_full()
7603 .border_l_1()
7604 .rounded_r_lg()
7605 .border_color(cx.theme().colors().border)
7606 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7607 .gap_1()
7608 .py_1()
7609 .px_2()
7610 .child(
7611 h_flex()
7612 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7613 .when(is_platform_style_mac, |parent| parent.gap_1())
7614 .child(h_flex().children(ui::render_modifiers(
7615 &accept_keystroke.modifiers,
7616 PlatformStyle::platform(),
7617 Some(if !has_completion {
7618 Color::Muted
7619 } else {
7620 Color::Default
7621 }),
7622 None,
7623 false,
7624 ))),
7625 )
7626 .child(Label::new("Preview").into_any_element())
7627 .opacity(if has_completion { 1.0 } else { 0.4 }),
7628 )
7629 })
7630 .into_any(),
7631 )
7632 }
7633
7634 fn render_edit_prediction_cursor_popover_preview(
7635 &self,
7636 completion: &InlineCompletionState,
7637 cursor_point: Point,
7638 style: &EditorStyle,
7639 cx: &mut Context<Editor>,
7640 ) -> Option<Div> {
7641 use text::ToPoint as _;
7642
7643 fn render_relative_row_jump(
7644 prefix: impl Into<String>,
7645 current_row: u32,
7646 target_row: u32,
7647 ) -> Div {
7648 let (row_diff, arrow) = if target_row < current_row {
7649 (current_row - target_row, IconName::ArrowUp)
7650 } else {
7651 (target_row - current_row, IconName::ArrowDown)
7652 };
7653
7654 h_flex()
7655 .child(
7656 Label::new(format!("{}{}", prefix.into(), row_diff))
7657 .color(Color::Muted)
7658 .size(LabelSize::Small),
7659 )
7660 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7661 }
7662
7663 match &completion.completion {
7664 InlineCompletion::Move {
7665 target, snapshot, ..
7666 } => Some(
7667 h_flex()
7668 .px_2()
7669 .gap_2()
7670 .flex_1()
7671 .child(
7672 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7673 Icon::new(IconName::ZedPredictDown)
7674 } else {
7675 Icon::new(IconName::ZedPredictUp)
7676 },
7677 )
7678 .child(Label::new("Jump to Edit")),
7679 ),
7680
7681 InlineCompletion::Edit {
7682 edits,
7683 edit_preview,
7684 snapshot,
7685 display_mode: _,
7686 } => {
7687 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7688
7689 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7690 &snapshot,
7691 &edits,
7692 edit_preview.as_ref()?,
7693 true,
7694 cx,
7695 )
7696 .first_line_preview();
7697
7698 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7699 .with_default_highlights(&style.text, highlighted_edits.highlights);
7700
7701 let preview = h_flex()
7702 .gap_1()
7703 .min_w_16()
7704 .child(styled_text)
7705 .when(has_more_lines, |parent| parent.child("…"));
7706
7707 let left = if first_edit_row != cursor_point.row {
7708 render_relative_row_jump("", cursor_point.row, first_edit_row)
7709 .into_any_element()
7710 } else {
7711 Icon::new(IconName::ZedPredict).into_any_element()
7712 };
7713
7714 Some(
7715 h_flex()
7716 .h_full()
7717 .flex_1()
7718 .gap_2()
7719 .pr_1()
7720 .overflow_x_hidden()
7721 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7722 .child(left)
7723 .child(preview),
7724 )
7725 }
7726 }
7727 }
7728
7729 fn render_context_menu(
7730 &self,
7731 style: &EditorStyle,
7732 max_height_in_lines: u32,
7733 y_flipped: bool,
7734 window: &mut Window,
7735 cx: &mut Context<Editor>,
7736 ) -> Option<AnyElement> {
7737 let menu = self.context_menu.borrow();
7738 let menu = menu.as_ref()?;
7739 if !menu.visible() {
7740 return None;
7741 };
7742 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7743 }
7744
7745 fn render_context_menu_aside(
7746 &mut self,
7747 max_size: Size<Pixels>,
7748 window: &mut Window,
7749 cx: &mut Context<Editor>,
7750 ) -> Option<AnyElement> {
7751 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7752 if menu.visible() {
7753 menu.render_aside(self, max_size, window, cx)
7754 } else {
7755 None
7756 }
7757 })
7758 }
7759
7760 fn hide_context_menu(
7761 &mut self,
7762 window: &mut Window,
7763 cx: &mut Context<Self>,
7764 ) -> Option<CodeContextMenu> {
7765 cx.notify();
7766 self.completion_tasks.clear();
7767 let context_menu = self.context_menu.borrow_mut().take();
7768 self.stale_inline_completion_in_menu.take();
7769 self.update_visible_inline_completion(window, cx);
7770 context_menu
7771 }
7772
7773 fn show_snippet_choices(
7774 &mut self,
7775 choices: &Vec<String>,
7776 selection: Range<Anchor>,
7777 cx: &mut Context<Self>,
7778 ) {
7779 if selection.start.buffer_id.is_none() {
7780 return;
7781 }
7782 let buffer_id = selection.start.buffer_id.unwrap();
7783 let buffer = self.buffer().read(cx).buffer(buffer_id);
7784 let id = post_inc(&mut self.next_completion_id);
7785
7786 if let Some(buffer) = buffer {
7787 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7788 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7789 ));
7790 }
7791 }
7792
7793 pub fn insert_snippet(
7794 &mut self,
7795 insertion_ranges: &[Range<usize>],
7796 snippet: Snippet,
7797 window: &mut Window,
7798 cx: &mut Context<Self>,
7799 ) -> Result<()> {
7800 struct Tabstop<T> {
7801 is_end_tabstop: bool,
7802 ranges: Vec<Range<T>>,
7803 choices: Option<Vec<String>>,
7804 }
7805
7806 let tabstops = self.buffer.update(cx, |buffer, cx| {
7807 let snippet_text: Arc<str> = snippet.text.clone().into();
7808 let edits = insertion_ranges
7809 .iter()
7810 .cloned()
7811 .map(|range| (range, snippet_text.clone()));
7812 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7813
7814 let snapshot = &*buffer.read(cx);
7815 let snippet = &snippet;
7816 snippet
7817 .tabstops
7818 .iter()
7819 .map(|tabstop| {
7820 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7821 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7822 });
7823 let mut tabstop_ranges = tabstop
7824 .ranges
7825 .iter()
7826 .flat_map(|tabstop_range| {
7827 let mut delta = 0_isize;
7828 insertion_ranges.iter().map(move |insertion_range| {
7829 let insertion_start = insertion_range.start as isize + delta;
7830 delta +=
7831 snippet.text.len() as isize - insertion_range.len() as isize;
7832
7833 let start = ((insertion_start + tabstop_range.start) as usize)
7834 .min(snapshot.len());
7835 let end = ((insertion_start + tabstop_range.end) as usize)
7836 .min(snapshot.len());
7837 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7838 })
7839 })
7840 .collect::<Vec<_>>();
7841 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7842
7843 Tabstop {
7844 is_end_tabstop,
7845 ranges: tabstop_ranges,
7846 choices: tabstop.choices.clone(),
7847 }
7848 })
7849 .collect::<Vec<_>>()
7850 });
7851 if let Some(tabstop) = tabstops.first() {
7852 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7853 s.select_ranges(tabstop.ranges.iter().cloned());
7854 });
7855
7856 if let Some(choices) = &tabstop.choices {
7857 if let Some(selection) = tabstop.ranges.first() {
7858 self.show_snippet_choices(choices, selection.clone(), cx)
7859 }
7860 }
7861
7862 // If we're already at the last tabstop and it's at the end of the snippet,
7863 // we're done, we don't need to keep the state around.
7864 if !tabstop.is_end_tabstop {
7865 let choices = tabstops
7866 .iter()
7867 .map(|tabstop| tabstop.choices.clone())
7868 .collect();
7869
7870 let ranges = tabstops
7871 .into_iter()
7872 .map(|tabstop| tabstop.ranges)
7873 .collect::<Vec<_>>();
7874
7875 self.snippet_stack.push(SnippetState {
7876 active_index: 0,
7877 ranges,
7878 choices,
7879 });
7880 }
7881
7882 // Check whether the just-entered snippet ends with an auto-closable bracket.
7883 if self.autoclose_regions.is_empty() {
7884 let snapshot = self.buffer.read(cx).snapshot(cx);
7885 for selection in &mut self.selections.all::<Point>(cx) {
7886 let selection_head = selection.head();
7887 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7888 continue;
7889 };
7890
7891 let mut bracket_pair = None;
7892 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7893 let prev_chars = snapshot
7894 .reversed_chars_at(selection_head)
7895 .collect::<String>();
7896 for (pair, enabled) in scope.brackets() {
7897 if enabled
7898 && pair.close
7899 && prev_chars.starts_with(pair.start.as_str())
7900 && next_chars.starts_with(pair.end.as_str())
7901 {
7902 bracket_pair = Some(pair.clone());
7903 break;
7904 }
7905 }
7906 if let Some(pair) = bracket_pair {
7907 let start = snapshot.anchor_after(selection_head);
7908 let end = snapshot.anchor_after(selection_head);
7909 self.autoclose_regions.push(AutocloseRegion {
7910 selection_id: selection.id,
7911 range: start..end,
7912 pair,
7913 });
7914 }
7915 }
7916 }
7917 }
7918 Ok(())
7919 }
7920
7921 pub fn move_to_next_snippet_tabstop(
7922 &mut self,
7923 window: &mut Window,
7924 cx: &mut Context<Self>,
7925 ) -> bool {
7926 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7927 }
7928
7929 pub fn move_to_prev_snippet_tabstop(
7930 &mut self,
7931 window: &mut Window,
7932 cx: &mut Context<Self>,
7933 ) -> bool {
7934 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7935 }
7936
7937 pub fn move_to_snippet_tabstop(
7938 &mut self,
7939 bias: Bias,
7940 window: &mut Window,
7941 cx: &mut Context<Self>,
7942 ) -> bool {
7943 if let Some(mut snippet) = self.snippet_stack.pop() {
7944 match bias {
7945 Bias::Left => {
7946 if snippet.active_index > 0 {
7947 snippet.active_index -= 1;
7948 } else {
7949 self.snippet_stack.push(snippet);
7950 return false;
7951 }
7952 }
7953 Bias::Right => {
7954 if snippet.active_index + 1 < snippet.ranges.len() {
7955 snippet.active_index += 1;
7956 } else {
7957 self.snippet_stack.push(snippet);
7958 return false;
7959 }
7960 }
7961 }
7962 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7963 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7964 s.select_anchor_ranges(current_ranges.iter().cloned())
7965 });
7966
7967 if let Some(choices) = &snippet.choices[snippet.active_index] {
7968 if let Some(selection) = current_ranges.first() {
7969 self.show_snippet_choices(&choices, selection.clone(), cx);
7970 }
7971 }
7972
7973 // If snippet state is not at the last tabstop, push it back on the stack
7974 if snippet.active_index + 1 < snippet.ranges.len() {
7975 self.snippet_stack.push(snippet);
7976 }
7977 return true;
7978 }
7979 }
7980
7981 false
7982 }
7983
7984 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7985 self.transact(window, cx, |this, window, cx| {
7986 this.select_all(&SelectAll, window, cx);
7987 this.insert("", window, cx);
7988 });
7989 }
7990
7991 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7992 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
7993 self.transact(window, cx, |this, window, cx| {
7994 this.select_autoclose_pair(window, cx);
7995 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7996 if !this.linked_edit_ranges.is_empty() {
7997 let selections = this.selections.all::<MultiBufferPoint>(cx);
7998 let snapshot = this.buffer.read(cx).snapshot(cx);
7999
8000 for selection in selections.iter() {
8001 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8002 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8003 if selection_start.buffer_id != selection_end.buffer_id {
8004 continue;
8005 }
8006 if let Some(ranges) =
8007 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8008 {
8009 for (buffer, entries) in ranges {
8010 linked_ranges.entry(buffer).or_default().extend(entries);
8011 }
8012 }
8013 }
8014 }
8015
8016 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8017 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8018 for selection in &mut selections {
8019 if selection.is_empty() {
8020 let old_head = selection.head();
8021 let mut new_head =
8022 movement::left(&display_map, old_head.to_display_point(&display_map))
8023 .to_point(&display_map);
8024 if let Some((buffer, line_buffer_range)) = display_map
8025 .buffer_snapshot
8026 .buffer_line_for_row(MultiBufferRow(old_head.row))
8027 {
8028 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8029 let indent_len = match indent_size.kind {
8030 IndentKind::Space => {
8031 buffer.settings_at(line_buffer_range.start, cx).tab_size
8032 }
8033 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8034 };
8035 if old_head.column <= indent_size.len && old_head.column > 0 {
8036 let indent_len = indent_len.get();
8037 new_head = cmp::min(
8038 new_head,
8039 MultiBufferPoint::new(
8040 old_head.row,
8041 ((old_head.column - 1) / indent_len) * indent_len,
8042 ),
8043 );
8044 }
8045 }
8046
8047 selection.set_head(new_head, SelectionGoal::None);
8048 }
8049 }
8050
8051 this.signature_help_state.set_backspace_pressed(true);
8052 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8053 s.select(selections)
8054 });
8055 this.insert("", window, cx);
8056 let empty_str: Arc<str> = Arc::from("");
8057 for (buffer, edits) in linked_ranges {
8058 let snapshot = buffer.read(cx).snapshot();
8059 use text::ToPoint as TP;
8060
8061 let edits = edits
8062 .into_iter()
8063 .map(|range| {
8064 let end_point = TP::to_point(&range.end, &snapshot);
8065 let mut start_point = TP::to_point(&range.start, &snapshot);
8066
8067 if end_point == start_point {
8068 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8069 .saturating_sub(1);
8070 start_point =
8071 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8072 };
8073
8074 (start_point..end_point, empty_str.clone())
8075 })
8076 .sorted_by_key(|(range, _)| range.start)
8077 .collect::<Vec<_>>();
8078 buffer.update(cx, |this, cx| {
8079 this.edit(edits, None, cx);
8080 })
8081 }
8082 this.refresh_inline_completion(true, false, window, cx);
8083 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8084 });
8085 }
8086
8087 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8088 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8089 self.transact(window, cx, |this, window, cx| {
8090 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8091 s.move_with(|map, selection| {
8092 if selection.is_empty() {
8093 let cursor = movement::right(map, selection.head());
8094 selection.end = cursor;
8095 selection.reversed = true;
8096 selection.goal = SelectionGoal::None;
8097 }
8098 })
8099 });
8100 this.insert("", window, cx);
8101 this.refresh_inline_completion(true, false, window, cx);
8102 });
8103 }
8104
8105 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8106 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8107 if self.move_to_prev_snippet_tabstop(window, cx) {
8108 return;
8109 }
8110 self.outdent(&Outdent, window, cx);
8111 }
8112
8113 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8114 if self.move_to_next_snippet_tabstop(window, cx) {
8115 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8116 return;
8117 }
8118 if self.read_only(cx) {
8119 return;
8120 }
8121 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8122 let mut selections = self.selections.all_adjusted(cx);
8123 let buffer = self.buffer.read(cx);
8124 let snapshot = buffer.snapshot(cx);
8125 let rows_iter = selections.iter().map(|s| s.head().row);
8126 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8127
8128 let mut edits = Vec::new();
8129 let mut prev_edited_row = 0;
8130 let mut row_delta = 0;
8131 for selection in &mut selections {
8132 if selection.start.row != prev_edited_row {
8133 row_delta = 0;
8134 }
8135 prev_edited_row = selection.end.row;
8136
8137 // If the selection is non-empty, then increase the indentation of the selected lines.
8138 if !selection.is_empty() {
8139 row_delta =
8140 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8141 continue;
8142 }
8143
8144 // If the selection is empty and the cursor is in the leading whitespace before the
8145 // suggested indentation, then auto-indent the line.
8146 let cursor = selection.head();
8147 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8148 if let Some(suggested_indent) =
8149 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8150 {
8151 if cursor.column < suggested_indent.len
8152 && cursor.column <= current_indent.len
8153 && current_indent.len <= suggested_indent.len
8154 {
8155 selection.start = Point::new(cursor.row, suggested_indent.len);
8156 selection.end = selection.start;
8157 if row_delta == 0 {
8158 edits.extend(Buffer::edit_for_indent_size_adjustment(
8159 cursor.row,
8160 current_indent,
8161 suggested_indent,
8162 ));
8163 row_delta = suggested_indent.len - current_indent.len;
8164 }
8165 continue;
8166 }
8167 }
8168
8169 // Otherwise, insert a hard or soft tab.
8170 let settings = buffer.language_settings_at(cursor, cx);
8171 let tab_size = if settings.hard_tabs {
8172 IndentSize::tab()
8173 } else {
8174 let tab_size = settings.tab_size.get();
8175 let char_column = snapshot
8176 .text_for_range(Point::new(cursor.row, 0)..cursor)
8177 .flat_map(str::chars)
8178 .count()
8179 + row_delta as usize;
8180 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
8181 IndentSize::spaces(chars_to_next_tab_stop)
8182 };
8183 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8184 selection.end = selection.start;
8185 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8186 row_delta += tab_size.len;
8187 }
8188
8189 self.transact(window, cx, |this, window, cx| {
8190 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8191 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8192 s.select(selections)
8193 });
8194 this.refresh_inline_completion(true, false, window, cx);
8195 });
8196 }
8197
8198 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8199 if self.read_only(cx) {
8200 return;
8201 }
8202 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8203 let mut selections = self.selections.all::<Point>(cx);
8204 let mut prev_edited_row = 0;
8205 let mut row_delta = 0;
8206 let mut edits = Vec::new();
8207 let buffer = self.buffer.read(cx);
8208 let snapshot = buffer.snapshot(cx);
8209 for selection in &mut selections {
8210 if selection.start.row != prev_edited_row {
8211 row_delta = 0;
8212 }
8213 prev_edited_row = selection.end.row;
8214
8215 row_delta =
8216 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8217 }
8218
8219 self.transact(window, cx, |this, window, cx| {
8220 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8221 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8222 s.select(selections)
8223 });
8224 });
8225 }
8226
8227 fn indent_selection(
8228 buffer: &MultiBuffer,
8229 snapshot: &MultiBufferSnapshot,
8230 selection: &mut Selection<Point>,
8231 edits: &mut Vec<(Range<Point>, String)>,
8232 delta_for_start_row: u32,
8233 cx: &App,
8234 ) -> u32 {
8235 let settings = buffer.language_settings_at(selection.start, cx);
8236 let tab_size = settings.tab_size.get();
8237 let indent_kind = if settings.hard_tabs {
8238 IndentKind::Tab
8239 } else {
8240 IndentKind::Space
8241 };
8242 let mut start_row = selection.start.row;
8243 let mut end_row = selection.end.row + 1;
8244
8245 // If a selection ends at the beginning of a line, don't indent
8246 // that last line.
8247 if selection.end.column == 0 && selection.end.row > selection.start.row {
8248 end_row -= 1;
8249 }
8250
8251 // Avoid re-indenting a row that has already been indented by a
8252 // previous selection, but still update this selection's column
8253 // to reflect that indentation.
8254 if delta_for_start_row > 0 {
8255 start_row += 1;
8256 selection.start.column += delta_for_start_row;
8257 if selection.end.row == selection.start.row {
8258 selection.end.column += delta_for_start_row;
8259 }
8260 }
8261
8262 let mut delta_for_end_row = 0;
8263 let has_multiple_rows = start_row + 1 != end_row;
8264 for row in start_row..end_row {
8265 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8266 let indent_delta = match (current_indent.kind, indent_kind) {
8267 (IndentKind::Space, IndentKind::Space) => {
8268 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8269 IndentSize::spaces(columns_to_next_tab_stop)
8270 }
8271 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8272 (_, IndentKind::Tab) => IndentSize::tab(),
8273 };
8274
8275 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8276 0
8277 } else {
8278 selection.start.column
8279 };
8280 let row_start = Point::new(row, start);
8281 edits.push((
8282 row_start..row_start,
8283 indent_delta.chars().collect::<String>(),
8284 ));
8285
8286 // Update this selection's endpoints to reflect the indentation.
8287 if row == selection.start.row {
8288 selection.start.column += indent_delta.len;
8289 }
8290 if row == selection.end.row {
8291 selection.end.column += indent_delta.len;
8292 delta_for_end_row = indent_delta.len;
8293 }
8294 }
8295
8296 if selection.start.row == selection.end.row {
8297 delta_for_start_row + delta_for_end_row
8298 } else {
8299 delta_for_end_row
8300 }
8301 }
8302
8303 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8304 if self.read_only(cx) {
8305 return;
8306 }
8307 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8308 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8309 let selections = self.selections.all::<Point>(cx);
8310 let mut deletion_ranges = Vec::new();
8311 let mut last_outdent = None;
8312 {
8313 let buffer = self.buffer.read(cx);
8314 let snapshot = buffer.snapshot(cx);
8315 for selection in &selections {
8316 let settings = buffer.language_settings_at(selection.start, cx);
8317 let tab_size = settings.tab_size.get();
8318 let mut rows = selection.spanned_rows(false, &display_map);
8319
8320 // Avoid re-outdenting a row that has already been outdented by a
8321 // previous selection.
8322 if let Some(last_row) = last_outdent {
8323 if last_row == rows.start {
8324 rows.start = rows.start.next_row();
8325 }
8326 }
8327 let has_multiple_rows = rows.len() > 1;
8328 for row in rows.iter_rows() {
8329 let indent_size = snapshot.indent_size_for_line(row);
8330 if indent_size.len > 0 {
8331 let deletion_len = match indent_size.kind {
8332 IndentKind::Space => {
8333 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8334 if columns_to_prev_tab_stop == 0 {
8335 tab_size
8336 } else {
8337 columns_to_prev_tab_stop
8338 }
8339 }
8340 IndentKind::Tab => 1,
8341 };
8342 let start = if has_multiple_rows
8343 || deletion_len > selection.start.column
8344 || indent_size.len < selection.start.column
8345 {
8346 0
8347 } else {
8348 selection.start.column - deletion_len
8349 };
8350 deletion_ranges.push(
8351 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8352 );
8353 last_outdent = Some(row);
8354 }
8355 }
8356 }
8357 }
8358
8359 self.transact(window, cx, |this, window, cx| {
8360 this.buffer.update(cx, |buffer, cx| {
8361 let empty_str: Arc<str> = Arc::default();
8362 buffer.edit(
8363 deletion_ranges
8364 .into_iter()
8365 .map(|range| (range, empty_str.clone())),
8366 None,
8367 cx,
8368 );
8369 });
8370 let selections = this.selections.all::<usize>(cx);
8371 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8372 s.select(selections)
8373 });
8374 });
8375 }
8376
8377 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8378 if self.read_only(cx) {
8379 return;
8380 }
8381 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8382 let selections = self
8383 .selections
8384 .all::<usize>(cx)
8385 .into_iter()
8386 .map(|s| s.range());
8387
8388 self.transact(window, cx, |this, window, cx| {
8389 this.buffer.update(cx, |buffer, cx| {
8390 buffer.autoindent_ranges(selections, cx);
8391 });
8392 let selections = this.selections.all::<usize>(cx);
8393 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8394 s.select(selections)
8395 });
8396 });
8397 }
8398
8399 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8400 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8401 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8402 let selections = self.selections.all::<Point>(cx);
8403
8404 let mut new_cursors = Vec::new();
8405 let mut edit_ranges = Vec::new();
8406 let mut selections = selections.iter().peekable();
8407 while let Some(selection) = selections.next() {
8408 let mut rows = selection.spanned_rows(false, &display_map);
8409 let goal_display_column = selection.head().to_display_point(&display_map).column();
8410
8411 // Accumulate contiguous regions of rows that we want to delete.
8412 while let Some(next_selection) = selections.peek() {
8413 let next_rows = next_selection.spanned_rows(false, &display_map);
8414 if next_rows.start <= rows.end {
8415 rows.end = next_rows.end;
8416 selections.next().unwrap();
8417 } else {
8418 break;
8419 }
8420 }
8421
8422 let buffer = &display_map.buffer_snapshot;
8423 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8424 let edit_end;
8425 let cursor_buffer_row;
8426 if buffer.max_point().row >= rows.end.0 {
8427 // If there's a line after the range, delete the \n from the end of the row range
8428 // and position the cursor on the next line.
8429 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8430 cursor_buffer_row = rows.end;
8431 } else {
8432 // If there isn't a line after the range, delete the \n from the line before the
8433 // start of the row range and position the cursor there.
8434 edit_start = edit_start.saturating_sub(1);
8435 edit_end = buffer.len();
8436 cursor_buffer_row = rows.start.previous_row();
8437 }
8438
8439 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8440 *cursor.column_mut() =
8441 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8442
8443 new_cursors.push((
8444 selection.id,
8445 buffer.anchor_after(cursor.to_point(&display_map)),
8446 ));
8447 edit_ranges.push(edit_start..edit_end);
8448 }
8449
8450 self.transact(window, cx, |this, window, cx| {
8451 let buffer = this.buffer.update(cx, |buffer, cx| {
8452 let empty_str: Arc<str> = Arc::default();
8453 buffer.edit(
8454 edit_ranges
8455 .into_iter()
8456 .map(|range| (range, empty_str.clone())),
8457 None,
8458 cx,
8459 );
8460 buffer.snapshot(cx)
8461 });
8462 let new_selections = new_cursors
8463 .into_iter()
8464 .map(|(id, cursor)| {
8465 let cursor = cursor.to_point(&buffer);
8466 Selection {
8467 id,
8468 start: cursor,
8469 end: cursor,
8470 reversed: false,
8471 goal: SelectionGoal::None,
8472 }
8473 })
8474 .collect();
8475
8476 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8477 s.select(new_selections);
8478 });
8479 });
8480 }
8481
8482 pub fn join_lines_impl(
8483 &mut self,
8484 insert_whitespace: bool,
8485 window: &mut Window,
8486 cx: &mut Context<Self>,
8487 ) {
8488 if self.read_only(cx) {
8489 return;
8490 }
8491 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8492 for selection in self.selections.all::<Point>(cx) {
8493 let start = MultiBufferRow(selection.start.row);
8494 // Treat single line selections as if they include the next line. Otherwise this action
8495 // would do nothing for single line selections individual cursors.
8496 let end = if selection.start.row == selection.end.row {
8497 MultiBufferRow(selection.start.row + 1)
8498 } else {
8499 MultiBufferRow(selection.end.row)
8500 };
8501
8502 if let Some(last_row_range) = row_ranges.last_mut() {
8503 if start <= last_row_range.end {
8504 last_row_range.end = end;
8505 continue;
8506 }
8507 }
8508 row_ranges.push(start..end);
8509 }
8510
8511 let snapshot = self.buffer.read(cx).snapshot(cx);
8512 let mut cursor_positions = Vec::new();
8513 for row_range in &row_ranges {
8514 let anchor = snapshot.anchor_before(Point::new(
8515 row_range.end.previous_row().0,
8516 snapshot.line_len(row_range.end.previous_row()),
8517 ));
8518 cursor_positions.push(anchor..anchor);
8519 }
8520
8521 self.transact(window, cx, |this, window, cx| {
8522 for row_range in row_ranges.into_iter().rev() {
8523 for row in row_range.iter_rows().rev() {
8524 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8525 let next_line_row = row.next_row();
8526 let indent = snapshot.indent_size_for_line(next_line_row);
8527 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8528
8529 let replace =
8530 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8531 " "
8532 } else {
8533 ""
8534 };
8535
8536 this.buffer.update(cx, |buffer, cx| {
8537 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8538 });
8539 }
8540 }
8541
8542 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8543 s.select_anchor_ranges(cursor_positions)
8544 });
8545 });
8546 }
8547
8548 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8549 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8550 self.join_lines_impl(true, window, cx);
8551 }
8552
8553 pub fn sort_lines_case_sensitive(
8554 &mut self,
8555 _: &SortLinesCaseSensitive,
8556 window: &mut Window,
8557 cx: &mut Context<Self>,
8558 ) {
8559 self.manipulate_lines(window, cx, |lines| lines.sort())
8560 }
8561
8562 pub fn sort_lines_case_insensitive(
8563 &mut self,
8564 _: &SortLinesCaseInsensitive,
8565 window: &mut Window,
8566 cx: &mut Context<Self>,
8567 ) {
8568 self.manipulate_lines(window, cx, |lines| {
8569 lines.sort_by_key(|line| line.to_lowercase())
8570 })
8571 }
8572
8573 pub fn unique_lines_case_insensitive(
8574 &mut self,
8575 _: &UniqueLinesCaseInsensitive,
8576 window: &mut Window,
8577 cx: &mut Context<Self>,
8578 ) {
8579 self.manipulate_lines(window, cx, |lines| {
8580 let mut seen = HashSet::default();
8581 lines.retain(|line| seen.insert(line.to_lowercase()));
8582 })
8583 }
8584
8585 pub fn unique_lines_case_sensitive(
8586 &mut self,
8587 _: &UniqueLinesCaseSensitive,
8588 window: &mut Window,
8589 cx: &mut Context<Self>,
8590 ) {
8591 self.manipulate_lines(window, cx, |lines| {
8592 let mut seen = HashSet::default();
8593 lines.retain(|line| seen.insert(*line));
8594 })
8595 }
8596
8597 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8598 let Some(project) = self.project.clone() else {
8599 return;
8600 };
8601 self.reload(project, window, cx)
8602 .detach_and_notify_err(window, cx);
8603 }
8604
8605 pub fn restore_file(
8606 &mut self,
8607 _: &::git::RestoreFile,
8608 window: &mut Window,
8609 cx: &mut Context<Self>,
8610 ) {
8611 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8612 let mut buffer_ids = HashSet::default();
8613 let snapshot = self.buffer().read(cx).snapshot(cx);
8614 for selection in self.selections.all::<usize>(cx) {
8615 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8616 }
8617
8618 let buffer = self.buffer().read(cx);
8619 let ranges = buffer_ids
8620 .into_iter()
8621 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8622 .collect::<Vec<_>>();
8623
8624 self.restore_hunks_in_ranges(ranges, window, cx);
8625 }
8626
8627 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8628 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8629 let selections = self
8630 .selections
8631 .all(cx)
8632 .into_iter()
8633 .map(|s| s.range())
8634 .collect();
8635 self.restore_hunks_in_ranges(selections, window, cx);
8636 }
8637
8638 pub fn restore_hunks_in_ranges(
8639 &mut self,
8640 ranges: Vec<Range<Point>>,
8641 window: &mut Window,
8642 cx: &mut Context<Editor>,
8643 ) {
8644 let mut revert_changes = HashMap::default();
8645 let chunk_by = self
8646 .snapshot(window, cx)
8647 .hunks_for_ranges(ranges)
8648 .into_iter()
8649 .chunk_by(|hunk| hunk.buffer_id);
8650 for (buffer_id, hunks) in &chunk_by {
8651 let hunks = hunks.collect::<Vec<_>>();
8652 for hunk in &hunks {
8653 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8654 }
8655 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8656 }
8657 drop(chunk_by);
8658 if !revert_changes.is_empty() {
8659 self.transact(window, cx, |editor, window, cx| {
8660 editor.restore(revert_changes, window, cx);
8661 });
8662 }
8663 }
8664
8665 pub fn open_active_item_in_terminal(
8666 &mut self,
8667 _: &OpenInTerminal,
8668 window: &mut Window,
8669 cx: &mut Context<Self>,
8670 ) {
8671 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8672 let project_path = buffer.read(cx).project_path(cx)?;
8673 let project = self.project.as_ref()?.read(cx);
8674 let entry = project.entry_for_path(&project_path, cx)?;
8675 let parent = match &entry.canonical_path {
8676 Some(canonical_path) => canonical_path.to_path_buf(),
8677 None => project.absolute_path(&project_path, cx)?,
8678 }
8679 .parent()?
8680 .to_path_buf();
8681 Some(parent)
8682 }) {
8683 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8684 }
8685 }
8686
8687 fn set_breakpoint_context_menu(
8688 &mut self,
8689 display_row: DisplayRow,
8690 position: Option<Anchor>,
8691 clicked_point: gpui::Point<Pixels>,
8692 window: &mut Window,
8693 cx: &mut Context<Self>,
8694 ) {
8695 if !cx.has_flag::<Debugger>() {
8696 return;
8697 }
8698 let source = self
8699 .buffer
8700 .read(cx)
8701 .snapshot(cx)
8702 .anchor_before(Point::new(display_row.0, 0u32));
8703
8704 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8705
8706 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8707 self,
8708 source,
8709 clicked_point,
8710 context_menu,
8711 window,
8712 cx,
8713 );
8714 }
8715
8716 fn add_edit_breakpoint_block(
8717 &mut self,
8718 anchor: Anchor,
8719 breakpoint: &Breakpoint,
8720 edit_action: BreakpointPromptEditAction,
8721 window: &mut Window,
8722 cx: &mut Context<Self>,
8723 ) {
8724 let weak_editor = cx.weak_entity();
8725 let bp_prompt = cx.new(|cx| {
8726 BreakpointPromptEditor::new(
8727 weak_editor,
8728 anchor,
8729 breakpoint.clone(),
8730 edit_action,
8731 window,
8732 cx,
8733 )
8734 });
8735
8736 let height = bp_prompt.update(cx, |this, cx| {
8737 this.prompt
8738 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8739 });
8740 let cloned_prompt = bp_prompt.clone();
8741 let blocks = vec![BlockProperties {
8742 style: BlockStyle::Sticky,
8743 placement: BlockPlacement::Above(anchor),
8744 height: Some(height),
8745 render: Arc::new(move |cx| {
8746 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8747 cloned_prompt.clone().into_any_element()
8748 }),
8749 priority: 0,
8750 }];
8751
8752 let focus_handle = bp_prompt.focus_handle(cx);
8753 window.focus(&focus_handle);
8754
8755 let block_ids = self.insert_blocks(blocks, None, cx);
8756 bp_prompt.update(cx, |prompt, _| {
8757 prompt.add_block_ids(block_ids);
8758 });
8759 }
8760
8761 fn breakpoint_at_cursor_head(
8762 &self,
8763 window: &mut Window,
8764 cx: &mut Context<Self>,
8765 ) -> Option<(Anchor, Breakpoint)> {
8766 let cursor_position: Point = self.selections.newest(cx).head();
8767 self.breakpoint_at_row(cursor_position.row, window, cx)
8768 }
8769
8770 pub(crate) fn breakpoint_at_row(
8771 &self,
8772 row: u32,
8773 window: &mut Window,
8774 cx: &mut Context<Self>,
8775 ) -> Option<(Anchor, Breakpoint)> {
8776 let snapshot = self.snapshot(window, cx);
8777 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8778
8779 let project = self.project.clone()?;
8780
8781 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8782 snapshot
8783 .buffer_snapshot
8784 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8785 })?;
8786
8787 let enclosing_excerpt = breakpoint_position.excerpt_id;
8788 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8789 let buffer_snapshot = buffer.read(cx).snapshot();
8790
8791 let row = buffer_snapshot
8792 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8793 .row;
8794
8795 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8796 let anchor_end = snapshot
8797 .buffer_snapshot
8798 .anchor_after(Point::new(row, line_len));
8799
8800 let bp = self
8801 .breakpoint_store
8802 .as_ref()?
8803 .read_with(cx, |breakpoint_store, cx| {
8804 breakpoint_store
8805 .breakpoints(
8806 &buffer,
8807 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8808 &buffer_snapshot,
8809 cx,
8810 )
8811 .next()
8812 .and_then(|(anchor, bp)| {
8813 let breakpoint_row = buffer_snapshot
8814 .summary_for_anchor::<text::PointUtf16>(anchor)
8815 .row;
8816
8817 if breakpoint_row == row {
8818 snapshot
8819 .buffer_snapshot
8820 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8821 .map(|anchor| (anchor, bp.clone()))
8822 } else {
8823 None
8824 }
8825 })
8826 });
8827 bp
8828 }
8829
8830 pub fn edit_log_breakpoint(
8831 &mut self,
8832 _: &EditLogBreakpoint,
8833 window: &mut Window,
8834 cx: &mut Context<Self>,
8835 ) {
8836 let (anchor, bp) = self
8837 .breakpoint_at_cursor_head(window, cx)
8838 .unwrap_or_else(|| {
8839 let cursor_position: Point = self.selections.newest(cx).head();
8840
8841 let breakpoint_position = self
8842 .snapshot(window, cx)
8843 .display_snapshot
8844 .buffer_snapshot
8845 .anchor_after(Point::new(cursor_position.row, 0));
8846
8847 (
8848 breakpoint_position,
8849 Breakpoint {
8850 message: None,
8851 state: BreakpointState::Enabled,
8852 condition: None,
8853 hit_condition: None,
8854 },
8855 )
8856 });
8857
8858 self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
8859 }
8860
8861 pub fn enable_breakpoint(
8862 &mut self,
8863 _: &crate::actions::EnableBreakpoint,
8864 window: &mut Window,
8865 cx: &mut Context<Self>,
8866 ) {
8867 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8868 if breakpoint.is_disabled() {
8869 self.edit_breakpoint_at_anchor(
8870 anchor,
8871 breakpoint,
8872 BreakpointEditAction::InvertState,
8873 cx,
8874 );
8875 }
8876 }
8877 }
8878
8879 pub fn disable_breakpoint(
8880 &mut self,
8881 _: &crate::actions::DisableBreakpoint,
8882 window: &mut Window,
8883 cx: &mut Context<Self>,
8884 ) {
8885 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8886 if breakpoint.is_enabled() {
8887 self.edit_breakpoint_at_anchor(
8888 anchor,
8889 breakpoint,
8890 BreakpointEditAction::InvertState,
8891 cx,
8892 );
8893 }
8894 }
8895 }
8896
8897 pub fn toggle_breakpoint(
8898 &mut self,
8899 _: &crate::actions::ToggleBreakpoint,
8900 window: &mut Window,
8901 cx: &mut Context<Self>,
8902 ) {
8903 let edit_action = BreakpointEditAction::Toggle;
8904
8905 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8906 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8907 } else {
8908 let cursor_position: Point = self.selections.newest(cx).head();
8909
8910 let breakpoint_position = self
8911 .snapshot(window, cx)
8912 .display_snapshot
8913 .buffer_snapshot
8914 .anchor_after(Point::new(cursor_position.row, 0));
8915
8916 self.edit_breakpoint_at_anchor(
8917 breakpoint_position,
8918 Breakpoint::new_standard(),
8919 edit_action,
8920 cx,
8921 );
8922 }
8923 }
8924
8925 pub fn edit_breakpoint_at_anchor(
8926 &mut self,
8927 breakpoint_position: Anchor,
8928 breakpoint: Breakpoint,
8929 edit_action: BreakpointEditAction,
8930 cx: &mut Context<Self>,
8931 ) {
8932 let Some(breakpoint_store) = &self.breakpoint_store else {
8933 return;
8934 };
8935
8936 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8937 if breakpoint_position == Anchor::min() {
8938 self.buffer()
8939 .read(cx)
8940 .excerpt_buffer_ids()
8941 .into_iter()
8942 .next()
8943 } else {
8944 None
8945 }
8946 }) else {
8947 return;
8948 };
8949
8950 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8951 return;
8952 };
8953
8954 breakpoint_store.update(cx, |breakpoint_store, cx| {
8955 breakpoint_store.toggle_breakpoint(
8956 buffer,
8957 (breakpoint_position.text_anchor, breakpoint),
8958 edit_action,
8959 cx,
8960 );
8961 });
8962
8963 cx.notify();
8964 }
8965
8966 #[cfg(any(test, feature = "test-support"))]
8967 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8968 self.breakpoint_store.clone()
8969 }
8970
8971 pub fn prepare_restore_change(
8972 &self,
8973 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8974 hunk: &MultiBufferDiffHunk,
8975 cx: &mut App,
8976 ) -> Option<()> {
8977 if hunk.is_created_file() {
8978 return None;
8979 }
8980 let buffer = self.buffer.read(cx);
8981 let diff = buffer.diff_for(hunk.buffer_id)?;
8982 let buffer = buffer.buffer(hunk.buffer_id)?;
8983 let buffer = buffer.read(cx);
8984 let original_text = diff
8985 .read(cx)
8986 .base_text()
8987 .as_rope()
8988 .slice(hunk.diff_base_byte_range.clone());
8989 let buffer_snapshot = buffer.snapshot();
8990 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8991 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8992 probe
8993 .0
8994 .start
8995 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8996 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8997 }) {
8998 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8999 Some(())
9000 } else {
9001 None
9002 }
9003 }
9004
9005 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9006 self.manipulate_lines(window, cx, |lines| lines.reverse())
9007 }
9008
9009 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9010 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9011 }
9012
9013 fn manipulate_lines<Fn>(
9014 &mut self,
9015 window: &mut Window,
9016 cx: &mut Context<Self>,
9017 mut callback: Fn,
9018 ) where
9019 Fn: FnMut(&mut Vec<&str>),
9020 {
9021 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9022
9023 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9024 let buffer = self.buffer.read(cx).snapshot(cx);
9025
9026 let mut edits = Vec::new();
9027
9028 let selections = self.selections.all::<Point>(cx);
9029 let mut selections = selections.iter().peekable();
9030 let mut contiguous_row_selections = Vec::new();
9031 let mut new_selections = Vec::new();
9032 let mut added_lines = 0;
9033 let mut removed_lines = 0;
9034
9035 while let Some(selection) = selections.next() {
9036 let (start_row, end_row) = consume_contiguous_rows(
9037 &mut contiguous_row_selections,
9038 selection,
9039 &display_map,
9040 &mut selections,
9041 );
9042
9043 let start_point = Point::new(start_row.0, 0);
9044 let end_point = Point::new(
9045 end_row.previous_row().0,
9046 buffer.line_len(end_row.previous_row()),
9047 );
9048 let text = buffer
9049 .text_for_range(start_point..end_point)
9050 .collect::<String>();
9051
9052 let mut lines = text.split('\n').collect_vec();
9053
9054 let lines_before = lines.len();
9055 callback(&mut lines);
9056 let lines_after = lines.len();
9057
9058 edits.push((start_point..end_point, lines.join("\n")));
9059
9060 // Selections must change based on added and removed line count
9061 let start_row =
9062 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9063 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9064 new_selections.push(Selection {
9065 id: selection.id,
9066 start: start_row,
9067 end: end_row,
9068 goal: SelectionGoal::None,
9069 reversed: selection.reversed,
9070 });
9071
9072 if lines_after > lines_before {
9073 added_lines += lines_after - lines_before;
9074 } else if lines_before > lines_after {
9075 removed_lines += lines_before - lines_after;
9076 }
9077 }
9078
9079 self.transact(window, cx, |this, window, cx| {
9080 let buffer = this.buffer.update(cx, |buffer, cx| {
9081 buffer.edit(edits, None, cx);
9082 buffer.snapshot(cx)
9083 });
9084
9085 // Recalculate offsets on newly edited buffer
9086 let new_selections = new_selections
9087 .iter()
9088 .map(|s| {
9089 let start_point = Point::new(s.start.0, 0);
9090 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9091 Selection {
9092 id: s.id,
9093 start: buffer.point_to_offset(start_point),
9094 end: buffer.point_to_offset(end_point),
9095 goal: s.goal,
9096 reversed: s.reversed,
9097 }
9098 })
9099 .collect();
9100
9101 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9102 s.select(new_selections);
9103 });
9104
9105 this.request_autoscroll(Autoscroll::fit(), cx);
9106 });
9107 }
9108
9109 pub fn convert_to_upper_case(
9110 &mut self,
9111 _: &ConvertToUpperCase,
9112 window: &mut Window,
9113 cx: &mut Context<Self>,
9114 ) {
9115 self.manipulate_text(window, cx, |text| text.to_uppercase())
9116 }
9117
9118 pub fn convert_to_lower_case(
9119 &mut self,
9120 _: &ConvertToLowerCase,
9121 window: &mut Window,
9122 cx: &mut Context<Self>,
9123 ) {
9124 self.manipulate_text(window, cx, |text| text.to_lowercase())
9125 }
9126
9127 pub fn convert_to_title_case(
9128 &mut self,
9129 _: &ConvertToTitleCase,
9130 window: &mut Window,
9131 cx: &mut Context<Self>,
9132 ) {
9133 self.manipulate_text(window, cx, |text| {
9134 text.split('\n')
9135 .map(|line| line.to_case(Case::Title))
9136 .join("\n")
9137 })
9138 }
9139
9140 pub fn convert_to_snake_case(
9141 &mut self,
9142 _: &ConvertToSnakeCase,
9143 window: &mut Window,
9144 cx: &mut Context<Self>,
9145 ) {
9146 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9147 }
9148
9149 pub fn convert_to_kebab_case(
9150 &mut self,
9151 _: &ConvertToKebabCase,
9152 window: &mut Window,
9153 cx: &mut Context<Self>,
9154 ) {
9155 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9156 }
9157
9158 pub fn convert_to_upper_camel_case(
9159 &mut self,
9160 _: &ConvertToUpperCamelCase,
9161 window: &mut Window,
9162 cx: &mut Context<Self>,
9163 ) {
9164 self.manipulate_text(window, cx, |text| {
9165 text.split('\n')
9166 .map(|line| line.to_case(Case::UpperCamel))
9167 .join("\n")
9168 })
9169 }
9170
9171 pub fn convert_to_lower_camel_case(
9172 &mut self,
9173 _: &ConvertToLowerCamelCase,
9174 window: &mut Window,
9175 cx: &mut Context<Self>,
9176 ) {
9177 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9178 }
9179
9180 pub fn convert_to_opposite_case(
9181 &mut self,
9182 _: &ConvertToOppositeCase,
9183 window: &mut Window,
9184 cx: &mut Context<Self>,
9185 ) {
9186 self.manipulate_text(window, cx, |text| {
9187 text.chars()
9188 .fold(String::with_capacity(text.len()), |mut t, c| {
9189 if c.is_uppercase() {
9190 t.extend(c.to_lowercase());
9191 } else {
9192 t.extend(c.to_uppercase());
9193 }
9194 t
9195 })
9196 })
9197 }
9198
9199 pub fn convert_to_rot13(
9200 &mut self,
9201 _: &ConvertToRot13,
9202 window: &mut Window,
9203 cx: &mut Context<Self>,
9204 ) {
9205 self.manipulate_text(window, cx, |text| {
9206 text.chars()
9207 .map(|c| match c {
9208 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9209 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9210 _ => c,
9211 })
9212 .collect()
9213 })
9214 }
9215
9216 pub fn convert_to_rot47(
9217 &mut self,
9218 _: &ConvertToRot47,
9219 window: &mut Window,
9220 cx: &mut Context<Self>,
9221 ) {
9222 self.manipulate_text(window, cx, |text| {
9223 text.chars()
9224 .map(|c| {
9225 let code_point = c as u32;
9226 if code_point >= 33 && code_point <= 126 {
9227 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9228 }
9229 c
9230 })
9231 .collect()
9232 })
9233 }
9234
9235 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9236 where
9237 Fn: FnMut(&str) -> String,
9238 {
9239 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9240 let buffer = self.buffer.read(cx).snapshot(cx);
9241
9242 let mut new_selections = Vec::new();
9243 let mut edits = Vec::new();
9244 let mut selection_adjustment = 0i32;
9245
9246 for selection in self.selections.all::<usize>(cx) {
9247 let selection_is_empty = selection.is_empty();
9248
9249 let (start, end) = if selection_is_empty {
9250 let word_range = movement::surrounding_word(
9251 &display_map,
9252 selection.start.to_display_point(&display_map),
9253 );
9254 let start = word_range.start.to_offset(&display_map, Bias::Left);
9255 let end = word_range.end.to_offset(&display_map, Bias::Left);
9256 (start, end)
9257 } else {
9258 (selection.start, selection.end)
9259 };
9260
9261 let text = buffer.text_for_range(start..end).collect::<String>();
9262 let old_length = text.len() as i32;
9263 let text = callback(&text);
9264
9265 new_selections.push(Selection {
9266 start: (start as i32 - selection_adjustment) as usize,
9267 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9268 goal: SelectionGoal::None,
9269 ..selection
9270 });
9271
9272 selection_adjustment += old_length - text.len() as i32;
9273
9274 edits.push((start..end, text));
9275 }
9276
9277 self.transact(window, cx, |this, window, cx| {
9278 this.buffer.update(cx, |buffer, cx| {
9279 buffer.edit(edits, None, cx);
9280 });
9281
9282 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9283 s.select(new_selections);
9284 });
9285
9286 this.request_autoscroll(Autoscroll::fit(), cx);
9287 });
9288 }
9289
9290 pub fn duplicate(
9291 &mut self,
9292 upwards: bool,
9293 whole_lines: bool,
9294 window: &mut Window,
9295 cx: &mut Context<Self>,
9296 ) {
9297 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9298
9299 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9300 let buffer = &display_map.buffer_snapshot;
9301 let selections = self.selections.all::<Point>(cx);
9302
9303 let mut edits = Vec::new();
9304 let mut selections_iter = selections.iter().peekable();
9305 while let Some(selection) = selections_iter.next() {
9306 let mut rows = selection.spanned_rows(false, &display_map);
9307 // duplicate line-wise
9308 if whole_lines || selection.start == selection.end {
9309 // Avoid duplicating the same lines twice.
9310 while let Some(next_selection) = selections_iter.peek() {
9311 let next_rows = next_selection.spanned_rows(false, &display_map);
9312 if next_rows.start < rows.end {
9313 rows.end = next_rows.end;
9314 selections_iter.next().unwrap();
9315 } else {
9316 break;
9317 }
9318 }
9319
9320 // Copy the text from the selected row region and splice it either at the start
9321 // or end of the region.
9322 let start = Point::new(rows.start.0, 0);
9323 let end = Point::new(
9324 rows.end.previous_row().0,
9325 buffer.line_len(rows.end.previous_row()),
9326 );
9327 let text = buffer
9328 .text_for_range(start..end)
9329 .chain(Some("\n"))
9330 .collect::<String>();
9331 let insert_location = if upwards {
9332 Point::new(rows.end.0, 0)
9333 } else {
9334 start
9335 };
9336 edits.push((insert_location..insert_location, text));
9337 } else {
9338 // duplicate character-wise
9339 let start = selection.start;
9340 let end = selection.end;
9341 let text = buffer.text_for_range(start..end).collect::<String>();
9342 edits.push((selection.end..selection.end, text));
9343 }
9344 }
9345
9346 self.transact(window, cx, |this, _, cx| {
9347 this.buffer.update(cx, |buffer, cx| {
9348 buffer.edit(edits, None, cx);
9349 });
9350
9351 this.request_autoscroll(Autoscroll::fit(), cx);
9352 });
9353 }
9354
9355 pub fn duplicate_line_up(
9356 &mut self,
9357 _: &DuplicateLineUp,
9358 window: &mut Window,
9359 cx: &mut Context<Self>,
9360 ) {
9361 self.duplicate(true, true, window, cx);
9362 }
9363
9364 pub fn duplicate_line_down(
9365 &mut self,
9366 _: &DuplicateLineDown,
9367 window: &mut Window,
9368 cx: &mut Context<Self>,
9369 ) {
9370 self.duplicate(false, true, window, cx);
9371 }
9372
9373 pub fn duplicate_selection(
9374 &mut self,
9375 _: &DuplicateSelection,
9376 window: &mut Window,
9377 cx: &mut Context<Self>,
9378 ) {
9379 self.duplicate(false, false, window, cx);
9380 }
9381
9382 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9383 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9384
9385 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9386 let buffer = self.buffer.read(cx).snapshot(cx);
9387
9388 let mut edits = Vec::new();
9389 let mut unfold_ranges = Vec::new();
9390 let mut refold_creases = Vec::new();
9391
9392 let selections = self.selections.all::<Point>(cx);
9393 let mut selections = selections.iter().peekable();
9394 let mut contiguous_row_selections = Vec::new();
9395 let mut new_selections = Vec::new();
9396
9397 while let Some(selection) = selections.next() {
9398 // Find all the selections that span a contiguous row range
9399 let (start_row, end_row) = consume_contiguous_rows(
9400 &mut contiguous_row_selections,
9401 selection,
9402 &display_map,
9403 &mut selections,
9404 );
9405
9406 // Move the text spanned by the row range to be before the line preceding the row range
9407 if start_row.0 > 0 {
9408 let range_to_move = Point::new(
9409 start_row.previous_row().0,
9410 buffer.line_len(start_row.previous_row()),
9411 )
9412 ..Point::new(
9413 end_row.previous_row().0,
9414 buffer.line_len(end_row.previous_row()),
9415 );
9416 let insertion_point = display_map
9417 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9418 .0;
9419
9420 // Don't move lines across excerpts
9421 if buffer
9422 .excerpt_containing(insertion_point..range_to_move.end)
9423 .is_some()
9424 {
9425 let text = buffer
9426 .text_for_range(range_to_move.clone())
9427 .flat_map(|s| s.chars())
9428 .skip(1)
9429 .chain(['\n'])
9430 .collect::<String>();
9431
9432 edits.push((
9433 buffer.anchor_after(range_to_move.start)
9434 ..buffer.anchor_before(range_to_move.end),
9435 String::new(),
9436 ));
9437 let insertion_anchor = buffer.anchor_after(insertion_point);
9438 edits.push((insertion_anchor..insertion_anchor, text));
9439
9440 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9441
9442 // Move selections up
9443 new_selections.extend(contiguous_row_selections.drain(..).map(
9444 |mut selection| {
9445 selection.start.row -= row_delta;
9446 selection.end.row -= row_delta;
9447 selection
9448 },
9449 ));
9450
9451 // Move folds up
9452 unfold_ranges.push(range_to_move.clone());
9453 for fold in display_map.folds_in_range(
9454 buffer.anchor_before(range_to_move.start)
9455 ..buffer.anchor_after(range_to_move.end),
9456 ) {
9457 let mut start = fold.range.start.to_point(&buffer);
9458 let mut end = fold.range.end.to_point(&buffer);
9459 start.row -= row_delta;
9460 end.row -= row_delta;
9461 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9462 }
9463 }
9464 }
9465
9466 // If we didn't move line(s), preserve the existing selections
9467 new_selections.append(&mut contiguous_row_selections);
9468 }
9469
9470 self.transact(window, cx, |this, window, cx| {
9471 this.unfold_ranges(&unfold_ranges, true, true, cx);
9472 this.buffer.update(cx, |buffer, cx| {
9473 for (range, text) in edits {
9474 buffer.edit([(range, text)], None, cx);
9475 }
9476 });
9477 this.fold_creases(refold_creases, true, window, cx);
9478 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9479 s.select(new_selections);
9480 })
9481 });
9482 }
9483
9484 pub fn move_line_down(
9485 &mut self,
9486 _: &MoveLineDown,
9487 window: &mut Window,
9488 cx: &mut Context<Self>,
9489 ) {
9490 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9491
9492 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9493 let buffer = self.buffer.read(cx).snapshot(cx);
9494
9495 let mut edits = Vec::new();
9496 let mut unfold_ranges = Vec::new();
9497 let mut refold_creases = Vec::new();
9498
9499 let selections = self.selections.all::<Point>(cx);
9500 let mut selections = selections.iter().peekable();
9501 let mut contiguous_row_selections = Vec::new();
9502 let mut new_selections = Vec::new();
9503
9504 while let Some(selection) = selections.next() {
9505 // Find all the selections that span a contiguous row range
9506 let (start_row, end_row) = consume_contiguous_rows(
9507 &mut contiguous_row_selections,
9508 selection,
9509 &display_map,
9510 &mut selections,
9511 );
9512
9513 // Move the text spanned by the row range to be after the last line of the row range
9514 if end_row.0 <= buffer.max_point().row {
9515 let range_to_move =
9516 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9517 let insertion_point = display_map
9518 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9519 .0;
9520
9521 // Don't move lines across excerpt boundaries
9522 if buffer
9523 .excerpt_containing(range_to_move.start..insertion_point)
9524 .is_some()
9525 {
9526 let mut text = String::from("\n");
9527 text.extend(buffer.text_for_range(range_to_move.clone()));
9528 text.pop(); // Drop trailing newline
9529 edits.push((
9530 buffer.anchor_after(range_to_move.start)
9531 ..buffer.anchor_before(range_to_move.end),
9532 String::new(),
9533 ));
9534 let insertion_anchor = buffer.anchor_after(insertion_point);
9535 edits.push((insertion_anchor..insertion_anchor, text));
9536
9537 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9538
9539 // Move selections down
9540 new_selections.extend(contiguous_row_selections.drain(..).map(
9541 |mut selection| {
9542 selection.start.row += row_delta;
9543 selection.end.row += row_delta;
9544 selection
9545 },
9546 ));
9547
9548 // Move folds down
9549 unfold_ranges.push(range_to_move.clone());
9550 for fold in display_map.folds_in_range(
9551 buffer.anchor_before(range_to_move.start)
9552 ..buffer.anchor_after(range_to_move.end),
9553 ) {
9554 let mut start = fold.range.start.to_point(&buffer);
9555 let mut end = fold.range.end.to_point(&buffer);
9556 start.row += row_delta;
9557 end.row += row_delta;
9558 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9559 }
9560 }
9561 }
9562
9563 // If we didn't move line(s), preserve the existing selections
9564 new_selections.append(&mut contiguous_row_selections);
9565 }
9566
9567 self.transact(window, cx, |this, window, cx| {
9568 this.unfold_ranges(&unfold_ranges, true, true, cx);
9569 this.buffer.update(cx, |buffer, cx| {
9570 for (range, text) in edits {
9571 buffer.edit([(range, text)], None, cx);
9572 }
9573 });
9574 this.fold_creases(refold_creases, true, window, cx);
9575 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9576 s.select(new_selections)
9577 });
9578 });
9579 }
9580
9581 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9582 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9583 let text_layout_details = &self.text_layout_details(window);
9584 self.transact(window, cx, |this, window, cx| {
9585 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9586 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9587 s.move_with(|display_map, selection| {
9588 if !selection.is_empty() {
9589 return;
9590 }
9591
9592 let mut head = selection.head();
9593 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9594 if head.column() == display_map.line_len(head.row()) {
9595 transpose_offset = display_map
9596 .buffer_snapshot
9597 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9598 }
9599
9600 if transpose_offset == 0 {
9601 return;
9602 }
9603
9604 *head.column_mut() += 1;
9605 head = display_map.clip_point(head, Bias::Right);
9606 let goal = SelectionGoal::HorizontalPosition(
9607 display_map
9608 .x_for_display_point(head, text_layout_details)
9609 .into(),
9610 );
9611 selection.collapse_to(head, goal);
9612
9613 let transpose_start = display_map
9614 .buffer_snapshot
9615 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9616 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9617 let transpose_end = display_map
9618 .buffer_snapshot
9619 .clip_offset(transpose_offset + 1, Bias::Right);
9620 if let Some(ch) =
9621 display_map.buffer_snapshot.chars_at(transpose_start).next()
9622 {
9623 edits.push((transpose_start..transpose_offset, String::new()));
9624 edits.push((transpose_end..transpose_end, ch.to_string()));
9625 }
9626 }
9627 });
9628 edits
9629 });
9630 this.buffer
9631 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9632 let selections = this.selections.all::<usize>(cx);
9633 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9634 s.select(selections);
9635 });
9636 });
9637 }
9638
9639 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9640 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9641 self.rewrap_impl(RewrapOptions::default(), cx)
9642 }
9643
9644 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9645 let buffer = self.buffer.read(cx).snapshot(cx);
9646 let selections = self.selections.all::<Point>(cx);
9647 let mut selections = selections.iter().peekable();
9648
9649 let mut edits = Vec::new();
9650 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9651
9652 while let Some(selection) = selections.next() {
9653 let mut start_row = selection.start.row;
9654 let mut end_row = selection.end.row;
9655
9656 // Skip selections that overlap with a range that has already been rewrapped.
9657 let selection_range = start_row..end_row;
9658 if rewrapped_row_ranges
9659 .iter()
9660 .any(|range| range.overlaps(&selection_range))
9661 {
9662 continue;
9663 }
9664
9665 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9666
9667 // Since not all lines in the selection may be at the same indent
9668 // level, choose the indent size that is the most common between all
9669 // of the lines.
9670 //
9671 // If there is a tie, we use the deepest indent.
9672 let (indent_size, indent_end) = {
9673 let mut indent_size_occurrences = HashMap::default();
9674 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9675
9676 for row in start_row..=end_row {
9677 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9678 rows_by_indent_size.entry(indent).or_default().push(row);
9679 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9680 }
9681
9682 let indent_size = indent_size_occurrences
9683 .into_iter()
9684 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9685 .map(|(indent, _)| indent)
9686 .unwrap_or_default();
9687 let row = rows_by_indent_size[&indent_size][0];
9688 let indent_end = Point::new(row, indent_size.len);
9689
9690 (indent_size, indent_end)
9691 };
9692
9693 let mut line_prefix = indent_size.chars().collect::<String>();
9694
9695 let mut inside_comment = false;
9696 if let Some(comment_prefix) =
9697 buffer
9698 .language_scope_at(selection.head())
9699 .and_then(|language| {
9700 language
9701 .line_comment_prefixes()
9702 .iter()
9703 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9704 .cloned()
9705 })
9706 {
9707 line_prefix.push_str(&comment_prefix);
9708 inside_comment = true;
9709 }
9710
9711 let language_settings = buffer.language_settings_at(selection.head(), cx);
9712 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9713 RewrapBehavior::InComments => inside_comment,
9714 RewrapBehavior::InSelections => !selection.is_empty(),
9715 RewrapBehavior::Anywhere => true,
9716 };
9717
9718 let should_rewrap = options.override_language_settings
9719 || allow_rewrap_based_on_language
9720 || self.hard_wrap.is_some();
9721 if !should_rewrap {
9722 continue;
9723 }
9724
9725 if selection.is_empty() {
9726 'expand_upwards: while start_row > 0 {
9727 let prev_row = start_row - 1;
9728 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9729 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9730 {
9731 start_row = prev_row;
9732 } else {
9733 break 'expand_upwards;
9734 }
9735 }
9736
9737 'expand_downwards: while end_row < buffer.max_point().row {
9738 let next_row = end_row + 1;
9739 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9740 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9741 {
9742 end_row = next_row;
9743 } else {
9744 break 'expand_downwards;
9745 }
9746 }
9747 }
9748
9749 let start = Point::new(start_row, 0);
9750 let start_offset = start.to_offset(&buffer);
9751 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9752 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9753 let Some(lines_without_prefixes) = selection_text
9754 .lines()
9755 .map(|line| {
9756 line.strip_prefix(&line_prefix)
9757 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9758 .ok_or_else(|| {
9759 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9760 })
9761 })
9762 .collect::<Result<Vec<_>, _>>()
9763 .log_err()
9764 else {
9765 continue;
9766 };
9767
9768 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9769 buffer
9770 .language_settings_at(Point::new(start_row, 0), cx)
9771 .preferred_line_length as usize
9772 });
9773 let wrapped_text = wrap_with_prefix(
9774 line_prefix,
9775 lines_without_prefixes.join("\n"),
9776 wrap_column,
9777 tab_size,
9778 options.preserve_existing_whitespace,
9779 );
9780
9781 // TODO: should always use char-based diff while still supporting cursor behavior that
9782 // matches vim.
9783 let mut diff_options = DiffOptions::default();
9784 if options.override_language_settings {
9785 diff_options.max_word_diff_len = 0;
9786 diff_options.max_word_diff_line_count = 0;
9787 } else {
9788 diff_options.max_word_diff_len = usize::MAX;
9789 diff_options.max_word_diff_line_count = usize::MAX;
9790 }
9791
9792 for (old_range, new_text) in
9793 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9794 {
9795 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9796 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9797 edits.push((edit_start..edit_end, new_text));
9798 }
9799
9800 rewrapped_row_ranges.push(start_row..=end_row);
9801 }
9802
9803 self.buffer
9804 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9805 }
9806
9807 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9808 let mut text = String::new();
9809 let buffer = self.buffer.read(cx).snapshot(cx);
9810 let mut selections = self.selections.all::<Point>(cx);
9811 let mut clipboard_selections = Vec::with_capacity(selections.len());
9812 {
9813 let max_point = buffer.max_point();
9814 let mut is_first = true;
9815 for selection in &mut selections {
9816 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9817 if is_entire_line {
9818 selection.start = Point::new(selection.start.row, 0);
9819 if !selection.is_empty() && selection.end.column == 0 {
9820 selection.end = cmp::min(max_point, selection.end);
9821 } else {
9822 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9823 }
9824 selection.goal = SelectionGoal::None;
9825 }
9826 if is_first {
9827 is_first = false;
9828 } else {
9829 text += "\n";
9830 }
9831 let mut len = 0;
9832 for chunk in buffer.text_for_range(selection.start..selection.end) {
9833 text.push_str(chunk);
9834 len += chunk.len();
9835 }
9836 clipboard_selections.push(ClipboardSelection {
9837 len,
9838 is_entire_line,
9839 first_line_indent: buffer
9840 .indent_size_for_line(MultiBufferRow(selection.start.row))
9841 .len,
9842 });
9843 }
9844 }
9845
9846 self.transact(window, cx, |this, window, cx| {
9847 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9848 s.select(selections);
9849 });
9850 this.insert("", window, cx);
9851 });
9852 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9853 }
9854
9855 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9856 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9857 let item = self.cut_common(window, cx);
9858 cx.write_to_clipboard(item);
9859 }
9860
9861 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9862 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9863 self.change_selections(None, window, cx, |s| {
9864 s.move_with(|snapshot, sel| {
9865 if sel.is_empty() {
9866 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9867 }
9868 });
9869 });
9870 let item = self.cut_common(window, cx);
9871 cx.set_global(KillRing(item))
9872 }
9873
9874 pub fn kill_ring_yank(
9875 &mut self,
9876 _: &KillRingYank,
9877 window: &mut Window,
9878 cx: &mut Context<Self>,
9879 ) {
9880 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9881 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9882 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9883 (kill_ring.text().to_string(), kill_ring.metadata_json())
9884 } else {
9885 return;
9886 }
9887 } else {
9888 return;
9889 };
9890 self.do_paste(&text, metadata, false, window, cx);
9891 }
9892
9893 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9894 self.do_copy(true, cx);
9895 }
9896
9897 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9898 self.do_copy(false, cx);
9899 }
9900
9901 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9902 let selections = self.selections.all::<Point>(cx);
9903 let buffer = self.buffer.read(cx).read(cx);
9904 let mut text = String::new();
9905
9906 let mut clipboard_selections = Vec::with_capacity(selections.len());
9907 {
9908 let max_point = buffer.max_point();
9909 let mut is_first = true;
9910 for selection in &selections {
9911 let mut start = selection.start;
9912 let mut end = selection.end;
9913 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9914 if is_entire_line {
9915 start = Point::new(start.row, 0);
9916 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9917 }
9918
9919 let mut trimmed_selections = Vec::new();
9920 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9921 let row = MultiBufferRow(start.row);
9922 let first_indent = buffer.indent_size_for_line(row);
9923 if first_indent.len == 0 || start.column > first_indent.len {
9924 trimmed_selections.push(start..end);
9925 } else {
9926 trimmed_selections.push(
9927 Point::new(row.0, first_indent.len)
9928 ..Point::new(row.0, buffer.line_len(row)),
9929 );
9930 for row in start.row + 1..=end.row {
9931 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
9932 if row_indent_size.len >= first_indent.len {
9933 trimmed_selections.push(
9934 Point::new(row, first_indent.len)
9935 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
9936 );
9937 } else {
9938 trimmed_selections.clear();
9939 trimmed_selections.push(start..end);
9940 break;
9941 }
9942 }
9943 }
9944 } else {
9945 trimmed_selections.push(start..end);
9946 }
9947
9948 for trimmed_range in trimmed_selections {
9949 if is_first {
9950 is_first = false;
9951 } else {
9952 text += "\n";
9953 }
9954 let mut len = 0;
9955 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
9956 text.push_str(chunk);
9957 len += chunk.len();
9958 }
9959 clipboard_selections.push(ClipboardSelection {
9960 len,
9961 is_entire_line,
9962 first_line_indent: buffer
9963 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
9964 .len,
9965 });
9966 }
9967 }
9968 }
9969
9970 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9971 text,
9972 clipboard_selections,
9973 ));
9974 }
9975
9976 pub fn do_paste(
9977 &mut self,
9978 text: &String,
9979 clipboard_selections: Option<Vec<ClipboardSelection>>,
9980 handle_entire_lines: bool,
9981 window: &mut Window,
9982 cx: &mut Context<Self>,
9983 ) {
9984 if self.read_only(cx) {
9985 return;
9986 }
9987
9988 let clipboard_text = Cow::Borrowed(text);
9989
9990 self.transact(window, cx, |this, window, cx| {
9991 if let Some(mut clipboard_selections) = clipboard_selections {
9992 let old_selections = this.selections.all::<usize>(cx);
9993 let all_selections_were_entire_line =
9994 clipboard_selections.iter().all(|s| s.is_entire_line);
9995 let first_selection_indent_column =
9996 clipboard_selections.first().map(|s| s.first_line_indent);
9997 if clipboard_selections.len() != old_selections.len() {
9998 clipboard_selections.drain(..);
9999 }
10000 let cursor_offset = this.selections.last::<usize>(cx).head();
10001 let mut auto_indent_on_paste = true;
10002
10003 this.buffer.update(cx, |buffer, cx| {
10004 let snapshot = buffer.read(cx);
10005 auto_indent_on_paste = snapshot
10006 .language_settings_at(cursor_offset, cx)
10007 .auto_indent_on_paste;
10008
10009 let mut start_offset = 0;
10010 let mut edits = Vec::new();
10011 let mut original_indent_columns = Vec::new();
10012 for (ix, selection) in old_selections.iter().enumerate() {
10013 let to_insert;
10014 let entire_line;
10015 let original_indent_column;
10016 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10017 let end_offset = start_offset + clipboard_selection.len;
10018 to_insert = &clipboard_text[start_offset..end_offset];
10019 entire_line = clipboard_selection.is_entire_line;
10020 start_offset = end_offset + 1;
10021 original_indent_column = Some(clipboard_selection.first_line_indent);
10022 } else {
10023 to_insert = clipboard_text.as_str();
10024 entire_line = all_selections_were_entire_line;
10025 original_indent_column = first_selection_indent_column
10026 }
10027
10028 // If the corresponding selection was empty when this slice of the
10029 // clipboard text was written, then the entire line containing the
10030 // selection was copied. If this selection is also currently empty,
10031 // then paste the line before the current line of the buffer.
10032 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10033 let column = selection.start.to_point(&snapshot).column as usize;
10034 let line_start = selection.start - column;
10035 line_start..line_start
10036 } else {
10037 selection.range()
10038 };
10039
10040 edits.push((range, to_insert));
10041 original_indent_columns.push(original_indent_column);
10042 }
10043 drop(snapshot);
10044
10045 buffer.edit(
10046 edits,
10047 if auto_indent_on_paste {
10048 Some(AutoindentMode::Block {
10049 original_indent_columns,
10050 })
10051 } else {
10052 None
10053 },
10054 cx,
10055 );
10056 });
10057
10058 let selections = this.selections.all::<usize>(cx);
10059 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10060 s.select(selections)
10061 });
10062 } else {
10063 this.insert(&clipboard_text, window, cx);
10064 }
10065 });
10066 }
10067
10068 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10069 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10070 if let Some(item) = cx.read_from_clipboard() {
10071 let entries = item.entries();
10072
10073 match entries.first() {
10074 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10075 // of all the pasted entries.
10076 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10077 .do_paste(
10078 clipboard_string.text(),
10079 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10080 true,
10081 window,
10082 cx,
10083 ),
10084 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10085 }
10086 }
10087 }
10088
10089 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10090 if self.read_only(cx) {
10091 return;
10092 }
10093
10094 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10095
10096 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10097 if let Some((selections, _)) =
10098 self.selection_history.transaction(transaction_id).cloned()
10099 {
10100 self.change_selections(None, window, cx, |s| {
10101 s.select_anchors(selections.to_vec());
10102 });
10103 } else {
10104 log::error!(
10105 "No entry in selection_history found for undo. \
10106 This may correspond to a bug where undo does not update the selection. \
10107 If this is occurring, please add details to \
10108 https://github.com/zed-industries/zed/issues/22692"
10109 );
10110 }
10111 self.request_autoscroll(Autoscroll::fit(), cx);
10112 self.unmark_text(window, cx);
10113 self.refresh_inline_completion(true, false, window, cx);
10114 cx.emit(EditorEvent::Edited { transaction_id });
10115 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10116 }
10117 }
10118
10119 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10120 if self.read_only(cx) {
10121 return;
10122 }
10123
10124 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10125
10126 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10127 if let Some((_, Some(selections))) =
10128 self.selection_history.transaction(transaction_id).cloned()
10129 {
10130 self.change_selections(None, window, cx, |s| {
10131 s.select_anchors(selections.to_vec());
10132 });
10133 } else {
10134 log::error!(
10135 "No entry in selection_history found for redo. \
10136 This may correspond to a bug where undo does not update the selection. \
10137 If this is occurring, please add details to \
10138 https://github.com/zed-industries/zed/issues/22692"
10139 );
10140 }
10141 self.request_autoscroll(Autoscroll::fit(), cx);
10142 self.unmark_text(window, cx);
10143 self.refresh_inline_completion(true, false, window, cx);
10144 cx.emit(EditorEvent::Edited { transaction_id });
10145 }
10146 }
10147
10148 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10149 self.buffer
10150 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10151 }
10152
10153 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10154 self.buffer
10155 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10156 }
10157
10158 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10159 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10160 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10161 s.move_with(|map, selection| {
10162 let cursor = if selection.is_empty() {
10163 movement::left(map, selection.start)
10164 } else {
10165 selection.start
10166 };
10167 selection.collapse_to(cursor, SelectionGoal::None);
10168 });
10169 })
10170 }
10171
10172 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10173 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10174 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10175 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10176 })
10177 }
10178
10179 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10180 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10181 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10182 s.move_with(|map, selection| {
10183 let cursor = if selection.is_empty() {
10184 movement::right(map, selection.end)
10185 } else {
10186 selection.end
10187 };
10188 selection.collapse_to(cursor, SelectionGoal::None)
10189 });
10190 })
10191 }
10192
10193 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10194 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10195 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10196 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10197 })
10198 }
10199
10200 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10201 if self.take_rename(true, window, cx).is_some() {
10202 return;
10203 }
10204
10205 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10206 cx.propagate();
10207 return;
10208 }
10209
10210 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10211
10212 let text_layout_details = &self.text_layout_details(window);
10213 let selection_count = self.selections.count();
10214 let first_selection = self.selections.first_anchor();
10215
10216 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10217 s.move_with(|map, selection| {
10218 if !selection.is_empty() {
10219 selection.goal = SelectionGoal::None;
10220 }
10221 let (cursor, goal) = movement::up(
10222 map,
10223 selection.start,
10224 selection.goal,
10225 false,
10226 text_layout_details,
10227 );
10228 selection.collapse_to(cursor, goal);
10229 });
10230 });
10231
10232 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10233 {
10234 cx.propagate();
10235 }
10236 }
10237
10238 pub fn move_up_by_lines(
10239 &mut self,
10240 action: &MoveUpByLines,
10241 window: &mut Window,
10242 cx: &mut Context<Self>,
10243 ) {
10244 if self.take_rename(true, window, cx).is_some() {
10245 return;
10246 }
10247
10248 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10249 cx.propagate();
10250 return;
10251 }
10252
10253 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10254
10255 let text_layout_details = &self.text_layout_details(window);
10256
10257 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10258 s.move_with(|map, selection| {
10259 if !selection.is_empty() {
10260 selection.goal = SelectionGoal::None;
10261 }
10262 let (cursor, goal) = movement::up_by_rows(
10263 map,
10264 selection.start,
10265 action.lines,
10266 selection.goal,
10267 false,
10268 text_layout_details,
10269 );
10270 selection.collapse_to(cursor, goal);
10271 });
10272 })
10273 }
10274
10275 pub fn move_down_by_lines(
10276 &mut self,
10277 action: &MoveDownByLines,
10278 window: &mut Window,
10279 cx: &mut Context<Self>,
10280 ) {
10281 if self.take_rename(true, window, cx).is_some() {
10282 return;
10283 }
10284
10285 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10286 cx.propagate();
10287 return;
10288 }
10289
10290 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10291
10292 let text_layout_details = &self.text_layout_details(window);
10293
10294 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10295 s.move_with(|map, selection| {
10296 if !selection.is_empty() {
10297 selection.goal = SelectionGoal::None;
10298 }
10299 let (cursor, goal) = movement::down_by_rows(
10300 map,
10301 selection.start,
10302 action.lines,
10303 selection.goal,
10304 false,
10305 text_layout_details,
10306 );
10307 selection.collapse_to(cursor, goal);
10308 });
10309 })
10310 }
10311
10312 pub fn select_down_by_lines(
10313 &mut self,
10314 action: &SelectDownByLines,
10315 window: &mut Window,
10316 cx: &mut Context<Self>,
10317 ) {
10318 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10319 let text_layout_details = &self.text_layout_details(window);
10320 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10321 s.move_heads_with(|map, head, goal| {
10322 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10323 })
10324 })
10325 }
10326
10327 pub fn select_up_by_lines(
10328 &mut self,
10329 action: &SelectUpByLines,
10330 window: &mut Window,
10331 cx: &mut Context<Self>,
10332 ) {
10333 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10334 let text_layout_details = &self.text_layout_details(window);
10335 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10336 s.move_heads_with(|map, head, goal| {
10337 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10338 })
10339 })
10340 }
10341
10342 pub fn select_page_up(
10343 &mut self,
10344 _: &SelectPageUp,
10345 window: &mut Window,
10346 cx: &mut Context<Self>,
10347 ) {
10348 let Some(row_count) = self.visible_row_count() else {
10349 return;
10350 };
10351
10352 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10353
10354 let text_layout_details = &self.text_layout_details(window);
10355
10356 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10357 s.move_heads_with(|map, head, goal| {
10358 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10359 })
10360 })
10361 }
10362
10363 pub fn move_page_up(
10364 &mut self,
10365 action: &MovePageUp,
10366 window: &mut Window,
10367 cx: &mut Context<Self>,
10368 ) {
10369 if self.take_rename(true, window, cx).is_some() {
10370 return;
10371 }
10372
10373 if self
10374 .context_menu
10375 .borrow_mut()
10376 .as_mut()
10377 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10378 .unwrap_or(false)
10379 {
10380 return;
10381 }
10382
10383 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10384 cx.propagate();
10385 return;
10386 }
10387
10388 let Some(row_count) = self.visible_row_count() else {
10389 return;
10390 };
10391
10392 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10393
10394 let autoscroll = if action.center_cursor {
10395 Autoscroll::center()
10396 } else {
10397 Autoscroll::fit()
10398 };
10399
10400 let text_layout_details = &self.text_layout_details(window);
10401
10402 self.change_selections(Some(autoscroll), window, cx, |s| {
10403 s.move_with(|map, selection| {
10404 if !selection.is_empty() {
10405 selection.goal = SelectionGoal::None;
10406 }
10407 let (cursor, goal) = movement::up_by_rows(
10408 map,
10409 selection.end,
10410 row_count,
10411 selection.goal,
10412 false,
10413 text_layout_details,
10414 );
10415 selection.collapse_to(cursor, goal);
10416 });
10417 });
10418 }
10419
10420 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10421 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10422 let text_layout_details = &self.text_layout_details(window);
10423 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10424 s.move_heads_with(|map, head, goal| {
10425 movement::up(map, head, goal, false, text_layout_details)
10426 })
10427 })
10428 }
10429
10430 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10431 self.take_rename(true, window, cx);
10432
10433 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10434 cx.propagate();
10435 return;
10436 }
10437
10438 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10439
10440 let text_layout_details = &self.text_layout_details(window);
10441 let selection_count = self.selections.count();
10442 let first_selection = self.selections.first_anchor();
10443
10444 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10445 s.move_with(|map, selection| {
10446 if !selection.is_empty() {
10447 selection.goal = SelectionGoal::None;
10448 }
10449 let (cursor, goal) = movement::down(
10450 map,
10451 selection.end,
10452 selection.goal,
10453 false,
10454 text_layout_details,
10455 );
10456 selection.collapse_to(cursor, goal);
10457 });
10458 });
10459
10460 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10461 {
10462 cx.propagate();
10463 }
10464 }
10465
10466 pub fn select_page_down(
10467 &mut self,
10468 _: &SelectPageDown,
10469 window: &mut Window,
10470 cx: &mut Context<Self>,
10471 ) {
10472 let Some(row_count) = self.visible_row_count() else {
10473 return;
10474 };
10475
10476 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10477
10478 let text_layout_details = &self.text_layout_details(window);
10479
10480 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10481 s.move_heads_with(|map, head, goal| {
10482 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10483 })
10484 })
10485 }
10486
10487 pub fn move_page_down(
10488 &mut self,
10489 action: &MovePageDown,
10490 window: &mut Window,
10491 cx: &mut Context<Self>,
10492 ) {
10493 if self.take_rename(true, window, cx).is_some() {
10494 return;
10495 }
10496
10497 if self
10498 .context_menu
10499 .borrow_mut()
10500 .as_mut()
10501 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10502 .unwrap_or(false)
10503 {
10504 return;
10505 }
10506
10507 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10508 cx.propagate();
10509 return;
10510 }
10511
10512 let Some(row_count) = self.visible_row_count() else {
10513 return;
10514 };
10515
10516 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10517
10518 let autoscroll = if action.center_cursor {
10519 Autoscroll::center()
10520 } else {
10521 Autoscroll::fit()
10522 };
10523
10524 let text_layout_details = &self.text_layout_details(window);
10525 self.change_selections(Some(autoscroll), window, cx, |s| {
10526 s.move_with(|map, selection| {
10527 if !selection.is_empty() {
10528 selection.goal = SelectionGoal::None;
10529 }
10530 let (cursor, goal) = movement::down_by_rows(
10531 map,
10532 selection.end,
10533 row_count,
10534 selection.goal,
10535 false,
10536 text_layout_details,
10537 );
10538 selection.collapse_to(cursor, goal);
10539 });
10540 });
10541 }
10542
10543 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10544 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10545 let text_layout_details = &self.text_layout_details(window);
10546 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10547 s.move_heads_with(|map, head, goal| {
10548 movement::down(map, head, goal, false, text_layout_details)
10549 })
10550 });
10551 }
10552
10553 pub fn context_menu_first(
10554 &mut self,
10555 _: &ContextMenuFirst,
10556 _window: &mut Window,
10557 cx: &mut Context<Self>,
10558 ) {
10559 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10560 context_menu.select_first(self.completion_provider.as_deref(), cx);
10561 }
10562 }
10563
10564 pub fn context_menu_prev(
10565 &mut self,
10566 _: &ContextMenuPrevious,
10567 _window: &mut Window,
10568 cx: &mut Context<Self>,
10569 ) {
10570 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10571 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10572 }
10573 }
10574
10575 pub fn context_menu_next(
10576 &mut self,
10577 _: &ContextMenuNext,
10578 _window: &mut Window,
10579 cx: &mut Context<Self>,
10580 ) {
10581 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10582 context_menu.select_next(self.completion_provider.as_deref(), cx);
10583 }
10584 }
10585
10586 pub fn context_menu_last(
10587 &mut self,
10588 _: &ContextMenuLast,
10589 _window: &mut Window,
10590 cx: &mut Context<Self>,
10591 ) {
10592 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10593 context_menu.select_last(self.completion_provider.as_deref(), cx);
10594 }
10595 }
10596
10597 pub fn move_to_previous_word_start(
10598 &mut self,
10599 _: &MoveToPreviousWordStart,
10600 window: &mut Window,
10601 cx: &mut Context<Self>,
10602 ) {
10603 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10604 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10605 s.move_cursors_with(|map, head, _| {
10606 (
10607 movement::previous_word_start(map, head),
10608 SelectionGoal::None,
10609 )
10610 });
10611 })
10612 }
10613
10614 pub fn move_to_previous_subword_start(
10615 &mut self,
10616 _: &MoveToPreviousSubwordStart,
10617 window: &mut Window,
10618 cx: &mut Context<Self>,
10619 ) {
10620 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10621 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10622 s.move_cursors_with(|map, head, _| {
10623 (
10624 movement::previous_subword_start(map, head),
10625 SelectionGoal::None,
10626 )
10627 });
10628 })
10629 }
10630
10631 pub fn select_to_previous_word_start(
10632 &mut self,
10633 _: &SelectToPreviousWordStart,
10634 window: &mut Window,
10635 cx: &mut Context<Self>,
10636 ) {
10637 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10638 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10639 s.move_heads_with(|map, head, _| {
10640 (
10641 movement::previous_word_start(map, head),
10642 SelectionGoal::None,
10643 )
10644 });
10645 })
10646 }
10647
10648 pub fn select_to_previous_subword_start(
10649 &mut self,
10650 _: &SelectToPreviousSubwordStart,
10651 window: &mut Window,
10652 cx: &mut Context<Self>,
10653 ) {
10654 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10656 s.move_heads_with(|map, head, _| {
10657 (
10658 movement::previous_subword_start(map, head),
10659 SelectionGoal::None,
10660 )
10661 });
10662 })
10663 }
10664
10665 pub fn delete_to_previous_word_start(
10666 &mut self,
10667 action: &DeleteToPreviousWordStart,
10668 window: &mut Window,
10669 cx: &mut Context<Self>,
10670 ) {
10671 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10672 self.transact(window, cx, |this, window, cx| {
10673 this.select_autoclose_pair(window, cx);
10674 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10675 s.move_with(|map, selection| {
10676 if selection.is_empty() {
10677 let cursor = if action.ignore_newlines {
10678 movement::previous_word_start(map, selection.head())
10679 } else {
10680 movement::previous_word_start_or_newline(map, selection.head())
10681 };
10682 selection.set_head(cursor, SelectionGoal::None);
10683 }
10684 });
10685 });
10686 this.insert("", window, cx);
10687 });
10688 }
10689
10690 pub fn delete_to_previous_subword_start(
10691 &mut self,
10692 _: &DeleteToPreviousSubwordStart,
10693 window: &mut Window,
10694 cx: &mut Context<Self>,
10695 ) {
10696 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10697 self.transact(window, cx, |this, window, cx| {
10698 this.select_autoclose_pair(window, cx);
10699 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10700 s.move_with(|map, selection| {
10701 if selection.is_empty() {
10702 let cursor = movement::previous_subword_start(map, selection.head());
10703 selection.set_head(cursor, SelectionGoal::None);
10704 }
10705 });
10706 });
10707 this.insert("", window, cx);
10708 });
10709 }
10710
10711 pub fn move_to_next_word_end(
10712 &mut self,
10713 _: &MoveToNextWordEnd,
10714 window: &mut Window,
10715 cx: &mut Context<Self>,
10716 ) {
10717 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10718 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10719 s.move_cursors_with(|map, head, _| {
10720 (movement::next_word_end(map, head), SelectionGoal::None)
10721 });
10722 })
10723 }
10724
10725 pub fn move_to_next_subword_end(
10726 &mut self,
10727 _: &MoveToNextSubwordEnd,
10728 window: &mut Window,
10729 cx: &mut Context<Self>,
10730 ) {
10731 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10732 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10733 s.move_cursors_with(|map, head, _| {
10734 (movement::next_subword_end(map, head), SelectionGoal::None)
10735 });
10736 })
10737 }
10738
10739 pub fn select_to_next_word_end(
10740 &mut self,
10741 _: &SelectToNextWordEnd,
10742 window: &mut Window,
10743 cx: &mut Context<Self>,
10744 ) {
10745 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10746 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10747 s.move_heads_with(|map, head, _| {
10748 (movement::next_word_end(map, head), SelectionGoal::None)
10749 });
10750 })
10751 }
10752
10753 pub fn select_to_next_subword_end(
10754 &mut self,
10755 _: &SelectToNextSubwordEnd,
10756 window: &mut Window,
10757 cx: &mut Context<Self>,
10758 ) {
10759 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10760 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10761 s.move_heads_with(|map, head, _| {
10762 (movement::next_subword_end(map, head), SelectionGoal::None)
10763 });
10764 })
10765 }
10766
10767 pub fn delete_to_next_word_end(
10768 &mut self,
10769 action: &DeleteToNextWordEnd,
10770 window: &mut Window,
10771 cx: &mut Context<Self>,
10772 ) {
10773 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10774 self.transact(window, cx, |this, window, cx| {
10775 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10776 s.move_with(|map, selection| {
10777 if selection.is_empty() {
10778 let cursor = if action.ignore_newlines {
10779 movement::next_word_end(map, selection.head())
10780 } else {
10781 movement::next_word_end_or_newline(map, selection.head())
10782 };
10783 selection.set_head(cursor, SelectionGoal::None);
10784 }
10785 });
10786 });
10787 this.insert("", window, cx);
10788 });
10789 }
10790
10791 pub fn delete_to_next_subword_end(
10792 &mut self,
10793 _: &DeleteToNextSubwordEnd,
10794 window: &mut Window,
10795 cx: &mut Context<Self>,
10796 ) {
10797 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10798 self.transact(window, cx, |this, window, cx| {
10799 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10800 s.move_with(|map, selection| {
10801 if selection.is_empty() {
10802 let cursor = movement::next_subword_end(map, selection.head());
10803 selection.set_head(cursor, SelectionGoal::None);
10804 }
10805 });
10806 });
10807 this.insert("", window, cx);
10808 });
10809 }
10810
10811 pub fn move_to_beginning_of_line(
10812 &mut self,
10813 action: &MoveToBeginningOfLine,
10814 window: &mut Window,
10815 cx: &mut Context<Self>,
10816 ) {
10817 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10818 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10819 s.move_cursors_with(|map, head, _| {
10820 (
10821 movement::indented_line_beginning(
10822 map,
10823 head,
10824 action.stop_at_soft_wraps,
10825 action.stop_at_indent,
10826 ),
10827 SelectionGoal::None,
10828 )
10829 });
10830 })
10831 }
10832
10833 pub fn select_to_beginning_of_line(
10834 &mut self,
10835 action: &SelectToBeginningOfLine,
10836 window: &mut Window,
10837 cx: &mut Context<Self>,
10838 ) {
10839 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10840 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10841 s.move_heads_with(|map, head, _| {
10842 (
10843 movement::indented_line_beginning(
10844 map,
10845 head,
10846 action.stop_at_soft_wraps,
10847 action.stop_at_indent,
10848 ),
10849 SelectionGoal::None,
10850 )
10851 });
10852 });
10853 }
10854
10855 pub fn delete_to_beginning_of_line(
10856 &mut self,
10857 action: &DeleteToBeginningOfLine,
10858 window: &mut Window,
10859 cx: &mut Context<Self>,
10860 ) {
10861 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10862 self.transact(window, cx, |this, window, cx| {
10863 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10864 s.move_with(|_, selection| {
10865 selection.reversed = true;
10866 });
10867 });
10868
10869 this.select_to_beginning_of_line(
10870 &SelectToBeginningOfLine {
10871 stop_at_soft_wraps: false,
10872 stop_at_indent: action.stop_at_indent,
10873 },
10874 window,
10875 cx,
10876 );
10877 this.backspace(&Backspace, window, cx);
10878 });
10879 }
10880
10881 pub fn move_to_end_of_line(
10882 &mut self,
10883 action: &MoveToEndOfLine,
10884 window: &mut Window,
10885 cx: &mut Context<Self>,
10886 ) {
10887 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10888 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10889 s.move_cursors_with(|map, head, _| {
10890 (
10891 movement::line_end(map, head, action.stop_at_soft_wraps),
10892 SelectionGoal::None,
10893 )
10894 });
10895 })
10896 }
10897
10898 pub fn select_to_end_of_line(
10899 &mut self,
10900 action: &SelectToEndOfLine,
10901 window: &mut Window,
10902 cx: &mut Context<Self>,
10903 ) {
10904 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10905 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10906 s.move_heads_with(|map, head, _| {
10907 (
10908 movement::line_end(map, head, action.stop_at_soft_wraps),
10909 SelectionGoal::None,
10910 )
10911 });
10912 })
10913 }
10914
10915 pub fn delete_to_end_of_line(
10916 &mut self,
10917 _: &DeleteToEndOfLine,
10918 window: &mut Window,
10919 cx: &mut Context<Self>,
10920 ) {
10921 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10922 self.transact(window, cx, |this, window, cx| {
10923 this.select_to_end_of_line(
10924 &SelectToEndOfLine {
10925 stop_at_soft_wraps: false,
10926 },
10927 window,
10928 cx,
10929 );
10930 this.delete(&Delete, window, cx);
10931 });
10932 }
10933
10934 pub fn cut_to_end_of_line(
10935 &mut self,
10936 _: &CutToEndOfLine,
10937 window: &mut Window,
10938 cx: &mut Context<Self>,
10939 ) {
10940 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10941 self.transact(window, cx, |this, window, cx| {
10942 this.select_to_end_of_line(
10943 &SelectToEndOfLine {
10944 stop_at_soft_wraps: false,
10945 },
10946 window,
10947 cx,
10948 );
10949 this.cut(&Cut, window, cx);
10950 });
10951 }
10952
10953 pub fn move_to_start_of_paragraph(
10954 &mut self,
10955 _: &MoveToStartOfParagraph,
10956 window: &mut Window,
10957 cx: &mut Context<Self>,
10958 ) {
10959 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10960 cx.propagate();
10961 return;
10962 }
10963 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10964 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10965 s.move_with(|map, selection| {
10966 selection.collapse_to(
10967 movement::start_of_paragraph(map, selection.head(), 1),
10968 SelectionGoal::None,
10969 )
10970 });
10971 })
10972 }
10973
10974 pub fn move_to_end_of_paragraph(
10975 &mut self,
10976 _: &MoveToEndOfParagraph,
10977 window: &mut Window,
10978 cx: &mut Context<Self>,
10979 ) {
10980 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10981 cx.propagate();
10982 return;
10983 }
10984 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10985 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10986 s.move_with(|map, selection| {
10987 selection.collapse_to(
10988 movement::end_of_paragraph(map, selection.head(), 1),
10989 SelectionGoal::None,
10990 )
10991 });
10992 })
10993 }
10994
10995 pub fn select_to_start_of_paragraph(
10996 &mut self,
10997 _: &SelectToStartOfParagraph,
10998 window: &mut Window,
10999 cx: &mut Context<Self>,
11000 ) {
11001 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11002 cx.propagate();
11003 return;
11004 }
11005 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11006 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11007 s.move_heads_with(|map, head, _| {
11008 (
11009 movement::start_of_paragraph(map, head, 1),
11010 SelectionGoal::None,
11011 )
11012 });
11013 })
11014 }
11015
11016 pub fn select_to_end_of_paragraph(
11017 &mut self,
11018 _: &SelectToEndOfParagraph,
11019 window: &mut Window,
11020 cx: &mut Context<Self>,
11021 ) {
11022 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11023 cx.propagate();
11024 return;
11025 }
11026 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11027 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11028 s.move_heads_with(|map, head, _| {
11029 (
11030 movement::end_of_paragraph(map, head, 1),
11031 SelectionGoal::None,
11032 )
11033 });
11034 })
11035 }
11036
11037 pub fn move_to_start_of_excerpt(
11038 &mut self,
11039 _: &MoveToStartOfExcerpt,
11040 window: &mut Window,
11041 cx: &mut Context<Self>,
11042 ) {
11043 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11044 cx.propagate();
11045 return;
11046 }
11047 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11048 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11049 s.move_with(|map, selection| {
11050 selection.collapse_to(
11051 movement::start_of_excerpt(
11052 map,
11053 selection.head(),
11054 workspace::searchable::Direction::Prev,
11055 ),
11056 SelectionGoal::None,
11057 )
11058 });
11059 })
11060 }
11061
11062 pub fn move_to_start_of_next_excerpt(
11063 &mut self,
11064 _: &MoveToStartOfNextExcerpt,
11065 window: &mut Window,
11066 cx: &mut Context<Self>,
11067 ) {
11068 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11069 cx.propagate();
11070 return;
11071 }
11072
11073 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11074 s.move_with(|map, selection| {
11075 selection.collapse_to(
11076 movement::start_of_excerpt(
11077 map,
11078 selection.head(),
11079 workspace::searchable::Direction::Next,
11080 ),
11081 SelectionGoal::None,
11082 )
11083 });
11084 })
11085 }
11086
11087 pub fn move_to_end_of_excerpt(
11088 &mut self,
11089 _: &MoveToEndOfExcerpt,
11090 window: &mut Window,
11091 cx: &mut Context<Self>,
11092 ) {
11093 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11094 cx.propagate();
11095 return;
11096 }
11097 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11098 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11099 s.move_with(|map, selection| {
11100 selection.collapse_to(
11101 movement::end_of_excerpt(
11102 map,
11103 selection.head(),
11104 workspace::searchable::Direction::Next,
11105 ),
11106 SelectionGoal::None,
11107 )
11108 });
11109 })
11110 }
11111
11112 pub fn move_to_end_of_previous_excerpt(
11113 &mut self,
11114 _: &MoveToEndOfPreviousExcerpt,
11115 window: &mut Window,
11116 cx: &mut Context<Self>,
11117 ) {
11118 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11119 cx.propagate();
11120 return;
11121 }
11122 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11123 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11124 s.move_with(|map, selection| {
11125 selection.collapse_to(
11126 movement::end_of_excerpt(
11127 map,
11128 selection.head(),
11129 workspace::searchable::Direction::Prev,
11130 ),
11131 SelectionGoal::None,
11132 )
11133 });
11134 })
11135 }
11136
11137 pub fn select_to_start_of_excerpt(
11138 &mut self,
11139 _: &SelectToStartOfExcerpt,
11140 window: &mut Window,
11141 cx: &mut Context<Self>,
11142 ) {
11143 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11144 cx.propagate();
11145 return;
11146 }
11147 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11148 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11149 s.move_heads_with(|map, head, _| {
11150 (
11151 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11152 SelectionGoal::None,
11153 )
11154 });
11155 })
11156 }
11157
11158 pub fn select_to_start_of_next_excerpt(
11159 &mut self,
11160 _: &SelectToStartOfNextExcerpt,
11161 window: &mut Window,
11162 cx: &mut Context<Self>,
11163 ) {
11164 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11165 cx.propagate();
11166 return;
11167 }
11168 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11169 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11170 s.move_heads_with(|map, head, _| {
11171 (
11172 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11173 SelectionGoal::None,
11174 )
11175 });
11176 })
11177 }
11178
11179 pub fn select_to_end_of_excerpt(
11180 &mut self,
11181 _: &SelectToEndOfExcerpt,
11182 window: &mut Window,
11183 cx: &mut Context<Self>,
11184 ) {
11185 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11186 cx.propagate();
11187 return;
11188 }
11189 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11190 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11191 s.move_heads_with(|map, head, _| {
11192 (
11193 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11194 SelectionGoal::None,
11195 )
11196 });
11197 })
11198 }
11199
11200 pub fn select_to_end_of_previous_excerpt(
11201 &mut self,
11202 _: &SelectToEndOfPreviousExcerpt,
11203 window: &mut Window,
11204 cx: &mut Context<Self>,
11205 ) {
11206 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11207 cx.propagate();
11208 return;
11209 }
11210 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11211 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11212 s.move_heads_with(|map, head, _| {
11213 (
11214 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11215 SelectionGoal::None,
11216 )
11217 });
11218 })
11219 }
11220
11221 pub fn move_to_beginning(
11222 &mut self,
11223 _: &MoveToBeginning,
11224 window: &mut Window,
11225 cx: &mut Context<Self>,
11226 ) {
11227 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11228 cx.propagate();
11229 return;
11230 }
11231 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11232 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11233 s.select_ranges(vec![0..0]);
11234 });
11235 }
11236
11237 pub fn select_to_beginning(
11238 &mut self,
11239 _: &SelectToBeginning,
11240 window: &mut Window,
11241 cx: &mut Context<Self>,
11242 ) {
11243 let mut selection = self.selections.last::<Point>(cx);
11244 selection.set_head(Point::zero(), SelectionGoal::None);
11245 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11246 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11247 s.select(vec![selection]);
11248 });
11249 }
11250
11251 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11252 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11253 cx.propagate();
11254 return;
11255 }
11256 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11257 let cursor = self.buffer.read(cx).read(cx).len();
11258 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11259 s.select_ranges(vec![cursor..cursor])
11260 });
11261 }
11262
11263 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11264 self.nav_history = nav_history;
11265 }
11266
11267 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11268 self.nav_history.as_ref()
11269 }
11270
11271 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11272 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11273 }
11274
11275 fn push_to_nav_history(
11276 &mut self,
11277 cursor_anchor: Anchor,
11278 new_position: Option<Point>,
11279 is_deactivate: bool,
11280 cx: &mut Context<Self>,
11281 ) {
11282 if let Some(nav_history) = self.nav_history.as_mut() {
11283 let buffer = self.buffer.read(cx).read(cx);
11284 let cursor_position = cursor_anchor.to_point(&buffer);
11285 let scroll_state = self.scroll_manager.anchor();
11286 let scroll_top_row = scroll_state.top_row(&buffer);
11287 drop(buffer);
11288
11289 if let Some(new_position) = new_position {
11290 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11291 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11292 return;
11293 }
11294 }
11295
11296 nav_history.push(
11297 Some(NavigationData {
11298 cursor_anchor,
11299 cursor_position,
11300 scroll_anchor: scroll_state,
11301 scroll_top_row,
11302 }),
11303 cx,
11304 );
11305 cx.emit(EditorEvent::PushedToNavHistory {
11306 anchor: cursor_anchor,
11307 is_deactivate,
11308 })
11309 }
11310 }
11311
11312 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11313 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11314 let buffer = self.buffer.read(cx).snapshot(cx);
11315 let mut selection = self.selections.first::<usize>(cx);
11316 selection.set_head(buffer.len(), SelectionGoal::None);
11317 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11318 s.select(vec![selection]);
11319 });
11320 }
11321
11322 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11323 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11324 let end = self.buffer.read(cx).read(cx).len();
11325 self.change_selections(None, window, cx, |s| {
11326 s.select_ranges(vec![0..end]);
11327 });
11328 }
11329
11330 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11331 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11332 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11333 let mut selections = self.selections.all::<Point>(cx);
11334 let max_point = display_map.buffer_snapshot.max_point();
11335 for selection in &mut selections {
11336 let rows = selection.spanned_rows(true, &display_map);
11337 selection.start = Point::new(rows.start.0, 0);
11338 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11339 selection.reversed = false;
11340 }
11341 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11342 s.select(selections);
11343 });
11344 }
11345
11346 pub fn split_selection_into_lines(
11347 &mut self,
11348 _: &SplitSelectionIntoLines,
11349 window: &mut Window,
11350 cx: &mut Context<Self>,
11351 ) {
11352 let selections = self
11353 .selections
11354 .all::<Point>(cx)
11355 .into_iter()
11356 .map(|selection| selection.start..selection.end)
11357 .collect::<Vec<_>>();
11358 self.unfold_ranges(&selections, true, true, cx);
11359
11360 let mut new_selection_ranges = Vec::new();
11361 {
11362 let buffer = self.buffer.read(cx).read(cx);
11363 for selection in selections {
11364 for row in selection.start.row..selection.end.row {
11365 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11366 new_selection_ranges.push(cursor..cursor);
11367 }
11368
11369 let is_multiline_selection = selection.start.row != selection.end.row;
11370 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11371 // so this action feels more ergonomic when paired with other selection operations
11372 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11373 if !should_skip_last {
11374 new_selection_ranges.push(selection.end..selection.end);
11375 }
11376 }
11377 }
11378 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11379 s.select_ranges(new_selection_ranges);
11380 });
11381 }
11382
11383 pub fn add_selection_above(
11384 &mut self,
11385 _: &AddSelectionAbove,
11386 window: &mut Window,
11387 cx: &mut Context<Self>,
11388 ) {
11389 self.add_selection(true, window, cx);
11390 }
11391
11392 pub fn add_selection_below(
11393 &mut self,
11394 _: &AddSelectionBelow,
11395 window: &mut Window,
11396 cx: &mut Context<Self>,
11397 ) {
11398 self.add_selection(false, window, cx);
11399 }
11400
11401 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11402 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11403
11404 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11405 let mut selections = self.selections.all::<Point>(cx);
11406 let text_layout_details = self.text_layout_details(window);
11407 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11408 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11409 let range = oldest_selection.display_range(&display_map).sorted();
11410
11411 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11412 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11413 let positions = start_x.min(end_x)..start_x.max(end_x);
11414
11415 selections.clear();
11416 let mut stack = Vec::new();
11417 for row in range.start.row().0..=range.end.row().0 {
11418 if let Some(selection) = self.selections.build_columnar_selection(
11419 &display_map,
11420 DisplayRow(row),
11421 &positions,
11422 oldest_selection.reversed,
11423 &text_layout_details,
11424 ) {
11425 stack.push(selection.id);
11426 selections.push(selection);
11427 }
11428 }
11429
11430 if above {
11431 stack.reverse();
11432 }
11433
11434 AddSelectionsState { above, stack }
11435 });
11436
11437 let last_added_selection = *state.stack.last().unwrap();
11438 let mut new_selections = Vec::new();
11439 if above == state.above {
11440 let end_row = if above {
11441 DisplayRow(0)
11442 } else {
11443 display_map.max_point().row()
11444 };
11445
11446 'outer: for selection in selections {
11447 if selection.id == last_added_selection {
11448 let range = selection.display_range(&display_map).sorted();
11449 debug_assert_eq!(range.start.row(), range.end.row());
11450 let mut row = range.start.row();
11451 let positions =
11452 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11453 px(start)..px(end)
11454 } else {
11455 let start_x =
11456 display_map.x_for_display_point(range.start, &text_layout_details);
11457 let end_x =
11458 display_map.x_for_display_point(range.end, &text_layout_details);
11459 start_x.min(end_x)..start_x.max(end_x)
11460 };
11461
11462 while row != end_row {
11463 if above {
11464 row.0 -= 1;
11465 } else {
11466 row.0 += 1;
11467 }
11468
11469 if let Some(new_selection) = self.selections.build_columnar_selection(
11470 &display_map,
11471 row,
11472 &positions,
11473 selection.reversed,
11474 &text_layout_details,
11475 ) {
11476 state.stack.push(new_selection.id);
11477 if above {
11478 new_selections.push(new_selection);
11479 new_selections.push(selection);
11480 } else {
11481 new_selections.push(selection);
11482 new_selections.push(new_selection);
11483 }
11484
11485 continue 'outer;
11486 }
11487 }
11488 }
11489
11490 new_selections.push(selection);
11491 }
11492 } else {
11493 new_selections = selections;
11494 new_selections.retain(|s| s.id != last_added_selection);
11495 state.stack.pop();
11496 }
11497
11498 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11499 s.select(new_selections);
11500 });
11501 if state.stack.len() > 1 {
11502 self.add_selections_state = Some(state);
11503 }
11504 }
11505
11506 pub fn select_next_match_internal(
11507 &mut self,
11508 display_map: &DisplaySnapshot,
11509 replace_newest: bool,
11510 autoscroll: Option<Autoscroll>,
11511 window: &mut Window,
11512 cx: &mut Context<Self>,
11513 ) -> Result<()> {
11514 fn select_next_match_ranges(
11515 this: &mut Editor,
11516 range: Range<usize>,
11517 replace_newest: bool,
11518 auto_scroll: Option<Autoscroll>,
11519 window: &mut Window,
11520 cx: &mut Context<Editor>,
11521 ) {
11522 this.unfold_ranges(&[range.clone()], false, true, cx);
11523 this.change_selections(auto_scroll, window, cx, |s| {
11524 if replace_newest {
11525 s.delete(s.newest_anchor().id);
11526 }
11527 s.insert_range(range.clone());
11528 });
11529 }
11530
11531 let buffer = &display_map.buffer_snapshot;
11532 let mut selections = self.selections.all::<usize>(cx);
11533 if let Some(mut select_next_state) = self.select_next_state.take() {
11534 let query = &select_next_state.query;
11535 if !select_next_state.done {
11536 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11537 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11538 let mut next_selected_range = None;
11539
11540 let bytes_after_last_selection =
11541 buffer.bytes_in_range(last_selection.end..buffer.len());
11542 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11543 let query_matches = query
11544 .stream_find_iter(bytes_after_last_selection)
11545 .map(|result| (last_selection.end, result))
11546 .chain(
11547 query
11548 .stream_find_iter(bytes_before_first_selection)
11549 .map(|result| (0, result)),
11550 );
11551
11552 for (start_offset, query_match) in query_matches {
11553 let query_match = query_match.unwrap(); // can only fail due to I/O
11554 let offset_range =
11555 start_offset + query_match.start()..start_offset + query_match.end();
11556 let display_range = offset_range.start.to_display_point(display_map)
11557 ..offset_range.end.to_display_point(display_map);
11558
11559 if !select_next_state.wordwise
11560 || (!movement::is_inside_word(display_map, display_range.start)
11561 && !movement::is_inside_word(display_map, display_range.end))
11562 {
11563 // TODO: This is n^2, because we might check all the selections
11564 if !selections
11565 .iter()
11566 .any(|selection| selection.range().overlaps(&offset_range))
11567 {
11568 next_selected_range = Some(offset_range);
11569 break;
11570 }
11571 }
11572 }
11573
11574 if let Some(next_selected_range) = next_selected_range {
11575 select_next_match_ranges(
11576 self,
11577 next_selected_range,
11578 replace_newest,
11579 autoscroll,
11580 window,
11581 cx,
11582 );
11583 } else {
11584 select_next_state.done = true;
11585 }
11586 }
11587
11588 self.select_next_state = Some(select_next_state);
11589 } else {
11590 let mut only_carets = true;
11591 let mut same_text_selected = true;
11592 let mut selected_text = None;
11593
11594 let mut selections_iter = selections.iter().peekable();
11595 while let Some(selection) = selections_iter.next() {
11596 if selection.start != selection.end {
11597 only_carets = false;
11598 }
11599
11600 if same_text_selected {
11601 if selected_text.is_none() {
11602 selected_text =
11603 Some(buffer.text_for_range(selection.range()).collect::<String>());
11604 }
11605
11606 if let Some(next_selection) = selections_iter.peek() {
11607 if next_selection.range().len() == selection.range().len() {
11608 let next_selected_text = buffer
11609 .text_for_range(next_selection.range())
11610 .collect::<String>();
11611 if Some(next_selected_text) != selected_text {
11612 same_text_selected = false;
11613 selected_text = None;
11614 }
11615 } else {
11616 same_text_selected = false;
11617 selected_text = None;
11618 }
11619 }
11620 }
11621 }
11622
11623 if only_carets {
11624 for selection in &mut selections {
11625 let word_range = movement::surrounding_word(
11626 display_map,
11627 selection.start.to_display_point(display_map),
11628 );
11629 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11630 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11631 selection.goal = SelectionGoal::None;
11632 selection.reversed = false;
11633 select_next_match_ranges(
11634 self,
11635 selection.start..selection.end,
11636 replace_newest,
11637 autoscroll,
11638 window,
11639 cx,
11640 );
11641 }
11642
11643 if selections.len() == 1 {
11644 let selection = selections
11645 .last()
11646 .expect("ensured that there's only one selection");
11647 let query = buffer
11648 .text_for_range(selection.start..selection.end)
11649 .collect::<String>();
11650 let is_empty = query.is_empty();
11651 let select_state = SelectNextState {
11652 query: AhoCorasick::new(&[query])?,
11653 wordwise: true,
11654 done: is_empty,
11655 };
11656 self.select_next_state = Some(select_state);
11657 } else {
11658 self.select_next_state = None;
11659 }
11660 } else if let Some(selected_text) = selected_text {
11661 self.select_next_state = Some(SelectNextState {
11662 query: AhoCorasick::new(&[selected_text])?,
11663 wordwise: false,
11664 done: false,
11665 });
11666 self.select_next_match_internal(
11667 display_map,
11668 replace_newest,
11669 autoscroll,
11670 window,
11671 cx,
11672 )?;
11673 }
11674 }
11675 Ok(())
11676 }
11677
11678 pub fn select_all_matches(
11679 &mut self,
11680 _action: &SelectAllMatches,
11681 window: &mut Window,
11682 cx: &mut Context<Self>,
11683 ) -> Result<()> {
11684 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11685
11686 self.push_to_selection_history();
11687 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11688
11689 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11690 let Some(select_next_state) = self.select_next_state.as_mut() else {
11691 return Ok(());
11692 };
11693 if select_next_state.done {
11694 return Ok(());
11695 }
11696
11697 let mut new_selections = self.selections.all::<usize>(cx);
11698
11699 let buffer = &display_map.buffer_snapshot;
11700 let query_matches = select_next_state
11701 .query
11702 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11703
11704 for query_match in query_matches {
11705 let query_match = query_match.unwrap(); // can only fail due to I/O
11706 let offset_range = query_match.start()..query_match.end();
11707 let display_range = offset_range.start.to_display_point(&display_map)
11708 ..offset_range.end.to_display_point(&display_map);
11709
11710 if !select_next_state.wordwise
11711 || (!movement::is_inside_word(&display_map, display_range.start)
11712 && !movement::is_inside_word(&display_map, display_range.end))
11713 {
11714 self.selections.change_with(cx, |selections| {
11715 new_selections.push(Selection {
11716 id: selections.new_selection_id(),
11717 start: offset_range.start,
11718 end: offset_range.end,
11719 reversed: false,
11720 goal: SelectionGoal::None,
11721 });
11722 });
11723 }
11724 }
11725
11726 new_selections.sort_by_key(|selection| selection.start);
11727 let mut ix = 0;
11728 while ix + 1 < new_selections.len() {
11729 let current_selection = &new_selections[ix];
11730 let next_selection = &new_selections[ix + 1];
11731 if current_selection.range().overlaps(&next_selection.range()) {
11732 if current_selection.id < next_selection.id {
11733 new_selections.remove(ix + 1);
11734 } else {
11735 new_selections.remove(ix);
11736 }
11737 } else {
11738 ix += 1;
11739 }
11740 }
11741
11742 let reversed = self.selections.oldest::<usize>(cx).reversed;
11743
11744 for selection in new_selections.iter_mut() {
11745 selection.reversed = reversed;
11746 }
11747
11748 select_next_state.done = true;
11749 self.unfold_ranges(
11750 &new_selections
11751 .iter()
11752 .map(|selection| selection.range())
11753 .collect::<Vec<_>>(),
11754 false,
11755 false,
11756 cx,
11757 );
11758 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11759 selections.select(new_selections)
11760 });
11761
11762 Ok(())
11763 }
11764
11765 pub fn select_next(
11766 &mut self,
11767 action: &SelectNext,
11768 window: &mut Window,
11769 cx: &mut Context<Self>,
11770 ) -> Result<()> {
11771 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11772 self.push_to_selection_history();
11773 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11774 self.select_next_match_internal(
11775 &display_map,
11776 action.replace_newest,
11777 Some(Autoscroll::newest()),
11778 window,
11779 cx,
11780 )?;
11781 Ok(())
11782 }
11783
11784 pub fn select_previous(
11785 &mut self,
11786 action: &SelectPrevious,
11787 window: &mut Window,
11788 cx: &mut Context<Self>,
11789 ) -> Result<()> {
11790 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11791 self.push_to_selection_history();
11792 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11793 let buffer = &display_map.buffer_snapshot;
11794 let mut selections = self.selections.all::<usize>(cx);
11795 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11796 let query = &select_prev_state.query;
11797 if !select_prev_state.done {
11798 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11799 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11800 let mut next_selected_range = None;
11801 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11802 let bytes_before_last_selection =
11803 buffer.reversed_bytes_in_range(0..last_selection.start);
11804 let bytes_after_first_selection =
11805 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11806 let query_matches = query
11807 .stream_find_iter(bytes_before_last_selection)
11808 .map(|result| (last_selection.start, result))
11809 .chain(
11810 query
11811 .stream_find_iter(bytes_after_first_selection)
11812 .map(|result| (buffer.len(), result)),
11813 );
11814 for (end_offset, query_match) in query_matches {
11815 let query_match = query_match.unwrap(); // can only fail due to I/O
11816 let offset_range =
11817 end_offset - query_match.end()..end_offset - query_match.start();
11818 let display_range = offset_range.start.to_display_point(&display_map)
11819 ..offset_range.end.to_display_point(&display_map);
11820
11821 if !select_prev_state.wordwise
11822 || (!movement::is_inside_word(&display_map, display_range.start)
11823 && !movement::is_inside_word(&display_map, display_range.end))
11824 {
11825 next_selected_range = Some(offset_range);
11826 break;
11827 }
11828 }
11829
11830 if let Some(next_selected_range) = next_selected_range {
11831 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11832 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11833 if action.replace_newest {
11834 s.delete(s.newest_anchor().id);
11835 }
11836 s.insert_range(next_selected_range);
11837 });
11838 } else {
11839 select_prev_state.done = true;
11840 }
11841 }
11842
11843 self.select_prev_state = Some(select_prev_state);
11844 } else {
11845 let mut only_carets = true;
11846 let mut same_text_selected = true;
11847 let mut selected_text = None;
11848
11849 let mut selections_iter = selections.iter().peekable();
11850 while let Some(selection) = selections_iter.next() {
11851 if selection.start != selection.end {
11852 only_carets = false;
11853 }
11854
11855 if same_text_selected {
11856 if selected_text.is_none() {
11857 selected_text =
11858 Some(buffer.text_for_range(selection.range()).collect::<String>());
11859 }
11860
11861 if let Some(next_selection) = selections_iter.peek() {
11862 if next_selection.range().len() == selection.range().len() {
11863 let next_selected_text = buffer
11864 .text_for_range(next_selection.range())
11865 .collect::<String>();
11866 if Some(next_selected_text) != selected_text {
11867 same_text_selected = false;
11868 selected_text = None;
11869 }
11870 } else {
11871 same_text_selected = false;
11872 selected_text = None;
11873 }
11874 }
11875 }
11876 }
11877
11878 if only_carets {
11879 for selection in &mut selections {
11880 let word_range = movement::surrounding_word(
11881 &display_map,
11882 selection.start.to_display_point(&display_map),
11883 );
11884 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11885 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11886 selection.goal = SelectionGoal::None;
11887 selection.reversed = false;
11888 }
11889 if selections.len() == 1 {
11890 let selection = selections
11891 .last()
11892 .expect("ensured that there's only one selection");
11893 let query = buffer
11894 .text_for_range(selection.start..selection.end)
11895 .collect::<String>();
11896 let is_empty = query.is_empty();
11897 let select_state = SelectNextState {
11898 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11899 wordwise: true,
11900 done: is_empty,
11901 };
11902 self.select_prev_state = Some(select_state);
11903 } else {
11904 self.select_prev_state = None;
11905 }
11906
11907 self.unfold_ranges(
11908 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11909 false,
11910 true,
11911 cx,
11912 );
11913 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11914 s.select(selections);
11915 });
11916 } else if let Some(selected_text) = selected_text {
11917 self.select_prev_state = Some(SelectNextState {
11918 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11919 wordwise: false,
11920 done: false,
11921 });
11922 self.select_previous(action, window, cx)?;
11923 }
11924 }
11925 Ok(())
11926 }
11927
11928 pub fn toggle_comments(
11929 &mut self,
11930 action: &ToggleComments,
11931 window: &mut Window,
11932 cx: &mut Context<Self>,
11933 ) {
11934 if self.read_only(cx) {
11935 return;
11936 }
11937 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11938 let text_layout_details = &self.text_layout_details(window);
11939 self.transact(window, cx, |this, window, cx| {
11940 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11941 let mut edits = Vec::new();
11942 let mut selection_edit_ranges = Vec::new();
11943 let mut last_toggled_row = None;
11944 let snapshot = this.buffer.read(cx).read(cx);
11945 let empty_str: Arc<str> = Arc::default();
11946 let mut suffixes_inserted = Vec::new();
11947 let ignore_indent = action.ignore_indent;
11948
11949 fn comment_prefix_range(
11950 snapshot: &MultiBufferSnapshot,
11951 row: MultiBufferRow,
11952 comment_prefix: &str,
11953 comment_prefix_whitespace: &str,
11954 ignore_indent: bool,
11955 ) -> Range<Point> {
11956 let indent_size = if ignore_indent {
11957 0
11958 } else {
11959 snapshot.indent_size_for_line(row).len
11960 };
11961
11962 let start = Point::new(row.0, indent_size);
11963
11964 let mut line_bytes = snapshot
11965 .bytes_in_range(start..snapshot.max_point())
11966 .flatten()
11967 .copied();
11968
11969 // If this line currently begins with the line comment prefix, then record
11970 // the range containing the prefix.
11971 if line_bytes
11972 .by_ref()
11973 .take(comment_prefix.len())
11974 .eq(comment_prefix.bytes())
11975 {
11976 // Include any whitespace that matches the comment prefix.
11977 let matching_whitespace_len = line_bytes
11978 .zip(comment_prefix_whitespace.bytes())
11979 .take_while(|(a, b)| a == b)
11980 .count() as u32;
11981 let end = Point::new(
11982 start.row,
11983 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11984 );
11985 start..end
11986 } else {
11987 start..start
11988 }
11989 }
11990
11991 fn comment_suffix_range(
11992 snapshot: &MultiBufferSnapshot,
11993 row: MultiBufferRow,
11994 comment_suffix: &str,
11995 comment_suffix_has_leading_space: bool,
11996 ) -> Range<Point> {
11997 let end = Point::new(row.0, snapshot.line_len(row));
11998 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11999
12000 let mut line_end_bytes = snapshot
12001 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12002 .flatten()
12003 .copied();
12004
12005 let leading_space_len = if suffix_start_column > 0
12006 && line_end_bytes.next() == Some(b' ')
12007 && comment_suffix_has_leading_space
12008 {
12009 1
12010 } else {
12011 0
12012 };
12013
12014 // If this line currently begins with the line comment prefix, then record
12015 // the range containing the prefix.
12016 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12017 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12018 start..end
12019 } else {
12020 end..end
12021 }
12022 }
12023
12024 // TODO: Handle selections that cross excerpts
12025 for selection in &mut selections {
12026 let start_column = snapshot
12027 .indent_size_for_line(MultiBufferRow(selection.start.row))
12028 .len;
12029 let language = if let Some(language) =
12030 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12031 {
12032 language
12033 } else {
12034 continue;
12035 };
12036
12037 selection_edit_ranges.clear();
12038
12039 // If multiple selections contain a given row, avoid processing that
12040 // row more than once.
12041 let mut start_row = MultiBufferRow(selection.start.row);
12042 if last_toggled_row == Some(start_row) {
12043 start_row = start_row.next_row();
12044 }
12045 let end_row =
12046 if selection.end.row > selection.start.row && selection.end.column == 0 {
12047 MultiBufferRow(selection.end.row - 1)
12048 } else {
12049 MultiBufferRow(selection.end.row)
12050 };
12051 last_toggled_row = Some(end_row);
12052
12053 if start_row > end_row {
12054 continue;
12055 }
12056
12057 // If the language has line comments, toggle those.
12058 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12059
12060 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12061 if ignore_indent {
12062 full_comment_prefixes = full_comment_prefixes
12063 .into_iter()
12064 .map(|s| Arc::from(s.trim_end()))
12065 .collect();
12066 }
12067
12068 if !full_comment_prefixes.is_empty() {
12069 let first_prefix = full_comment_prefixes
12070 .first()
12071 .expect("prefixes is non-empty");
12072 let prefix_trimmed_lengths = full_comment_prefixes
12073 .iter()
12074 .map(|p| p.trim_end_matches(' ').len())
12075 .collect::<SmallVec<[usize; 4]>>();
12076
12077 let mut all_selection_lines_are_comments = true;
12078
12079 for row in start_row.0..=end_row.0 {
12080 let row = MultiBufferRow(row);
12081 if start_row < end_row && snapshot.is_line_blank(row) {
12082 continue;
12083 }
12084
12085 let prefix_range = full_comment_prefixes
12086 .iter()
12087 .zip(prefix_trimmed_lengths.iter().copied())
12088 .map(|(prefix, trimmed_prefix_len)| {
12089 comment_prefix_range(
12090 snapshot.deref(),
12091 row,
12092 &prefix[..trimmed_prefix_len],
12093 &prefix[trimmed_prefix_len..],
12094 ignore_indent,
12095 )
12096 })
12097 .max_by_key(|range| range.end.column - range.start.column)
12098 .expect("prefixes is non-empty");
12099
12100 if prefix_range.is_empty() {
12101 all_selection_lines_are_comments = false;
12102 }
12103
12104 selection_edit_ranges.push(prefix_range);
12105 }
12106
12107 if all_selection_lines_are_comments {
12108 edits.extend(
12109 selection_edit_ranges
12110 .iter()
12111 .cloned()
12112 .map(|range| (range, empty_str.clone())),
12113 );
12114 } else {
12115 let min_column = selection_edit_ranges
12116 .iter()
12117 .map(|range| range.start.column)
12118 .min()
12119 .unwrap_or(0);
12120 edits.extend(selection_edit_ranges.iter().map(|range| {
12121 let position = Point::new(range.start.row, min_column);
12122 (position..position, first_prefix.clone())
12123 }));
12124 }
12125 } else if let Some((full_comment_prefix, comment_suffix)) =
12126 language.block_comment_delimiters()
12127 {
12128 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12129 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12130 let prefix_range = comment_prefix_range(
12131 snapshot.deref(),
12132 start_row,
12133 comment_prefix,
12134 comment_prefix_whitespace,
12135 ignore_indent,
12136 );
12137 let suffix_range = comment_suffix_range(
12138 snapshot.deref(),
12139 end_row,
12140 comment_suffix.trim_start_matches(' '),
12141 comment_suffix.starts_with(' '),
12142 );
12143
12144 if prefix_range.is_empty() || suffix_range.is_empty() {
12145 edits.push((
12146 prefix_range.start..prefix_range.start,
12147 full_comment_prefix.clone(),
12148 ));
12149 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12150 suffixes_inserted.push((end_row, comment_suffix.len()));
12151 } else {
12152 edits.push((prefix_range, empty_str.clone()));
12153 edits.push((suffix_range, empty_str.clone()));
12154 }
12155 } else {
12156 continue;
12157 }
12158 }
12159
12160 drop(snapshot);
12161 this.buffer.update(cx, |buffer, cx| {
12162 buffer.edit(edits, None, cx);
12163 });
12164
12165 // Adjust selections so that they end before any comment suffixes that
12166 // were inserted.
12167 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12168 let mut selections = this.selections.all::<Point>(cx);
12169 let snapshot = this.buffer.read(cx).read(cx);
12170 for selection in &mut selections {
12171 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12172 match row.cmp(&MultiBufferRow(selection.end.row)) {
12173 Ordering::Less => {
12174 suffixes_inserted.next();
12175 continue;
12176 }
12177 Ordering::Greater => break,
12178 Ordering::Equal => {
12179 if selection.end.column == snapshot.line_len(row) {
12180 if selection.is_empty() {
12181 selection.start.column -= suffix_len as u32;
12182 }
12183 selection.end.column -= suffix_len as u32;
12184 }
12185 break;
12186 }
12187 }
12188 }
12189 }
12190
12191 drop(snapshot);
12192 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12193 s.select(selections)
12194 });
12195
12196 let selections = this.selections.all::<Point>(cx);
12197 let selections_on_single_row = selections.windows(2).all(|selections| {
12198 selections[0].start.row == selections[1].start.row
12199 && selections[0].end.row == selections[1].end.row
12200 && selections[0].start.row == selections[0].end.row
12201 });
12202 let selections_selecting = selections
12203 .iter()
12204 .any(|selection| selection.start != selection.end);
12205 let advance_downwards = action.advance_downwards
12206 && selections_on_single_row
12207 && !selections_selecting
12208 && !matches!(this.mode, EditorMode::SingleLine { .. });
12209
12210 if advance_downwards {
12211 let snapshot = this.buffer.read(cx).snapshot(cx);
12212
12213 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12214 s.move_cursors_with(|display_snapshot, display_point, _| {
12215 let mut point = display_point.to_point(display_snapshot);
12216 point.row += 1;
12217 point = snapshot.clip_point(point, Bias::Left);
12218 let display_point = point.to_display_point(display_snapshot);
12219 let goal = SelectionGoal::HorizontalPosition(
12220 display_snapshot
12221 .x_for_display_point(display_point, text_layout_details)
12222 .into(),
12223 );
12224 (display_point, goal)
12225 })
12226 });
12227 }
12228 });
12229 }
12230
12231 pub fn select_enclosing_symbol(
12232 &mut self,
12233 _: &SelectEnclosingSymbol,
12234 window: &mut Window,
12235 cx: &mut Context<Self>,
12236 ) {
12237 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12238
12239 let buffer = self.buffer.read(cx).snapshot(cx);
12240 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12241
12242 fn update_selection(
12243 selection: &Selection<usize>,
12244 buffer_snap: &MultiBufferSnapshot,
12245 ) -> Option<Selection<usize>> {
12246 let cursor = selection.head();
12247 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12248 for symbol in symbols.iter().rev() {
12249 let start = symbol.range.start.to_offset(buffer_snap);
12250 let end = symbol.range.end.to_offset(buffer_snap);
12251 let new_range = start..end;
12252 if start < selection.start || end > selection.end {
12253 return Some(Selection {
12254 id: selection.id,
12255 start: new_range.start,
12256 end: new_range.end,
12257 goal: SelectionGoal::None,
12258 reversed: selection.reversed,
12259 });
12260 }
12261 }
12262 None
12263 }
12264
12265 let mut selected_larger_symbol = false;
12266 let new_selections = old_selections
12267 .iter()
12268 .map(|selection| match update_selection(selection, &buffer) {
12269 Some(new_selection) => {
12270 if new_selection.range() != selection.range() {
12271 selected_larger_symbol = true;
12272 }
12273 new_selection
12274 }
12275 None => selection.clone(),
12276 })
12277 .collect::<Vec<_>>();
12278
12279 if selected_larger_symbol {
12280 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12281 s.select(new_selections);
12282 });
12283 }
12284 }
12285
12286 pub fn select_larger_syntax_node(
12287 &mut self,
12288 _: &SelectLargerSyntaxNode,
12289 window: &mut Window,
12290 cx: &mut Context<Self>,
12291 ) {
12292 let Some(visible_row_count) = self.visible_row_count() else {
12293 return;
12294 };
12295 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12296 if old_selections.is_empty() {
12297 return;
12298 }
12299
12300 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12301
12302 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12303 let buffer = self.buffer.read(cx).snapshot(cx);
12304
12305 let mut selected_larger_node = false;
12306 let mut new_selections = old_selections
12307 .iter()
12308 .map(|selection| {
12309 let old_range = selection.start..selection.end;
12310 let mut new_range = old_range.clone();
12311 let mut new_node = None;
12312 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12313 {
12314 new_node = Some(node);
12315 new_range = match containing_range {
12316 MultiOrSingleBufferOffsetRange::Single(_) => break,
12317 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12318 };
12319 if !display_map.intersects_fold(new_range.start)
12320 && !display_map.intersects_fold(new_range.end)
12321 {
12322 break;
12323 }
12324 }
12325
12326 if let Some(node) = new_node {
12327 // Log the ancestor, to support using this action as a way to explore TreeSitter
12328 // nodes. Parent and grandparent are also logged because this operation will not
12329 // visit nodes that have the same range as their parent.
12330 log::info!("Node: {node:?}");
12331 let parent = node.parent();
12332 log::info!("Parent: {parent:?}");
12333 let grandparent = parent.and_then(|x| x.parent());
12334 log::info!("Grandparent: {grandparent:?}");
12335 }
12336
12337 selected_larger_node |= new_range != old_range;
12338 Selection {
12339 id: selection.id,
12340 start: new_range.start,
12341 end: new_range.end,
12342 goal: SelectionGoal::None,
12343 reversed: selection.reversed,
12344 }
12345 })
12346 .collect::<Vec<_>>();
12347
12348 if !selected_larger_node {
12349 return; // don't put this call in the history
12350 }
12351
12352 // scroll based on transformation done to the last selection created by the user
12353 let (last_old, last_new) = old_selections
12354 .last()
12355 .zip(new_selections.last().cloned())
12356 .expect("old_selections isn't empty");
12357
12358 // revert selection
12359 let is_selection_reversed = {
12360 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12361 new_selections.last_mut().expect("checked above").reversed =
12362 should_newest_selection_be_reversed;
12363 should_newest_selection_be_reversed
12364 };
12365
12366 if selected_larger_node {
12367 self.select_syntax_node_history.disable_clearing = true;
12368 self.change_selections(None, window, cx, |s| {
12369 s.select(new_selections.clone());
12370 });
12371 self.select_syntax_node_history.disable_clearing = false;
12372 }
12373
12374 let start_row = last_new.start.to_display_point(&display_map).row().0;
12375 let end_row = last_new.end.to_display_point(&display_map).row().0;
12376 let selection_height = end_row - start_row + 1;
12377 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12378
12379 // if fits on screen (considering margin), keep it in the middle, else, scroll to selection head
12380 let scroll_behavior = if visible_row_count >= selection_height + scroll_margin_rows * 2 {
12381 let middle_row = (end_row + start_row) / 2;
12382 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12383 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12384 SelectSyntaxNodeScrollBehavior::CenterSelection
12385 } else if is_selection_reversed {
12386 self.scroll_cursor_top(&Default::default(), window, cx);
12387 SelectSyntaxNodeScrollBehavior::CursorTop
12388 } else {
12389 self.scroll_cursor_bottom(&Default::default(), window, cx);
12390 SelectSyntaxNodeScrollBehavior::CursorBottom
12391 };
12392
12393 self.select_syntax_node_history.push((
12394 old_selections,
12395 scroll_behavior,
12396 is_selection_reversed,
12397 ));
12398 }
12399
12400 pub fn select_smaller_syntax_node(
12401 &mut self,
12402 _: &SelectSmallerSyntaxNode,
12403 window: &mut Window,
12404 cx: &mut Context<Self>,
12405 ) {
12406 let Some(visible_row_count) = self.visible_row_count() else {
12407 return;
12408 };
12409
12410 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12411
12412 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12413 self.select_syntax_node_history.pop()
12414 {
12415 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12416
12417 if let Some(selection) = selections.last_mut() {
12418 selection.reversed = is_selection_reversed;
12419 }
12420
12421 self.select_syntax_node_history.disable_clearing = true;
12422 self.change_selections(None, window, cx, |s| {
12423 s.select(selections.to_vec());
12424 });
12425 self.select_syntax_node_history.disable_clearing = false;
12426
12427 let newest = self.selections.newest::<usize>(cx);
12428 let start_row = newest.start.to_display_point(&display_map).row().0;
12429 let end_row = newest.end.to_display_point(&display_map).row().0;
12430
12431 match scroll_behavior {
12432 SelectSyntaxNodeScrollBehavior::CursorTop => {
12433 self.scroll_cursor_top(&Default::default(), window, cx);
12434 }
12435 SelectSyntaxNodeScrollBehavior::CenterSelection => {
12436 let middle_row = (end_row + start_row) / 2;
12437 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12438 // centralize the selection, not the cursor
12439 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12440 }
12441 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12442 self.scroll_cursor_bottom(&Default::default(), window, cx);
12443 }
12444 }
12445 }
12446 }
12447
12448 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12449 if !EditorSettings::get_global(cx).gutter.runnables {
12450 self.clear_tasks();
12451 return Task::ready(());
12452 }
12453 let project = self.project.as_ref().map(Entity::downgrade);
12454 cx.spawn_in(window, async move |this, cx| {
12455 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12456 let Some(project) = project.and_then(|p| p.upgrade()) else {
12457 return;
12458 };
12459 let Ok(display_snapshot) = this.update(cx, |this, cx| {
12460 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12461 }) else {
12462 return;
12463 };
12464
12465 let hide_runnables = project
12466 .update(cx, |project, cx| {
12467 // Do not display any test indicators in non-dev server remote projects.
12468 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12469 })
12470 .unwrap_or(true);
12471 if hide_runnables {
12472 return;
12473 }
12474 let new_rows =
12475 cx.background_spawn({
12476 let snapshot = display_snapshot.clone();
12477 async move {
12478 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12479 }
12480 })
12481 .await;
12482
12483 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12484 this.update(cx, |this, _| {
12485 this.clear_tasks();
12486 for (key, value) in rows {
12487 this.insert_tasks(key, value);
12488 }
12489 })
12490 .ok();
12491 })
12492 }
12493 fn fetch_runnable_ranges(
12494 snapshot: &DisplaySnapshot,
12495 range: Range<Anchor>,
12496 ) -> Vec<language::RunnableRange> {
12497 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12498 }
12499
12500 fn runnable_rows(
12501 project: Entity<Project>,
12502 snapshot: DisplaySnapshot,
12503 runnable_ranges: Vec<RunnableRange>,
12504 mut cx: AsyncWindowContext,
12505 ) -> Vec<((BufferId, u32), RunnableTasks)> {
12506 runnable_ranges
12507 .into_iter()
12508 .filter_map(|mut runnable| {
12509 let tasks = cx
12510 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12511 .ok()?;
12512 if tasks.is_empty() {
12513 return None;
12514 }
12515
12516 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12517
12518 let row = snapshot
12519 .buffer_snapshot
12520 .buffer_line_for_row(MultiBufferRow(point.row))?
12521 .1
12522 .start
12523 .row;
12524
12525 let context_range =
12526 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12527 Some((
12528 (runnable.buffer_id, row),
12529 RunnableTasks {
12530 templates: tasks,
12531 offset: snapshot
12532 .buffer_snapshot
12533 .anchor_before(runnable.run_range.start),
12534 context_range,
12535 column: point.column,
12536 extra_variables: runnable.extra_captures,
12537 },
12538 ))
12539 })
12540 .collect()
12541 }
12542
12543 fn templates_with_tags(
12544 project: &Entity<Project>,
12545 runnable: &mut Runnable,
12546 cx: &mut App,
12547 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12548 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12549 let (worktree_id, file) = project
12550 .buffer_for_id(runnable.buffer, cx)
12551 .and_then(|buffer| buffer.read(cx).file())
12552 .map(|file| (file.worktree_id(cx), file.clone()))
12553 .unzip();
12554
12555 (
12556 project.task_store().read(cx).task_inventory().cloned(),
12557 worktree_id,
12558 file,
12559 )
12560 });
12561
12562 let tags = mem::take(&mut runnable.tags);
12563 let mut tags: Vec<_> = tags
12564 .into_iter()
12565 .flat_map(|tag| {
12566 let tag = tag.0.clone();
12567 inventory
12568 .as_ref()
12569 .into_iter()
12570 .flat_map(|inventory| {
12571 inventory.read(cx).list_tasks(
12572 file.clone(),
12573 Some(runnable.language.clone()),
12574 worktree_id,
12575 cx,
12576 )
12577 })
12578 .filter(move |(_, template)| {
12579 template.tags.iter().any(|source_tag| source_tag == &tag)
12580 })
12581 })
12582 .sorted_by_key(|(kind, _)| kind.to_owned())
12583 .collect();
12584 if let Some((leading_tag_source, _)) = tags.first() {
12585 // Strongest source wins; if we have worktree tag binding, prefer that to
12586 // global and language bindings;
12587 // if we have a global binding, prefer that to language binding.
12588 let first_mismatch = tags
12589 .iter()
12590 .position(|(tag_source, _)| tag_source != leading_tag_source);
12591 if let Some(index) = first_mismatch {
12592 tags.truncate(index);
12593 }
12594 }
12595
12596 tags
12597 }
12598
12599 pub fn move_to_enclosing_bracket(
12600 &mut self,
12601 _: &MoveToEnclosingBracket,
12602 window: &mut Window,
12603 cx: &mut Context<Self>,
12604 ) {
12605 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12606 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12607 s.move_offsets_with(|snapshot, selection| {
12608 let Some(enclosing_bracket_ranges) =
12609 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12610 else {
12611 return;
12612 };
12613
12614 let mut best_length = usize::MAX;
12615 let mut best_inside = false;
12616 let mut best_in_bracket_range = false;
12617 let mut best_destination = None;
12618 for (open, close) in enclosing_bracket_ranges {
12619 let close = close.to_inclusive();
12620 let length = close.end() - open.start;
12621 let inside = selection.start >= open.end && selection.end <= *close.start();
12622 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12623 || close.contains(&selection.head());
12624
12625 // If best is next to a bracket and current isn't, skip
12626 if !in_bracket_range && best_in_bracket_range {
12627 continue;
12628 }
12629
12630 // Prefer smaller lengths unless best is inside and current isn't
12631 if length > best_length && (best_inside || !inside) {
12632 continue;
12633 }
12634
12635 best_length = length;
12636 best_inside = inside;
12637 best_in_bracket_range = in_bracket_range;
12638 best_destination = Some(
12639 if close.contains(&selection.start) && close.contains(&selection.end) {
12640 if inside { open.end } else { open.start }
12641 } else if inside {
12642 *close.start()
12643 } else {
12644 *close.end()
12645 },
12646 );
12647 }
12648
12649 if let Some(destination) = best_destination {
12650 selection.collapse_to(destination, SelectionGoal::None);
12651 }
12652 })
12653 });
12654 }
12655
12656 pub fn undo_selection(
12657 &mut self,
12658 _: &UndoSelection,
12659 window: &mut Window,
12660 cx: &mut Context<Self>,
12661 ) {
12662 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12663 self.end_selection(window, cx);
12664 self.selection_history.mode = SelectionHistoryMode::Undoing;
12665 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12666 self.change_selections(None, window, cx, |s| {
12667 s.select_anchors(entry.selections.to_vec())
12668 });
12669 self.select_next_state = entry.select_next_state;
12670 self.select_prev_state = entry.select_prev_state;
12671 self.add_selections_state = entry.add_selections_state;
12672 self.request_autoscroll(Autoscroll::newest(), cx);
12673 }
12674 self.selection_history.mode = SelectionHistoryMode::Normal;
12675 }
12676
12677 pub fn redo_selection(
12678 &mut self,
12679 _: &RedoSelection,
12680 window: &mut Window,
12681 cx: &mut Context<Self>,
12682 ) {
12683 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12684 self.end_selection(window, cx);
12685 self.selection_history.mode = SelectionHistoryMode::Redoing;
12686 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12687 self.change_selections(None, window, cx, |s| {
12688 s.select_anchors(entry.selections.to_vec())
12689 });
12690 self.select_next_state = entry.select_next_state;
12691 self.select_prev_state = entry.select_prev_state;
12692 self.add_selections_state = entry.add_selections_state;
12693 self.request_autoscroll(Autoscroll::newest(), cx);
12694 }
12695 self.selection_history.mode = SelectionHistoryMode::Normal;
12696 }
12697
12698 pub fn expand_excerpts(
12699 &mut self,
12700 action: &ExpandExcerpts,
12701 _: &mut Window,
12702 cx: &mut Context<Self>,
12703 ) {
12704 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12705 }
12706
12707 pub fn expand_excerpts_down(
12708 &mut self,
12709 action: &ExpandExcerptsDown,
12710 _: &mut Window,
12711 cx: &mut Context<Self>,
12712 ) {
12713 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12714 }
12715
12716 pub fn expand_excerpts_up(
12717 &mut self,
12718 action: &ExpandExcerptsUp,
12719 _: &mut Window,
12720 cx: &mut Context<Self>,
12721 ) {
12722 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12723 }
12724
12725 pub fn expand_excerpts_for_direction(
12726 &mut self,
12727 lines: u32,
12728 direction: ExpandExcerptDirection,
12729
12730 cx: &mut Context<Self>,
12731 ) {
12732 let selections = self.selections.disjoint_anchors();
12733
12734 let lines = if lines == 0 {
12735 EditorSettings::get_global(cx).expand_excerpt_lines
12736 } else {
12737 lines
12738 };
12739
12740 self.buffer.update(cx, |buffer, cx| {
12741 let snapshot = buffer.snapshot(cx);
12742 let mut excerpt_ids = selections
12743 .iter()
12744 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12745 .collect::<Vec<_>>();
12746 excerpt_ids.sort();
12747 excerpt_ids.dedup();
12748 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12749 })
12750 }
12751
12752 pub fn expand_excerpt(
12753 &mut self,
12754 excerpt: ExcerptId,
12755 direction: ExpandExcerptDirection,
12756 window: &mut Window,
12757 cx: &mut Context<Self>,
12758 ) {
12759 let current_scroll_position = self.scroll_position(cx);
12760 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12761 self.buffer.update(cx, |buffer, cx| {
12762 buffer.expand_excerpts([excerpt], lines, direction, cx)
12763 });
12764 if direction == ExpandExcerptDirection::Down {
12765 let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12766 self.set_scroll_position(new_scroll_position, window, cx);
12767 }
12768 }
12769
12770 pub fn go_to_singleton_buffer_point(
12771 &mut self,
12772 point: Point,
12773 window: &mut Window,
12774 cx: &mut Context<Self>,
12775 ) {
12776 self.go_to_singleton_buffer_range(point..point, window, cx);
12777 }
12778
12779 pub fn go_to_singleton_buffer_range(
12780 &mut self,
12781 range: Range<Point>,
12782 window: &mut Window,
12783 cx: &mut Context<Self>,
12784 ) {
12785 let multibuffer = self.buffer().read(cx);
12786 let Some(buffer) = multibuffer.as_singleton() else {
12787 return;
12788 };
12789 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12790 return;
12791 };
12792 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12793 return;
12794 };
12795 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12796 s.select_anchor_ranges([start..end])
12797 });
12798 }
12799
12800 fn go_to_diagnostic(
12801 &mut self,
12802 _: &GoToDiagnostic,
12803 window: &mut Window,
12804 cx: &mut Context<Self>,
12805 ) {
12806 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12807 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12808 }
12809
12810 fn go_to_prev_diagnostic(
12811 &mut self,
12812 _: &GoToPreviousDiagnostic,
12813 window: &mut Window,
12814 cx: &mut Context<Self>,
12815 ) {
12816 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12817 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12818 }
12819
12820 pub fn go_to_diagnostic_impl(
12821 &mut self,
12822 direction: Direction,
12823 window: &mut Window,
12824 cx: &mut Context<Self>,
12825 ) {
12826 let buffer = self.buffer.read(cx).snapshot(cx);
12827 let selection = self.selections.newest::<usize>(cx);
12828 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12829 if direction == Direction::Next {
12830 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12831 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12832 return;
12833 };
12834 self.activate_diagnostics(
12835 buffer_id,
12836 popover.local_diagnostic.diagnostic.group_id,
12837 window,
12838 cx,
12839 );
12840 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12841 let primary_range_start = active_diagnostics.primary_range.start;
12842 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12843 let mut new_selection = s.newest_anchor().clone();
12844 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12845 s.select_anchors(vec![new_selection.clone()]);
12846 });
12847 self.refresh_inline_completion(false, true, window, cx);
12848 }
12849 return;
12850 }
12851 }
12852
12853 let active_group_id = self
12854 .active_diagnostics
12855 .as_ref()
12856 .map(|active_group| active_group.group_id);
12857 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12858 active_diagnostics
12859 .primary_range
12860 .to_offset(&buffer)
12861 .to_inclusive()
12862 });
12863 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12864 if active_primary_range.contains(&selection.head()) {
12865 *active_primary_range.start()
12866 } else {
12867 selection.head()
12868 }
12869 } else {
12870 selection.head()
12871 };
12872
12873 let snapshot = self.snapshot(window, cx);
12874 let primary_diagnostics_before = buffer
12875 .diagnostics_in_range::<usize>(0..search_start)
12876 .filter(|entry| entry.diagnostic.is_primary)
12877 .filter(|entry| entry.range.start != entry.range.end)
12878 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12879 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12880 .collect::<Vec<_>>();
12881 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12882 primary_diagnostics_before
12883 .iter()
12884 .position(|entry| entry.diagnostic.group_id == active_group_id)
12885 });
12886
12887 let primary_diagnostics_after = buffer
12888 .diagnostics_in_range::<usize>(search_start..buffer.len())
12889 .filter(|entry| entry.diagnostic.is_primary)
12890 .filter(|entry| entry.range.start != entry.range.end)
12891 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12892 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12893 .collect::<Vec<_>>();
12894 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12895 primary_diagnostics_after
12896 .iter()
12897 .enumerate()
12898 .rev()
12899 .find_map(|(i, entry)| {
12900 if entry.diagnostic.group_id == active_group_id {
12901 Some(i)
12902 } else {
12903 None
12904 }
12905 })
12906 });
12907
12908 let next_primary_diagnostic = match direction {
12909 Direction::Prev => primary_diagnostics_before
12910 .iter()
12911 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12912 .rev()
12913 .next(),
12914 Direction::Next => primary_diagnostics_after
12915 .iter()
12916 .skip(
12917 last_same_group_diagnostic_after
12918 .map(|index| index + 1)
12919 .unwrap_or(0),
12920 )
12921 .next(),
12922 };
12923
12924 // Cycle around to the start of the buffer, potentially moving back to the start of
12925 // the currently active diagnostic.
12926 let cycle_around = || match direction {
12927 Direction::Prev => primary_diagnostics_after
12928 .iter()
12929 .rev()
12930 .chain(primary_diagnostics_before.iter().rev())
12931 .next(),
12932 Direction::Next => primary_diagnostics_before
12933 .iter()
12934 .chain(primary_diagnostics_after.iter())
12935 .next(),
12936 };
12937
12938 if let Some((primary_range, group_id)) = next_primary_diagnostic
12939 .or_else(cycle_around)
12940 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12941 {
12942 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12943 return;
12944 };
12945 self.activate_diagnostics(buffer_id, group_id, window, cx);
12946 if self.active_diagnostics.is_some() {
12947 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12948 s.select(vec![Selection {
12949 id: selection.id,
12950 start: primary_range.start,
12951 end: primary_range.start,
12952 reversed: false,
12953 goal: SelectionGoal::None,
12954 }]);
12955 });
12956 self.refresh_inline_completion(false, true, window, cx);
12957 }
12958 }
12959 }
12960
12961 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12962 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12963 let snapshot = self.snapshot(window, cx);
12964 let selection = self.selections.newest::<Point>(cx);
12965 self.go_to_hunk_before_or_after_position(
12966 &snapshot,
12967 selection.head(),
12968 Direction::Next,
12969 window,
12970 cx,
12971 );
12972 }
12973
12974 pub fn go_to_hunk_before_or_after_position(
12975 &mut self,
12976 snapshot: &EditorSnapshot,
12977 position: Point,
12978 direction: Direction,
12979 window: &mut Window,
12980 cx: &mut Context<Editor>,
12981 ) {
12982 let row = if direction == Direction::Next {
12983 self.hunk_after_position(snapshot, position)
12984 .map(|hunk| hunk.row_range.start)
12985 } else {
12986 self.hunk_before_position(snapshot, position)
12987 };
12988
12989 if let Some(row) = row {
12990 let destination = Point::new(row.0, 0);
12991 let autoscroll = Autoscroll::center();
12992
12993 self.unfold_ranges(&[destination..destination], false, false, cx);
12994 self.change_selections(Some(autoscroll), window, cx, |s| {
12995 s.select_ranges([destination..destination]);
12996 });
12997 }
12998 }
12999
13000 fn hunk_after_position(
13001 &mut self,
13002 snapshot: &EditorSnapshot,
13003 position: Point,
13004 ) -> Option<MultiBufferDiffHunk> {
13005 snapshot
13006 .buffer_snapshot
13007 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13008 .find(|hunk| hunk.row_range.start.0 > position.row)
13009 .or_else(|| {
13010 snapshot
13011 .buffer_snapshot
13012 .diff_hunks_in_range(Point::zero()..position)
13013 .find(|hunk| hunk.row_range.end.0 < position.row)
13014 })
13015 }
13016
13017 fn go_to_prev_hunk(
13018 &mut self,
13019 _: &GoToPreviousHunk,
13020 window: &mut Window,
13021 cx: &mut Context<Self>,
13022 ) {
13023 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13024 let snapshot = self.snapshot(window, cx);
13025 let selection = self.selections.newest::<Point>(cx);
13026 self.go_to_hunk_before_or_after_position(
13027 &snapshot,
13028 selection.head(),
13029 Direction::Prev,
13030 window,
13031 cx,
13032 );
13033 }
13034
13035 fn hunk_before_position(
13036 &mut self,
13037 snapshot: &EditorSnapshot,
13038 position: Point,
13039 ) -> Option<MultiBufferRow> {
13040 snapshot
13041 .buffer_snapshot
13042 .diff_hunk_before(position)
13043 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13044 }
13045
13046 fn go_to_line<T: 'static>(
13047 &mut self,
13048 position: Anchor,
13049 highlight_color: Option<Hsla>,
13050 window: &mut Window,
13051 cx: &mut Context<Self>,
13052 ) {
13053 let snapshot = self.snapshot(window, cx).display_snapshot;
13054 let position = position.to_point(&snapshot.buffer_snapshot);
13055 let start = snapshot
13056 .buffer_snapshot
13057 .clip_point(Point::new(position.row, 0), Bias::Left);
13058 let end = start + Point::new(1, 0);
13059 let start = snapshot.buffer_snapshot.anchor_before(start);
13060 let end = snapshot.buffer_snapshot.anchor_before(end);
13061
13062 self.highlight_rows::<T>(
13063 start..end,
13064 highlight_color
13065 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13066 false,
13067 cx,
13068 );
13069 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13070 }
13071
13072 pub fn go_to_definition(
13073 &mut self,
13074 _: &GoToDefinition,
13075 window: &mut Window,
13076 cx: &mut Context<Self>,
13077 ) -> Task<Result<Navigated>> {
13078 let definition =
13079 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13080 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13081 cx.spawn_in(window, async move |editor, cx| {
13082 if definition.await? == Navigated::Yes {
13083 return Ok(Navigated::Yes);
13084 }
13085 match fallback_strategy {
13086 GoToDefinitionFallback::None => Ok(Navigated::No),
13087 GoToDefinitionFallback::FindAllReferences => {
13088 match editor.update_in(cx, |editor, window, cx| {
13089 editor.find_all_references(&FindAllReferences, window, cx)
13090 })? {
13091 Some(references) => references.await,
13092 None => Ok(Navigated::No),
13093 }
13094 }
13095 }
13096 })
13097 }
13098
13099 pub fn go_to_declaration(
13100 &mut self,
13101 _: &GoToDeclaration,
13102 window: &mut Window,
13103 cx: &mut Context<Self>,
13104 ) -> Task<Result<Navigated>> {
13105 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13106 }
13107
13108 pub fn go_to_declaration_split(
13109 &mut self,
13110 _: &GoToDeclaration,
13111 window: &mut Window,
13112 cx: &mut Context<Self>,
13113 ) -> Task<Result<Navigated>> {
13114 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13115 }
13116
13117 pub fn go_to_implementation(
13118 &mut self,
13119 _: &GoToImplementation,
13120 window: &mut Window,
13121 cx: &mut Context<Self>,
13122 ) -> Task<Result<Navigated>> {
13123 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13124 }
13125
13126 pub fn go_to_implementation_split(
13127 &mut self,
13128 _: &GoToImplementationSplit,
13129 window: &mut Window,
13130 cx: &mut Context<Self>,
13131 ) -> Task<Result<Navigated>> {
13132 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13133 }
13134
13135 pub fn go_to_type_definition(
13136 &mut self,
13137 _: &GoToTypeDefinition,
13138 window: &mut Window,
13139 cx: &mut Context<Self>,
13140 ) -> Task<Result<Navigated>> {
13141 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13142 }
13143
13144 pub fn go_to_definition_split(
13145 &mut self,
13146 _: &GoToDefinitionSplit,
13147 window: &mut Window,
13148 cx: &mut Context<Self>,
13149 ) -> Task<Result<Navigated>> {
13150 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13151 }
13152
13153 pub fn go_to_type_definition_split(
13154 &mut self,
13155 _: &GoToTypeDefinitionSplit,
13156 window: &mut Window,
13157 cx: &mut Context<Self>,
13158 ) -> Task<Result<Navigated>> {
13159 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13160 }
13161
13162 fn go_to_definition_of_kind(
13163 &mut self,
13164 kind: GotoDefinitionKind,
13165 split: bool,
13166 window: &mut Window,
13167 cx: &mut Context<Self>,
13168 ) -> Task<Result<Navigated>> {
13169 let Some(provider) = self.semantics_provider.clone() else {
13170 return Task::ready(Ok(Navigated::No));
13171 };
13172 let head = self.selections.newest::<usize>(cx).head();
13173 let buffer = self.buffer.read(cx);
13174 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13175 text_anchor
13176 } else {
13177 return Task::ready(Ok(Navigated::No));
13178 };
13179
13180 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13181 return Task::ready(Ok(Navigated::No));
13182 };
13183
13184 cx.spawn_in(window, async move |editor, cx| {
13185 let definitions = definitions.await?;
13186 let navigated = editor
13187 .update_in(cx, |editor, window, cx| {
13188 editor.navigate_to_hover_links(
13189 Some(kind),
13190 definitions
13191 .into_iter()
13192 .filter(|location| {
13193 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13194 })
13195 .map(HoverLink::Text)
13196 .collect::<Vec<_>>(),
13197 split,
13198 window,
13199 cx,
13200 )
13201 })?
13202 .await?;
13203 anyhow::Ok(navigated)
13204 })
13205 }
13206
13207 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13208 let selection = self.selections.newest_anchor();
13209 let head = selection.head();
13210 let tail = selection.tail();
13211
13212 let Some((buffer, start_position)) =
13213 self.buffer.read(cx).text_anchor_for_position(head, cx)
13214 else {
13215 return;
13216 };
13217
13218 let end_position = if head != tail {
13219 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13220 return;
13221 };
13222 Some(pos)
13223 } else {
13224 None
13225 };
13226
13227 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13228 let url = if let Some(end_pos) = end_position {
13229 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13230 } else {
13231 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13232 };
13233
13234 if let Some(url) = url {
13235 editor.update(cx, |_, cx| {
13236 cx.open_url(&url);
13237 })
13238 } else {
13239 Ok(())
13240 }
13241 });
13242
13243 url_finder.detach();
13244 }
13245
13246 pub fn open_selected_filename(
13247 &mut self,
13248 _: &OpenSelectedFilename,
13249 window: &mut Window,
13250 cx: &mut Context<Self>,
13251 ) {
13252 let Some(workspace) = self.workspace() else {
13253 return;
13254 };
13255
13256 let position = self.selections.newest_anchor().head();
13257
13258 let Some((buffer, buffer_position)) =
13259 self.buffer.read(cx).text_anchor_for_position(position, cx)
13260 else {
13261 return;
13262 };
13263
13264 let project = self.project.clone();
13265
13266 cx.spawn_in(window, async move |_, cx| {
13267 let result = find_file(&buffer, project, buffer_position, cx).await;
13268
13269 if let Some((_, path)) = result {
13270 workspace
13271 .update_in(cx, |workspace, window, cx| {
13272 workspace.open_resolved_path(path, window, cx)
13273 })?
13274 .await?;
13275 }
13276 anyhow::Ok(())
13277 })
13278 .detach();
13279 }
13280
13281 pub(crate) fn navigate_to_hover_links(
13282 &mut self,
13283 kind: Option<GotoDefinitionKind>,
13284 mut definitions: Vec<HoverLink>,
13285 split: bool,
13286 window: &mut Window,
13287 cx: &mut Context<Editor>,
13288 ) -> Task<Result<Navigated>> {
13289 // If there is one definition, just open it directly
13290 if definitions.len() == 1 {
13291 let definition = definitions.pop().unwrap();
13292
13293 enum TargetTaskResult {
13294 Location(Option<Location>),
13295 AlreadyNavigated,
13296 }
13297
13298 let target_task = match definition {
13299 HoverLink::Text(link) => {
13300 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13301 }
13302 HoverLink::InlayHint(lsp_location, server_id) => {
13303 let computation =
13304 self.compute_target_location(lsp_location, server_id, window, cx);
13305 cx.background_spawn(async move {
13306 let location = computation.await?;
13307 Ok(TargetTaskResult::Location(location))
13308 })
13309 }
13310 HoverLink::Url(url) => {
13311 cx.open_url(&url);
13312 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13313 }
13314 HoverLink::File(path) => {
13315 if let Some(workspace) = self.workspace() {
13316 cx.spawn_in(window, async move |_, cx| {
13317 workspace
13318 .update_in(cx, |workspace, window, cx| {
13319 workspace.open_resolved_path(path, window, cx)
13320 })?
13321 .await
13322 .map(|_| TargetTaskResult::AlreadyNavigated)
13323 })
13324 } else {
13325 Task::ready(Ok(TargetTaskResult::Location(None)))
13326 }
13327 }
13328 };
13329 cx.spawn_in(window, async move |editor, cx| {
13330 let target = match target_task.await.context("target resolution task")? {
13331 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13332 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13333 TargetTaskResult::Location(Some(target)) => target,
13334 };
13335
13336 editor.update_in(cx, |editor, window, cx| {
13337 let Some(workspace) = editor.workspace() else {
13338 return Navigated::No;
13339 };
13340 let pane = workspace.read(cx).active_pane().clone();
13341
13342 let range = target.range.to_point(target.buffer.read(cx));
13343 let range = editor.range_for_match(&range);
13344 let range = collapse_multiline_range(range);
13345
13346 if !split
13347 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13348 {
13349 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13350 } else {
13351 window.defer(cx, move |window, cx| {
13352 let target_editor: Entity<Self> =
13353 workspace.update(cx, |workspace, cx| {
13354 let pane = if split {
13355 workspace.adjacent_pane(window, cx)
13356 } else {
13357 workspace.active_pane().clone()
13358 };
13359
13360 workspace.open_project_item(
13361 pane,
13362 target.buffer.clone(),
13363 true,
13364 true,
13365 window,
13366 cx,
13367 )
13368 });
13369 target_editor.update(cx, |target_editor, cx| {
13370 // When selecting a definition in a different buffer, disable the nav history
13371 // to avoid creating a history entry at the previous cursor location.
13372 pane.update(cx, |pane, _| pane.disable_history());
13373 target_editor.go_to_singleton_buffer_range(range, window, cx);
13374 pane.update(cx, |pane, _| pane.enable_history());
13375 });
13376 });
13377 }
13378 Navigated::Yes
13379 })
13380 })
13381 } else if !definitions.is_empty() {
13382 cx.spawn_in(window, async move |editor, cx| {
13383 let (title, location_tasks, workspace) = editor
13384 .update_in(cx, |editor, window, cx| {
13385 let tab_kind = match kind {
13386 Some(GotoDefinitionKind::Implementation) => "Implementations",
13387 _ => "Definitions",
13388 };
13389 let title = definitions
13390 .iter()
13391 .find_map(|definition| match definition {
13392 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13393 let buffer = origin.buffer.read(cx);
13394 format!(
13395 "{} for {}",
13396 tab_kind,
13397 buffer
13398 .text_for_range(origin.range.clone())
13399 .collect::<String>()
13400 )
13401 }),
13402 HoverLink::InlayHint(_, _) => None,
13403 HoverLink::Url(_) => None,
13404 HoverLink::File(_) => None,
13405 })
13406 .unwrap_or(tab_kind.to_string());
13407 let location_tasks = definitions
13408 .into_iter()
13409 .map(|definition| match definition {
13410 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13411 HoverLink::InlayHint(lsp_location, server_id) => editor
13412 .compute_target_location(lsp_location, server_id, window, cx),
13413 HoverLink::Url(_) => Task::ready(Ok(None)),
13414 HoverLink::File(_) => Task::ready(Ok(None)),
13415 })
13416 .collect::<Vec<_>>();
13417 (title, location_tasks, editor.workspace().clone())
13418 })
13419 .context("location tasks preparation")?;
13420
13421 let locations = future::join_all(location_tasks)
13422 .await
13423 .into_iter()
13424 .filter_map(|location| location.transpose())
13425 .collect::<Result<_>>()
13426 .context("location tasks")?;
13427
13428 let Some(workspace) = workspace else {
13429 return Ok(Navigated::No);
13430 };
13431 let opened = workspace
13432 .update_in(cx, |workspace, window, cx| {
13433 Self::open_locations_in_multibuffer(
13434 workspace,
13435 locations,
13436 title,
13437 split,
13438 MultibufferSelectionMode::First,
13439 window,
13440 cx,
13441 )
13442 })
13443 .ok();
13444
13445 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13446 })
13447 } else {
13448 Task::ready(Ok(Navigated::No))
13449 }
13450 }
13451
13452 fn compute_target_location(
13453 &self,
13454 lsp_location: lsp::Location,
13455 server_id: LanguageServerId,
13456 window: &mut Window,
13457 cx: &mut Context<Self>,
13458 ) -> Task<anyhow::Result<Option<Location>>> {
13459 let Some(project) = self.project.clone() else {
13460 return Task::ready(Ok(None));
13461 };
13462
13463 cx.spawn_in(window, async move |editor, cx| {
13464 let location_task = editor.update(cx, |_, cx| {
13465 project.update(cx, |project, cx| {
13466 let language_server_name = project
13467 .language_server_statuses(cx)
13468 .find(|(id, _)| server_id == *id)
13469 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13470 language_server_name.map(|language_server_name| {
13471 project.open_local_buffer_via_lsp(
13472 lsp_location.uri.clone(),
13473 server_id,
13474 language_server_name,
13475 cx,
13476 )
13477 })
13478 })
13479 })?;
13480 let location = match location_task {
13481 Some(task) => Some({
13482 let target_buffer_handle = task.await.context("open local buffer")?;
13483 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13484 let target_start = target_buffer
13485 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13486 let target_end = target_buffer
13487 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13488 target_buffer.anchor_after(target_start)
13489 ..target_buffer.anchor_before(target_end)
13490 })?;
13491 Location {
13492 buffer: target_buffer_handle,
13493 range,
13494 }
13495 }),
13496 None => None,
13497 };
13498 Ok(location)
13499 })
13500 }
13501
13502 pub fn find_all_references(
13503 &mut self,
13504 _: &FindAllReferences,
13505 window: &mut Window,
13506 cx: &mut Context<Self>,
13507 ) -> Option<Task<Result<Navigated>>> {
13508 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13509
13510 let selection = self.selections.newest::<usize>(cx);
13511 let multi_buffer = self.buffer.read(cx);
13512 let head = selection.head();
13513
13514 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13515 let head_anchor = multi_buffer_snapshot.anchor_at(
13516 head,
13517 if head < selection.tail() {
13518 Bias::Right
13519 } else {
13520 Bias::Left
13521 },
13522 );
13523
13524 match self
13525 .find_all_references_task_sources
13526 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13527 {
13528 Ok(_) => {
13529 log::info!(
13530 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13531 );
13532 return None;
13533 }
13534 Err(i) => {
13535 self.find_all_references_task_sources.insert(i, head_anchor);
13536 }
13537 }
13538
13539 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13540 let workspace = self.workspace()?;
13541 let project = workspace.read(cx).project().clone();
13542 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13543 Some(cx.spawn_in(window, async move |editor, cx| {
13544 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13545 if let Ok(i) = editor
13546 .find_all_references_task_sources
13547 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13548 {
13549 editor.find_all_references_task_sources.remove(i);
13550 }
13551 });
13552
13553 let locations = references.await?;
13554 if locations.is_empty() {
13555 return anyhow::Ok(Navigated::No);
13556 }
13557
13558 workspace.update_in(cx, |workspace, window, cx| {
13559 let title = locations
13560 .first()
13561 .as_ref()
13562 .map(|location| {
13563 let buffer = location.buffer.read(cx);
13564 format!(
13565 "References to `{}`",
13566 buffer
13567 .text_for_range(location.range.clone())
13568 .collect::<String>()
13569 )
13570 })
13571 .unwrap();
13572 Self::open_locations_in_multibuffer(
13573 workspace,
13574 locations,
13575 title,
13576 false,
13577 MultibufferSelectionMode::First,
13578 window,
13579 cx,
13580 );
13581 Navigated::Yes
13582 })
13583 }))
13584 }
13585
13586 /// Opens a multibuffer with the given project locations in it
13587 pub fn open_locations_in_multibuffer(
13588 workspace: &mut Workspace,
13589 mut locations: Vec<Location>,
13590 title: String,
13591 split: bool,
13592 multibuffer_selection_mode: MultibufferSelectionMode,
13593 window: &mut Window,
13594 cx: &mut Context<Workspace>,
13595 ) {
13596 // If there are multiple definitions, open them in a multibuffer
13597 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13598 let mut locations = locations.into_iter().peekable();
13599 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13600 let capability = workspace.project().read(cx).capability();
13601
13602 let excerpt_buffer = cx.new(|cx| {
13603 let mut multibuffer = MultiBuffer::new(capability);
13604 while let Some(location) = locations.next() {
13605 let buffer = location.buffer.read(cx);
13606 let mut ranges_for_buffer = Vec::new();
13607 let range = location.range.to_point(buffer);
13608 ranges_for_buffer.push(range.clone());
13609
13610 while let Some(next_location) = locations.peek() {
13611 if next_location.buffer == location.buffer {
13612 ranges_for_buffer.push(next_location.range.to_point(buffer));
13613 locations.next();
13614 } else {
13615 break;
13616 }
13617 }
13618
13619 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13620 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13621 PathKey::for_buffer(&location.buffer, cx),
13622 location.buffer.clone(),
13623 ranges_for_buffer,
13624 DEFAULT_MULTIBUFFER_CONTEXT,
13625 cx,
13626 );
13627 ranges.extend(new_ranges)
13628 }
13629
13630 multibuffer.with_title(title)
13631 });
13632
13633 let editor = cx.new(|cx| {
13634 Editor::for_multibuffer(
13635 excerpt_buffer,
13636 Some(workspace.project().clone()),
13637 window,
13638 cx,
13639 )
13640 });
13641 editor.update(cx, |editor, cx| {
13642 match multibuffer_selection_mode {
13643 MultibufferSelectionMode::First => {
13644 if let Some(first_range) = ranges.first() {
13645 editor.change_selections(None, window, cx, |selections| {
13646 selections.clear_disjoint();
13647 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13648 });
13649 }
13650 editor.highlight_background::<Self>(
13651 &ranges,
13652 |theme| theme.editor_highlighted_line_background,
13653 cx,
13654 );
13655 }
13656 MultibufferSelectionMode::All => {
13657 editor.change_selections(None, window, cx, |selections| {
13658 selections.clear_disjoint();
13659 selections.select_anchor_ranges(ranges);
13660 });
13661 }
13662 }
13663 editor.register_buffers_with_language_servers(cx);
13664 });
13665
13666 let item = Box::new(editor);
13667 let item_id = item.item_id();
13668
13669 if split {
13670 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13671 } else {
13672 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13673 let (preview_item_id, preview_item_idx) =
13674 workspace.active_pane().update(cx, |pane, _| {
13675 (pane.preview_item_id(), pane.preview_item_idx())
13676 });
13677
13678 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13679
13680 if let Some(preview_item_id) = preview_item_id {
13681 workspace.active_pane().update(cx, |pane, cx| {
13682 pane.remove_item(preview_item_id, false, false, window, cx);
13683 });
13684 }
13685 } else {
13686 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13687 }
13688 }
13689 workspace.active_pane().update(cx, |pane, cx| {
13690 pane.set_preview_item_id(Some(item_id), cx);
13691 });
13692 }
13693
13694 pub fn rename(
13695 &mut self,
13696 _: &Rename,
13697 window: &mut Window,
13698 cx: &mut Context<Self>,
13699 ) -> Option<Task<Result<()>>> {
13700 use language::ToOffset as _;
13701
13702 let provider = self.semantics_provider.clone()?;
13703 let selection = self.selections.newest_anchor().clone();
13704 let (cursor_buffer, cursor_buffer_position) = self
13705 .buffer
13706 .read(cx)
13707 .text_anchor_for_position(selection.head(), cx)?;
13708 let (tail_buffer, cursor_buffer_position_end) = self
13709 .buffer
13710 .read(cx)
13711 .text_anchor_for_position(selection.tail(), cx)?;
13712 if tail_buffer != cursor_buffer {
13713 return None;
13714 }
13715
13716 let snapshot = cursor_buffer.read(cx).snapshot();
13717 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13718 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13719 let prepare_rename = provider
13720 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13721 .unwrap_or_else(|| Task::ready(Ok(None)));
13722 drop(snapshot);
13723
13724 Some(cx.spawn_in(window, async move |this, cx| {
13725 let rename_range = if let Some(range) = prepare_rename.await? {
13726 Some(range)
13727 } else {
13728 this.update(cx, |this, cx| {
13729 let buffer = this.buffer.read(cx).snapshot(cx);
13730 let mut buffer_highlights = this
13731 .document_highlights_for_position(selection.head(), &buffer)
13732 .filter(|highlight| {
13733 highlight.start.excerpt_id == selection.head().excerpt_id
13734 && highlight.end.excerpt_id == selection.head().excerpt_id
13735 });
13736 buffer_highlights
13737 .next()
13738 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13739 })?
13740 };
13741 if let Some(rename_range) = rename_range {
13742 this.update_in(cx, |this, window, cx| {
13743 let snapshot = cursor_buffer.read(cx).snapshot();
13744 let rename_buffer_range = rename_range.to_offset(&snapshot);
13745 let cursor_offset_in_rename_range =
13746 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13747 let cursor_offset_in_rename_range_end =
13748 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13749
13750 this.take_rename(false, window, cx);
13751 let buffer = this.buffer.read(cx).read(cx);
13752 let cursor_offset = selection.head().to_offset(&buffer);
13753 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13754 let rename_end = rename_start + rename_buffer_range.len();
13755 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13756 let mut old_highlight_id = None;
13757 let old_name: Arc<str> = buffer
13758 .chunks(rename_start..rename_end, true)
13759 .map(|chunk| {
13760 if old_highlight_id.is_none() {
13761 old_highlight_id = chunk.syntax_highlight_id;
13762 }
13763 chunk.text
13764 })
13765 .collect::<String>()
13766 .into();
13767
13768 drop(buffer);
13769
13770 // Position the selection in the rename editor so that it matches the current selection.
13771 this.show_local_selections = false;
13772 let rename_editor = cx.new(|cx| {
13773 let mut editor = Editor::single_line(window, cx);
13774 editor.buffer.update(cx, |buffer, cx| {
13775 buffer.edit([(0..0, old_name.clone())], None, cx)
13776 });
13777 let rename_selection_range = match cursor_offset_in_rename_range
13778 .cmp(&cursor_offset_in_rename_range_end)
13779 {
13780 Ordering::Equal => {
13781 editor.select_all(&SelectAll, window, cx);
13782 return editor;
13783 }
13784 Ordering::Less => {
13785 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13786 }
13787 Ordering::Greater => {
13788 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13789 }
13790 };
13791 if rename_selection_range.end > old_name.len() {
13792 editor.select_all(&SelectAll, window, cx);
13793 } else {
13794 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13795 s.select_ranges([rename_selection_range]);
13796 });
13797 }
13798 editor
13799 });
13800 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13801 if e == &EditorEvent::Focused {
13802 cx.emit(EditorEvent::FocusedIn)
13803 }
13804 })
13805 .detach();
13806
13807 let write_highlights =
13808 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13809 let read_highlights =
13810 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13811 let ranges = write_highlights
13812 .iter()
13813 .flat_map(|(_, ranges)| ranges.iter())
13814 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13815 .cloned()
13816 .collect();
13817
13818 this.highlight_text::<Rename>(
13819 ranges,
13820 HighlightStyle {
13821 fade_out: Some(0.6),
13822 ..Default::default()
13823 },
13824 cx,
13825 );
13826 let rename_focus_handle = rename_editor.focus_handle(cx);
13827 window.focus(&rename_focus_handle);
13828 let block_id = this.insert_blocks(
13829 [BlockProperties {
13830 style: BlockStyle::Flex,
13831 placement: BlockPlacement::Below(range.start),
13832 height: Some(1),
13833 render: Arc::new({
13834 let rename_editor = rename_editor.clone();
13835 move |cx: &mut BlockContext| {
13836 let mut text_style = cx.editor_style.text.clone();
13837 if let Some(highlight_style) = old_highlight_id
13838 .and_then(|h| h.style(&cx.editor_style.syntax))
13839 {
13840 text_style = text_style.highlight(highlight_style);
13841 }
13842 div()
13843 .block_mouse_down()
13844 .pl(cx.anchor_x)
13845 .child(EditorElement::new(
13846 &rename_editor,
13847 EditorStyle {
13848 background: cx.theme().system().transparent,
13849 local_player: cx.editor_style.local_player,
13850 text: text_style,
13851 scrollbar_width: cx.editor_style.scrollbar_width,
13852 syntax: cx.editor_style.syntax.clone(),
13853 status: cx.editor_style.status.clone(),
13854 inlay_hints_style: HighlightStyle {
13855 font_weight: Some(FontWeight::BOLD),
13856 ..make_inlay_hints_style(cx.app)
13857 },
13858 inline_completion_styles: make_suggestion_styles(
13859 cx.app,
13860 ),
13861 ..EditorStyle::default()
13862 },
13863 ))
13864 .into_any_element()
13865 }
13866 }),
13867 priority: 0,
13868 }],
13869 Some(Autoscroll::fit()),
13870 cx,
13871 )[0];
13872 this.pending_rename = Some(RenameState {
13873 range,
13874 old_name,
13875 editor: rename_editor,
13876 block_id,
13877 });
13878 })?;
13879 }
13880
13881 Ok(())
13882 }))
13883 }
13884
13885 pub fn confirm_rename(
13886 &mut self,
13887 _: &ConfirmRename,
13888 window: &mut Window,
13889 cx: &mut Context<Self>,
13890 ) -> Option<Task<Result<()>>> {
13891 let rename = self.take_rename(false, window, cx)?;
13892 let workspace = self.workspace()?.downgrade();
13893 let (buffer, start) = self
13894 .buffer
13895 .read(cx)
13896 .text_anchor_for_position(rename.range.start, cx)?;
13897 let (end_buffer, _) = self
13898 .buffer
13899 .read(cx)
13900 .text_anchor_for_position(rename.range.end, cx)?;
13901 if buffer != end_buffer {
13902 return None;
13903 }
13904
13905 let old_name = rename.old_name;
13906 let new_name = rename.editor.read(cx).text(cx);
13907
13908 let rename = self.semantics_provider.as_ref()?.perform_rename(
13909 &buffer,
13910 start,
13911 new_name.clone(),
13912 cx,
13913 )?;
13914
13915 Some(cx.spawn_in(window, async move |editor, cx| {
13916 let project_transaction = rename.await?;
13917 Self::open_project_transaction(
13918 &editor,
13919 workspace,
13920 project_transaction,
13921 format!("Rename: {} → {}", old_name, new_name),
13922 cx,
13923 )
13924 .await?;
13925
13926 editor.update(cx, |editor, cx| {
13927 editor.refresh_document_highlights(cx);
13928 })?;
13929 Ok(())
13930 }))
13931 }
13932
13933 fn take_rename(
13934 &mut self,
13935 moving_cursor: bool,
13936 window: &mut Window,
13937 cx: &mut Context<Self>,
13938 ) -> Option<RenameState> {
13939 let rename = self.pending_rename.take()?;
13940 if rename.editor.focus_handle(cx).is_focused(window) {
13941 window.focus(&self.focus_handle);
13942 }
13943
13944 self.remove_blocks(
13945 [rename.block_id].into_iter().collect(),
13946 Some(Autoscroll::fit()),
13947 cx,
13948 );
13949 self.clear_highlights::<Rename>(cx);
13950 self.show_local_selections = true;
13951
13952 if moving_cursor {
13953 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13954 editor.selections.newest::<usize>(cx).head()
13955 });
13956
13957 // Update the selection to match the position of the selection inside
13958 // the rename editor.
13959 let snapshot = self.buffer.read(cx).read(cx);
13960 let rename_range = rename.range.to_offset(&snapshot);
13961 let cursor_in_editor = snapshot
13962 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13963 .min(rename_range.end);
13964 drop(snapshot);
13965
13966 self.change_selections(None, window, cx, |s| {
13967 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13968 });
13969 } else {
13970 self.refresh_document_highlights(cx);
13971 }
13972
13973 Some(rename)
13974 }
13975
13976 pub fn pending_rename(&self) -> Option<&RenameState> {
13977 self.pending_rename.as_ref()
13978 }
13979
13980 fn format(
13981 &mut self,
13982 _: &Format,
13983 window: &mut Window,
13984 cx: &mut Context<Self>,
13985 ) -> Option<Task<Result<()>>> {
13986 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13987
13988 let project = match &self.project {
13989 Some(project) => project.clone(),
13990 None => return None,
13991 };
13992
13993 Some(self.perform_format(
13994 project,
13995 FormatTrigger::Manual,
13996 FormatTarget::Buffers,
13997 window,
13998 cx,
13999 ))
14000 }
14001
14002 fn format_selections(
14003 &mut self,
14004 _: &FormatSelections,
14005 window: &mut Window,
14006 cx: &mut Context<Self>,
14007 ) -> Option<Task<Result<()>>> {
14008 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14009
14010 let project = match &self.project {
14011 Some(project) => project.clone(),
14012 None => return None,
14013 };
14014
14015 let ranges = self
14016 .selections
14017 .all_adjusted(cx)
14018 .into_iter()
14019 .map(|selection| selection.range())
14020 .collect_vec();
14021
14022 Some(self.perform_format(
14023 project,
14024 FormatTrigger::Manual,
14025 FormatTarget::Ranges(ranges),
14026 window,
14027 cx,
14028 ))
14029 }
14030
14031 fn perform_format(
14032 &mut self,
14033 project: Entity<Project>,
14034 trigger: FormatTrigger,
14035 target: FormatTarget,
14036 window: &mut Window,
14037 cx: &mut Context<Self>,
14038 ) -> Task<Result<()>> {
14039 let buffer = self.buffer.clone();
14040 let (buffers, target) = match target {
14041 FormatTarget::Buffers => {
14042 let mut buffers = buffer.read(cx).all_buffers();
14043 if trigger == FormatTrigger::Save {
14044 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14045 }
14046 (buffers, LspFormatTarget::Buffers)
14047 }
14048 FormatTarget::Ranges(selection_ranges) => {
14049 let multi_buffer = buffer.read(cx);
14050 let snapshot = multi_buffer.read(cx);
14051 let mut buffers = HashSet::default();
14052 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14053 BTreeMap::new();
14054 for selection_range in selection_ranges {
14055 for (buffer, buffer_range, _) in
14056 snapshot.range_to_buffer_ranges(selection_range)
14057 {
14058 let buffer_id = buffer.remote_id();
14059 let start = buffer.anchor_before(buffer_range.start);
14060 let end = buffer.anchor_after(buffer_range.end);
14061 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14062 buffer_id_to_ranges
14063 .entry(buffer_id)
14064 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14065 .or_insert_with(|| vec![start..end]);
14066 }
14067 }
14068 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14069 }
14070 };
14071
14072 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14073 let format = project.update(cx, |project, cx| {
14074 project.format(buffers, target, true, trigger, cx)
14075 });
14076
14077 cx.spawn_in(window, async move |_, cx| {
14078 let transaction = futures::select_biased! {
14079 transaction = format.log_err().fuse() => transaction,
14080 () = timeout => {
14081 log::warn!("timed out waiting for formatting");
14082 None
14083 }
14084 };
14085
14086 buffer
14087 .update(cx, |buffer, cx| {
14088 if let Some(transaction) = transaction {
14089 if !buffer.is_singleton() {
14090 buffer.push_transaction(&transaction.0, cx);
14091 }
14092 }
14093 cx.notify();
14094 })
14095 .ok();
14096
14097 Ok(())
14098 })
14099 }
14100
14101 fn organize_imports(
14102 &mut self,
14103 _: &OrganizeImports,
14104 window: &mut Window,
14105 cx: &mut Context<Self>,
14106 ) -> Option<Task<Result<()>>> {
14107 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14108 let project = match &self.project {
14109 Some(project) => project.clone(),
14110 None => return None,
14111 };
14112 Some(self.perform_code_action_kind(
14113 project,
14114 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14115 window,
14116 cx,
14117 ))
14118 }
14119
14120 fn perform_code_action_kind(
14121 &mut self,
14122 project: Entity<Project>,
14123 kind: CodeActionKind,
14124 window: &mut Window,
14125 cx: &mut Context<Self>,
14126 ) -> Task<Result<()>> {
14127 let buffer = self.buffer.clone();
14128 let buffers = buffer.read(cx).all_buffers();
14129 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14130 let apply_action = project.update(cx, |project, cx| {
14131 project.apply_code_action_kind(buffers, kind, true, cx)
14132 });
14133 cx.spawn_in(window, async move |_, cx| {
14134 let transaction = futures::select_biased! {
14135 () = timeout => {
14136 log::warn!("timed out waiting for executing code action");
14137 None
14138 }
14139 transaction = apply_action.log_err().fuse() => transaction,
14140 };
14141 buffer
14142 .update(cx, |buffer, cx| {
14143 // check if we need this
14144 if let Some(transaction) = transaction {
14145 if !buffer.is_singleton() {
14146 buffer.push_transaction(&transaction.0, cx);
14147 }
14148 }
14149 cx.notify();
14150 })
14151 .ok();
14152 Ok(())
14153 })
14154 }
14155
14156 fn restart_language_server(
14157 &mut self,
14158 _: &RestartLanguageServer,
14159 _: &mut Window,
14160 cx: &mut Context<Self>,
14161 ) {
14162 if let Some(project) = self.project.clone() {
14163 self.buffer.update(cx, |multi_buffer, cx| {
14164 project.update(cx, |project, cx| {
14165 project.restart_language_servers_for_buffers(
14166 multi_buffer.all_buffers().into_iter().collect(),
14167 cx,
14168 );
14169 });
14170 })
14171 }
14172 }
14173
14174 fn cancel_language_server_work(
14175 workspace: &mut Workspace,
14176 _: &actions::CancelLanguageServerWork,
14177 _: &mut Window,
14178 cx: &mut Context<Workspace>,
14179 ) {
14180 let project = workspace.project();
14181 let buffers = workspace
14182 .active_item(cx)
14183 .and_then(|item| item.act_as::<Editor>(cx))
14184 .map_or(HashSet::default(), |editor| {
14185 editor.read(cx).buffer.read(cx).all_buffers()
14186 });
14187 project.update(cx, |project, cx| {
14188 project.cancel_language_server_work_for_buffers(buffers, cx);
14189 });
14190 }
14191
14192 fn show_character_palette(
14193 &mut self,
14194 _: &ShowCharacterPalette,
14195 window: &mut Window,
14196 _: &mut Context<Self>,
14197 ) {
14198 window.show_character_palette();
14199 }
14200
14201 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14202 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14203 let buffer = self.buffer.read(cx).snapshot(cx);
14204 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14205 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14206 let is_valid = buffer
14207 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14208 .any(|entry| {
14209 entry.diagnostic.is_primary
14210 && !entry.range.is_empty()
14211 && entry.range.start == primary_range_start
14212 && entry.diagnostic.message == active_diagnostics.primary_message
14213 });
14214
14215 if is_valid != active_diagnostics.is_valid {
14216 active_diagnostics.is_valid = is_valid;
14217 if is_valid {
14218 let mut new_styles = HashMap::default();
14219 for (block_id, diagnostic) in &active_diagnostics.blocks {
14220 new_styles.insert(
14221 *block_id,
14222 diagnostic_block_renderer(diagnostic.clone(), None, true),
14223 );
14224 }
14225 self.display_map.update(cx, |display_map, _cx| {
14226 display_map.replace_blocks(new_styles);
14227 });
14228 } else {
14229 self.dismiss_diagnostics(cx);
14230 }
14231 }
14232 }
14233 }
14234
14235 fn activate_diagnostics(
14236 &mut self,
14237 buffer_id: BufferId,
14238 group_id: usize,
14239 window: &mut Window,
14240 cx: &mut Context<Self>,
14241 ) {
14242 self.dismiss_diagnostics(cx);
14243 let snapshot = self.snapshot(window, cx);
14244 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14245 let buffer = self.buffer.read(cx).snapshot(cx);
14246
14247 let mut primary_range = None;
14248 let mut primary_message = None;
14249 let diagnostic_group = buffer
14250 .diagnostic_group(buffer_id, group_id)
14251 .filter_map(|entry| {
14252 let start = entry.range.start;
14253 let end = entry.range.end;
14254 if snapshot.is_line_folded(MultiBufferRow(start.row))
14255 && (start.row == end.row
14256 || snapshot.is_line_folded(MultiBufferRow(end.row)))
14257 {
14258 return None;
14259 }
14260 if entry.diagnostic.is_primary {
14261 primary_range = Some(entry.range.clone());
14262 primary_message = Some(entry.diagnostic.message.clone());
14263 }
14264 Some(entry)
14265 })
14266 .collect::<Vec<_>>();
14267 let primary_range = primary_range?;
14268 let primary_message = primary_message?;
14269
14270 let blocks = display_map
14271 .insert_blocks(
14272 diagnostic_group.iter().map(|entry| {
14273 let diagnostic = entry.diagnostic.clone();
14274 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14275 BlockProperties {
14276 style: BlockStyle::Fixed,
14277 placement: BlockPlacement::Below(
14278 buffer.anchor_after(entry.range.start),
14279 ),
14280 height: Some(message_height),
14281 render: diagnostic_block_renderer(diagnostic, None, true),
14282 priority: 0,
14283 }
14284 }),
14285 cx,
14286 )
14287 .into_iter()
14288 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14289 .collect();
14290
14291 Some(ActiveDiagnosticGroup {
14292 primary_range: buffer.anchor_before(primary_range.start)
14293 ..buffer.anchor_after(primary_range.end),
14294 primary_message,
14295 group_id,
14296 blocks,
14297 is_valid: true,
14298 })
14299 });
14300 }
14301
14302 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14303 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14304 self.display_map.update(cx, |display_map, cx| {
14305 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14306 });
14307 cx.notify();
14308 }
14309 }
14310
14311 /// Disable inline diagnostics rendering for this editor.
14312 pub fn disable_inline_diagnostics(&mut self) {
14313 self.inline_diagnostics_enabled = false;
14314 self.inline_diagnostics_update = Task::ready(());
14315 self.inline_diagnostics.clear();
14316 }
14317
14318 pub fn inline_diagnostics_enabled(&self) -> bool {
14319 self.inline_diagnostics_enabled
14320 }
14321
14322 pub fn show_inline_diagnostics(&self) -> bool {
14323 self.show_inline_diagnostics
14324 }
14325
14326 pub fn toggle_inline_diagnostics(
14327 &mut self,
14328 _: &ToggleInlineDiagnostics,
14329 window: &mut Window,
14330 cx: &mut Context<Editor>,
14331 ) {
14332 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14333 self.refresh_inline_diagnostics(false, window, cx);
14334 }
14335
14336 fn refresh_inline_diagnostics(
14337 &mut self,
14338 debounce: bool,
14339 window: &mut Window,
14340 cx: &mut Context<Self>,
14341 ) {
14342 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14343 self.inline_diagnostics_update = Task::ready(());
14344 self.inline_diagnostics.clear();
14345 return;
14346 }
14347
14348 let debounce_ms = ProjectSettings::get_global(cx)
14349 .diagnostics
14350 .inline
14351 .update_debounce_ms;
14352 let debounce = if debounce && debounce_ms > 0 {
14353 Some(Duration::from_millis(debounce_ms))
14354 } else {
14355 None
14356 };
14357 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14358 if let Some(debounce) = debounce {
14359 cx.background_executor().timer(debounce).await;
14360 }
14361 let Some(snapshot) = editor
14362 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14363 .ok()
14364 else {
14365 return;
14366 };
14367
14368 let new_inline_diagnostics = cx
14369 .background_spawn(async move {
14370 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14371 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14372 let message = diagnostic_entry
14373 .diagnostic
14374 .message
14375 .split_once('\n')
14376 .map(|(line, _)| line)
14377 .map(SharedString::new)
14378 .unwrap_or_else(|| {
14379 SharedString::from(diagnostic_entry.diagnostic.message)
14380 });
14381 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14382 let (Ok(i) | Err(i)) = inline_diagnostics
14383 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14384 inline_diagnostics.insert(
14385 i,
14386 (
14387 start_anchor,
14388 InlineDiagnostic {
14389 message,
14390 group_id: diagnostic_entry.diagnostic.group_id,
14391 start: diagnostic_entry.range.start.to_point(&snapshot),
14392 is_primary: diagnostic_entry.diagnostic.is_primary,
14393 severity: diagnostic_entry.diagnostic.severity,
14394 },
14395 ),
14396 );
14397 }
14398 inline_diagnostics
14399 })
14400 .await;
14401
14402 editor
14403 .update(cx, |editor, cx| {
14404 editor.inline_diagnostics = new_inline_diagnostics;
14405 cx.notify();
14406 })
14407 .ok();
14408 });
14409 }
14410
14411 pub fn set_selections_from_remote(
14412 &mut self,
14413 selections: Vec<Selection<Anchor>>,
14414 pending_selection: Option<Selection<Anchor>>,
14415 window: &mut Window,
14416 cx: &mut Context<Self>,
14417 ) {
14418 let old_cursor_position = self.selections.newest_anchor().head();
14419 self.selections.change_with(cx, |s| {
14420 s.select_anchors(selections);
14421 if let Some(pending_selection) = pending_selection {
14422 s.set_pending(pending_selection, SelectMode::Character);
14423 } else {
14424 s.clear_pending();
14425 }
14426 });
14427 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14428 }
14429
14430 fn push_to_selection_history(&mut self) {
14431 self.selection_history.push(SelectionHistoryEntry {
14432 selections: self.selections.disjoint_anchors(),
14433 select_next_state: self.select_next_state.clone(),
14434 select_prev_state: self.select_prev_state.clone(),
14435 add_selections_state: self.add_selections_state.clone(),
14436 });
14437 }
14438
14439 pub fn transact(
14440 &mut self,
14441 window: &mut Window,
14442 cx: &mut Context<Self>,
14443 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14444 ) -> Option<TransactionId> {
14445 self.start_transaction_at(Instant::now(), window, cx);
14446 update(self, window, cx);
14447 self.end_transaction_at(Instant::now(), cx)
14448 }
14449
14450 pub fn start_transaction_at(
14451 &mut self,
14452 now: Instant,
14453 window: &mut Window,
14454 cx: &mut Context<Self>,
14455 ) {
14456 self.end_selection(window, cx);
14457 if let Some(tx_id) = self
14458 .buffer
14459 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14460 {
14461 self.selection_history
14462 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14463 cx.emit(EditorEvent::TransactionBegun {
14464 transaction_id: tx_id,
14465 })
14466 }
14467 }
14468
14469 pub fn end_transaction_at(
14470 &mut self,
14471 now: Instant,
14472 cx: &mut Context<Self>,
14473 ) -> Option<TransactionId> {
14474 if let Some(transaction_id) = self
14475 .buffer
14476 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14477 {
14478 if let Some((_, end_selections)) =
14479 self.selection_history.transaction_mut(transaction_id)
14480 {
14481 *end_selections = Some(self.selections.disjoint_anchors());
14482 } else {
14483 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14484 }
14485
14486 cx.emit(EditorEvent::Edited { transaction_id });
14487 Some(transaction_id)
14488 } else {
14489 None
14490 }
14491 }
14492
14493 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14494 if self.selection_mark_mode {
14495 self.change_selections(None, window, cx, |s| {
14496 s.move_with(|_, sel| {
14497 sel.collapse_to(sel.head(), SelectionGoal::None);
14498 });
14499 })
14500 }
14501 self.selection_mark_mode = true;
14502 cx.notify();
14503 }
14504
14505 pub fn swap_selection_ends(
14506 &mut self,
14507 _: &actions::SwapSelectionEnds,
14508 window: &mut Window,
14509 cx: &mut Context<Self>,
14510 ) {
14511 self.change_selections(None, window, cx, |s| {
14512 s.move_with(|_, sel| {
14513 if sel.start != sel.end {
14514 sel.reversed = !sel.reversed
14515 }
14516 });
14517 });
14518 self.request_autoscroll(Autoscroll::newest(), cx);
14519 cx.notify();
14520 }
14521
14522 pub fn toggle_fold(
14523 &mut self,
14524 _: &actions::ToggleFold,
14525 window: &mut Window,
14526 cx: &mut Context<Self>,
14527 ) {
14528 if self.is_singleton(cx) {
14529 let selection = self.selections.newest::<Point>(cx);
14530
14531 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14532 let range = if selection.is_empty() {
14533 let point = selection.head().to_display_point(&display_map);
14534 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14535 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14536 .to_point(&display_map);
14537 start..end
14538 } else {
14539 selection.range()
14540 };
14541 if display_map.folds_in_range(range).next().is_some() {
14542 self.unfold_lines(&Default::default(), window, cx)
14543 } else {
14544 self.fold(&Default::default(), window, cx)
14545 }
14546 } else {
14547 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14548 let buffer_ids: HashSet<_> = self
14549 .selections
14550 .disjoint_anchor_ranges()
14551 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14552 .collect();
14553
14554 let should_unfold = buffer_ids
14555 .iter()
14556 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14557
14558 for buffer_id in buffer_ids {
14559 if should_unfold {
14560 self.unfold_buffer(buffer_id, cx);
14561 } else {
14562 self.fold_buffer(buffer_id, cx);
14563 }
14564 }
14565 }
14566 }
14567
14568 pub fn toggle_fold_recursive(
14569 &mut self,
14570 _: &actions::ToggleFoldRecursive,
14571 window: &mut Window,
14572 cx: &mut Context<Self>,
14573 ) {
14574 let selection = self.selections.newest::<Point>(cx);
14575
14576 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14577 let range = if selection.is_empty() {
14578 let point = selection.head().to_display_point(&display_map);
14579 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14580 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14581 .to_point(&display_map);
14582 start..end
14583 } else {
14584 selection.range()
14585 };
14586 if display_map.folds_in_range(range).next().is_some() {
14587 self.unfold_recursive(&Default::default(), window, cx)
14588 } else {
14589 self.fold_recursive(&Default::default(), window, cx)
14590 }
14591 }
14592
14593 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14594 if self.is_singleton(cx) {
14595 let mut to_fold = Vec::new();
14596 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14597 let selections = self.selections.all_adjusted(cx);
14598
14599 for selection in selections {
14600 let range = selection.range().sorted();
14601 let buffer_start_row = range.start.row;
14602
14603 if range.start.row != range.end.row {
14604 let mut found = false;
14605 let mut row = range.start.row;
14606 while row <= range.end.row {
14607 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14608 {
14609 found = true;
14610 row = crease.range().end.row + 1;
14611 to_fold.push(crease);
14612 } else {
14613 row += 1
14614 }
14615 }
14616 if found {
14617 continue;
14618 }
14619 }
14620
14621 for row in (0..=range.start.row).rev() {
14622 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14623 if crease.range().end.row >= buffer_start_row {
14624 to_fold.push(crease);
14625 if row <= range.start.row {
14626 break;
14627 }
14628 }
14629 }
14630 }
14631 }
14632
14633 self.fold_creases(to_fold, true, window, cx);
14634 } else {
14635 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14636 let buffer_ids = self
14637 .selections
14638 .disjoint_anchor_ranges()
14639 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14640 .collect::<HashSet<_>>();
14641 for buffer_id in buffer_ids {
14642 self.fold_buffer(buffer_id, cx);
14643 }
14644 }
14645 }
14646
14647 fn fold_at_level(
14648 &mut self,
14649 fold_at: &FoldAtLevel,
14650 window: &mut Window,
14651 cx: &mut Context<Self>,
14652 ) {
14653 if !self.buffer.read(cx).is_singleton() {
14654 return;
14655 }
14656
14657 let fold_at_level = fold_at.0;
14658 let snapshot = self.buffer.read(cx).snapshot(cx);
14659 let mut to_fold = Vec::new();
14660 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14661
14662 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14663 while start_row < end_row {
14664 match self
14665 .snapshot(window, cx)
14666 .crease_for_buffer_row(MultiBufferRow(start_row))
14667 {
14668 Some(crease) => {
14669 let nested_start_row = crease.range().start.row + 1;
14670 let nested_end_row = crease.range().end.row;
14671
14672 if current_level < fold_at_level {
14673 stack.push((nested_start_row, nested_end_row, current_level + 1));
14674 } else if current_level == fold_at_level {
14675 to_fold.push(crease);
14676 }
14677
14678 start_row = nested_end_row + 1;
14679 }
14680 None => start_row += 1,
14681 }
14682 }
14683 }
14684
14685 self.fold_creases(to_fold, true, window, cx);
14686 }
14687
14688 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14689 if self.buffer.read(cx).is_singleton() {
14690 let mut fold_ranges = Vec::new();
14691 let snapshot = self.buffer.read(cx).snapshot(cx);
14692
14693 for row in 0..snapshot.max_row().0 {
14694 if let Some(foldable_range) = self
14695 .snapshot(window, cx)
14696 .crease_for_buffer_row(MultiBufferRow(row))
14697 {
14698 fold_ranges.push(foldable_range);
14699 }
14700 }
14701
14702 self.fold_creases(fold_ranges, true, window, cx);
14703 } else {
14704 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14705 editor
14706 .update_in(cx, |editor, _, cx| {
14707 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14708 editor.fold_buffer(buffer_id, cx);
14709 }
14710 })
14711 .ok();
14712 });
14713 }
14714 }
14715
14716 pub fn fold_function_bodies(
14717 &mut self,
14718 _: &actions::FoldFunctionBodies,
14719 window: &mut Window,
14720 cx: &mut Context<Self>,
14721 ) {
14722 let snapshot = self.buffer.read(cx).snapshot(cx);
14723
14724 let ranges = snapshot
14725 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14726 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14727 .collect::<Vec<_>>();
14728
14729 let creases = ranges
14730 .into_iter()
14731 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14732 .collect();
14733
14734 self.fold_creases(creases, true, window, cx);
14735 }
14736
14737 pub fn fold_recursive(
14738 &mut self,
14739 _: &actions::FoldRecursive,
14740 window: &mut Window,
14741 cx: &mut Context<Self>,
14742 ) {
14743 let mut to_fold = Vec::new();
14744 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14745 let selections = self.selections.all_adjusted(cx);
14746
14747 for selection in selections {
14748 let range = selection.range().sorted();
14749 let buffer_start_row = range.start.row;
14750
14751 if range.start.row != range.end.row {
14752 let mut found = false;
14753 for row in range.start.row..=range.end.row {
14754 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14755 found = true;
14756 to_fold.push(crease);
14757 }
14758 }
14759 if found {
14760 continue;
14761 }
14762 }
14763
14764 for row in (0..=range.start.row).rev() {
14765 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14766 if crease.range().end.row >= buffer_start_row {
14767 to_fold.push(crease);
14768 } else {
14769 break;
14770 }
14771 }
14772 }
14773 }
14774
14775 self.fold_creases(to_fold, true, window, cx);
14776 }
14777
14778 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14779 let buffer_row = fold_at.buffer_row;
14780 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14781
14782 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14783 let autoscroll = self
14784 .selections
14785 .all::<Point>(cx)
14786 .iter()
14787 .any(|selection| crease.range().overlaps(&selection.range()));
14788
14789 self.fold_creases(vec![crease], autoscroll, window, cx);
14790 }
14791 }
14792
14793 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14794 if self.is_singleton(cx) {
14795 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14796 let buffer = &display_map.buffer_snapshot;
14797 let selections = self.selections.all::<Point>(cx);
14798 let ranges = selections
14799 .iter()
14800 .map(|s| {
14801 let range = s.display_range(&display_map).sorted();
14802 let mut start = range.start.to_point(&display_map);
14803 let mut end = range.end.to_point(&display_map);
14804 start.column = 0;
14805 end.column = buffer.line_len(MultiBufferRow(end.row));
14806 start..end
14807 })
14808 .collect::<Vec<_>>();
14809
14810 self.unfold_ranges(&ranges, true, true, cx);
14811 } else {
14812 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14813 let buffer_ids = self
14814 .selections
14815 .disjoint_anchor_ranges()
14816 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14817 .collect::<HashSet<_>>();
14818 for buffer_id in buffer_ids {
14819 self.unfold_buffer(buffer_id, cx);
14820 }
14821 }
14822 }
14823
14824 pub fn unfold_recursive(
14825 &mut self,
14826 _: &UnfoldRecursive,
14827 _window: &mut Window,
14828 cx: &mut Context<Self>,
14829 ) {
14830 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14831 let selections = self.selections.all::<Point>(cx);
14832 let ranges = selections
14833 .iter()
14834 .map(|s| {
14835 let mut range = s.display_range(&display_map).sorted();
14836 *range.start.column_mut() = 0;
14837 *range.end.column_mut() = display_map.line_len(range.end.row());
14838 let start = range.start.to_point(&display_map);
14839 let end = range.end.to_point(&display_map);
14840 start..end
14841 })
14842 .collect::<Vec<_>>();
14843
14844 self.unfold_ranges(&ranges, true, true, cx);
14845 }
14846
14847 pub fn unfold_at(
14848 &mut self,
14849 unfold_at: &UnfoldAt,
14850 _window: &mut Window,
14851 cx: &mut Context<Self>,
14852 ) {
14853 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14854
14855 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14856 ..Point::new(
14857 unfold_at.buffer_row.0,
14858 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14859 );
14860
14861 let autoscroll = self
14862 .selections
14863 .all::<Point>(cx)
14864 .iter()
14865 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14866
14867 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14868 }
14869
14870 pub fn unfold_all(
14871 &mut self,
14872 _: &actions::UnfoldAll,
14873 _window: &mut Window,
14874 cx: &mut Context<Self>,
14875 ) {
14876 if self.buffer.read(cx).is_singleton() {
14877 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14878 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14879 } else {
14880 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14881 editor
14882 .update(cx, |editor, cx| {
14883 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14884 editor.unfold_buffer(buffer_id, cx);
14885 }
14886 })
14887 .ok();
14888 });
14889 }
14890 }
14891
14892 pub fn fold_selected_ranges(
14893 &mut self,
14894 _: &FoldSelectedRanges,
14895 window: &mut Window,
14896 cx: &mut Context<Self>,
14897 ) {
14898 let selections = self.selections.all_adjusted(cx);
14899 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14900 let ranges = selections
14901 .into_iter()
14902 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
14903 .collect::<Vec<_>>();
14904 self.fold_creases(ranges, true, window, cx);
14905 }
14906
14907 pub fn fold_ranges<T: ToOffset + Clone>(
14908 &mut self,
14909 ranges: Vec<Range<T>>,
14910 auto_scroll: bool,
14911 window: &mut Window,
14912 cx: &mut Context<Self>,
14913 ) {
14914 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14915 let ranges = ranges
14916 .into_iter()
14917 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14918 .collect::<Vec<_>>();
14919 self.fold_creases(ranges, auto_scroll, window, cx);
14920 }
14921
14922 pub fn fold_creases<T: ToOffset + Clone>(
14923 &mut self,
14924 creases: Vec<Crease<T>>,
14925 auto_scroll: bool,
14926 window: &mut Window,
14927 cx: &mut Context<Self>,
14928 ) {
14929 if creases.is_empty() {
14930 return;
14931 }
14932
14933 let mut buffers_affected = HashSet::default();
14934 let multi_buffer = self.buffer().read(cx);
14935 for crease in &creases {
14936 if let Some((_, buffer, _)) =
14937 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14938 {
14939 buffers_affected.insert(buffer.read(cx).remote_id());
14940 };
14941 }
14942
14943 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14944
14945 if auto_scroll {
14946 self.request_autoscroll(Autoscroll::fit(), cx);
14947 }
14948
14949 cx.notify();
14950
14951 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14952 // Clear diagnostics block when folding a range that contains it.
14953 let snapshot = self.snapshot(window, cx);
14954 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14955 drop(snapshot);
14956 self.active_diagnostics = Some(active_diagnostics);
14957 self.dismiss_diagnostics(cx);
14958 } else {
14959 self.active_diagnostics = Some(active_diagnostics);
14960 }
14961 }
14962
14963 self.scrollbar_marker_state.dirty = true;
14964 self.folds_did_change(cx);
14965 }
14966
14967 /// Removes any folds whose ranges intersect any of the given ranges.
14968 pub fn unfold_ranges<T: ToOffset + Clone>(
14969 &mut self,
14970 ranges: &[Range<T>],
14971 inclusive: bool,
14972 auto_scroll: bool,
14973 cx: &mut Context<Self>,
14974 ) {
14975 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14976 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14977 });
14978 self.folds_did_change(cx);
14979 }
14980
14981 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14982 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14983 return;
14984 }
14985 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14986 self.display_map.update(cx, |display_map, cx| {
14987 display_map.fold_buffers([buffer_id], cx)
14988 });
14989 cx.emit(EditorEvent::BufferFoldToggled {
14990 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14991 folded: true,
14992 });
14993 cx.notify();
14994 }
14995
14996 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14997 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14998 return;
14999 }
15000 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15001 self.display_map.update(cx, |display_map, cx| {
15002 display_map.unfold_buffers([buffer_id], cx);
15003 });
15004 cx.emit(EditorEvent::BufferFoldToggled {
15005 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15006 folded: false,
15007 });
15008 cx.notify();
15009 }
15010
15011 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15012 self.display_map.read(cx).is_buffer_folded(buffer)
15013 }
15014
15015 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15016 self.display_map.read(cx).folded_buffers()
15017 }
15018
15019 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15020 self.display_map.update(cx, |display_map, cx| {
15021 display_map.disable_header_for_buffer(buffer_id, cx);
15022 });
15023 cx.notify();
15024 }
15025
15026 /// Removes any folds with the given ranges.
15027 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15028 &mut self,
15029 ranges: &[Range<T>],
15030 type_id: TypeId,
15031 auto_scroll: bool,
15032 cx: &mut Context<Self>,
15033 ) {
15034 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15035 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15036 });
15037 self.folds_did_change(cx);
15038 }
15039
15040 fn remove_folds_with<T: ToOffset + Clone>(
15041 &mut self,
15042 ranges: &[Range<T>],
15043 auto_scroll: bool,
15044 cx: &mut Context<Self>,
15045 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15046 ) {
15047 if ranges.is_empty() {
15048 return;
15049 }
15050
15051 let mut buffers_affected = HashSet::default();
15052 let multi_buffer = self.buffer().read(cx);
15053 for range in ranges {
15054 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15055 buffers_affected.insert(buffer.read(cx).remote_id());
15056 };
15057 }
15058
15059 self.display_map.update(cx, update);
15060
15061 if auto_scroll {
15062 self.request_autoscroll(Autoscroll::fit(), cx);
15063 }
15064
15065 cx.notify();
15066 self.scrollbar_marker_state.dirty = true;
15067 self.active_indent_guides_state.dirty = true;
15068 }
15069
15070 pub fn update_fold_widths(
15071 &mut self,
15072 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15073 cx: &mut Context<Self>,
15074 ) -> bool {
15075 self.display_map
15076 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15077 }
15078
15079 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15080 self.display_map.read(cx).fold_placeholder.clone()
15081 }
15082
15083 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15084 self.buffer.update(cx, |buffer, cx| {
15085 buffer.set_all_diff_hunks_expanded(cx);
15086 });
15087 }
15088
15089 pub fn expand_all_diff_hunks(
15090 &mut self,
15091 _: &ExpandAllDiffHunks,
15092 _window: &mut Window,
15093 cx: &mut Context<Self>,
15094 ) {
15095 self.buffer.update(cx, |buffer, cx| {
15096 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15097 });
15098 }
15099
15100 pub fn toggle_selected_diff_hunks(
15101 &mut self,
15102 _: &ToggleSelectedDiffHunks,
15103 _window: &mut Window,
15104 cx: &mut Context<Self>,
15105 ) {
15106 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15107 self.toggle_diff_hunks_in_ranges(ranges, cx);
15108 }
15109
15110 pub fn diff_hunks_in_ranges<'a>(
15111 &'a self,
15112 ranges: &'a [Range<Anchor>],
15113 buffer: &'a MultiBufferSnapshot,
15114 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15115 ranges.iter().flat_map(move |range| {
15116 let end_excerpt_id = range.end.excerpt_id;
15117 let range = range.to_point(buffer);
15118 let mut peek_end = range.end;
15119 if range.end.row < buffer.max_row().0 {
15120 peek_end = Point::new(range.end.row + 1, 0);
15121 }
15122 buffer
15123 .diff_hunks_in_range(range.start..peek_end)
15124 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15125 })
15126 }
15127
15128 pub fn has_stageable_diff_hunks_in_ranges(
15129 &self,
15130 ranges: &[Range<Anchor>],
15131 snapshot: &MultiBufferSnapshot,
15132 ) -> bool {
15133 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15134 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15135 }
15136
15137 pub fn toggle_staged_selected_diff_hunks(
15138 &mut self,
15139 _: &::git::ToggleStaged,
15140 _: &mut Window,
15141 cx: &mut Context<Self>,
15142 ) {
15143 let snapshot = self.buffer.read(cx).snapshot(cx);
15144 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15145 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15146 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15147 }
15148
15149 pub fn set_render_diff_hunk_controls(
15150 &mut self,
15151 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15152 cx: &mut Context<Self>,
15153 ) {
15154 self.render_diff_hunk_controls = render_diff_hunk_controls;
15155 cx.notify();
15156 }
15157
15158 pub fn stage_and_next(
15159 &mut self,
15160 _: &::git::StageAndNext,
15161 window: &mut Window,
15162 cx: &mut Context<Self>,
15163 ) {
15164 self.do_stage_or_unstage_and_next(true, window, cx);
15165 }
15166
15167 pub fn unstage_and_next(
15168 &mut self,
15169 _: &::git::UnstageAndNext,
15170 window: &mut Window,
15171 cx: &mut Context<Self>,
15172 ) {
15173 self.do_stage_or_unstage_and_next(false, window, cx);
15174 }
15175
15176 pub fn stage_or_unstage_diff_hunks(
15177 &mut self,
15178 stage: bool,
15179 ranges: Vec<Range<Anchor>>,
15180 cx: &mut Context<Self>,
15181 ) {
15182 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15183 cx.spawn(async move |this, cx| {
15184 task.await?;
15185 this.update(cx, |this, cx| {
15186 let snapshot = this.buffer.read(cx).snapshot(cx);
15187 let chunk_by = this
15188 .diff_hunks_in_ranges(&ranges, &snapshot)
15189 .chunk_by(|hunk| hunk.buffer_id);
15190 for (buffer_id, hunks) in &chunk_by {
15191 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15192 }
15193 })
15194 })
15195 .detach_and_log_err(cx);
15196 }
15197
15198 fn save_buffers_for_ranges_if_needed(
15199 &mut self,
15200 ranges: &[Range<Anchor>],
15201 cx: &mut Context<Editor>,
15202 ) -> Task<Result<()>> {
15203 let multibuffer = self.buffer.read(cx);
15204 let snapshot = multibuffer.read(cx);
15205 let buffer_ids: HashSet<_> = ranges
15206 .iter()
15207 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15208 .collect();
15209 drop(snapshot);
15210
15211 let mut buffers = HashSet::default();
15212 for buffer_id in buffer_ids {
15213 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15214 let buffer = buffer_entity.read(cx);
15215 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15216 {
15217 buffers.insert(buffer_entity);
15218 }
15219 }
15220 }
15221
15222 if let Some(project) = &self.project {
15223 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15224 } else {
15225 Task::ready(Ok(()))
15226 }
15227 }
15228
15229 fn do_stage_or_unstage_and_next(
15230 &mut self,
15231 stage: bool,
15232 window: &mut Window,
15233 cx: &mut Context<Self>,
15234 ) {
15235 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15236
15237 if ranges.iter().any(|range| range.start != range.end) {
15238 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15239 return;
15240 }
15241
15242 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15243 let snapshot = self.snapshot(window, cx);
15244 let position = self.selections.newest::<Point>(cx).head();
15245 let mut row = snapshot
15246 .buffer_snapshot
15247 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15248 .find(|hunk| hunk.row_range.start.0 > position.row)
15249 .map(|hunk| hunk.row_range.start);
15250
15251 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15252 // Outside of the project diff editor, wrap around to the beginning.
15253 if !all_diff_hunks_expanded {
15254 row = row.or_else(|| {
15255 snapshot
15256 .buffer_snapshot
15257 .diff_hunks_in_range(Point::zero()..position)
15258 .find(|hunk| hunk.row_range.end.0 < position.row)
15259 .map(|hunk| hunk.row_range.start)
15260 });
15261 }
15262
15263 if let Some(row) = row {
15264 let destination = Point::new(row.0, 0);
15265 let autoscroll = Autoscroll::center();
15266
15267 self.unfold_ranges(&[destination..destination], false, false, cx);
15268 self.change_selections(Some(autoscroll), window, cx, |s| {
15269 s.select_ranges([destination..destination]);
15270 });
15271 }
15272 }
15273
15274 fn do_stage_or_unstage(
15275 &self,
15276 stage: bool,
15277 buffer_id: BufferId,
15278 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15279 cx: &mut App,
15280 ) -> Option<()> {
15281 let project = self.project.as_ref()?;
15282 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15283 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15284 let buffer_snapshot = buffer.read(cx).snapshot();
15285 let file_exists = buffer_snapshot
15286 .file()
15287 .is_some_and(|file| file.disk_state().exists());
15288 diff.update(cx, |diff, cx| {
15289 diff.stage_or_unstage_hunks(
15290 stage,
15291 &hunks
15292 .map(|hunk| buffer_diff::DiffHunk {
15293 buffer_range: hunk.buffer_range,
15294 diff_base_byte_range: hunk.diff_base_byte_range,
15295 secondary_status: hunk.secondary_status,
15296 range: Point::zero()..Point::zero(), // unused
15297 })
15298 .collect::<Vec<_>>(),
15299 &buffer_snapshot,
15300 file_exists,
15301 cx,
15302 )
15303 });
15304 None
15305 }
15306
15307 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15308 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15309 self.buffer
15310 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15311 }
15312
15313 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15314 self.buffer.update(cx, |buffer, cx| {
15315 let ranges = vec![Anchor::min()..Anchor::max()];
15316 if !buffer.all_diff_hunks_expanded()
15317 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15318 {
15319 buffer.collapse_diff_hunks(ranges, cx);
15320 true
15321 } else {
15322 false
15323 }
15324 })
15325 }
15326
15327 fn toggle_diff_hunks_in_ranges(
15328 &mut self,
15329 ranges: Vec<Range<Anchor>>,
15330 cx: &mut Context<Editor>,
15331 ) {
15332 self.buffer.update(cx, |buffer, cx| {
15333 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15334 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15335 })
15336 }
15337
15338 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15339 self.buffer.update(cx, |buffer, cx| {
15340 let snapshot = buffer.snapshot(cx);
15341 let excerpt_id = range.end.excerpt_id;
15342 let point_range = range.to_point(&snapshot);
15343 let expand = !buffer.single_hunk_is_expanded(range, cx);
15344 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15345 })
15346 }
15347
15348 pub(crate) fn apply_all_diff_hunks(
15349 &mut self,
15350 _: &ApplyAllDiffHunks,
15351 window: &mut Window,
15352 cx: &mut Context<Self>,
15353 ) {
15354 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15355
15356 let buffers = self.buffer.read(cx).all_buffers();
15357 for branch_buffer in buffers {
15358 branch_buffer.update(cx, |branch_buffer, cx| {
15359 branch_buffer.merge_into_base(Vec::new(), cx);
15360 });
15361 }
15362
15363 if let Some(project) = self.project.clone() {
15364 self.save(true, project, window, cx).detach_and_log_err(cx);
15365 }
15366 }
15367
15368 pub(crate) fn apply_selected_diff_hunks(
15369 &mut self,
15370 _: &ApplyDiffHunk,
15371 window: &mut Window,
15372 cx: &mut Context<Self>,
15373 ) {
15374 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15375 let snapshot = self.snapshot(window, cx);
15376 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15377 let mut ranges_by_buffer = HashMap::default();
15378 self.transact(window, cx, |editor, _window, cx| {
15379 for hunk in hunks {
15380 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15381 ranges_by_buffer
15382 .entry(buffer.clone())
15383 .or_insert_with(Vec::new)
15384 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15385 }
15386 }
15387
15388 for (buffer, ranges) in ranges_by_buffer {
15389 buffer.update(cx, |buffer, cx| {
15390 buffer.merge_into_base(ranges, cx);
15391 });
15392 }
15393 });
15394
15395 if let Some(project) = self.project.clone() {
15396 self.save(true, project, window, cx).detach_and_log_err(cx);
15397 }
15398 }
15399
15400 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15401 if hovered != self.gutter_hovered {
15402 self.gutter_hovered = hovered;
15403 cx.notify();
15404 }
15405 }
15406
15407 pub fn insert_blocks(
15408 &mut self,
15409 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15410 autoscroll: Option<Autoscroll>,
15411 cx: &mut Context<Self>,
15412 ) -> Vec<CustomBlockId> {
15413 let blocks = self
15414 .display_map
15415 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15416 if let Some(autoscroll) = autoscroll {
15417 self.request_autoscroll(autoscroll, cx);
15418 }
15419 cx.notify();
15420 blocks
15421 }
15422
15423 pub fn resize_blocks(
15424 &mut self,
15425 heights: HashMap<CustomBlockId, u32>,
15426 autoscroll: Option<Autoscroll>,
15427 cx: &mut Context<Self>,
15428 ) {
15429 self.display_map
15430 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15431 if let Some(autoscroll) = autoscroll {
15432 self.request_autoscroll(autoscroll, cx);
15433 }
15434 cx.notify();
15435 }
15436
15437 pub fn replace_blocks(
15438 &mut self,
15439 renderers: HashMap<CustomBlockId, RenderBlock>,
15440 autoscroll: Option<Autoscroll>,
15441 cx: &mut Context<Self>,
15442 ) {
15443 self.display_map
15444 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15445 if let Some(autoscroll) = autoscroll {
15446 self.request_autoscroll(autoscroll, cx);
15447 }
15448 cx.notify();
15449 }
15450
15451 pub fn remove_blocks(
15452 &mut self,
15453 block_ids: HashSet<CustomBlockId>,
15454 autoscroll: Option<Autoscroll>,
15455 cx: &mut Context<Self>,
15456 ) {
15457 self.display_map.update(cx, |display_map, cx| {
15458 display_map.remove_blocks(block_ids, cx)
15459 });
15460 if let Some(autoscroll) = autoscroll {
15461 self.request_autoscroll(autoscroll, cx);
15462 }
15463 cx.notify();
15464 }
15465
15466 pub fn row_for_block(
15467 &self,
15468 block_id: CustomBlockId,
15469 cx: &mut Context<Self>,
15470 ) -> Option<DisplayRow> {
15471 self.display_map
15472 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15473 }
15474
15475 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15476 self.focused_block = Some(focused_block);
15477 }
15478
15479 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15480 self.focused_block.take()
15481 }
15482
15483 pub fn insert_creases(
15484 &mut self,
15485 creases: impl IntoIterator<Item = Crease<Anchor>>,
15486 cx: &mut Context<Self>,
15487 ) -> Vec<CreaseId> {
15488 self.display_map
15489 .update(cx, |map, cx| map.insert_creases(creases, cx))
15490 }
15491
15492 pub fn remove_creases(
15493 &mut self,
15494 ids: impl IntoIterator<Item = CreaseId>,
15495 cx: &mut Context<Self>,
15496 ) {
15497 self.display_map
15498 .update(cx, |map, cx| map.remove_creases(ids, cx));
15499 }
15500
15501 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15502 self.display_map
15503 .update(cx, |map, cx| map.snapshot(cx))
15504 .longest_row()
15505 }
15506
15507 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15508 self.display_map
15509 .update(cx, |map, cx| map.snapshot(cx))
15510 .max_point()
15511 }
15512
15513 pub fn text(&self, cx: &App) -> String {
15514 self.buffer.read(cx).read(cx).text()
15515 }
15516
15517 pub fn is_empty(&self, cx: &App) -> bool {
15518 self.buffer.read(cx).read(cx).is_empty()
15519 }
15520
15521 pub fn text_option(&self, cx: &App) -> Option<String> {
15522 let text = self.text(cx);
15523 let text = text.trim();
15524
15525 if text.is_empty() {
15526 return None;
15527 }
15528
15529 Some(text.to_string())
15530 }
15531
15532 pub fn set_text(
15533 &mut self,
15534 text: impl Into<Arc<str>>,
15535 window: &mut Window,
15536 cx: &mut Context<Self>,
15537 ) {
15538 self.transact(window, cx, |this, _, cx| {
15539 this.buffer
15540 .read(cx)
15541 .as_singleton()
15542 .expect("you can only call set_text on editors for singleton buffers")
15543 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15544 });
15545 }
15546
15547 pub fn display_text(&self, cx: &mut App) -> String {
15548 self.display_map
15549 .update(cx, |map, cx| map.snapshot(cx))
15550 .text()
15551 }
15552
15553 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15554 let mut wrap_guides = smallvec::smallvec![];
15555
15556 if self.show_wrap_guides == Some(false) {
15557 return wrap_guides;
15558 }
15559
15560 let settings = self.buffer.read(cx).language_settings(cx);
15561 if settings.show_wrap_guides {
15562 match self.soft_wrap_mode(cx) {
15563 SoftWrap::Column(soft_wrap) => {
15564 wrap_guides.push((soft_wrap as usize, true));
15565 }
15566 SoftWrap::Bounded(soft_wrap) => {
15567 wrap_guides.push((soft_wrap as usize, true));
15568 }
15569 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15570 }
15571 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15572 }
15573
15574 wrap_guides
15575 }
15576
15577 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15578 let settings = self.buffer.read(cx).language_settings(cx);
15579 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15580 match mode {
15581 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15582 SoftWrap::None
15583 }
15584 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15585 language_settings::SoftWrap::PreferredLineLength => {
15586 SoftWrap::Column(settings.preferred_line_length)
15587 }
15588 language_settings::SoftWrap::Bounded => {
15589 SoftWrap::Bounded(settings.preferred_line_length)
15590 }
15591 }
15592 }
15593
15594 pub fn set_soft_wrap_mode(
15595 &mut self,
15596 mode: language_settings::SoftWrap,
15597
15598 cx: &mut Context<Self>,
15599 ) {
15600 self.soft_wrap_mode_override = Some(mode);
15601 cx.notify();
15602 }
15603
15604 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15605 self.hard_wrap = hard_wrap;
15606 cx.notify();
15607 }
15608
15609 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15610 self.text_style_refinement = Some(style);
15611 }
15612
15613 /// called by the Element so we know what style we were most recently rendered with.
15614 pub(crate) fn set_style(
15615 &mut self,
15616 style: EditorStyle,
15617 window: &mut Window,
15618 cx: &mut Context<Self>,
15619 ) {
15620 let rem_size = window.rem_size();
15621 self.display_map.update(cx, |map, cx| {
15622 map.set_font(
15623 style.text.font(),
15624 style.text.font_size.to_pixels(rem_size),
15625 cx,
15626 )
15627 });
15628 self.style = Some(style);
15629 }
15630
15631 pub fn style(&self) -> Option<&EditorStyle> {
15632 self.style.as_ref()
15633 }
15634
15635 // Called by the element. This method is not designed to be called outside of the editor
15636 // element's layout code because it does not notify when rewrapping is computed synchronously.
15637 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15638 self.display_map
15639 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15640 }
15641
15642 pub fn set_soft_wrap(&mut self) {
15643 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15644 }
15645
15646 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15647 if self.soft_wrap_mode_override.is_some() {
15648 self.soft_wrap_mode_override.take();
15649 } else {
15650 let soft_wrap = match self.soft_wrap_mode(cx) {
15651 SoftWrap::GitDiff => return,
15652 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15653 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15654 language_settings::SoftWrap::None
15655 }
15656 };
15657 self.soft_wrap_mode_override = Some(soft_wrap);
15658 }
15659 cx.notify();
15660 }
15661
15662 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15663 let Some(workspace) = self.workspace() else {
15664 return;
15665 };
15666 let fs = workspace.read(cx).app_state().fs.clone();
15667 let current_show = TabBarSettings::get_global(cx).show;
15668 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15669 setting.show = Some(!current_show);
15670 });
15671 }
15672
15673 pub fn toggle_indent_guides(
15674 &mut self,
15675 _: &ToggleIndentGuides,
15676 _: &mut Window,
15677 cx: &mut Context<Self>,
15678 ) {
15679 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15680 self.buffer
15681 .read(cx)
15682 .language_settings(cx)
15683 .indent_guides
15684 .enabled
15685 });
15686 self.show_indent_guides = Some(!currently_enabled);
15687 cx.notify();
15688 }
15689
15690 fn should_show_indent_guides(&self) -> Option<bool> {
15691 self.show_indent_guides
15692 }
15693
15694 pub fn toggle_line_numbers(
15695 &mut self,
15696 _: &ToggleLineNumbers,
15697 _: &mut Window,
15698 cx: &mut Context<Self>,
15699 ) {
15700 let mut editor_settings = EditorSettings::get_global(cx).clone();
15701 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15702 EditorSettings::override_global(editor_settings, cx);
15703 }
15704
15705 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15706 if let Some(show_line_numbers) = self.show_line_numbers {
15707 return show_line_numbers;
15708 }
15709 EditorSettings::get_global(cx).gutter.line_numbers
15710 }
15711
15712 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15713 self.use_relative_line_numbers
15714 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15715 }
15716
15717 pub fn toggle_relative_line_numbers(
15718 &mut self,
15719 _: &ToggleRelativeLineNumbers,
15720 _: &mut Window,
15721 cx: &mut Context<Self>,
15722 ) {
15723 let is_relative = self.should_use_relative_line_numbers(cx);
15724 self.set_relative_line_number(Some(!is_relative), cx)
15725 }
15726
15727 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15728 self.use_relative_line_numbers = is_relative;
15729 cx.notify();
15730 }
15731
15732 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15733 self.show_gutter = show_gutter;
15734 cx.notify();
15735 }
15736
15737 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15738 self.show_scrollbars = show_scrollbars;
15739 cx.notify();
15740 }
15741
15742 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15743 self.show_line_numbers = Some(show_line_numbers);
15744 cx.notify();
15745 }
15746
15747 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15748 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15749 cx.notify();
15750 }
15751
15752 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15753 self.show_code_actions = Some(show_code_actions);
15754 cx.notify();
15755 }
15756
15757 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15758 self.show_runnables = Some(show_runnables);
15759 cx.notify();
15760 }
15761
15762 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15763 self.show_breakpoints = Some(show_breakpoints);
15764 cx.notify();
15765 }
15766
15767 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15768 if self.display_map.read(cx).masked != masked {
15769 self.display_map.update(cx, |map, _| map.masked = masked);
15770 }
15771 cx.notify()
15772 }
15773
15774 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15775 self.show_wrap_guides = Some(show_wrap_guides);
15776 cx.notify();
15777 }
15778
15779 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15780 self.show_indent_guides = Some(show_indent_guides);
15781 cx.notify();
15782 }
15783
15784 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15785 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15786 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15787 if let Some(dir) = file.abs_path(cx).parent() {
15788 return Some(dir.to_owned());
15789 }
15790 }
15791
15792 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15793 return Some(project_path.path.to_path_buf());
15794 }
15795 }
15796
15797 None
15798 }
15799
15800 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15801 self.active_excerpt(cx)?
15802 .1
15803 .read(cx)
15804 .file()
15805 .and_then(|f| f.as_local())
15806 }
15807
15808 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15809 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15810 let buffer = buffer.read(cx);
15811 if let Some(project_path) = buffer.project_path(cx) {
15812 let project = self.project.as_ref()?.read(cx);
15813 project.absolute_path(&project_path, cx)
15814 } else {
15815 buffer
15816 .file()
15817 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15818 }
15819 })
15820 }
15821
15822 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15823 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15824 let project_path = buffer.read(cx).project_path(cx)?;
15825 let project = self.project.as_ref()?.read(cx);
15826 let entry = project.entry_for_path(&project_path, cx)?;
15827 let path = entry.path.to_path_buf();
15828 Some(path)
15829 })
15830 }
15831
15832 pub fn reveal_in_finder(
15833 &mut self,
15834 _: &RevealInFileManager,
15835 _window: &mut Window,
15836 cx: &mut Context<Self>,
15837 ) {
15838 if let Some(target) = self.target_file(cx) {
15839 cx.reveal_path(&target.abs_path(cx));
15840 }
15841 }
15842
15843 pub fn copy_path(
15844 &mut self,
15845 _: &zed_actions::workspace::CopyPath,
15846 _window: &mut Window,
15847 cx: &mut Context<Self>,
15848 ) {
15849 if let Some(path) = self.target_file_abs_path(cx) {
15850 if let Some(path) = path.to_str() {
15851 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15852 }
15853 }
15854 }
15855
15856 pub fn copy_relative_path(
15857 &mut self,
15858 _: &zed_actions::workspace::CopyRelativePath,
15859 _window: &mut Window,
15860 cx: &mut Context<Self>,
15861 ) {
15862 if let Some(path) = self.target_file_path(cx) {
15863 if let Some(path) = path.to_str() {
15864 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15865 }
15866 }
15867 }
15868
15869 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15870 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15871 buffer.read(cx).project_path(cx)
15872 } else {
15873 None
15874 }
15875 }
15876
15877 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15878 let _ = maybe!({
15879 let breakpoint_store = self.breakpoint_store.as_ref()?;
15880
15881 let Some((_, _, active_position)) =
15882 breakpoint_store.read(cx).active_position().cloned()
15883 else {
15884 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15885 return None;
15886 };
15887
15888 let snapshot = self
15889 .project
15890 .as_ref()?
15891 .read(cx)
15892 .buffer_for_id(active_position.buffer_id?, cx)?
15893 .read(cx)
15894 .snapshot();
15895
15896 for (id, ExcerptRange { context, .. }) in self
15897 .buffer
15898 .read(cx)
15899 .excerpts_for_buffer(active_position.buffer_id?, cx)
15900 {
15901 if context.start.cmp(&active_position, &snapshot).is_ge()
15902 || context.end.cmp(&active_position, &snapshot).is_lt()
15903 {
15904 continue;
15905 }
15906 let snapshot = self.buffer.read(cx).snapshot(cx);
15907 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15908
15909 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15910 self.go_to_line::<DebugCurrentRowHighlight>(
15911 multibuffer_anchor,
15912 Some(cx.theme().colors().editor_debugger_active_line_background),
15913 window,
15914 cx,
15915 );
15916
15917 cx.notify();
15918 }
15919
15920 Some(())
15921 });
15922 }
15923
15924 pub fn copy_file_name_without_extension(
15925 &mut self,
15926 _: &CopyFileNameWithoutExtension,
15927 _: &mut Window,
15928 cx: &mut Context<Self>,
15929 ) {
15930 if let Some(file) = self.target_file(cx) {
15931 if let Some(file_stem) = file.path().file_stem() {
15932 if let Some(name) = file_stem.to_str() {
15933 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15934 }
15935 }
15936 }
15937 }
15938
15939 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15940 if let Some(file) = self.target_file(cx) {
15941 if let Some(file_name) = file.path().file_name() {
15942 if let Some(name) = file_name.to_str() {
15943 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15944 }
15945 }
15946 }
15947 }
15948
15949 pub fn toggle_git_blame(
15950 &mut self,
15951 _: &::git::Blame,
15952 window: &mut Window,
15953 cx: &mut Context<Self>,
15954 ) {
15955 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15956
15957 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15958 self.start_git_blame(true, window, cx);
15959 }
15960
15961 cx.notify();
15962 }
15963
15964 pub fn toggle_git_blame_inline(
15965 &mut self,
15966 _: &ToggleGitBlameInline,
15967 window: &mut Window,
15968 cx: &mut Context<Self>,
15969 ) {
15970 self.toggle_git_blame_inline_internal(true, window, cx);
15971 cx.notify();
15972 }
15973
15974 pub fn open_git_blame_commit(
15975 &mut self,
15976 _: &OpenGitBlameCommit,
15977 window: &mut Window,
15978 cx: &mut Context<Self>,
15979 ) {
15980 self.open_git_blame_commit_internal(window, cx);
15981 }
15982
15983 fn open_git_blame_commit_internal(
15984 &mut self,
15985 window: &mut Window,
15986 cx: &mut Context<Self>,
15987 ) -> Option<()> {
15988 let blame = self.blame.as_ref()?;
15989 let snapshot = self.snapshot(window, cx);
15990 let cursor = self.selections.newest::<Point>(cx).head();
15991 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
15992 let blame_entry = blame
15993 .update(cx, |blame, cx| {
15994 blame
15995 .blame_for_rows(
15996 &[RowInfo {
15997 buffer_id: Some(buffer.remote_id()),
15998 buffer_row: Some(point.row),
15999 ..Default::default()
16000 }],
16001 cx,
16002 )
16003 .next()
16004 })
16005 .flatten()?;
16006 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16007 let repo = blame.read(cx).repository(cx)?;
16008 let workspace = self.workspace()?.downgrade();
16009 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16010 None
16011 }
16012
16013 pub fn git_blame_inline_enabled(&self) -> bool {
16014 self.git_blame_inline_enabled
16015 }
16016
16017 pub fn toggle_selection_menu(
16018 &mut self,
16019 _: &ToggleSelectionMenu,
16020 _: &mut Window,
16021 cx: &mut Context<Self>,
16022 ) {
16023 self.show_selection_menu = self
16024 .show_selection_menu
16025 .map(|show_selections_menu| !show_selections_menu)
16026 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16027
16028 cx.notify();
16029 }
16030
16031 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16032 self.show_selection_menu
16033 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16034 }
16035
16036 fn start_git_blame(
16037 &mut self,
16038 user_triggered: bool,
16039 window: &mut Window,
16040 cx: &mut Context<Self>,
16041 ) {
16042 if let Some(project) = self.project.as_ref() {
16043 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16044 return;
16045 };
16046
16047 if buffer.read(cx).file().is_none() {
16048 return;
16049 }
16050
16051 let focused = self.focus_handle(cx).contains_focused(window, cx);
16052
16053 let project = project.clone();
16054 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16055 self.blame_subscription =
16056 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16057 self.blame = Some(blame);
16058 }
16059 }
16060
16061 fn toggle_git_blame_inline_internal(
16062 &mut self,
16063 user_triggered: bool,
16064 window: &mut Window,
16065 cx: &mut Context<Self>,
16066 ) {
16067 if self.git_blame_inline_enabled {
16068 self.git_blame_inline_enabled = false;
16069 self.show_git_blame_inline = false;
16070 self.show_git_blame_inline_delay_task.take();
16071 } else {
16072 self.git_blame_inline_enabled = true;
16073 self.start_git_blame_inline(user_triggered, window, cx);
16074 }
16075
16076 cx.notify();
16077 }
16078
16079 fn start_git_blame_inline(
16080 &mut self,
16081 user_triggered: bool,
16082 window: &mut Window,
16083 cx: &mut Context<Self>,
16084 ) {
16085 self.start_git_blame(user_triggered, window, cx);
16086
16087 if ProjectSettings::get_global(cx)
16088 .git
16089 .inline_blame_delay()
16090 .is_some()
16091 {
16092 self.start_inline_blame_timer(window, cx);
16093 } else {
16094 self.show_git_blame_inline = true
16095 }
16096 }
16097
16098 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16099 self.blame.as_ref()
16100 }
16101
16102 pub fn show_git_blame_gutter(&self) -> bool {
16103 self.show_git_blame_gutter
16104 }
16105
16106 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16107 self.show_git_blame_gutter && self.has_blame_entries(cx)
16108 }
16109
16110 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16111 self.show_git_blame_inline
16112 && (self.focus_handle.is_focused(window)
16113 || self
16114 .git_blame_inline_tooltip
16115 .as_ref()
16116 .and_then(|t| t.upgrade())
16117 .is_some())
16118 && !self.newest_selection_head_on_empty_line(cx)
16119 && self.has_blame_entries(cx)
16120 }
16121
16122 fn has_blame_entries(&self, cx: &App) -> bool {
16123 self.blame()
16124 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16125 }
16126
16127 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16128 let cursor_anchor = self.selections.newest_anchor().head();
16129
16130 let snapshot = self.buffer.read(cx).snapshot(cx);
16131 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16132
16133 snapshot.line_len(buffer_row) == 0
16134 }
16135
16136 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16137 let buffer_and_selection = maybe!({
16138 let selection = self.selections.newest::<Point>(cx);
16139 let selection_range = selection.range();
16140
16141 let multi_buffer = self.buffer().read(cx);
16142 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16143 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16144
16145 let (buffer, range, _) = if selection.reversed {
16146 buffer_ranges.first()
16147 } else {
16148 buffer_ranges.last()
16149 }?;
16150
16151 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16152 ..text::ToPoint::to_point(&range.end, &buffer).row;
16153 Some((
16154 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16155 selection,
16156 ))
16157 });
16158
16159 let Some((buffer, selection)) = buffer_and_selection else {
16160 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16161 };
16162
16163 let Some(project) = self.project.as_ref() else {
16164 return Task::ready(Err(anyhow!("editor does not have project")));
16165 };
16166
16167 project.update(cx, |project, cx| {
16168 project.get_permalink_to_line(&buffer, selection, cx)
16169 })
16170 }
16171
16172 pub fn copy_permalink_to_line(
16173 &mut self,
16174 _: &CopyPermalinkToLine,
16175 window: &mut Window,
16176 cx: &mut Context<Self>,
16177 ) {
16178 let permalink_task = self.get_permalink_to_line(cx);
16179 let workspace = self.workspace();
16180
16181 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16182 Ok(permalink) => {
16183 cx.update(|_, cx| {
16184 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16185 })
16186 .ok();
16187 }
16188 Err(err) => {
16189 let message = format!("Failed to copy permalink: {err}");
16190
16191 Err::<(), anyhow::Error>(err).log_err();
16192
16193 if let Some(workspace) = workspace {
16194 workspace
16195 .update_in(cx, |workspace, _, cx| {
16196 struct CopyPermalinkToLine;
16197
16198 workspace.show_toast(
16199 Toast::new(
16200 NotificationId::unique::<CopyPermalinkToLine>(),
16201 message,
16202 ),
16203 cx,
16204 )
16205 })
16206 .ok();
16207 }
16208 }
16209 })
16210 .detach();
16211 }
16212
16213 pub fn copy_file_location(
16214 &mut self,
16215 _: &CopyFileLocation,
16216 _: &mut Window,
16217 cx: &mut Context<Self>,
16218 ) {
16219 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16220 if let Some(file) = self.target_file(cx) {
16221 if let Some(path) = file.path().to_str() {
16222 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16223 }
16224 }
16225 }
16226
16227 pub fn open_permalink_to_line(
16228 &mut self,
16229 _: &OpenPermalinkToLine,
16230 window: &mut Window,
16231 cx: &mut Context<Self>,
16232 ) {
16233 let permalink_task = self.get_permalink_to_line(cx);
16234 let workspace = self.workspace();
16235
16236 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16237 Ok(permalink) => {
16238 cx.update(|_, cx| {
16239 cx.open_url(permalink.as_ref());
16240 })
16241 .ok();
16242 }
16243 Err(err) => {
16244 let message = format!("Failed to open permalink: {err}");
16245
16246 Err::<(), anyhow::Error>(err).log_err();
16247
16248 if let Some(workspace) = workspace {
16249 workspace
16250 .update(cx, |workspace, cx| {
16251 struct OpenPermalinkToLine;
16252
16253 workspace.show_toast(
16254 Toast::new(
16255 NotificationId::unique::<OpenPermalinkToLine>(),
16256 message,
16257 ),
16258 cx,
16259 )
16260 })
16261 .ok();
16262 }
16263 }
16264 })
16265 .detach();
16266 }
16267
16268 pub fn insert_uuid_v4(
16269 &mut self,
16270 _: &InsertUuidV4,
16271 window: &mut Window,
16272 cx: &mut Context<Self>,
16273 ) {
16274 self.insert_uuid(UuidVersion::V4, window, cx);
16275 }
16276
16277 pub fn insert_uuid_v7(
16278 &mut self,
16279 _: &InsertUuidV7,
16280 window: &mut Window,
16281 cx: &mut Context<Self>,
16282 ) {
16283 self.insert_uuid(UuidVersion::V7, window, cx);
16284 }
16285
16286 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16287 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16288 self.transact(window, cx, |this, window, cx| {
16289 let edits = this
16290 .selections
16291 .all::<Point>(cx)
16292 .into_iter()
16293 .map(|selection| {
16294 let uuid = match version {
16295 UuidVersion::V4 => uuid::Uuid::new_v4(),
16296 UuidVersion::V7 => uuid::Uuid::now_v7(),
16297 };
16298
16299 (selection.range(), uuid.to_string())
16300 });
16301 this.edit(edits, cx);
16302 this.refresh_inline_completion(true, false, window, cx);
16303 });
16304 }
16305
16306 pub fn open_selections_in_multibuffer(
16307 &mut self,
16308 _: &OpenSelectionsInMultibuffer,
16309 window: &mut Window,
16310 cx: &mut Context<Self>,
16311 ) {
16312 let multibuffer = self.buffer.read(cx);
16313
16314 let Some(buffer) = multibuffer.as_singleton() else {
16315 return;
16316 };
16317
16318 let Some(workspace) = self.workspace() else {
16319 return;
16320 };
16321
16322 let locations = self
16323 .selections
16324 .disjoint_anchors()
16325 .iter()
16326 .map(|range| Location {
16327 buffer: buffer.clone(),
16328 range: range.start.text_anchor..range.end.text_anchor,
16329 })
16330 .collect::<Vec<_>>();
16331
16332 let title = multibuffer.title(cx).to_string();
16333
16334 cx.spawn_in(window, async move |_, cx| {
16335 workspace.update_in(cx, |workspace, window, cx| {
16336 Self::open_locations_in_multibuffer(
16337 workspace,
16338 locations,
16339 format!("Selections for '{title}'"),
16340 false,
16341 MultibufferSelectionMode::All,
16342 window,
16343 cx,
16344 );
16345 })
16346 })
16347 .detach();
16348 }
16349
16350 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16351 /// last highlight added will be used.
16352 ///
16353 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16354 pub fn highlight_rows<T: 'static>(
16355 &mut self,
16356 range: Range<Anchor>,
16357 color: Hsla,
16358 should_autoscroll: bool,
16359 cx: &mut Context<Self>,
16360 ) {
16361 let snapshot = self.buffer().read(cx).snapshot(cx);
16362 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16363 let ix = row_highlights.binary_search_by(|highlight| {
16364 Ordering::Equal
16365 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16366 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16367 });
16368
16369 if let Err(mut ix) = ix {
16370 let index = post_inc(&mut self.highlight_order);
16371
16372 // If this range intersects with the preceding highlight, then merge it with
16373 // the preceding highlight. Otherwise insert a new highlight.
16374 let mut merged = false;
16375 if ix > 0 {
16376 let prev_highlight = &mut row_highlights[ix - 1];
16377 if prev_highlight
16378 .range
16379 .end
16380 .cmp(&range.start, &snapshot)
16381 .is_ge()
16382 {
16383 ix -= 1;
16384 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16385 prev_highlight.range.end = range.end;
16386 }
16387 merged = true;
16388 prev_highlight.index = index;
16389 prev_highlight.color = color;
16390 prev_highlight.should_autoscroll = should_autoscroll;
16391 }
16392 }
16393
16394 if !merged {
16395 row_highlights.insert(
16396 ix,
16397 RowHighlight {
16398 range: range.clone(),
16399 index,
16400 color,
16401 should_autoscroll,
16402 },
16403 );
16404 }
16405
16406 // If any of the following highlights intersect with this one, merge them.
16407 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16408 let highlight = &row_highlights[ix];
16409 if next_highlight
16410 .range
16411 .start
16412 .cmp(&highlight.range.end, &snapshot)
16413 .is_le()
16414 {
16415 if next_highlight
16416 .range
16417 .end
16418 .cmp(&highlight.range.end, &snapshot)
16419 .is_gt()
16420 {
16421 row_highlights[ix].range.end = next_highlight.range.end;
16422 }
16423 row_highlights.remove(ix + 1);
16424 } else {
16425 break;
16426 }
16427 }
16428 }
16429 }
16430
16431 /// Remove any highlighted row ranges of the given type that intersect the
16432 /// given ranges.
16433 pub fn remove_highlighted_rows<T: 'static>(
16434 &mut self,
16435 ranges_to_remove: Vec<Range<Anchor>>,
16436 cx: &mut Context<Self>,
16437 ) {
16438 let snapshot = self.buffer().read(cx).snapshot(cx);
16439 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16440 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16441 row_highlights.retain(|highlight| {
16442 while let Some(range_to_remove) = ranges_to_remove.peek() {
16443 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16444 Ordering::Less | Ordering::Equal => {
16445 ranges_to_remove.next();
16446 }
16447 Ordering::Greater => {
16448 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16449 Ordering::Less | Ordering::Equal => {
16450 return false;
16451 }
16452 Ordering::Greater => break,
16453 }
16454 }
16455 }
16456 }
16457
16458 true
16459 })
16460 }
16461
16462 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16463 pub fn clear_row_highlights<T: 'static>(&mut self) {
16464 self.highlighted_rows.remove(&TypeId::of::<T>());
16465 }
16466
16467 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16468 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16469 self.highlighted_rows
16470 .get(&TypeId::of::<T>())
16471 .map_or(&[] as &[_], |vec| vec.as_slice())
16472 .iter()
16473 .map(|highlight| (highlight.range.clone(), highlight.color))
16474 }
16475
16476 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16477 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16478 /// Allows to ignore certain kinds of highlights.
16479 pub fn highlighted_display_rows(
16480 &self,
16481 window: &mut Window,
16482 cx: &mut App,
16483 ) -> BTreeMap<DisplayRow, LineHighlight> {
16484 let snapshot = self.snapshot(window, cx);
16485 let mut used_highlight_orders = HashMap::default();
16486 self.highlighted_rows
16487 .iter()
16488 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16489 .fold(
16490 BTreeMap::<DisplayRow, LineHighlight>::new(),
16491 |mut unique_rows, highlight| {
16492 let start = highlight.range.start.to_display_point(&snapshot);
16493 let end = highlight.range.end.to_display_point(&snapshot);
16494 let start_row = start.row().0;
16495 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16496 && end.column() == 0
16497 {
16498 end.row().0.saturating_sub(1)
16499 } else {
16500 end.row().0
16501 };
16502 for row in start_row..=end_row {
16503 let used_index =
16504 used_highlight_orders.entry(row).or_insert(highlight.index);
16505 if highlight.index >= *used_index {
16506 *used_index = highlight.index;
16507 unique_rows.insert(DisplayRow(row), highlight.color.into());
16508 }
16509 }
16510 unique_rows
16511 },
16512 )
16513 }
16514
16515 pub fn highlighted_display_row_for_autoscroll(
16516 &self,
16517 snapshot: &DisplaySnapshot,
16518 ) -> Option<DisplayRow> {
16519 self.highlighted_rows
16520 .values()
16521 .flat_map(|highlighted_rows| highlighted_rows.iter())
16522 .filter_map(|highlight| {
16523 if highlight.should_autoscroll {
16524 Some(highlight.range.start.to_display_point(snapshot).row())
16525 } else {
16526 None
16527 }
16528 })
16529 .min()
16530 }
16531
16532 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16533 self.highlight_background::<SearchWithinRange>(
16534 ranges,
16535 |colors| colors.editor_document_highlight_read_background,
16536 cx,
16537 )
16538 }
16539
16540 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16541 self.breadcrumb_header = Some(new_header);
16542 }
16543
16544 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16545 self.clear_background_highlights::<SearchWithinRange>(cx);
16546 }
16547
16548 pub fn highlight_background<T: 'static>(
16549 &mut self,
16550 ranges: &[Range<Anchor>],
16551 color_fetcher: fn(&ThemeColors) -> Hsla,
16552 cx: &mut Context<Self>,
16553 ) {
16554 self.background_highlights
16555 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16556 self.scrollbar_marker_state.dirty = true;
16557 cx.notify();
16558 }
16559
16560 pub fn clear_background_highlights<T: 'static>(
16561 &mut self,
16562 cx: &mut Context<Self>,
16563 ) -> Option<BackgroundHighlight> {
16564 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16565 if !text_highlights.1.is_empty() {
16566 self.scrollbar_marker_state.dirty = true;
16567 cx.notify();
16568 }
16569 Some(text_highlights)
16570 }
16571
16572 pub fn highlight_gutter<T: 'static>(
16573 &mut self,
16574 ranges: &[Range<Anchor>],
16575 color_fetcher: fn(&App) -> Hsla,
16576 cx: &mut Context<Self>,
16577 ) {
16578 self.gutter_highlights
16579 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16580 cx.notify();
16581 }
16582
16583 pub fn clear_gutter_highlights<T: 'static>(
16584 &mut self,
16585 cx: &mut Context<Self>,
16586 ) -> Option<GutterHighlight> {
16587 cx.notify();
16588 self.gutter_highlights.remove(&TypeId::of::<T>())
16589 }
16590
16591 #[cfg(feature = "test-support")]
16592 pub fn all_text_background_highlights(
16593 &self,
16594 window: &mut Window,
16595 cx: &mut Context<Self>,
16596 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16597 let snapshot = self.snapshot(window, cx);
16598 let buffer = &snapshot.buffer_snapshot;
16599 let start = buffer.anchor_before(0);
16600 let end = buffer.anchor_after(buffer.len());
16601 let theme = cx.theme().colors();
16602 self.background_highlights_in_range(start..end, &snapshot, theme)
16603 }
16604
16605 #[cfg(feature = "test-support")]
16606 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16607 let snapshot = self.buffer().read(cx).snapshot(cx);
16608
16609 let highlights = self
16610 .background_highlights
16611 .get(&TypeId::of::<items::BufferSearchHighlights>());
16612
16613 if let Some((_color, ranges)) = highlights {
16614 ranges
16615 .iter()
16616 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16617 .collect_vec()
16618 } else {
16619 vec![]
16620 }
16621 }
16622
16623 fn document_highlights_for_position<'a>(
16624 &'a self,
16625 position: Anchor,
16626 buffer: &'a MultiBufferSnapshot,
16627 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16628 let read_highlights = self
16629 .background_highlights
16630 .get(&TypeId::of::<DocumentHighlightRead>())
16631 .map(|h| &h.1);
16632 let write_highlights = self
16633 .background_highlights
16634 .get(&TypeId::of::<DocumentHighlightWrite>())
16635 .map(|h| &h.1);
16636 let left_position = position.bias_left(buffer);
16637 let right_position = position.bias_right(buffer);
16638 read_highlights
16639 .into_iter()
16640 .chain(write_highlights)
16641 .flat_map(move |ranges| {
16642 let start_ix = match ranges.binary_search_by(|probe| {
16643 let cmp = probe.end.cmp(&left_position, buffer);
16644 if cmp.is_ge() {
16645 Ordering::Greater
16646 } else {
16647 Ordering::Less
16648 }
16649 }) {
16650 Ok(i) | Err(i) => i,
16651 };
16652
16653 ranges[start_ix..]
16654 .iter()
16655 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16656 })
16657 }
16658
16659 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16660 self.background_highlights
16661 .get(&TypeId::of::<T>())
16662 .map_or(false, |(_, highlights)| !highlights.is_empty())
16663 }
16664
16665 pub fn background_highlights_in_range(
16666 &self,
16667 search_range: Range<Anchor>,
16668 display_snapshot: &DisplaySnapshot,
16669 theme: &ThemeColors,
16670 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16671 let mut results = Vec::new();
16672 for (color_fetcher, ranges) in self.background_highlights.values() {
16673 let color = color_fetcher(theme);
16674 let start_ix = match ranges.binary_search_by(|probe| {
16675 let cmp = probe
16676 .end
16677 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16678 if cmp.is_gt() {
16679 Ordering::Greater
16680 } else {
16681 Ordering::Less
16682 }
16683 }) {
16684 Ok(i) | Err(i) => i,
16685 };
16686 for range in &ranges[start_ix..] {
16687 if range
16688 .start
16689 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16690 .is_ge()
16691 {
16692 break;
16693 }
16694
16695 let start = range.start.to_display_point(display_snapshot);
16696 let end = range.end.to_display_point(display_snapshot);
16697 results.push((start..end, color))
16698 }
16699 }
16700 results
16701 }
16702
16703 pub fn background_highlight_row_ranges<T: 'static>(
16704 &self,
16705 search_range: Range<Anchor>,
16706 display_snapshot: &DisplaySnapshot,
16707 count: usize,
16708 ) -> Vec<RangeInclusive<DisplayPoint>> {
16709 let mut results = Vec::new();
16710 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16711 return vec![];
16712 };
16713
16714 let start_ix = match ranges.binary_search_by(|probe| {
16715 let cmp = probe
16716 .end
16717 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16718 if cmp.is_gt() {
16719 Ordering::Greater
16720 } else {
16721 Ordering::Less
16722 }
16723 }) {
16724 Ok(i) | Err(i) => i,
16725 };
16726 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16727 if let (Some(start_display), Some(end_display)) = (start, end) {
16728 results.push(
16729 start_display.to_display_point(display_snapshot)
16730 ..=end_display.to_display_point(display_snapshot),
16731 );
16732 }
16733 };
16734 let mut start_row: Option<Point> = None;
16735 let mut end_row: Option<Point> = None;
16736 if ranges.len() > count {
16737 return Vec::new();
16738 }
16739 for range in &ranges[start_ix..] {
16740 if range
16741 .start
16742 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16743 .is_ge()
16744 {
16745 break;
16746 }
16747 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16748 if let Some(current_row) = &end_row {
16749 if end.row == current_row.row {
16750 continue;
16751 }
16752 }
16753 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16754 if start_row.is_none() {
16755 assert_eq!(end_row, None);
16756 start_row = Some(start);
16757 end_row = Some(end);
16758 continue;
16759 }
16760 if let Some(current_end) = end_row.as_mut() {
16761 if start.row > current_end.row + 1 {
16762 push_region(start_row, end_row);
16763 start_row = Some(start);
16764 end_row = Some(end);
16765 } else {
16766 // Merge two hunks.
16767 *current_end = end;
16768 }
16769 } else {
16770 unreachable!();
16771 }
16772 }
16773 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16774 push_region(start_row, end_row);
16775 results
16776 }
16777
16778 pub fn gutter_highlights_in_range(
16779 &self,
16780 search_range: Range<Anchor>,
16781 display_snapshot: &DisplaySnapshot,
16782 cx: &App,
16783 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16784 let mut results = Vec::new();
16785 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16786 let color = color_fetcher(cx);
16787 let start_ix = match ranges.binary_search_by(|probe| {
16788 let cmp = probe
16789 .end
16790 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16791 if cmp.is_gt() {
16792 Ordering::Greater
16793 } else {
16794 Ordering::Less
16795 }
16796 }) {
16797 Ok(i) | Err(i) => i,
16798 };
16799 for range in &ranges[start_ix..] {
16800 if range
16801 .start
16802 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16803 .is_ge()
16804 {
16805 break;
16806 }
16807
16808 let start = range.start.to_display_point(display_snapshot);
16809 let end = range.end.to_display_point(display_snapshot);
16810 results.push((start..end, color))
16811 }
16812 }
16813 results
16814 }
16815
16816 /// Get the text ranges corresponding to the redaction query
16817 pub fn redacted_ranges(
16818 &self,
16819 search_range: Range<Anchor>,
16820 display_snapshot: &DisplaySnapshot,
16821 cx: &App,
16822 ) -> Vec<Range<DisplayPoint>> {
16823 display_snapshot
16824 .buffer_snapshot
16825 .redacted_ranges(search_range, |file| {
16826 if let Some(file) = file {
16827 file.is_private()
16828 && EditorSettings::get(
16829 Some(SettingsLocation {
16830 worktree_id: file.worktree_id(cx),
16831 path: file.path().as_ref(),
16832 }),
16833 cx,
16834 )
16835 .redact_private_values
16836 } else {
16837 false
16838 }
16839 })
16840 .map(|range| {
16841 range.start.to_display_point(display_snapshot)
16842 ..range.end.to_display_point(display_snapshot)
16843 })
16844 .collect()
16845 }
16846
16847 pub fn highlight_text<T: 'static>(
16848 &mut self,
16849 ranges: Vec<Range<Anchor>>,
16850 style: HighlightStyle,
16851 cx: &mut Context<Self>,
16852 ) {
16853 self.display_map.update(cx, |map, _| {
16854 map.highlight_text(TypeId::of::<T>(), ranges, style)
16855 });
16856 cx.notify();
16857 }
16858
16859 pub(crate) fn highlight_inlays<T: 'static>(
16860 &mut self,
16861 highlights: Vec<InlayHighlight>,
16862 style: HighlightStyle,
16863 cx: &mut Context<Self>,
16864 ) {
16865 self.display_map.update(cx, |map, _| {
16866 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16867 });
16868 cx.notify();
16869 }
16870
16871 pub fn text_highlights<'a, T: 'static>(
16872 &'a self,
16873 cx: &'a App,
16874 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16875 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16876 }
16877
16878 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16879 let cleared = self
16880 .display_map
16881 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16882 if cleared {
16883 cx.notify();
16884 }
16885 }
16886
16887 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16888 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16889 && self.focus_handle.is_focused(window)
16890 }
16891
16892 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16893 self.show_cursor_when_unfocused = is_enabled;
16894 cx.notify();
16895 }
16896
16897 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16898 cx.notify();
16899 }
16900
16901 fn on_buffer_event(
16902 &mut self,
16903 multibuffer: &Entity<MultiBuffer>,
16904 event: &multi_buffer::Event,
16905 window: &mut Window,
16906 cx: &mut Context<Self>,
16907 ) {
16908 match event {
16909 multi_buffer::Event::Edited {
16910 singleton_buffer_edited,
16911 edited_buffer: buffer_edited,
16912 } => {
16913 self.scrollbar_marker_state.dirty = true;
16914 self.active_indent_guides_state.dirty = true;
16915 self.refresh_active_diagnostics(cx);
16916 self.refresh_code_actions(window, cx);
16917 if self.has_active_inline_completion() {
16918 self.update_visible_inline_completion(window, cx);
16919 }
16920 if let Some(buffer) = buffer_edited {
16921 let buffer_id = buffer.read(cx).remote_id();
16922 if !self.registered_buffers.contains_key(&buffer_id) {
16923 if let Some(project) = self.project.as_ref() {
16924 project.update(cx, |project, cx| {
16925 self.registered_buffers.insert(
16926 buffer_id,
16927 project.register_buffer_with_language_servers(&buffer, cx),
16928 );
16929 })
16930 }
16931 }
16932 }
16933 cx.emit(EditorEvent::BufferEdited);
16934 cx.emit(SearchEvent::MatchesInvalidated);
16935 if *singleton_buffer_edited {
16936 if let Some(project) = &self.project {
16937 #[allow(clippy::mutable_key_type)]
16938 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16939 multibuffer
16940 .all_buffers()
16941 .into_iter()
16942 .filter_map(|buffer| {
16943 buffer.update(cx, |buffer, cx| {
16944 let language = buffer.language()?;
16945 let should_discard = project.update(cx, |project, cx| {
16946 project.is_local()
16947 && !project.has_language_servers_for(buffer, cx)
16948 });
16949 should_discard.not().then_some(language.clone())
16950 })
16951 })
16952 .collect::<HashSet<_>>()
16953 });
16954 if !languages_affected.is_empty() {
16955 self.refresh_inlay_hints(
16956 InlayHintRefreshReason::BufferEdited(languages_affected),
16957 cx,
16958 );
16959 }
16960 }
16961 }
16962
16963 let Some(project) = &self.project else { return };
16964 let (telemetry, is_via_ssh) = {
16965 let project = project.read(cx);
16966 let telemetry = project.client().telemetry().clone();
16967 let is_via_ssh = project.is_via_ssh();
16968 (telemetry, is_via_ssh)
16969 };
16970 refresh_linked_ranges(self, window, cx);
16971 telemetry.log_edit_event("editor", is_via_ssh);
16972 }
16973 multi_buffer::Event::ExcerptsAdded {
16974 buffer,
16975 predecessor,
16976 excerpts,
16977 } => {
16978 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16979 let buffer_id = buffer.read(cx).remote_id();
16980 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16981 if let Some(project) = &self.project {
16982 get_uncommitted_diff_for_buffer(
16983 project,
16984 [buffer.clone()],
16985 self.buffer.clone(),
16986 cx,
16987 )
16988 .detach();
16989 }
16990 }
16991 cx.emit(EditorEvent::ExcerptsAdded {
16992 buffer: buffer.clone(),
16993 predecessor: *predecessor,
16994 excerpts: excerpts.clone(),
16995 });
16996 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16997 }
16998 multi_buffer::Event::ExcerptsRemoved { ids } => {
16999 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17000 let buffer = self.buffer.read(cx);
17001 self.registered_buffers
17002 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17003 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17004 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17005 }
17006 multi_buffer::Event::ExcerptsEdited {
17007 excerpt_ids,
17008 buffer_ids,
17009 } => {
17010 self.display_map.update(cx, |map, cx| {
17011 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17012 });
17013 cx.emit(EditorEvent::ExcerptsEdited {
17014 ids: excerpt_ids.clone(),
17015 })
17016 }
17017 multi_buffer::Event::ExcerptsExpanded { ids } => {
17018 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17019 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17020 }
17021 multi_buffer::Event::Reparsed(buffer_id) => {
17022 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17023 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17024
17025 cx.emit(EditorEvent::Reparsed(*buffer_id));
17026 }
17027 multi_buffer::Event::DiffHunksToggled => {
17028 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17029 }
17030 multi_buffer::Event::LanguageChanged(buffer_id) => {
17031 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17032 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17033 cx.emit(EditorEvent::Reparsed(*buffer_id));
17034 cx.notify();
17035 }
17036 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17037 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17038 multi_buffer::Event::FileHandleChanged
17039 | multi_buffer::Event::Reloaded
17040 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17041 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17042 multi_buffer::Event::DiagnosticsUpdated => {
17043 self.refresh_active_diagnostics(cx);
17044 self.refresh_inline_diagnostics(true, window, cx);
17045 self.scrollbar_marker_state.dirty = true;
17046 cx.notify();
17047 }
17048 _ => {}
17049 };
17050 }
17051
17052 fn on_display_map_changed(
17053 &mut self,
17054 _: Entity<DisplayMap>,
17055 _: &mut Window,
17056 cx: &mut Context<Self>,
17057 ) {
17058 cx.notify();
17059 }
17060
17061 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17062 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17063 self.update_edit_prediction_settings(cx);
17064 self.refresh_inline_completion(true, false, window, cx);
17065 self.refresh_inlay_hints(
17066 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17067 self.selections.newest_anchor().head(),
17068 &self.buffer.read(cx).snapshot(cx),
17069 cx,
17070 )),
17071 cx,
17072 );
17073
17074 let old_cursor_shape = self.cursor_shape;
17075
17076 {
17077 let editor_settings = EditorSettings::get_global(cx);
17078 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17079 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17080 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17081 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17082 }
17083
17084 if old_cursor_shape != self.cursor_shape {
17085 cx.emit(EditorEvent::CursorShapeChanged);
17086 }
17087
17088 let project_settings = ProjectSettings::get_global(cx);
17089 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17090
17091 if self.mode == EditorMode::Full {
17092 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17093 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17094 if self.show_inline_diagnostics != show_inline_diagnostics {
17095 self.show_inline_diagnostics = show_inline_diagnostics;
17096 self.refresh_inline_diagnostics(false, window, cx);
17097 }
17098
17099 if self.git_blame_inline_enabled != inline_blame_enabled {
17100 self.toggle_git_blame_inline_internal(false, window, cx);
17101 }
17102 }
17103
17104 cx.notify();
17105 }
17106
17107 pub fn set_searchable(&mut self, searchable: bool) {
17108 self.searchable = searchable;
17109 }
17110
17111 pub fn searchable(&self) -> bool {
17112 self.searchable
17113 }
17114
17115 fn open_proposed_changes_editor(
17116 &mut self,
17117 _: &OpenProposedChangesEditor,
17118 window: &mut Window,
17119 cx: &mut Context<Self>,
17120 ) {
17121 let Some(workspace) = self.workspace() else {
17122 cx.propagate();
17123 return;
17124 };
17125
17126 let selections = self.selections.all::<usize>(cx);
17127 let multi_buffer = self.buffer.read(cx);
17128 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17129 let mut new_selections_by_buffer = HashMap::default();
17130 for selection in selections {
17131 for (buffer, range, _) in
17132 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17133 {
17134 let mut range = range.to_point(buffer);
17135 range.start.column = 0;
17136 range.end.column = buffer.line_len(range.end.row);
17137 new_selections_by_buffer
17138 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17139 .or_insert(Vec::new())
17140 .push(range)
17141 }
17142 }
17143
17144 let proposed_changes_buffers = new_selections_by_buffer
17145 .into_iter()
17146 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17147 .collect::<Vec<_>>();
17148 let proposed_changes_editor = cx.new(|cx| {
17149 ProposedChangesEditor::new(
17150 "Proposed changes",
17151 proposed_changes_buffers,
17152 self.project.clone(),
17153 window,
17154 cx,
17155 )
17156 });
17157
17158 window.defer(cx, move |window, cx| {
17159 workspace.update(cx, |workspace, cx| {
17160 workspace.active_pane().update(cx, |pane, cx| {
17161 pane.add_item(
17162 Box::new(proposed_changes_editor),
17163 true,
17164 true,
17165 None,
17166 window,
17167 cx,
17168 );
17169 });
17170 });
17171 });
17172 }
17173
17174 pub fn open_excerpts_in_split(
17175 &mut self,
17176 _: &OpenExcerptsSplit,
17177 window: &mut Window,
17178 cx: &mut Context<Self>,
17179 ) {
17180 self.open_excerpts_common(None, true, window, cx)
17181 }
17182
17183 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17184 self.open_excerpts_common(None, false, window, cx)
17185 }
17186
17187 fn open_excerpts_common(
17188 &mut self,
17189 jump_data: Option<JumpData>,
17190 split: bool,
17191 window: &mut Window,
17192 cx: &mut Context<Self>,
17193 ) {
17194 let Some(workspace) = self.workspace() else {
17195 cx.propagate();
17196 return;
17197 };
17198
17199 if self.buffer.read(cx).is_singleton() {
17200 cx.propagate();
17201 return;
17202 }
17203
17204 let mut new_selections_by_buffer = HashMap::default();
17205 match &jump_data {
17206 Some(JumpData::MultiBufferPoint {
17207 excerpt_id,
17208 position,
17209 anchor,
17210 line_offset_from_top,
17211 }) => {
17212 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17213 if let Some(buffer) = multi_buffer_snapshot
17214 .buffer_id_for_excerpt(*excerpt_id)
17215 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17216 {
17217 let buffer_snapshot = buffer.read(cx).snapshot();
17218 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17219 language::ToPoint::to_point(anchor, &buffer_snapshot)
17220 } else {
17221 buffer_snapshot.clip_point(*position, Bias::Left)
17222 };
17223 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17224 new_selections_by_buffer.insert(
17225 buffer,
17226 (
17227 vec![jump_to_offset..jump_to_offset],
17228 Some(*line_offset_from_top),
17229 ),
17230 );
17231 }
17232 }
17233 Some(JumpData::MultiBufferRow {
17234 row,
17235 line_offset_from_top,
17236 }) => {
17237 let point = MultiBufferPoint::new(row.0, 0);
17238 if let Some((buffer, buffer_point, _)) =
17239 self.buffer.read(cx).point_to_buffer_point(point, cx)
17240 {
17241 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17242 new_selections_by_buffer
17243 .entry(buffer)
17244 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17245 .0
17246 .push(buffer_offset..buffer_offset)
17247 }
17248 }
17249 None => {
17250 let selections = self.selections.all::<usize>(cx);
17251 let multi_buffer = self.buffer.read(cx);
17252 for selection in selections {
17253 for (snapshot, range, _, anchor) in multi_buffer
17254 .snapshot(cx)
17255 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17256 {
17257 if let Some(anchor) = anchor {
17258 // selection is in a deleted hunk
17259 let Some(buffer_id) = anchor.buffer_id else {
17260 continue;
17261 };
17262 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17263 continue;
17264 };
17265 let offset = text::ToOffset::to_offset(
17266 &anchor.text_anchor,
17267 &buffer_handle.read(cx).snapshot(),
17268 );
17269 let range = offset..offset;
17270 new_selections_by_buffer
17271 .entry(buffer_handle)
17272 .or_insert((Vec::new(), None))
17273 .0
17274 .push(range)
17275 } else {
17276 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17277 else {
17278 continue;
17279 };
17280 new_selections_by_buffer
17281 .entry(buffer_handle)
17282 .or_insert((Vec::new(), None))
17283 .0
17284 .push(range)
17285 }
17286 }
17287 }
17288 }
17289 }
17290
17291 new_selections_by_buffer
17292 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17293
17294 if new_selections_by_buffer.is_empty() {
17295 return;
17296 }
17297
17298 // We defer the pane interaction because we ourselves are a workspace item
17299 // and activating a new item causes the pane to call a method on us reentrantly,
17300 // which panics if we're on the stack.
17301 window.defer(cx, move |window, cx| {
17302 workspace.update(cx, |workspace, cx| {
17303 let pane = if split {
17304 workspace.adjacent_pane(window, cx)
17305 } else {
17306 workspace.active_pane().clone()
17307 };
17308
17309 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17310 let editor = buffer
17311 .read(cx)
17312 .file()
17313 .is_none()
17314 .then(|| {
17315 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17316 // so `workspace.open_project_item` will never find them, always opening a new editor.
17317 // Instead, we try to activate the existing editor in the pane first.
17318 let (editor, pane_item_index) =
17319 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17320 let editor = item.downcast::<Editor>()?;
17321 let singleton_buffer =
17322 editor.read(cx).buffer().read(cx).as_singleton()?;
17323 if singleton_buffer == buffer {
17324 Some((editor, i))
17325 } else {
17326 None
17327 }
17328 })?;
17329 pane.update(cx, |pane, cx| {
17330 pane.activate_item(pane_item_index, true, true, window, cx)
17331 });
17332 Some(editor)
17333 })
17334 .flatten()
17335 .unwrap_or_else(|| {
17336 workspace.open_project_item::<Self>(
17337 pane.clone(),
17338 buffer,
17339 true,
17340 true,
17341 window,
17342 cx,
17343 )
17344 });
17345
17346 editor.update(cx, |editor, cx| {
17347 let autoscroll = match scroll_offset {
17348 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17349 None => Autoscroll::newest(),
17350 };
17351 let nav_history = editor.nav_history.take();
17352 editor.change_selections(Some(autoscroll), window, cx, |s| {
17353 s.select_ranges(ranges);
17354 });
17355 editor.nav_history = nav_history;
17356 });
17357 }
17358 })
17359 });
17360 }
17361
17362 // For now, don't allow opening excerpts in buffers that aren't backed by
17363 // regular project files.
17364 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17365 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17366 }
17367
17368 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17369 let snapshot = self.buffer.read(cx).read(cx);
17370 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17371 Some(
17372 ranges
17373 .iter()
17374 .map(move |range| {
17375 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17376 })
17377 .collect(),
17378 )
17379 }
17380
17381 fn selection_replacement_ranges(
17382 &self,
17383 range: Range<OffsetUtf16>,
17384 cx: &mut App,
17385 ) -> Vec<Range<OffsetUtf16>> {
17386 let selections = self.selections.all::<OffsetUtf16>(cx);
17387 let newest_selection = selections
17388 .iter()
17389 .max_by_key(|selection| selection.id)
17390 .unwrap();
17391 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17392 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17393 let snapshot = self.buffer.read(cx).read(cx);
17394 selections
17395 .into_iter()
17396 .map(|mut selection| {
17397 selection.start.0 =
17398 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17399 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17400 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17401 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17402 })
17403 .collect()
17404 }
17405
17406 fn report_editor_event(
17407 &self,
17408 event_type: &'static str,
17409 file_extension: Option<String>,
17410 cx: &App,
17411 ) {
17412 if cfg!(any(test, feature = "test-support")) {
17413 return;
17414 }
17415
17416 let Some(project) = &self.project else { return };
17417
17418 // If None, we are in a file without an extension
17419 let file = self
17420 .buffer
17421 .read(cx)
17422 .as_singleton()
17423 .and_then(|b| b.read(cx).file());
17424 let file_extension = file_extension.or(file
17425 .as_ref()
17426 .and_then(|file| Path::new(file.file_name(cx)).extension())
17427 .and_then(|e| e.to_str())
17428 .map(|a| a.to_string()));
17429
17430 let vim_mode = cx
17431 .global::<SettingsStore>()
17432 .raw_user_settings()
17433 .get("vim_mode")
17434 == Some(&serde_json::Value::Bool(true));
17435
17436 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17437 let copilot_enabled = edit_predictions_provider
17438 == language::language_settings::EditPredictionProvider::Copilot;
17439 let copilot_enabled_for_language = self
17440 .buffer
17441 .read(cx)
17442 .language_settings(cx)
17443 .show_edit_predictions;
17444
17445 let project = project.read(cx);
17446 telemetry::event!(
17447 event_type,
17448 file_extension,
17449 vim_mode,
17450 copilot_enabled,
17451 copilot_enabled_for_language,
17452 edit_predictions_provider,
17453 is_via_ssh = project.is_via_ssh(),
17454 );
17455 }
17456
17457 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17458 /// with each line being an array of {text, highlight} objects.
17459 fn copy_highlight_json(
17460 &mut self,
17461 _: &CopyHighlightJson,
17462 window: &mut Window,
17463 cx: &mut Context<Self>,
17464 ) {
17465 #[derive(Serialize)]
17466 struct Chunk<'a> {
17467 text: String,
17468 highlight: Option<&'a str>,
17469 }
17470
17471 let snapshot = self.buffer.read(cx).snapshot(cx);
17472 let range = self
17473 .selected_text_range(false, window, cx)
17474 .and_then(|selection| {
17475 if selection.range.is_empty() {
17476 None
17477 } else {
17478 Some(selection.range)
17479 }
17480 })
17481 .unwrap_or_else(|| 0..snapshot.len());
17482
17483 let chunks = snapshot.chunks(range, true);
17484 let mut lines = Vec::new();
17485 let mut line: VecDeque<Chunk> = VecDeque::new();
17486
17487 let Some(style) = self.style.as_ref() else {
17488 return;
17489 };
17490
17491 for chunk in chunks {
17492 let highlight = chunk
17493 .syntax_highlight_id
17494 .and_then(|id| id.name(&style.syntax));
17495 let mut chunk_lines = chunk.text.split('\n').peekable();
17496 while let Some(text) = chunk_lines.next() {
17497 let mut merged_with_last_token = false;
17498 if let Some(last_token) = line.back_mut() {
17499 if last_token.highlight == highlight {
17500 last_token.text.push_str(text);
17501 merged_with_last_token = true;
17502 }
17503 }
17504
17505 if !merged_with_last_token {
17506 line.push_back(Chunk {
17507 text: text.into(),
17508 highlight,
17509 });
17510 }
17511
17512 if chunk_lines.peek().is_some() {
17513 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17514 line.pop_front();
17515 }
17516 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17517 line.pop_back();
17518 }
17519
17520 lines.push(mem::take(&mut line));
17521 }
17522 }
17523 }
17524
17525 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17526 return;
17527 };
17528 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17529 }
17530
17531 pub fn open_context_menu(
17532 &mut self,
17533 _: &OpenContextMenu,
17534 window: &mut Window,
17535 cx: &mut Context<Self>,
17536 ) {
17537 self.request_autoscroll(Autoscroll::newest(), cx);
17538 let position = self.selections.newest_display(cx).start;
17539 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17540 }
17541
17542 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17543 &self.inlay_hint_cache
17544 }
17545
17546 pub fn replay_insert_event(
17547 &mut self,
17548 text: &str,
17549 relative_utf16_range: Option<Range<isize>>,
17550 window: &mut Window,
17551 cx: &mut Context<Self>,
17552 ) {
17553 if !self.input_enabled {
17554 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17555 return;
17556 }
17557 if let Some(relative_utf16_range) = relative_utf16_range {
17558 let selections = self.selections.all::<OffsetUtf16>(cx);
17559 self.change_selections(None, window, cx, |s| {
17560 let new_ranges = selections.into_iter().map(|range| {
17561 let start = OffsetUtf16(
17562 range
17563 .head()
17564 .0
17565 .saturating_add_signed(relative_utf16_range.start),
17566 );
17567 let end = OffsetUtf16(
17568 range
17569 .head()
17570 .0
17571 .saturating_add_signed(relative_utf16_range.end),
17572 );
17573 start..end
17574 });
17575 s.select_ranges(new_ranges);
17576 });
17577 }
17578
17579 self.handle_input(text, window, cx);
17580 }
17581
17582 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17583 let Some(provider) = self.semantics_provider.as_ref() else {
17584 return false;
17585 };
17586
17587 let mut supports = false;
17588 self.buffer().update(cx, |this, cx| {
17589 this.for_each_buffer(|buffer| {
17590 supports |= provider.supports_inlay_hints(buffer, cx);
17591 });
17592 });
17593
17594 supports
17595 }
17596
17597 pub fn is_focused(&self, window: &Window) -> bool {
17598 self.focus_handle.is_focused(window)
17599 }
17600
17601 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17602 cx.emit(EditorEvent::Focused);
17603
17604 if let Some(descendant) = self
17605 .last_focused_descendant
17606 .take()
17607 .and_then(|descendant| descendant.upgrade())
17608 {
17609 window.focus(&descendant);
17610 } else {
17611 if let Some(blame) = self.blame.as_ref() {
17612 blame.update(cx, GitBlame::focus)
17613 }
17614
17615 self.blink_manager.update(cx, BlinkManager::enable);
17616 self.show_cursor_names(window, cx);
17617 self.buffer.update(cx, |buffer, cx| {
17618 buffer.finalize_last_transaction(cx);
17619 if self.leader_peer_id.is_none() {
17620 buffer.set_active_selections(
17621 &self.selections.disjoint_anchors(),
17622 self.selections.line_mode,
17623 self.cursor_shape,
17624 cx,
17625 );
17626 }
17627 });
17628 }
17629 }
17630
17631 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17632 cx.emit(EditorEvent::FocusedIn)
17633 }
17634
17635 fn handle_focus_out(
17636 &mut self,
17637 event: FocusOutEvent,
17638 _window: &mut Window,
17639 cx: &mut Context<Self>,
17640 ) {
17641 if event.blurred != self.focus_handle {
17642 self.last_focused_descendant = Some(event.blurred);
17643 }
17644 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17645 }
17646
17647 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17648 self.blink_manager.update(cx, BlinkManager::disable);
17649 self.buffer
17650 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17651
17652 if let Some(blame) = self.blame.as_ref() {
17653 blame.update(cx, GitBlame::blur)
17654 }
17655 if !self.hover_state.focused(window, cx) {
17656 hide_hover(self, cx);
17657 }
17658 if !self
17659 .context_menu
17660 .borrow()
17661 .as_ref()
17662 .is_some_and(|context_menu| context_menu.focused(window, cx))
17663 {
17664 self.hide_context_menu(window, cx);
17665 }
17666 self.discard_inline_completion(false, cx);
17667 cx.emit(EditorEvent::Blurred);
17668 cx.notify();
17669 }
17670
17671 pub fn register_action<A: Action>(
17672 &mut self,
17673 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17674 ) -> Subscription {
17675 let id = self.next_editor_action_id.post_inc();
17676 let listener = Arc::new(listener);
17677 self.editor_actions.borrow_mut().insert(
17678 id,
17679 Box::new(move |window, _| {
17680 let listener = listener.clone();
17681 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17682 let action = action.downcast_ref().unwrap();
17683 if phase == DispatchPhase::Bubble {
17684 listener(action, window, cx)
17685 }
17686 })
17687 }),
17688 );
17689
17690 let editor_actions = self.editor_actions.clone();
17691 Subscription::new(move || {
17692 editor_actions.borrow_mut().remove(&id);
17693 })
17694 }
17695
17696 pub fn file_header_size(&self) -> u32 {
17697 FILE_HEADER_HEIGHT
17698 }
17699
17700 pub fn restore(
17701 &mut self,
17702 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17703 window: &mut Window,
17704 cx: &mut Context<Self>,
17705 ) {
17706 let workspace = self.workspace();
17707 let project = self.project.as_ref();
17708 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17709 let mut tasks = Vec::new();
17710 for (buffer_id, changes) in revert_changes {
17711 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17712 buffer.update(cx, |buffer, cx| {
17713 buffer.edit(
17714 changes
17715 .into_iter()
17716 .map(|(range, text)| (range, text.to_string())),
17717 None,
17718 cx,
17719 );
17720 });
17721
17722 if let Some(project) =
17723 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17724 {
17725 project.update(cx, |project, cx| {
17726 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17727 })
17728 }
17729 }
17730 }
17731 tasks
17732 });
17733 cx.spawn_in(window, async move |_, cx| {
17734 for (buffer, task) in save_tasks {
17735 let result = task.await;
17736 if result.is_err() {
17737 let Some(path) = buffer
17738 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17739 .ok()
17740 else {
17741 continue;
17742 };
17743 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17744 let Some(task) = cx
17745 .update_window_entity(&workspace, |workspace, window, cx| {
17746 workspace
17747 .open_path_preview(path, None, false, false, false, window, cx)
17748 })
17749 .ok()
17750 else {
17751 continue;
17752 };
17753 task.await.log_err();
17754 }
17755 }
17756 }
17757 })
17758 .detach();
17759 self.change_selections(None, window, cx, |selections| selections.refresh());
17760 }
17761
17762 pub fn to_pixel_point(
17763 &self,
17764 source: multi_buffer::Anchor,
17765 editor_snapshot: &EditorSnapshot,
17766 window: &mut Window,
17767 ) -> Option<gpui::Point<Pixels>> {
17768 let source_point = source.to_display_point(editor_snapshot);
17769 self.display_to_pixel_point(source_point, editor_snapshot, window)
17770 }
17771
17772 pub fn display_to_pixel_point(
17773 &self,
17774 source: DisplayPoint,
17775 editor_snapshot: &EditorSnapshot,
17776 window: &mut Window,
17777 ) -> Option<gpui::Point<Pixels>> {
17778 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17779 let text_layout_details = self.text_layout_details(window);
17780 let scroll_top = text_layout_details
17781 .scroll_anchor
17782 .scroll_position(editor_snapshot)
17783 .y;
17784
17785 if source.row().as_f32() < scroll_top.floor() {
17786 return None;
17787 }
17788 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17789 let source_y = line_height * (source.row().as_f32() - scroll_top);
17790 Some(gpui::Point::new(source_x, source_y))
17791 }
17792
17793 pub fn has_visible_completions_menu(&self) -> bool {
17794 !self.edit_prediction_preview_is_active()
17795 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17796 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17797 })
17798 }
17799
17800 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17801 self.addons
17802 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17803 }
17804
17805 pub fn unregister_addon<T: Addon>(&mut self) {
17806 self.addons.remove(&std::any::TypeId::of::<T>());
17807 }
17808
17809 pub fn addon<T: Addon>(&self) -> Option<&T> {
17810 let type_id = std::any::TypeId::of::<T>();
17811 self.addons
17812 .get(&type_id)
17813 .and_then(|item| item.to_any().downcast_ref::<T>())
17814 }
17815
17816 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17817 let text_layout_details = self.text_layout_details(window);
17818 let style = &text_layout_details.editor_style;
17819 let font_id = window.text_system().resolve_font(&style.text.font());
17820 let font_size = style.text.font_size.to_pixels(window.rem_size());
17821 let line_height = style.text.line_height_in_pixels(window.rem_size());
17822 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17823
17824 gpui::Size::new(em_width, line_height)
17825 }
17826
17827 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17828 self.load_diff_task.clone()
17829 }
17830
17831 fn read_metadata_from_db(
17832 &mut self,
17833 item_id: u64,
17834 workspace_id: WorkspaceId,
17835 window: &mut Window,
17836 cx: &mut Context<Editor>,
17837 ) {
17838 if self.is_singleton(cx)
17839 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17840 {
17841 let buffer_snapshot = OnceCell::new();
17842
17843 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17844 if !folds.is_empty() {
17845 let snapshot =
17846 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17847 self.fold_ranges(
17848 folds
17849 .into_iter()
17850 .map(|(start, end)| {
17851 snapshot.clip_offset(start, Bias::Left)
17852 ..snapshot.clip_offset(end, Bias::Right)
17853 })
17854 .collect(),
17855 false,
17856 window,
17857 cx,
17858 );
17859 }
17860 }
17861
17862 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17863 if !selections.is_empty() {
17864 let snapshot =
17865 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17866 self.change_selections(None, window, cx, |s| {
17867 s.select_ranges(selections.into_iter().map(|(start, end)| {
17868 snapshot.clip_offset(start, Bias::Left)
17869 ..snapshot.clip_offset(end, Bias::Right)
17870 }));
17871 });
17872 }
17873 };
17874 }
17875
17876 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17877 }
17878}
17879
17880fn insert_extra_newline_brackets(
17881 buffer: &MultiBufferSnapshot,
17882 range: Range<usize>,
17883 language: &language::LanguageScope,
17884) -> bool {
17885 let leading_whitespace_len = buffer
17886 .reversed_chars_at(range.start)
17887 .take_while(|c| c.is_whitespace() && *c != '\n')
17888 .map(|c| c.len_utf8())
17889 .sum::<usize>();
17890 let trailing_whitespace_len = buffer
17891 .chars_at(range.end)
17892 .take_while(|c| c.is_whitespace() && *c != '\n')
17893 .map(|c| c.len_utf8())
17894 .sum::<usize>();
17895 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17896
17897 language.brackets().any(|(pair, enabled)| {
17898 let pair_start = pair.start.trim_end();
17899 let pair_end = pair.end.trim_start();
17900
17901 enabled
17902 && pair.newline
17903 && buffer.contains_str_at(range.end, pair_end)
17904 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17905 })
17906}
17907
17908fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17909 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17910 [(buffer, range, _)] => (*buffer, range.clone()),
17911 _ => return false,
17912 };
17913 let pair = {
17914 let mut result: Option<BracketMatch> = None;
17915
17916 for pair in buffer
17917 .all_bracket_ranges(range.clone())
17918 .filter(move |pair| {
17919 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17920 })
17921 {
17922 let len = pair.close_range.end - pair.open_range.start;
17923
17924 if let Some(existing) = &result {
17925 let existing_len = existing.close_range.end - existing.open_range.start;
17926 if len > existing_len {
17927 continue;
17928 }
17929 }
17930
17931 result = Some(pair);
17932 }
17933
17934 result
17935 };
17936 let Some(pair) = pair else {
17937 return false;
17938 };
17939 pair.newline_only
17940 && buffer
17941 .chars_for_range(pair.open_range.end..range.start)
17942 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17943 .all(|c| c.is_whitespace() && c != '\n')
17944}
17945
17946fn get_uncommitted_diff_for_buffer(
17947 project: &Entity<Project>,
17948 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17949 buffer: Entity<MultiBuffer>,
17950 cx: &mut App,
17951) -> Task<()> {
17952 let mut tasks = Vec::new();
17953 project.update(cx, |project, cx| {
17954 for buffer in buffers {
17955 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
17956 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17957 }
17958 }
17959 });
17960 cx.spawn(async move |cx| {
17961 let diffs = future::join_all(tasks).await;
17962 buffer
17963 .update(cx, |buffer, cx| {
17964 for diff in diffs.into_iter().flatten() {
17965 buffer.add_diff(diff, cx);
17966 }
17967 })
17968 .ok();
17969 })
17970}
17971
17972fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17973 let tab_size = tab_size.get() as usize;
17974 let mut width = offset;
17975
17976 for ch in text.chars() {
17977 width += if ch == '\t' {
17978 tab_size - (width % tab_size)
17979 } else {
17980 1
17981 };
17982 }
17983
17984 width - offset
17985}
17986
17987#[cfg(test)]
17988mod tests {
17989 use super::*;
17990
17991 #[test]
17992 fn test_string_size_with_expanded_tabs() {
17993 let nz = |val| NonZeroU32::new(val).unwrap();
17994 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17995 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17996 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17997 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17998 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17999 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18000 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18001 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18002 }
18003}
18004
18005/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18006struct WordBreakingTokenizer<'a> {
18007 input: &'a str,
18008}
18009
18010impl<'a> WordBreakingTokenizer<'a> {
18011 fn new(input: &'a str) -> Self {
18012 Self { input }
18013 }
18014}
18015
18016fn is_char_ideographic(ch: char) -> bool {
18017 use unicode_script::Script::*;
18018 use unicode_script::UnicodeScript;
18019 matches!(ch.script(), Han | Tangut | Yi)
18020}
18021
18022fn is_grapheme_ideographic(text: &str) -> bool {
18023 text.chars().any(is_char_ideographic)
18024}
18025
18026fn is_grapheme_whitespace(text: &str) -> bool {
18027 text.chars().any(|x| x.is_whitespace())
18028}
18029
18030fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18031 text.chars().next().map_or(false, |ch| {
18032 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18033 })
18034}
18035
18036#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18037enum WordBreakToken<'a> {
18038 Word { token: &'a str, grapheme_len: usize },
18039 InlineWhitespace { token: &'a str, grapheme_len: usize },
18040 Newline,
18041}
18042
18043impl<'a> Iterator for WordBreakingTokenizer<'a> {
18044 /// Yields a span, the count of graphemes in the token, and whether it was
18045 /// whitespace. Note that it also breaks at word boundaries.
18046 type Item = WordBreakToken<'a>;
18047
18048 fn next(&mut self) -> Option<Self::Item> {
18049 use unicode_segmentation::UnicodeSegmentation;
18050 if self.input.is_empty() {
18051 return None;
18052 }
18053
18054 let mut iter = self.input.graphemes(true).peekable();
18055 let mut offset = 0;
18056 let mut grapheme_len = 0;
18057 if let Some(first_grapheme) = iter.next() {
18058 let is_newline = first_grapheme == "\n";
18059 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18060 offset += first_grapheme.len();
18061 grapheme_len += 1;
18062 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18063 if let Some(grapheme) = iter.peek().copied() {
18064 if should_stay_with_preceding_ideograph(grapheme) {
18065 offset += grapheme.len();
18066 grapheme_len += 1;
18067 }
18068 }
18069 } else {
18070 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18071 let mut next_word_bound = words.peek().copied();
18072 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18073 next_word_bound = words.next();
18074 }
18075 while let Some(grapheme) = iter.peek().copied() {
18076 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18077 break;
18078 };
18079 if is_grapheme_whitespace(grapheme) != is_whitespace
18080 || (grapheme == "\n") != is_newline
18081 {
18082 break;
18083 };
18084 offset += grapheme.len();
18085 grapheme_len += 1;
18086 iter.next();
18087 }
18088 }
18089 let token = &self.input[..offset];
18090 self.input = &self.input[offset..];
18091 if token == "\n" {
18092 Some(WordBreakToken::Newline)
18093 } else if is_whitespace {
18094 Some(WordBreakToken::InlineWhitespace {
18095 token,
18096 grapheme_len,
18097 })
18098 } else {
18099 Some(WordBreakToken::Word {
18100 token,
18101 grapheme_len,
18102 })
18103 }
18104 } else {
18105 None
18106 }
18107 }
18108}
18109
18110#[test]
18111fn test_word_breaking_tokenizer() {
18112 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18113 ("", &[]),
18114 (" ", &[whitespace(" ", 2)]),
18115 ("Ʒ", &[word("Ʒ", 1)]),
18116 ("Ǽ", &[word("Ǽ", 1)]),
18117 ("⋑", &[word("⋑", 1)]),
18118 ("⋑⋑", &[word("⋑⋑", 2)]),
18119 (
18120 "原理,进而",
18121 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18122 ),
18123 (
18124 "hello world",
18125 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18126 ),
18127 (
18128 "hello, world",
18129 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18130 ),
18131 (
18132 " hello world",
18133 &[
18134 whitespace(" ", 2),
18135 word("hello", 5),
18136 whitespace(" ", 1),
18137 word("world", 5),
18138 ],
18139 ),
18140 (
18141 "这是什么 \n 钢笔",
18142 &[
18143 word("这", 1),
18144 word("是", 1),
18145 word("什", 1),
18146 word("么", 1),
18147 whitespace(" ", 1),
18148 newline(),
18149 whitespace(" ", 1),
18150 word("钢", 1),
18151 word("笔", 1),
18152 ],
18153 ),
18154 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18155 ];
18156
18157 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18158 WordBreakToken::Word {
18159 token,
18160 grapheme_len,
18161 }
18162 }
18163
18164 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18165 WordBreakToken::InlineWhitespace {
18166 token,
18167 grapheme_len,
18168 }
18169 }
18170
18171 fn newline() -> WordBreakToken<'static> {
18172 WordBreakToken::Newline
18173 }
18174
18175 for (input, result) in tests {
18176 assert_eq!(
18177 WordBreakingTokenizer::new(input)
18178 .collect::<Vec<_>>()
18179 .as_slice(),
18180 *result,
18181 );
18182 }
18183}
18184
18185fn wrap_with_prefix(
18186 line_prefix: String,
18187 unwrapped_text: String,
18188 wrap_column: usize,
18189 tab_size: NonZeroU32,
18190 preserve_existing_whitespace: bool,
18191) -> String {
18192 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18193 let mut wrapped_text = String::new();
18194 let mut current_line = line_prefix.clone();
18195
18196 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18197 let mut current_line_len = line_prefix_len;
18198 let mut in_whitespace = false;
18199 for token in tokenizer {
18200 let have_preceding_whitespace = in_whitespace;
18201 match token {
18202 WordBreakToken::Word {
18203 token,
18204 grapheme_len,
18205 } => {
18206 in_whitespace = false;
18207 if current_line_len + grapheme_len > wrap_column
18208 && current_line_len != line_prefix_len
18209 {
18210 wrapped_text.push_str(current_line.trim_end());
18211 wrapped_text.push('\n');
18212 current_line.truncate(line_prefix.len());
18213 current_line_len = line_prefix_len;
18214 }
18215 current_line.push_str(token);
18216 current_line_len += grapheme_len;
18217 }
18218 WordBreakToken::InlineWhitespace {
18219 mut token,
18220 mut grapheme_len,
18221 } => {
18222 in_whitespace = true;
18223 if have_preceding_whitespace && !preserve_existing_whitespace {
18224 continue;
18225 }
18226 if !preserve_existing_whitespace {
18227 token = " ";
18228 grapheme_len = 1;
18229 }
18230 if current_line_len + grapheme_len > wrap_column {
18231 wrapped_text.push_str(current_line.trim_end());
18232 wrapped_text.push('\n');
18233 current_line.truncate(line_prefix.len());
18234 current_line_len = line_prefix_len;
18235 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18236 current_line.push_str(token);
18237 current_line_len += grapheme_len;
18238 }
18239 }
18240 WordBreakToken::Newline => {
18241 in_whitespace = true;
18242 if preserve_existing_whitespace {
18243 wrapped_text.push_str(current_line.trim_end());
18244 wrapped_text.push('\n');
18245 current_line.truncate(line_prefix.len());
18246 current_line_len = line_prefix_len;
18247 } else if have_preceding_whitespace {
18248 continue;
18249 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18250 {
18251 wrapped_text.push_str(current_line.trim_end());
18252 wrapped_text.push('\n');
18253 current_line.truncate(line_prefix.len());
18254 current_line_len = line_prefix_len;
18255 } else if current_line_len != line_prefix_len {
18256 current_line.push(' ');
18257 current_line_len += 1;
18258 }
18259 }
18260 }
18261 }
18262
18263 if !current_line.is_empty() {
18264 wrapped_text.push_str(¤t_line);
18265 }
18266 wrapped_text
18267}
18268
18269#[test]
18270fn test_wrap_with_prefix() {
18271 assert_eq!(
18272 wrap_with_prefix(
18273 "# ".to_string(),
18274 "abcdefg".to_string(),
18275 4,
18276 NonZeroU32::new(4).unwrap(),
18277 false,
18278 ),
18279 "# abcdefg"
18280 );
18281 assert_eq!(
18282 wrap_with_prefix(
18283 "".to_string(),
18284 "\thello world".to_string(),
18285 8,
18286 NonZeroU32::new(4).unwrap(),
18287 false,
18288 ),
18289 "hello\nworld"
18290 );
18291 assert_eq!(
18292 wrap_with_prefix(
18293 "// ".to_string(),
18294 "xx \nyy zz aa bb cc".to_string(),
18295 12,
18296 NonZeroU32::new(4).unwrap(),
18297 false,
18298 ),
18299 "// xx yy zz\n// aa bb cc"
18300 );
18301 assert_eq!(
18302 wrap_with_prefix(
18303 String::new(),
18304 "这是什么 \n 钢笔".to_string(),
18305 3,
18306 NonZeroU32::new(4).unwrap(),
18307 false,
18308 ),
18309 "这是什\n么 钢\n笔"
18310 );
18311}
18312
18313pub trait CollaborationHub {
18314 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18315 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18316 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18317}
18318
18319impl CollaborationHub for Entity<Project> {
18320 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18321 self.read(cx).collaborators()
18322 }
18323
18324 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18325 self.read(cx).user_store().read(cx).participant_indices()
18326 }
18327
18328 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18329 let this = self.read(cx);
18330 let user_ids = this.collaborators().values().map(|c| c.user_id);
18331 this.user_store().read_with(cx, |user_store, cx| {
18332 user_store.participant_names(user_ids, cx)
18333 })
18334 }
18335}
18336
18337pub trait SemanticsProvider {
18338 fn hover(
18339 &self,
18340 buffer: &Entity<Buffer>,
18341 position: text::Anchor,
18342 cx: &mut App,
18343 ) -> Option<Task<Vec<project::Hover>>>;
18344
18345 fn inlay_hints(
18346 &self,
18347 buffer_handle: Entity<Buffer>,
18348 range: Range<text::Anchor>,
18349 cx: &mut App,
18350 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18351
18352 fn resolve_inlay_hint(
18353 &self,
18354 hint: InlayHint,
18355 buffer_handle: Entity<Buffer>,
18356 server_id: LanguageServerId,
18357 cx: &mut App,
18358 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18359
18360 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18361
18362 fn document_highlights(
18363 &self,
18364 buffer: &Entity<Buffer>,
18365 position: text::Anchor,
18366 cx: &mut App,
18367 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18368
18369 fn definitions(
18370 &self,
18371 buffer: &Entity<Buffer>,
18372 position: text::Anchor,
18373 kind: GotoDefinitionKind,
18374 cx: &mut App,
18375 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18376
18377 fn range_for_rename(
18378 &self,
18379 buffer: &Entity<Buffer>,
18380 position: text::Anchor,
18381 cx: &mut App,
18382 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18383
18384 fn perform_rename(
18385 &self,
18386 buffer: &Entity<Buffer>,
18387 position: text::Anchor,
18388 new_name: String,
18389 cx: &mut App,
18390 ) -> Option<Task<Result<ProjectTransaction>>>;
18391}
18392
18393pub trait CompletionProvider {
18394 fn completions(
18395 &self,
18396 excerpt_id: ExcerptId,
18397 buffer: &Entity<Buffer>,
18398 buffer_position: text::Anchor,
18399 trigger: CompletionContext,
18400 window: &mut Window,
18401 cx: &mut Context<Editor>,
18402 ) -> Task<Result<Option<Vec<Completion>>>>;
18403
18404 fn resolve_completions(
18405 &self,
18406 buffer: Entity<Buffer>,
18407 completion_indices: Vec<usize>,
18408 completions: Rc<RefCell<Box<[Completion]>>>,
18409 cx: &mut Context<Editor>,
18410 ) -> Task<Result<bool>>;
18411
18412 fn apply_additional_edits_for_completion(
18413 &self,
18414 _buffer: Entity<Buffer>,
18415 _completions: Rc<RefCell<Box<[Completion]>>>,
18416 _completion_index: usize,
18417 _push_to_history: bool,
18418 _cx: &mut Context<Editor>,
18419 ) -> Task<Result<Option<language::Transaction>>> {
18420 Task::ready(Ok(None))
18421 }
18422
18423 fn is_completion_trigger(
18424 &self,
18425 buffer: &Entity<Buffer>,
18426 position: language::Anchor,
18427 text: &str,
18428 trigger_in_words: bool,
18429 cx: &mut Context<Editor>,
18430 ) -> bool;
18431
18432 fn sort_completions(&self) -> bool {
18433 true
18434 }
18435
18436 fn filter_completions(&self) -> bool {
18437 true
18438 }
18439}
18440
18441pub trait CodeActionProvider {
18442 fn id(&self) -> Arc<str>;
18443
18444 fn code_actions(
18445 &self,
18446 buffer: &Entity<Buffer>,
18447 range: Range<text::Anchor>,
18448 window: &mut Window,
18449 cx: &mut App,
18450 ) -> Task<Result<Vec<CodeAction>>>;
18451
18452 fn apply_code_action(
18453 &self,
18454 buffer_handle: Entity<Buffer>,
18455 action: CodeAction,
18456 excerpt_id: ExcerptId,
18457 push_to_history: bool,
18458 window: &mut Window,
18459 cx: &mut App,
18460 ) -> Task<Result<ProjectTransaction>>;
18461}
18462
18463impl CodeActionProvider for Entity<Project> {
18464 fn id(&self) -> Arc<str> {
18465 "project".into()
18466 }
18467
18468 fn code_actions(
18469 &self,
18470 buffer: &Entity<Buffer>,
18471 range: Range<text::Anchor>,
18472 _window: &mut Window,
18473 cx: &mut App,
18474 ) -> Task<Result<Vec<CodeAction>>> {
18475 self.update(cx, |project, cx| {
18476 let code_lens = project.code_lens(buffer, range.clone(), cx);
18477 let code_actions = project.code_actions(buffer, range, None, cx);
18478 cx.background_spawn(async move {
18479 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18480 Ok(code_lens
18481 .context("code lens fetch")?
18482 .into_iter()
18483 .chain(code_actions.context("code action fetch")?)
18484 .collect())
18485 })
18486 })
18487 }
18488
18489 fn apply_code_action(
18490 &self,
18491 buffer_handle: Entity<Buffer>,
18492 action: CodeAction,
18493 _excerpt_id: ExcerptId,
18494 push_to_history: bool,
18495 _window: &mut Window,
18496 cx: &mut App,
18497 ) -> Task<Result<ProjectTransaction>> {
18498 self.update(cx, |project, cx| {
18499 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18500 })
18501 }
18502}
18503
18504fn snippet_completions(
18505 project: &Project,
18506 buffer: &Entity<Buffer>,
18507 buffer_position: text::Anchor,
18508 cx: &mut App,
18509) -> Task<Result<Vec<Completion>>> {
18510 let language = buffer.read(cx).language_at(buffer_position);
18511 let language_name = language.as_ref().map(|language| language.lsp_id());
18512 let snippet_store = project.snippets().read(cx);
18513 let snippets = snippet_store.snippets_for(language_name, cx);
18514
18515 if snippets.is_empty() {
18516 return Task::ready(Ok(vec![]));
18517 }
18518 let snapshot = buffer.read(cx).text_snapshot();
18519 let chars: String = snapshot
18520 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18521 .collect();
18522
18523 let scope = language.map(|language| language.default_scope());
18524 let executor = cx.background_executor().clone();
18525
18526 cx.background_spawn(async move {
18527 let classifier = CharClassifier::new(scope).for_completion(true);
18528 let mut last_word = chars
18529 .chars()
18530 .take_while(|c| classifier.is_word(*c))
18531 .collect::<String>();
18532 last_word = last_word.chars().rev().collect();
18533
18534 if last_word.is_empty() {
18535 return Ok(vec![]);
18536 }
18537
18538 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18539 let to_lsp = |point: &text::Anchor| {
18540 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18541 point_to_lsp(end)
18542 };
18543 let lsp_end = to_lsp(&buffer_position);
18544
18545 let candidates = snippets
18546 .iter()
18547 .enumerate()
18548 .flat_map(|(ix, snippet)| {
18549 snippet
18550 .prefix
18551 .iter()
18552 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18553 })
18554 .collect::<Vec<StringMatchCandidate>>();
18555
18556 let mut matches = fuzzy::match_strings(
18557 &candidates,
18558 &last_word,
18559 last_word.chars().any(|c| c.is_uppercase()),
18560 100,
18561 &Default::default(),
18562 executor,
18563 )
18564 .await;
18565
18566 // Remove all candidates where the query's start does not match the start of any word in the candidate
18567 if let Some(query_start) = last_word.chars().next() {
18568 matches.retain(|string_match| {
18569 split_words(&string_match.string).any(|word| {
18570 // Check that the first codepoint of the word as lowercase matches the first
18571 // codepoint of the query as lowercase
18572 word.chars()
18573 .flat_map(|codepoint| codepoint.to_lowercase())
18574 .zip(query_start.to_lowercase())
18575 .all(|(word_cp, query_cp)| word_cp == query_cp)
18576 })
18577 });
18578 }
18579
18580 let matched_strings = matches
18581 .into_iter()
18582 .map(|m| m.string)
18583 .collect::<HashSet<_>>();
18584
18585 let result: Vec<Completion> = snippets
18586 .into_iter()
18587 .filter_map(|snippet| {
18588 let matching_prefix = snippet
18589 .prefix
18590 .iter()
18591 .find(|prefix| matched_strings.contains(*prefix))?;
18592 let start = as_offset - last_word.len();
18593 let start = snapshot.anchor_before(start);
18594 let range = start..buffer_position;
18595 let lsp_start = to_lsp(&start);
18596 let lsp_range = lsp::Range {
18597 start: lsp_start,
18598 end: lsp_end,
18599 };
18600 Some(Completion {
18601 old_range: range,
18602 new_text: snippet.body.clone(),
18603 source: CompletionSource::Lsp {
18604 server_id: LanguageServerId(usize::MAX),
18605 resolved: true,
18606 lsp_completion: Box::new(lsp::CompletionItem {
18607 label: snippet.prefix.first().unwrap().clone(),
18608 kind: Some(CompletionItemKind::SNIPPET),
18609 label_details: snippet.description.as_ref().map(|description| {
18610 lsp::CompletionItemLabelDetails {
18611 detail: Some(description.clone()),
18612 description: None,
18613 }
18614 }),
18615 insert_text_format: Some(InsertTextFormat::SNIPPET),
18616 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18617 lsp::InsertReplaceEdit {
18618 new_text: snippet.body.clone(),
18619 insert: lsp_range,
18620 replace: lsp_range,
18621 },
18622 )),
18623 filter_text: Some(snippet.body.clone()),
18624 sort_text: Some(char::MAX.to_string()),
18625 ..lsp::CompletionItem::default()
18626 }),
18627 lsp_defaults: None,
18628 },
18629 label: CodeLabel {
18630 text: matching_prefix.clone(),
18631 runs: Vec::new(),
18632 filter_range: 0..matching_prefix.len(),
18633 },
18634 icon_path: None,
18635 documentation: snippet
18636 .description
18637 .clone()
18638 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18639 confirm: None,
18640 })
18641 })
18642 .collect();
18643
18644 Ok(result)
18645 })
18646}
18647
18648impl CompletionProvider for Entity<Project> {
18649 fn completions(
18650 &self,
18651 _excerpt_id: ExcerptId,
18652 buffer: &Entity<Buffer>,
18653 buffer_position: text::Anchor,
18654 options: CompletionContext,
18655 _window: &mut Window,
18656 cx: &mut Context<Editor>,
18657 ) -> Task<Result<Option<Vec<Completion>>>> {
18658 self.update(cx, |project, cx| {
18659 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18660 let project_completions = project.completions(buffer, buffer_position, options, cx);
18661 cx.background_spawn(async move {
18662 let snippets_completions = snippets.await?;
18663 match project_completions.await? {
18664 Some(mut completions) => {
18665 completions.extend(snippets_completions);
18666 Ok(Some(completions))
18667 }
18668 None => {
18669 if snippets_completions.is_empty() {
18670 Ok(None)
18671 } else {
18672 Ok(Some(snippets_completions))
18673 }
18674 }
18675 }
18676 })
18677 })
18678 }
18679
18680 fn resolve_completions(
18681 &self,
18682 buffer: Entity<Buffer>,
18683 completion_indices: Vec<usize>,
18684 completions: Rc<RefCell<Box<[Completion]>>>,
18685 cx: &mut Context<Editor>,
18686 ) -> Task<Result<bool>> {
18687 self.update(cx, |project, cx| {
18688 project.lsp_store().update(cx, |lsp_store, cx| {
18689 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18690 })
18691 })
18692 }
18693
18694 fn apply_additional_edits_for_completion(
18695 &self,
18696 buffer: Entity<Buffer>,
18697 completions: Rc<RefCell<Box<[Completion]>>>,
18698 completion_index: usize,
18699 push_to_history: bool,
18700 cx: &mut Context<Editor>,
18701 ) -> Task<Result<Option<language::Transaction>>> {
18702 self.update(cx, |project, cx| {
18703 project.lsp_store().update(cx, |lsp_store, cx| {
18704 lsp_store.apply_additional_edits_for_completion(
18705 buffer,
18706 completions,
18707 completion_index,
18708 push_to_history,
18709 cx,
18710 )
18711 })
18712 })
18713 }
18714
18715 fn is_completion_trigger(
18716 &self,
18717 buffer: &Entity<Buffer>,
18718 position: language::Anchor,
18719 text: &str,
18720 trigger_in_words: bool,
18721 cx: &mut Context<Editor>,
18722 ) -> bool {
18723 let mut chars = text.chars();
18724 let char = if let Some(char) = chars.next() {
18725 char
18726 } else {
18727 return false;
18728 };
18729 if chars.next().is_some() {
18730 return false;
18731 }
18732
18733 let buffer = buffer.read(cx);
18734 let snapshot = buffer.snapshot();
18735 if !snapshot.settings_at(position, cx).show_completions_on_input {
18736 return false;
18737 }
18738 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18739 if trigger_in_words && classifier.is_word(char) {
18740 return true;
18741 }
18742
18743 buffer.completion_triggers().contains(text)
18744 }
18745}
18746
18747impl SemanticsProvider for Entity<Project> {
18748 fn hover(
18749 &self,
18750 buffer: &Entity<Buffer>,
18751 position: text::Anchor,
18752 cx: &mut App,
18753 ) -> Option<Task<Vec<project::Hover>>> {
18754 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18755 }
18756
18757 fn document_highlights(
18758 &self,
18759 buffer: &Entity<Buffer>,
18760 position: text::Anchor,
18761 cx: &mut App,
18762 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18763 Some(self.update(cx, |project, cx| {
18764 project.document_highlights(buffer, position, cx)
18765 }))
18766 }
18767
18768 fn definitions(
18769 &self,
18770 buffer: &Entity<Buffer>,
18771 position: text::Anchor,
18772 kind: GotoDefinitionKind,
18773 cx: &mut App,
18774 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18775 Some(self.update(cx, |project, cx| match kind {
18776 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18777 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18778 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18779 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18780 }))
18781 }
18782
18783 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18784 // TODO: make this work for remote projects
18785 self.update(cx, |this, cx| {
18786 buffer.update(cx, |buffer, cx| {
18787 this.any_language_server_supports_inlay_hints(buffer, cx)
18788 })
18789 })
18790 }
18791
18792 fn inlay_hints(
18793 &self,
18794 buffer_handle: Entity<Buffer>,
18795 range: Range<text::Anchor>,
18796 cx: &mut App,
18797 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18798 Some(self.update(cx, |project, cx| {
18799 project.inlay_hints(buffer_handle, range, cx)
18800 }))
18801 }
18802
18803 fn resolve_inlay_hint(
18804 &self,
18805 hint: InlayHint,
18806 buffer_handle: Entity<Buffer>,
18807 server_id: LanguageServerId,
18808 cx: &mut App,
18809 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18810 Some(self.update(cx, |project, cx| {
18811 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18812 }))
18813 }
18814
18815 fn range_for_rename(
18816 &self,
18817 buffer: &Entity<Buffer>,
18818 position: text::Anchor,
18819 cx: &mut App,
18820 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18821 Some(self.update(cx, |project, cx| {
18822 let buffer = buffer.clone();
18823 let task = project.prepare_rename(buffer.clone(), position, cx);
18824 cx.spawn(async move |_, cx| {
18825 Ok(match task.await? {
18826 PrepareRenameResponse::Success(range) => Some(range),
18827 PrepareRenameResponse::InvalidPosition => None,
18828 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18829 // Fallback on using TreeSitter info to determine identifier range
18830 buffer.update(cx, |buffer, _| {
18831 let snapshot = buffer.snapshot();
18832 let (range, kind) = snapshot.surrounding_word(position);
18833 if kind != Some(CharKind::Word) {
18834 return None;
18835 }
18836 Some(
18837 snapshot.anchor_before(range.start)
18838 ..snapshot.anchor_after(range.end),
18839 )
18840 })?
18841 }
18842 })
18843 })
18844 }))
18845 }
18846
18847 fn perform_rename(
18848 &self,
18849 buffer: &Entity<Buffer>,
18850 position: text::Anchor,
18851 new_name: String,
18852 cx: &mut App,
18853 ) -> Option<Task<Result<ProjectTransaction>>> {
18854 Some(self.update(cx, |project, cx| {
18855 project.perform_rename(buffer.clone(), position, new_name, cx)
18856 }))
18857 }
18858}
18859
18860fn inlay_hint_settings(
18861 location: Anchor,
18862 snapshot: &MultiBufferSnapshot,
18863 cx: &mut Context<Editor>,
18864) -> InlayHintSettings {
18865 let file = snapshot.file_at(location);
18866 let language = snapshot.language_at(location).map(|l| l.name());
18867 language_settings(language, file, cx).inlay_hints
18868}
18869
18870fn consume_contiguous_rows(
18871 contiguous_row_selections: &mut Vec<Selection<Point>>,
18872 selection: &Selection<Point>,
18873 display_map: &DisplaySnapshot,
18874 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18875) -> (MultiBufferRow, MultiBufferRow) {
18876 contiguous_row_selections.push(selection.clone());
18877 let start_row = MultiBufferRow(selection.start.row);
18878 let mut end_row = ending_row(selection, display_map);
18879
18880 while let Some(next_selection) = selections.peek() {
18881 if next_selection.start.row <= end_row.0 {
18882 end_row = ending_row(next_selection, display_map);
18883 contiguous_row_selections.push(selections.next().unwrap().clone());
18884 } else {
18885 break;
18886 }
18887 }
18888 (start_row, end_row)
18889}
18890
18891fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18892 if next_selection.end.column > 0 || next_selection.is_empty() {
18893 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18894 } else {
18895 MultiBufferRow(next_selection.end.row)
18896 }
18897}
18898
18899impl EditorSnapshot {
18900 pub fn remote_selections_in_range<'a>(
18901 &'a self,
18902 range: &'a Range<Anchor>,
18903 collaboration_hub: &dyn CollaborationHub,
18904 cx: &'a App,
18905 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18906 let participant_names = collaboration_hub.user_names(cx);
18907 let participant_indices = collaboration_hub.user_participant_indices(cx);
18908 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18909 let collaborators_by_replica_id = collaborators_by_peer_id
18910 .iter()
18911 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18912 .collect::<HashMap<_, _>>();
18913 self.buffer_snapshot
18914 .selections_in_range(range, false)
18915 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18916 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18917 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18918 let user_name = participant_names.get(&collaborator.user_id).cloned();
18919 Some(RemoteSelection {
18920 replica_id,
18921 selection,
18922 cursor_shape,
18923 line_mode,
18924 participant_index,
18925 peer_id: collaborator.peer_id,
18926 user_name,
18927 })
18928 })
18929 }
18930
18931 pub fn hunks_for_ranges(
18932 &self,
18933 ranges: impl IntoIterator<Item = Range<Point>>,
18934 ) -> Vec<MultiBufferDiffHunk> {
18935 let mut hunks = Vec::new();
18936 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18937 HashMap::default();
18938 for query_range in ranges {
18939 let query_rows =
18940 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18941 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18942 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18943 ) {
18944 // Include deleted hunks that are adjacent to the query range, because
18945 // otherwise they would be missed.
18946 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18947 if hunk.status().is_deleted() {
18948 intersects_range |= hunk.row_range.start == query_rows.end;
18949 intersects_range |= hunk.row_range.end == query_rows.start;
18950 }
18951 if intersects_range {
18952 if !processed_buffer_rows
18953 .entry(hunk.buffer_id)
18954 .or_default()
18955 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18956 {
18957 continue;
18958 }
18959 hunks.push(hunk);
18960 }
18961 }
18962 }
18963
18964 hunks
18965 }
18966
18967 fn display_diff_hunks_for_rows<'a>(
18968 &'a self,
18969 display_rows: Range<DisplayRow>,
18970 folded_buffers: &'a HashSet<BufferId>,
18971 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18972 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18973 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18974
18975 self.buffer_snapshot
18976 .diff_hunks_in_range(buffer_start..buffer_end)
18977 .filter_map(|hunk| {
18978 if folded_buffers.contains(&hunk.buffer_id) {
18979 return None;
18980 }
18981
18982 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18983 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18984
18985 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18986 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18987
18988 let display_hunk = if hunk_display_start.column() != 0 {
18989 DisplayDiffHunk::Folded {
18990 display_row: hunk_display_start.row(),
18991 }
18992 } else {
18993 let mut end_row = hunk_display_end.row();
18994 if hunk_display_end.column() > 0 {
18995 end_row.0 += 1;
18996 }
18997 let is_created_file = hunk.is_created_file();
18998 DisplayDiffHunk::Unfolded {
18999 status: hunk.status(),
19000 diff_base_byte_range: hunk.diff_base_byte_range,
19001 display_row_range: hunk_display_start.row()..end_row,
19002 multi_buffer_range: Anchor::range_in_buffer(
19003 hunk.excerpt_id,
19004 hunk.buffer_id,
19005 hunk.buffer_range,
19006 ),
19007 is_created_file,
19008 }
19009 };
19010
19011 Some(display_hunk)
19012 })
19013 }
19014
19015 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19016 self.display_snapshot.buffer_snapshot.language_at(position)
19017 }
19018
19019 pub fn is_focused(&self) -> bool {
19020 self.is_focused
19021 }
19022
19023 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19024 self.placeholder_text.as_ref()
19025 }
19026
19027 pub fn scroll_position(&self) -> gpui::Point<f32> {
19028 self.scroll_anchor.scroll_position(&self.display_snapshot)
19029 }
19030
19031 fn gutter_dimensions(
19032 &self,
19033 font_id: FontId,
19034 font_size: Pixels,
19035 max_line_number_width: Pixels,
19036 cx: &App,
19037 ) -> Option<GutterDimensions> {
19038 if !self.show_gutter {
19039 return None;
19040 }
19041
19042 let descent = cx.text_system().descent(font_id, font_size);
19043 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19044 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19045
19046 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19047 matches!(
19048 ProjectSettings::get_global(cx).git.git_gutter,
19049 Some(GitGutterSetting::TrackedFiles)
19050 )
19051 });
19052 let gutter_settings = EditorSettings::get_global(cx).gutter;
19053 let show_line_numbers = self
19054 .show_line_numbers
19055 .unwrap_or(gutter_settings.line_numbers);
19056 let line_gutter_width = if show_line_numbers {
19057 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19058 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19059 max_line_number_width.max(min_width_for_number_on_gutter)
19060 } else {
19061 0.0.into()
19062 };
19063
19064 let show_code_actions = self
19065 .show_code_actions
19066 .unwrap_or(gutter_settings.code_actions);
19067
19068 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19069 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19070
19071 let git_blame_entries_width =
19072 self.git_blame_gutter_max_author_length
19073 .map(|max_author_length| {
19074 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19075 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19076
19077 /// The number of characters to dedicate to gaps and margins.
19078 const SPACING_WIDTH: usize = 4;
19079
19080 let max_char_count = max_author_length.min(renderer.max_author_length())
19081 + ::git::SHORT_SHA_LENGTH
19082 + MAX_RELATIVE_TIMESTAMP.len()
19083 + SPACING_WIDTH;
19084
19085 em_advance * max_char_count
19086 });
19087
19088 let is_singleton = self.buffer_snapshot.is_singleton();
19089
19090 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19091 left_padding += if !is_singleton {
19092 em_width * 4.0
19093 } else if show_code_actions || show_runnables || show_breakpoints {
19094 em_width * 3.0
19095 } else if show_git_gutter && show_line_numbers {
19096 em_width * 2.0
19097 } else if show_git_gutter || show_line_numbers {
19098 em_width
19099 } else {
19100 px(0.)
19101 };
19102
19103 let shows_folds = is_singleton && gutter_settings.folds;
19104
19105 let right_padding = if shows_folds && show_line_numbers {
19106 em_width * 4.0
19107 } else if shows_folds || (!is_singleton && show_line_numbers) {
19108 em_width * 3.0
19109 } else if show_line_numbers {
19110 em_width
19111 } else {
19112 px(0.)
19113 };
19114
19115 Some(GutterDimensions {
19116 left_padding,
19117 right_padding,
19118 width: line_gutter_width + left_padding + right_padding,
19119 margin: -descent,
19120 git_blame_entries_width,
19121 })
19122 }
19123
19124 pub fn render_crease_toggle(
19125 &self,
19126 buffer_row: MultiBufferRow,
19127 row_contains_cursor: bool,
19128 editor: Entity<Editor>,
19129 window: &mut Window,
19130 cx: &mut App,
19131 ) -> Option<AnyElement> {
19132 let folded = self.is_line_folded(buffer_row);
19133 let mut is_foldable = false;
19134
19135 if let Some(crease) = self
19136 .crease_snapshot
19137 .query_row(buffer_row, &self.buffer_snapshot)
19138 {
19139 is_foldable = true;
19140 match crease {
19141 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19142 if let Some(render_toggle) = render_toggle {
19143 let toggle_callback =
19144 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19145 if folded {
19146 editor.update(cx, |editor, cx| {
19147 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19148 });
19149 } else {
19150 editor.update(cx, |editor, cx| {
19151 editor.unfold_at(
19152 &crate::UnfoldAt { buffer_row },
19153 window,
19154 cx,
19155 )
19156 });
19157 }
19158 });
19159 return Some((render_toggle)(
19160 buffer_row,
19161 folded,
19162 toggle_callback,
19163 window,
19164 cx,
19165 ));
19166 }
19167 }
19168 }
19169 }
19170
19171 is_foldable |= self.starts_indent(buffer_row);
19172
19173 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19174 Some(
19175 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19176 .toggle_state(folded)
19177 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19178 if folded {
19179 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19180 } else {
19181 this.fold_at(&FoldAt { buffer_row }, window, cx);
19182 }
19183 }))
19184 .into_any_element(),
19185 )
19186 } else {
19187 None
19188 }
19189 }
19190
19191 pub fn render_crease_trailer(
19192 &self,
19193 buffer_row: MultiBufferRow,
19194 window: &mut Window,
19195 cx: &mut App,
19196 ) -> Option<AnyElement> {
19197 let folded = self.is_line_folded(buffer_row);
19198 if let Crease::Inline { render_trailer, .. } = self
19199 .crease_snapshot
19200 .query_row(buffer_row, &self.buffer_snapshot)?
19201 {
19202 let render_trailer = render_trailer.as_ref()?;
19203 Some(render_trailer(buffer_row, folded, window, cx))
19204 } else {
19205 None
19206 }
19207 }
19208}
19209
19210impl Deref for EditorSnapshot {
19211 type Target = DisplaySnapshot;
19212
19213 fn deref(&self) -> &Self::Target {
19214 &self.display_snapshot
19215 }
19216}
19217
19218#[derive(Clone, Debug, PartialEq, Eq)]
19219pub enum EditorEvent {
19220 InputIgnored {
19221 text: Arc<str>,
19222 },
19223 InputHandled {
19224 utf16_range_to_replace: Option<Range<isize>>,
19225 text: Arc<str>,
19226 },
19227 ExcerptsAdded {
19228 buffer: Entity<Buffer>,
19229 predecessor: ExcerptId,
19230 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19231 },
19232 ExcerptsRemoved {
19233 ids: Vec<ExcerptId>,
19234 },
19235 BufferFoldToggled {
19236 ids: Vec<ExcerptId>,
19237 folded: bool,
19238 },
19239 ExcerptsEdited {
19240 ids: Vec<ExcerptId>,
19241 },
19242 ExcerptsExpanded {
19243 ids: Vec<ExcerptId>,
19244 },
19245 BufferEdited,
19246 Edited {
19247 transaction_id: clock::Lamport,
19248 },
19249 Reparsed(BufferId),
19250 Focused,
19251 FocusedIn,
19252 Blurred,
19253 DirtyChanged,
19254 Saved,
19255 TitleChanged,
19256 DiffBaseChanged,
19257 SelectionsChanged {
19258 local: bool,
19259 },
19260 ScrollPositionChanged {
19261 local: bool,
19262 autoscroll: bool,
19263 },
19264 Closed,
19265 TransactionUndone {
19266 transaction_id: clock::Lamport,
19267 },
19268 TransactionBegun {
19269 transaction_id: clock::Lamport,
19270 },
19271 Reloaded,
19272 CursorShapeChanged,
19273 PushedToNavHistory {
19274 anchor: Anchor,
19275 is_deactivate: bool,
19276 },
19277}
19278
19279impl EventEmitter<EditorEvent> for Editor {}
19280
19281impl Focusable for Editor {
19282 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19283 self.focus_handle.clone()
19284 }
19285}
19286
19287impl Render for Editor {
19288 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19289 let settings = ThemeSettings::get_global(cx);
19290
19291 let mut text_style = match self.mode {
19292 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19293 color: cx.theme().colors().editor_foreground,
19294 font_family: settings.ui_font.family.clone(),
19295 font_features: settings.ui_font.features.clone(),
19296 font_fallbacks: settings.ui_font.fallbacks.clone(),
19297 font_size: rems(0.875).into(),
19298 font_weight: settings.ui_font.weight,
19299 line_height: relative(settings.buffer_line_height.value()),
19300 ..Default::default()
19301 },
19302 EditorMode::Full => TextStyle {
19303 color: cx.theme().colors().editor_foreground,
19304 font_family: settings.buffer_font.family.clone(),
19305 font_features: settings.buffer_font.features.clone(),
19306 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19307 font_size: settings.buffer_font_size(cx).into(),
19308 font_weight: settings.buffer_font.weight,
19309 line_height: relative(settings.buffer_line_height.value()),
19310 ..Default::default()
19311 },
19312 };
19313 if let Some(text_style_refinement) = &self.text_style_refinement {
19314 text_style.refine(text_style_refinement)
19315 }
19316
19317 let background = match self.mode {
19318 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19319 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19320 EditorMode::Full => cx.theme().colors().editor_background,
19321 };
19322
19323 EditorElement::new(
19324 &cx.entity(),
19325 EditorStyle {
19326 background,
19327 local_player: cx.theme().players().local(),
19328 text: text_style,
19329 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19330 syntax: cx.theme().syntax().clone(),
19331 status: cx.theme().status().clone(),
19332 inlay_hints_style: make_inlay_hints_style(cx),
19333 inline_completion_styles: make_suggestion_styles(cx),
19334 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19335 },
19336 )
19337 }
19338}
19339
19340impl EntityInputHandler for Editor {
19341 fn text_for_range(
19342 &mut self,
19343 range_utf16: Range<usize>,
19344 adjusted_range: &mut Option<Range<usize>>,
19345 _: &mut Window,
19346 cx: &mut Context<Self>,
19347 ) -> Option<String> {
19348 let snapshot = self.buffer.read(cx).read(cx);
19349 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19350 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19351 if (start.0..end.0) != range_utf16 {
19352 adjusted_range.replace(start.0..end.0);
19353 }
19354 Some(snapshot.text_for_range(start..end).collect())
19355 }
19356
19357 fn selected_text_range(
19358 &mut self,
19359 ignore_disabled_input: bool,
19360 _: &mut Window,
19361 cx: &mut Context<Self>,
19362 ) -> Option<UTF16Selection> {
19363 // Prevent the IME menu from appearing when holding down an alphabetic key
19364 // while input is disabled.
19365 if !ignore_disabled_input && !self.input_enabled {
19366 return None;
19367 }
19368
19369 let selection = self.selections.newest::<OffsetUtf16>(cx);
19370 let range = selection.range();
19371
19372 Some(UTF16Selection {
19373 range: range.start.0..range.end.0,
19374 reversed: selection.reversed,
19375 })
19376 }
19377
19378 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19379 let snapshot = self.buffer.read(cx).read(cx);
19380 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19381 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19382 }
19383
19384 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19385 self.clear_highlights::<InputComposition>(cx);
19386 self.ime_transaction.take();
19387 }
19388
19389 fn replace_text_in_range(
19390 &mut self,
19391 range_utf16: Option<Range<usize>>,
19392 text: &str,
19393 window: &mut Window,
19394 cx: &mut Context<Self>,
19395 ) {
19396 if !self.input_enabled {
19397 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19398 return;
19399 }
19400
19401 self.transact(window, cx, |this, window, cx| {
19402 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19403 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19404 Some(this.selection_replacement_ranges(range_utf16, cx))
19405 } else {
19406 this.marked_text_ranges(cx)
19407 };
19408
19409 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19410 let newest_selection_id = this.selections.newest_anchor().id;
19411 this.selections
19412 .all::<OffsetUtf16>(cx)
19413 .iter()
19414 .zip(ranges_to_replace.iter())
19415 .find_map(|(selection, range)| {
19416 if selection.id == newest_selection_id {
19417 Some(
19418 (range.start.0 as isize - selection.head().0 as isize)
19419 ..(range.end.0 as isize - selection.head().0 as isize),
19420 )
19421 } else {
19422 None
19423 }
19424 })
19425 });
19426
19427 cx.emit(EditorEvent::InputHandled {
19428 utf16_range_to_replace: range_to_replace,
19429 text: text.into(),
19430 });
19431
19432 if let Some(new_selected_ranges) = new_selected_ranges {
19433 this.change_selections(None, window, cx, |selections| {
19434 selections.select_ranges(new_selected_ranges)
19435 });
19436 this.backspace(&Default::default(), window, cx);
19437 }
19438
19439 this.handle_input(text, window, cx);
19440 });
19441
19442 if let Some(transaction) = self.ime_transaction {
19443 self.buffer.update(cx, |buffer, cx| {
19444 buffer.group_until_transaction(transaction, cx);
19445 });
19446 }
19447
19448 self.unmark_text(window, cx);
19449 }
19450
19451 fn replace_and_mark_text_in_range(
19452 &mut self,
19453 range_utf16: Option<Range<usize>>,
19454 text: &str,
19455 new_selected_range_utf16: Option<Range<usize>>,
19456 window: &mut Window,
19457 cx: &mut Context<Self>,
19458 ) {
19459 if !self.input_enabled {
19460 return;
19461 }
19462
19463 let transaction = self.transact(window, cx, |this, window, cx| {
19464 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19465 let snapshot = this.buffer.read(cx).read(cx);
19466 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19467 for marked_range in &mut marked_ranges {
19468 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19469 marked_range.start.0 += relative_range_utf16.start;
19470 marked_range.start =
19471 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19472 marked_range.end =
19473 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19474 }
19475 }
19476 Some(marked_ranges)
19477 } else if let Some(range_utf16) = range_utf16 {
19478 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19479 Some(this.selection_replacement_ranges(range_utf16, cx))
19480 } else {
19481 None
19482 };
19483
19484 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19485 let newest_selection_id = this.selections.newest_anchor().id;
19486 this.selections
19487 .all::<OffsetUtf16>(cx)
19488 .iter()
19489 .zip(ranges_to_replace.iter())
19490 .find_map(|(selection, range)| {
19491 if selection.id == newest_selection_id {
19492 Some(
19493 (range.start.0 as isize - selection.head().0 as isize)
19494 ..(range.end.0 as isize - selection.head().0 as isize),
19495 )
19496 } else {
19497 None
19498 }
19499 })
19500 });
19501
19502 cx.emit(EditorEvent::InputHandled {
19503 utf16_range_to_replace: range_to_replace,
19504 text: text.into(),
19505 });
19506
19507 if let Some(ranges) = ranges_to_replace {
19508 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19509 }
19510
19511 let marked_ranges = {
19512 let snapshot = this.buffer.read(cx).read(cx);
19513 this.selections
19514 .disjoint_anchors()
19515 .iter()
19516 .map(|selection| {
19517 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19518 })
19519 .collect::<Vec<_>>()
19520 };
19521
19522 if text.is_empty() {
19523 this.unmark_text(window, cx);
19524 } else {
19525 this.highlight_text::<InputComposition>(
19526 marked_ranges.clone(),
19527 HighlightStyle {
19528 underline: Some(UnderlineStyle {
19529 thickness: px(1.),
19530 color: None,
19531 wavy: false,
19532 }),
19533 ..Default::default()
19534 },
19535 cx,
19536 );
19537 }
19538
19539 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19540 let use_autoclose = this.use_autoclose;
19541 let use_auto_surround = this.use_auto_surround;
19542 this.set_use_autoclose(false);
19543 this.set_use_auto_surround(false);
19544 this.handle_input(text, window, cx);
19545 this.set_use_autoclose(use_autoclose);
19546 this.set_use_auto_surround(use_auto_surround);
19547
19548 if let Some(new_selected_range) = new_selected_range_utf16 {
19549 let snapshot = this.buffer.read(cx).read(cx);
19550 let new_selected_ranges = marked_ranges
19551 .into_iter()
19552 .map(|marked_range| {
19553 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19554 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19555 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19556 snapshot.clip_offset_utf16(new_start, Bias::Left)
19557 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19558 })
19559 .collect::<Vec<_>>();
19560
19561 drop(snapshot);
19562 this.change_selections(None, window, cx, |selections| {
19563 selections.select_ranges(new_selected_ranges)
19564 });
19565 }
19566 });
19567
19568 self.ime_transaction = self.ime_transaction.or(transaction);
19569 if let Some(transaction) = self.ime_transaction {
19570 self.buffer.update(cx, |buffer, cx| {
19571 buffer.group_until_transaction(transaction, cx);
19572 });
19573 }
19574
19575 if self.text_highlights::<InputComposition>(cx).is_none() {
19576 self.ime_transaction.take();
19577 }
19578 }
19579
19580 fn bounds_for_range(
19581 &mut self,
19582 range_utf16: Range<usize>,
19583 element_bounds: gpui::Bounds<Pixels>,
19584 window: &mut Window,
19585 cx: &mut Context<Self>,
19586 ) -> Option<gpui::Bounds<Pixels>> {
19587 let text_layout_details = self.text_layout_details(window);
19588 let gpui::Size {
19589 width: em_width,
19590 height: line_height,
19591 } = self.character_size(window);
19592
19593 let snapshot = self.snapshot(window, cx);
19594 let scroll_position = snapshot.scroll_position();
19595 let scroll_left = scroll_position.x * em_width;
19596
19597 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19598 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19599 + self.gutter_dimensions.width
19600 + self.gutter_dimensions.margin;
19601 let y = line_height * (start.row().as_f32() - scroll_position.y);
19602
19603 Some(Bounds {
19604 origin: element_bounds.origin + point(x, y),
19605 size: size(em_width, line_height),
19606 })
19607 }
19608
19609 fn character_index_for_point(
19610 &mut self,
19611 point: gpui::Point<Pixels>,
19612 _window: &mut Window,
19613 _cx: &mut Context<Self>,
19614 ) -> Option<usize> {
19615 let position_map = self.last_position_map.as_ref()?;
19616 if !position_map.text_hitbox.contains(&point) {
19617 return None;
19618 }
19619 let display_point = position_map.point_for_position(point).previous_valid;
19620 let anchor = position_map
19621 .snapshot
19622 .display_point_to_anchor(display_point, Bias::Left);
19623 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19624 Some(utf16_offset.0)
19625 }
19626}
19627
19628trait SelectionExt {
19629 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19630 fn spanned_rows(
19631 &self,
19632 include_end_if_at_line_start: bool,
19633 map: &DisplaySnapshot,
19634 ) -> Range<MultiBufferRow>;
19635}
19636
19637impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19638 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19639 let start = self
19640 .start
19641 .to_point(&map.buffer_snapshot)
19642 .to_display_point(map);
19643 let end = self
19644 .end
19645 .to_point(&map.buffer_snapshot)
19646 .to_display_point(map);
19647 if self.reversed {
19648 end..start
19649 } else {
19650 start..end
19651 }
19652 }
19653
19654 fn spanned_rows(
19655 &self,
19656 include_end_if_at_line_start: bool,
19657 map: &DisplaySnapshot,
19658 ) -> Range<MultiBufferRow> {
19659 let start = self.start.to_point(&map.buffer_snapshot);
19660 let mut end = self.end.to_point(&map.buffer_snapshot);
19661 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19662 end.row -= 1;
19663 }
19664
19665 let buffer_start = map.prev_line_boundary(start).0;
19666 let buffer_end = map.next_line_boundary(end).0;
19667 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19668 }
19669}
19670
19671impl<T: InvalidationRegion> InvalidationStack<T> {
19672 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19673 where
19674 S: Clone + ToOffset,
19675 {
19676 while let Some(region) = self.last() {
19677 let all_selections_inside_invalidation_ranges =
19678 if selections.len() == region.ranges().len() {
19679 selections
19680 .iter()
19681 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19682 .all(|(selection, invalidation_range)| {
19683 let head = selection.head().to_offset(buffer);
19684 invalidation_range.start <= head && invalidation_range.end >= head
19685 })
19686 } else {
19687 false
19688 };
19689
19690 if all_selections_inside_invalidation_ranges {
19691 break;
19692 } else {
19693 self.pop();
19694 }
19695 }
19696 }
19697}
19698
19699impl<T> Default for InvalidationStack<T> {
19700 fn default() -> Self {
19701 Self(Default::default())
19702 }
19703}
19704
19705impl<T> Deref for InvalidationStack<T> {
19706 type Target = Vec<T>;
19707
19708 fn deref(&self) -> &Self::Target {
19709 &self.0
19710 }
19711}
19712
19713impl<T> DerefMut for InvalidationStack<T> {
19714 fn deref_mut(&mut self) -> &mut Self::Target {
19715 &mut self.0
19716 }
19717}
19718
19719impl InvalidationRegion for SnippetState {
19720 fn ranges(&self) -> &[Range<Anchor>] {
19721 &self.ranges[self.active_index]
19722 }
19723}
19724
19725pub fn diagnostic_block_renderer(
19726 diagnostic: Diagnostic,
19727 max_message_rows: Option<u8>,
19728 allow_closing: bool,
19729) -> RenderBlock {
19730 let (text_without_backticks, code_ranges) =
19731 highlight_diagnostic_message(&diagnostic, max_message_rows);
19732
19733 Arc::new(move |cx: &mut BlockContext| {
19734 let group_id: SharedString = cx.block_id.to_string().into();
19735
19736 let mut text_style = cx.window.text_style().clone();
19737 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19738 let theme_settings = ThemeSettings::get_global(cx);
19739 text_style.font_family = theme_settings.buffer_font.family.clone();
19740 text_style.font_style = theme_settings.buffer_font.style;
19741 text_style.font_features = theme_settings.buffer_font.features.clone();
19742 text_style.font_weight = theme_settings.buffer_font.weight;
19743
19744 let multi_line_diagnostic = diagnostic.message.contains('\n');
19745
19746 let buttons = |diagnostic: &Diagnostic| {
19747 if multi_line_diagnostic {
19748 v_flex()
19749 } else {
19750 h_flex()
19751 }
19752 .when(allow_closing, |div| {
19753 div.children(diagnostic.is_primary.then(|| {
19754 IconButton::new("close-block", IconName::XCircle)
19755 .icon_color(Color::Muted)
19756 .size(ButtonSize::Compact)
19757 .style(ButtonStyle::Transparent)
19758 .visible_on_hover(group_id.clone())
19759 .on_click(move |_click, window, cx| {
19760 window.dispatch_action(Box::new(Cancel), cx)
19761 })
19762 .tooltip(|window, cx| {
19763 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19764 })
19765 }))
19766 })
19767 .child(
19768 IconButton::new("copy-block", IconName::Copy)
19769 .icon_color(Color::Muted)
19770 .size(ButtonSize::Compact)
19771 .style(ButtonStyle::Transparent)
19772 .visible_on_hover(group_id.clone())
19773 .on_click({
19774 let message = diagnostic.message.clone();
19775 move |_click, _, cx| {
19776 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19777 }
19778 })
19779 .tooltip(Tooltip::text("Copy diagnostic message")),
19780 )
19781 };
19782
19783 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19784 AvailableSpace::min_size(),
19785 cx.window,
19786 cx.app,
19787 );
19788
19789 h_flex()
19790 .id(cx.block_id)
19791 .group(group_id.clone())
19792 .relative()
19793 .size_full()
19794 .block_mouse_down()
19795 .pl(cx.gutter_dimensions.width)
19796 .w(cx.max_width - cx.gutter_dimensions.full_width())
19797 .child(
19798 div()
19799 .flex()
19800 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19801 .flex_shrink(),
19802 )
19803 .child(buttons(&diagnostic))
19804 .child(div().flex().flex_shrink_0().child(
19805 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19806 &text_style,
19807 code_ranges.iter().map(|range| {
19808 (
19809 range.clone(),
19810 HighlightStyle {
19811 font_weight: Some(FontWeight::BOLD),
19812 ..Default::default()
19813 },
19814 )
19815 }),
19816 ),
19817 ))
19818 .into_any_element()
19819 })
19820}
19821
19822fn inline_completion_edit_text(
19823 current_snapshot: &BufferSnapshot,
19824 edits: &[(Range<Anchor>, String)],
19825 edit_preview: &EditPreview,
19826 include_deletions: bool,
19827 cx: &App,
19828) -> HighlightedText {
19829 let edits = edits
19830 .iter()
19831 .map(|(anchor, text)| {
19832 (
19833 anchor.start.text_anchor..anchor.end.text_anchor,
19834 text.clone(),
19835 )
19836 })
19837 .collect::<Vec<_>>();
19838
19839 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19840}
19841
19842pub fn highlight_diagnostic_message(
19843 diagnostic: &Diagnostic,
19844 mut max_message_rows: Option<u8>,
19845) -> (SharedString, Vec<Range<usize>>) {
19846 let mut text_without_backticks = String::new();
19847 let mut code_ranges = Vec::new();
19848
19849 if let Some(source) = &diagnostic.source {
19850 text_without_backticks.push_str(source);
19851 code_ranges.push(0..source.len());
19852 text_without_backticks.push_str(": ");
19853 }
19854
19855 let mut prev_offset = 0;
19856 let mut in_code_block = false;
19857 let has_row_limit = max_message_rows.is_some();
19858 let mut newline_indices = diagnostic
19859 .message
19860 .match_indices('\n')
19861 .filter(|_| has_row_limit)
19862 .map(|(ix, _)| ix)
19863 .fuse()
19864 .peekable();
19865
19866 for (quote_ix, _) in diagnostic
19867 .message
19868 .match_indices('`')
19869 .chain([(diagnostic.message.len(), "")])
19870 {
19871 let mut first_newline_ix = None;
19872 let mut last_newline_ix = None;
19873 while let Some(newline_ix) = newline_indices.peek() {
19874 if *newline_ix < quote_ix {
19875 if first_newline_ix.is_none() {
19876 first_newline_ix = Some(*newline_ix);
19877 }
19878 last_newline_ix = Some(*newline_ix);
19879
19880 if let Some(rows_left) = &mut max_message_rows {
19881 if *rows_left == 0 {
19882 break;
19883 } else {
19884 *rows_left -= 1;
19885 }
19886 }
19887 let _ = newline_indices.next();
19888 } else {
19889 break;
19890 }
19891 }
19892 let prev_len = text_without_backticks.len();
19893 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19894 text_without_backticks.push_str(new_text);
19895 if in_code_block {
19896 code_ranges.push(prev_len..text_without_backticks.len());
19897 }
19898 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19899 in_code_block = !in_code_block;
19900 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19901 text_without_backticks.push_str("...");
19902 break;
19903 }
19904 }
19905
19906 (text_without_backticks.into(), code_ranges)
19907}
19908
19909fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19910 match severity {
19911 DiagnosticSeverity::ERROR => colors.error,
19912 DiagnosticSeverity::WARNING => colors.warning,
19913 DiagnosticSeverity::INFORMATION => colors.info,
19914 DiagnosticSeverity::HINT => colors.info,
19915 _ => colors.ignored,
19916 }
19917}
19918
19919pub fn styled_runs_for_code_label<'a>(
19920 label: &'a CodeLabel,
19921 syntax_theme: &'a theme::SyntaxTheme,
19922) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19923 let fade_out = HighlightStyle {
19924 fade_out: Some(0.35),
19925 ..Default::default()
19926 };
19927
19928 let mut prev_end = label.filter_range.end;
19929 label
19930 .runs
19931 .iter()
19932 .enumerate()
19933 .flat_map(move |(ix, (range, highlight_id))| {
19934 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19935 style
19936 } else {
19937 return Default::default();
19938 };
19939 let mut muted_style = style;
19940 muted_style.highlight(fade_out);
19941
19942 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19943 if range.start >= label.filter_range.end {
19944 if range.start > prev_end {
19945 runs.push((prev_end..range.start, fade_out));
19946 }
19947 runs.push((range.clone(), muted_style));
19948 } else if range.end <= label.filter_range.end {
19949 runs.push((range.clone(), style));
19950 } else {
19951 runs.push((range.start..label.filter_range.end, style));
19952 runs.push((label.filter_range.end..range.end, muted_style));
19953 }
19954 prev_end = cmp::max(prev_end, range.end);
19955
19956 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19957 runs.push((prev_end..label.text.len(), fade_out));
19958 }
19959
19960 runs
19961 })
19962}
19963
19964pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19965 let mut prev_index = 0;
19966 let mut prev_codepoint: Option<char> = None;
19967 text.char_indices()
19968 .chain([(text.len(), '\0')])
19969 .filter_map(move |(index, codepoint)| {
19970 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19971 let is_boundary = index == text.len()
19972 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19973 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19974 if is_boundary {
19975 let chunk = &text[prev_index..index];
19976 prev_index = index;
19977 Some(chunk)
19978 } else {
19979 None
19980 }
19981 })
19982}
19983
19984pub trait RangeToAnchorExt: Sized {
19985 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19986
19987 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19988 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19989 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19990 }
19991}
19992
19993impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19994 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19995 let start_offset = self.start.to_offset(snapshot);
19996 let end_offset = self.end.to_offset(snapshot);
19997 if start_offset == end_offset {
19998 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19999 } else {
20000 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20001 }
20002 }
20003}
20004
20005pub trait RowExt {
20006 fn as_f32(&self) -> f32;
20007
20008 fn next_row(&self) -> Self;
20009
20010 fn previous_row(&self) -> Self;
20011
20012 fn minus(&self, other: Self) -> u32;
20013}
20014
20015impl RowExt for DisplayRow {
20016 fn as_f32(&self) -> f32 {
20017 self.0 as f32
20018 }
20019
20020 fn next_row(&self) -> Self {
20021 Self(self.0 + 1)
20022 }
20023
20024 fn previous_row(&self) -> Self {
20025 Self(self.0.saturating_sub(1))
20026 }
20027
20028 fn minus(&self, other: Self) -> u32 {
20029 self.0 - other.0
20030 }
20031}
20032
20033impl RowExt for MultiBufferRow {
20034 fn as_f32(&self) -> f32 {
20035 self.0 as f32
20036 }
20037
20038 fn next_row(&self) -> Self {
20039 Self(self.0 + 1)
20040 }
20041
20042 fn previous_row(&self) -> Self {
20043 Self(self.0.saturating_sub(1))
20044 }
20045
20046 fn minus(&self, other: Self) -> u32 {
20047 self.0 - other.0
20048 }
20049}
20050
20051trait RowRangeExt {
20052 type Row;
20053
20054 fn len(&self) -> usize;
20055
20056 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20057}
20058
20059impl RowRangeExt for Range<MultiBufferRow> {
20060 type Row = MultiBufferRow;
20061
20062 fn len(&self) -> usize {
20063 (self.end.0 - self.start.0) as usize
20064 }
20065
20066 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20067 (self.start.0..self.end.0).map(MultiBufferRow)
20068 }
20069}
20070
20071impl RowRangeExt for Range<DisplayRow> {
20072 type Row = DisplayRow;
20073
20074 fn len(&self) -> usize {
20075 (self.end.0 - self.start.0) as usize
20076 }
20077
20078 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20079 (self.start.0..self.end.0).map(DisplayRow)
20080 }
20081}
20082
20083/// If select range has more than one line, we
20084/// just point the cursor to range.start.
20085fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20086 if range.start.row == range.end.row {
20087 range
20088 } else {
20089 range.start..range.start
20090 }
20091}
20092pub struct KillRing(ClipboardItem);
20093impl Global for KillRing {}
20094
20095const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20096
20097enum BreakpointPromptEditAction {
20098 Log,
20099 Condition,
20100 HitCondition,
20101}
20102
20103struct BreakpointPromptEditor {
20104 pub(crate) prompt: Entity<Editor>,
20105 editor: WeakEntity<Editor>,
20106 breakpoint_anchor: Anchor,
20107 breakpoint: Breakpoint,
20108 edit_action: BreakpointPromptEditAction,
20109 block_ids: HashSet<CustomBlockId>,
20110 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20111 _subscriptions: Vec<Subscription>,
20112}
20113
20114impl BreakpointPromptEditor {
20115 const MAX_LINES: u8 = 4;
20116
20117 fn new(
20118 editor: WeakEntity<Editor>,
20119 breakpoint_anchor: Anchor,
20120 breakpoint: Breakpoint,
20121 edit_action: BreakpointPromptEditAction,
20122 window: &mut Window,
20123 cx: &mut Context<Self>,
20124 ) -> Self {
20125 let base_text = match edit_action {
20126 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20127 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20128 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20129 }
20130 .map(|msg| msg.to_string())
20131 .unwrap_or_default();
20132
20133 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20134 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20135
20136 let prompt = cx.new(|cx| {
20137 let mut prompt = Editor::new(
20138 EditorMode::AutoHeight {
20139 max_lines: Self::MAX_LINES as usize,
20140 },
20141 buffer,
20142 None,
20143 window,
20144 cx,
20145 );
20146 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20147 prompt.set_show_cursor_when_unfocused(false, cx);
20148 prompt.set_placeholder_text(
20149 match edit_action {
20150 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20151 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20152 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20153 },
20154 cx,
20155 );
20156
20157 prompt
20158 });
20159
20160 Self {
20161 prompt,
20162 editor,
20163 breakpoint_anchor,
20164 breakpoint,
20165 edit_action,
20166 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20167 block_ids: Default::default(),
20168 _subscriptions: vec![],
20169 }
20170 }
20171
20172 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20173 self.block_ids.extend(block_ids)
20174 }
20175
20176 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20177 if let Some(editor) = self.editor.upgrade() {
20178 let message = self
20179 .prompt
20180 .read(cx)
20181 .buffer
20182 .read(cx)
20183 .as_singleton()
20184 .expect("A multi buffer in breakpoint prompt isn't possible")
20185 .read(cx)
20186 .as_rope()
20187 .to_string();
20188
20189 editor.update(cx, |editor, cx| {
20190 editor.edit_breakpoint_at_anchor(
20191 self.breakpoint_anchor,
20192 self.breakpoint.clone(),
20193 match self.edit_action {
20194 BreakpointPromptEditAction::Log => {
20195 BreakpointEditAction::EditLogMessage(message.into())
20196 }
20197 BreakpointPromptEditAction::Condition => {
20198 BreakpointEditAction::EditCondition(message.into())
20199 }
20200 BreakpointPromptEditAction::HitCondition => {
20201 BreakpointEditAction::EditHitCondition(message.into())
20202 }
20203 },
20204 cx,
20205 );
20206
20207 editor.remove_blocks(self.block_ids.clone(), None, cx);
20208 cx.focus_self(window);
20209 });
20210 }
20211 }
20212
20213 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20214 self.editor
20215 .update(cx, |editor, cx| {
20216 editor.remove_blocks(self.block_ids.clone(), None, cx);
20217 window.focus(&editor.focus_handle);
20218 })
20219 .log_err();
20220 }
20221
20222 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20223 let settings = ThemeSettings::get_global(cx);
20224 let text_style = TextStyle {
20225 color: if self.prompt.read(cx).read_only(cx) {
20226 cx.theme().colors().text_disabled
20227 } else {
20228 cx.theme().colors().text
20229 },
20230 font_family: settings.buffer_font.family.clone(),
20231 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20232 font_size: settings.buffer_font_size(cx).into(),
20233 font_weight: settings.buffer_font.weight,
20234 line_height: relative(settings.buffer_line_height.value()),
20235 ..Default::default()
20236 };
20237 EditorElement::new(
20238 &self.prompt,
20239 EditorStyle {
20240 background: cx.theme().colors().editor_background,
20241 local_player: cx.theme().players().local(),
20242 text: text_style,
20243 ..Default::default()
20244 },
20245 )
20246 }
20247}
20248
20249impl Render for BreakpointPromptEditor {
20250 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20251 let gutter_dimensions = *self.gutter_dimensions.lock();
20252 h_flex()
20253 .key_context("Editor")
20254 .bg(cx.theme().colors().editor_background)
20255 .border_y_1()
20256 .border_color(cx.theme().status().info_border)
20257 .size_full()
20258 .py(window.line_height() / 2.5)
20259 .on_action(cx.listener(Self::confirm))
20260 .on_action(cx.listener(Self::cancel))
20261 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20262 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20263 }
20264}
20265
20266impl Focusable for BreakpointPromptEditor {
20267 fn focus_handle(&self, cx: &App) -> FocusHandle {
20268 self.prompt.focus_handle(cx)
20269 }
20270}
20271
20272fn all_edits_insertions_or_deletions(
20273 edits: &Vec<(Range<Anchor>, String)>,
20274 snapshot: &MultiBufferSnapshot,
20275) -> bool {
20276 let mut all_insertions = true;
20277 let mut all_deletions = true;
20278
20279 for (range, new_text) in edits.iter() {
20280 let range_is_empty = range.to_offset(&snapshot).is_empty();
20281 let text_is_empty = new_text.is_empty();
20282
20283 if range_is_empty != text_is_empty {
20284 if range_is_empty {
20285 all_deletions = false;
20286 } else {
20287 all_insertions = false;
20288 }
20289 } else {
20290 return false;
20291 }
20292
20293 if !all_insertions && !all_deletions {
20294 return false;
20295 }
20296 }
20297 all_insertions || all_deletions
20298}
20299
20300struct MissingEditPredictionKeybindingTooltip;
20301
20302impl Render for MissingEditPredictionKeybindingTooltip {
20303 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20304 ui::tooltip_container(window, cx, |container, _, cx| {
20305 container
20306 .flex_shrink_0()
20307 .max_w_80()
20308 .min_h(rems_from_px(124.))
20309 .justify_between()
20310 .child(
20311 v_flex()
20312 .flex_1()
20313 .text_ui_sm(cx)
20314 .child(Label::new("Conflict with Accept Keybinding"))
20315 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20316 )
20317 .child(
20318 h_flex()
20319 .pb_1()
20320 .gap_1()
20321 .items_end()
20322 .w_full()
20323 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20324 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20325 }))
20326 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20327 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20328 })),
20329 )
20330 })
20331 }
20332}
20333
20334#[derive(Debug, Clone, Copy, PartialEq)]
20335pub struct LineHighlight {
20336 pub background: Background,
20337 pub border: Option<gpui::Hsla>,
20338}
20339
20340impl From<Hsla> for LineHighlight {
20341 fn from(hsla: Hsla) -> Self {
20342 Self {
20343 background: hsla.into(),
20344 border: None,
20345 }
20346 }
20347}
20348
20349impl From<Background> for LineHighlight {
20350 fn from(background: Background) -> Self {
20351 Self {
20352 background,
20353 border: None,
20354 }
20355 }
20356}
20357
20358fn render_diff_hunk_controls(
20359 row: u32,
20360 status: &DiffHunkStatus,
20361 hunk_range: Range<Anchor>,
20362 is_created_file: bool,
20363 line_height: Pixels,
20364 editor: &Entity<Editor>,
20365 _window: &mut Window,
20366 cx: &mut App,
20367) -> AnyElement {
20368 h_flex()
20369 .h(line_height)
20370 .mr_1()
20371 .gap_1()
20372 .px_0p5()
20373 .pb_1()
20374 .border_x_1()
20375 .border_b_1()
20376 .border_color(cx.theme().colors().border_variant)
20377 .rounded_b_lg()
20378 .bg(cx.theme().colors().editor_background)
20379 .gap_1()
20380 .occlude()
20381 .shadow_md()
20382 .child(if status.has_secondary_hunk() {
20383 Button::new(("stage", row as u64), "Stage")
20384 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20385 .tooltip({
20386 let focus_handle = editor.focus_handle(cx);
20387 move |window, cx| {
20388 Tooltip::for_action_in(
20389 "Stage Hunk",
20390 &::git::ToggleStaged,
20391 &focus_handle,
20392 window,
20393 cx,
20394 )
20395 }
20396 })
20397 .on_click({
20398 let editor = editor.clone();
20399 move |_event, _window, cx| {
20400 editor.update(cx, |editor, cx| {
20401 editor.stage_or_unstage_diff_hunks(
20402 true,
20403 vec![hunk_range.start..hunk_range.start],
20404 cx,
20405 );
20406 });
20407 }
20408 })
20409 } else {
20410 Button::new(("unstage", row as u64), "Unstage")
20411 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20412 .tooltip({
20413 let focus_handle = editor.focus_handle(cx);
20414 move |window, cx| {
20415 Tooltip::for_action_in(
20416 "Unstage Hunk",
20417 &::git::ToggleStaged,
20418 &focus_handle,
20419 window,
20420 cx,
20421 )
20422 }
20423 })
20424 .on_click({
20425 let editor = editor.clone();
20426 move |_event, _window, cx| {
20427 editor.update(cx, |editor, cx| {
20428 editor.stage_or_unstage_diff_hunks(
20429 false,
20430 vec![hunk_range.start..hunk_range.start],
20431 cx,
20432 );
20433 });
20434 }
20435 })
20436 })
20437 .child(
20438 Button::new(("restore", row as u64), "Restore")
20439 .tooltip({
20440 let focus_handle = editor.focus_handle(cx);
20441 move |window, cx| {
20442 Tooltip::for_action_in(
20443 "Restore Hunk",
20444 &::git::Restore,
20445 &focus_handle,
20446 window,
20447 cx,
20448 )
20449 }
20450 })
20451 .on_click({
20452 let editor = editor.clone();
20453 move |_event, window, cx| {
20454 editor.update(cx, |editor, cx| {
20455 let snapshot = editor.snapshot(window, cx);
20456 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20457 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20458 });
20459 }
20460 })
20461 .disabled(is_created_file),
20462 )
20463 .when(
20464 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20465 |el| {
20466 el.child(
20467 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20468 .shape(IconButtonShape::Square)
20469 .icon_size(IconSize::Small)
20470 // .disabled(!has_multiple_hunks)
20471 .tooltip({
20472 let focus_handle = editor.focus_handle(cx);
20473 move |window, cx| {
20474 Tooltip::for_action_in(
20475 "Next Hunk",
20476 &GoToHunk,
20477 &focus_handle,
20478 window,
20479 cx,
20480 )
20481 }
20482 })
20483 .on_click({
20484 let editor = editor.clone();
20485 move |_event, window, cx| {
20486 editor.update(cx, |editor, cx| {
20487 let snapshot = editor.snapshot(window, cx);
20488 let position =
20489 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20490 editor.go_to_hunk_before_or_after_position(
20491 &snapshot,
20492 position,
20493 Direction::Next,
20494 window,
20495 cx,
20496 );
20497 editor.expand_selected_diff_hunks(cx);
20498 });
20499 }
20500 }),
20501 )
20502 .child(
20503 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20504 .shape(IconButtonShape::Square)
20505 .icon_size(IconSize::Small)
20506 // .disabled(!has_multiple_hunks)
20507 .tooltip({
20508 let focus_handle = editor.focus_handle(cx);
20509 move |window, cx| {
20510 Tooltip::for_action_in(
20511 "Previous Hunk",
20512 &GoToPreviousHunk,
20513 &focus_handle,
20514 window,
20515 cx,
20516 )
20517 }
20518 })
20519 .on_click({
20520 let editor = editor.clone();
20521 move |_event, window, cx| {
20522 editor.update(cx, |editor, cx| {
20523 let snapshot = editor.snapshot(window, cx);
20524 let point =
20525 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20526 editor.go_to_hunk_before_or_after_position(
20527 &snapshot,
20528 point,
20529 Direction::Prev,
20530 window,
20531 cx,
20532 );
20533 editor.expand_selected_diff_hunks(cx);
20534 });
20535 }
20536 }),
20537 )
20538 },
20539 )
20540 .into_any_element()
20541}