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 this._subscriptions
1611 .push(cx.subscribe_self(|editor, e: &EditorEvent, cx| {
1612 if let EditorEvent::SelectionsChanged { local } = e {
1613 if *local {
1614 let new_anchor = editor.scroll_manager.anchor();
1615 editor.update_restoration_data(cx, move |data| {
1616 data.scroll_anchor = new_anchor;
1617 });
1618 }
1619 }
1620 }));
1621
1622 this.end_selection(window, cx);
1623 this.scroll_manager.show_scrollbars(window, cx);
1624 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1625
1626 if mode == EditorMode::Full {
1627 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1628 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1629
1630 if this.git_blame_inline_enabled {
1631 this.git_blame_inline_enabled = true;
1632 this.start_git_blame_inline(false, window, cx);
1633 }
1634
1635 this.go_to_active_debug_line(window, cx);
1636
1637 if let Some(buffer) = buffer.read(cx).as_singleton() {
1638 if let Some(project) = this.project.as_ref() {
1639 let handle = project.update(cx, |project, cx| {
1640 project.register_buffer_with_language_servers(&buffer, cx)
1641 });
1642 this.registered_buffers
1643 .insert(buffer.read(cx).remote_id(), handle);
1644 }
1645 }
1646 }
1647
1648 this.report_editor_event("Editor Opened", None, cx);
1649 this
1650 }
1651
1652 pub fn deploy_mouse_context_menu(
1653 &mut self,
1654 position: gpui::Point<Pixels>,
1655 context_menu: Entity<ContextMenu>,
1656 window: &mut Window,
1657 cx: &mut Context<Self>,
1658 ) {
1659 self.mouse_context_menu = Some(MouseContextMenu::new(
1660 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1661 context_menu,
1662 window,
1663 cx,
1664 ));
1665 }
1666
1667 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1668 self.mouse_context_menu
1669 .as_ref()
1670 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1671 }
1672
1673 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1674 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1675 }
1676
1677 fn key_context_internal(
1678 &self,
1679 has_active_edit_prediction: bool,
1680 window: &Window,
1681 cx: &App,
1682 ) -> KeyContext {
1683 let mut key_context = KeyContext::new_with_defaults();
1684 key_context.add("Editor");
1685 let mode = match self.mode {
1686 EditorMode::SingleLine { .. } => "single_line",
1687 EditorMode::AutoHeight { .. } => "auto_height",
1688 EditorMode::Full => "full",
1689 };
1690
1691 if EditorSettings::jupyter_enabled(cx) {
1692 key_context.add("jupyter");
1693 }
1694
1695 key_context.set("mode", mode);
1696 if self.pending_rename.is_some() {
1697 key_context.add("renaming");
1698 }
1699
1700 match self.context_menu.borrow().as_ref() {
1701 Some(CodeContextMenu::Completions(_)) => {
1702 key_context.add("menu");
1703 key_context.add("showing_completions");
1704 }
1705 Some(CodeContextMenu::CodeActions(_)) => {
1706 key_context.add("menu");
1707 key_context.add("showing_code_actions")
1708 }
1709 None => {}
1710 }
1711
1712 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1713 if !self.focus_handle(cx).contains_focused(window, cx)
1714 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1715 {
1716 for addon in self.addons.values() {
1717 addon.extend_key_context(&mut key_context, cx)
1718 }
1719 }
1720
1721 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1722 if let Some(extension) = singleton_buffer
1723 .read(cx)
1724 .file()
1725 .and_then(|file| file.path().extension()?.to_str())
1726 {
1727 key_context.set("extension", extension.to_string());
1728 }
1729 } else {
1730 key_context.add("multibuffer");
1731 }
1732
1733 if has_active_edit_prediction {
1734 if self.edit_prediction_in_conflict() {
1735 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1736 } else {
1737 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1738 key_context.add("copilot_suggestion");
1739 }
1740 }
1741
1742 if self.selection_mark_mode {
1743 key_context.add("selection_mode");
1744 }
1745
1746 key_context
1747 }
1748
1749 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1750 self.mouse_cursor_hidden = match origin {
1751 HideMouseCursorOrigin::TypingAction => {
1752 matches!(
1753 self.hide_mouse_mode,
1754 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1755 )
1756 }
1757 HideMouseCursorOrigin::MovementAction => {
1758 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1759 }
1760 };
1761 }
1762
1763 pub fn edit_prediction_in_conflict(&self) -> bool {
1764 if !self.show_edit_predictions_in_menu() {
1765 return false;
1766 }
1767
1768 let showing_completions = self
1769 .context_menu
1770 .borrow()
1771 .as_ref()
1772 .map_or(false, |context| {
1773 matches!(context, CodeContextMenu::Completions(_))
1774 });
1775
1776 showing_completions
1777 || self.edit_prediction_requires_modifier()
1778 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1779 // bindings to insert tab characters.
1780 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1781 }
1782
1783 pub fn accept_edit_prediction_keybind(
1784 &self,
1785 window: &Window,
1786 cx: &App,
1787 ) -> AcceptEditPredictionBinding {
1788 let key_context = self.key_context_internal(true, window, cx);
1789 let in_conflict = self.edit_prediction_in_conflict();
1790
1791 AcceptEditPredictionBinding(
1792 window
1793 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1794 .into_iter()
1795 .filter(|binding| {
1796 !in_conflict
1797 || binding
1798 .keystrokes()
1799 .first()
1800 .map_or(false, |keystroke| keystroke.modifiers.modified())
1801 })
1802 .rev()
1803 .min_by_key(|binding| {
1804 binding
1805 .keystrokes()
1806 .first()
1807 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1808 }),
1809 )
1810 }
1811
1812 pub fn new_file(
1813 workspace: &mut Workspace,
1814 _: &workspace::NewFile,
1815 window: &mut Window,
1816 cx: &mut Context<Workspace>,
1817 ) {
1818 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1819 "Failed to create buffer",
1820 window,
1821 cx,
1822 |e, _, _| match e.error_code() {
1823 ErrorCode::RemoteUpgradeRequired => Some(format!(
1824 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1825 e.error_tag("required").unwrap_or("the latest version")
1826 )),
1827 _ => None,
1828 },
1829 );
1830 }
1831
1832 pub fn new_in_workspace(
1833 workspace: &mut Workspace,
1834 window: &mut Window,
1835 cx: &mut Context<Workspace>,
1836 ) -> Task<Result<Entity<Editor>>> {
1837 let project = workspace.project().clone();
1838 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1839
1840 cx.spawn_in(window, async move |workspace, cx| {
1841 let buffer = create.await?;
1842 workspace.update_in(cx, |workspace, window, cx| {
1843 let editor =
1844 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1845 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1846 editor
1847 })
1848 })
1849 }
1850
1851 fn new_file_vertical(
1852 workspace: &mut Workspace,
1853 _: &workspace::NewFileSplitVertical,
1854 window: &mut Window,
1855 cx: &mut Context<Workspace>,
1856 ) {
1857 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1858 }
1859
1860 fn new_file_horizontal(
1861 workspace: &mut Workspace,
1862 _: &workspace::NewFileSplitHorizontal,
1863 window: &mut Window,
1864 cx: &mut Context<Workspace>,
1865 ) {
1866 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1867 }
1868
1869 fn new_file_in_direction(
1870 workspace: &mut Workspace,
1871 direction: SplitDirection,
1872 window: &mut Window,
1873 cx: &mut Context<Workspace>,
1874 ) {
1875 let project = workspace.project().clone();
1876 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1877
1878 cx.spawn_in(window, async move |workspace, cx| {
1879 let buffer = create.await?;
1880 workspace.update_in(cx, move |workspace, window, cx| {
1881 workspace.split_item(
1882 direction,
1883 Box::new(
1884 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1885 ),
1886 window,
1887 cx,
1888 )
1889 })?;
1890 anyhow::Ok(())
1891 })
1892 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1893 match e.error_code() {
1894 ErrorCode::RemoteUpgradeRequired => Some(format!(
1895 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1896 e.error_tag("required").unwrap_or("the latest version")
1897 )),
1898 _ => None,
1899 }
1900 });
1901 }
1902
1903 pub fn leader_peer_id(&self) -> Option<PeerId> {
1904 self.leader_peer_id
1905 }
1906
1907 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1908 &self.buffer
1909 }
1910
1911 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1912 self.workspace.as_ref()?.0.upgrade()
1913 }
1914
1915 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1916 self.buffer().read(cx).title(cx)
1917 }
1918
1919 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1920 let git_blame_gutter_max_author_length = self
1921 .render_git_blame_gutter(cx)
1922 .then(|| {
1923 if let Some(blame) = self.blame.as_ref() {
1924 let max_author_length =
1925 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1926 Some(max_author_length)
1927 } else {
1928 None
1929 }
1930 })
1931 .flatten();
1932
1933 EditorSnapshot {
1934 mode: self.mode,
1935 show_gutter: self.show_gutter,
1936 show_line_numbers: self.show_line_numbers,
1937 show_git_diff_gutter: self.show_git_diff_gutter,
1938 show_code_actions: self.show_code_actions,
1939 show_runnables: self.show_runnables,
1940 show_breakpoints: self.show_breakpoints,
1941 git_blame_gutter_max_author_length,
1942 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1943 scroll_anchor: self.scroll_manager.anchor(),
1944 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1945 placeholder_text: self.placeholder_text.clone(),
1946 is_focused: self.focus_handle.is_focused(window),
1947 current_line_highlight: self
1948 .current_line_highlight
1949 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1950 gutter_hovered: self.gutter_hovered,
1951 }
1952 }
1953
1954 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1955 self.buffer.read(cx).language_at(point, cx)
1956 }
1957
1958 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1959 self.buffer.read(cx).read(cx).file_at(point).cloned()
1960 }
1961
1962 pub fn active_excerpt(
1963 &self,
1964 cx: &App,
1965 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1966 self.buffer
1967 .read(cx)
1968 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1969 }
1970
1971 pub fn mode(&self) -> EditorMode {
1972 self.mode
1973 }
1974
1975 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1976 self.collaboration_hub.as_deref()
1977 }
1978
1979 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1980 self.collaboration_hub = Some(hub);
1981 }
1982
1983 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1984 self.in_project_search = in_project_search;
1985 }
1986
1987 pub fn set_custom_context_menu(
1988 &mut self,
1989 f: impl 'static
1990 + Fn(
1991 &mut Self,
1992 DisplayPoint,
1993 &mut Window,
1994 &mut Context<Self>,
1995 ) -> Option<Entity<ui::ContextMenu>>,
1996 ) {
1997 self.custom_context_menu = Some(Box::new(f))
1998 }
1999
2000 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2001 self.completion_provider = provider;
2002 }
2003
2004 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2005 self.semantics_provider.clone()
2006 }
2007
2008 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2009 self.semantics_provider = provider;
2010 }
2011
2012 pub fn set_edit_prediction_provider<T>(
2013 &mut self,
2014 provider: Option<Entity<T>>,
2015 window: &mut Window,
2016 cx: &mut Context<Self>,
2017 ) where
2018 T: EditPredictionProvider,
2019 {
2020 self.edit_prediction_provider =
2021 provider.map(|provider| RegisteredInlineCompletionProvider {
2022 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2023 if this.focus_handle.is_focused(window) {
2024 this.update_visible_inline_completion(window, cx);
2025 }
2026 }),
2027 provider: Arc::new(provider),
2028 });
2029 self.update_edit_prediction_settings(cx);
2030 self.refresh_inline_completion(false, false, window, cx);
2031 }
2032
2033 pub fn placeholder_text(&self) -> Option<&str> {
2034 self.placeholder_text.as_deref()
2035 }
2036
2037 pub fn set_placeholder_text(
2038 &mut self,
2039 placeholder_text: impl Into<Arc<str>>,
2040 cx: &mut Context<Self>,
2041 ) {
2042 let placeholder_text = Some(placeholder_text.into());
2043 if self.placeholder_text != placeholder_text {
2044 self.placeholder_text = placeholder_text;
2045 cx.notify();
2046 }
2047 }
2048
2049 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2050 self.cursor_shape = cursor_shape;
2051
2052 // Disrupt blink for immediate user feedback that the cursor shape has changed
2053 self.blink_manager.update(cx, BlinkManager::show_cursor);
2054
2055 cx.notify();
2056 }
2057
2058 pub fn set_current_line_highlight(
2059 &mut self,
2060 current_line_highlight: Option<CurrentLineHighlight>,
2061 ) {
2062 self.current_line_highlight = current_line_highlight;
2063 }
2064
2065 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2066 self.collapse_matches = collapse_matches;
2067 }
2068
2069 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2070 let buffers = self.buffer.read(cx).all_buffers();
2071 let Some(project) = self.project.as_ref() else {
2072 return;
2073 };
2074 project.update(cx, |project, cx| {
2075 for buffer in buffers {
2076 self.registered_buffers
2077 .entry(buffer.read(cx).remote_id())
2078 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2079 }
2080 })
2081 }
2082
2083 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2084 if self.collapse_matches {
2085 return range.start..range.start;
2086 }
2087 range.clone()
2088 }
2089
2090 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2091 if self.display_map.read(cx).clip_at_line_ends != clip {
2092 self.display_map
2093 .update(cx, |map, _| map.clip_at_line_ends = clip);
2094 }
2095 }
2096
2097 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2098 self.input_enabled = input_enabled;
2099 }
2100
2101 pub fn set_inline_completions_hidden_for_vim_mode(
2102 &mut self,
2103 hidden: bool,
2104 window: &mut Window,
2105 cx: &mut Context<Self>,
2106 ) {
2107 if hidden != self.inline_completions_hidden_for_vim_mode {
2108 self.inline_completions_hidden_for_vim_mode = hidden;
2109 if hidden {
2110 self.update_visible_inline_completion(window, cx);
2111 } else {
2112 self.refresh_inline_completion(true, false, window, cx);
2113 }
2114 }
2115 }
2116
2117 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2118 self.menu_inline_completions_policy = value;
2119 }
2120
2121 pub fn set_autoindent(&mut self, autoindent: bool) {
2122 if autoindent {
2123 self.autoindent_mode = Some(AutoindentMode::EachLine);
2124 } else {
2125 self.autoindent_mode = None;
2126 }
2127 }
2128
2129 pub fn read_only(&self, cx: &App) -> bool {
2130 self.read_only || self.buffer.read(cx).read_only()
2131 }
2132
2133 pub fn set_read_only(&mut self, read_only: bool) {
2134 self.read_only = read_only;
2135 }
2136
2137 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2138 self.use_autoclose = autoclose;
2139 }
2140
2141 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2142 self.use_auto_surround = auto_surround;
2143 }
2144
2145 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2146 self.auto_replace_emoji_shortcode = auto_replace;
2147 }
2148
2149 pub fn toggle_edit_predictions(
2150 &mut self,
2151 _: &ToggleEditPrediction,
2152 window: &mut Window,
2153 cx: &mut Context<Self>,
2154 ) {
2155 if self.show_inline_completions_override.is_some() {
2156 self.set_show_edit_predictions(None, window, cx);
2157 } else {
2158 let show_edit_predictions = !self.edit_predictions_enabled();
2159 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2160 }
2161 }
2162
2163 pub fn set_show_edit_predictions(
2164 &mut self,
2165 show_edit_predictions: Option<bool>,
2166 window: &mut Window,
2167 cx: &mut Context<Self>,
2168 ) {
2169 self.show_inline_completions_override = show_edit_predictions;
2170 self.update_edit_prediction_settings(cx);
2171
2172 if let Some(false) = show_edit_predictions {
2173 self.discard_inline_completion(false, cx);
2174 } else {
2175 self.refresh_inline_completion(false, true, window, cx);
2176 }
2177 }
2178
2179 fn inline_completions_disabled_in_scope(
2180 &self,
2181 buffer: &Entity<Buffer>,
2182 buffer_position: language::Anchor,
2183 cx: &App,
2184 ) -> bool {
2185 let snapshot = buffer.read(cx).snapshot();
2186 let settings = snapshot.settings_at(buffer_position, cx);
2187
2188 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2189 return false;
2190 };
2191
2192 scope.override_name().map_or(false, |scope_name| {
2193 settings
2194 .edit_predictions_disabled_in
2195 .iter()
2196 .any(|s| s == scope_name)
2197 })
2198 }
2199
2200 pub fn set_use_modal_editing(&mut self, to: bool) {
2201 self.use_modal_editing = to;
2202 }
2203
2204 pub fn use_modal_editing(&self) -> bool {
2205 self.use_modal_editing
2206 }
2207
2208 fn selections_did_change(
2209 &mut self,
2210 local: bool,
2211 old_cursor_position: &Anchor,
2212 show_completions: bool,
2213 window: &mut Window,
2214 cx: &mut Context<Self>,
2215 ) {
2216 window.invalidate_character_coordinates();
2217
2218 // Copy selections to primary selection buffer
2219 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2220 if local {
2221 let selections = self.selections.all::<usize>(cx);
2222 let buffer_handle = self.buffer.read(cx).read(cx);
2223
2224 let mut text = String::new();
2225 for (index, selection) in selections.iter().enumerate() {
2226 let text_for_selection = buffer_handle
2227 .text_for_range(selection.start..selection.end)
2228 .collect::<String>();
2229
2230 text.push_str(&text_for_selection);
2231 if index != selections.len() - 1 {
2232 text.push('\n');
2233 }
2234 }
2235
2236 if !text.is_empty() {
2237 cx.write_to_primary(ClipboardItem::new_string(text));
2238 }
2239 }
2240
2241 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2242 self.buffer.update(cx, |buffer, cx| {
2243 buffer.set_active_selections(
2244 &self.selections.disjoint_anchors(),
2245 self.selections.line_mode,
2246 self.cursor_shape,
2247 cx,
2248 )
2249 });
2250 }
2251 let display_map = self
2252 .display_map
2253 .update(cx, |display_map, cx| display_map.snapshot(cx));
2254 let buffer = &display_map.buffer_snapshot;
2255 self.add_selections_state = None;
2256 self.select_next_state = None;
2257 self.select_prev_state = None;
2258 self.select_syntax_node_history.try_clear();
2259 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2260 self.snippet_stack
2261 .invalidate(&self.selections.disjoint_anchors(), buffer);
2262 self.take_rename(false, window, cx);
2263
2264 let new_cursor_position = self.selections.newest_anchor().head();
2265
2266 self.push_to_nav_history(
2267 *old_cursor_position,
2268 Some(new_cursor_position.to_point(buffer)),
2269 false,
2270 cx,
2271 );
2272
2273 if local {
2274 let new_cursor_position = self.selections.newest_anchor().head();
2275 let mut context_menu = self.context_menu.borrow_mut();
2276 let completion_menu = match context_menu.as_ref() {
2277 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2278 _ => {
2279 *context_menu = None;
2280 None
2281 }
2282 };
2283 if let Some(buffer_id) = new_cursor_position.buffer_id {
2284 if !self.registered_buffers.contains_key(&buffer_id) {
2285 if let Some(project) = self.project.as_ref() {
2286 project.update(cx, |project, cx| {
2287 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2288 return;
2289 };
2290 self.registered_buffers.insert(
2291 buffer_id,
2292 project.register_buffer_with_language_servers(&buffer, cx),
2293 );
2294 })
2295 }
2296 }
2297 }
2298
2299 if let Some(completion_menu) = completion_menu {
2300 let cursor_position = new_cursor_position.to_offset(buffer);
2301 let (word_range, kind) =
2302 buffer.surrounding_word(completion_menu.initial_position, true);
2303 if kind == Some(CharKind::Word)
2304 && word_range.to_inclusive().contains(&cursor_position)
2305 {
2306 let mut completion_menu = completion_menu.clone();
2307 drop(context_menu);
2308
2309 let query = Self::completion_query(buffer, cursor_position);
2310 cx.spawn(async move |this, cx| {
2311 completion_menu
2312 .filter(query.as_deref(), cx.background_executor().clone())
2313 .await;
2314
2315 this.update(cx, |this, cx| {
2316 let mut context_menu = this.context_menu.borrow_mut();
2317 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2318 else {
2319 return;
2320 };
2321
2322 if menu.id > completion_menu.id {
2323 return;
2324 }
2325
2326 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2327 drop(context_menu);
2328 cx.notify();
2329 })
2330 })
2331 .detach();
2332
2333 if show_completions {
2334 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2335 }
2336 } else {
2337 drop(context_menu);
2338 self.hide_context_menu(window, cx);
2339 }
2340 } else {
2341 drop(context_menu);
2342 }
2343
2344 hide_hover(self, cx);
2345
2346 if old_cursor_position.to_display_point(&display_map).row()
2347 != new_cursor_position.to_display_point(&display_map).row()
2348 {
2349 self.available_code_actions.take();
2350 }
2351 self.refresh_code_actions(window, cx);
2352 self.refresh_document_highlights(cx);
2353 self.refresh_selected_text_highlights(window, cx);
2354 refresh_matching_bracket_highlights(self, window, cx);
2355 self.update_visible_inline_completion(window, cx);
2356 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2357 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2358 if self.git_blame_inline_enabled {
2359 self.start_inline_blame_timer(window, cx);
2360 }
2361 }
2362
2363 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2364 cx.emit(EditorEvent::SelectionsChanged { local });
2365
2366 let selections = &self.selections.disjoint;
2367 if selections.len() == 1 {
2368 cx.emit(SearchEvent::ActiveMatchChanged)
2369 }
2370 if local && self.is_singleton(cx) {
2371 let inmemory_selections = selections.iter().map(|s| s.range()).collect();
2372 self.update_restoration_data(cx, |data| {
2373 data.selections = inmemory_selections;
2374 });
2375
2376 if WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2377 {
2378 if let Some(workspace_id) =
2379 self.workspace.as_ref().and_then(|workspace| workspace.1)
2380 {
2381 let snapshot = self.buffer().read(cx).snapshot(cx);
2382 let selections = selections.clone();
2383 let background_executor = cx.background_executor().clone();
2384 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2385 self.serialize_selections = cx.background_spawn(async move {
2386 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2387 let db_selections = selections
2388 .iter()
2389 .map(|selection| {
2390 (
2391 selection.start.to_offset(&snapshot),
2392 selection.end.to_offset(&snapshot),
2393 )
2394 })
2395 .collect();
2396
2397 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2398 .await
2399 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2400 .log_err();
2401 });
2402 }
2403 }
2404 }
2405
2406 cx.notify();
2407 }
2408
2409 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2410 if !self.is_singleton(cx)
2411 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
2412 {
2413 return;
2414 }
2415
2416 let snapshot = self.buffer().read(cx).snapshot(cx);
2417 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2418 display_map
2419 .snapshot(cx)
2420 .folds_in_range(0..snapshot.len())
2421 .map(|fold| fold.range.deref().clone())
2422 .collect()
2423 });
2424 self.update_restoration_data(cx, |data| {
2425 data.folds = inmemory_folds;
2426 });
2427
2428 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2429 return;
2430 };
2431 let background_executor = cx.background_executor().clone();
2432 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2433 let db_folds = self.display_map.update(cx, |display_map, cx| {
2434 display_map
2435 .snapshot(cx)
2436 .folds_in_range(0..snapshot.len())
2437 .map(|fold| {
2438 (
2439 fold.range.start.to_offset(&snapshot),
2440 fold.range.end.to_offset(&snapshot),
2441 )
2442 })
2443 .collect()
2444 });
2445 self.serialize_folds = cx.background_spawn(async move {
2446 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2447 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2448 .await
2449 .with_context(|| {
2450 format!(
2451 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2452 )
2453 })
2454 .log_err();
2455 });
2456 }
2457
2458 pub fn sync_selections(
2459 &mut self,
2460 other: Entity<Editor>,
2461 cx: &mut Context<Self>,
2462 ) -> gpui::Subscription {
2463 let other_selections = other.read(cx).selections.disjoint.to_vec();
2464 self.selections.change_with(cx, |selections| {
2465 selections.select_anchors(other_selections);
2466 });
2467
2468 let other_subscription =
2469 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2470 EditorEvent::SelectionsChanged { local: true } => {
2471 let other_selections = other.read(cx).selections.disjoint.to_vec();
2472 if other_selections.is_empty() {
2473 return;
2474 }
2475 this.selections.change_with(cx, |selections| {
2476 selections.select_anchors(other_selections);
2477 });
2478 }
2479 _ => {}
2480 });
2481
2482 let this_subscription =
2483 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2484 EditorEvent::SelectionsChanged { local: true } => {
2485 let these_selections = this.selections.disjoint.to_vec();
2486 if these_selections.is_empty() {
2487 return;
2488 }
2489 other.update(cx, |other_editor, cx| {
2490 other_editor.selections.change_with(cx, |selections| {
2491 selections.select_anchors(these_selections);
2492 })
2493 });
2494 }
2495 _ => {}
2496 });
2497
2498 Subscription::join(other_subscription, this_subscription)
2499 }
2500
2501 pub fn change_selections<R>(
2502 &mut self,
2503 autoscroll: Option<Autoscroll>,
2504 window: &mut Window,
2505 cx: &mut Context<Self>,
2506 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2507 ) -> R {
2508 self.change_selections_inner(autoscroll, true, window, cx, change)
2509 }
2510
2511 fn change_selections_inner<R>(
2512 &mut self,
2513 autoscroll: Option<Autoscroll>,
2514 request_completions: bool,
2515 window: &mut Window,
2516 cx: &mut Context<Self>,
2517 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2518 ) -> R {
2519 let old_cursor_position = self.selections.newest_anchor().head();
2520 self.push_to_selection_history();
2521
2522 let (changed, result) = self.selections.change_with(cx, change);
2523
2524 if changed {
2525 if let Some(autoscroll) = autoscroll {
2526 self.request_autoscroll(autoscroll, cx);
2527 }
2528 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2529
2530 if self.should_open_signature_help_automatically(
2531 &old_cursor_position,
2532 self.signature_help_state.backspace_pressed(),
2533 cx,
2534 ) {
2535 self.show_signature_help(&ShowSignatureHelp, window, cx);
2536 }
2537 self.signature_help_state.set_backspace_pressed(false);
2538 }
2539
2540 result
2541 }
2542
2543 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2544 where
2545 I: IntoIterator<Item = (Range<S>, T)>,
2546 S: ToOffset,
2547 T: Into<Arc<str>>,
2548 {
2549 if self.read_only(cx) {
2550 return;
2551 }
2552
2553 self.buffer
2554 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2555 }
2556
2557 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2558 where
2559 I: IntoIterator<Item = (Range<S>, T)>,
2560 S: ToOffset,
2561 T: Into<Arc<str>>,
2562 {
2563 if self.read_only(cx) {
2564 return;
2565 }
2566
2567 self.buffer.update(cx, |buffer, cx| {
2568 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2569 });
2570 }
2571
2572 pub fn edit_with_block_indent<I, S, T>(
2573 &mut self,
2574 edits: I,
2575 original_indent_columns: Vec<Option<u32>>,
2576 cx: &mut Context<Self>,
2577 ) where
2578 I: IntoIterator<Item = (Range<S>, T)>,
2579 S: ToOffset,
2580 T: Into<Arc<str>>,
2581 {
2582 if self.read_only(cx) {
2583 return;
2584 }
2585
2586 self.buffer.update(cx, |buffer, cx| {
2587 buffer.edit(
2588 edits,
2589 Some(AutoindentMode::Block {
2590 original_indent_columns,
2591 }),
2592 cx,
2593 )
2594 });
2595 }
2596
2597 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2598 self.hide_context_menu(window, cx);
2599
2600 match phase {
2601 SelectPhase::Begin {
2602 position,
2603 add,
2604 click_count,
2605 } => self.begin_selection(position, add, click_count, window, cx),
2606 SelectPhase::BeginColumnar {
2607 position,
2608 goal_column,
2609 reset,
2610 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2611 SelectPhase::Extend {
2612 position,
2613 click_count,
2614 } => self.extend_selection(position, click_count, window, cx),
2615 SelectPhase::Update {
2616 position,
2617 goal_column,
2618 scroll_delta,
2619 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2620 SelectPhase::End => self.end_selection(window, cx),
2621 }
2622 }
2623
2624 fn extend_selection(
2625 &mut self,
2626 position: DisplayPoint,
2627 click_count: usize,
2628 window: &mut Window,
2629 cx: &mut Context<Self>,
2630 ) {
2631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2632 let tail = self.selections.newest::<usize>(cx).tail();
2633 self.begin_selection(position, false, click_count, window, cx);
2634
2635 let position = position.to_offset(&display_map, Bias::Left);
2636 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2637
2638 let mut pending_selection = self
2639 .selections
2640 .pending_anchor()
2641 .expect("extend_selection not called with pending selection");
2642 if position >= tail {
2643 pending_selection.start = tail_anchor;
2644 } else {
2645 pending_selection.end = tail_anchor;
2646 pending_selection.reversed = true;
2647 }
2648
2649 let mut pending_mode = self.selections.pending_mode().unwrap();
2650 match &mut pending_mode {
2651 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2652 _ => {}
2653 }
2654
2655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2656 s.set_pending(pending_selection, pending_mode)
2657 });
2658 }
2659
2660 fn begin_selection(
2661 &mut self,
2662 position: DisplayPoint,
2663 add: bool,
2664 click_count: usize,
2665 window: &mut Window,
2666 cx: &mut Context<Self>,
2667 ) {
2668 if !self.focus_handle.is_focused(window) {
2669 self.last_focused_descendant = None;
2670 window.focus(&self.focus_handle);
2671 }
2672
2673 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2674 let buffer = &display_map.buffer_snapshot;
2675 let newest_selection = self.selections.newest_anchor().clone();
2676 let position = display_map.clip_point(position, Bias::Left);
2677
2678 let start;
2679 let end;
2680 let mode;
2681 let mut auto_scroll;
2682 match click_count {
2683 1 => {
2684 start = buffer.anchor_before(position.to_point(&display_map));
2685 end = start;
2686 mode = SelectMode::Character;
2687 auto_scroll = true;
2688 }
2689 2 => {
2690 let range = movement::surrounding_word(&display_map, position);
2691 start = buffer.anchor_before(range.start.to_point(&display_map));
2692 end = buffer.anchor_before(range.end.to_point(&display_map));
2693 mode = SelectMode::Word(start..end);
2694 auto_scroll = true;
2695 }
2696 3 => {
2697 let position = display_map
2698 .clip_point(position, Bias::Left)
2699 .to_point(&display_map);
2700 let line_start = display_map.prev_line_boundary(position).0;
2701 let next_line_start = buffer.clip_point(
2702 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2703 Bias::Left,
2704 );
2705 start = buffer.anchor_before(line_start);
2706 end = buffer.anchor_before(next_line_start);
2707 mode = SelectMode::Line(start..end);
2708 auto_scroll = true;
2709 }
2710 _ => {
2711 start = buffer.anchor_before(0);
2712 end = buffer.anchor_before(buffer.len());
2713 mode = SelectMode::All;
2714 auto_scroll = false;
2715 }
2716 }
2717 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2718
2719 let point_to_delete: Option<usize> = {
2720 let selected_points: Vec<Selection<Point>> =
2721 self.selections.disjoint_in_range(start..end, cx);
2722
2723 if !add || click_count > 1 {
2724 None
2725 } else if !selected_points.is_empty() {
2726 Some(selected_points[0].id)
2727 } else {
2728 let clicked_point_already_selected =
2729 self.selections.disjoint.iter().find(|selection| {
2730 selection.start.to_point(buffer) == start.to_point(buffer)
2731 || selection.end.to_point(buffer) == end.to_point(buffer)
2732 });
2733
2734 clicked_point_already_selected.map(|selection| selection.id)
2735 }
2736 };
2737
2738 let selections_count = self.selections.count();
2739
2740 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2741 if let Some(point_to_delete) = point_to_delete {
2742 s.delete(point_to_delete);
2743
2744 if selections_count == 1 {
2745 s.set_pending_anchor_range(start..end, mode);
2746 }
2747 } else {
2748 if !add {
2749 s.clear_disjoint();
2750 } else if click_count > 1 {
2751 s.delete(newest_selection.id)
2752 }
2753
2754 s.set_pending_anchor_range(start..end, mode);
2755 }
2756 });
2757 }
2758
2759 fn begin_columnar_selection(
2760 &mut self,
2761 position: DisplayPoint,
2762 goal_column: u32,
2763 reset: bool,
2764 window: &mut Window,
2765 cx: &mut Context<Self>,
2766 ) {
2767 if !self.focus_handle.is_focused(window) {
2768 self.last_focused_descendant = None;
2769 window.focus(&self.focus_handle);
2770 }
2771
2772 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2773
2774 if reset {
2775 let pointer_position = display_map
2776 .buffer_snapshot
2777 .anchor_before(position.to_point(&display_map));
2778
2779 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2780 s.clear_disjoint();
2781 s.set_pending_anchor_range(
2782 pointer_position..pointer_position,
2783 SelectMode::Character,
2784 );
2785 });
2786 }
2787
2788 let tail = self.selections.newest::<Point>(cx).tail();
2789 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2790
2791 if !reset {
2792 self.select_columns(
2793 tail.to_display_point(&display_map),
2794 position,
2795 goal_column,
2796 &display_map,
2797 window,
2798 cx,
2799 );
2800 }
2801 }
2802
2803 fn update_selection(
2804 &mut self,
2805 position: DisplayPoint,
2806 goal_column: u32,
2807 scroll_delta: gpui::Point<f32>,
2808 window: &mut Window,
2809 cx: &mut Context<Self>,
2810 ) {
2811 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2812
2813 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2814 let tail = tail.to_display_point(&display_map);
2815 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2816 } else if let Some(mut pending) = self.selections.pending_anchor() {
2817 let buffer = self.buffer.read(cx).snapshot(cx);
2818 let head;
2819 let tail;
2820 let mode = self.selections.pending_mode().unwrap();
2821 match &mode {
2822 SelectMode::Character => {
2823 head = position.to_point(&display_map);
2824 tail = pending.tail().to_point(&buffer);
2825 }
2826 SelectMode::Word(original_range) => {
2827 let original_display_range = original_range.start.to_display_point(&display_map)
2828 ..original_range.end.to_display_point(&display_map);
2829 let original_buffer_range = original_display_range.start.to_point(&display_map)
2830 ..original_display_range.end.to_point(&display_map);
2831 if movement::is_inside_word(&display_map, position)
2832 || original_display_range.contains(&position)
2833 {
2834 let word_range = movement::surrounding_word(&display_map, position);
2835 if word_range.start < original_display_range.start {
2836 head = word_range.start.to_point(&display_map);
2837 } else {
2838 head = word_range.end.to_point(&display_map);
2839 }
2840 } else {
2841 head = position.to_point(&display_map);
2842 }
2843
2844 if head <= original_buffer_range.start {
2845 tail = original_buffer_range.end;
2846 } else {
2847 tail = original_buffer_range.start;
2848 }
2849 }
2850 SelectMode::Line(original_range) => {
2851 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2852
2853 let position = display_map
2854 .clip_point(position, Bias::Left)
2855 .to_point(&display_map);
2856 let line_start = display_map.prev_line_boundary(position).0;
2857 let next_line_start = buffer.clip_point(
2858 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2859 Bias::Left,
2860 );
2861
2862 if line_start < original_range.start {
2863 head = line_start
2864 } else {
2865 head = next_line_start
2866 }
2867
2868 if head <= original_range.start {
2869 tail = original_range.end;
2870 } else {
2871 tail = original_range.start;
2872 }
2873 }
2874 SelectMode::All => {
2875 return;
2876 }
2877 };
2878
2879 if head < tail {
2880 pending.start = buffer.anchor_before(head);
2881 pending.end = buffer.anchor_before(tail);
2882 pending.reversed = true;
2883 } else {
2884 pending.start = buffer.anchor_before(tail);
2885 pending.end = buffer.anchor_before(head);
2886 pending.reversed = false;
2887 }
2888
2889 self.change_selections(None, window, cx, |s| {
2890 s.set_pending(pending, mode);
2891 });
2892 } else {
2893 log::error!("update_selection dispatched with no pending selection");
2894 return;
2895 }
2896
2897 self.apply_scroll_delta(scroll_delta, window, cx);
2898 cx.notify();
2899 }
2900
2901 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2902 self.columnar_selection_tail.take();
2903 if self.selections.pending_anchor().is_some() {
2904 let selections = self.selections.all::<usize>(cx);
2905 self.change_selections(None, window, cx, |s| {
2906 s.select(selections);
2907 s.clear_pending();
2908 });
2909 }
2910 }
2911
2912 fn select_columns(
2913 &mut self,
2914 tail: DisplayPoint,
2915 head: DisplayPoint,
2916 goal_column: u32,
2917 display_map: &DisplaySnapshot,
2918 window: &mut Window,
2919 cx: &mut Context<Self>,
2920 ) {
2921 let start_row = cmp::min(tail.row(), head.row());
2922 let end_row = cmp::max(tail.row(), head.row());
2923 let start_column = cmp::min(tail.column(), goal_column);
2924 let end_column = cmp::max(tail.column(), goal_column);
2925 let reversed = start_column < tail.column();
2926
2927 let selection_ranges = (start_row.0..=end_row.0)
2928 .map(DisplayRow)
2929 .filter_map(|row| {
2930 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2931 let start = display_map
2932 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2933 .to_point(display_map);
2934 let end = display_map
2935 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2936 .to_point(display_map);
2937 if reversed {
2938 Some(end..start)
2939 } else {
2940 Some(start..end)
2941 }
2942 } else {
2943 None
2944 }
2945 })
2946 .collect::<Vec<_>>();
2947
2948 self.change_selections(None, window, cx, |s| {
2949 s.select_ranges(selection_ranges);
2950 });
2951 cx.notify();
2952 }
2953
2954 pub fn has_pending_nonempty_selection(&self) -> bool {
2955 let pending_nonempty_selection = match self.selections.pending_anchor() {
2956 Some(Selection { start, end, .. }) => start != end,
2957 None => false,
2958 };
2959
2960 pending_nonempty_selection
2961 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2962 }
2963
2964 pub fn has_pending_selection(&self) -> bool {
2965 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2966 }
2967
2968 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2969 self.selection_mark_mode = false;
2970
2971 if self.clear_expanded_diff_hunks(cx) {
2972 cx.notify();
2973 return;
2974 }
2975 if self.dismiss_menus_and_popups(true, window, cx) {
2976 return;
2977 }
2978
2979 if self.mode == EditorMode::Full
2980 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2981 {
2982 return;
2983 }
2984
2985 cx.propagate();
2986 }
2987
2988 pub fn dismiss_menus_and_popups(
2989 &mut self,
2990 is_user_requested: bool,
2991 window: &mut Window,
2992 cx: &mut Context<Self>,
2993 ) -> bool {
2994 if self.take_rename(false, window, cx).is_some() {
2995 return true;
2996 }
2997
2998 if hide_hover(self, cx) {
2999 return true;
3000 }
3001
3002 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3003 return true;
3004 }
3005
3006 if self.hide_context_menu(window, cx).is_some() {
3007 return true;
3008 }
3009
3010 if self.mouse_context_menu.take().is_some() {
3011 return true;
3012 }
3013
3014 if is_user_requested && self.discard_inline_completion(true, cx) {
3015 return true;
3016 }
3017
3018 if self.snippet_stack.pop().is_some() {
3019 return true;
3020 }
3021
3022 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3023 self.dismiss_diagnostics(cx);
3024 return true;
3025 }
3026
3027 false
3028 }
3029
3030 fn linked_editing_ranges_for(
3031 &self,
3032 selection: Range<text::Anchor>,
3033 cx: &App,
3034 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3035 if self.linked_edit_ranges.is_empty() {
3036 return None;
3037 }
3038 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3039 selection.end.buffer_id.and_then(|end_buffer_id| {
3040 if selection.start.buffer_id != Some(end_buffer_id) {
3041 return None;
3042 }
3043 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3044 let snapshot = buffer.read(cx).snapshot();
3045 self.linked_edit_ranges
3046 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3047 .map(|ranges| (ranges, snapshot, buffer))
3048 })?;
3049 use text::ToOffset as TO;
3050 // find offset from the start of current range to current cursor position
3051 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3052
3053 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3054 let start_difference = start_offset - start_byte_offset;
3055 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3056 let end_difference = end_offset - start_byte_offset;
3057 // Current range has associated linked ranges.
3058 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3059 for range in linked_ranges.iter() {
3060 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3061 let end_offset = start_offset + end_difference;
3062 let start_offset = start_offset + start_difference;
3063 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3064 continue;
3065 }
3066 if self.selections.disjoint_anchor_ranges().any(|s| {
3067 if s.start.buffer_id != selection.start.buffer_id
3068 || s.end.buffer_id != selection.end.buffer_id
3069 {
3070 return false;
3071 }
3072 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3073 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3074 }) {
3075 continue;
3076 }
3077 let start = buffer_snapshot.anchor_after(start_offset);
3078 let end = buffer_snapshot.anchor_after(end_offset);
3079 linked_edits
3080 .entry(buffer.clone())
3081 .or_default()
3082 .push(start..end);
3083 }
3084 Some(linked_edits)
3085 }
3086
3087 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3088 let text: Arc<str> = text.into();
3089
3090 if self.read_only(cx) {
3091 return;
3092 }
3093
3094 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3095
3096 let selections = self.selections.all_adjusted(cx);
3097 let mut bracket_inserted = false;
3098 let mut edits = Vec::new();
3099 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3100 let mut new_selections = Vec::with_capacity(selections.len());
3101 let mut new_autoclose_regions = Vec::new();
3102 let snapshot = self.buffer.read(cx).read(cx);
3103
3104 for (selection, autoclose_region) in
3105 self.selections_with_autoclose_regions(selections, &snapshot)
3106 {
3107 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3108 // Determine if the inserted text matches the opening or closing
3109 // bracket of any of this language's bracket pairs.
3110 let mut bracket_pair = None;
3111 let mut is_bracket_pair_start = false;
3112 let mut is_bracket_pair_end = false;
3113 if !text.is_empty() {
3114 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3115 // and they are removing the character that triggered IME popup.
3116 for (pair, enabled) in scope.brackets() {
3117 if !pair.close && !pair.surround {
3118 continue;
3119 }
3120
3121 if enabled && pair.start.ends_with(text.as_ref()) {
3122 let prefix_len = pair.start.len() - text.len();
3123 let preceding_text_matches_prefix = prefix_len == 0
3124 || (selection.start.column >= (prefix_len as u32)
3125 && snapshot.contains_str_at(
3126 Point::new(
3127 selection.start.row,
3128 selection.start.column - (prefix_len as u32),
3129 ),
3130 &pair.start[..prefix_len],
3131 ));
3132 if preceding_text_matches_prefix {
3133 bracket_pair = Some(pair.clone());
3134 is_bracket_pair_start = true;
3135 break;
3136 }
3137 }
3138 if pair.end.as_str() == text.as_ref() {
3139 bracket_pair = Some(pair.clone());
3140 is_bracket_pair_end = true;
3141 break;
3142 }
3143 }
3144 }
3145
3146 if let Some(bracket_pair) = bracket_pair {
3147 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3148 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3149 let auto_surround =
3150 self.use_auto_surround && snapshot_settings.use_auto_surround;
3151 if selection.is_empty() {
3152 if is_bracket_pair_start {
3153 // If the inserted text is a suffix of an opening bracket and the
3154 // selection is preceded by the rest of the opening bracket, then
3155 // insert the closing bracket.
3156 let following_text_allows_autoclose = snapshot
3157 .chars_at(selection.start)
3158 .next()
3159 .map_or(true, |c| scope.should_autoclose_before(c));
3160
3161 let preceding_text_allows_autoclose = selection.start.column == 0
3162 || snapshot.reversed_chars_at(selection.start).next().map_or(
3163 true,
3164 |c| {
3165 bracket_pair.start != bracket_pair.end
3166 || !snapshot
3167 .char_classifier_at(selection.start)
3168 .is_word(c)
3169 },
3170 );
3171
3172 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3173 && bracket_pair.start.len() == 1
3174 {
3175 let target = bracket_pair.start.chars().next().unwrap();
3176 let current_line_count = snapshot
3177 .reversed_chars_at(selection.start)
3178 .take_while(|&c| c != '\n')
3179 .filter(|&c| c == target)
3180 .count();
3181 current_line_count % 2 == 1
3182 } else {
3183 false
3184 };
3185
3186 if autoclose
3187 && bracket_pair.close
3188 && following_text_allows_autoclose
3189 && preceding_text_allows_autoclose
3190 && !is_closing_quote
3191 {
3192 let anchor = snapshot.anchor_before(selection.end);
3193 new_selections.push((selection.map(|_| anchor), text.len()));
3194 new_autoclose_regions.push((
3195 anchor,
3196 text.len(),
3197 selection.id,
3198 bracket_pair.clone(),
3199 ));
3200 edits.push((
3201 selection.range(),
3202 format!("{}{}", text, bracket_pair.end).into(),
3203 ));
3204 bracket_inserted = true;
3205 continue;
3206 }
3207 }
3208
3209 if let Some(region) = autoclose_region {
3210 // If the selection is followed by an auto-inserted closing bracket,
3211 // then don't insert that closing bracket again; just move the selection
3212 // past the closing bracket.
3213 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3214 && text.as_ref() == region.pair.end.as_str();
3215 if should_skip {
3216 let anchor = snapshot.anchor_after(selection.end);
3217 new_selections
3218 .push((selection.map(|_| anchor), region.pair.end.len()));
3219 continue;
3220 }
3221 }
3222
3223 let always_treat_brackets_as_autoclosed = snapshot
3224 .language_settings_at(selection.start, cx)
3225 .always_treat_brackets_as_autoclosed;
3226 if always_treat_brackets_as_autoclosed
3227 && is_bracket_pair_end
3228 && snapshot.contains_str_at(selection.end, text.as_ref())
3229 {
3230 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3231 // and the inserted text is a closing bracket and the selection is followed
3232 // by the closing bracket then move the selection past the closing bracket.
3233 let anchor = snapshot.anchor_after(selection.end);
3234 new_selections.push((selection.map(|_| anchor), text.len()));
3235 continue;
3236 }
3237 }
3238 // If an opening bracket is 1 character long and is typed while
3239 // text is selected, then surround that text with the bracket pair.
3240 else if auto_surround
3241 && bracket_pair.surround
3242 && is_bracket_pair_start
3243 && bracket_pair.start.chars().count() == 1
3244 {
3245 edits.push((selection.start..selection.start, text.clone()));
3246 edits.push((
3247 selection.end..selection.end,
3248 bracket_pair.end.as_str().into(),
3249 ));
3250 bracket_inserted = true;
3251 new_selections.push((
3252 Selection {
3253 id: selection.id,
3254 start: snapshot.anchor_after(selection.start),
3255 end: snapshot.anchor_before(selection.end),
3256 reversed: selection.reversed,
3257 goal: selection.goal,
3258 },
3259 0,
3260 ));
3261 continue;
3262 }
3263 }
3264 }
3265
3266 if self.auto_replace_emoji_shortcode
3267 && selection.is_empty()
3268 && text.as_ref().ends_with(':')
3269 {
3270 if let Some(possible_emoji_short_code) =
3271 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3272 {
3273 if !possible_emoji_short_code.is_empty() {
3274 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3275 let emoji_shortcode_start = Point::new(
3276 selection.start.row,
3277 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3278 );
3279
3280 // Remove shortcode from buffer
3281 edits.push((
3282 emoji_shortcode_start..selection.start,
3283 "".to_string().into(),
3284 ));
3285 new_selections.push((
3286 Selection {
3287 id: selection.id,
3288 start: snapshot.anchor_after(emoji_shortcode_start),
3289 end: snapshot.anchor_before(selection.start),
3290 reversed: selection.reversed,
3291 goal: selection.goal,
3292 },
3293 0,
3294 ));
3295
3296 // Insert emoji
3297 let selection_start_anchor = snapshot.anchor_after(selection.start);
3298 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3299 edits.push((selection.start..selection.end, emoji.to_string().into()));
3300
3301 continue;
3302 }
3303 }
3304 }
3305 }
3306
3307 // If not handling any auto-close operation, then just replace the selected
3308 // text with the given input and move the selection to the end of the
3309 // newly inserted text.
3310 let anchor = snapshot.anchor_after(selection.end);
3311 if !self.linked_edit_ranges.is_empty() {
3312 let start_anchor = snapshot.anchor_before(selection.start);
3313
3314 let is_word_char = text.chars().next().map_or(true, |char| {
3315 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3316 classifier.is_word(char)
3317 });
3318
3319 if is_word_char {
3320 if let Some(ranges) = self
3321 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3322 {
3323 for (buffer, edits) in ranges {
3324 linked_edits
3325 .entry(buffer.clone())
3326 .or_default()
3327 .extend(edits.into_iter().map(|range| (range, text.clone())));
3328 }
3329 }
3330 }
3331 }
3332
3333 new_selections.push((selection.map(|_| anchor), 0));
3334 edits.push((selection.start..selection.end, text.clone()));
3335 }
3336
3337 drop(snapshot);
3338
3339 self.transact(window, cx, |this, window, cx| {
3340 let initial_buffer_versions =
3341 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3342
3343 this.buffer.update(cx, |buffer, cx| {
3344 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3345 });
3346 for (buffer, edits) in linked_edits {
3347 buffer.update(cx, |buffer, cx| {
3348 let snapshot = buffer.snapshot();
3349 let edits = edits
3350 .into_iter()
3351 .map(|(range, text)| {
3352 use text::ToPoint as TP;
3353 let end_point = TP::to_point(&range.end, &snapshot);
3354 let start_point = TP::to_point(&range.start, &snapshot);
3355 (start_point..end_point, text)
3356 })
3357 .sorted_by_key(|(range, _)| range.start);
3358 buffer.edit(edits, None, cx);
3359 })
3360 }
3361 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3362 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3363 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3364 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3365 .zip(new_selection_deltas)
3366 .map(|(selection, delta)| Selection {
3367 id: selection.id,
3368 start: selection.start + delta,
3369 end: selection.end + delta,
3370 reversed: selection.reversed,
3371 goal: SelectionGoal::None,
3372 })
3373 .collect::<Vec<_>>();
3374
3375 let mut i = 0;
3376 for (position, delta, selection_id, pair) in new_autoclose_regions {
3377 let position = position.to_offset(&map.buffer_snapshot) + delta;
3378 let start = map.buffer_snapshot.anchor_before(position);
3379 let end = map.buffer_snapshot.anchor_after(position);
3380 while let Some(existing_state) = this.autoclose_regions.get(i) {
3381 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3382 Ordering::Less => i += 1,
3383 Ordering::Greater => break,
3384 Ordering::Equal => {
3385 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3386 Ordering::Less => i += 1,
3387 Ordering::Equal => break,
3388 Ordering::Greater => break,
3389 }
3390 }
3391 }
3392 }
3393 this.autoclose_regions.insert(
3394 i,
3395 AutocloseRegion {
3396 selection_id,
3397 range: start..end,
3398 pair,
3399 },
3400 );
3401 }
3402
3403 let had_active_inline_completion = this.has_active_inline_completion();
3404 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3405 s.select(new_selections)
3406 });
3407
3408 if !bracket_inserted {
3409 if let Some(on_type_format_task) =
3410 this.trigger_on_type_formatting(text.to_string(), window, cx)
3411 {
3412 on_type_format_task.detach_and_log_err(cx);
3413 }
3414 }
3415
3416 let editor_settings = EditorSettings::get_global(cx);
3417 if bracket_inserted
3418 && (editor_settings.auto_signature_help
3419 || editor_settings.show_signature_help_after_edits)
3420 {
3421 this.show_signature_help(&ShowSignatureHelp, window, cx);
3422 }
3423
3424 let trigger_in_words =
3425 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3426 if this.hard_wrap.is_some() {
3427 let latest: Range<Point> = this.selections.newest(cx).range();
3428 if latest.is_empty()
3429 && this
3430 .buffer()
3431 .read(cx)
3432 .snapshot(cx)
3433 .line_len(MultiBufferRow(latest.start.row))
3434 == latest.start.column
3435 {
3436 this.rewrap_impl(
3437 RewrapOptions {
3438 override_language_settings: true,
3439 preserve_existing_whitespace: true,
3440 },
3441 cx,
3442 )
3443 }
3444 }
3445 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3446 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3447 this.refresh_inline_completion(true, false, window, cx);
3448 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3449 });
3450 }
3451
3452 fn find_possible_emoji_shortcode_at_position(
3453 snapshot: &MultiBufferSnapshot,
3454 position: Point,
3455 ) -> Option<String> {
3456 let mut chars = Vec::new();
3457 let mut found_colon = false;
3458 for char in snapshot.reversed_chars_at(position).take(100) {
3459 // Found a possible emoji shortcode in the middle of the buffer
3460 if found_colon {
3461 if char.is_whitespace() {
3462 chars.reverse();
3463 return Some(chars.iter().collect());
3464 }
3465 // If the previous character is not a whitespace, we are in the middle of a word
3466 // and we only want to complete the shortcode if the word is made up of other emojis
3467 let mut containing_word = String::new();
3468 for ch in snapshot
3469 .reversed_chars_at(position)
3470 .skip(chars.len() + 1)
3471 .take(100)
3472 {
3473 if ch.is_whitespace() {
3474 break;
3475 }
3476 containing_word.push(ch);
3477 }
3478 let containing_word = containing_word.chars().rev().collect::<String>();
3479 if util::word_consists_of_emojis(containing_word.as_str()) {
3480 chars.reverse();
3481 return Some(chars.iter().collect());
3482 }
3483 }
3484
3485 if char.is_whitespace() || !char.is_ascii() {
3486 return None;
3487 }
3488 if char == ':' {
3489 found_colon = true;
3490 } else {
3491 chars.push(char);
3492 }
3493 }
3494 // Found a possible emoji shortcode at the beginning of the buffer
3495 chars.reverse();
3496 Some(chars.iter().collect())
3497 }
3498
3499 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3500 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3501 self.transact(window, cx, |this, window, cx| {
3502 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3503 let selections = this.selections.all::<usize>(cx);
3504 let multi_buffer = this.buffer.read(cx);
3505 let buffer = multi_buffer.snapshot(cx);
3506 selections
3507 .iter()
3508 .map(|selection| {
3509 let start_point = selection.start.to_point(&buffer);
3510 let mut indent =
3511 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3512 indent.len = cmp::min(indent.len, start_point.column);
3513 let start = selection.start;
3514 let end = selection.end;
3515 let selection_is_empty = start == end;
3516 let language_scope = buffer.language_scope_at(start);
3517 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3518 &language_scope
3519 {
3520 let insert_extra_newline =
3521 insert_extra_newline_brackets(&buffer, start..end, language)
3522 || insert_extra_newline_tree_sitter(&buffer, start..end);
3523
3524 // Comment extension on newline is allowed only for cursor selections
3525 let comment_delimiter = maybe!({
3526 if !selection_is_empty {
3527 return None;
3528 }
3529
3530 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3531 return None;
3532 }
3533
3534 let delimiters = language.line_comment_prefixes();
3535 let max_len_of_delimiter =
3536 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3537 let (snapshot, range) =
3538 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3539
3540 let mut index_of_first_non_whitespace = 0;
3541 let comment_candidate = snapshot
3542 .chars_for_range(range)
3543 .skip_while(|c| {
3544 let should_skip = c.is_whitespace();
3545 if should_skip {
3546 index_of_first_non_whitespace += 1;
3547 }
3548 should_skip
3549 })
3550 .take(max_len_of_delimiter)
3551 .collect::<String>();
3552 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3553 comment_candidate.starts_with(comment_prefix.as_ref())
3554 })?;
3555 let cursor_is_placed_after_comment_marker =
3556 index_of_first_non_whitespace + comment_prefix.len()
3557 <= start_point.column as usize;
3558 if cursor_is_placed_after_comment_marker {
3559 Some(comment_prefix.clone())
3560 } else {
3561 None
3562 }
3563 });
3564 (comment_delimiter, insert_extra_newline)
3565 } else {
3566 (None, false)
3567 };
3568
3569 let capacity_for_delimiter = comment_delimiter
3570 .as_deref()
3571 .map(str::len)
3572 .unwrap_or_default();
3573 let mut new_text =
3574 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3575 new_text.push('\n');
3576 new_text.extend(indent.chars());
3577 if let Some(delimiter) = &comment_delimiter {
3578 new_text.push_str(delimiter);
3579 }
3580 if insert_extra_newline {
3581 new_text = new_text.repeat(2);
3582 }
3583
3584 let anchor = buffer.anchor_after(end);
3585 let new_selection = selection.map(|_| anchor);
3586 (
3587 (start..end, new_text),
3588 (insert_extra_newline, new_selection),
3589 )
3590 })
3591 .unzip()
3592 };
3593
3594 this.edit_with_autoindent(edits, cx);
3595 let buffer = this.buffer.read(cx).snapshot(cx);
3596 let new_selections = selection_fixup_info
3597 .into_iter()
3598 .map(|(extra_newline_inserted, new_selection)| {
3599 let mut cursor = new_selection.end.to_point(&buffer);
3600 if extra_newline_inserted {
3601 cursor.row -= 1;
3602 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3603 }
3604 new_selection.map(|_| cursor)
3605 })
3606 .collect();
3607
3608 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3609 s.select(new_selections)
3610 });
3611 this.refresh_inline_completion(true, false, window, cx);
3612 });
3613 }
3614
3615 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3616 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3617
3618 let buffer = self.buffer.read(cx);
3619 let snapshot = buffer.snapshot(cx);
3620
3621 let mut edits = Vec::new();
3622 let mut rows = Vec::new();
3623
3624 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3625 let cursor = selection.head();
3626 let row = cursor.row;
3627
3628 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3629
3630 let newline = "\n".to_string();
3631 edits.push((start_of_line..start_of_line, newline));
3632
3633 rows.push(row + rows_inserted as u32);
3634 }
3635
3636 self.transact(window, cx, |editor, window, cx| {
3637 editor.edit(edits, cx);
3638
3639 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3640 let mut index = 0;
3641 s.move_cursors_with(|map, _, _| {
3642 let row = rows[index];
3643 index += 1;
3644
3645 let point = Point::new(row, 0);
3646 let boundary = map.next_line_boundary(point).1;
3647 let clipped = map.clip_point(boundary, Bias::Left);
3648
3649 (clipped, SelectionGoal::None)
3650 });
3651 });
3652
3653 let mut indent_edits = Vec::new();
3654 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3655 for row in rows {
3656 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3657 for (row, indent) in indents {
3658 if indent.len == 0 {
3659 continue;
3660 }
3661
3662 let text = match indent.kind {
3663 IndentKind::Space => " ".repeat(indent.len as usize),
3664 IndentKind::Tab => "\t".repeat(indent.len as usize),
3665 };
3666 let point = Point::new(row.0, 0);
3667 indent_edits.push((point..point, text));
3668 }
3669 }
3670 editor.edit(indent_edits, cx);
3671 });
3672 }
3673
3674 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3675 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3676
3677 let buffer = self.buffer.read(cx);
3678 let snapshot = buffer.snapshot(cx);
3679
3680 let mut edits = Vec::new();
3681 let mut rows = Vec::new();
3682 let mut rows_inserted = 0;
3683
3684 for selection in self.selections.all_adjusted(cx) {
3685 let cursor = selection.head();
3686 let row = cursor.row;
3687
3688 let point = Point::new(row + 1, 0);
3689 let start_of_line = snapshot.clip_point(point, Bias::Left);
3690
3691 let newline = "\n".to_string();
3692 edits.push((start_of_line..start_of_line, newline));
3693
3694 rows_inserted += 1;
3695 rows.push(row + rows_inserted);
3696 }
3697
3698 self.transact(window, cx, |editor, window, cx| {
3699 editor.edit(edits, cx);
3700
3701 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3702 let mut index = 0;
3703 s.move_cursors_with(|map, _, _| {
3704 let row = rows[index];
3705 index += 1;
3706
3707 let point = Point::new(row, 0);
3708 let boundary = map.next_line_boundary(point).1;
3709 let clipped = map.clip_point(boundary, Bias::Left);
3710
3711 (clipped, SelectionGoal::None)
3712 });
3713 });
3714
3715 let mut indent_edits = Vec::new();
3716 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3717 for row in rows {
3718 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3719 for (row, indent) in indents {
3720 if indent.len == 0 {
3721 continue;
3722 }
3723
3724 let text = match indent.kind {
3725 IndentKind::Space => " ".repeat(indent.len as usize),
3726 IndentKind::Tab => "\t".repeat(indent.len as usize),
3727 };
3728 let point = Point::new(row.0, 0);
3729 indent_edits.push((point..point, text));
3730 }
3731 }
3732 editor.edit(indent_edits, cx);
3733 });
3734 }
3735
3736 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3737 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3738 original_indent_columns: Vec::new(),
3739 });
3740 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3741 }
3742
3743 fn insert_with_autoindent_mode(
3744 &mut self,
3745 text: &str,
3746 autoindent_mode: Option<AutoindentMode>,
3747 window: &mut Window,
3748 cx: &mut Context<Self>,
3749 ) {
3750 if self.read_only(cx) {
3751 return;
3752 }
3753
3754 let text: Arc<str> = text.into();
3755 self.transact(window, cx, |this, window, cx| {
3756 let old_selections = this.selections.all_adjusted(cx);
3757 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3758 let anchors = {
3759 let snapshot = buffer.read(cx);
3760 old_selections
3761 .iter()
3762 .map(|s| {
3763 let anchor = snapshot.anchor_after(s.head());
3764 s.map(|_| anchor)
3765 })
3766 .collect::<Vec<_>>()
3767 };
3768 buffer.edit(
3769 old_selections
3770 .iter()
3771 .map(|s| (s.start..s.end, text.clone())),
3772 autoindent_mode,
3773 cx,
3774 );
3775 anchors
3776 });
3777
3778 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3779 s.select_anchors(selection_anchors);
3780 });
3781
3782 cx.notify();
3783 });
3784 }
3785
3786 fn trigger_completion_on_input(
3787 &mut self,
3788 text: &str,
3789 trigger_in_words: bool,
3790 window: &mut Window,
3791 cx: &mut Context<Self>,
3792 ) {
3793 let ignore_completion_provider = self
3794 .context_menu
3795 .borrow()
3796 .as_ref()
3797 .map(|menu| match menu {
3798 CodeContextMenu::Completions(completions_menu) => {
3799 completions_menu.ignore_completion_provider
3800 }
3801 CodeContextMenu::CodeActions(_) => false,
3802 })
3803 .unwrap_or(false);
3804
3805 if ignore_completion_provider {
3806 self.show_word_completions(&ShowWordCompletions, window, cx);
3807 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3808 self.show_completions(
3809 &ShowCompletions {
3810 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3811 },
3812 window,
3813 cx,
3814 );
3815 } else {
3816 self.hide_context_menu(window, cx);
3817 }
3818 }
3819
3820 fn is_completion_trigger(
3821 &self,
3822 text: &str,
3823 trigger_in_words: bool,
3824 cx: &mut Context<Self>,
3825 ) -> bool {
3826 let position = self.selections.newest_anchor().head();
3827 let multibuffer = self.buffer.read(cx);
3828 let Some(buffer) = position
3829 .buffer_id
3830 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3831 else {
3832 return false;
3833 };
3834
3835 if let Some(completion_provider) = &self.completion_provider {
3836 completion_provider.is_completion_trigger(
3837 &buffer,
3838 position.text_anchor,
3839 text,
3840 trigger_in_words,
3841 cx,
3842 )
3843 } else {
3844 false
3845 }
3846 }
3847
3848 /// If any empty selections is touching the start of its innermost containing autoclose
3849 /// region, expand it to select the brackets.
3850 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3851 let selections = self.selections.all::<usize>(cx);
3852 let buffer = self.buffer.read(cx).read(cx);
3853 let new_selections = self
3854 .selections_with_autoclose_regions(selections, &buffer)
3855 .map(|(mut selection, region)| {
3856 if !selection.is_empty() {
3857 return selection;
3858 }
3859
3860 if let Some(region) = region {
3861 let mut range = region.range.to_offset(&buffer);
3862 if selection.start == range.start && range.start >= region.pair.start.len() {
3863 range.start -= region.pair.start.len();
3864 if buffer.contains_str_at(range.start, ®ion.pair.start)
3865 && buffer.contains_str_at(range.end, ®ion.pair.end)
3866 {
3867 range.end += region.pair.end.len();
3868 selection.start = range.start;
3869 selection.end = range.end;
3870
3871 return selection;
3872 }
3873 }
3874 }
3875
3876 let always_treat_brackets_as_autoclosed = buffer
3877 .language_settings_at(selection.start, cx)
3878 .always_treat_brackets_as_autoclosed;
3879
3880 if !always_treat_brackets_as_autoclosed {
3881 return selection;
3882 }
3883
3884 if let Some(scope) = buffer.language_scope_at(selection.start) {
3885 for (pair, enabled) in scope.brackets() {
3886 if !enabled || !pair.close {
3887 continue;
3888 }
3889
3890 if buffer.contains_str_at(selection.start, &pair.end) {
3891 let pair_start_len = pair.start.len();
3892 if buffer.contains_str_at(
3893 selection.start.saturating_sub(pair_start_len),
3894 &pair.start,
3895 ) {
3896 selection.start -= pair_start_len;
3897 selection.end += pair.end.len();
3898
3899 return selection;
3900 }
3901 }
3902 }
3903 }
3904
3905 selection
3906 })
3907 .collect();
3908
3909 drop(buffer);
3910 self.change_selections(None, window, cx, |selections| {
3911 selections.select(new_selections)
3912 });
3913 }
3914
3915 /// Iterate the given selections, and for each one, find the smallest surrounding
3916 /// autoclose region. This uses the ordering of the selections and the autoclose
3917 /// regions to avoid repeated comparisons.
3918 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3919 &'a self,
3920 selections: impl IntoIterator<Item = Selection<D>>,
3921 buffer: &'a MultiBufferSnapshot,
3922 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3923 let mut i = 0;
3924 let mut regions = self.autoclose_regions.as_slice();
3925 selections.into_iter().map(move |selection| {
3926 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3927
3928 let mut enclosing = None;
3929 while let Some(pair_state) = regions.get(i) {
3930 if pair_state.range.end.to_offset(buffer) < range.start {
3931 regions = ®ions[i + 1..];
3932 i = 0;
3933 } else if pair_state.range.start.to_offset(buffer) > range.end {
3934 break;
3935 } else {
3936 if pair_state.selection_id == selection.id {
3937 enclosing = Some(pair_state);
3938 }
3939 i += 1;
3940 }
3941 }
3942
3943 (selection, enclosing)
3944 })
3945 }
3946
3947 /// Remove any autoclose regions that no longer contain their selection.
3948 fn invalidate_autoclose_regions(
3949 &mut self,
3950 mut selections: &[Selection<Anchor>],
3951 buffer: &MultiBufferSnapshot,
3952 ) {
3953 self.autoclose_regions.retain(|state| {
3954 let mut i = 0;
3955 while let Some(selection) = selections.get(i) {
3956 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3957 selections = &selections[1..];
3958 continue;
3959 }
3960 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3961 break;
3962 }
3963 if selection.id == state.selection_id {
3964 return true;
3965 } else {
3966 i += 1;
3967 }
3968 }
3969 false
3970 });
3971 }
3972
3973 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3974 let offset = position.to_offset(buffer);
3975 let (word_range, kind) = buffer.surrounding_word(offset, true);
3976 if offset > word_range.start && kind == Some(CharKind::Word) {
3977 Some(
3978 buffer
3979 .text_for_range(word_range.start..offset)
3980 .collect::<String>(),
3981 )
3982 } else {
3983 None
3984 }
3985 }
3986
3987 pub fn toggle_inlay_hints(
3988 &mut self,
3989 _: &ToggleInlayHints,
3990 _: &mut Window,
3991 cx: &mut Context<Self>,
3992 ) {
3993 self.refresh_inlay_hints(
3994 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3995 cx,
3996 );
3997 }
3998
3999 pub fn inlay_hints_enabled(&self) -> bool {
4000 self.inlay_hint_cache.enabled
4001 }
4002
4003 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4004 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4005 return;
4006 }
4007
4008 let reason_description = reason.description();
4009 let ignore_debounce = matches!(
4010 reason,
4011 InlayHintRefreshReason::SettingsChange(_)
4012 | InlayHintRefreshReason::Toggle(_)
4013 | InlayHintRefreshReason::ExcerptsRemoved(_)
4014 | InlayHintRefreshReason::ModifiersChanged(_)
4015 );
4016 let (invalidate_cache, required_languages) = match reason {
4017 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4018 match self.inlay_hint_cache.modifiers_override(enabled) {
4019 Some(enabled) => {
4020 if enabled {
4021 (InvalidationStrategy::RefreshRequested, None)
4022 } else {
4023 self.splice_inlays(
4024 &self
4025 .visible_inlay_hints(cx)
4026 .iter()
4027 .map(|inlay| inlay.id)
4028 .collect::<Vec<InlayId>>(),
4029 Vec::new(),
4030 cx,
4031 );
4032 return;
4033 }
4034 }
4035 None => return,
4036 }
4037 }
4038 InlayHintRefreshReason::Toggle(enabled) => {
4039 if self.inlay_hint_cache.toggle(enabled) {
4040 if enabled {
4041 (InvalidationStrategy::RefreshRequested, None)
4042 } else {
4043 self.splice_inlays(
4044 &self
4045 .visible_inlay_hints(cx)
4046 .iter()
4047 .map(|inlay| inlay.id)
4048 .collect::<Vec<InlayId>>(),
4049 Vec::new(),
4050 cx,
4051 );
4052 return;
4053 }
4054 } else {
4055 return;
4056 }
4057 }
4058 InlayHintRefreshReason::SettingsChange(new_settings) => {
4059 match self.inlay_hint_cache.update_settings(
4060 &self.buffer,
4061 new_settings,
4062 self.visible_inlay_hints(cx),
4063 cx,
4064 ) {
4065 ControlFlow::Break(Some(InlaySplice {
4066 to_remove,
4067 to_insert,
4068 })) => {
4069 self.splice_inlays(&to_remove, to_insert, cx);
4070 return;
4071 }
4072 ControlFlow::Break(None) => return,
4073 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4074 }
4075 }
4076 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4077 if let Some(InlaySplice {
4078 to_remove,
4079 to_insert,
4080 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4081 {
4082 self.splice_inlays(&to_remove, to_insert, cx);
4083 }
4084 return;
4085 }
4086 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4087 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4088 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4089 }
4090 InlayHintRefreshReason::RefreshRequested => {
4091 (InvalidationStrategy::RefreshRequested, None)
4092 }
4093 };
4094
4095 if let Some(InlaySplice {
4096 to_remove,
4097 to_insert,
4098 }) = self.inlay_hint_cache.spawn_hint_refresh(
4099 reason_description,
4100 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4101 invalidate_cache,
4102 ignore_debounce,
4103 cx,
4104 ) {
4105 self.splice_inlays(&to_remove, to_insert, cx);
4106 }
4107 }
4108
4109 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4110 self.display_map
4111 .read(cx)
4112 .current_inlays()
4113 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4114 .cloned()
4115 .collect()
4116 }
4117
4118 pub fn excerpts_for_inlay_hints_query(
4119 &self,
4120 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4121 cx: &mut Context<Editor>,
4122 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4123 let Some(project) = self.project.as_ref() else {
4124 return HashMap::default();
4125 };
4126 let project = project.read(cx);
4127 let multi_buffer = self.buffer().read(cx);
4128 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4129 let multi_buffer_visible_start = self
4130 .scroll_manager
4131 .anchor()
4132 .anchor
4133 .to_point(&multi_buffer_snapshot);
4134 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4135 multi_buffer_visible_start
4136 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4137 Bias::Left,
4138 );
4139 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4140 multi_buffer_snapshot
4141 .range_to_buffer_ranges(multi_buffer_visible_range)
4142 .into_iter()
4143 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4144 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4145 let buffer_file = project::File::from_dyn(buffer.file())?;
4146 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4147 let worktree_entry = buffer_worktree
4148 .read(cx)
4149 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4150 if worktree_entry.is_ignored {
4151 return None;
4152 }
4153
4154 let language = buffer.language()?;
4155 if let Some(restrict_to_languages) = restrict_to_languages {
4156 if !restrict_to_languages.contains(language) {
4157 return None;
4158 }
4159 }
4160 Some((
4161 excerpt_id,
4162 (
4163 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4164 buffer.version().clone(),
4165 excerpt_visible_range,
4166 ),
4167 ))
4168 })
4169 .collect()
4170 }
4171
4172 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4173 TextLayoutDetails {
4174 text_system: window.text_system().clone(),
4175 editor_style: self.style.clone().unwrap(),
4176 rem_size: window.rem_size(),
4177 scroll_anchor: self.scroll_manager.anchor(),
4178 visible_rows: self.visible_line_count(),
4179 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4180 }
4181 }
4182
4183 pub fn splice_inlays(
4184 &self,
4185 to_remove: &[InlayId],
4186 to_insert: Vec<Inlay>,
4187 cx: &mut Context<Self>,
4188 ) {
4189 self.display_map.update(cx, |display_map, cx| {
4190 display_map.splice_inlays(to_remove, to_insert, cx)
4191 });
4192 cx.notify();
4193 }
4194
4195 fn trigger_on_type_formatting(
4196 &self,
4197 input: String,
4198 window: &mut Window,
4199 cx: &mut Context<Self>,
4200 ) -> Option<Task<Result<()>>> {
4201 if input.len() != 1 {
4202 return None;
4203 }
4204
4205 let project = self.project.as_ref()?;
4206 let position = self.selections.newest_anchor().head();
4207 let (buffer, buffer_position) = self
4208 .buffer
4209 .read(cx)
4210 .text_anchor_for_position(position, cx)?;
4211
4212 let settings = language_settings::language_settings(
4213 buffer
4214 .read(cx)
4215 .language_at(buffer_position)
4216 .map(|l| l.name()),
4217 buffer.read(cx).file(),
4218 cx,
4219 );
4220 if !settings.use_on_type_format {
4221 return None;
4222 }
4223
4224 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4225 // hence we do LSP request & edit on host side only — add formats to host's history.
4226 let push_to_lsp_host_history = true;
4227 // If this is not the host, append its history with new edits.
4228 let push_to_client_history = project.read(cx).is_via_collab();
4229
4230 let on_type_formatting = project.update(cx, |project, cx| {
4231 project.on_type_format(
4232 buffer.clone(),
4233 buffer_position,
4234 input,
4235 push_to_lsp_host_history,
4236 cx,
4237 )
4238 });
4239 Some(cx.spawn_in(window, async move |editor, cx| {
4240 if let Some(transaction) = on_type_formatting.await? {
4241 if push_to_client_history {
4242 buffer
4243 .update(cx, |buffer, _| {
4244 buffer.push_transaction(transaction, Instant::now());
4245 })
4246 .ok();
4247 }
4248 editor.update(cx, |editor, cx| {
4249 editor.refresh_document_highlights(cx);
4250 })?;
4251 }
4252 Ok(())
4253 }))
4254 }
4255
4256 pub fn show_word_completions(
4257 &mut self,
4258 _: &ShowWordCompletions,
4259 window: &mut Window,
4260 cx: &mut Context<Self>,
4261 ) {
4262 self.open_completions_menu(true, None, window, cx);
4263 }
4264
4265 pub fn show_completions(
4266 &mut self,
4267 options: &ShowCompletions,
4268 window: &mut Window,
4269 cx: &mut Context<Self>,
4270 ) {
4271 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4272 }
4273
4274 fn open_completions_menu(
4275 &mut self,
4276 ignore_completion_provider: bool,
4277 trigger: Option<&str>,
4278 window: &mut Window,
4279 cx: &mut Context<Self>,
4280 ) {
4281 if self.pending_rename.is_some() {
4282 return;
4283 }
4284 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4285 return;
4286 }
4287
4288 let position = self.selections.newest_anchor().head();
4289 if position.diff_base_anchor.is_some() {
4290 return;
4291 }
4292 let (buffer, buffer_position) =
4293 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4294 output
4295 } else {
4296 return;
4297 };
4298 let buffer_snapshot = buffer.read(cx).snapshot();
4299 let show_completion_documentation = buffer_snapshot
4300 .settings_at(buffer_position, cx)
4301 .show_completion_documentation;
4302
4303 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4304
4305 let trigger_kind = match trigger {
4306 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4307 CompletionTriggerKind::TRIGGER_CHARACTER
4308 }
4309 _ => CompletionTriggerKind::INVOKED,
4310 };
4311 let completion_context = CompletionContext {
4312 trigger_character: trigger.and_then(|trigger| {
4313 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4314 Some(String::from(trigger))
4315 } else {
4316 None
4317 }
4318 }),
4319 trigger_kind,
4320 };
4321
4322 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4323 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4324 let word_to_exclude = buffer_snapshot
4325 .text_for_range(old_range.clone())
4326 .collect::<String>();
4327 (
4328 buffer_snapshot.anchor_before(old_range.start)
4329 ..buffer_snapshot.anchor_after(old_range.end),
4330 Some(word_to_exclude),
4331 )
4332 } else {
4333 (buffer_position..buffer_position, None)
4334 };
4335
4336 let completion_settings = language_settings(
4337 buffer_snapshot
4338 .language_at(buffer_position)
4339 .map(|language| language.name()),
4340 buffer_snapshot.file(),
4341 cx,
4342 )
4343 .completions;
4344
4345 // The document can be large, so stay in reasonable bounds when searching for words,
4346 // otherwise completion pop-up might be slow to appear.
4347 const WORD_LOOKUP_ROWS: u32 = 5_000;
4348 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4349 let min_word_search = buffer_snapshot.clip_point(
4350 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4351 Bias::Left,
4352 );
4353 let max_word_search = buffer_snapshot.clip_point(
4354 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4355 Bias::Right,
4356 );
4357 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4358 ..buffer_snapshot.point_to_offset(max_word_search);
4359
4360 let provider = self
4361 .completion_provider
4362 .as_ref()
4363 .filter(|_| !ignore_completion_provider);
4364 let skip_digits = query
4365 .as_ref()
4366 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4367
4368 let (mut words, provided_completions) = match provider {
4369 Some(provider) => {
4370 let completions = provider.completions(
4371 position.excerpt_id,
4372 &buffer,
4373 buffer_position,
4374 completion_context,
4375 window,
4376 cx,
4377 );
4378
4379 let words = match completion_settings.words {
4380 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4381 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4382 .background_spawn(async move {
4383 buffer_snapshot.words_in_range(WordsQuery {
4384 fuzzy_contents: None,
4385 range: word_search_range,
4386 skip_digits,
4387 })
4388 }),
4389 };
4390
4391 (words, completions)
4392 }
4393 None => (
4394 cx.background_spawn(async move {
4395 buffer_snapshot.words_in_range(WordsQuery {
4396 fuzzy_contents: None,
4397 range: word_search_range,
4398 skip_digits,
4399 })
4400 }),
4401 Task::ready(Ok(None)),
4402 ),
4403 };
4404
4405 let sort_completions = provider
4406 .as_ref()
4407 .map_or(true, |provider| provider.sort_completions());
4408
4409 let filter_completions = provider
4410 .as_ref()
4411 .map_or(true, |provider| provider.filter_completions());
4412
4413 let id = post_inc(&mut self.next_completion_id);
4414 let task = cx.spawn_in(window, async move |editor, cx| {
4415 async move {
4416 editor.update(cx, |this, _| {
4417 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4418 })?;
4419
4420 let mut completions = Vec::new();
4421 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4422 completions.extend(provided_completions);
4423 if completion_settings.words == WordsCompletionMode::Fallback {
4424 words = Task::ready(HashMap::default());
4425 }
4426 }
4427
4428 let mut words = words.await;
4429 if let Some(word_to_exclude) = &word_to_exclude {
4430 words.remove(word_to_exclude);
4431 }
4432 for lsp_completion in &completions {
4433 words.remove(&lsp_completion.new_text);
4434 }
4435 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4436 old_range: old_range.clone(),
4437 new_text: word.clone(),
4438 label: CodeLabel::plain(word, None),
4439 icon_path: None,
4440 documentation: None,
4441 source: CompletionSource::BufferWord {
4442 word_range,
4443 resolved: false,
4444 },
4445 confirm: None,
4446 }));
4447
4448 let menu = if completions.is_empty() {
4449 None
4450 } else {
4451 let mut menu = CompletionsMenu::new(
4452 id,
4453 sort_completions,
4454 show_completion_documentation,
4455 ignore_completion_provider,
4456 position,
4457 buffer.clone(),
4458 completions.into(),
4459 );
4460
4461 menu.filter(
4462 if filter_completions {
4463 query.as_deref()
4464 } else {
4465 None
4466 },
4467 cx.background_executor().clone(),
4468 )
4469 .await;
4470
4471 menu.visible().then_some(menu)
4472 };
4473
4474 editor.update_in(cx, |editor, window, cx| {
4475 match editor.context_menu.borrow().as_ref() {
4476 None => {}
4477 Some(CodeContextMenu::Completions(prev_menu)) => {
4478 if prev_menu.id > id {
4479 return;
4480 }
4481 }
4482 _ => return,
4483 }
4484
4485 if editor.focus_handle.is_focused(window) && menu.is_some() {
4486 let mut menu = menu.unwrap();
4487 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4488
4489 *editor.context_menu.borrow_mut() =
4490 Some(CodeContextMenu::Completions(menu));
4491
4492 if editor.show_edit_predictions_in_menu() {
4493 editor.update_visible_inline_completion(window, cx);
4494 } else {
4495 editor.discard_inline_completion(false, cx);
4496 }
4497
4498 cx.notify();
4499 } else if editor.completion_tasks.len() <= 1 {
4500 // If there are no more completion tasks and the last menu was
4501 // empty, we should hide it.
4502 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4503 // If it was already hidden and we don't show inline
4504 // completions in the menu, we should also show the
4505 // inline-completion when available.
4506 if was_hidden && editor.show_edit_predictions_in_menu() {
4507 editor.update_visible_inline_completion(window, cx);
4508 }
4509 }
4510 })?;
4511
4512 anyhow::Ok(())
4513 }
4514 .log_err()
4515 .await
4516 });
4517
4518 self.completion_tasks.push((id, task));
4519 }
4520
4521 #[cfg(feature = "test-support")]
4522 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4523 let menu = self.context_menu.borrow();
4524 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4525 let completions = menu.completions.borrow();
4526 Some(completions.to_vec())
4527 } else {
4528 None
4529 }
4530 }
4531
4532 pub fn confirm_completion(
4533 &mut self,
4534 action: &ConfirmCompletion,
4535 window: &mut Window,
4536 cx: &mut Context<Self>,
4537 ) -> Option<Task<Result<()>>> {
4538 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4539 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4540 }
4541
4542 pub fn compose_completion(
4543 &mut self,
4544 action: &ComposeCompletion,
4545 window: &mut Window,
4546 cx: &mut Context<Self>,
4547 ) -> Option<Task<Result<()>>> {
4548 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4549 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4550 }
4551
4552 fn do_completion(
4553 &mut self,
4554 item_ix: Option<usize>,
4555 intent: CompletionIntent,
4556 window: &mut Window,
4557 cx: &mut Context<Editor>,
4558 ) -> Option<Task<Result<()>>> {
4559 use language::ToOffset as _;
4560
4561 let completions_menu =
4562 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4563 menu
4564 } else {
4565 return None;
4566 };
4567
4568 let candidate_id = {
4569 let entries = completions_menu.entries.borrow();
4570 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4571 if self.show_edit_predictions_in_menu() {
4572 self.discard_inline_completion(true, cx);
4573 }
4574 mat.candidate_id
4575 };
4576
4577 let buffer_handle = completions_menu.buffer;
4578 let completion = completions_menu
4579 .completions
4580 .borrow()
4581 .get(candidate_id)?
4582 .clone();
4583 cx.stop_propagation();
4584
4585 let snippet;
4586 let new_text;
4587 if completion.is_snippet() {
4588 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4589 new_text = snippet.as_ref().unwrap().text.clone();
4590 } else {
4591 snippet = None;
4592 new_text = completion.new_text.clone();
4593 };
4594 let selections = self.selections.all::<usize>(cx);
4595 let buffer = buffer_handle.read(cx);
4596 let old_range = completion.old_range.to_offset(buffer);
4597 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4598
4599 let newest_selection = self.selections.newest_anchor();
4600 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4601 return None;
4602 }
4603
4604 let lookbehind = newest_selection
4605 .start
4606 .text_anchor
4607 .to_offset(buffer)
4608 .saturating_sub(old_range.start);
4609 let lookahead = old_range
4610 .end
4611 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4612 let mut common_prefix_len = 0;
4613 for (a, b) in old_text.chars().zip(new_text.chars()) {
4614 if a == b {
4615 common_prefix_len += a.len_utf8();
4616 } else {
4617 break;
4618 }
4619 }
4620
4621 let snapshot = self.buffer.read(cx).snapshot(cx);
4622 let mut range_to_replace: Option<Range<usize>> = None;
4623 let mut ranges = Vec::new();
4624 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4625 for selection in &selections {
4626 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4627 let start = selection.start.saturating_sub(lookbehind);
4628 let end = selection.end + lookahead;
4629 if selection.id == newest_selection.id {
4630 range_to_replace = Some(start + common_prefix_len..end);
4631 }
4632 ranges.push(start + common_prefix_len..end);
4633 } else {
4634 common_prefix_len = 0;
4635 ranges.clear();
4636 ranges.extend(selections.iter().map(|s| {
4637 if s.id == newest_selection.id {
4638 range_to_replace = Some(old_range.clone());
4639 old_range.clone()
4640 } else {
4641 s.start..s.end
4642 }
4643 }));
4644 break;
4645 }
4646 if !self.linked_edit_ranges.is_empty() {
4647 let start_anchor = snapshot.anchor_before(selection.head());
4648 let end_anchor = snapshot.anchor_after(selection.tail());
4649 if let Some(ranges) = self
4650 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4651 {
4652 for (buffer, edits) in ranges {
4653 linked_edits.entry(buffer.clone()).or_default().extend(
4654 edits
4655 .into_iter()
4656 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4657 );
4658 }
4659 }
4660 }
4661 }
4662 let text = &new_text[common_prefix_len..];
4663
4664 let utf16_range_to_replace = range_to_replace.map(|range| {
4665 let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
4666 let selection_start_utf16 = newest_selection.start.0 as isize;
4667
4668 range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4669 ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4670 });
4671 cx.emit(EditorEvent::InputHandled {
4672 utf16_range_to_replace,
4673 text: text.into(),
4674 });
4675
4676 self.transact(window, cx, |this, window, cx| {
4677 if let Some(mut snippet) = snippet {
4678 snippet.text = text.to_string();
4679 for tabstop in snippet
4680 .tabstops
4681 .iter_mut()
4682 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4683 {
4684 tabstop.start -= common_prefix_len as isize;
4685 tabstop.end -= common_prefix_len as isize;
4686 }
4687
4688 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4689 } else {
4690 this.buffer.update(cx, |buffer, cx| {
4691 let edits = ranges.iter().map(|range| (range.clone(), text));
4692 buffer.edit(edits, this.autoindent_mode.clone(), cx);
4693 });
4694 }
4695 for (buffer, edits) in linked_edits {
4696 buffer.update(cx, |buffer, cx| {
4697 let snapshot = buffer.snapshot();
4698 let edits = edits
4699 .into_iter()
4700 .map(|(range, text)| {
4701 use text::ToPoint as TP;
4702 let end_point = TP::to_point(&range.end, &snapshot);
4703 let start_point = TP::to_point(&range.start, &snapshot);
4704 (start_point..end_point, text)
4705 })
4706 .sorted_by_key(|(range, _)| range.start);
4707 buffer.edit(edits, None, cx);
4708 })
4709 }
4710
4711 this.refresh_inline_completion(true, false, window, cx);
4712 });
4713
4714 let show_new_completions_on_confirm = completion
4715 .confirm
4716 .as_ref()
4717 .map_or(false, |confirm| confirm(intent, window, cx));
4718 if show_new_completions_on_confirm {
4719 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4720 }
4721
4722 let provider = self.completion_provider.as_ref()?;
4723 drop(completion);
4724 let apply_edits = provider.apply_additional_edits_for_completion(
4725 buffer_handle,
4726 completions_menu.completions.clone(),
4727 candidate_id,
4728 true,
4729 cx,
4730 );
4731
4732 let editor_settings = EditorSettings::get_global(cx);
4733 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4734 // After the code completion is finished, users often want to know what signatures are needed.
4735 // so we should automatically call signature_help
4736 self.show_signature_help(&ShowSignatureHelp, window, cx);
4737 }
4738
4739 Some(cx.foreground_executor().spawn(async move {
4740 apply_edits.await?;
4741 Ok(())
4742 }))
4743 }
4744
4745 pub fn toggle_code_actions(
4746 &mut self,
4747 action: &ToggleCodeActions,
4748 window: &mut Window,
4749 cx: &mut Context<Self>,
4750 ) {
4751 let mut context_menu = self.context_menu.borrow_mut();
4752 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4753 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4754 // Toggle if we're selecting the same one
4755 *context_menu = None;
4756 cx.notify();
4757 return;
4758 } else {
4759 // Otherwise, clear it and start a new one
4760 *context_menu = None;
4761 cx.notify();
4762 }
4763 }
4764 drop(context_menu);
4765 let snapshot = self.snapshot(window, cx);
4766 let deployed_from_indicator = action.deployed_from_indicator;
4767 let mut task = self.code_actions_task.take();
4768 let action = action.clone();
4769 cx.spawn_in(window, async move |editor, cx| {
4770 while let Some(prev_task) = task {
4771 prev_task.await.log_err();
4772 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4773 }
4774
4775 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4776 if editor.focus_handle.is_focused(window) {
4777 let multibuffer_point = action
4778 .deployed_from_indicator
4779 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4780 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4781 let (buffer, buffer_row) = snapshot
4782 .buffer_snapshot
4783 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4784 .and_then(|(buffer_snapshot, range)| {
4785 editor
4786 .buffer
4787 .read(cx)
4788 .buffer(buffer_snapshot.remote_id())
4789 .map(|buffer| (buffer, range.start.row))
4790 })?;
4791 let (_, code_actions) = editor
4792 .available_code_actions
4793 .clone()
4794 .and_then(|(location, code_actions)| {
4795 let snapshot = location.buffer.read(cx).snapshot();
4796 let point_range = location.range.to_point(&snapshot);
4797 let point_range = point_range.start.row..=point_range.end.row;
4798 if point_range.contains(&buffer_row) {
4799 Some((location, code_actions))
4800 } else {
4801 None
4802 }
4803 })
4804 .unzip();
4805 let buffer_id = buffer.read(cx).remote_id();
4806 let tasks = editor
4807 .tasks
4808 .get(&(buffer_id, buffer_row))
4809 .map(|t| Arc::new(t.to_owned()));
4810 if tasks.is_none() && code_actions.is_none() {
4811 return None;
4812 }
4813
4814 editor.completion_tasks.clear();
4815 editor.discard_inline_completion(false, cx);
4816 let task_context =
4817 tasks
4818 .as_ref()
4819 .zip(editor.project.clone())
4820 .map(|(tasks, project)| {
4821 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4822 });
4823
4824 let debugger_flag = cx.has_flag::<Debugger>();
4825
4826 Some(cx.spawn_in(window, async move |editor, cx| {
4827 let task_context = match task_context {
4828 Some(task_context) => task_context.await,
4829 None => None,
4830 };
4831 let resolved_tasks =
4832 tasks.zip(task_context).map(|(tasks, task_context)| {
4833 Rc::new(ResolvedTasks {
4834 templates: tasks.resolve(&task_context).collect(),
4835 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4836 multibuffer_point.row,
4837 tasks.column,
4838 )),
4839 })
4840 });
4841 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
4842 tasks
4843 .templates
4844 .iter()
4845 .filter(|task| {
4846 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4847 debugger_flag
4848 } else {
4849 true
4850 }
4851 })
4852 .count()
4853 == 1
4854 }) && code_actions
4855 .as_ref()
4856 .map_or(true, |actions| actions.is_empty());
4857 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4858 *editor.context_menu.borrow_mut() =
4859 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4860 buffer,
4861 actions: CodeActionContents {
4862 tasks: resolved_tasks,
4863 actions: code_actions,
4864 },
4865 selected_item: Default::default(),
4866 scroll_handle: UniformListScrollHandle::default(),
4867 deployed_from_indicator,
4868 }));
4869 if spawn_straight_away {
4870 if let Some(task) = editor.confirm_code_action(
4871 &ConfirmCodeAction { item_ix: Some(0) },
4872 window,
4873 cx,
4874 ) {
4875 cx.notify();
4876 return task;
4877 }
4878 }
4879 cx.notify();
4880 Task::ready(Ok(()))
4881 }) {
4882 task.await
4883 } else {
4884 Ok(())
4885 }
4886 }))
4887 } else {
4888 Some(Task::ready(Ok(())))
4889 }
4890 })?;
4891 if let Some(task) = spawned_test_task {
4892 task.await?;
4893 }
4894
4895 Ok::<_, anyhow::Error>(())
4896 })
4897 .detach_and_log_err(cx);
4898 }
4899
4900 pub fn confirm_code_action(
4901 &mut self,
4902 action: &ConfirmCodeAction,
4903 window: &mut Window,
4904 cx: &mut Context<Self>,
4905 ) -> Option<Task<Result<()>>> {
4906 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4907
4908 let actions_menu =
4909 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4910 menu
4911 } else {
4912 return None;
4913 };
4914
4915 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4916 let action = actions_menu.actions.get(action_ix)?;
4917 let title = action.label();
4918 let buffer = actions_menu.buffer;
4919 let workspace = self.workspace()?;
4920
4921 match action {
4922 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4923 match resolved_task.task_type() {
4924 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
4925 workspace::tasks::schedule_resolved_task(
4926 workspace,
4927 task_source_kind,
4928 resolved_task,
4929 false,
4930 cx,
4931 );
4932
4933 Some(Task::ready(Ok(())))
4934 }),
4935 task::TaskType::Debug(debug_args) => {
4936 if debug_args.locator.is_some() {
4937 workspace.update(cx, |workspace, cx| {
4938 workspace::tasks::schedule_resolved_task(
4939 workspace,
4940 task_source_kind,
4941 resolved_task,
4942 false,
4943 cx,
4944 );
4945 });
4946
4947 return Some(Task::ready(Ok(())));
4948 }
4949
4950 if let Some(project) = self.project.as_ref() {
4951 project
4952 .update(cx, |project, cx| {
4953 project.start_debug_session(
4954 resolved_task.resolved_debug_adapter_config().unwrap(),
4955 cx,
4956 )
4957 })
4958 .detach_and_log_err(cx);
4959 Some(Task::ready(Ok(())))
4960 } else {
4961 Some(Task::ready(Ok(())))
4962 }
4963 }
4964 }
4965 }
4966 CodeActionsItem::CodeAction {
4967 excerpt_id,
4968 action,
4969 provider,
4970 } => {
4971 let apply_code_action =
4972 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4973 let workspace = workspace.downgrade();
4974 Some(cx.spawn_in(window, async move |editor, cx| {
4975 let project_transaction = apply_code_action.await?;
4976 Self::open_project_transaction(
4977 &editor,
4978 workspace,
4979 project_transaction,
4980 title,
4981 cx,
4982 )
4983 .await
4984 }))
4985 }
4986 }
4987 }
4988
4989 pub async fn open_project_transaction(
4990 this: &WeakEntity<Editor>,
4991 workspace: WeakEntity<Workspace>,
4992 transaction: ProjectTransaction,
4993 title: String,
4994 cx: &mut AsyncWindowContext,
4995 ) -> Result<()> {
4996 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4997 cx.update(|_, cx| {
4998 entries.sort_unstable_by_key(|(buffer, _)| {
4999 buffer.read(cx).file().map(|f| f.path().clone())
5000 });
5001 })?;
5002
5003 // If the project transaction's edits are all contained within this editor, then
5004 // avoid opening a new editor to display them.
5005
5006 if let Some((buffer, transaction)) = entries.first() {
5007 if entries.len() == 1 {
5008 let excerpt = this.update(cx, |editor, cx| {
5009 editor
5010 .buffer()
5011 .read(cx)
5012 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5013 })?;
5014 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5015 if excerpted_buffer == *buffer {
5016 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5017 let excerpt_range = excerpt_range.to_offset(buffer);
5018 buffer
5019 .edited_ranges_for_transaction::<usize>(transaction)
5020 .all(|range| {
5021 excerpt_range.start <= range.start
5022 && excerpt_range.end >= range.end
5023 })
5024 })?;
5025
5026 if all_edits_within_excerpt {
5027 return Ok(());
5028 }
5029 }
5030 }
5031 }
5032 } else {
5033 return Ok(());
5034 }
5035
5036 let mut ranges_to_highlight = Vec::new();
5037 let excerpt_buffer = cx.new(|cx| {
5038 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5039 for (buffer_handle, transaction) in &entries {
5040 let edited_ranges = buffer_handle
5041 .read(cx)
5042 .edited_ranges_for_transaction::<Point>(transaction)
5043 .collect::<Vec<_>>();
5044 let (ranges, _) = multibuffer.set_excerpts_for_path(
5045 PathKey::for_buffer(buffer_handle, cx),
5046 buffer_handle.clone(),
5047 edited_ranges,
5048 DEFAULT_MULTIBUFFER_CONTEXT,
5049 cx,
5050 );
5051
5052 ranges_to_highlight.extend(ranges);
5053 }
5054 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5055 multibuffer
5056 })?;
5057
5058 workspace.update_in(cx, |workspace, window, cx| {
5059 let project = workspace.project().clone();
5060 let editor =
5061 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5062 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5063 editor.update(cx, |editor, cx| {
5064 editor.highlight_background::<Self>(
5065 &ranges_to_highlight,
5066 |theme| theme.editor_highlighted_line_background,
5067 cx,
5068 );
5069 });
5070 })?;
5071
5072 Ok(())
5073 }
5074
5075 pub fn clear_code_action_providers(&mut self) {
5076 self.code_action_providers.clear();
5077 self.available_code_actions.take();
5078 }
5079
5080 pub fn add_code_action_provider(
5081 &mut self,
5082 provider: Rc<dyn CodeActionProvider>,
5083 window: &mut Window,
5084 cx: &mut Context<Self>,
5085 ) {
5086 if self
5087 .code_action_providers
5088 .iter()
5089 .any(|existing_provider| existing_provider.id() == provider.id())
5090 {
5091 return;
5092 }
5093
5094 self.code_action_providers.push(provider);
5095 self.refresh_code_actions(window, cx);
5096 }
5097
5098 pub fn remove_code_action_provider(
5099 &mut self,
5100 id: Arc<str>,
5101 window: &mut Window,
5102 cx: &mut Context<Self>,
5103 ) {
5104 self.code_action_providers
5105 .retain(|provider| provider.id() != id);
5106 self.refresh_code_actions(window, cx);
5107 }
5108
5109 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5110 let buffer = self.buffer.read(cx);
5111 let newest_selection = self.selections.newest_anchor().clone();
5112 if newest_selection.head().diff_base_anchor.is_some() {
5113 return None;
5114 }
5115 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5116 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5117 if start_buffer != end_buffer {
5118 return None;
5119 }
5120
5121 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5122 cx.background_executor()
5123 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5124 .await;
5125
5126 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5127 let providers = this.code_action_providers.clone();
5128 let tasks = this
5129 .code_action_providers
5130 .iter()
5131 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5132 .collect::<Vec<_>>();
5133 (providers, tasks)
5134 })?;
5135
5136 let mut actions = Vec::new();
5137 for (provider, provider_actions) in
5138 providers.into_iter().zip(future::join_all(tasks).await)
5139 {
5140 if let Some(provider_actions) = provider_actions.log_err() {
5141 actions.extend(provider_actions.into_iter().map(|action| {
5142 AvailableCodeAction {
5143 excerpt_id: newest_selection.start.excerpt_id,
5144 action,
5145 provider: provider.clone(),
5146 }
5147 }));
5148 }
5149 }
5150
5151 this.update(cx, |this, cx| {
5152 this.available_code_actions = if actions.is_empty() {
5153 None
5154 } else {
5155 Some((
5156 Location {
5157 buffer: start_buffer,
5158 range: start..end,
5159 },
5160 actions.into(),
5161 ))
5162 };
5163 cx.notify();
5164 })
5165 }));
5166 None
5167 }
5168
5169 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5170 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5171 self.show_git_blame_inline = false;
5172
5173 self.show_git_blame_inline_delay_task =
5174 Some(cx.spawn_in(window, async move |this, cx| {
5175 cx.background_executor().timer(delay).await;
5176
5177 this.update(cx, |this, cx| {
5178 this.show_git_blame_inline = true;
5179 cx.notify();
5180 })
5181 .log_err();
5182 }));
5183 }
5184 }
5185
5186 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5187 if self.pending_rename.is_some() {
5188 return None;
5189 }
5190
5191 let provider = self.semantics_provider.clone()?;
5192 let buffer = self.buffer.read(cx);
5193 let newest_selection = self.selections.newest_anchor().clone();
5194 let cursor_position = newest_selection.head();
5195 let (cursor_buffer, cursor_buffer_position) =
5196 buffer.text_anchor_for_position(cursor_position, cx)?;
5197 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5198 if cursor_buffer != tail_buffer {
5199 return None;
5200 }
5201 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5202 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5203 cx.background_executor()
5204 .timer(Duration::from_millis(debounce))
5205 .await;
5206
5207 let highlights = if let Some(highlights) = cx
5208 .update(|cx| {
5209 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5210 })
5211 .ok()
5212 .flatten()
5213 {
5214 highlights.await.log_err()
5215 } else {
5216 None
5217 };
5218
5219 if let Some(highlights) = highlights {
5220 this.update(cx, |this, cx| {
5221 if this.pending_rename.is_some() {
5222 return;
5223 }
5224
5225 let buffer_id = cursor_position.buffer_id;
5226 let buffer = this.buffer.read(cx);
5227 if !buffer
5228 .text_anchor_for_position(cursor_position, cx)
5229 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5230 {
5231 return;
5232 }
5233
5234 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5235 let mut write_ranges = Vec::new();
5236 let mut read_ranges = Vec::new();
5237 for highlight in highlights {
5238 for (excerpt_id, excerpt_range) in
5239 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5240 {
5241 let start = highlight
5242 .range
5243 .start
5244 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5245 let end = highlight
5246 .range
5247 .end
5248 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5249 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5250 continue;
5251 }
5252
5253 let range = Anchor {
5254 buffer_id,
5255 excerpt_id,
5256 text_anchor: start,
5257 diff_base_anchor: None,
5258 }..Anchor {
5259 buffer_id,
5260 excerpt_id,
5261 text_anchor: end,
5262 diff_base_anchor: None,
5263 };
5264 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5265 write_ranges.push(range);
5266 } else {
5267 read_ranges.push(range);
5268 }
5269 }
5270 }
5271
5272 this.highlight_background::<DocumentHighlightRead>(
5273 &read_ranges,
5274 |theme| theme.editor_document_highlight_read_background,
5275 cx,
5276 );
5277 this.highlight_background::<DocumentHighlightWrite>(
5278 &write_ranges,
5279 |theme| theme.editor_document_highlight_write_background,
5280 cx,
5281 );
5282 cx.notify();
5283 })
5284 .log_err();
5285 }
5286 }));
5287 None
5288 }
5289
5290 pub fn refresh_selected_text_highlights(
5291 &mut self,
5292 window: &mut Window,
5293 cx: &mut Context<Editor>,
5294 ) {
5295 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5296 return;
5297 }
5298 self.selection_highlight_task.take();
5299 if !EditorSettings::get_global(cx).selection_highlight {
5300 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5301 return;
5302 }
5303 if self.selections.count() != 1 || self.selections.line_mode {
5304 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5305 return;
5306 }
5307 let selection = self.selections.newest::<Point>(cx);
5308 if selection.is_empty() || selection.start.row != selection.end.row {
5309 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5310 return;
5311 }
5312 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5313 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5314 cx.background_executor()
5315 .timer(Duration::from_millis(debounce))
5316 .await;
5317 let Some(Some(matches_task)) = editor
5318 .update_in(cx, |editor, _, cx| {
5319 if editor.selections.count() != 1 || editor.selections.line_mode {
5320 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5321 return None;
5322 }
5323 let selection = editor.selections.newest::<Point>(cx);
5324 if selection.is_empty() || selection.start.row != selection.end.row {
5325 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5326 return None;
5327 }
5328 let buffer = editor.buffer().read(cx).snapshot(cx);
5329 let query = buffer.text_for_range(selection.range()).collect::<String>();
5330 if query.trim().is_empty() {
5331 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5332 return None;
5333 }
5334 Some(cx.background_spawn(async move {
5335 let mut ranges = Vec::new();
5336 let selection_anchors = selection.range().to_anchors(&buffer);
5337 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5338 for (search_buffer, search_range, excerpt_id) in
5339 buffer.range_to_buffer_ranges(range)
5340 {
5341 ranges.extend(
5342 project::search::SearchQuery::text(
5343 query.clone(),
5344 false,
5345 false,
5346 false,
5347 Default::default(),
5348 Default::default(),
5349 None,
5350 )
5351 .unwrap()
5352 .search(search_buffer, Some(search_range.clone()))
5353 .await
5354 .into_iter()
5355 .filter_map(
5356 |match_range| {
5357 let start = search_buffer.anchor_after(
5358 search_range.start + match_range.start,
5359 );
5360 let end = search_buffer.anchor_before(
5361 search_range.start + match_range.end,
5362 );
5363 let range = Anchor::range_in_buffer(
5364 excerpt_id,
5365 search_buffer.remote_id(),
5366 start..end,
5367 );
5368 (range != selection_anchors).then_some(range)
5369 },
5370 ),
5371 );
5372 }
5373 }
5374 ranges
5375 }))
5376 })
5377 .log_err()
5378 else {
5379 return;
5380 };
5381 let matches = matches_task.await;
5382 editor
5383 .update_in(cx, |editor, _, cx| {
5384 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5385 if !matches.is_empty() {
5386 editor.highlight_background::<SelectedTextHighlight>(
5387 &matches,
5388 |theme| theme.editor_document_highlight_bracket_background,
5389 cx,
5390 )
5391 }
5392 })
5393 .log_err();
5394 }));
5395 }
5396
5397 pub fn refresh_inline_completion(
5398 &mut self,
5399 debounce: bool,
5400 user_requested: bool,
5401 window: &mut Window,
5402 cx: &mut Context<Self>,
5403 ) -> Option<()> {
5404 let provider = self.edit_prediction_provider()?;
5405 let cursor = self.selections.newest_anchor().head();
5406 let (buffer, cursor_buffer_position) =
5407 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5408
5409 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5410 self.discard_inline_completion(false, cx);
5411 return None;
5412 }
5413
5414 if !user_requested
5415 && (!self.should_show_edit_predictions()
5416 || !self.is_focused(window)
5417 || buffer.read(cx).is_empty())
5418 {
5419 self.discard_inline_completion(false, cx);
5420 return None;
5421 }
5422
5423 self.update_visible_inline_completion(window, cx);
5424 provider.refresh(
5425 self.project.clone(),
5426 buffer,
5427 cursor_buffer_position,
5428 debounce,
5429 cx,
5430 );
5431 Some(())
5432 }
5433
5434 fn show_edit_predictions_in_menu(&self) -> bool {
5435 match self.edit_prediction_settings {
5436 EditPredictionSettings::Disabled => false,
5437 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5438 }
5439 }
5440
5441 pub fn edit_predictions_enabled(&self) -> bool {
5442 match self.edit_prediction_settings {
5443 EditPredictionSettings::Disabled => false,
5444 EditPredictionSettings::Enabled { .. } => true,
5445 }
5446 }
5447
5448 fn edit_prediction_requires_modifier(&self) -> bool {
5449 match self.edit_prediction_settings {
5450 EditPredictionSettings::Disabled => false,
5451 EditPredictionSettings::Enabled {
5452 preview_requires_modifier,
5453 ..
5454 } => preview_requires_modifier,
5455 }
5456 }
5457
5458 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5459 if self.edit_prediction_provider.is_none() {
5460 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5461 } else {
5462 let selection = self.selections.newest_anchor();
5463 let cursor = selection.head();
5464
5465 if let Some((buffer, cursor_buffer_position)) =
5466 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5467 {
5468 self.edit_prediction_settings =
5469 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5470 }
5471 }
5472 }
5473
5474 fn edit_prediction_settings_at_position(
5475 &self,
5476 buffer: &Entity<Buffer>,
5477 buffer_position: language::Anchor,
5478 cx: &App,
5479 ) -> EditPredictionSettings {
5480 if self.mode != EditorMode::Full
5481 || !self.show_inline_completions_override.unwrap_or(true)
5482 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5483 {
5484 return EditPredictionSettings::Disabled;
5485 }
5486
5487 let buffer = buffer.read(cx);
5488
5489 let file = buffer.file();
5490
5491 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5492 return EditPredictionSettings::Disabled;
5493 };
5494
5495 let by_provider = matches!(
5496 self.menu_inline_completions_policy,
5497 MenuInlineCompletionsPolicy::ByProvider
5498 );
5499
5500 let show_in_menu = by_provider
5501 && self
5502 .edit_prediction_provider
5503 .as_ref()
5504 .map_or(false, |provider| {
5505 provider.provider.show_completions_in_menu()
5506 });
5507
5508 let preview_requires_modifier =
5509 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5510
5511 EditPredictionSettings::Enabled {
5512 show_in_menu,
5513 preview_requires_modifier,
5514 }
5515 }
5516
5517 fn should_show_edit_predictions(&self) -> bool {
5518 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5519 }
5520
5521 pub fn edit_prediction_preview_is_active(&self) -> bool {
5522 matches!(
5523 self.edit_prediction_preview,
5524 EditPredictionPreview::Active { .. }
5525 )
5526 }
5527
5528 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5529 let cursor = self.selections.newest_anchor().head();
5530 if let Some((buffer, cursor_position)) =
5531 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5532 {
5533 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5534 } else {
5535 false
5536 }
5537 }
5538
5539 fn edit_predictions_enabled_in_buffer(
5540 &self,
5541 buffer: &Entity<Buffer>,
5542 buffer_position: language::Anchor,
5543 cx: &App,
5544 ) -> bool {
5545 maybe!({
5546 if self.read_only(cx) {
5547 return Some(false);
5548 }
5549 let provider = self.edit_prediction_provider()?;
5550 if !provider.is_enabled(&buffer, buffer_position, cx) {
5551 return Some(false);
5552 }
5553 let buffer = buffer.read(cx);
5554 let Some(file) = buffer.file() else {
5555 return Some(true);
5556 };
5557 let settings = all_language_settings(Some(file), cx);
5558 Some(settings.edit_predictions_enabled_for_file(file, cx))
5559 })
5560 .unwrap_or(false)
5561 }
5562
5563 fn cycle_inline_completion(
5564 &mut self,
5565 direction: Direction,
5566 window: &mut Window,
5567 cx: &mut Context<Self>,
5568 ) -> Option<()> {
5569 let provider = self.edit_prediction_provider()?;
5570 let cursor = self.selections.newest_anchor().head();
5571 let (buffer, cursor_buffer_position) =
5572 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5573 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5574 return None;
5575 }
5576
5577 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5578 self.update_visible_inline_completion(window, cx);
5579
5580 Some(())
5581 }
5582
5583 pub fn show_inline_completion(
5584 &mut self,
5585 _: &ShowEditPrediction,
5586 window: &mut Window,
5587 cx: &mut Context<Self>,
5588 ) {
5589 if !self.has_active_inline_completion() {
5590 self.refresh_inline_completion(false, true, window, cx);
5591 return;
5592 }
5593
5594 self.update_visible_inline_completion(window, cx);
5595 }
5596
5597 pub fn display_cursor_names(
5598 &mut self,
5599 _: &DisplayCursorNames,
5600 window: &mut Window,
5601 cx: &mut Context<Self>,
5602 ) {
5603 self.show_cursor_names(window, cx);
5604 }
5605
5606 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5607 self.show_cursor_names = true;
5608 cx.notify();
5609 cx.spawn_in(window, async move |this, cx| {
5610 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5611 this.update(cx, |this, cx| {
5612 this.show_cursor_names = false;
5613 cx.notify()
5614 })
5615 .ok()
5616 })
5617 .detach();
5618 }
5619
5620 pub fn next_edit_prediction(
5621 &mut self,
5622 _: &NextEditPrediction,
5623 window: &mut Window,
5624 cx: &mut Context<Self>,
5625 ) {
5626 if self.has_active_inline_completion() {
5627 self.cycle_inline_completion(Direction::Next, window, cx);
5628 } else {
5629 let is_copilot_disabled = self
5630 .refresh_inline_completion(false, true, window, cx)
5631 .is_none();
5632 if is_copilot_disabled {
5633 cx.propagate();
5634 }
5635 }
5636 }
5637
5638 pub fn previous_edit_prediction(
5639 &mut self,
5640 _: &PreviousEditPrediction,
5641 window: &mut Window,
5642 cx: &mut Context<Self>,
5643 ) {
5644 if self.has_active_inline_completion() {
5645 self.cycle_inline_completion(Direction::Prev, window, cx);
5646 } else {
5647 let is_copilot_disabled = self
5648 .refresh_inline_completion(false, true, window, cx)
5649 .is_none();
5650 if is_copilot_disabled {
5651 cx.propagate();
5652 }
5653 }
5654 }
5655
5656 pub fn accept_edit_prediction(
5657 &mut self,
5658 _: &AcceptEditPrediction,
5659 window: &mut Window,
5660 cx: &mut Context<Self>,
5661 ) {
5662 if self.show_edit_predictions_in_menu() {
5663 self.hide_context_menu(window, cx);
5664 }
5665
5666 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5667 return;
5668 };
5669
5670 self.report_inline_completion_event(
5671 active_inline_completion.completion_id.clone(),
5672 true,
5673 cx,
5674 );
5675
5676 match &active_inline_completion.completion {
5677 InlineCompletion::Move { target, .. } => {
5678 let target = *target;
5679
5680 if let Some(position_map) = &self.last_position_map {
5681 if position_map
5682 .visible_row_range
5683 .contains(&target.to_display_point(&position_map.snapshot).row())
5684 || !self.edit_prediction_requires_modifier()
5685 {
5686 self.unfold_ranges(&[target..target], true, false, cx);
5687 // Note that this is also done in vim's handler of the Tab action.
5688 self.change_selections(
5689 Some(Autoscroll::newest()),
5690 window,
5691 cx,
5692 |selections| {
5693 selections.select_anchor_ranges([target..target]);
5694 },
5695 );
5696 self.clear_row_highlights::<EditPredictionPreview>();
5697
5698 self.edit_prediction_preview
5699 .set_previous_scroll_position(None);
5700 } else {
5701 self.edit_prediction_preview
5702 .set_previous_scroll_position(Some(
5703 position_map.snapshot.scroll_anchor,
5704 ));
5705
5706 self.highlight_rows::<EditPredictionPreview>(
5707 target..target,
5708 cx.theme().colors().editor_highlighted_line_background,
5709 true,
5710 cx,
5711 );
5712 self.request_autoscroll(Autoscroll::fit(), cx);
5713 }
5714 }
5715 }
5716 InlineCompletion::Edit { edits, .. } => {
5717 if let Some(provider) = self.edit_prediction_provider() {
5718 provider.accept(cx);
5719 }
5720
5721 let snapshot = self.buffer.read(cx).snapshot(cx);
5722 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5723
5724 self.buffer.update(cx, |buffer, cx| {
5725 buffer.edit(edits.iter().cloned(), None, cx)
5726 });
5727
5728 self.change_selections(None, window, cx, |s| {
5729 s.select_anchor_ranges([last_edit_end..last_edit_end])
5730 });
5731
5732 self.update_visible_inline_completion(window, cx);
5733 if self.active_inline_completion.is_none() {
5734 self.refresh_inline_completion(true, true, window, cx);
5735 }
5736
5737 cx.notify();
5738 }
5739 }
5740
5741 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5742 }
5743
5744 pub fn accept_partial_inline_completion(
5745 &mut self,
5746 _: &AcceptPartialEditPrediction,
5747 window: &mut Window,
5748 cx: &mut Context<Self>,
5749 ) {
5750 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5751 return;
5752 };
5753 if self.selections.count() != 1 {
5754 return;
5755 }
5756
5757 self.report_inline_completion_event(
5758 active_inline_completion.completion_id.clone(),
5759 true,
5760 cx,
5761 );
5762
5763 match &active_inline_completion.completion {
5764 InlineCompletion::Move { target, .. } => {
5765 let target = *target;
5766 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5767 selections.select_anchor_ranges([target..target]);
5768 });
5769 }
5770 InlineCompletion::Edit { edits, .. } => {
5771 // Find an insertion that starts at the cursor position.
5772 let snapshot = self.buffer.read(cx).snapshot(cx);
5773 let cursor_offset = self.selections.newest::<usize>(cx).head();
5774 let insertion = edits.iter().find_map(|(range, text)| {
5775 let range = range.to_offset(&snapshot);
5776 if range.is_empty() && range.start == cursor_offset {
5777 Some(text)
5778 } else {
5779 None
5780 }
5781 });
5782
5783 if let Some(text) = insertion {
5784 let mut partial_completion = text
5785 .chars()
5786 .by_ref()
5787 .take_while(|c| c.is_alphabetic())
5788 .collect::<String>();
5789 if partial_completion.is_empty() {
5790 partial_completion = text
5791 .chars()
5792 .by_ref()
5793 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5794 .collect::<String>();
5795 }
5796
5797 cx.emit(EditorEvent::InputHandled {
5798 utf16_range_to_replace: None,
5799 text: partial_completion.clone().into(),
5800 });
5801
5802 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5803
5804 self.refresh_inline_completion(true, true, window, cx);
5805 cx.notify();
5806 } else {
5807 self.accept_edit_prediction(&Default::default(), window, cx);
5808 }
5809 }
5810 }
5811 }
5812
5813 fn discard_inline_completion(
5814 &mut self,
5815 should_report_inline_completion_event: bool,
5816 cx: &mut Context<Self>,
5817 ) -> bool {
5818 if should_report_inline_completion_event {
5819 let completion_id = self
5820 .active_inline_completion
5821 .as_ref()
5822 .and_then(|active_completion| active_completion.completion_id.clone());
5823
5824 self.report_inline_completion_event(completion_id, false, cx);
5825 }
5826
5827 if let Some(provider) = self.edit_prediction_provider() {
5828 provider.discard(cx);
5829 }
5830
5831 self.take_active_inline_completion(cx)
5832 }
5833
5834 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5835 let Some(provider) = self.edit_prediction_provider() else {
5836 return;
5837 };
5838
5839 let Some((_, buffer, _)) = self
5840 .buffer
5841 .read(cx)
5842 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5843 else {
5844 return;
5845 };
5846
5847 let extension = buffer
5848 .read(cx)
5849 .file()
5850 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5851
5852 let event_type = match accepted {
5853 true => "Edit Prediction Accepted",
5854 false => "Edit Prediction Discarded",
5855 };
5856 telemetry::event!(
5857 event_type,
5858 provider = provider.name(),
5859 prediction_id = id,
5860 suggestion_accepted = accepted,
5861 file_extension = extension,
5862 );
5863 }
5864
5865 pub fn has_active_inline_completion(&self) -> bool {
5866 self.active_inline_completion.is_some()
5867 }
5868
5869 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5870 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5871 return false;
5872 };
5873
5874 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5875 self.clear_highlights::<InlineCompletionHighlight>(cx);
5876 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5877 true
5878 }
5879
5880 /// Returns true when we're displaying the edit prediction popover below the cursor
5881 /// like we are not previewing and the LSP autocomplete menu is visible
5882 /// or we are in `when_holding_modifier` mode.
5883 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5884 if self.edit_prediction_preview_is_active()
5885 || !self.show_edit_predictions_in_menu()
5886 || !self.edit_predictions_enabled()
5887 {
5888 return false;
5889 }
5890
5891 if self.has_visible_completions_menu() {
5892 return true;
5893 }
5894
5895 has_completion && self.edit_prediction_requires_modifier()
5896 }
5897
5898 fn handle_modifiers_changed(
5899 &mut self,
5900 modifiers: Modifiers,
5901 position_map: &PositionMap,
5902 window: &mut Window,
5903 cx: &mut Context<Self>,
5904 ) {
5905 if self.show_edit_predictions_in_menu() {
5906 self.update_edit_prediction_preview(&modifiers, window, cx);
5907 }
5908
5909 self.update_selection_mode(&modifiers, position_map, window, cx);
5910
5911 let mouse_position = window.mouse_position();
5912 if !position_map.text_hitbox.is_hovered(window) {
5913 return;
5914 }
5915
5916 self.update_hovered_link(
5917 position_map.point_for_position(mouse_position),
5918 &position_map.snapshot,
5919 modifiers,
5920 window,
5921 cx,
5922 )
5923 }
5924
5925 fn update_selection_mode(
5926 &mut self,
5927 modifiers: &Modifiers,
5928 position_map: &PositionMap,
5929 window: &mut Window,
5930 cx: &mut Context<Self>,
5931 ) {
5932 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5933 return;
5934 }
5935
5936 let mouse_position = window.mouse_position();
5937 let point_for_position = position_map.point_for_position(mouse_position);
5938 let position = point_for_position.previous_valid;
5939
5940 self.select(
5941 SelectPhase::BeginColumnar {
5942 position,
5943 reset: false,
5944 goal_column: point_for_position.exact_unclipped.column(),
5945 },
5946 window,
5947 cx,
5948 );
5949 }
5950
5951 fn update_edit_prediction_preview(
5952 &mut self,
5953 modifiers: &Modifiers,
5954 window: &mut Window,
5955 cx: &mut Context<Self>,
5956 ) {
5957 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5958 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5959 return;
5960 };
5961
5962 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5963 if matches!(
5964 self.edit_prediction_preview,
5965 EditPredictionPreview::Inactive { .. }
5966 ) {
5967 self.edit_prediction_preview = EditPredictionPreview::Active {
5968 previous_scroll_position: None,
5969 since: Instant::now(),
5970 };
5971
5972 self.update_visible_inline_completion(window, cx);
5973 cx.notify();
5974 }
5975 } else if let EditPredictionPreview::Active {
5976 previous_scroll_position,
5977 since,
5978 } = self.edit_prediction_preview
5979 {
5980 if let (Some(previous_scroll_position), Some(position_map)) =
5981 (previous_scroll_position, self.last_position_map.as_ref())
5982 {
5983 self.set_scroll_position(
5984 previous_scroll_position
5985 .scroll_position(&position_map.snapshot.display_snapshot),
5986 window,
5987 cx,
5988 );
5989 }
5990
5991 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5992 released_too_fast: since.elapsed() < Duration::from_millis(200),
5993 };
5994 self.clear_row_highlights::<EditPredictionPreview>();
5995 self.update_visible_inline_completion(window, cx);
5996 cx.notify();
5997 }
5998 }
5999
6000 fn update_visible_inline_completion(
6001 &mut self,
6002 _window: &mut Window,
6003 cx: &mut Context<Self>,
6004 ) -> Option<()> {
6005 let selection = self.selections.newest_anchor();
6006 let cursor = selection.head();
6007 let multibuffer = self.buffer.read(cx).snapshot(cx);
6008 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6009 let excerpt_id = cursor.excerpt_id;
6010
6011 let show_in_menu = self.show_edit_predictions_in_menu();
6012 let completions_menu_has_precedence = !show_in_menu
6013 && (self.context_menu.borrow().is_some()
6014 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6015
6016 if completions_menu_has_precedence
6017 || !offset_selection.is_empty()
6018 || self
6019 .active_inline_completion
6020 .as_ref()
6021 .map_or(false, |completion| {
6022 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6023 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6024 !invalidation_range.contains(&offset_selection.head())
6025 })
6026 {
6027 self.discard_inline_completion(false, cx);
6028 return None;
6029 }
6030
6031 self.take_active_inline_completion(cx);
6032 let Some(provider) = self.edit_prediction_provider() else {
6033 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6034 return None;
6035 };
6036
6037 let (buffer, cursor_buffer_position) =
6038 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6039
6040 self.edit_prediction_settings =
6041 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6042
6043 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6044
6045 if self.edit_prediction_indent_conflict {
6046 let cursor_point = cursor.to_point(&multibuffer);
6047
6048 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6049
6050 if let Some((_, indent)) = indents.iter().next() {
6051 if indent.len == cursor_point.column {
6052 self.edit_prediction_indent_conflict = false;
6053 }
6054 }
6055 }
6056
6057 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6058 let edits = inline_completion
6059 .edits
6060 .into_iter()
6061 .flat_map(|(range, new_text)| {
6062 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6063 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6064 Some((start..end, new_text))
6065 })
6066 .collect::<Vec<_>>();
6067 if edits.is_empty() {
6068 return None;
6069 }
6070
6071 let first_edit_start = edits.first().unwrap().0.start;
6072 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6073 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6074
6075 let last_edit_end = edits.last().unwrap().0.end;
6076 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6077 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6078
6079 let cursor_row = cursor.to_point(&multibuffer).row;
6080
6081 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6082
6083 let mut inlay_ids = Vec::new();
6084 let invalidation_row_range;
6085 let move_invalidation_row_range = if cursor_row < edit_start_row {
6086 Some(cursor_row..edit_end_row)
6087 } else if cursor_row > edit_end_row {
6088 Some(edit_start_row..cursor_row)
6089 } else {
6090 None
6091 };
6092 let is_move =
6093 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6094 let completion = if is_move {
6095 invalidation_row_range =
6096 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6097 let target = first_edit_start;
6098 InlineCompletion::Move { target, snapshot }
6099 } else {
6100 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6101 && !self.inline_completions_hidden_for_vim_mode;
6102
6103 if show_completions_in_buffer {
6104 if edits
6105 .iter()
6106 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6107 {
6108 let mut inlays = Vec::new();
6109 for (range, new_text) in &edits {
6110 let inlay = Inlay::inline_completion(
6111 post_inc(&mut self.next_inlay_id),
6112 range.start,
6113 new_text.as_str(),
6114 );
6115 inlay_ids.push(inlay.id);
6116 inlays.push(inlay);
6117 }
6118
6119 self.splice_inlays(&[], inlays, cx);
6120 } else {
6121 let background_color = cx.theme().status().deleted_background;
6122 self.highlight_text::<InlineCompletionHighlight>(
6123 edits.iter().map(|(range, _)| range.clone()).collect(),
6124 HighlightStyle {
6125 background_color: Some(background_color),
6126 ..Default::default()
6127 },
6128 cx,
6129 );
6130 }
6131 }
6132
6133 invalidation_row_range = edit_start_row..edit_end_row;
6134
6135 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6136 if provider.show_tab_accept_marker() {
6137 EditDisplayMode::TabAccept
6138 } else {
6139 EditDisplayMode::Inline
6140 }
6141 } else {
6142 EditDisplayMode::DiffPopover
6143 };
6144
6145 InlineCompletion::Edit {
6146 edits,
6147 edit_preview: inline_completion.edit_preview,
6148 display_mode,
6149 snapshot,
6150 }
6151 };
6152
6153 let invalidation_range = multibuffer
6154 .anchor_before(Point::new(invalidation_row_range.start, 0))
6155 ..multibuffer.anchor_after(Point::new(
6156 invalidation_row_range.end,
6157 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6158 ));
6159
6160 self.stale_inline_completion_in_menu = None;
6161 self.active_inline_completion = Some(InlineCompletionState {
6162 inlay_ids,
6163 completion,
6164 completion_id: inline_completion.id,
6165 invalidation_range,
6166 });
6167
6168 cx.notify();
6169
6170 Some(())
6171 }
6172
6173 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6174 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6175 }
6176
6177 fn render_code_actions_indicator(
6178 &self,
6179 _style: &EditorStyle,
6180 row: DisplayRow,
6181 is_active: bool,
6182 breakpoint: Option<&(Anchor, Breakpoint)>,
6183 cx: &mut Context<Self>,
6184 ) -> Option<IconButton> {
6185 let color = Color::Muted;
6186 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6187 let show_tooltip = !self.context_menu_visible();
6188
6189 if self.available_code_actions.is_some() {
6190 Some(
6191 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6192 .shape(ui::IconButtonShape::Square)
6193 .icon_size(IconSize::XSmall)
6194 .icon_color(color)
6195 .toggle_state(is_active)
6196 .when(show_tooltip, |this| {
6197 this.tooltip({
6198 let focus_handle = self.focus_handle.clone();
6199 move |window, cx| {
6200 Tooltip::for_action_in(
6201 "Toggle Code Actions",
6202 &ToggleCodeActions {
6203 deployed_from_indicator: None,
6204 },
6205 &focus_handle,
6206 window,
6207 cx,
6208 )
6209 }
6210 })
6211 })
6212 .on_click(cx.listener(move |editor, _e, window, cx| {
6213 window.focus(&editor.focus_handle(cx));
6214 editor.toggle_code_actions(
6215 &ToggleCodeActions {
6216 deployed_from_indicator: Some(row),
6217 },
6218 window,
6219 cx,
6220 );
6221 }))
6222 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6223 editor.set_breakpoint_context_menu(
6224 row,
6225 position,
6226 event.down.position,
6227 window,
6228 cx,
6229 );
6230 })),
6231 )
6232 } else {
6233 None
6234 }
6235 }
6236
6237 fn clear_tasks(&mut self) {
6238 self.tasks.clear()
6239 }
6240
6241 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6242 if self.tasks.insert(key, value).is_some() {
6243 // This case should hopefully be rare, but just in case...
6244 log::error!(
6245 "multiple different run targets found on a single line, only the last target will be rendered"
6246 )
6247 }
6248 }
6249
6250 /// Get all display points of breakpoints that will be rendered within editor
6251 ///
6252 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6253 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6254 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6255 fn active_breakpoints(
6256 &self,
6257 range: Range<DisplayRow>,
6258 window: &mut Window,
6259 cx: &mut Context<Self>,
6260 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6261 let mut breakpoint_display_points = HashMap::default();
6262
6263 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6264 return breakpoint_display_points;
6265 };
6266
6267 let snapshot = self.snapshot(window, cx);
6268
6269 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6270 let Some(project) = self.project.as_ref() else {
6271 return breakpoint_display_points;
6272 };
6273
6274 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6275 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6276
6277 for (buffer_snapshot, range, excerpt_id) in
6278 multi_buffer_snapshot.range_to_buffer_ranges(range)
6279 {
6280 let Some(buffer) = project.read_with(cx, |this, cx| {
6281 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6282 }) else {
6283 continue;
6284 };
6285 let breakpoints = breakpoint_store.read(cx).breakpoints(
6286 &buffer,
6287 Some(
6288 buffer_snapshot.anchor_before(range.start)
6289 ..buffer_snapshot.anchor_after(range.end),
6290 ),
6291 buffer_snapshot,
6292 cx,
6293 );
6294 for (anchor, breakpoint) in breakpoints {
6295 let multi_buffer_anchor =
6296 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6297 let position = multi_buffer_anchor
6298 .to_point(&multi_buffer_snapshot)
6299 .to_display_point(&snapshot);
6300
6301 breakpoint_display_points
6302 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6303 }
6304 }
6305
6306 breakpoint_display_points
6307 }
6308
6309 fn breakpoint_context_menu(
6310 &self,
6311 anchor: Anchor,
6312 window: &mut Window,
6313 cx: &mut Context<Self>,
6314 ) -> Entity<ui::ContextMenu> {
6315 let weak_editor = cx.weak_entity();
6316 let focus_handle = self.focus_handle(cx);
6317
6318 let row = self
6319 .buffer
6320 .read(cx)
6321 .snapshot(cx)
6322 .summary_for_anchor::<Point>(&anchor)
6323 .row;
6324
6325 let breakpoint = self
6326 .breakpoint_at_row(row, window, cx)
6327 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6328
6329 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6330 "Edit Log Breakpoint"
6331 } else {
6332 "Set Log Breakpoint"
6333 };
6334
6335 let condition_breakpoint_msg = if breakpoint
6336 .as_ref()
6337 .is_some_and(|bp| bp.1.condition.is_some())
6338 {
6339 "Edit Condition Breakpoint"
6340 } else {
6341 "Set Condition Breakpoint"
6342 };
6343
6344 let hit_condition_breakpoint_msg = if breakpoint
6345 .as_ref()
6346 .is_some_and(|bp| bp.1.hit_condition.is_some())
6347 {
6348 "Edit Hit Condition Breakpoint"
6349 } else {
6350 "Set Hit Condition Breakpoint"
6351 };
6352
6353 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6354 "Unset Breakpoint"
6355 } else {
6356 "Set Breakpoint"
6357 };
6358
6359 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6360 BreakpointState::Enabled => Some("Disable"),
6361 BreakpointState::Disabled => Some("Enable"),
6362 });
6363
6364 let (anchor, breakpoint) =
6365 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6366
6367 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6368 menu.on_blur_subscription(Subscription::new(|| {}))
6369 .context(focus_handle)
6370 .when_some(toggle_state_msg, |this, msg| {
6371 this.entry(msg, None, {
6372 let weak_editor = weak_editor.clone();
6373 let breakpoint = breakpoint.clone();
6374 move |_window, cx| {
6375 weak_editor
6376 .update(cx, |this, cx| {
6377 this.edit_breakpoint_at_anchor(
6378 anchor,
6379 breakpoint.as_ref().clone(),
6380 BreakpointEditAction::InvertState,
6381 cx,
6382 );
6383 })
6384 .log_err();
6385 }
6386 })
6387 })
6388 .entry(set_breakpoint_msg, None, {
6389 let weak_editor = weak_editor.clone();
6390 let breakpoint = breakpoint.clone();
6391 move |_window, cx| {
6392 weak_editor
6393 .update(cx, |this, cx| {
6394 this.edit_breakpoint_at_anchor(
6395 anchor,
6396 breakpoint.as_ref().clone(),
6397 BreakpointEditAction::Toggle,
6398 cx,
6399 );
6400 })
6401 .log_err();
6402 }
6403 })
6404 .entry(log_breakpoint_msg, None, {
6405 let breakpoint = breakpoint.clone();
6406 let weak_editor = weak_editor.clone();
6407 move |window, cx| {
6408 weak_editor
6409 .update(cx, |this, cx| {
6410 this.add_edit_breakpoint_block(
6411 anchor,
6412 breakpoint.as_ref(),
6413 BreakpointPromptEditAction::Log,
6414 window,
6415 cx,
6416 );
6417 })
6418 .log_err();
6419 }
6420 })
6421 .entry(condition_breakpoint_msg, None, {
6422 let breakpoint = breakpoint.clone();
6423 let weak_editor = weak_editor.clone();
6424 move |window, cx| {
6425 weak_editor
6426 .update(cx, |this, cx| {
6427 this.add_edit_breakpoint_block(
6428 anchor,
6429 breakpoint.as_ref(),
6430 BreakpointPromptEditAction::Condition,
6431 window,
6432 cx,
6433 );
6434 })
6435 .log_err();
6436 }
6437 })
6438 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6439 weak_editor
6440 .update(cx, |this, cx| {
6441 this.add_edit_breakpoint_block(
6442 anchor,
6443 breakpoint.as_ref(),
6444 BreakpointPromptEditAction::HitCondition,
6445 window,
6446 cx,
6447 );
6448 })
6449 .log_err();
6450 })
6451 })
6452 }
6453
6454 fn render_breakpoint(
6455 &self,
6456 position: Anchor,
6457 row: DisplayRow,
6458 breakpoint: &Breakpoint,
6459 cx: &mut Context<Self>,
6460 ) -> IconButton {
6461 let (color, icon) = {
6462 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6463 (false, false) => ui::IconName::DebugBreakpoint,
6464 (true, false) => ui::IconName::DebugLogBreakpoint,
6465 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6466 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6467 };
6468
6469 let color = if self
6470 .gutter_breakpoint_indicator
6471 .0
6472 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6473 {
6474 Color::Hint
6475 } else {
6476 Color::Debugger
6477 };
6478
6479 (color, icon)
6480 };
6481
6482 let breakpoint = Arc::from(breakpoint.clone());
6483
6484 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6485 .icon_size(IconSize::XSmall)
6486 .size(ui::ButtonSize::None)
6487 .icon_color(color)
6488 .style(ButtonStyle::Transparent)
6489 .on_click(cx.listener({
6490 let breakpoint = breakpoint.clone();
6491
6492 move |editor, event: &ClickEvent, window, cx| {
6493 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6494 BreakpointEditAction::InvertState
6495 } else {
6496 BreakpointEditAction::Toggle
6497 };
6498
6499 window.focus(&editor.focus_handle(cx));
6500 editor.edit_breakpoint_at_anchor(
6501 position,
6502 breakpoint.as_ref().clone(),
6503 edit_action,
6504 cx,
6505 );
6506 }
6507 }))
6508 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6509 editor.set_breakpoint_context_menu(
6510 row,
6511 Some(position),
6512 event.down.position,
6513 window,
6514 cx,
6515 );
6516 }))
6517 }
6518
6519 fn build_tasks_context(
6520 project: &Entity<Project>,
6521 buffer: &Entity<Buffer>,
6522 buffer_row: u32,
6523 tasks: &Arc<RunnableTasks>,
6524 cx: &mut Context<Self>,
6525 ) -> Task<Option<task::TaskContext>> {
6526 let position = Point::new(buffer_row, tasks.column);
6527 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6528 let location = Location {
6529 buffer: buffer.clone(),
6530 range: range_start..range_start,
6531 };
6532 // Fill in the environmental variables from the tree-sitter captures
6533 let mut captured_task_variables = TaskVariables::default();
6534 for (capture_name, value) in tasks.extra_variables.clone() {
6535 captured_task_variables.insert(
6536 task::VariableName::Custom(capture_name.into()),
6537 value.clone(),
6538 );
6539 }
6540 project.update(cx, |project, cx| {
6541 project.task_store().update(cx, |task_store, cx| {
6542 task_store.task_context_for_location(captured_task_variables, location, cx)
6543 })
6544 })
6545 }
6546
6547 pub fn spawn_nearest_task(
6548 &mut self,
6549 action: &SpawnNearestTask,
6550 window: &mut Window,
6551 cx: &mut Context<Self>,
6552 ) {
6553 let Some((workspace, _)) = self.workspace.clone() else {
6554 return;
6555 };
6556 let Some(project) = self.project.clone() else {
6557 return;
6558 };
6559
6560 // Try to find a closest, enclosing node using tree-sitter that has a
6561 // task
6562 let Some((buffer, buffer_row, tasks)) = self
6563 .find_enclosing_node_task(cx)
6564 // Or find the task that's closest in row-distance.
6565 .or_else(|| self.find_closest_task(cx))
6566 else {
6567 return;
6568 };
6569
6570 let reveal_strategy = action.reveal;
6571 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6572 cx.spawn_in(window, async move |_, cx| {
6573 let context = task_context.await?;
6574 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6575
6576 let resolved = resolved_task.resolved.as_mut()?;
6577 resolved.reveal = reveal_strategy;
6578
6579 workspace
6580 .update(cx, |workspace, cx| {
6581 workspace::tasks::schedule_resolved_task(
6582 workspace,
6583 task_source_kind,
6584 resolved_task,
6585 false,
6586 cx,
6587 );
6588 })
6589 .ok()
6590 })
6591 .detach();
6592 }
6593
6594 fn find_closest_task(
6595 &mut self,
6596 cx: &mut Context<Self>,
6597 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6598 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6599
6600 let ((buffer_id, row), tasks) = self
6601 .tasks
6602 .iter()
6603 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6604
6605 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6606 let tasks = Arc::new(tasks.to_owned());
6607 Some((buffer, *row, tasks))
6608 }
6609
6610 fn find_enclosing_node_task(
6611 &mut self,
6612 cx: &mut Context<Self>,
6613 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6614 let snapshot = self.buffer.read(cx).snapshot(cx);
6615 let offset = self.selections.newest::<usize>(cx).head();
6616 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6617 let buffer_id = excerpt.buffer().remote_id();
6618
6619 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6620 let mut cursor = layer.node().walk();
6621
6622 while cursor.goto_first_child_for_byte(offset).is_some() {
6623 if cursor.node().end_byte() == offset {
6624 cursor.goto_next_sibling();
6625 }
6626 }
6627
6628 // Ascend to the smallest ancestor that contains the range and has a task.
6629 loop {
6630 let node = cursor.node();
6631 let node_range = node.byte_range();
6632 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6633
6634 // Check if this node contains our offset
6635 if node_range.start <= offset && node_range.end >= offset {
6636 // If it contains offset, check for task
6637 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6638 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6639 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6640 }
6641 }
6642
6643 if !cursor.goto_parent() {
6644 break;
6645 }
6646 }
6647 None
6648 }
6649
6650 fn render_run_indicator(
6651 &self,
6652 _style: &EditorStyle,
6653 is_active: bool,
6654 row: DisplayRow,
6655 breakpoint: Option<(Anchor, Breakpoint)>,
6656 cx: &mut Context<Self>,
6657 ) -> IconButton {
6658 let color = Color::Muted;
6659 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6660
6661 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6662 .shape(ui::IconButtonShape::Square)
6663 .icon_size(IconSize::XSmall)
6664 .icon_color(color)
6665 .toggle_state(is_active)
6666 .on_click(cx.listener(move |editor, _e, window, cx| {
6667 window.focus(&editor.focus_handle(cx));
6668 editor.toggle_code_actions(
6669 &ToggleCodeActions {
6670 deployed_from_indicator: Some(row),
6671 },
6672 window,
6673 cx,
6674 );
6675 }))
6676 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6677 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6678 }))
6679 }
6680
6681 pub fn context_menu_visible(&self) -> bool {
6682 !self.edit_prediction_preview_is_active()
6683 && self
6684 .context_menu
6685 .borrow()
6686 .as_ref()
6687 .map_or(false, |menu| menu.visible())
6688 }
6689
6690 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6691 self.context_menu
6692 .borrow()
6693 .as_ref()
6694 .map(|menu| menu.origin())
6695 }
6696
6697 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6698 self.context_menu_options = Some(options);
6699 }
6700
6701 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6702 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6703
6704 fn render_edit_prediction_popover(
6705 &mut self,
6706 text_bounds: &Bounds<Pixels>,
6707 content_origin: gpui::Point<Pixels>,
6708 editor_snapshot: &EditorSnapshot,
6709 visible_row_range: Range<DisplayRow>,
6710 scroll_top: f32,
6711 scroll_bottom: f32,
6712 line_layouts: &[LineWithInvisibles],
6713 line_height: Pixels,
6714 scroll_pixel_position: gpui::Point<Pixels>,
6715 newest_selection_head: Option<DisplayPoint>,
6716 editor_width: Pixels,
6717 style: &EditorStyle,
6718 window: &mut Window,
6719 cx: &mut App,
6720 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6721 let active_inline_completion = self.active_inline_completion.as_ref()?;
6722
6723 if self.edit_prediction_visible_in_cursor_popover(true) {
6724 return None;
6725 }
6726
6727 match &active_inline_completion.completion {
6728 InlineCompletion::Move { target, .. } => {
6729 let target_display_point = target.to_display_point(editor_snapshot);
6730
6731 if self.edit_prediction_requires_modifier() {
6732 if !self.edit_prediction_preview_is_active() {
6733 return None;
6734 }
6735
6736 self.render_edit_prediction_modifier_jump_popover(
6737 text_bounds,
6738 content_origin,
6739 visible_row_range,
6740 line_layouts,
6741 line_height,
6742 scroll_pixel_position,
6743 newest_selection_head,
6744 target_display_point,
6745 window,
6746 cx,
6747 )
6748 } else {
6749 self.render_edit_prediction_eager_jump_popover(
6750 text_bounds,
6751 content_origin,
6752 editor_snapshot,
6753 visible_row_range,
6754 scroll_top,
6755 scroll_bottom,
6756 line_height,
6757 scroll_pixel_position,
6758 target_display_point,
6759 editor_width,
6760 window,
6761 cx,
6762 )
6763 }
6764 }
6765 InlineCompletion::Edit {
6766 display_mode: EditDisplayMode::Inline,
6767 ..
6768 } => None,
6769 InlineCompletion::Edit {
6770 display_mode: EditDisplayMode::TabAccept,
6771 edits,
6772 ..
6773 } => {
6774 let range = &edits.first()?.0;
6775 let target_display_point = range.end.to_display_point(editor_snapshot);
6776
6777 self.render_edit_prediction_end_of_line_popover(
6778 "Accept",
6779 editor_snapshot,
6780 visible_row_range,
6781 target_display_point,
6782 line_height,
6783 scroll_pixel_position,
6784 content_origin,
6785 editor_width,
6786 window,
6787 cx,
6788 )
6789 }
6790 InlineCompletion::Edit {
6791 edits,
6792 edit_preview,
6793 display_mode: EditDisplayMode::DiffPopover,
6794 snapshot,
6795 } => self.render_edit_prediction_diff_popover(
6796 text_bounds,
6797 content_origin,
6798 editor_snapshot,
6799 visible_row_range,
6800 line_layouts,
6801 line_height,
6802 scroll_pixel_position,
6803 newest_selection_head,
6804 editor_width,
6805 style,
6806 edits,
6807 edit_preview,
6808 snapshot,
6809 window,
6810 cx,
6811 ),
6812 }
6813 }
6814
6815 fn render_edit_prediction_modifier_jump_popover(
6816 &mut self,
6817 text_bounds: &Bounds<Pixels>,
6818 content_origin: gpui::Point<Pixels>,
6819 visible_row_range: Range<DisplayRow>,
6820 line_layouts: &[LineWithInvisibles],
6821 line_height: Pixels,
6822 scroll_pixel_position: gpui::Point<Pixels>,
6823 newest_selection_head: Option<DisplayPoint>,
6824 target_display_point: DisplayPoint,
6825 window: &mut Window,
6826 cx: &mut App,
6827 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6828 let scrolled_content_origin =
6829 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6830
6831 const SCROLL_PADDING_Y: Pixels = px(12.);
6832
6833 if target_display_point.row() < visible_row_range.start {
6834 return self.render_edit_prediction_scroll_popover(
6835 |_| SCROLL_PADDING_Y,
6836 IconName::ArrowUp,
6837 visible_row_range,
6838 line_layouts,
6839 newest_selection_head,
6840 scrolled_content_origin,
6841 window,
6842 cx,
6843 );
6844 } else if target_display_point.row() >= visible_row_range.end {
6845 return self.render_edit_prediction_scroll_popover(
6846 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6847 IconName::ArrowDown,
6848 visible_row_range,
6849 line_layouts,
6850 newest_selection_head,
6851 scrolled_content_origin,
6852 window,
6853 cx,
6854 );
6855 }
6856
6857 const POLE_WIDTH: Pixels = px(2.);
6858
6859 let line_layout =
6860 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6861 let target_column = target_display_point.column() as usize;
6862
6863 let target_x = line_layout.x_for_index(target_column);
6864 let target_y =
6865 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6866
6867 let flag_on_right = target_x < text_bounds.size.width / 2.;
6868
6869 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6870 border_color.l += 0.001;
6871
6872 let mut element = v_flex()
6873 .items_end()
6874 .when(flag_on_right, |el| el.items_start())
6875 .child(if flag_on_right {
6876 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6877 .rounded_bl(px(0.))
6878 .rounded_tl(px(0.))
6879 .border_l_2()
6880 .border_color(border_color)
6881 } else {
6882 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6883 .rounded_br(px(0.))
6884 .rounded_tr(px(0.))
6885 .border_r_2()
6886 .border_color(border_color)
6887 })
6888 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6889 .into_any();
6890
6891 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6892
6893 let mut origin = scrolled_content_origin + point(target_x, target_y)
6894 - point(
6895 if flag_on_right {
6896 POLE_WIDTH
6897 } else {
6898 size.width - POLE_WIDTH
6899 },
6900 size.height - line_height,
6901 );
6902
6903 origin.x = origin.x.max(content_origin.x);
6904
6905 element.prepaint_at(origin, window, cx);
6906
6907 Some((element, origin))
6908 }
6909
6910 fn render_edit_prediction_scroll_popover(
6911 &mut self,
6912 to_y: impl Fn(Size<Pixels>) -> Pixels,
6913 scroll_icon: IconName,
6914 visible_row_range: Range<DisplayRow>,
6915 line_layouts: &[LineWithInvisibles],
6916 newest_selection_head: Option<DisplayPoint>,
6917 scrolled_content_origin: gpui::Point<Pixels>,
6918 window: &mut Window,
6919 cx: &mut App,
6920 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6921 let mut element = self
6922 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6923 .into_any();
6924
6925 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6926
6927 let cursor = newest_selection_head?;
6928 let cursor_row_layout =
6929 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6930 let cursor_column = cursor.column() as usize;
6931
6932 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6933
6934 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6935
6936 element.prepaint_at(origin, window, cx);
6937 Some((element, origin))
6938 }
6939
6940 fn render_edit_prediction_eager_jump_popover(
6941 &mut self,
6942 text_bounds: &Bounds<Pixels>,
6943 content_origin: gpui::Point<Pixels>,
6944 editor_snapshot: &EditorSnapshot,
6945 visible_row_range: Range<DisplayRow>,
6946 scroll_top: f32,
6947 scroll_bottom: f32,
6948 line_height: Pixels,
6949 scroll_pixel_position: gpui::Point<Pixels>,
6950 target_display_point: DisplayPoint,
6951 editor_width: Pixels,
6952 window: &mut Window,
6953 cx: &mut App,
6954 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6955 if target_display_point.row().as_f32() < scroll_top {
6956 let mut element = self
6957 .render_edit_prediction_line_popover(
6958 "Jump to Edit",
6959 Some(IconName::ArrowUp),
6960 window,
6961 cx,
6962 )?
6963 .into_any();
6964
6965 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6966 let offset = point(
6967 (text_bounds.size.width - size.width) / 2.,
6968 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6969 );
6970
6971 let origin = text_bounds.origin + offset;
6972 element.prepaint_at(origin, window, cx);
6973 Some((element, origin))
6974 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6975 let mut element = self
6976 .render_edit_prediction_line_popover(
6977 "Jump to Edit",
6978 Some(IconName::ArrowDown),
6979 window,
6980 cx,
6981 )?
6982 .into_any();
6983
6984 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6985 let offset = point(
6986 (text_bounds.size.width - size.width) / 2.,
6987 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6988 );
6989
6990 let origin = text_bounds.origin + offset;
6991 element.prepaint_at(origin, window, cx);
6992 Some((element, origin))
6993 } else {
6994 self.render_edit_prediction_end_of_line_popover(
6995 "Jump to Edit",
6996 editor_snapshot,
6997 visible_row_range,
6998 target_display_point,
6999 line_height,
7000 scroll_pixel_position,
7001 content_origin,
7002 editor_width,
7003 window,
7004 cx,
7005 )
7006 }
7007 }
7008
7009 fn render_edit_prediction_end_of_line_popover(
7010 self: &mut Editor,
7011 label: &'static str,
7012 editor_snapshot: &EditorSnapshot,
7013 visible_row_range: Range<DisplayRow>,
7014 target_display_point: DisplayPoint,
7015 line_height: Pixels,
7016 scroll_pixel_position: gpui::Point<Pixels>,
7017 content_origin: gpui::Point<Pixels>,
7018 editor_width: Pixels,
7019 window: &mut Window,
7020 cx: &mut App,
7021 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7022 let target_line_end = DisplayPoint::new(
7023 target_display_point.row(),
7024 editor_snapshot.line_len(target_display_point.row()),
7025 );
7026
7027 let mut element = self
7028 .render_edit_prediction_line_popover(label, None, window, cx)?
7029 .into_any();
7030
7031 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7032
7033 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7034
7035 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7036 let mut origin = start_point
7037 + line_origin
7038 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7039 origin.x = origin.x.max(content_origin.x);
7040
7041 let max_x = content_origin.x + editor_width - size.width;
7042
7043 if origin.x > max_x {
7044 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7045
7046 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7047 origin.y += offset;
7048 IconName::ArrowUp
7049 } else {
7050 origin.y -= offset;
7051 IconName::ArrowDown
7052 };
7053
7054 element = self
7055 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7056 .into_any();
7057
7058 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7059
7060 origin.x = content_origin.x + editor_width - size.width - px(2.);
7061 }
7062
7063 element.prepaint_at(origin, window, cx);
7064 Some((element, origin))
7065 }
7066
7067 fn render_edit_prediction_diff_popover(
7068 self: &Editor,
7069 text_bounds: &Bounds<Pixels>,
7070 content_origin: gpui::Point<Pixels>,
7071 editor_snapshot: &EditorSnapshot,
7072 visible_row_range: Range<DisplayRow>,
7073 line_layouts: &[LineWithInvisibles],
7074 line_height: Pixels,
7075 scroll_pixel_position: gpui::Point<Pixels>,
7076 newest_selection_head: Option<DisplayPoint>,
7077 editor_width: Pixels,
7078 style: &EditorStyle,
7079 edits: &Vec<(Range<Anchor>, String)>,
7080 edit_preview: &Option<language::EditPreview>,
7081 snapshot: &language::BufferSnapshot,
7082 window: &mut Window,
7083 cx: &mut App,
7084 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7085 let edit_start = edits
7086 .first()
7087 .unwrap()
7088 .0
7089 .start
7090 .to_display_point(editor_snapshot);
7091 let edit_end = edits
7092 .last()
7093 .unwrap()
7094 .0
7095 .end
7096 .to_display_point(editor_snapshot);
7097
7098 let is_visible = visible_row_range.contains(&edit_start.row())
7099 || visible_row_range.contains(&edit_end.row());
7100 if !is_visible {
7101 return None;
7102 }
7103
7104 let highlighted_edits =
7105 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7106
7107 let styled_text = highlighted_edits.to_styled_text(&style.text);
7108 let line_count = highlighted_edits.text.lines().count();
7109
7110 const BORDER_WIDTH: Pixels = px(1.);
7111
7112 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7113 let has_keybind = keybind.is_some();
7114
7115 let mut element = h_flex()
7116 .items_start()
7117 .child(
7118 h_flex()
7119 .bg(cx.theme().colors().editor_background)
7120 .border(BORDER_WIDTH)
7121 .shadow_sm()
7122 .border_color(cx.theme().colors().border)
7123 .rounded_l_lg()
7124 .when(line_count > 1, |el| el.rounded_br_lg())
7125 .pr_1()
7126 .child(styled_text),
7127 )
7128 .child(
7129 h_flex()
7130 .h(line_height + BORDER_WIDTH * 2.)
7131 .px_1p5()
7132 .gap_1()
7133 // Workaround: For some reason, there's a gap if we don't do this
7134 .ml(-BORDER_WIDTH)
7135 .shadow(smallvec![gpui::BoxShadow {
7136 color: gpui::black().opacity(0.05),
7137 offset: point(px(1.), px(1.)),
7138 blur_radius: px(2.),
7139 spread_radius: px(0.),
7140 }])
7141 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7142 .border(BORDER_WIDTH)
7143 .border_color(cx.theme().colors().border)
7144 .rounded_r_lg()
7145 .id("edit_prediction_diff_popover_keybind")
7146 .when(!has_keybind, |el| {
7147 let status_colors = cx.theme().status();
7148
7149 el.bg(status_colors.error_background)
7150 .border_color(status_colors.error.opacity(0.6))
7151 .child(Icon::new(IconName::Info).color(Color::Error))
7152 .cursor_default()
7153 .hoverable_tooltip(move |_window, cx| {
7154 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7155 })
7156 })
7157 .children(keybind),
7158 )
7159 .into_any();
7160
7161 let longest_row =
7162 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7163 let longest_line_width = if visible_row_range.contains(&longest_row) {
7164 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7165 } else {
7166 layout_line(
7167 longest_row,
7168 editor_snapshot,
7169 style,
7170 editor_width,
7171 |_| false,
7172 window,
7173 cx,
7174 )
7175 .width
7176 };
7177
7178 let viewport_bounds =
7179 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7180 right: -EditorElement::SCROLLBAR_WIDTH,
7181 ..Default::default()
7182 });
7183
7184 let x_after_longest =
7185 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7186 - scroll_pixel_position.x;
7187
7188 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7189
7190 // Fully visible if it can be displayed within the window (allow overlapping other
7191 // panes). However, this is only allowed if the popover starts within text_bounds.
7192 let can_position_to_the_right = x_after_longest < text_bounds.right()
7193 && x_after_longest + element_bounds.width < viewport_bounds.right();
7194
7195 let mut origin = if can_position_to_the_right {
7196 point(
7197 x_after_longest,
7198 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7199 - scroll_pixel_position.y,
7200 )
7201 } else {
7202 let cursor_row = newest_selection_head.map(|head| head.row());
7203 let above_edit = edit_start
7204 .row()
7205 .0
7206 .checked_sub(line_count as u32)
7207 .map(DisplayRow);
7208 let below_edit = Some(edit_end.row() + 1);
7209 let above_cursor =
7210 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7211 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7212
7213 // Place the edit popover adjacent to the edit if there is a location
7214 // available that is onscreen and does not obscure the cursor. Otherwise,
7215 // place it adjacent to the cursor.
7216 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7217 .into_iter()
7218 .flatten()
7219 .find(|&start_row| {
7220 let end_row = start_row + line_count as u32;
7221 visible_row_range.contains(&start_row)
7222 && visible_row_range.contains(&end_row)
7223 && cursor_row.map_or(true, |cursor_row| {
7224 !((start_row..end_row).contains(&cursor_row))
7225 })
7226 })?;
7227
7228 content_origin
7229 + point(
7230 -scroll_pixel_position.x,
7231 row_target.as_f32() * line_height - scroll_pixel_position.y,
7232 )
7233 };
7234
7235 origin.x -= BORDER_WIDTH;
7236
7237 window.defer_draw(element, origin, 1);
7238
7239 // Do not return an element, since it will already be drawn due to defer_draw.
7240 None
7241 }
7242
7243 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7244 px(30.)
7245 }
7246
7247 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7248 if self.read_only(cx) {
7249 cx.theme().players().read_only()
7250 } else {
7251 self.style.as_ref().unwrap().local_player
7252 }
7253 }
7254
7255 fn render_edit_prediction_accept_keybind(
7256 &self,
7257 window: &mut Window,
7258 cx: &App,
7259 ) -> Option<AnyElement> {
7260 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7261 let accept_keystroke = accept_binding.keystroke()?;
7262
7263 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7264
7265 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7266 Color::Accent
7267 } else {
7268 Color::Muted
7269 };
7270
7271 h_flex()
7272 .px_0p5()
7273 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7274 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7275 .text_size(TextSize::XSmall.rems(cx))
7276 .child(h_flex().children(ui::render_modifiers(
7277 &accept_keystroke.modifiers,
7278 PlatformStyle::platform(),
7279 Some(modifiers_color),
7280 Some(IconSize::XSmall.rems().into()),
7281 true,
7282 )))
7283 .when(is_platform_style_mac, |parent| {
7284 parent.child(accept_keystroke.key.clone())
7285 })
7286 .when(!is_platform_style_mac, |parent| {
7287 parent.child(
7288 Key::new(
7289 util::capitalize(&accept_keystroke.key),
7290 Some(Color::Default),
7291 )
7292 .size(Some(IconSize::XSmall.rems().into())),
7293 )
7294 })
7295 .into_any()
7296 .into()
7297 }
7298
7299 fn render_edit_prediction_line_popover(
7300 &self,
7301 label: impl Into<SharedString>,
7302 icon: Option<IconName>,
7303 window: &mut Window,
7304 cx: &App,
7305 ) -> Option<Stateful<Div>> {
7306 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7307
7308 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7309 let has_keybind = keybind.is_some();
7310
7311 let result = h_flex()
7312 .id("ep-line-popover")
7313 .py_0p5()
7314 .pl_1()
7315 .pr(padding_right)
7316 .gap_1()
7317 .rounded_md()
7318 .border_1()
7319 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7320 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7321 .shadow_sm()
7322 .when(!has_keybind, |el| {
7323 let status_colors = cx.theme().status();
7324
7325 el.bg(status_colors.error_background)
7326 .border_color(status_colors.error.opacity(0.6))
7327 .pl_2()
7328 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7329 .cursor_default()
7330 .hoverable_tooltip(move |_window, cx| {
7331 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7332 })
7333 })
7334 .children(keybind)
7335 .child(
7336 Label::new(label)
7337 .size(LabelSize::Small)
7338 .when(!has_keybind, |el| {
7339 el.color(cx.theme().status().error.into()).strikethrough()
7340 }),
7341 )
7342 .when(!has_keybind, |el| {
7343 el.child(
7344 h_flex().ml_1().child(
7345 Icon::new(IconName::Info)
7346 .size(IconSize::Small)
7347 .color(cx.theme().status().error.into()),
7348 ),
7349 )
7350 })
7351 .when_some(icon, |element, icon| {
7352 element.child(
7353 div()
7354 .mt(px(1.5))
7355 .child(Icon::new(icon).size(IconSize::Small)),
7356 )
7357 });
7358
7359 Some(result)
7360 }
7361
7362 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7363 let accent_color = cx.theme().colors().text_accent;
7364 let editor_bg_color = cx.theme().colors().editor_background;
7365 editor_bg_color.blend(accent_color.opacity(0.1))
7366 }
7367
7368 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7369 let accent_color = cx.theme().colors().text_accent;
7370 let editor_bg_color = cx.theme().colors().editor_background;
7371 editor_bg_color.blend(accent_color.opacity(0.6))
7372 }
7373
7374 fn render_edit_prediction_cursor_popover(
7375 &self,
7376 min_width: Pixels,
7377 max_width: Pixels,
7378 cursor_point: Point,
7379 style: &EditorStyle,
7380 accept_keystroke: Option<&gpui::Keystroke>,
7381 _window: &Window,
7382 cx: &mut Context<Editor>,
7383 ) -> Option<AnyElement> {
7384 let provider = self.edit_prediction_provider.as_ref()?;
7385
7386 if provider.provider.needs_terms_acceptance(cx) {
7387 return Some(
7388 h_flex()
7389 .min_w(min_width)
7390 .flex_1()
7391 .px_2()
7392 .py_1()
7393 .gap_3()
7394 .elevation_2(cx)
7395 .hover(|style| style.bg(cx.theme().colors().element_hover))
7396 .id("accept-terms")
7397 .cursor_pointer()
7398 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7399 .on_click(cx.listener(|this, _event, window, cx| {
7400 cx.stop_propagation();
7401 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7402 window.dispatch_action(
7403 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7404 cx,
7405 );
7406 }))
7407 .child(
7408 h_flex()
7409 .flex_1()
7410 .gap_2()
7411 .child(Icon::new(IconName::ZedPredict))
7412 .child(Label::new("Accept Terms of Service"))
7413 .child(div().w_full())
7414 .child(
7415 Icon::new(IconName::ArrowUpRight)
7416 .color(Color::Muted)
7417 .size(IconSize::Small),
7418 )
7419 .into_any_element(),
7420 )
7421 .into_any(),
7422 );
7423 }
7424
7425 let is_refreshing = provider.provider.is_refreshing(cx);
7426
7427 fn pending_completion_container() -> Div {
7428 h_flex()
7429 .h_full()
7430 .flex_1()
7431 .gap_2()
7432 .child(Icon::new(IconName::ZedPredict))
7433 }
7434
7435 let completion = match &self.active_inline_completion {
7436 Some(prediction) => {
7437 if !self.has_visible_completions_menu() {
7438 const RADIUS: Pixels = px(6.);
7439 const BORDER_WIDTH: Pixels = px(1.);
7440
7441 return Some(
7442 h_flex()
7443 .elevation_2(cx)
7444 .border(BORDER_WIDTH)
7445 .border_color(cx.theme().colors().border)
7446 .when(accept_keystroke.is_none(), |el| {
7447 el.border_color(cx.theme().status().error)
7448 })
7449 .rounded(RADIUS)
7450 .rounded_tl(px(0.))
7451 .overflow_hidden()
7452 .child(div().px_1p5().child(match &prediction.completion {
7453 InlineCompletion::Move { target, snapshot } => {
7454 use text::ToPoint as _;
7455 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7456 {
7457 Icon::new(IconName::ZedPredictDown)
7458 } else {
7459 Icon::new(IconName::ZedPredictUp)
7460 }
7461 }
7462 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7463 }))
7464 .child(
7465 h_flex()
7466 .gap_1()
7467 .py_1()
7468 .px_2()
7469 .rounded_r(RADIUS - BORDER_WIDTH)
7470 .border_l_1()
7471 .border_color(cx.theme().colors().border)
7472 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7473 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7474 el.child(
7475 Label::new("Hold")
7476 .size(LabelSize::Small)
7477 .when(accept_keystroke.is_none(), |el| {
7478 el.strikethrough()
7479 })
7480 .line_height_style(LineHeightStyle::UiLabel),
7481 )
7482 })
7483 .id("edit_prediction_cursor_popover_keybind")
7484 .when(accept_keystroke.is_none(), |el| {
7485 let status_colors = cx.theme().status();
7486
7487 el.bg(status_colors.error_background)
7488 .border_color(status_colors.error.opacity(0.6))
7489 .child(Icon::new(IconName::Info).color(Color::Error))
7490 .cursor_default()
7491 .hoverable_tooltip(move |_window, cx| {
7492 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7493 .into()
7494 })
7495 })
7496 .when_some(
7497 accept_keystroke.as_ref(),
7498 |el, accept_keystroke| {
7499 el.child(h_flex().children(ui::render_modifiers(
7500 &accept_keystroke.modifiers,
7501 PlatformStyle::platform(),
7502 Some(Color::Default),
7503 Some(IconSize::XSmall.rems().into()),
7504 false,
7505 )))
7506 },
7507 ),
7508 )
7509 .into_any(),
7510 );
7511 }
7512
7513 self.render_edit_prediction_cursor_popover_preview(
7514 prediction,
7515 cursor_point,
7516 style,
7517 cx,
7518 )?
7519 }
7520
7521 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7522 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7523 stale_completion,
7524 cursor_point,
7525 style,
7526 cx,
7527 )?,
7528
7529 None => {
7530 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7531 }
7532 },
7533
7534 None => pending_completion_container().child(Label::new("No Prediction")),
7535 };
7536
7537 let completion = if is_refreshing {
7538 completion
7539 .with_animation(
7540 "loading-completion",
7541 Animation::new(Duration::from_secs(2))
7542 .repeat()
7543 .with_easing(pulsating_between(0.4, 0.8)),
7544 |label, delta| label.opacity(delta),
7545 )
7546 .into_any_element()
7547 } else {
7548 completion.into_any_element()
7549 };
7550
7551 let has_completion = self.active_inline_completion.is_some();
7552
7553 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7554 Some(
7555 h_flex()
7556 .min_w(min_width)
7557 .max_w(max_width)
7558 .flex_1()
7559 .elevation_2(cx)
7560 .border_color(cx.theme().colors().border)
7561 .child(
7562 div()
7563 .flex_1()
7564 .py_1()
7565 .px_2()
7566 .overflow_hidden()
7567 .child(completion),
7568 )
7569 .when_some(accept_keystroke, |el, accept_keystroke| {
7570 if !accept_keystroke.modifiers.modified() {
7571 return el;
7572 }
7573
7574 el.child(
7575 h_flex()
7576 .h_full()
7577 .border_l_1()
7578 .rounded_r_lg()
7579 .border_color(cx.theme().colors().border)
7580 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7581 .gap_1()
7582 .py_1()
7583 .px_2()
7584 .child(
7585 h_flex()
7586 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7587 .when(is_platform_style_mac, |parent| parent.gap_1())
7588 .child(h_flex().children(ui::render_modifiers(
7589 &accept_keystroke.modifiers,
7590 PlatformStyle::platform(),
7591 Some(if !has_completion {
7592 Color::Muted
7593 } else {
7594 Color::Default
7595 }),
7596 None,
7597 false,
7598 ))),
7599 )
7600 .child(Label::new("Preview").into_any_element())
7601 .opacity(if has_completion { 1.0 } else { 0.4 }),
7602 )
7603 })
7604 .into_any(),
7605 )
7606 }
7607
7608 fn render_edit_prediction_cursor_popover_preview(
7609 &self,
7610 completion: &InlineCompletionState,
7611 cursor_point: Point,
7612 style: &EditorStyle,
7613 cx: &mut Context<Editor>,
7614 ) -> Option<Div> {
7615 use text::ToPoint as _;
7616
7617 fn render_relative_row_jump(
7618 prefix: impl Into<String>,
7619 current_row: u32,
7620 target_row: u32,
7621 ) -> Div {
7622 let (row_diff, arrow) = if target_row < current_row {
7623 (current_row - target_row, IconName::ArrowUp)
7624 } else {
7625 (target_row - current_row, IconName::ArrowDown)
7626 };
7627
7628 h_flex()
7629 .child(
7630 Label::new(format!("{}{}", prefix.into(), row_diff))
7631 .color(Color::Muted)
7632 .size(LabelSize::Small),
7633 )
7634 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7635 }
7636
7637 match &completion.completion {
7638 InlineCompletion::Move {
7639 target, snapshot, ..
7640 } => Some(
7641 h_flex()
7642 .px_2()
7643 .gap_2()
7644 .flex_1()
7645 .child(
7646 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7647 Icon::new(IconName::ZedPredictDown)
7648 } else {
7649 Icon::new(IconName::ZedPredictUp)
7650 },
7651 )
7652 .child(Label::new("Jump to Edit")),
7653 ),
7654
7655 InlineCompletion::Edit {
7656 edits,
7657 edit_preview,
7658 snapshot,
7659 display_mode: _,
7660 } => {
7661 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7662
7663 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7664 &snapshot,
7665 &edits,
7666 edit_preview.as_ref()?,
7667 true,
7668 cx,
7669 )
7670 .first_line_preview();
7671
7672 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7673 .with_default_highlights(&style.text, highlighted_edits.highlights);
7674
7675 let preview = h_flex()
7676 .gap_1()
7677 .min_w_16()
7678 .child(styled_text)
7679 .when(has_more_lines, |parent| parent.child("…"));
7680
7681 let left = if first_edit_row != cursor_point.row {
7682 render_relative_row_jump("", cursor_point.row, first_edit_row)
7683 .into_any_element()
7684 } else {
7685 Icon::new(IconName::ZedPredict).into_any_element()
7686 };
7687
7688 Some(
7689 h_flex()
7690 .h_full()
7691 .flex_1()
7692 .gap_2()
7693 .pr_1()
7694 .overflow_x_hidden()
7695 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7696 .child(left)
7697 .child(preview),
7698 )
7699 }
7700 }
7701 }
7702
7703 fn render_context_menu(
7704 &self,
7705 style: &EditorStyle,
7706 max_height_in_lines: u32,
7707 y_flipped: bool,
7708 window: &mut Window,
7709 cx: &mut Context<Editor>,
7710 ) -> Option<AnyElement> {
7711 let menu = self.context_menu.borrow();
7712 let menu = menu.as_ref()?;
7713 if !menu.visible() {
7714 return None;
7715 };
7716 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7717 }
7718
7719 fn render_context_menu_aside(
7720 &mut self,
7721 max_size: Size<Pixels>,
7722 window: &mut Window,
7723 cx: &mut Context<Editor>,
7724 ) -> Option<AnyElement> {
7725 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7726 if menu.visible() {
7727 menu.render_aside(self, max_size, window, cx)
7728 } else {
7729 None
7730 }
7731 })
7732 }
7733
7734 fn hide_context_menu(
7735 &mut self,
7736 window: &mut Window,
7737 cx: &mut Context<Self>,
7738 ) -> Option<CodeContextMenu> {
7739 cx.notify();
7740 self.completion_tasks.clear();
7741 let context_menu = self.context_menu.borrow_mut().take();
7742 self.stale_inline_completion_in_menu.take();
7743 self.update_visible_inline_completion(window, cx);
7744 context_menu
7745 }
7746
7747 fn show_snippet_choices(
7748 &mut self,
7749 choices: &Vec<String>,
7750 selection: Range<Anchor>,
7751 cx: &mut Context<Self>,
7752 ) {
7753 if selection.start.buffer_id.is_none() {
7754 return;
7755 }
7756 let buffer_id = selection.start.buffer_id.unwrap();
7757 let buffer = self.buffer().read(cx).buffer(buffer_id);
7758 let id = post_inc(&mut self.next_completion_id);
7759
7760 if let Some(buffer) = buffer {
7761 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7762 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7763 ));
7764 }
7765 }
7766
7767 pub fn insert_snippet(
7768 &mut self,
7769 insertion_ranges: &[Range<usize>],
7770 snippet: Snippet,
7771 window: &mut Window,
7772 cx: &mut Context<Self>,
7773 ) -> Result<()> {
7774 struct Tabstop<T> {
7775 is_end_tabstop: bool,
7776 ranges: Vec<Range<T>>,
7777 choices: Option<Vec<String>>,
7778 }
7779
7780 let tabstops = self.buffer.update(cx, |buffer, cx| {
7781 let snippet_text: Arc<str> = snippet.text.clone().into();
7782 let edits = insertion_ranges
7783 .iter()
7784 .cloned()
7785 .map(|range| (range, snippet_text.clone()));
7786 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7787
7788 let snapshot = &*buffer.read(cx);
7789 let snippet = &snippet;
7790 snippet
7791 .tabstops
7792 .iter()
7793 .map(|tabstop| {
7794 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7795 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7796 });
7797 let mut tabstop_ranges = tabstop
7798 .ranges
7799 .iter()
7800 .flat_map(|tabstop_range| {
7801 let mut delta = 0_isize;
7802 insertion_ranges.iter().map(move |insertion_range| {
7803 let insertion_start = insertion_range.start as isize + delta;
7804 delta +=
7805 snippet.text.len() as isize - insertion_range.len() as isize;
7806
7807 let start = ((insertion_start + tabstop_range.start) as usize)
7808 .min(snapshot.len());
7809 let end = ((insertion_start + tabstop_range.end) as usize)
7810 .min(snapshot.len());
7811 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7812 })
7813 })
7814 .collect::<Vec<_>>();
7815 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7816
7817 Tabstop {
7818 is_end_tabstop,
7819 ranges: tabstop_ranges,
7820 choices: tabstop.choices.clone(),
7821 }
7822 })
7823 .collect::<Vec<_>>()
7824 });
7825 if let Some(tabstop) = tabstops.first() {
7826 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7827 s.select_ranges(tabstop.ranges.iter().cloned());
7828 });
7829
7830 if let Some(choices) = &tabstop.choices {
7831 if let Some(selection) = tabstop.ranges.first() {
7832 self.show_snippet_choices(choices, selection.clone(), cx)
7833 }
7834 }
7835
7836 // If we're already at the last tabstop and it's at the end of the snippet,
7837 // we're done, we don't need to keep the state around.
7838 if !tabstop.is_end_tabstop {
7839 let choices = tabstops
7840 .iter()
7841 .map(|tabstop| tabstop.choices.clone())
7842 .collect();
7843
7844 let ranges = tabstops
7845 .into_iter()
7846 .map(|tabstop| tabstop.ranges)
7847 .collect::<Vec<_>>();
7848
7849 self.snippet_stack.push(SnippetState {
7850 active_index: 0,
7851 ranges,
7852 choices,
7853 });
7854 }
7855
7856 // Check whether the just-entered snippet ends with an auto-closable bracket.
7857 if self.autoclose_regions.is_empty() {
7858 let snapshot = self.buffer.read(cx).snapshot(cx);
7859 for selection in &mut self.selections.all::<Point>(cx) {
7860 let selection_head = selection.head();
7861 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7862 continue;
7863 };
7864
7865 let mut bracket_pair = None;
7866 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7867 let prev_chars = snapshot
7868 .reversed_chars_at(selection_head)
7869 .collect::<String>();
7870 for (pair, enabled) in scope.brackets() {
7871 if enabled
7872 && pair.close
7873 && prev_chars.starts_with(pair.start.as_str())
7874 && next_chars.starts_with(pair.end.as_str())
7875 {
7876 bracket_pair = Some(pair.clone());
7877 break;
7878 }
7879 }
7880 if let Some(pair) = bracket_pair {
7881 let start = snapshot.anchor_after(selection_head);
7882 let end = snapshot.anchor_after(selection_head);
7883 self.autoclose_regions.push(AutocloseRegion {
7884 selection_id: selection.id,
7885 range: start..end,
7886 pair,
7887 });
7888 }
7889 }
7890 }
7891 }
7892 Ok(())
7893 }
7894
7895 pub fn move_to_next_snippet_tabstop(
7896 &mut self,
7897 window: &mut Window,
7898 cx: &mut Context<Self>,
7899 ) -> bool {
7900 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7901 }
7902
7903 pub fn move_to_prev_snippet_tabstop(
7904 &mut self,
7905 window: &mut Window,
7906 cx: &mut Context<Self>,
7907 ) -> bool {
7908 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7909 }
7910
7911 pub fn move_to_snippet_tabstop(
7912 &mut self,
7913 bias: Bias,
7914 window: &mut Window,
7915 cx: &mut Context<Self>,
7916 ) -> bool {
7917 if let Some(mut snippet) = self.snippet_stack.pop() {
7918 match bias {
7919 Bias::Left => {
7920 if snippet.active_index > 0 {
7921 snippet.active_index -= 1;
7922 } else {
7923 self.snippet_stack.push(snippet);
7924 return false;
7925 }
7926 }
7927 Bias::Right => {
7928 if snippet.active_index + 1 < snippet.ranges.len() {
7929 snippet.active_index += 1;
7930 } else {
7931 self.snippet_stack.push(snippet);
7932 return false;
7933 }
7934 }
7935 }
7936 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7937 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7938 s.select_anchor_ranges(current_ranges.iter().cloned())
7939 });
7940
7941 if let Some(choices) = &snippet.choices[snippet.active_index] {
7942 if let Some(selection) = current_ranges.first() {
7943 self.show_snippet_choices(&choices, selection.clone(), cx);
7944 }
7945 }
7946
7947 // If snippet state is not at the last tabstop, push it back on the stack
7948 if snippet.active_index + 1 < snippet.ranges.len() {
7949 self.snippet_stack.push(snippet);
7950 }
7951 return true;
7952 }
7953 }
7954
7955 false
7956 }
7957
7958 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7959 self.transact(window, cx, |this, window, cx| {
7960 this.select_all(&SelectAll, window, cx);
7961 this.insert("", window, cx);
7962 });
7963 }
7964
7965 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7966 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
7967 self.transact(window, cx, |this, window, cx| {
7968 this.select_autoclose_pair(window, cx);
7969 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7970 if !this.linked_edit_ranges.is_empty() {
7971 let selections = this.selections.all::<MultiBufferPoint>(cx);
7972 let snapshot = this.buffer.read(cx).snapshot(cx);
7973
7974 for selection in selections.iter() {
7975 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7976 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7977 if selection_start.buffer_id != selection_end.buffer_id {
7978 continue;
7979 }
7980 if let Some(ranges) =
7981 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7982 {
7983 for (buffer, entries) in ranges {
7984 linked_ranges.entry(buffer).or_default().extend(entries);
7985 }
7986 }
7987 }
7988 }
7989
7990 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7991 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7992 for selection in &mut selections {
7993 if selection.is_empty() {
7994 let old_head = selection.head();
7995 let mut new_head =
7996 movement::left(&display_map, old_head.to_display_point(&display_map))
7997 .to_point(&display_map);
7998 if let Some((buffer, line_buffer_range)) = display_map
7999 .buffer_snapshot
8000 .buffer_line_for_row(MultiBufferRow(old_head.row))
8001 {
8002 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8003 let indent_len = match indent_size.kind {
8004 IndentKind::Space => {
8005 buffer.settings_at(line_buffer_range.start, cx).tab_size
8006 }
8007 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8008 };
8009 if old_head.column <= indent_size.len && old_head.column > 0 {
8010 let indent_len = indent_len.get();
8011 new_head = cmp::min(
8012 new_head,
8013 MultiBufferPoint::new(
8014 old_head.row,
8015 ((old_head.column - 1) / indent_len) * indent_len,
8016 ),
8017 );
8018 }
8019 }
8020
8021 selection.set_head(new_head, SelectionGoal::None);
8022 }
8023 }
8024
8025 this.signature_help_state.set_backspace_pressed(true);
8026 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8027 s.select(selections)
8028 });
8029 this.insert("", window, cx);
8030 let empty_str: Arc<str> = Arc::from("");
8031 for (buffer, edits) in linked_ranges {
8032 let snapshot = buffer.read(cx).snapshot();
8033 use text::ToPoint as TP;
8034
8035 let edits = edits
8036 .into_iter()
8037 .map(|range| {
8038 let end_point = TP::to_point(&range.end, &snapshot);
8039 let mut start_point = TP::to_point(&range.start, &snapshot);
8040
8041 if end_point == start_point {
8042 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8043 .saturating_sub(1);
8044 start_point =
8045 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8046 };
8047
8048 (start_point..end_point, empty_str.clone())
8049 })
8050 .sorted_by_key(|(range, _)| range.start)
8051 .collect::<Vec<_>>();
8052 buffer.update(cx, |this, cx| {
8053 this.edit(edits, None, cx);
8054 })
8055 }
8056 this.refresh_inline_completion(true, false, window, cx);
8057 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8058 });
8059 }
8060
8061 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8062 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8063 self.transact(window, cx, |this, window, cx| {
8064 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8065 s.move_with(|map, selection| {
8066 if selection.is_empty() {
8067 let cursor = movement::right(map, selection.head());
8068 selection.end = cursor;
8069 selection.reversed = true;
8070 selection.goal = SelectionGoal::None;
8071 }
8072 })
8073 });
8074 this.insert("", window, cx);
8075 this.refresh_inline_completion(true, false, window, cx);
8076 });
8077 }
8078
8079 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8080 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8081 if self.move_to_prev_snippet_tabstop(window, cx) {
8082 return;
8083 }
8084 self.outdent(&Outdent, window, cx);
8085 }
8086
8087 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8088 if self.move_to_next_snippet_tabstop(window, cx) {
8089 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8090 return;
8091 }
8092 if self.read_only(cx) {
8093 return;
8094 }
8095 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8096 let mut selections = self.selections.all_adjusted(cx);
8097 let buffer = self.buffer.read(cx);
8098 let snapshot = buffer.snapshot(cx);
8099 let rows_iter = selections.iter().map(|s| s.head().row);
8100 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8101
8102 let mut edits = Vec::new();
8103 let mut prev_edited_row = 0;
8104 let mut row_delta = 0;
8105 for selection in &mut selections {
8106 if selection.start.row != prev_edited_row {
8107 row_delta = 0;
8108 }
8109 prev_edited_row = selection.end.row;
8110
8111 // If the selection is non-empty, then increase the indentation of the selected lines.
8112 if !selection.is_empty() {
8113 row_delta =
8114 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8115 continue;
8116 }
8117
8118 // If the selection is empty and the cursor is in the leading whitespace before the
8119 // suggested indentation, then auto-indent the line.
8120 let cursor = selection.head();
8121 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8122 if let Some(suggested_indent) =
8123 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8124 {
8125 if cursor.column < suggested_indent.len
8126 && cursor.column <= current_indent.len
8127 && current_indent.len <= suggested_indent.len
8128 {
8129 selection.start = Point::new(cursor.row, suggested_indent.len);
8130 selection.end = selection.start;
8131 if row_delta == 0 {
8132 edits.extend(Buffer::edit_for_indent_size_adjustment(
8133 cursor.row,
8134 current_indent,
8135 suggested_indent,
8136 ));
8137 row_delta = suggested_indent.len - current_indent.len;
8138 }
8139 continue;
8140 }
8141 }
8142
8143 // Otherwise, insert a hard or soft tab.
8144 let settings = buffer.language_settings_at(cursor, cx);
8145 let tab_size = if settings.hard_tabs {
8146 IndentSize::tab()
8147 } else {
8148 let tab_size = settings.tab_size.get();
8149 let char_column = snapshot
8150 .text_for_range(Point::new(cursor.row, 0)..cursor)
8151 .flat_map(str::chars)
8152 .count()
8153 + row_delta as usize;
8154 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
8155 IndentSize::spaces(chars_to_next_tab_stop)
8156 };
8157 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8158 selection.end = selection.start;
8159 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8160 row_delta += tab_size.len;
8161 }
8162
8163 self.transact(window, cx, |this, window, cx| {
8164 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8165 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8166 s.select(selections)
8167 });
8168 this.refresh_inline_completion(true, false, window, cx);
8169 });
8170 }
8171
8172 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8173 if self.read_only(cx) {
8174 return;
8175 }
8176 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8177 let mut selections = self.selections.all::<Point>(cx);
8178 let mut prev_edited_row = 0;
8179 let mut row_delta = 0;
8180 let mut edits = Vec::new();
8181 let buffer = self.buffer.read(cx);
8182 let snapshot = buffer.snapshot(cx);
8183 for selection in &mut selections {
8184 if selection.start.row != prev_edited_row {
8185 row_delta = 0;
8186 }
8187 prev_edited_row = selection.end.row;
8188
8189 row_delta =
8190 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8191 }
8192
8193 self.transact(window, cx, |this, window, cx| {
8194 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8195 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8196 s.select(selections)
8197 });
8198 });
8199 }
8200
8201 fn indent_selection(
8202 buffer: &MultiBuffer,
8203 snapshot: &MultiBufferSnapshot,
8204 selection: &mut Selection<Point>,
8205 edits: &mut Vec<(Range<Point>, String)>,
8206 delta_for_start_row: u32,
8207 cx: &App,
8208 ) -> u32 {
8209 let settings = buffer.language_settings_at(selection.start, cx);
8210 let tab_size = settings.tab_size.get();
8211 let indent_kind = if settings.hard_tabs {
8212 IndentKind::Tab
8213 } else {
8214 IndentKind::Space
8215 };
8216 let mut start_row = selection.start.row;
8217 let mut end_row = selection.end.row + 1;
8218
8219 // If a selection ends at the beginning of a line, don't indent
8220 // that last line.
8221 if selection.end.column == 0 && selection.end.row > selection.start.row {
8222 end_row -= 1;
8223 }
8224
8225 // Avoid re-indenting a row that has already been indented by a
8226 // previous selection, but still update this selection's column
8227 // to reflect that indentation.
8228 if delta_for_start_row > 0 {
8229 start_row += 1;
8230 selection.start.column += delta_for_start_row;
8231 if selection.end.row == selection.start.row {
8232 selection.end.column += delta_for_start_row;
8233 }
8234 }
8235
8236 let mut delta_for_end_row = 0;
8237 let has_multiple_rows = start_row + 1 != end_row;
8238 for row in start_row..end_row {
8239 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8240 let indent_delta = match (current_indent.kind, indent_kind) {
8241 (IndentKind::Space, IndentKind::Space) => {
8242 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8243 IndentSize::spaces(columns_to_next_tab_stop)
8244 }
8245 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8246 (_, IndentKind::Tab) => IndentSize::tab(),
8247 };
8248
8249 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8250 0
8251 } else {
8252 selection.start.column
8253 };
8254 let row_start = Point::new(row, start);
8255 edits.push((
8256 row_start..row_start,
8257 indent_delta.chars().collect::<String>(),
8258 ));
8259
8260 // Update this selection's endpoints to reflect the indentation.
8261 if row == selection.start.row {
8262 selection.start.column += indent_delta.len;
8263 }
8264 if row == selection.end.row {
8265 selection.end.column += indent_delta.len;
8266 delta_for_end_row = indent_delta.len;
8267 }
8268 }
8269
8270 if selection.start.row == selection.end.row {
8271 delta_for_start_row + delta_for_end_row
8272 } else {
8273 delta_for_end_row
8274 }
8275 }
8276
8277 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8278 if self.read_only(cx) {
8279 return;
8280 }
8281 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8282 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8283 let selections = self.selections.all::<Point>(cx);
8284 let mut deletion_ranges = Vec::new();
8285 let mut last_outdent = None;
8286 {
8287 let buffer = self.buffer.read(cx);
8288 let snapshot = buffer.snapshot(cx);
8289 for selection in &selections {
8290 let settings = buffer.language_settings_at(selection.start, cx);
8291 let tab_size = settings.tab_size.get();
8292 let mut rows = selection.spanned_rows(false, &display_map);
8293
8294 // Avoid re-outdenting a row that has already been outdented by a
8295 // previous selection.
8296 if let Some(last_row) = last_outdent {
8297 if last_row == rows.start {
8298 rows.start = rows.start.next_row();
8299 }
8300 }
8301 let has_multiple_rows = rows.len() > 1;
8302 for row in rows.iter_rows() {
8303 let indent_size = snapshot.indent_size_for_line(row);
8304 if indent_size.len > 0 {
8305 let deletion_len = match indent_size.kind {
8306 IndentKind::Space => {
8307 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8308 if columns_to_prev_tab_stop == 0 {
8309 tab_size
8310 } else {
8311 columns_to_prev_tab_stop
8312 }
8313 }
8314 IndentKind::Tab => 1,
8315 };
8316 let start = if has_multiple_rows
8317 || deletion_len > selection.start.column
8318 || indent_size.len < selection.start.column
8319 {
8320 0
8321 } else {
8322 selection.start.column - deletion_len
8323 };
8324 deletion_ranges.push(
8325 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8326 );
8327 last_outdent = Some(row);
8328 }
8329 }
8330 }
8331 }
8332
8333 self.transact(window, cx, |this, window, cx| {
8334 this.buffer.update(cx, |buffer, cx| {
8335 let empty_str: Arc<str> = Arc::default();
8336 buffer.edit(
8337 deletion_ranges
8338 .into_iter()
8339 .map(|range| (range, empty_str.clone())),
8340 None,
8341 cx,
8342 );
8343 });
8344 let selections = this.selections.all::<usize>(cx);
8345 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8346 s.select(selections)
8347 });
8348 });
8349 }
8350
8351 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8352 if self.read_only(cx) {
8353 return;
8354 }
8355 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8356 let selections = self
8357 .selections
8358 .all::<usize>(cx)
8359 .into_iter()
8360 .map(|s| s.range());
8361
8362 self.transact(window, cx, |this, window, cx| {
8363 this.buffer.update(cx, |buffer, cx| {
8364 buffer.autoindent_ranges(selections, cx);
8365 });
8366 let selections = this.selections.all::<usize>(cx);
8367 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8368 s.select(selections)
8369 });
8370 });
8371 }
8372
8373 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8374 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8375 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8376 let selections = self.selections.all::<Point>(cx);
8377
8378 let mut new_cursors = Vec::new();
8379 let mut edit_ranges = Vec::new();
8380 let mut selections = selections.iter().peekable();
8381 while let Some(selection) = selections.next() {
8382 let mut rows = selection.spanned_rows(false, &display_map);
8383 let goal_display_column = selection.head().to_display_point(&display_map).column();
8384
8385 // Accumulate contiguous regions of rows that we want to delete.
8386 while let Some(next_selection) = selections.peek() {
8387 let next_rows = next_selection.spanned_rows(false, &display_map);
8388 if next_rows.start <= rows.end {
8389 rows.end = next_rows.end;
8390 selections.next().unwrap();
8391 } else {
8392 break;
8393 }
8394 }
8395
8396 let buffer = &display_map.buffer_snapshot;
8397 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8398 let edit_end;
8399 let cursor_buffer_row;
8400 if buffer.max_point().row >= rows.end.0 {
8401 // If there's a line after the range, delete the \n from the end of the row range
8402 // and position the cursor on the next line.
8403 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8404 cursor_buffer_row = rows.end;
8405 } else {
8406 // If there isn't a line after the range, delete the \n from the line before the
8407 // start of the row range and position the cursor there.
8408 edit_start = edit_start.saturating_sub(1);
8409 edit_end = buffer.len();
8410 cursor_buffer_row = rows.start.previous_row();
8411 }
8412
8413 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8414 *cursor.column_mut() =
8415 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8416
8417 new_cursors.push((
8418 selection.id,
8419 buffer.anchor_after(cursor.to_point(&display_map)),
8420 ));
8421 edit_ranges.push(edit_start..edit_end);
8422 }
8423
8424 self.transact(window, cx, |this, window, cx| {
8425 let buffer = this.buffer.update(cx, |buffer, cx| {
8426 let empty_str: Arc<str> = Arc::default();
8427 buffer.edit(
8428 edit_ranges
8429 .into_iter()
8430 .map(|range| (range, empty_str.clone())),
8431 None,
8432 cx,
8433 );
8434 buffer.snapshot(cx)
8435 });
8436 let new_selections = new_cursors
8437 .into_iter()
8438 .map(|(id, cursor)| {
8439 let cursor = cursor.to_point(&buffer);
8440 Selection {
8441 id,
8442 start: cursor,
8443 end: cursor,
8444 reversed: false,
8445 goal: SelectionGoal::None,
8446 }
8447 })
8448 .collect();
8449
8450 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8451 s.select(new_selections);
8452 });
8453 });
8454 }
8455
8456 pub fn join_lines_impl(
8457 &mut self,
8458 insert_whitespace: bool,
8459 window: &mut Window,
8460 cx: &mut Context<Self>,
8461 ) {
8462 if self.read_only(cx) {
8463 return;
8464 }
8465 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8466 for selection in self.selections.all::<Point>(cx) {
8467 let start = MultiBufferRow(selection.start.row);
8468 // Treat single line selections as if they include the next line. Otherwise this action
8469 // would do nothing for single line selections individual cursors.
8470 let end = if selection.start.row == selection.end.row {
8471 MultiBufferRow(selection.start.row + 1)
8472 } else {
8473 MultiBufferRow(selection.end.row)
8474 };
8475
8476 if let Some(last_row_range) = row_ranges.last_mut() {
8477 if start <= last_row_range.end {
8478 last_row_range.end = end;
8479 continue;
8480 }
8481 }
8482 row_ranges.push(start..end);
8483 }
8484
8485 let snapshot = self.buffer.read(cx).snapshot(cx);
8486 let mut cursor_positions = Vec::new();
8487 for row_range in &row_ranges {
8488 let anchor = snapshot.anchor_before(Point::new(
8489 row_range.end.previous_row().0,
8490 snapshot.line_len(row_range.end.previous_row()),
8491 ));
8492 cursor_positions.push(anchor..anchor);
8493 }
8494
8495 self.transact(window, cx, |this, window, cx| {
8496 for row_range in row_ranges.into_iter().rev() {
8497 for row in row_range.iter_rows().rev() {
8498 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8499 let next_line_row = row.next_row();
8500 let indent = snapshot.indent_size_for_line(next_line_row);
8501 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8502
8503 let replace =
8504 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8505 " "
8506 } else {
8507 ""
8508 };
8509
8510 this.buffer.update(cx, |buffer, cx| {
8511 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8512 });
8513 }
8514 }
8515
8516 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8517 s.select_anchor_ranges(cursor_positions)
8518 });
8519 });
8520 }
8521
8522 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8523 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8524 self.join_lines_impl(true, window, cx);
8525 }
8526
8527 pub fn sort_lines_case_sensitive(
8528 &mut self,
8529 _: &SortLinesCaseSensitive,
8530 window: &mut Window,
8531 cx: &mut Context<Self>,
8532 ) {
8533 self.manipulate_lines(window, cx, |lines| lines.sort())
8534 }
8535
8536 pub fn sort_lines_case_insensitive(
8537 &mut self,
8538 _: &SortLinesCaseInsensitive,
8539 window: &mut Window,
8540 cx: &mut Context<Self>,
8541 ) {
8542 self.manipulate_lines(window, cx, |lines| {
8543 lines.sort_by_key(|line| line.to_lowercase())
8544 })
8545 }
8546
8547 pub fn unique_lines_case_insensitive(
8548 &mut self,
8549 _: &UniqueLinesCaseInsensitive,
8550 window: &mut Window,
8551 cx: &mut Context<Self>,
8552 ) {
8553 self.manipulate_lines(window, cx, |lines| {
8554 let mut seen = HashSet::default();
8555 lines.retain(|line| seen.insert(line.to_lowercase()));
8556 })
8557 }
8558
8559 pub fn unique_lines_case_sensitive(
8560 &mut self,
8561 _: &UniqueLinesCaseSensitive,
8562 window: &mut Window,
8563 cx: &mut Context<Self>,
8564 ) {
8565 self.manipulate_lines(window, cx, |lines| {
8566 let mut seen = HashSet::default();
8567 lines.retain(|line| seen.insert(*line));
8568 })
8569 }
8570
8571 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8572 let Some(project) = self.project.clone() else {
8573 return;
8574 };
8575 self.reload(project, window, cx)
8576 .detach_and_notify_err(window, cx);
8577 }
8578
8579 pub fn restore_file(
8580 &mut self,
8581 _: &::git::RestoreFile,
8582 window: &mut Window,
8583 cx: &mut Context<Self>,
8584 ) {
8585 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8586 let mut buffer_ids = HashSet::default();
8587 let snapshot = self.buffer().read(cx).snapshot(cx);
8588 for selection in self.selections.all::<usize>(cx) {
8589 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8590 }
8591
8592 let buffer = self.buffer().read(cx);
8593 let ranges = buffer_ids
8594 .into_iter()
8595 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8596 .collect::<Vec<_>>();
8597
8598 self.restore_hunks_in_ranges(ranges, window, cx);
8599 }
8600
8601 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8602 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8603 let selections = self
8604 .selections
8605 .all(cx)
8606 .into_iter()
8607 .map(|s| s.range())
8608 .collect();
8609 self.restore_hunks_in_ranges(selections, window, cx);
8610 }
8611
8612 pub fn restore_hunks_in_ranges(
8613 &mut self,
8614 ranges: Vec<Range<Point>>,
8615 window: &mut Window,
8616 cx: &mut Context<Editor>,
8617 ) {
8618 let mut revert_changes = HashMap::default();
8619 let chunk_by = self
8620 .snapshot(window, cx)
8621 .hunks_for_ranges(ranges)
8622 .into_iter()
8623 .chunk_by(|hunk| hunk.buffer_id);
8624 for (buffer_id, hunks) in &chunk_by {
8625 let hunks = hunks.collect::<Vec<_>>();
8626 for hunk in &hunks {
8627 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8628 }
8629 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8630 }
8631 drop(chunk_by);
8632 if !revert_changes.is_empty() {
8633 self.transact(window, cx, |editor, window, cx| {
8634 editor.restore(revert_changes, window, cx);
8635 });
8636 }
8637 }
8638
8639 pub fn open_active_item_in_terminal(
8640 &mut self,
8641 _: &OpenInTerminal,
8642 window: &mut Window,
8643 cx: &mut Context<Self>,
8644 ) {
8645 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8646 let project_path = buffer.read(cx).project_path(cx)?;
8647 let project = self.project.as_ref()?.read(cx);
8648 let entry = project.entry_for_path(&project_path, cx)?;
8649 let parent = match &entry.canonical_path {
8650 Some(canonical_path) => canonical_path.to_path_buf(),
8651 None => project.absolute_path(&project_path, cx)?,
8652 }
8653 .parent()?
8654 .to_path_buf();
8655 Some(parent)
8656 }) {
8657 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8658 }
8659 }
8660
8661 fn set_breakpoint_context_menu(
8662 &mut self,
8663 display_row: DisplayRow,
8664 position: Option<Anchor>,
8665 clicked_point: gpui::Point<Pixels>,
8666 window: &mut Window,
8667 cx: &mut Context<Self>,
8668 ) {
8669 if !cx.has_flag::<Debugger>() {
8670 return;
8671 }
8672 let source = self
8673 .buffer
8674 .read(cx)
8675 .snapshot(cx)
8676 .anchor_before(Point::new(display_row.0, 0u32));
8677
8678 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8679
8680 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8681 self,
8682 source,
8683 clicked_point,
8684 context_menu,
8685 window,
8686 cx,
8687 );
8688 }
8689
8690 fn add_edit_breakpoint_block(
8691 &mut self,
8692 anchor: Anchor,
8693 breakpoint: &Breakpoint,
8694 edit_action: BreakpointPromptEditAction,
8695 window: &mut Window,
8696 cx: &mut Context<Self>,
8697 ) {
8698 let weak_editor = cx.weak_entity();
8699 let bp_prompt = cx.new(|cx| {
8700 BreakpointPromptEditor::new(
8701 weak_editor,
8702 anchor,
8703 breakpoint.clone(),
8704 edit_action,
8705 window,
8706 cx,
8707 )
8708 });
8709
8710 let height = bp_prompt.update(cx, |this, cx| {
8711 this.prompt
8712 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8713 });
8714 let cloned_prompt = bp_prompt.clone();
8715 let blocks = vec![BlockProperties {
8716 style: BlockStyle::Sticky,
8717 placement: BlockPlacement::Above(anchor),
8718 height: Some(height),
8719 render: Arc::new(move |cx| {
8720 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8721 cloned_prompt.clone().into_any_element()
8722 }),
8723 priority: 0,
8724 }];
8725
8726 let focus_handle = bp_prompt.focus_handle(cx);
8727 window.focus(&focus_handle);
8728
8729 let block_ids = self.insert_blocks(blocks, None, cx);
8730 bp_prompt.update(cx, |prompt, _| {
8731 prompt.add_block_ids(block_ids);
8732 });
8733 }
8734
8735 fn breakpoint_at_cursor_head(
8736 &self,
8737 window: &mut Window,
8738 cx: &mut Context<Self>,
8739 ) -> Option<(Anchor, Breakpoint)> {
8740 let cursor_position: Point = self.selections.newest(cx).head();
8741 self.breakpoint_at_row(cursor_position.row, window, cx)
8742 }
8743
8744 pub(crate) fn breakpoint_at_row(
8745 &self,
8746 row: u32,
8747 window: &mut Window,
8748 cx: &mut Context<Self>,
8749 ) -> Option<(Anchor, Breakpoint)> {
8750 let snapshot = self.snapshot(window, cx);
8751 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8752
8753 let project = self.project.clone()?;
8754
8755 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8756 snapshot
8757 .buffer_snapshot
8758 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8759 })?;
8760
8761 let enclosing_excerpt = breakpoint_position.excerpt_id;
8762 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8763 let buffer_snapshot = buffer.read(cx).snapshot();
8764
8765 let row = buffer_snapshot
8766 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8767 .row;
8768
8769 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8770 let anchor_end = snapshot
8771 .buffer_snapshot
8772 .anchor_after(Point::new(row, line_len));
8773
8774 let bp = self
8775 .breakpoint_store
8776 .as_ref()?
8777 .read_with(cx, |breakpoint_store, cx| {
8778 breakpoint_store
8779 .breakpoints(
8780 &buffer,
8781 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8782 &buffer_snapshot,
8783 cx,
8784 )
8785 .next()
8786 .and_then(|(anchor, bp)| {
8787 let breakpoint_row = buffer_snapshot
8788 .summary_for_anchor::<text::PointUtf16>(anchor)
8789 .row;
8790
8791 if breakpoint_row == row {
8792 snapshot
8793 .buffer_snapshot
8794 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8795 .map(|anchor| (anchor, bp.clone()))
8796 } else {
8797 None
8798 }
8799 })
8800 });
8801 bp
8802 }
8803
8804 pub fn edit_log_breakpoint(
8805 &mut self,
8806 _: &EditLogBreakpoint,
8807 window: &mut Window,
8808 cx: &mut Context<Self>,
8809 ) {
8810 let (anchor, bp) = self
8811 .breakpoint_at_cursor_head(window, cx)
8812 .unwrap_or_else(|| {
8813 let cursor_position: Point = self.selections.newest(cx).head();
8814
8815 let breakpoint_position = self
8816 .snapshot(window, cx)
8817 .display_snapshot
8818 .buffer_snapshot
8819 .anchor_after(Point::new(cursor_position.row, 0));
8820
8821 (
8822 breakpoint_position,
8823 Breakpoint {
8824 message: None,
8825 state: BreakpointState::Enabled,
8826 condition: None,
8827 hit_condition: None,
8828 },
8829 )
8830 });
8831
8832 self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
8833 }
8834
8835 pub fn enable_breakpoint(
8836 &mut self,
8837 _: &crate::actions::EnableBreakpoint,
8838 window: &mut Window,
8839 cx: &mut Context<Self>,
8840 ) {
8841 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8842 if breakpoint.is_disabled() {
8843 self.edit_breakpoint_at_anchor(
8844 anchor,
8845 breakpoint,
8846 BreakpointEditAction::InvertState,
8847 cx,
8848 );
8849 }
8850 }
8851 }
8852
8853 pub fn disable_breakpoint(
8854 &mut self,
8855 _: &crate::actions::DisableBreakpoint,
8856 window: &mut Window,
8857 cx: &mut Context<Self>,
8858 ) {
8859 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8860 if breakpoint.is_enabled() {
8861 self.edit_breakpoint_at_anchor(
8862 anchor,
8863 breakpoint,
8864 BreakpointEditAction::InvertState,
8865 cx,
8866 );
8867 }
8868 }
8869 }
8870
8871 pub fn toggle_breakpoint(
8872 &mut self,
8873 _: &crate::actions::ToggleBreakpoint,
8874 window: &mut Window,
8875 cx: &mut Context<Self>,
8876 ) {
8877 let edit_action = BreakpointEditAction::Toggle;
8878
8879 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8880 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8881 } else {
8882 let cursor_position: Point = self.selections.newest(cx).head();
8883
8884 let breakpoint_position = self
8885 .snapshot(window, cx)
8886 .display_snapshot
8887 .buffer_snapshot
8888 .anchor_after(Point::new(cursor_position.row, 0));
8889
8890 self.edit_breakpoint_at_anchor(
8891 breakpoint_position,
8892 Breakpoint::new_standard(),
8893 edit_action,
8894 cx,
8895 );
8896 }
8897 }
8898
8899 pub fn edit_breakpoint_at_anchor(
8900 &mut self,
8901 breakpoint_position: Anchor,
8902 breakpoint: Breakpoint,
8903 edit_action: BreakpointEditAction,
8904 cx: &mut Context<Self>,
8905 ) {
8906 let Some(breakpoint_store) = &self.breakpoint_store else {
8907 return;
8908 };
8909
8910 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8911 if breakpoint_position == Anchor::min() {
8912 self.buffer()
8913 .read(cx)
8914 .excerpt_buffer_ids()
8915 .into_iter()
8916 .next()
8917 } else {
8918 None
8919 }
8920 }) else {
8921 return;
8922 };
8923
8924 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8925 return;
8926 };
8927
8928 breakpoint_store.update(cx, |breakpoint_store, cx| {
8929 breakpoint_store.toggle_breakpoint(
8930 buffer,
8931 (breakpoint_position.text_anchor, breakpoint),
8932 edit_action,
8933 cx,
8934 );
8935 });
8936
8937 cx.notify();
8938 }
8939
8940 #[cfg(any(test, feature = "test-support"))]
8941 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8942 self.breakpoint_store.clone()
8943 }
8944
8945 pub fn prepare_restore_change(
8946 &self,
8947 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8948 hunk: &MultiBufferDiffHunk,
8949 cx: &mut App,
8950 ) -> Option<()> {
8951 if hunk.is_created_file() {
8952 return None;
8953 }
8954 let buffer = self.buffer.read(cx);
8955 let diff = buffer.diff_for(hunk.buffer_id)?;
8956 let buffer = buffer.buffer(hunk.buffer_id)?;
8957 let buffer = buffer.read(cx);
8958 let original_text = diff
8959 .read(cx)
8960 .base_text()
8961 .as_rope()
8962 .slice(hunk.diff_base_byte_range.clone());
8963 let buffer_snapshot = buffer.snapshot();
8964 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8965 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8966 probe
8967 .0
8968 .start
8969 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8970 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8971 }) {
8972 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8973 Some(())
8974 } else {
8975 None
8976 }
8977 }
8978
8979 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8980 self.manipulate_lines(window, cx, |lines| lines.reverse())
8981 }
8982
8983 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8984 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8985 }
8986
8987 fn manipulate_lines<Fn>(
8988 &mut self,
8989 window: &mut Window,
8990 cx: &mut Context<Self>,
8991 mut callback: Fn,
8992 ) where
8993 Fn: FnMut(&mut Vec<&str>),
8994 {
8995 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8996
8997 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8998 let buffer = self.buffer.read(cx).snapshot(cx);
8999
9000 let mut edits = Vec::new();
9001
9002 let selections = self.selections.all::<Point>(cx);
9003 let mut selections = selections.iter().peekable();
9004 let mut contiguous_row_selections = Vec::new();
9005 let mut new_selections = Vec::new();
9006 let mut added_lines = 0;
9007 let mut removed_lines = 0;
9008
9009 while let Some(selection) = selections.next() {
9010 let (start_row, end_row) = consume_contiguous_rows(
9011 &mut contiguous_row_selections,
9012 selection,
9013 &display_map,
9014 &mut selections,
9015 );
9016
9017 let start_point = Point::new(start_row.0, 0);
9018 let end_point = Point::new(
9019 end_row.previous_row().0,
9020 buffer.line_len(end_row.previous_row()),
9021 );
9022 let text = buffer
9023 .text_for_range(start_point..end_point)
9024 .collect::<String>();
9025
9026 let mut lines = text.split('\n').collect_vec();
9027
9028 let lines_before = lines.len();
9029 callback(&mut lines);
9030 let lines_after = lines.len();
9031
9032 edits.push((start_point..end_point, lines.join("\n")));
9033
9034 // Selections must change based on added and removed line count
9035 let start_row =
9036 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9037 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9038 new_selections.push(Selection {
9039 id: selection.id,
9040 start: start_row,
9041 end: end_row,
9042 goal: SelectionGoal::None,
9043 reversed: selection.reversed,
9044 });
9045
9046 if lines_after > lines_before {
9047 added_lines += lines_after - lines_before;
9048 } else if lines_before > lines_after {
9049 removed_lines += lines_before - lines_after;
9050 }
9051 }
9052
9053 self.transact(window, cx, |this, window, cx| {
9054 let buffer = this.buffer.update(cx, |buffer, cx| {
9055 buffer.edit(edits, None, cx);
9056 buffer.snapshot(cx)
9057 });
9058
9059 // Recalculate offsets on newly edited buffer
9060 let new_selections = new_selections
9061 .iter()
9062 .map(|s| {
9063 let start_point = Point::new(s.start.0, 0);
9064 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9065 Selection {
9066 id: s.id,
9067 start: buffer.point_to_offset(start_point),
9068 end: buffer.point_to_offset(end_point),
9069 goal: s.goal,
9070 reversed: s.reversed,
9071 }
9072 })
9073 .collect();
9074
9075 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9076 s.select(new_selections);
9077 });
9078
9079 this.request_autoscroll(Autoscroll::fit(), cx);
9080 });
9081 }
9082
9083 pub fn convert_to_upper_case(
9084 &mut self,
9085 _: &ConvertToUpperCase,
9086 window: &mut Window,
9087 cx: &mut Context<Self>,
9088 ) {
9089 self.manipulate_text(window, cx, |text| text.to_uppercase())
9090 }
9091
9092 pub fn convert_to_lower_case(
9093 &mut self,
9094 _: &ConvertToLowerCase,
9095 window: &mut Window,
9096 cx: &mut Context<Self>,
9097 ) {
9098 self.manipulate_text(window, cx, |text| text.to_lowercase())
9099 }
9100
9101 pub fn convert_to_title_case(
9102 &mut self,
9103 _: &ConvertToTitleCase,
9104 window: &mut Window,
9105 cx: &mut Context<Self>,
9106 ) {
9107 self.manipulate_text(window, cx, |text| {
9108 text.split('\n')
9109 .map(|line| line.to_case(Case::Title))
9110 .join("\n")
9111 })
9112 }
9113
9114 pub fn convert_to_snake_case(
9115 &mut self,
9116 _: &ConvertToSnakeCase,
9117 window: &mut Window,
9118 cx: &mut Context<Self>,
9119 ) {
9120 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9121 }
9122
9123 pub fn convert_to_kebab_case(
9124 &mut self,
9125 _: &ConvertToKebabCase,
9126 window: &mut Window,
9127 cx: &mut Context<Self>,
9128 ) {
9129 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9130 }
9131
9132 pub fn convert_to_upper_camel_case(
9133 &mut self,
9134 _: &ConvertToUpperCamelCase,
9135 window: &mut Window,
9136 cx: &mut Context<Self>,
9137 ) {
9138 self.manipulate_text(window, cx, |text| {
9139 text.split('\n')
9140 .map(|line| line.to_case(Case::UpperCamel))
9141 .join("\n")
9142 })
9143 }
9144
9145 pub fn convert_to_lower_camel_case(
9146 &mut self,
9147 _: &ConvertToLowerCamelCase,
9148 window: &mut Window,
9149 cx: &mut Context<Self>,
9150 ) {
9151 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9152 }
9153
9154 pub fn convert_to_opposite_case(
9155 &mut self,
9156 _: &ConvertToOppositeCase,
9157 window: &mut Window,
9158 cx: &mut Context<Self>,
9159 ) {
9160 self.manipulate_text(window, cx, |text| {
9161 text.chars()
9162 .fold(String::with_capacity(text.len()), |mut t, c| {
9163 if c.is_uppercase() {
9164 t.extend(c.to_lowercase());
9165 } else {
9166 t.extend(c.to_uppercase());
9167 }
9168 t
9169 })
9170 })
9171 }
9172
9173 pub fn convert_to_rot13(
9174 &mut self,
9175 _: &ConvertToRot13,
9176 window: &mut Window,
9177 cx: &mut Context<Self>,
9178 ) {
9179 self.manipulate_text(window, cx, |text| {
9180 text.chars()
9181 .map(|c| match c {
9182 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9183 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9184 _ => c,
9185 })
9186 .collect()
9187 })
9188 }
9189
9190 pub fn convert_to_rot47(
9191 &mut self,
9192 _: &ConvertToRot47,
9193 window: &mut Window,
9194 cx: &mut Context<Self>,
9195 ) {
9196 self.manipulate_text(window, cx, |text| {
9197 text.chars()
9198 .map(|c| {
9199 let code_point = c as u32;
9200 if code_point >= 33 && code_point <= 126 {
9201 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9202 }
9203 c
9204 })
9205 .collect()
9206 })
9207 }
9208
9209 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9210 where
9211 Fn: FnMut(&str) -> String,
9212 {
9213 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9214 let buffer = self.buffer.read(cx).snapshot(cx);
9215
9216 let mut new_selections = Vec::new();
9217 let mut edits = Vec::new();
9218 let mut selection_adjustment = 0i32;
9219
9220 for selection in self.selections.all::<usize>(cx) {
9221 let selection_is_empty = selection.is_empty();
9222
9223 let (start, end) = if selection_is_empty {
9224 let word_range = movement::surrounding_word(
9225 &display_map,
9226 selection.start.to_display_point(&display_map),
9227 );
9228 let start = word_range.start.to_offset(&display_map, Bias::Left);
9229 let end = word_range.end.to_offset(&display_map, Bias::Left);
9230 (start, end)
9231 } else {
9232 (selection.start, selection.end)
9233 };
9234
9235 let text = buffer.text_for_range(start..end).collect::<String>();
9236 let old_length = text.len() as i32;
9237 let text = callback(&text);
9238
9239 new_selections.push(Selection {
9240 start: (start as i32 - selection_adjustment) as usize,
9241 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9242 goal: SelectionGoal::None,
9243 ..selection
9244 });
9245
9246 selection_adjustment += old_length - text.len() as i32;
9247
9248 edits.push((start..end, text));
9249 }
9250
9251 self.transact(window, cx, |this, window, cx| {
9252 this.buffer.update(cx, |buffer, cx| {
9253 buffer.edit(edits, None, cx);
9254 });
9255
9256 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9257 s.select(new_selections);
9258 });
9259
9260 this.request_autoscroll(Autoscroll::fit(), cx);
9261 });
9262 }
9263
9264 pub fn duplicate(
9265 &mut self,
9266 upwards: bool,
9267 whole_lines: bool,
9268 window: &mut Window,
9269 cx: &mut Context<Self>,
9270 ) {
9271 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9272
9273 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9274 let buffer = &display_map.buffer_snapshot;
9275 let selections = self.selections.all::<Point>(cx);
9276
9277 let mut edits = Vec::new();
9278 let mut selections_iter = selections.iter().peekable();
9279 while let Some(selection) = selections_iter.next() {
9280 let mut rows = selection.spanned_rows(false, &display_map);
9281 // duplicate line-wise
9282 if whole_lines || selection.start == selection.end {
9283 // Avoid duplicating the same lines twice.
9284 while let Some(next_selection) = selections_iter.peek() {
9285 let next_rows = next_selection.spanned_rows(false, &display_map);
9286 if next_rows.start < rows.end {
9287 rows.end = next_rows.end;
9288 selections_iter.next().unwrap();
9289 } else {
9290 break;
9291 }
9292 }
9293
9294 // Copy the text from the selected row region and splice it either at the start
9295 // or end of the region.
9296 let start = Point::new(rows.start.0, 0);
9297 let end = Point::new(
9298 rows.end.previous_row().0,
9299 buffer.line_len(rows.end.previous_row()),
9300 );
9301 let text = buffer
9302 .text_for_range(start..end)
9303 .chain(Some("\n"))
9304 .collect::<String>();
9305 let insert_location = if upwards {
9306 Point::new(rows.end.0, 0)
9307 } else {
9308 start
9309 };
9310 edits.push((insert_location..insert_location, text));
9311 } else {
9312 // duplicate character-wise
9313 let start = selection.start;
9314 let end = selection.end;
9315 let text = buffer.text_for_range(start..end).collect::<String>();
9316 edits.push((selection.end..selection.end, text));
9317 }
9318 }
9319
9320 self.transact(window, cx, |this, _, cx| {
9321 this.buffer.update(cx, |buffer, cx| {
9322 buffer.edit(edits, None, cx);
9323 });
9324
9325 this.request_autoscroll(Autoscroll::fit(), cx);
9326 });
9327 }
9328
9329 pub fn duplicate_line_up(
9330 &mut self,
9331 _: &DuplicateLineUp,
9332 window: &mut Window,
9333 cx: &mut Context<Self>,
9334 ) {
9335 self.duplicate(true, true, window, cx);
9336 }
9337
9338 pub fn duplicate_line_down(
9339 &mut self,
9340 _: &DuplicateLineDown,
9341 window: &mut Window,
9342 cx: &mut Context<Self>,
9343 ) {
9344 self.duplicate(false, true, window, cx);
9345 }
9346
9347 pub fn duplicate_selection(
9348 &mut self,
9349 _: &DuplicateSelection,
9350 window: &mut Window,
9351 cx: &mut Context<Self>,
9352 ) {
9353 self.duplicate(false, false, window, cx);
9354 }
9355
9356 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9357 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9358
9359 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9360 let buffer = self.buffer.read(cx).snapshot(cx);
9361
9362 let mut edits = Vec::new();
9363 let mut unfold_ranges = Vec::new();
9364 let mut refold_creases = Vec::new();
9365
9366 let selections = self.selections.all::<Point>(cx);
9367 let mut selections = selections.iter().peekable();
9368 let mut contiguous_row_selections = Vec::new();
9369 let mut new_selections = Vec::new();
9370
9371 while let Some(selection) = selections.next() {
9372 // Find all the selections that span a contiguous row range
9373 let (start_row, end_row) = consume_contiguous_rows(
9374 &mut contiguous_row_selections,
9375 selection,
9376 &display_map,
9377 &mut selections,
9378 );
9379
9380 // Move the text spanned by the row range to be before the line preceding the row range
9381 if start_row.0 > 0 {
9382 let range_to_move = Point::new(
9383 start_row.previous_row().0,
9384 buffer.line_len(start_row.previous_row()),
9385 )
9386 ..Point::new(
9387 end_row.previous_row().0,
9388 buffer.line_len(end_row.previous_row()),
9389 );
9390 let insertion_point = display_map
9391 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9392 .0;
9393
9394 // Don't move lines across excerpts
9395 if buffer
9396 .excerpt_containing(insertion_point..range_to_move.end)
9397 .is_some()
9398 {
9399 let text = buffer
9400 .text_for_range(range_to_move.clone())
9401 .flat_map(|s| s.chars())
9402 .skip(1)
9403 .chain(['\n'])
9404 .collect::<String>();
9405
9406 edits.push((
9407 buffer.anchor_after(range_to_move.start)
9408 ..buffer.anchor_before(range_to_move.end),
9409 String::new(),
9410 ));
9411 let insertion_anchor = buffer.anchor_after(insertion_point);
9412 edits.push((insertion_anchor..insertion_anchor, text));
9413
9414 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9415
9416 // Move selections up
9417 new_selections.extend(contiguous_row_selections.drain(..).map(
9418 |mut selection| {
9419 selection.start.row -= row_delta;
9420 selection.end.row -= row_delta;
9421 selection
9422 },
9423 ));
9424
9425 // Move folds up
9426 unfold_ranges.push(range_to_move.clone());
9427 for fold in display_map.folds_in_range(
9428 buffer.anchor_before(range_to_move.start)
9429 ..buffer.anchor_after(range_to_move.end),
9430 ) {
9431 let mut start = fold.range.start.to_point(&buffer);
9432 let mut end = fold.range.end.to_point(&buffer);
9433 start.row -= row_delta;
9434 end.row -= row_delta;
9435 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9436 }
9437 }
9438 }
9439
9440 // If we didn't move line(s), preserve the existing selections
9441 new_selections.append(&mut contiguous_row_selections);
9442 }
9443
9444 self.transact(window, cx, |this, window, cx| {
9445 this.unfold_ranges(&unfold_ranges, true, true, cx);
9446 this.buffer.update(cx, |buffer, cx| {
9447 for (range, text) in edits {
9448 buffer.edit([(range, text)], None, cx);
9449 }
9450 });
9451 this.fold_creases(refold_creases, true, window, cx);
9452 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9453 s.select(new_selections);
9454 })
9455 });
9456 }
9457
9458 pub fn move_line_down(
9459 &mut self,
9460 _: &MoveLineDown,
9461 window: &mut Window,
9462 cx: &mut Context<Self>,
9463 ) {
9464 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9465
9466 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9467 let buffer = self.buffer.read(cx).snapshot(cx);
9468
9469 let mut edits = Vec::new();
9470 let mut unfold_ranges = Vec::new();
9471 let mut refold_creases = Vec::new();
9472
9473 let selections = self.selections.all::<Point>(cx);
9474 let mut selections = selections.iter().peekable();
9475 let mut contiguous_row_selections = Vec::new();
9476 let mut new_selections = Vec::new();
9477
9478 while let Some(selection) = selections.next() {
9479 // Find all the selections that span a contiguous row range
9480 let (start_row, end_row) = consume_contiguous_rows(
9481 &mut contiguous_row_selections,
9482 selection,
9483 &display_map,
9484 &mut selections,
9485 );
9486
9487 // Move the text spanned by the row range to be after the last line of the row range
9488 if end_row.0 <= buffer.max_point().row {
9489 let range_to_move =
9490 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9491 let insertion_point = display_map
9492 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9493 .0;
9494
9495 // Don't move lines across excerpt boundaries
9496 if buffer
9497 .excerpt_containing(range_to_move.start..insertion_point)
9498 .is_some()
9499 {
9500 let mut text = String::from("\n");
9501 text.extend(buffer.text_for_range(range_to_move.clone()));
9502 text.pop(); // Drop trailing newline
9503 edits.push((
9504 buffer.anchor_after(range_to_move.start)
9505 ..buffer.anchor_before(range_to_move.end),
9506 String::new(),
9507 ));
9508 let insertion_anchor = buffer.anchor_after(insertion_point);
9509 edits.push((insertion_anchor..insertion_anchor, text));
9510
9511 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9512
9513 // Move selections down
9514 new_selections.extend(contiguous_row_selections.drain(..).map(
9515 |mut selection| {
9516 selection.start.row += row_delta;
9517 selection.end.row += row_delta;
9518 selection
9519 },
9520 ));
9521
9522 // Move folds down
9523 unfold_ranges.push(range_to_move.clone());
9524 for fold in display_map.folds_in_range(
9525 buffer.anchor_before(range_to_move.start)
9526 ..buffer.anchor_after(range_to_move.end),
9527 ) {
9528 let mut start = fold.range.start.to_point(&buffer);
9529 let mut end = fold.range.end.to_point(&buffer);
9530 start.row += row_delta;
9531 end.row += row_delta;
9532 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9533 }
9534 }
9535 }
9536
9537 // If we didn't move line(s), preserve the existing selections
9538 new_selections.append(&mut contiguous_row_selections);
9539 }
9540
9541 self.transact(window, cx, |this, window, cx| {
9542 this.unfold_ranges(&unfold_ranges, true, true, cx);
9543 this.buffer.update(cx, |buffer, cx| {
9544 for (range, text) in edits {
9545 buffer.edit([(range, text)], None, cx);
9546 }
9547 });
9548 this.fold_creases(refold_creases, true, window, cx);
9549 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9550 s.select(new_selections)
9551 });
9552 });
9553 }
9554
9555 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9556 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9557 let text_layout_details = &self.text_layout_details(window);
9558 self.transact(window, cx, |this, window, cx| {
9559 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9560 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9561 s.move_with(|display_map, selection| {
9562 if !selection.is_empty() {
9563 return;
9564 }
9565
9566 let mut head = selection.head();
9567 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9568 if head.column() == display_map.line_len(head.row()) {
9569 transpose_offset = display_map
9570 .buffer_snapshot
9571 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9572 }
9573
9574 if transpose_offset == 0 {
9575 return;
9576 }
9577
9578 *head.column_mut() += 1;
9579 head = display_map.clip_point(head, Bias::Right);
9580 let goal = SelectionGoal::HorizontalPosition(
9581 display_map
9582 .x_for_display_point(head, text_layout_details)
9583 .into(),
9584 );
9585 selection.collapse_to(head, goal);
9586
9587 let transpose_start = display_map
9588 .buffer_snapshot
9589 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9590 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9591 let transpose_end = display_map
9592 .buffer_snapshot
9593 .clip_offset(transpose_offset + 1, Bias::Right);
9594 if let Some(ch) =
9595 display_map.buffer_snapshot.chars_at(transpose_start).next()
9596 {
9597 edits.push((transpose_start..transpose_offset, String::new()));
9598 edits.push((transpose_end..transpose_end, ch.to_string()));
9599 }
9600 }
9601 });
9602 edits
9603 });
9604 this.buffer
9605 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9606 let selections = this.selections.all::<usize>(cx);
9607 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9608 s.select(selections);
9609 });
9610 });
9611 }
9612
9613 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9614 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9615 self.rewrap_impl(RewrapOptions::default(), cx)
9616 }
9617
9618 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9619 let buffer = self.buffer.read(cx).snapshot(cx);
9620 let selections = self.selections.all::<Point>(cx);
9621 let mut selections = selections.iter().peekable();
9622
9623 let mut edits = Vec::new();
9624 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9625
9626 while let Some(selection) = selections.next() {
9627 let mut start_row = selection.start.row;
9628 let mut end_row = selection.end.row;
9629
9630 // Skip selections that overlap with a range that has already been rewrapped.
9631 let selection_range = start_row..end_row;
9632 if rewrapped_row_ranges
9633 .iter()
9634 .any(|range| range.overlaps(&selection_range))
9635 {
9636 continue;
9637 }
9638
9639 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9640
9641 // Since not all lines in the selection may be at the same indent
9642 // level, choose the indent size that is the most common between all
9643 // of the lines.
9644 //
9645 // If there is a tie, we use the deepest indent.
9646 let (indent_size, indent_end) = {
9647 let mut indent_size_occurrences = HashMap::default();
9648 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9649
9650 for row in start_row..=end_row {
9651 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9652 rows_by_indent_size.entry(indent).or_default().push(row);
9653 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9654 }
9655
9656 let indent_size = indent_size_occurrences
9657 .into_iter()
9658 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9659 .map(|(indent, _)| indent)
9660 .unwrap_or_default();
9661 let row = rows_by_indent_size[&indent_size][0];
9662 let indent_end = Point::new(row, indent_size.len);
9663
9664 (indent_size, indent_end)
9665 };
9666
9667 let mut line_prefix = indent_size.chars().collect::<String>();
9668
9669 let mut inside_comment = false;
9670 if let Some(comment_prefix) =
9671 buffer
9672 .language_scope_at(selection.head())
9673 .and_then(|language| {
9674 language
9675 .line_comment_prefixes()
9676 .iter()
9677 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9678 .cloned()
9679 })
9680 {
9681 line_prefix.push_str(&comment_prefix);
9682 inside_comment = true;
9683 }
9684
9685 let language_settings = buffer.language_settings_at(selection.head(), cx);
9686 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9687 RewrapBehavior::InComments => inside_comment,
9688 RewrapBehavior::InSelections => !selection.is_empty(),
9689 RewrapBehavior::Anywhere => true,
9690 };
9691
9692 let should_rewrap = options.override_language_settings
9693 || allow_rewrap_based_on_language
9694 || self.hard_wrap.is_some();
9695 if !should_rewrap {
9696 continue;
9697 }
9698
9699 if selection.is_empty() {
9700 'expand_upwards: while start_row > 0 {
9701 let prev_row = start_row - 1;
9702 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9703 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9704 {
9705 start_row = prev_row;
9706 } else {
9707 break 'expand_upwards;
9708 }
9709 }
9710
9711 'expand_downwards: while end_row < buffer.max_point().row {
9712 let next_row = end_row + 1;
9713 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9714 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9715 {
9716 end_row = next_row;
9717 } else {
9718 break 'expand_downwards;
9719 }
9720 }
9721 }
9722
9723 let start = Point::new(start_row, 0);
9724 let start_offset = start.to_offset(&buffer);
9725 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9726 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9727 let Some(lines_without_prefixes) = selection_text
9728 .lines()
9729 .map(|line| {
9730 line.strip_prefix(&line_prefix)
9731 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9732 .ok_or_else(|| {
9733 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9734 })
9735 })
9736 .collect::<Result<Vec<_>, _>>()
9737 .log_err()
9738 else {
9739 continue;
9740 };
9741
9742 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9743 buffer
9744 .language_settings_at(Point::new(start_row, 0), cx)
9745 .preferred_line_length as usize
9746 });
9747 let wrapped_text = wrap_with_prefix(
9748 line_prefix,
9749 lines_without_prefixes.join("\n"),
9750 wrap_column,
9751 tab_size,
9752 options.preserve_existing_whitespace,
9753 );
9754
9755 // TODO: should always use char-based diff while still supporting cursor behavior that
9756 // matches vim.
9757 let mut diff_options = DiffOptions::default();
9758 if options.override_language_settings {
9759 diff_options.max_word_diff_len = 0;
9760 diff_options.max_word_diff_line_count = 0;
9761 } else {
9762 diff_options.max_word_diff_len = usize::MAX;
9763 diff_options.max_word_diff_line_count = usize::MAX;
9764 }
9765
9766 for (old_range, new_text) in
9767 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9768 {
9769 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9770 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9771 edits.push((edit_start..edit_end, new_text));
9772 }
9773
9774 rewrapped_row_ranges.push(start_row..=end_row);
9775 }
9776
9777 self.buffer
9778 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9779 }
9780
9781 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9782 let mut text = String::new();
9783 let buffer = self.buffer.read(cx).snapshot(cx);
9784 let mut selections = self.selections.all::<Point>(cx);
9785 let mut clipboard_selections = Vec::with_capacity(selections.len());
9786 {
9787 let max_point = buffer.max_point();
9788 let mut is_first = true;
9789 for selection in &mut selections {
9790 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9791 if is_entire_line {
9792 selection.start = Point::new(selection.start.row, 0);
9793 if !selection.is_empty() && selection.end.column == 0 {
9794 selection.end = cmp::min(max_point, selection.end);
9795 } else {
9796 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9797 }
9798 selection.goal = SelectionGoal::None;
9799 }
9800 if is_first {
9801 is_first = false;
9802 } else {
9803 text += "\n";
9804 }
9805 let mut len = 0;
9806 for chunk in buffer.text_for_range(selection.start..selection.end) {
9807 text.push_str(chunk);
9808 len += chunk.len();
9809 }
9810 clipboard_selections.push(ClipboardSelection {
9811 len,
9812 is_entire_line,
9813 first_line_indent: buffer
9814 .indent_size_for_line(MultiBufferRow(selection.start.row))
9815 .len,
9816 });
9817 }
9818 }
9819
9820 self.transact(window, cx, |this, window, cx| {
9821 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9822 s.select(selections);
9823 });
9824 this.insert("", window, cx);
9825 });
9826 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9827 }
9828
9829 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9830 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9831 let item = self.cut_common(window, cx);
9832 cx.write_to_clipboard(item);
9833 }
9834
9835 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9836 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9837 self.change_selections(None, window, cx, |s| {
9838 s.move_with(|snapshot, sel| {
9839 if sel.is_empty() {
9840 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9841 }
9842 });
9843 });
9844 let item = self.cut_common(window, cx);
9845 cx.set_global(KillRing(item))
9846 }
9847
9848 pub fn kill_ring_yank(
9849 &mut self,
9850 _: &KillRingYank,
9851 window: &mut Window,
9852 cx: &mut Context<Self>,
9853 ) {
9854 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9855 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9856 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9857 (kill_ring.text().to_string(), kill_ring.metadata_json())
9858 } else {
9859 return;
9860 }
9861 } else {
9862 return;
9863 };
9864 self.do_paste(&text, metadata, false, window, cx);
9865 }
9866
9867 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9868 self.do_copy(true, cx);
9869 }
9870
9871 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9872 self.do_copy(false, cx);
9873 }
9874
9875 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9876 let selections = self.selections.all::<Point>(cx);
9877 let buffer = self.buffer.read(cx).read(cx);
9878 let mut text = String::new();
9879
9880 let mut clipboard_selections = Vec::with_capacity(selections.len());
9881 {
9882 let max_point = buffer.max_point();
9883 let mut is_first = true;
9884 for selection in &selections {
9885 let mut start = selection.start;
9886 let mut end = selection.end;
9887 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9888 if is_entire_line {
9889 start = Point::new(start.row, 0);
9890 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9891 }
9892
9893 let mut trimmed_selections = Vec::new();
9894 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9895 let row = MultiBufferRow(start.row);
9896 let first_indent = buffer.indent_size_for_line(row);
9897 if first_indent.len == 0 || start.column > first_indent.len {
9898 trimmed_selections.push(start..end);
9899 } else {
9900 trimmed_selections.push(
9901 Point::new(row.0, first_indent.len)
9902 ..Point::new(row.0, buffer.line_len(row)),
9903 );
9904 for row in start.row + 1..=end.row {
9905 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
9906 if row_indent_size.len >= first_indent.len {
9907 trimmed_selections.push(
9908 Point::new(row, first_indent.len)
9909 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
9910 );
9911 } else {
9912 trimmed_selections.clear();
9913 trimmed_selections.push(start..end);
9914 break;
9915 }
9916 }
9917 }
9918 } else {
9919 trimmed_selections.push(start..end);
9920 }
9921
9922 for trimmed_range in trimmed_selections {
9923 if is_first {
9924 is_first = false;
9925 } else {
9926 text += "\n";
9927 }
9928 let mut len = 0;
9929 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
9930 text.push_str(chunk);
9931 len += chunk.len();
9932 }
9933 clipboard_selections.push(ClipboardSelection {
9934 len,
9935 is_entire_line,
9936 first_line_indent: buffer
9937 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
9938 .len,
9939 });
9940 }
9941 }
9942 }
9943
9944 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9945 text,
9946 clipboard_selections,
9947 ));
9948 }
9949
9950 pub fn do_paste(
9951 &mut self,
9952 text: &String,
9953 clipboard_selections: Option<Vec<ClipboardSelection>>,
9954 handle_entire_lines: bool,
9955 window: &mut Window,
9956 cx: &mut Context<Self>,
9957 ) {
9958 if self.read_only(cx) {
9959 return;
9960 }
9961
9962 let clipboard_text = Cow::Borrowed(text);
9963
9964 self.transact(window, cx, |this, window, cx| {
9965 if let Some(mut clipboard_selections) = clipboard_selections {
9966 let old_selections = this.selections.all::<usize>(cx);
9967 let all_selections_were_entire_line =
9968 clipboard_selections.iter().all(|s| s.is_entire_line);
9969 let first_selection_indent_column =
9970 clipboard_selections.first().map(|s| s.first_line_indent);
9971 if clipboard_selections.len() != old_selections.len() {
9972 clipboard_selections.drain(..);
9973 }
9974 let cursor_offset = this.selections.last::<usize>(cx).head();
9975 let mut auto_indent_on_paste = true;
9976
9977 this.buffer.update(cx, |buffer, cx| {
9978 let snapshot = buffer.read(cx);
9979 auto_indent_on_paste = snapshot
9980 .language_settings_at(cursor_offset, cx)
9981 .auto_indent_on_paste;
9982
9983 let mut start_offset = 0;
9984 let mut edits = Vec::new();
9985 let mut original_indent_columns = Vec::new();
9986 for (ix, selection) in old_selections.iter().enumerate() {
9987 let to_insert;
9988 let entire_line;
9989 let original_indent_column;
9990 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
9991 let end_offset = start_offset + clipboard_selection.len;
9992 to_insert = &clipboard_text[start_offset..end_offset];
9993 entire_line = clipboard_selection.is_entire_line;
9994 start_offset = end_offset + 1;
9995 original_indent_column = Some(clipboard_selection.first_line_indent);
9996 } else {
9997 to_insert = clipboard_text.as_str();
9998 entire_line = all_selections_were_entire_line;
9999 original_indent_column = first_selection_indent_column
10000 }
10001
10002 // If the corresponding selection was empty when this slice of the
10003 // clipboard text was written, then the entire line containing the
10004 // selection was copied. If this selection is also currently empty,
10005 // then paste the line before the current line of the buffer.
10006 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10007 let column = selection.start.to_point(&snapshot).column as usize;
10008 let line_start = selection.start - column;
10009 line_start..line_start
10010 } else {
10011 selection.range()
10012 };
10013
10014 edits.push((range, to_insert));
10015 original_indent_columns.push(original_indent_column);
10016 }
10017 drop(snapshot);
10018
10019 buffer.edit(
10020 edits,
10021 if auto_indent_on_paste {
10022 Some(AutoindentMode::Block {
10023 original_indent_columns,
10024 })
10025 } else {
10026 None
10027 },
10028 cx,
10029 );
10030 });
10031
10032 let selections = this.selections.all::<usize>(cx);
10033 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10034 s.select(selections)
10035 });
10036 } else {
10037 this.insert(&clipboard_text, window, cx);
10038 }
10039 });
10040 }
10041
10042 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10043 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10044 if let Some(item) = cx.read_from_clipboard() {
10045 let entries = item.entries();
10046
10047 match entries.first() {
10048 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10049 // of all the pasted entries.
10050 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10051 .do_paste(
10052 clipboard_string.text(),
10053 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10054 true,
10055 window,
10056 cx,
10057 ),
10058 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10059 }
10060 }
10061 }
10062
10063 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10064 if self.read_only(cx) {
10065 return;
10066 }
10067
10068 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10069
10070 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10071 if let Some((selections, _)) =
10072 self.selection_history.transaction(transaction_id).cloned()
10073 {
10074 self.change_selections(None, window, cx, |s| {
10075 s.select_anchors(selections.to_vec());
10076 });
10077 } else {
10078 log::error!(
10079 "No entry in selection_history found for undo. \
10080 This may correspond to a bug where undo does not update the selection. \
10081 If this is occurring, please add details to \
10082 https://github.com/zed-industries/zed/issues/22692"
10083 );
10084 }
10085 self.request_autoscroll(Autoscroll::fit(), cx);
10086 self.unmark_text(window, cx);
10087 self.refresh_inline_completion(true, false, window, cx);
10088 cx.emit(EditorEvent::Edited { transaction_id });
10089 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10090 }
10091 }
10092
10093 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10094 if self.read_only(cx) {
10095 return;
10096 }
10097
10098 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10099
10100 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10101 if let Some((_, Some(selections))) =
10102 self.selection_history.transaction(transaction_id).cloned()
10103 {
10104 self.change_selections(None, window, cx, |s| {
10105 s.select_anchors(selections.to_vec());
10106 });
10107 } else {
10108 log::error!(
10109 "No entry in selection_history found for redo. \
10110 This may correspond to a bug where undo does not update the selection. \
10111 If this is occurring, please add details to \
10112 https://github.com/zed-industries/zed/issues/22692"
10113 );
10114 }
10115 self.request_autoscroll(Autoscroll::fit(), cx);
10116 self.unmark_text(window, cx);
10117 self.refresh_inline_completion(true, false, window, cx);
10118 cx.emit(EditorEvent::Edited { transaction_id });
10119 }
10120 }
10121
10122 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10123 self.buffer
10124 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10125 }
10126
10127 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10128 self.buffer
10129 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10130 }
10131
10132 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10133 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10134 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10135 s.move_with(|map, selection| {
10136 let cursor = if selection.is_empty() {
10137 movement::left(map, selection.start)
10138 } else {
10139 selection.start
10140 };
10141 selection.collapse_to(cursor, SelectionGoal::None);
10142 });
10143 })
10144 }
10145
10146 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10147 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10148 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10149 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10150 })
10151 }
10152
10153 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10154 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10155 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10156 s.move_with(|map, selection| {
10157 let cursor = if selection.is_empty() {
10158 movement::right(map, selection.end)
10159 } else {
10160 selection.end
10161 };
10162 selection.collapse_to(cursor, SelectionGoal::None)
10163 });
10164 })
10165 }
10166
10167 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10168 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10169 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10170 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10171 })
10172 }
10173
10174 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10175 if self.take_rename(true, window, cx).is_some() {
10176 return;
10177 }
10178
10179 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10180 cx.propagate();
10181 return;
10182 }
10183
10184 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10185
10186 let text_layout_details = &self.text_layout_details(window);
10187 let selection_count = self.selections.count();
10188 let first_selection = self.selections.first_anchor();
10189
10190 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10191 s.move_with(|map, selection| {
10192 if !selection.is_empty() {
10193 selection.goal = SelectionGoal::None;
10194 }
10195 let (cursor, goal) = movement::up(
10196 map,
10197 selection.start,
10198 selection.goal,
10199 false,
10200 text_layout_details,
10201 );
10202 selection.collapse_to(cursor, goal);
10203 });
10204 });
10205
10206 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10207 {
10208 cx.propagate();
10209 }
10210 }
10211
10212 pub fn move_up_by_lines(
10213 &mut self,
10214 action: &MoveUpByLines,
10215 window: &mut Window,
10216 cx: &mut Context<Self>,
10217 ) {
10218 if self.take_rename(true, window, cx).is_some() {
10219 return;
10220 }
10221
10222 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10223 cx.propagate();
10224 return;
10225 }
10226
10227 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10228
10229 let text_layout_details = &self.text_layout_details(window);
10230
10231 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10232 s.move_with(|map, selection| {
10233 if !selection.is_empty() {
10234 selection.goal = SelectionGoal::None;
10235 }
10236 let (cursor, goal) = movement::up_by_rows(
10237 map,
10238 selection.start,
10239 action.lines,
10240 selection.goal,
10241 false,
10242 text_layout_details,
10243 );
10244 selection.collapse_to(cursor, goal);
10245 });
10246 })
10247 }
10248
10249 pub fn move_down_by_lines(
10250 &mut self,
10251 action: &MoveDownByLines,
10252 window: &mut Window,
10253 cx: &mut Context<Self>,
10254 ) {
10255 if self.take_rename(true, window, cx).is_some() {
10256 return;
10257 }
10258
10259 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10260 cx.propagate();
10261 return;
10262 }
10263
10264 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10265
10266 let text_layout_details = &self.text_layout_details(window);
10267
10268 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10269 s.move_with(|map, selection| {
10270 if !selection.is_empty() {
10271 selection.goal = SelectionGoal::None;
10272 }
10273 let (cursor, goal) = movement::down_by_rows(
10274 map,
10275 selection.start,
10276 action.lines,
10277 selection.goal,
10278 false,
10279 text_layout_details,
10280 );
10281 selection.collapse_to(cursor, goal);
10282 });
10283 })
10284 }
10285
10286 pub fn select_down_by_lines(
10287 &mut self,
10288 action: &SelectDownByLines,
10289 window: &mut Window,
10290 cx: &mut Context<Self>,
10291 ) {
10292 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10293 let text_layout_details = &self.text_layout_details(window);
10294 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10295 s.move_heads_with(|map, head, goal| {
10296 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10297 })
10298 })
10299 }
10300
10301 pub fn select_up_by_lines(
10302 &mut self,
10303 action: &SelectUpByLines,
10304 window: &mut Window,
10305 cx: &mut Context<Self>,
10306 ) {
10307 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10308 let text_layout_details = &self.text_layout_details(window);
10309 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10310 s.move_heads_with(|map, head, goal| {
10311 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10312 })
10313 })
10314 }
10315
10316 pub fn select_page_up(
10317 &mut self,
10318 _: &SelectPageUp,
10319 window: &mut Window,
10320 cx: &mut Context<Self>,
10321 ) {
10322 let Some(row_count) = self.visible_row_count() else {
10323 return;
10324 };
10325
10326 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10327
10328 let text_layout_details = &self.text_layout_details(window);
10329
10330 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10331 s.move_heads_with(|map, head, goal| {
10332 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10333 })
10334 })
10335 }
10336
10337 pub fn move_page_up(
10338 &mut self,
10339 action: &MovePageUp,
10340 window: &mut Window,
10341 cx: &mut Context<Self>,
10342 ) {
10343 if self.take_rename(true, window, cx).is_some() {
10344 return;
10345 }
10346
10347 if self
10348 .context_menu
10349 .borrow_mut()
10350 .as_mut()
10351 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10352 .unwrap_or(false)
10353 {
10354 return;
10355 }
10356
10357 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10358 cx.propagate();
10359 return;
10360 }
10361
10362 let Some(row_count) = self.visible_row_count() else {
10363 return;
10364 };
10365
10366 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10367
10368 let autoscroll = if action.center_cursor {
10369 Autoscroll::center()
10370 } else {
10371 Autoscroll::fit()
10372 };
10373
10374 let text_layout_details = &self.text_layout_details(window);
10375
10376 self.change_selections(Some(autoscroll), window, cx, |s| {
10377 s.move_with(|map, selection| {
10378 if !selection.is_empty() {
10379 selection.goal = SelectionGoal::None;
10380 }
10381 let (cursor, goal) = movement::up_by_rows(
10382 map,
10383 selection.end,
10384 row_count,
10385 selection.goal,
10386 false,
10387 text_layout_details,
10388 );
10389 selection.collapse_to(cursor, goal);
10390 });
10391 });
10392 }
10393
10394 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10395 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10396 let text_layout_details = &self.text_layout_details(window);
10397 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10398 s.move_heads_with(|map, head, goal| {
10399 movement::up(map, head, goal, false, text_layout_details)
10400 })
10401 })
10402 }
10403
10404 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10405 self.take_rename(true, window, cx);
10406
10407 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10408 cx.propagate();
10409 return;
10410 }
10411
10412 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10413
10414 let text_layout_details = &self.text_layout_details(window);
10415 let selection_count = self.selections.count();
10416 let first_selection = self.selections.first_anchor();
10417
10418 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10419 s.move_with(|map, selection| {
10420 if !selection.is_empty() {
10421 selection.goal = SelectionGoal::None;
10422 }
10423 let (cursor, goal) = movement::down(
10424 map,
10425 selection.end,
10426 selection.goal,
10427 false,
10428 text_layout_details,
10429 );
10430 selection.collapse_to(cursor, goal);
10431 });
10432 });
10433
10434 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10435 {
10436 cx.propagate();
10437 }
10438 }
10439
10440 pub fn select_page_down(
10441 &mut self,
10442 _: &SelectPageDown,
10443 window: &mut Window,
10444 cx: &mut Context<Self>,
10445 ) {
10446 let Some(row_count) = self.visible_row_count() else {
10447 return;
10448 };
10449
10450 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10451
10452 let text_layout_details = &self.text_layout_details(window);
10453
10454 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10455 s.move_heads_with(|map, head, goal| {
10456 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10457 })
10458 })
10459 }
10460
10461 pub fn move_page_down(
10462 &mut self,
10463 action: &MovePageDown,
10464 window: &mut Window,
10465 cx: &mut Context<Self>,
10466 ) {
10467 if self.take_rename(true, window, cx).is_some() {
10468 return;
10469 }
10470
10471 if self
10472 .context_menu
10473 .borrow_mut()
10474 .as_mut()
10475 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10476 .unwrap_or(false)
10477 {
10478 return;
10479 }
10480
10481 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10482 cx.propagate();
10483 return;
10484 }
10485
10486 let Some(row_count) = self.visible_row_count() else {
10487 return;
10488 };
10489
10490 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10491
10492 let autoscroll = if action.center_cursor {
10493 Autoscroll::center()
10494 } else {
10495 Autoscroll::fit()
10496 };
10497
10498 let text_layout_details = &self.text_layout_details(window);
10499 self.change_selections(Some(autoscroll), window, cx, |s| {
10500 s.move_with(|map, selection| {
10501 if !selection.is_empty() {
10502 selection.goal = SelectionGoal::None;
10503 }
10504 let (cursor, goal) = movement::down_by_rows(
10505 map,
10506 selection.end,
10507 row_count,
10508 selection.goal,
10509 false,
10510 text_layout_details,
10511 );
10512 selection.collapse_to(cursor, goal);
10513 });
10514 });
10515 }
10516
10517 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10518 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10519 let text_layout_details = &self.text_layout_details(window);
10520 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10521 s.move_heads_with(|map, head, goal| {
10522 movement::down(map, head, goal, false, text_layout_details)
10523 })
10524 });
10525 }
10526
10527 pub fn context_menu_first(
10528 &mut self,
10529 _: &ContextMenuFirst,
10530 _window: &mut Window,
10531 cx: &mut Context<Self>,
10532 ) {
10533 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10534 context_menu.select_first(self.completion_provider.as_deref(), cx);
10535 }
10536 }
10537
10538 pub fn context_menu_prev(
10539 &mut self,
10540 _: &ContextMenuPrevious,
10541 _window: &mut Window,
10542 cx: &mut Context<Self>,
10543 ) {
10544 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10545 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10546 }
10547 }
10548
10549 pub fn context_menu_next(
10550 &mut self,
10551 _: &ContextMenuNext,
10552 _window: &mut Window,
10553 cx: &mut Context<Self>,
10554 ) {
10555 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10556 context_menu.select_next(self.completion_provider.as_deref(), cx);
10557 }
10558 }
10559
10560 pub fn context_menu_last(
10561 &mut self,
10562 _: &ContextMenuLast,
10563 _window: &mut Window,
10564 cx: &mut Context<Self>,
10565 ) {
10566 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10567 context_menu.select_last(self.completion_provider.as_deref(), cx);
10568 }
10569 }
10570
10571 pub fn move_to_previous_word_start(
10572 &mut self,
10573 _: &MoveToPreviousWordStart,
10574 window: &mut Window,
10575 cx: &mut Context<Self>,
10576 ) {
10577 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10578 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10579 s.move_cursors_with(|map, head, _| {
10580 (
10581 movement::previous_word_start(map, head),
10582 SelectionGoal::None,
10583 )
10584 });
10585 })
10586 }
10587
10588 pub fn move_to_previous_subword_start(
10589 &mut self,
10590 _: &MoveToPreviousSubwordStart,
10591 window: &mut Window,
10592 cx: &mut Context<Self>,
10593 ) {
10594 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10595 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10596 s.move_cursors_with(|map, head, _| {
10597 (
10598 movement::previous_subword_start(map, head),
10599 SelectionGoal::None,
10600 )
10601 });
10602 })
10603 }
10604
10605 pub fn select_to_previous_word_start(
10606 &mut self,
10607 _: &SelectToPreviousWordStart,
10608 window: &mut Window,
10609 cx: &mut Context<Self>,
10610 ) {
10611 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10612 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10613 s.move_heads_with(|map, head, _| {
10614 (
10615 movement::previous_word_start(map, head),
10616 SelectionGoal::None,
10617 )
10618 });
10619 })
10620 }
10621
10622 pub fn select_to_previous_subword_start(
10623 &mut self,
10624 _: &SelectToPreviousSubwordStart,
10625 window: &mut Window,
10626 cx: &mut Context<Self>,
10627 ) {
10628 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10629 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10630 s.move_heads_with(|map, head, _| {
10631 (
10632 movement::previous_subword_start(map, head),
10633 SelectionGoal::None,
10634 )
10635 });
10636 })
10637 }
10638
10639 pub fn delete_to_previous_word_start(
10640 &mut self,
10641 action: &DeleteToPreviousWordStart,
10642 window: &mut Window,
10643 cx: &mut Context<Self>,
10644 ) {
10645 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10646 self.transact(window, cx, |this, window, cx| {
10647 this.select_autoclose_pair(window, cx);
10648 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10649 s.move_with(|map, selection| {
10650 if selection.is_empty() {
10651 let cursor = if action.ignore_newlines {
10652 movement::previous_word_start(map, selection.head())
10653 } else {
10654 movement::previous_word_start_or_newline(map, selection.head())
10655 };
10656 selection.set_head(cursor, SelectionGoal::None);
10657 }
10658 });
10659 });
10660 this.insert("", window, cx);
10661 });
10662 }
10663
10664 pub fn delete_to_previous_subword_start(
10665 &mut self,
10666 _: &DeleteToPreviousSubwordStart,
10667 window: &mut Window,
10668 cx: &mut Context<Self>,
10669 ) {
10670 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10671 self.transact(window, cx, |this, window, cx| {
10672 this.select_autoclose_pair(window, cx);
10673 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10674 s.move_with(|map, selection| {
10675 if selection.is_empty() {
10676 let cursor = movement::previous_subword_start(map, selection.head());
10677 selection.set_head(cursor, SelectionGoal::None);
10678 }
10679 });
10680 });
10681 this.insert("", window, cx);
10682 });
10683 }
10684
10685 pub fn move_to_next_word_end(
10686 &mut self,
10687 _: &MoveToNextWordEnd,
10688 window: &mut Window,
10689 cx: &mut Context<Self>,
10690 ) {
10691 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10692 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10693 s.move_cursors_with(|map, head, _| {
10694 (movement::next_word_end(map, head), SelectionGoal::None)
10695 });
10696 })
10697 }
10698
10699 pub fn move_to_next_subword_end(
10700 &mut self,
10701 _: &MoveToNextSubwordEnd,
10702 window: &mut Window,
10703 cx: &mut Context<Self>,
10704 ) {
10705 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10706 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10707 s.move_cursors_with(|map, head, _| {
10708 (movement::next_subword_end(map, head), SelectionGoal::None)
10709 });
10710 })
10711 }
10712
10713 pub fn select_to_next_word_end(
10714 &mut self,
10715 _: &SelectToNextWordEnd,
10716 window: &mut Window,
10717 cx: &mut Context<Self>,
10718 ) {
10719 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10720 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10721 s.move_heads_with(|map, head, _| {
10722 (movement::next_word_end(map, head), SelectionGoal::None)
10723 });
10724 })
10725 }
10726
10727 pub fn select_to_next_subword_end(
10728 &mut self,
10729 _: &SelectToNextSubwordEnd,
10730 window: &mut Window,
10731 cx: &mut Context<Self>,
10732 ) {
10733 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10734 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10735 s.move_heads_with(|map, head, _| {
10736 (movement::next_subword_end(map, head), SelectionGoal::None)
10737 });
10738 })
10739 }
10740
10741 pub fn delete_to_next_word_end(
10742 &mut self,
10743 action: &DeleteToNextWordEnd,
10744 window: &mut Window,
10745 cx: &mut Context<Self>,
10746 ) {
10747 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10748 self.transact(window, cx, |this, window, cx| {
10749 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10750 s.move_with(|map, selection| {
10751 if selection.is_empty() {
10752 let cursor = if action.ignore_newlines {
10753 movement::next_word_end(map, selection.head())
10754 } else {
10755 movement::next_word_end_or_newline(map, selection.head())
10756 };
10757 selection.set_head(cursor, SelectionGoal::None);
10758 }
10759 });
10760 });
10761 this.insert("", window, cx);
10762 });
10763 }
10764
10765 pub fn delete_to_next_subword_end(
10766 &mut self,
10767 _: &DeleteToNextSubwordEnd,
10768 window: &mut Window,
10769 cx: &mut Context<Self>,
10770 ) {
10771 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10772 self.transact(window, cx, |this, window, cx| {
10773 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10774 s.move_with(|map, selection| {
10775 if selection.is_empty() {
10776 let cursor = movement::next_subword_end(map, selection.head());
10777 selection.set_head(cursor, SelectionGoal::None);
10778 }
10779 });
10780 });
10781 this.insert("", window, cx);
10782 });
10783 }
10784
10785 pub fn move_to_beginning_of_line(
10786 &mut self,
10787 action: &MoveToBeginningOfLine,
10788 window: &mut Window,
10789 cx: &mut Context<Self>,
10790 ) {
10791 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10792 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10793 s.move_cursors_with(|map, head, _| {
10794 (
10795 movement::indented_line_beginning(
10796 map,
10797 head,
10798 action.stop_at_soft_wraps,
10799 action.stop_at_indent,
10800 ),
10801 SelectionGoal::None,
10802 )
10803 });
10804 })
10805 }
10806
10807 pub fn select_to_beginning_of_line(
10808 &mut self,
10809 action: &SelectToBeginningOfLine,
10810 window: &mut Window,
10811 cx: &mut Context<Self>,
10812 ) {
10813 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10814 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10815 s.move_heads_with(|map, head, _| {
10816 (
10817 movement::indented_line_beginning(
10818 map,
10819 head,
10820 action.stop_at_soft_wraps,
10821 action.stop_at_indent,
10822 ),
10823 SelectionGoal::None,
10824 )
10825 });
10826 });
10827 }
10828
10829 pub fn delete_to_beginning_of_line(
10830 &mut self,
10831 action: &DeleteToBeginningOfLine,
10832 window: &mut Window,
10833 cx: &mut Context<Self>,
10834 ) {
10835 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10836 self.transact(window, cx, |this, window, cx| {
10837 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10838 s.move_with(|_, selection| {
10839 selection.reversed = true;
10840 });
10841 });
10842
10843 this.select_to_beginning_of_line(
10844 &SelectToBeginningOfLine {
10845 stop_at_soft_wraps: false,
10846 stop_at_indent: action.stop_at_indent,
10847 },
10848 window,
10849 cx,
10850 );
10851 this.backspace(&Backspace, window, cx);
10852 });
10853 }
10854
10855 pub fn move_to_end_of_line(
10856 &mut self,
10857 action: &MoveToEndOfLine,
10858 window: &mut Window,
10859 cx: &mut Context<Self>,
10860 ) {
10861 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10862 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10863 s.move_cursors_with(|map, head, _| {
10864 (
10865 movement::line_end(map, head, action.stop_at_soft_wraps),
10866 SelectionGoal::None,
10867 )
10868 });
10869 })
10870 }
10871
10872 pub fn select_to_end_of_line(
10873 &mut self,
10874 action: &SelectToEndOfLine,
10875 window: &mut Window,
10876 cx: &mut Context<Self>,
10877 ) {
10878 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10879 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10880 s.move_heads_with(|map, head, _| {
10881 (
10882 movement::line_end(map, head, action.stop_at_soft_wraps),
10883 SelectionGoal::None,
10884 )
10885 });
10886 })
10887 }
10888
10889 pub fn delete_to_end_of_line(
10890 &mut self,
10891 _: &DeleteToEndOfLine,
10892 window: &mut Window,
10893 cx: &mut Context<Self>,
10894 ) {
10895 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10896 self.transact(window, cx, |this, window, cx| {
10897 this.select_to_end_of_line(
10898 &SelectToEndOfLine {
10899 stop_at_soft_wraps: false,
10900 },
10901 window,
10902 cx,
10903 );
10904 this.delete(&Delete, window, cx);
10905 });
10906 }
10907
10908 pub fn cut_to_end_of_line(
10909 &mut self,
10910 _: &CutToEndOfLine,
10911 window: &mut Window,
10912 cx: &mut Context<Self>,
10913 ) {
10914 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10915 self.transact(window, cx, |this, window, cx| {
10916 this.select_to_end_of_line(
10917 &SelectToEndOfLine {
10918 stop_at_soft_wraps: false,
10919 },
10920 window,
10921 cx,
10922 );
10923 this.cut(&Cut, window, cx);
10924 });
10925 }
10926
10927 pub fn move_to_start_of_paragraph(
10928 &mut self,
10929 _: &MoveToStartOfParagraph,
10930 window: &mut Window,
10931 cx: &mut Context<Self>,
10932 ) {
10933 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10934 cx.propagate();
10935 return;
10936 }
10937 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10938 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10939 s.move_with(|map, selection| {
10940 selection.collapse_to(
10941 movement::start_of_paragraph(map, selection.head(), 1),
10942 SelectionGoal::None,
10943 )
10944 });
10945 })
10946 }
10947
10948 pub fn move_to_end_of_paragraph(
10949 &mut self,
10950 _: &MoveToEndOfParagraph,
10951 window: &mut Window,
10952 cx: &mut Context<Self>,
10953 ) {
10954 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10955 cx.propagate();
10956 return;
10957 }
10958 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10959 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10960 s.move_with(|map, selection| {
10961 selection.collapse_to(
10962 movement::end_of_paragraph(map, selection.head(), 1),
10963 SelectionGoal::None,
10964 )
10965 });
10966 })
10967 }
10968
10969 pub fn select_to_start_of_paragraph(
10970 &mut self,
10971 _: &SelectToStartOfParagraph,
10972 window: &mut Window,
10973 cx: &mut Context<Self>,
10974 ) {
10975 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10976 cx.propagate();
10977 return;
10978 }
10979 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10980 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10981 s.move_heads_with(|map, head, _| {
10982 (
10983 movement::start_of_paragraph(map, head, 1),
10984 SelectionGoal::None,
10985 )
10986 });
10987 })
10988 }
10989
10990 pub fn select_to_end_of_paragraph(
10991 &mut self,
10992 _: &SelectToEndOfParagraph,
10993 window: &mut Window,
10994 cx: &mut Context<Self>,
10995 ) {
10996 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10997 cx.propagate();
10998 return;
10999 }
11000 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11001 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11002 s.move_heads_with(|map, head, _| {
11003 (
11004 movement::end_of_paragraph(map, head, 1),
11005 SelectionGoal::None,
11006 )
11007 });
11008 })
11009 }
11010
11011 pub fn move_to_start_of_excerpt(
11012 &mut self,
11013 _: &MoveToStartOfExcerpt,
11014 window: &mut Window,
11015 cx: &mut Context<Self>,
11016 ) {
11017 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11018 cx.propagate();
11019 return;
11020 }
11021 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11022 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11023 s.move_with(|map, selection| {
11024 selection.collapse_to(
11025 movement::start_of_excerpt(
11026 map,
11027 selection.head(),
11028 workspace::searchable::Direction::Prev,
11029 ),
11030 SelectionGoal::None,
11031 )
11032 });
11033 })
11034 }
11035
11036 pub fn move_to_start_of_next_excerpt(
11037 &mut self,
11038 _: &MoveToStartOfNextExcerpt,
11039 window: &mut Window,
11040 cx: &mut Context<Self>,
11041 ) {
11042 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11043 cx.propagate();
11044 return;
11045 }
11046
11047 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11048 s.move_with(|map, selection| {
11049 selection.collapse_to(
11050 movement::start_of_excerpt(
11051 map,
11052 selection.head(),
11053 workspace::searchable::Direction::Next,
11054 ),
11055 SelectionGoal::None,
11056 )
11057 });
11058 })
11059 }
11060
11061 pub fn move_to_end_of_excerpt(
11062 &mut self,
11063 _: &MoveToEndOfExcerpt,
11064 window: &mut Window,
11065 cx: &mut Context<Self>,
11066 ) {
11067 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11068 cx.propagate();
11069 return;
11070 }
11071 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11072 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11073 s.move_with(|map, selection| {
11074 selection.collapse_to(
11075 movement::end_of_excerpt(
11076 map,
11077 selection.head(),
11078 workspace::searchable::Direction::Next,
11079 ),
11080 SelectionGoal::None,
11081 )
11082 });
11083 })
11084 }
11085
11086 pub fn move_to_end_of_previous_excerpt(
11087 &mut self,
11088 _: &MoveToEndOfPreviousExcerpt,
11089 window: &mut Window,
11090 cx: &mut Context<Self>,
11091 ) {
11092 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11093 cx.propagate();
11094 return;
11095 }
11096 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11097 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11098 s.move_with(|map, selection| {
11099 selection.collapse_to(
11100 movement::end_of_excerpt(
11101 map,
11102 selection.head(),
11103 workspace::searchable::Direction::Prev,
11104 ),
11105 SelectionGoal::None,
11106 )
11107 });
11108 })
11109 }
11110
11111 pub fn select_to_start_of_excerpt(
11112 &mut self,
11113 _: &SelectToStartOfExcerpt,
11114 window: &mut Window,
11115 cx: &mut Context<Self>,
11116 ) {
11117 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11118 cx.propagate();
11119 return;
11120 }
11121 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11122 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11123 s.move_heads_with(|map, head, _| {
11124 (
11125 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11126 SelectionGoal::None,
11127 )
11128 });
11129 })
11130 }
11131
11132 pub fn select_to_start_of_next_excerpt(
11133 &mut self,
11134 _: &SelectToStartOfNextExcerpt,
11135 window: &mut Window,
11136 cx: &mut Context<Self>,
11137 ) {
11138 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11139 cx.propagate();
11140 return;
11141 }
11142 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11143 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11144 s.move_heads_with(|map, head, _| {
11145 (
11146 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11147 SelectionGoal::None,
11148 )
11149 });
11150 })
11151 }
11152
11153 pub fn select_to_end_of_excerpt(
11154 &mut self,
11155 _: &SelectToEndOfExcerpt,
11156 window: &mut Window,
11157 cx: &mut Context<Self>,
11158 ) {
11159 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11160 cx.propagate();
11161 return;
11162 }
11163 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11165 s.move_heads_with(|map, head, _| {
11166 (
11167 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11168 SelectionGoal::None,
11169 )
11170 });
11171 })
11172 }
11173
11174 pub fn select_to_end_of_previous_excerpt(
11175 &mut self,
11176 _: &SelectToEndOfPreviousExcerpt,
11177 window: &mut Window,
11178 cx: &mut Context<Self>,
11179 ) {
11180 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11181 cx.propagate();
11182 return;
11183 }
11184 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11185 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11186 s.move_heads_with(|map, head, _| {
11187 (
11188 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11189 SelectionGoal::None,
11190 )
11191 });
11192 })
11193 }
11194
11195 pub fn move_to_beginning(
11196 &mut self,
11197 _: &MoveToBeginning,
11198 window: &mut Window,
11199 cx: &mut Context<Self>,
11200 ) {
11201 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11202 cx.propagate();
11203 return;
11204 }
11205 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11206 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11207 s.select_ranges(vec![0..0]);
11208 });
11209 }
11210
11211 pub fn select_to_beginning(
11212 &mut self,
11213 _: &SelectToBeginning,
11214 window: &mut Window,
11215 cx: &mut Context<Self>,
11216 ) {
11217 let mut selection = self.selections.last::<Point>(cx);
11218 selection.set_head(Point::zero(), SelectionGoal::None);
11219 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11220 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11221 s.select(vec![selection]);
11222 });
11223 }
11224
11225 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11226 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11227 cx.propagate();
11228 return;
11229 }
11230 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11231 let cursor = self.buffer.read(cx).read(cx).len();
11232 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11233 s.select_ranges(vec![cursor..cursor])
11234 });
11235 }
11236
11237 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11238 self.nav_history = nav_history;
11239 }
11240
11241 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11242 self.nav_history.as_ref()
11243 }
11244
11245 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11246 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11247 }
11248
11249 fn push_to_nav_history(
11250 &mut self,
11251 cursor_anchor: Anchor,
11252 new_position: Option<Point>,
11253 is_deactivate: bool,
11254 cx: &mut Context<Self>,
11255 ) {
11256 if let Some(nav_history) = self.nav_history.as_mut() {
11257 let buffer = self.buffer.read(cx).read(cx);
11258 let cursor_position = cursor_anchor.to_point(&buffer);
11259 let scroll_state = self.scroll_manager.anchor();
11260 let scroll_top_row = scroll_state.top_row(&buffer);
11261 drop(buffer);
11262
11263 if let Some(new_position) = new_position {
11264 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11265 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11266 return;
11267 }
11268 }
11269
11270 nav_history.push(
11271 Some(NavigationData {
11272 cursor_anchor,
11273 cursor_position,
11274 scroll_anchor: scroll_state,
11275 scroll_top_row,
11276 }),
11277 cx,
11278 );
11279 cx.emit(EditorEvent::PushedToNavHistory {
11280 anchor: cursor_anchor,
11281 is_deactivate,
11282 })
11283 }
11284 }
11285
11286 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11287 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11288 let buffer = self.buffer.read(cx).snapshot(cx);
11289 let mut selection = self.selections.first::<usize>(cx);
11290 selection.set_head(buffer.len(), SelectionGoal::None);
11291 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11292 s.select(vec![selection]);
11293 });
11294 }
11295
11296 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11297 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11298 let end = self.buffer.read(cx).read(cx).len();
11299 self.change_selections(None, window, cx, |s| {
11300 s.select_ranges(vec![0..end]);
11301 });
11302 }
11303
11304 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11305 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11306 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11307 let mut selections = self.selections.all::<Point>(cx);
11308 let max_point = display_map.buffer_snapshot.max_point();
11309 for selection in &mut selections {
11310 let rows = selection.spanned_rows(true, &display_map);
11311 selection.start = Point::new(rows.start.0, 0);
11312 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11313 selection.reversed = false;
11314 }
11315 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11316 s.select(selections);
11317 });
11318 }
11319
11320 pub fn split_selection_into_lines(
11321 &mut self,
11322 _: &SplitSelectionIntoLines,
11323 window: &mut Window,
11324 cx: &mut Context<Self>,
11325 ) {
11326 let selections = self
11327 .selections
11328 .all::<Point>(cx)
11329 .into_iter()
11330 .map(|selection| selection.start..selection.end)
11331 .collect::<Vec<_>>();
11332 self.unfold_ranges(&selections, true, true, cx);
11333
11334 let mut new_selection_ranges = Vec::new();
11335 {
11336 let buffer = self.buffer.read(cx).read(cx);
11337 for selection in selections {
11338 for row in selection.start.row..selection.end.row {
11339 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11340 new_selection_ranges.push(cursor..cursor);
11341 }
11342
11343 let is_multiline_selection = selection.start.row != selection.end.row;
11344 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11345 // so this action feels more ergonomic when paired with other selection operations
11346 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11347 if !should_skip_last {
11348 new_selection_ranges.push(selection.end..selection.end);
11349 }
11350 }
11351 }
11352 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11353 s.select_ranges(new_selection_ranges);
11354 });
11355 }
11356
11357 pub fn add_selection_above(
11358 &mut self,
11359 _: &AddSelectionAbove,
11360 window: &mut Window,
11361 cx: &mut Context<Self>,
11362 ) {
11363 self.add_selection(true, window, cx);
11364 }
11365
11366 pub fn add_selection_below(
11367 &mut self,
11368 _: &AddSelectionBelow,
11369 window: &mut Window,
11370 cx: &mut Context<Self>,
11371 ) {
11372 self.add_selection(false, window, cx);
11373 }
11374
11375 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11376 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11377
11378 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11379 let mut selections = self.selections.all::<Point>(cx);
11380 let text_layout_details = self.text_layout_details(window);
11381 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11382 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11383 let range = oldest_selection.display_range(&display_map).sorted();
11384
11385 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11386 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11387 let positions = start_x.min(end_x)..start_x.max(end_x);
11388
11389 selections.clear();
11390 let mut stack = Vec::new();
11391 for row in range.start.row().0..=range.end.row().0 {
11392 if let Some(selection) = self.selections.build_columnar_selection(
11393 &display_map,
11394 DisplayRow(row),
11395 &positions,
11396 oldest_selection.reversed,
11397 &text_layout_details,
11398 ) {
11399 stack.push(selection.id);
11400 selections.push(selection);
11401 }
11402 }
11403
11404 if above {
11405 stack.reverse();
11406 }
11407
11408 AddSelectionsState { above, stack }
11409 });
11410
11411 let last_added_selection = *state.stack.last().unwrap();
11412 let mut new_selections = Vec::new();
11413 if above == state.above {
11414 let end_row = if above {
11415 DisplayRow(0)
11416 } else {
11417 display_map.max_point().row()
11418 };
11419
11420 'outer: for selection in selections {
11421 if selection.id == last_added_selection {
11422 let range = selection.display_range(&display_map).sorted();
11423 debug_assert_eq!(range.start.row(), range.end.row());
11424 let mut row = range.start.row();
11425 let positions =
11426 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11427 px(start)..px(end)
11428 } else {
11429 let start_x =
11430 display_map.x_for_display_point(range.start, &text_layout_details);
11431 let end_x =
11432 display_map.x_for_display_point(range.end, &text_layout_details);
11433 start_x.min(end_x)..start_x.max(end_x)
11434 };
11435
11436 while row != end_row {
11437 if above {
11438 row.0 -= 1;
11439 } else {
11440 row.0 += 1;
11441 }
11442
11443 if let Some(new_selection) = self.selections.build_columnar_selection(
11444 &display_map,
11445 row,
11446 &positions,
11447 selection.reversed,
11448 &text_layout_details,
11449 ) {
11450 state.stack.push(new_selection.id);
11451 if above {
11452 new_selections.push(new_selection);
11453 new_selections.push(selection);
11454 } else {
11455 new_selections.push(selection);
11456 new_selections.push(new_selection);
11457 }
11458
11459 continue 'outer;
11460 }
11461 }
11462 }
11463
11464 new_selections.push(selection);
11465 }
11466 } else {
11467 new_selections = selections;
11468 new_selections.retain(|s| s.id != last_added_selection);
11469 state.stack.pop();
11470 }
11471
11472 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11473 s.select(new_selections);
11474 });
11475 if state.stack.len() > 1 {
11476 self.add_selections_state = Some(state);
11477 }
11478 }
11479
11480 pub fn select_next_match_internal(
11481 &mut self,
11482 display_map: &DisplaySnapshot,
11483 replace_newest: bool,
11484 autoscroll: Option<Autoscroll>,
11485 window: &mut Window,
11486 cx: &mut Context<Self>,
11487 ) -> Result<()> {
11488 fn select_next_match_ranges(
11489 this: &mut Editor,
11490 range: Range<usize>,
11491 replace_newest: bool,
11492 auto_scroll: Option<Autoscroll>,
11493 window: &mut Window,
11494 cx: &mut Context<Editor>,
11495 ) {
11496 this.unfold_ranges(&[range.clone()], false, true, cx);
11497 this.change_selections(auto_scroll, window, cx, |s| {
11498 if replace_newest {
11499 s.delete(s.newest_anchor().id);
11500 }
11501 s.insert_range(range.clone());
11502 });
11503 }
11504
11505 let buffer = &display_map.buffer_snapshot;
11506 let mut selections = self.selections.all::<usize>(cx);
11507 if let Some(mut select_next_state) = self.select_next_state.take() {
11508 let query = &select_next_state.query;
11509 if !select_next_state.done {
11510 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11511 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11512 let mut next_selected_range = None;
11513
11514 let bytes_after_last_selection =
11515 buffer.bytes_in_range(last_selection.end..buffer.len());
11516 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11517 let query_matches = query
11518 .stream_find_iter(bytes_after_last_selection)
11519 .map(|result| (last_selection.end, result))
11520 .chain(
11521 query
11522 .stream_find_iter(bytes_before_first_selection)
11523 .map(|result| (0, result)),
11524 );
11525
11526 for (start_offset, query_match) in query_matches {
11527 let query_match = query_match.unwrap(); // can only fail due to I/O
11528 let offset_range =
11529 start_offset + query_match.start()..start_offset + query_match.end();
11530 let display_range = offset_range.start.to_display_point(display_map)
11531 ..offset_range.end.to_display_point(display_map);
11532
11533 if !select_next_state.wordwise
11534 || (!movement::is_inside_word(display_map, display_range.start)
11535 && !movement::is_inside_word(display_map, display_range.end))
11536 {
11537 // TODO: This is n^2, because we might check all the selections
11538 if !selections
11539 .iter()
11540 .any(|selection| selection.range().overlaps(&offset_range))
11541 {
11542 next_selected_range = Some(offset_range);
11543 break;
11544 }
11545 }
11546 }
11547
11548 if let Some(next_selected_range) = next_selected_range {
11549 select_next_match_ranges(
11550 self,
11551 next_selected_range,
11552 replace_newest,
11553 autoscroll,
11554 window,
11555 cx,
11556 );
11557 } else {
11558 select_next_state.done = true;
11559 }
11560 }
11561
11562 self.select_next_state = Some(select_next_state);
11563 } else {
11564 let mut only_carets = true;
11565 let mut same_text_selected = true;
11566 let mut selected_text = None;
11567
11568 let mut selections_iter = selections.iter().peekable();
11569 while let Some(selection) = selections_iter.next() {
11570 if selection.start != selection.end {
11571 only_carets = false;
11572 }
11573
11574 if same_text_selected {
11575 if selected_text.is_none() {
11576 selected_text =
11577 Some(buffer.text_for_range(selection.range()).collect::<String>());
11578 }
11579
11580 if let Some(next_selection) = selections_iter.peek() {
11581 if next_selection.range().len() == selection.range().len() {
11582 let next_selected_text = buffer
11583 .text_for_range(next_selection.range())
11584 .collect::<String>();
11585 if Some(next_selected_text) != selected_text {
11586 same_text_selected = false;
11587 selected_text = None;
11588 }
11589 } else {
11590 same_text_selected = false;
11591 selected_text = None;
11592 }
11593 }
11594 }
11595 }
11596
11597 if only_carets {
11598 for selection in &mut selections {
11599 let word_range = movement::surrounding_word(
11600 display_map,
11601 selection.start.to_display_point(display_map),
11602 );
11603 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11604 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11605 selection.goal = SelectionGoal::None;
11606 selection.reversed = false;
11607 select_next_match_ranges(
11608 self,
11609 selection.start..selection.end,
11610 replace_newest,
11611 autoscroll,
11612 window,
11613 cx,
11614 );
11615 }
11616
11617 if selections.len() == 1 {
11618 let selection = selections
11619 .last()
11620 .expect("ensured that there's only one selection");
11621 let query = buffer
11622 .text_for_range(selection.start..selection.end)
11623 .collect::<String>();
11624 let is_empty = query.is_empty();
11625 let select_state = SelectNextState {
11626 query: AhoCorasick::new(&[query])?,
11627 wordwise: true,
11628 done: is_empty,
11629 };
11630 self.select_next_state = Some(select_state);
11631 } else {
11632 self.select_next_state = None;
11633 }
11634 } else if let Some(selected_text) = selected_text {
11635 self.select_next_state = Some(SelectNextState {
11636 query: AhoCorasick::new(&[selected_text])?,
11637 wordwise: false,
11638 done: false,
11639 });
11640 self.select_next_match_internal(
11641 display_map,
11642 replace_newest,
11643 autoscroll,
11644 window,
11645 cx,
11646 )?;
11647 }
11648 }
11649 Ok(())
11650 }
11651
11652 pub fn select_all_matches(
11653 &mut self,
11654 _action: &SelectAllMatches,
11655 window: &mut Window,
11656 cx: &mut Context<Self>,
11657 ) -> Result<()> {
11658 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11659
11660 self.push_to_selection_history();
11661 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11662
11663 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11664 let Some(select_next_state) = self.select_next_state.as_mut() else {
11665 return Ok(());
11666 };
11667 if select_next_state.done {
11668 return Ok(());
11669 }
11670
11671 let mut new_selections = self.selections.all::<usize>(cx);
11672
11673 let buffer = &display_map.buffer_snapshot;
11674 let query_matches = select_next_state
11675 .query
11676 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11677
11678 for query_match in query_matches {
11679 let query_match = query_match.unwrap(); // can only fail due to I/O
11680 let offset_range = query_match.start()..query_match.end();
11681 let display_range = offset_range.start.to_display_point(&display_map)
11682 ..offset_range.end.to_display_point(&display_map);
11683
11684 if !select_next_state.wordwise
11685 || (!movement::is_inside_word(&display_map, display_range.start)
11686 && !movement::is_inside_word(&display_map, display_range.end))
11687 {
11688 self.selections.change_with(cx, |selections| {
11689 new_selections.push(Selection {
11690 id: selections.new_selection_id(),
11691 start: offset_range.start,
11692 end: offset_range.end,
11693 reversed: false,
11694 goal: SelectionGoal::None,
11695 });
11696 });
11697 }
11698 }
11699
11700 new_selections.sort_by_key(|selection| selection.start);
11701 let mut ix = 0;
11702 while ix + 1 < new_selections.len() {
11703 let current_selection = &new_selections[ix];
11704 let next_selection = &new_selections[ix + 1];
11705 if current_selection.range().overlaps(&next_selection.range()) {
11706 if current_selection.id < next_selection.id {
11707 new_selections.remove(ix + 1);
11708 } else {
11709 new_selections.remove(ix);
11710 }
11711 } else {
11712 ix += 1;
11713 }
11714 }
11715
11716 let reversed = self.selections.oldest::<usize>(cx).reversed;
11717
11718 for selection in new_selections.iter_mut() {
11719 selection.reversed = reversed;
11720 }
11721
11722 select_next_state.done = true;
11723 self.unfold_ranges(
11724 &new_selections
11725 .iter()
11726 .map(|selection| selection.range())
11727 .collect::<Vec<_>>(),
11728 false,
11729 false,
11730 cx,
11731 );
11732 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11733 selections.select(new_selections)
11734 });
11735
11736 Ok(())
11737 }
11738
11739 pub fn select_next(
11740 &mut self,
11741 action: &SelectNext,
11742 window: &mut Window,
11743 cx: &mut Context<Self>,
11744 ) -> Result<()> {
11745 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11746 self.push_to_selection_history();
11747 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11748 self.select_next_match_internal(
11749 &display_map,
11750 action.replace_newest,
11751 Some(Autoscroll::newest()),
11752 window,
11753 cx,
11754 )?;
11755 Ok(())
11756 }
11757
11758 pub fn select_previous(
11759 &mut self,
11760 action: &SelectPrevious,
11761 window: &mut Window,
11762 cx: &mut Context<Self>,
11763 ) -> Result<()> {
11764 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11765 self.push_to_selection_history();
11766 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11767 let buffer = &display_map.buffer_snapshot;
11768 let mut selections = self.selections.all::<usize>(cx);
11769 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11770 let query = &select_prev_state.query;
11771 if !select_prev_state.done {
11772 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11773 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11774 let mut next_selected_range = None;
11775 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11776 let bytes_before_last_selection =
11777 buffer.reversed_bytes_in_range(0..last_selection.start);
11778 let bytes_after_first_selection =
11779 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11780 let query_matches = query
11781 .stream_find_iter(bytes_before_last_selection)
11782 .map(|result| (last_selection.start, result))
11783 .chain(
11784 query
11785 .stream_find_iter(bytes_after_first_selection)
11786 .map(|result| (buffer.len(), result)),
11787 );
11788 for (end_offset, query_match) in query_matches {
11789 let query_match = query_match.unwrap(); // can only fail due to I/O
11790 let offset_range =
11791 end_offset - query_match.end()..end_offset - query_match.start();
11792 let display_range = offset_range.start.to_display_point(&display_map)
11793 ..offset_range.end.to_display_point(&display_map);
11794
11795 if !select_prev_state.wordwise
11796 || (!movement::is_inside_word(&display_map, display_range.start)
11797 && !movement::is_inside_word(&display_map, display_range.end))
11798 {
11799 next_selected_range = Some(offset_range);
11800 break;
11801 }
11802 }
11803
11804 if let Some(next_selected_range) = next_selected_range {
11805 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11806 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11807 if action.replace_newest {
11808 s.delete(s.newest_anchor().id);
11809 }
11810 s.insert_range(next_selected_range);
11811 });
11812 } else {
11813 select_prev_state.done = true;
11814 }
11815 }
11816
11817 self.select_prev_state = Some(select_prev_state);
11818 } else {
11819 let mut only_carets = true;
11820 let mut same_text_selected = true;
11821 let mut selected_text = None;
11822
11823 let mut selections_iter = selections.iter().peekable();
11824 while let Some(selection) = selections_iter.next() {
11825 if selection.start != selection.end {
11826 only_carets = false;
11827 }
11828
11829 if same_text_selected {
11830 if selected_text.is_none() {
11831 selected_text =
11832 Some(buffer.text_for_range(selection.range()).collect::<String>());
11833 }
11834
11835 if let Some(next_selection) = selections_iter.peek() {
11836 if next_selection.range().len() == selection.range().len() {
11837 let next_selected_text = buffer
11838 .text_for_range(next_selection.range())
11839 .collect::<String>();
11840 if Some(next_selected_text) != selected_text {
11841 same_text_selected = false;
11842 selected_text = None;
11843 }
11844 } else {
11845 same_text_selected = false;
11846 selected_text = None;
11847 }
11848 }
11849 }
11850 }
11851
11852 if only_carets {
11853 for selection in &mut selections {
11854 let word_range = movement::surrounding_word(
11855 &display_map,
11856 selection.start.to_display_point(&display_map),
11857 );
11858 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11859 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11860 selection.goal = SelectionGoal::None;
11861 selection.reversed = false;
11862 }
11863 if selections.len() == 1 {
11864 let selection = selections
11865 .last()
11866 .expect("ensured that there's only one selection");
11867 let query = buffer
11868 .text_for_range(selection.start..selection.end)
11869 .collect::<String>();
11870 let is_empty = query.is_empty();
11871 let select_state = SelectNextState {
11872 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11873 wordwise: true,
11874 done: is_empty,
11875 };
11876 self.select_prev_state = Some(select_state);
11877 } else {
11878 self.select_prev_state = None;
11879 }
11880
11881 self.unfold_ranges(
11882 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11883 false,
11884 true,
11885 cx,
11886 );
11887 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11888 s.select(selections);
11889 });
11890 } else if let Some(selected_text) = selected_text {
11891 self.select_prev_state = Some(SelectNextState {
11892 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11893 wordwise: false,
11894 done: false,
11895 });
11896 self.select_previous(action, window, cx)?;
11897 }
11898 }
11899 Ok(())
11900 }
11901
11902 pub fn toggle_comments(
11903 &mut self,
11904 action: &ToggleComments,
11905 window: &mut Window,
11906 cx: &mut Context<Self>,
11907 ) {
11908 if self.read_only(cx) {
11909 return;
11910 }
11911 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11912 let text_layout_details = &self.text_layout_details(window);
11913 self.transact(window, cx, |this, window, cx| {
11914 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11915 let mut edits = Vec::new();
11916 let mut selection_edit_ranges = Vec::new();
11917 let mut last_toggled_row = None;
11918 let snapshot = this.buffer.read(cx).read(cx);
11919 let empty_str: Arc<str> = Arc::default();
11920 let mut suffixes_inserted = Vec::new();
11921 let ignore_indent = action.ignore_indent;
11922
11923 fn comment_prefix_range(
11924 snapshot: &MultiBufferSnapshot,
11925 row: MultiBufferRow,
11926 comment_prefix: &str,
11927 comment_prefix_whitespace: &str,
11928 ignore_indent: bool,
11929 ) -> Range<Point> {
11930 let indent_size = if ignore_indent {
11931 0
11932 } else {
11933 snapshot.indent_size_for_line(row).len
11934 };
11935
11936 let start = Point::new(row.0, indent_size);
11937
11938 let mut line_bytes = snapshot
11939 .bytes_in_range(start..snapshot.max_point())
11940 .flatten()
11941 .copied();
11942
11943 // If this line currently begins with the line comment prefix, then record
11944 // the range containing the prefix.
11945 if line_bytes
11946 .by_ref()
11947 .take(comment_prefix.len())
11948 .eq(comment_prefix.bytes())
11949 {
11950 // Include any whitespace that matches the comment prefix.
11951 let matching_whitespace_len = line_bytes
11952 .zip(comment_prefix_whitespace.bytes())
11953 .take_while(|(a, b)| a == b)
11954 .count() as u32;
11955 let end = Point::new(
11956 start.row,
11957 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11958 );
11959 start..end
11960 } else {
11961 start..start
11962 }
11963 }
11964
11965 fn comment_suffix_range(
11966 snapshot: &MultiBufferSnapshot,
11967 row: MultiBufferRow,
11968 comment_suffix: &str,
11969 comment_suffix_has_leading_space: bool,
11970 ) -> Range<Point> {
11971 let end = Point::new(row.0, snapshot.line_len(row));
11972 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11973
11974 let mut line_end_bytes = snapshot
11975 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11976 .flatten()
11977 .copied();
11978
11979 let leading_space_len = if suffix_start_column > 0
11980 && line_end_bytes.next() == Some(b' ')
11981 && comment_suffix_has_leading_space
11982 {
11983 1
11984 } else {
11985 0
11986 };
11987
11988 // If this line currently begins with the line comment prefix, then record
11989 // the range containing the prefix.
11990 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11991 let start = Point::new(end.row, suffix_start_column - leading_space_len);
11992 start..end
11993 } else {
11994 end..end
11995 }
11996 }
11997
11998 // TODO: Handle selections that cross excerpts
11999 for selection in &mut selections {
12000 let start_column = snapshot
12001 .indent_size_for_line(MultiBufferRow(selection.start.row))
12002 .len;
12003 let language = if let Some(language) =
12004 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12005 {
12006 language
12007 } else {
12008 continue;
12009 };
12010
12011 selection_edit_ranges.clear();
12012
12013 // If multiple selections contain a given row, avoid processing that
12014 // row more than once.
12015 let mut start_row = MultiBufferRow(selection.start.row);
12016 if last_toggled_row == Some(start_row) {
12017 start_row = start_row.next_row();
12018 }
12019 let end_row =
12020 if selection.end.row > selection.start.row && selection.end.column == 0 {
12021 MultiBufferRow(selection.end.row - 1)
12022 } else {
12023 MultiBufferRow(selection.end.row)
12024 };
12025 last_toggled_row = Some(end_row);
12026
12027 if start_row > end_row {
12028 continue;
12029 }
12030
12031 // If the language has line comments, toggle those.
12032 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12033
12034 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12035 if ignore_indent {
12036 full_comment_prefixes = full_comment_prefixes
12037 .into_iter()
12038 .map(|s| Arc::from(s.trim_end()))
12039 .collect();
12040 }
12041
12042 if !full_comment_prefixes.is_empty() {
12043 let first_prefix = full_comment_prefixes
12044 .first()
12045 .expect("prefixes is non-empty");
12046 let prefix_trimmed_lengths = full_comment_prefixes
12047 .iter()
12048 .map(|p| p.trim_end_matches(' ').len())
12049 .collect::<SmallVec<[usize; 4]>>();
12050
12051 let mut all_selection_lines_are_comments = true;
12052
12053 for row in start_row.0..=end_row.0 {
12054 let row = MultiBufferRow(row);
12055 if start_row < end_row && snapshot.is_line_blank(row) {
12056 continue;
12057 }
12058
12059 let prefix_range = full_comment_prefixes
12060 .iter()
12061 .zip(prefix_trimmed_lengths.iter().copied())
12062 .map(|(prefix, trimmed_prefix_len)| {
12063 comment_prefix_range(
12064 snapshot.deref(),
12065 row,
12066 &prefix[..trimmed_prefix_len],
12067 &prefix[trimmed_prefix_len..],
12068 ignore_indent,
12069 )
12070 })
12071 .max_by_key(|range| range.end.column - range.start.column)
12072 .expect("prefixes is non-empty");
12073
12074 if prefix_range.is_empty() {
12075 all_selection_lines_are_comments = false;
12076 }
12077
12078 selection_edit_ranges.push(prefix_range);
12079 }
12080
12081 if all_selection_lines_are_comments {
12082 edits.extend(
12083 selection_edit_ranges
12084 .iter()
12085 .cloned()
12086 .map(|range| (range, empty_str.clone())),
12087 );
12088 } else {
12089 let min_column = selection_edit_ranges
12090 .iter()
12091 .map(|range| range.start.column)
12092 .min()
12093 .unwrap_or(0);
12094 edits.extend(selection_edit_ranges.iter().map(|range| {
12095 let position = Point::new(range.start.row, min_column);
12096 (position..position, first_prefix.clone())
12097 }));
12098 }
12099 } else if let Some((full_comment_prefix, comment_suffix)) =
12100 language.block_comment_delimiters()
12101 {
12102 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12103 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12104 let prefix_range = comment_prefix_range(
12105 snapshot.deref(),
12106 start_row,
12107 comment_prefix,
12108 comment_prefix_whitespace,
12109 ignore_indent,
12110 );
12111 let suffix_range = comment_suffix_range(
12112 snapshot.deref(),
12113 end_row,
12114 comment_suffix.trim_start_matches(' '),
12115 comment_suffix.starts_with(' '),
12116 );
12117
12118 if prefix_range.is_empty() || suffix_range.is_empty() {
12119 edits.push((
12120 prefix_range.start..prefix_range.start,
12121 full_comment_prefix.clone(),
12122 ));
12123 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12124 suffixes_inserted.push((end_row, comment_suffix.len()));
12125 } else {
12126 edits.push((prefix_range, empty_str.clone()));
12127 edits.push((suffix_range, empty_str.clone()));
12128 }
12129 } else {
12130 continue;
12131 }
12132 }
12133
12134 drop(snapshot);
12135 this.buffer.update(cx, |buffer, cx| {
12136 buffer.edit(edits, None, cx);
12137 });
12138
12139 // Adjust selections so that they end before any comment suffixes that
12140 // were inserted.
12141 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12142 let mut selections = this.selections.all::<Point>(cx);
12143 let snapshot = this.buffer.read(cx).read(cx);
12144 for selection in &mut selections {
12145 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12146 match row.cmp(&MultiBufferRow(selection.end.row)) {
12147 Ordering::Less => {
12148 suffixes_inserted.next();
12149 continue;
12150 }
12151 Ordering::Greater => break,
12152 Ordering::Equal => {
12153 if selection.end.column == snapshot.line_len(row) {
12154 if selection.is_empty() {
12155 selection.start.column -= suffix_len as u32;
12156 }
12157 selection.end.column -= suffix_len as u32;
12158 }
12159 break;
12160 }
12161 }
12162 }
12163 }
12164
12165 drop(snapshot);
12166 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12167 s.select(selections)
12168 });
12169
12170 let selections = this.selections.all::<Point>(cx);
12171 let selections_on_single_row = selections.windows(2).all(|selections| {
12172 selections[0].start.row == selections[1].start.row
12173 && selections[0].end.row == selections[1].end.row
12174 && selections[0].start.row == selections[0].end.row
12175 });
12176 let selections_selecting = selections
12177 .iter()
12178 .any(|selection| selection.start != selection.end);
12179 let advance_downwards = action.advance_downwards
12180 && selections_on_single_row
12181 && !selections_selecting
12182 && !matches!(this.mode, EditorMode::SingleLine { .. });
12183
12184 if advance_downwards {
12185 let snapshot = this.buffer.read(cx).snapshot(cx);
12186
12187 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12188 s.move_cursors_with(|display_snapshot, display_point, _| {
12189 let mut point = display_point.to_point(display_snapshot);
12190 point.row += 1;
12191 point = snapshot.clip_point(point, Bias::Left);
12192 let display_point = point.to_display_point(display_snapshot);
12193 let goal = SelectionGoal::HorizontalPosition(
12194 display_snapshot
12195 .x_for_display_point(display_point, text_layout_details)
12196 .into(),
12197 );
12198 (display_point, goal)
12199 })
12200 });
12201 }
12202 });
12203 }
12204
12205 pub fn select_enclosing_symbol(
12206 &mut self,
12207 _: &SelectEnclosingSymbol,
12208 window: &mut Window,
12209 cx: &mut Context<Self>,
12210 ) {
12211 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12212
12213 let buffer = self.buffer.read(cx).snapshot(cx);
12214 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12215
12216 fn update_selection(
12217 selection: &Selection<usize>,
12218 buffer_snap: &MultiBufferSnapshot,
12219 ) -> Option<Selection<usize>> {
12220 let cursor = selection.head();
12221 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12222 for symbol in symbols.iter().rev() {
12223 let start = symbol.range.start.to_offset(buffer_snap);
12224 let end = symbol.range.end.to_offset(buffer_snap);
12225 let new_range = start..end;
12226 if start < selection.start || end > selection.end {
12227 return Some(Selection {
12228 id: selection.id,
12229 start: new_range.start,
12230 end: new_range.end,
12231 goal: SelectionGoal::None,
12232 reversed: selection.reversed,
12233 });
12234 }
12235 }
12236 None
12237 }
12238
12239 let mut selected_larger_symbol = false;
12240 let new_selections = old_selections
12241 .iter()
12242 .map(|selection| match update_selection(selection, &buffer) {
12243 Some(new_selection) => {
12244 if new_selection.range() != selection.range() {
12245 selected_larger_symbol = true;
12246 }
12247 new_selection
12248 }
12249 None => selection.clone(),
12250 })
12251 .collect::<Vec<_>>();
12252
12253 if selected_larger_symbol {
12254 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12255 s.select(new_selections);
12256 });
12257 }
12258 }
12259
12260 pub fn select_larger_syntax_node(
12261 &mut self,
12262 _: &SelectLargerSyntaxNode,
12263 window: &mut Window,
12264 cx: &mut Context<Self>,
12265 ) {
12266 let Some(visible_row_count) = self.visible_row_count() else {
12267 return;
12268 };
12269 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12270 if old_selections.is_empty() {
12271 return;
12272 }
12273
12274 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12275
12276 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12277 let buffer = self.buffer.read(cx).snapshot(cx);
12278
12279 let mut selected_larger_node = false;
12280 let mut new_selections = old_selections
12281 .iter()
12282 .map(|selection| {
12283 let old_range = selection.start..selection.end;
12284 let mut new_range = old_range.clone();
12285 let mut new_node = None;
12286 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12287 {
12288 new_node = Some(node);
12289 new_range = match containing_range {
12290 MultiOrSingleBufferOffsetRange::Single(_) => break,
12291 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12292 };
12293 if !display_map.intersects_fold(new_range.start)
12294 && !display_map.intersects_fold(new_range.end)
12295 {
12296 break;
12297 }
12298 }
12299
12300 if let Some(node) = new_node {
12301 // Log the ancestor, to support using this action as a way to explore TreeSitter
12302 // nodes. Parent and grandparent are also logged because this operation will not
12303 // visit nodes that have the same range as their parent.
12304 log::info!("Node: {node:?}");
12305 let parent = node.parent();
12306 log::info!("Parent: {parent:?}");
12307 let grandparent = parent.and_then(|x| x.parent());
12308 log::info!("Grandparent: {grandparent:?}");
12309 }
12310
12311 selected_larger_node |= new_range != old_range;
12312 Selection {
12313 id: selection.id,
12314 start: new_range.start,
12315 end: new_range.end,
12316 goal: SelectionGoal::None,
12317 reversed: selection.reversed,
12318 }
12319 })
12320 .collect::<Vec<_>>();
12321
12322 if !selected_larger_node {
12323 return; // don't put this call in the history
12324 }
12325
12326 // scroll based on transformation done to the last selection created by the user
12327 let (last_old, last_new) = old_selections
12328 .last()
12329 .zip(new_selections.last().cloned())
12330 .expect("old_selections isn't empty");
12331
12332 // revert selection
12333 let is_selection_reversed = {
12334 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12335 new_selections.last_mut().expect("checked above").reversed =
12336 should_newest_selection_be_reversed;
12337 should_newest_selection_be_reversed
12338 };
12339
12340 if selected_larger_node {
12341 self.select_syntax_node_history.disable_clearing = true;
12342 self.change_selections(None, window, cx, |s| {
12343 s.select(new_selections.clone());
12344 });
12345 self.select_syntax_node_history.disable_clearing = false;
12346 }
12347
12348 let start_row = last_new.start.to_display_point(&display_map).row().0;
12349 let end_row = last_new.end.to_display_point(&display_map).row().0;
12350 let selection_height = end_row - start_row + 1;
12351 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12352
12353 // if fits on screen (considering margin), keep it in the middle, else, scroll to selection head
12354 let scroll_behavior = if visible_row_count >= selection_height + scroll_margin_rows * 2 {
12355 let middle_row = (end_row + start_row) / 2;
12356 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12357 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12358 SelectSyntaxNodeScrollBehavior::CenterSelection
12359 } else if is_selection_reversed {
12360 self.scroll_cursor_top(&Default::default(), window, cx);
12361 SelectSyntaxNodeScrollBehavior::CursorTop
12362 } else {
12363 self.scroll_cursor_bottom(&Default::default(), window, cx);
12364 SelectSyntaxNodeScrollBehavior::CursorBottom
12365 };
12366
12367 self.select_syntax_node_history.push((
12368 old_selections,
12369 scroll_behavior,
12370 is_selection_reversed,
12371 ));
12372 }
12373
12374 pub fn select_smaller_syntax_node(
12375 &mut self,
12376 _: &SelectSmallerSyntaxNode,
12377 window: &mut Window,
12378 cx: &mut Context<Self>,
12379 ) {
12380 let Some(visible_row_count) = self.visible_row_count() else {
12381 return;
12382 };
12383
12384 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12385
12386 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12387 self.select_syntax_node_history.pop()
12388 {
12389 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12390
12391 if let Some(selection) = selections.last_mut() {
12392 selection.reversed = is_selection_reversed;
12393 }
12394
12395 self.select_syntax_node_history.disable_clearing = true;
12396 self.change_selections(None, window, cx, |s| {
12397 s.select(selections.to_vec());
12398 });
12399 self.select_syntax_node_history.disable_clearing = false;
12400
12401 let newest = self.selections.newest::<usize>(cx);
12402 let start_row = newest.start.to_display_point(&display_map).row().0;
12403 let end_row = newest.end.to_display_point(&display_map).row().0;
12404
12405 match scroll_behavior {
12406 SelectSyntaxNodeScrollBehavior::CursorTop => {
12407 self.scroll_cursor_top(&Default::default(), window, cx);
12408 }
12409 SelectSyntaxNodeScrollBehavior::CenterSelection => {
12410 let middle_row = (end_row + start_row) / 2;
12411 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12412 // centralize the selection, not the cursor
12413 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12414 }
12415 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12416 self.scroll_cursor_bottom(&Default::default(), window, cx);
12417 }
12418 }
12419 }
12420 }
12421
12422 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12423 if !EditorSettings::get_global(cx).gutter.runnables {
12424 self.clear_tasks();
12425 return Task::ready(());
12426 }
12427 let project = self.project.as_ref().map(Entity::downgrade);
12428 cx.spawn_in(window, async move |this, cx| {
12429 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12430 let Some(project) = project.and_then(|p| p.upgrade()) else {
12431 return;
12432 };
12433 let Ok(display_snapshot) = this.update(cx, |this, cx| {
12434 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12435 }) else {
12436 return;
12437 };
12438
12439 let hide_runnables = project
12440 .update(cx, |project, cx| {
12441 // Do not display any test indicators in non-dev server remote projects.
12442 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12443 })
12444 .unwrap_or(true);
12445 if hide_runnables {
12446 return;
12447 }
12448 let new_rows =
12449 cx.background_spawn({
12450 let snapshot = display_snapshot.clone();
12451 async move {
12452 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12453 }
12454 })
12455 .await;
12456
12457 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12458 this.update(cx, |this, _| {
12459 this.clear_tasks();
12460 for (key, value) in rows {
12461 this.insert_tasks(key, value);
12462 }
12463 })
12464 .ok();
12465 })
12466 }
12467 fn fetch_runnable_ranges(
12468 snapshot: &DisplaySnapshot,
12469 range: Range<Anchor>,
12470 ) -> Vec<language::RunnableRange> {
12471 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12472 }
12473
12474 fn runnable_rows(
12475 project: Entity<Project>,
12476 snapshot: DisplaySnapshot,
12477 runnable_ranges: Vec<RunnableRange>,
12478 mut cx: AsyncWindowContext,
12479 ) -> Vec<((BufferId, u32), RunnableTasks)> {
12480 runnable_ranges
12481 .into_iter()
12482 .filter_map(|mut runnable| {
12483 let tasks = cx
12484 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12485 .ok()?;
12486 if tasks.is_empty() {
12487 return None;
12488 }
12489
12490 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12491
12492 let row = snapshot
12493 .buffer_snapshot
12494 .buffer_line_for_row(MultiBufferRow(point.row))?
12495 .1
12496 .start
12497 .row;
12498
12499 let context_range =
12500 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12501 Some((
12502 (runnable.buffer_id, row),
12503 RunnableTasks {
12504 templates: tasks,
12505 offset: snapshot
12506 .buffer_snapshot
12507 .anchor_before(runnable.run_range.start),
12508 context_range,
12509 column: point.column,
12510 extra_variables: runnable.extra_captures,
12511 },
12512 ))
12513 })
12514 .collect()
12515 }
12516
12517 fn templates_with_tags(
12518 project: &Entity<Project>,
12519 runnable: &mut Runnable,
12520 cx: &mut App,
12521 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12522 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12523 let (worktree_id, file) = project
12524 .buffer_for_id(runnable.buffer, cx)
12525 .and_then(|buffer| buffer.read(cx).file())
12526 .map(|file| (file.worktree_id(cx), file.clone()))
12527 .unzip();
12528
12529 (
12530 project.task_store().read(cx).task_inventory().cloned(),
12531 worktree_id,
12532 file,
12533 )
12534 });
12535
12536 let tags = mem::take(&mut runnable.tags);
12537 let mut tags: Vec<_> = tags
12538 .into_iter()
12539 .flat_map(|tag| {
12540 let tag = tag.0.clone();
12541 inventory
12542 .as_ref()
12543 .into_iter()
12544 .flat_map(|inventory| {
12545 inventory.read(cx).list_tasks(
12546 file.clone(),
12547 Some(runnable.language.clone()),
12548 worktree_id,
12549 cx,
12550 )
12551 })
12552 .filter(move |(_, template)| {
12553 template.tags.iter().any(|source_tag| source_tag == &tag)
12554 })
12555 })
12556 .sorted_by_key(|(kind, _)| kind.to_owned())
12557 .collect();
12558 if let Some((leading_tag_source, _)) = tags.first() {
12559 // Strongest source wins; if we have worktree tag binding, prefer that to
12560 // global and language bindings;
12561 // if we have a global binding, prefer that to language binding.
12562 let first_mismatch = tags
12563 .iter()
12564 .position(|(tag_source, _)| tag_source != leading_tag_source);
12565 if let Some(index) = first_mismatch {
12566 tags.truncate(index);
12567 }
12568 }
12569
12570 tags
12571 }
12572
12573 pub fn move_to_enclosing_bracket(
12574 &mut self,
12575 _: &MoveToEnclosingBracket,
12576 window: &mut Window,
12577 cx: &mut Context<Self>,
12578 ) {
12579 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12580 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12581 s.move_offsets_with(|snapshot, selection| {
12582 let Some(enclosing_bracket_ranges) =
12583 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12584 else {
12585 return;
12586 };
12587
12588 let mut best_length = usize::MAX;
12589 let mut best_inside = false;
12590 let mut best_in_bracket_range = false;
12591 let mut best_destination = None;
12592 for (open, close) in enclosing_bracket_ranges {
12593 let close = close.to_inclusive();
12594 let length = close.end() - open.start;
12595 let inside = selection.start >= open.end && selection.end <= *close.start();
12596 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12597 || close.contains(&selection.head());
12598
12599 // If best is next to a bracket and current isn't, skip
12600 if !in_bracket_range && best_in_bracket_range {
12601 continue;
12602 }
12603
12604 // Prefer smaller lengths unless best is inside and current isn't
12605 if length > best_length && (best_inside || !inside) {
12606 continue;
12607 }
12608
12609 best_length = length;
12610 best_inside = inside;
12611 best_in_bracket_range = in_bracket_range;
12612 best_destination = Some(
12613 if close.contains(&selection.start) && close.contains(&selection.end) {
12614 if inside { open.end } else { open.start }
12615 } else if inside {
12616 *close.start()
12617 } else {
12618 *close.end()
12619 },
12620 );
12621 }
12622
12623 if let Some(destination) = best_destination {
12624 selection.collapse_to(destination, SelectionGoal::None);
12625 }
12626 })
12627 });
12628 }
12629
12630 pub fn undo_selection(
12631 &mut self,
12632 _: &UndoSelection,
12633 window: &mut Window,
12634 cx: &mut Context<Self>,
12635 ) {
12636 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12637 self.end_selection(window, cx);
12638 self.selection_history.mode = SelectionHistoryMode::Undoing;
12639 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12640 self.change_selections(None, window, cx, |s| {
12641 s.select_anchors(entry.selections.to_vec())
12642 });
12643 self.select_next_state = entry.select_next_state;
12644 self.select_prev_state = entry.select_prev_state;
12645 self.add_selections_state = entry.add_selections_state;
12646 self.request_autoscroll(Autoscroll::newest(), cx);
12647 }
12648 self.selection_history.mode = SelectionHistoryMode::Normal;
12649 }
12650
12651 pub fn redo_selection(
12652 &mut self,
12653 _: &RedoSelection,
12654 window: &mut Window,
12655 cx: &mut Context<Self>,
12656 ) {
12657 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12658 self.end_selection(window, cx);
12659 self.selection_history.mode = SelectionHistoryMode::Redoing;
12660 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12661 self.change_selections(None, window, cx, |s| {
12662 s.select_anchors(entry.selections.to_vec())
12663 });
12664 self.select_next_state = entry.select_next_state;
12665 self.select_prev_state = entry.select_prev_state;
12666 self.add_selections_state = entry.add_selections_state;
12667 self.request_autoscroll(Autoscroll::newest(), cx);
12668 }
12669 self.selection_history.mode = SelectionHistoryMode::Normal;
12670 }
12671
12672 pub fn expand_excerpts(
12673 &mut self,
12674 action: &ExpandExcerpts,
12675 _: &mut Window,
12676 cx: &mut Context<Self>,
12677 ) {
12678 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12679 }
12680
12681 pub fn expand_excerpts_down(
12682 &mut self,
12683 action: &ExpandExcerptsDown,
12684 _: &mut Window,
12685 cx: &mut Context<Self>,
12686 ) {
12687 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12688 }
12689
12690 pub fn expand_excerpts_up(
12691 &mut self,
12692 action: &ExpandExcerptsUp,
12693 _: &mut Window,
12694 cx: &mut Context<Self>,
12695 ) {
12696 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12697 }
12698
12699 pub fn expand_excerpts_for_direction(
12700 &mut self,
12701 lines: u32,
12702 direction: ExpandExcerptDirection,
12703
12704 cx: &mut Context<Self>,
12705 ) {
12706 let selections = self.selections.disjoint_anchors();
12707
12708 let lines = if lines == 0 {
12709 EditorSettings::get_global(cx).expand_excerpt_lines
12710 } else {
12711 lines
12712 };
12713
12714 self.buffer.update(cx, |buffer, cx| {
12715 let snapshot = buffer.snapshot(cx);
12716 let mut excerpt_ids = selections
12717 .iter()
12718 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12719 .collect::<Vec<_>>();
12720 excerpt_ids.sort();
12721 excerpt_ids.dedup();
12722 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12723 })
12724 }
12725
12726 pub fn expand_excerpt(
12727 &mut self,
12728 excerpt: ExcerptId,
12729 direction: ExpandExcerptDirection,
12730 window: &mut Window,
12731 cx: &mut Context<Self>,
12732 ) {
12733 let current_scroll_position = self.scroll_position(cx);
12734 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12735 self.buffer.update(cx, |buffer, cx| {
12736 buffer.expand_excerpts([excerpt], lines, direction, cx)
12737 });
12738 if direction == ExpandExcerptDirection::Down {
12739 let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12740 self.set_scroll_position(new_scroll_position, window, cx);
12741 }
12742 }
12743
12744 pub fn go_to_singleton_buffer_point(
12745 &mut self,
12746 point: Point,
12747 window: &mut Window,
12748 cx: &mut Context<Self>,
12749 ) {
12750 self.go_to_singleton_buffer_range(point..point, window, cx);
12751 }
12752
12753 pub fn go_to_singleton_buffer_range(
12754 &mut self,
12755 range: Range<Point>,
12756 window: &mut Window,
12757 cx: &mut Context<Self>,
12758 ) {
12759 let multibuffer = self.buffer().read(cx);
12760 let Some(buffer) = multibuffer.as_singleton() else {
12761 return;
12762 };
12763 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12764 return;
12765 };
12766 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12767 return;
12768 };
12769 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12770 s.select_anchor_ranges([start..end])
12771 });
12772 }
12773
12774 fn go_to_diagnostic(
12775 &mut self,
12776 _: &GoToDiagnostic,
12777 window: &mut Window,
12778 cx: &mut Context<Self>,
12779 ) {
12780 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12781 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12782 }
12783
12784 fn go_to_prev_diagnostic(
12785 &mut self,
12786 _: &GoToPreviousDiagnostic,
12787 window: &mut Window,
12788 cx: &mut Context<Self>,
12789 ) {
12790 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12791 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12792 }
12793
12794 pub fn go_to_diagnostic_impl(
12795 &mut self,
12796 direction: Direction,
12797 window: &mut Window,
12798 cx: &mut Context<Self>,
12799 ) {
12800 let buffer = self.buffer.read(cx).snapshot(cx);
12801 let selection = self.selections.newest::<usize>(cx);
12802 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12803 if direction == Direction::Next {
12804 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12805 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12806 return;
12807 };
12808 self.activate_diagnostics(
12809 buffer_id,
12810 popover.local_diagnostic.diagnostic.group_id,
12811 window,
12812 cx,
12813 );
12814 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12815 let primary_range_start = active_diagnostics.primary_range.start;
12816 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12817 let mut new_selection = s.newest_anchor().clone();
12818 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12819 s.select_anchors(vec![new_selection.clone()]);
12820 });
12821 self.refresh_inline_completion(false, true, window, cx);
12822 }
12823 return;
12824 }
12825 }
12826
12827 let active_group_id = self
12828 .active_diagnostics
12829 .as_ref()
12830 .map(|active_group| active_group.group_id);
12831 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12832 active_diagnostics
12833 .primary_range
12834 .to_offset(&buffer)
12835 .to_inclusive()
12836 });
12837 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12838 if active_primary_range.contains(&selection.head()) {
12839 *active_primary_range.start()
12840 } else {
12841 selection.head()
12842 }
12843 } else {
12844 selection.head()
12845 };
12846
12847 let snapshot = self.snapshot(window, cx);
12848 let primary_diagnostics_before = buffer
12849 .diagnostics_in_range::<usize>(0..search_start)
12850 .filter(|entry| entry.diagnostic.is_primary)
12851 .filter(|entry| entry.range.start != entry.range.end)
12852 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12853 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12854 .collect::<Vec<_>>();
12855 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12856 primary_diagnostics_before
12857 .iter()
12858 .position(|entry| entry.diagnostic.group_id == active_group_id)
12859 });
12860
12861 let primary_diagnostics_after = buffer
12862 .diagnostics_in_range::<usize>(search_start..buffer.len())
12863 .filter(|entry| entry.diagnostic.is_primary)
12864 .filter(|entry| entry.range.start != entry.range.end)
12865 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12866 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12867 .collect::<Vec<_>>();
12868 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12869 primary_diagnostics_after
12870 .iter()
12871 .enumerate()
12872 .rev()
12873 .find_map(|(i, entry)| {
12874 if entry.diagnostic.group_id == active_group_id {
12875 Some(i)
12876 } else {
12877 None
12878 }
12879 })
12880 });
12881
12882 let next_primary_diagnostic = match direction {
12883 Direction::Prev => primary_diagnostics_before
12884 .iter()
12885 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12886 .rev()
12887 .next(),
12888 Direction::Next => primary_diagnostics_after
12889 .iter()
12890 .skip(
12891 last_same_group_diagnostic_after
12892 .map(|index| index + 1)
12893 .unwrap_or(0),
12894 )
12895 .next(),
12896 };
12897
12898 // Cycle around to the start of the buffer, potentially moving back to the start of
12899 // the currently active diagnostic.
12900 let cycle_around = || match direction {
12901 Direction::Prev => primary_diagnostics_after
12902 .iter()
12903 .rev()
12904 .chain(primary_diagnostics_before.iter().rev())
12905 .next(),
12906 Direction::Next => primary_diagnostics_before
12907 .iter()
12908 .chain(primary_diagnostics_after.iter())
12909 .next(),
12910 };
12911
12912 if let Some((primary_range, group_id)) = next_primary_diagnostic
12913 .or_else(cycle_around)
12914 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12915 {
12916 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12917 return;
12918 };
12919 self.activate_diagnostics(buffer_id, group_id, window, cx);
12920 if self.active_diagnostics.is_some() {
12921 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12922 s.select(vec![Selection {
12923 id: selection.id,
12924 start: primary_range.start,
12925 end: primary_range.start,
12926 reversed: false,
12927 goal: SelectionGoal::None,
12928 }]);
12929 });
12930 self.refresh_inline_completion(false, true, window, cx);
12931 }
12932 }
12933 }
12934
12935 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12936 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12937 let snapshot = self.snapshot(window, cx);
12938 let selection = self.selections.newest::<Point>(cx);
12939 self.go_to_hunk_before_or_after_position(
12940 &snapshot,
12941 selection.head(),
12942 Direction::Next,
12943 window,
12944 cx,
12945 );
12946 }
12947
12948 pub fn go_to_hunk_before_or_after_position(
12949 &mut self,
12950 snapshot: &EditorSnapshot,
12951 position: Point,
12952 direction: Direction,
12953 window: &mut Window,
12954 cx: &mut Context<Editor>,
12955 ) {
12956 let row = if direction == Direction::Next {
12957 self.hunk_after_position(snapshot, position)
12958 .map(|hunk| hunk.row_range.start)
12959 } else {
12960 self.hunk_before_position(snapshot, position)
12961 };
12962
12963 if let Some(row) = row {
12964 let destination = Point::new(row.0, 0);
12965 let autoscroll = Autoscroll::center();
12966
12967 self.unfold_ranges(&[destination..destination], false, false, cx);
12968 self.change_selections(Some(autoscroll), window, cx, |s| {
12969 s.select_ranges([destination..destination]);
12970 });
12971 }
12972 }
12973
12974 fn hunk_after_position(
12975 &mut self,
12976 snapshot: &EditorSnapshot,
12977 position: Point,
12978 ) -> Option<MultiBufferDiffHunk> {
12979 snapshot
12980 .buffer_snapshot
12981 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12982 .find(|hunk| hunk.row_range.start.0 > position.row)
12983 .or_else(|| {
12984 snapshot
12985 .buffer_snapshot
12986 .diff_hunks_in_range(Point::zero()..position)
12987 .find(|hunk| hunk.row_range.end.0 < position.row)
12988 })
12989 }
12990
12991 fn go_to_prev_hunk(
12992 &mut self,
12993 _: &GoToPreviousHunk,
12994 window: &mut Window,
12995 cx: &mut Context<Self>,
12996 ) {
12997 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12998 let snapshot = self.snapshot(window, cx);
12999 let selection = self.selections.newest::<Point>(cx);
13000 self.go_to_hunk_before_or_after_position(
13001 &snapshot,
13002 selection.head(),
13003 Direction::Prev,
13004 window,
13005 cx,
13006 );
13007 }
13008
13009 fn hunk_before_position(
13010 &mut self,
13011 snapshot: &EditorSnapshot,
13012 position: Point,
13013 ) -> Option<MultiBufferRow> {
13014 snapshot
13015 .buffer_snapshot
13016 .diff_hunk_before(position)
13017 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13018 }
13019
13020 fn go_to_line<T: 'static>(
13021 &mut self,
13022 position: Anchor,
13023 highlight_color: Option<Hsla>,
13024 window: &mut Window,
13025 cx: &mut Context<Self>,
13026 ) {
13027 let snapshot = self.snapshot(window, cx).display_snapshot;
13028 let position = position.to_point(&snapshot.buffer_snapshot);
13029 let start = snapshot
13030 .buffer_snapshot
13031 .clip_point(Point::new(position.row, 0), Bias::Left);
13032 let end = start + Point::new(1, 0);
13033 let start = snapshot.buffer_snapshot.anchor_before(start);
13034 let end = snapshot.buffer_snapshot.anchor_before(end);
13035
13036 self.highlight_rows::<T>(
13037 start..end,
13038 highlight_color
13039 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13040 false,
13041 cx,
13042 );
13043 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13044 }
13045
13046 pub fn go_to_definition(
13047 &mut self,
13048 _: &GoToDefinition,
13049 window: &mut Window,
13050 cx: &mut Context<Self>,
13051 ) -> Task<Result<Navigated>> {
13052 let definition =
13053 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13054 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13055 cx.spawn_in(window, async move |editor, cx| {
13056 if definition.await? == Navigated::Yes {
13057 return Ok(Navigated::Yes);
13058 }
13059 match fallback_strategy {
13060 GoToDefinitionFallback::None => Ok(Navigated::No),
13061 GoToDefinitionFallback::FindAllReferences => {
13062 match editor.update_in(cx, |editor, window, cx| {
13063 editor.find_all_references(&FindAllReferences, window, cx)
13064 })? {
13065 Some(references) => references.await,
13066 None => Ok(Navigated::No),
13067 }
13068 }
13069 }
13070 })
13071 }
13072
13073 pub fn go_to_declaration(
13074 &mut self,
13075 _: &GoToDeclaration,
13076 window: &mut Window,
13077 cx: &mut Context<Self>,
13078 ) -> Task<Result<Navigated>> {
13079 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13080 }
13081
13082 pub fn go_to_declaration_split(
13083 &mut self,
13084 _: &GoToDeclaration,
13085 window: &mut Window,
13086 cx: &mut Context<Self>,
13087 ) -> Task<Result<Navigated>> {
13088 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13089 }
13090
13091 pub fn go_to_implementation(
13092 &mut self,
13093 _: &GoToImplementation,
13094 window: &mut Window,
13095 cx: &mut Context<Self>,
13096 ) -> Task<Result<Navigated>> {
13097 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13098 }
13099
13100 pub fn go_to_implementation_split(
13101 &mut self,
13102 _: &GoToImplementationSplit,
13103 window: &mut Window,
13104 cx: &mut Context<Self>,
13105 ) -> Task<Result<Navigated>> {
13106 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13107 }
13108
13109 pub fn go_to_type_definition(
13110 &mut self,
13111 _: &GoToTypeDefinition,
13112 window: &mut Window,
13113 cx: &mut Context<Self>,
13114 ) -> Task<Result<Navigated>> {
13115 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13116 }
13117
13118 pub fn go_to_definition_split(
13119 &mut self,
13120 _: &GoToDefinitionSplit,
13121 window: &mut Window,
13122 cx: &mut Context<Self>,
13123 ) -> Task<Result<Navigated>> {
13124 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13125 }
13126
13127 pub fn go_to_type_definition_split(
13128 &mut self,
13129 _: &GoToTypeDefinitionSplit,
13130 window: &mut Window,
13131 cx: &mut Context<Self>,
13132 ) -> Task<Result<Navigated>> {
13133 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13134 }
13135
13136 fn go_to_definition_of_kind(
13137 &mut self,
13138 kind: GotoDefinitionKind,
13139 split: bool,
13140 window: &mut Window,
13141 cx: &mut Context<Self>,
13142 ) -> Task<Result<Navigated>> {
13143 let Some(provider) = self.semantics_provider.clone() else {
13144 return Task::ready(Ok(Navigated::No));
13145 };
13146 let head = self.selections.newest::<usize>(cx).head();
13147 let buffer = self.buffer.read(cx);
13148 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13149 text_anchor
13150 } else {
13151 return Task::ready(Ok(Navigated::No));
13152 };
13153
13154 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13155 return Task::ready(Ok(Navigated::No));
13156 };
13157
13158 cx.spawn_in(window, async move |editor, cx| {
13159 let definitions = definitions.await?;
13160 let navigated = editor
13161 .update_in(cx, |editor, window, cx| {
13162 editor.navigate_to_hover_links(
13163 Some(kind),
13164 definitions
13165 .into_iter()
13166 .filter(|location| {
13167 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13168 })
13169 .map(HoverLink::Text)
13170 .collect::<Vec<_>>(),
13171 split,
13172 window,
13173 cx,
13174 )
13175 })?
13176 .await?;
13177 anyhow::Ok(navigated)
13178 })
13179 }
13180
13181 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13182 let selection = self.selections.newest_anchor();
13183 let head = selection.head();
13184 let tail = selection.tail();
13185
13186 let Some((buffer, start_position)) =
13187 self.buffer.read(cx).text_anchor_for_position(head, cx)
13188 else {
13189 return;
13190 };
13191
13192 let end_position = if head != tail {
13193 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13194 return;
13195 };
13196 Some(pos)
13197 } else {
13198 None
13199 };
13200
13201 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13202 let url = if let Some(end_pos) = end_position {
13203 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13204 } else {
13205 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13206 };
13207
13208 if let Some(url) = url {
13209 editor.update(cx, |_, cx| {
13210 cx.open_url(&url);
13211 })
13212 } else {
13213 Ok(())
13214 }
13215 });
13216
13217 url_finder.detach();
13218 }
13219
13220 pub fn open_selected_filename(
13221 &mut self,
13222 _: &OpenSelectedFilename,
13223 window: &mut Window,
13224 cx: &mut Context<Self>,
13225 ) {
13226 let Some(workspace) = self.workspace() else {
13227 return;
13228 };
13229
13230 let position = self.selections.newest_anchor().head();
13231
13232 let Some((buffer, buffer_position)) =
13233 self.buffer.read(cx).text_anchor_for_position(position, cx)
13234 else {
13235 return;
13236 };
13237
13238 let project = self.project.clone();
13239
13240 cx.spawn_in(window, async move |_, cx| {
13241 let result = find_file(&buffer, project, buffer_position, cx).await;
13242
13243 if let Some((_, path)) = result {
13244 workspace
13245 .update_in(cx, |workspace, window, cx| {
13246 workspace.open_resolved_path(path, window, cx)
13247 })?
13248 .await?;
13249 }
13250 anyhow::Ok(())
13251 })
13252 .detach();
13253 }
13254
13255 pub(crate) fn navigate_to_hover_links(
13256 &mut self,
13257 kind: Option<GotoDefinitionKind>,
13258 mut definitions: Vec<HoverLink>,
13259 split: bool,
13260 window: &mut Window,
13261 cx: &mut Context<Editor>,
13262 ) -> Task<Result<Navigated>> {
13263 // If there is one definition, just open it directly
13264 if definitions.len() == 1 {
13265 let definition = definitions.pop().unwrap();
13266
13267 enum TargetTaskResult {
13268 Location(Option<Location>),
13269 AlreadyNavigated,
13270 }
13271
13272 let target_task = match definition {
13273 HoverLink::Text(link) => {
13274 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13275 }
13276 HoverLink::InlayHint(lsp_location, server_id) => {
13277 let computation =
13278 self.compute_target_location(lsp_location, server_id, window, cx);
13279 cx.background_spawn(async move {
13280 let location = computation.await?;
13281 Ok(TargetTaskResult::Location(location))
13282 })
13283 }
13284 HoverLink::Url(url) => {
13285 cx.open_url(&url);
13286 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13287 }
13288 HoverLink::File(path) => {
13289 if let Some(workspace) = self.workspace() {
13290 cx.spawn_in(window, async move |_, cx| {
13291 workspace
13292 .update_in(cx, |workspace, window, cx| {
13293 workspace.open_resolved_path(path, window, cx)
13294 })?
13295 .await
13296 .map(|_| TargetTaskResult::AlreadyNavigated)
13297 })
13298 } else {
13299 Task::ready(Ok(TargetTaskResult::Location(None)))
13300 }
13301 }
13302 };
13303 cx.spawn_in(window, async move |editor, cx| {
13304 let target = match target_task.await.context("target resolution task")? {
13305 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13306 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13307 TargetTaskResult::Location(Some(target)) => target,
13308 };
13309
13310 editor.update_in(cx, |editor, window, cx| {
13311 let Some(workspace) = editor.workspace() else {
13312 return Navigated::No;
13313 };
13314 let pane = workspace.read(cx).active_pane().clone();
13315
13316 let range = target.range.to_point(target.buffer.read(cx));
13317 let range = editor.range_for_match(&range);
13318 let range = collapse_multiline_range(range);
13319
13320 if !split
13321 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13322 {
13323 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13324 } else {
13325 window.defer(cx, move |window, cx| {
13326 let target_editor: Entity<Self> =
13327 workspace.update(cx, |workspace, cx| {
13328 let pane = if split {
13329 workspace.adjacent_pane(window, cx)
13330 } else {
13331 workspace.active_pane().clone()
13332 };
13333
13334 workspace.open_project_item(
13335 pane,
13336 target.buffer.clone(),
13337 true,
13338 true,
13339 window,
13340 cx,
13341 )
13342 });
13343 target_editor.update(cx, |target_editor, cx| {
13344 // When selecting a definition in a different buffer, disable the nav history
13345 // to avoid creating a history entry at the previous cursor location.
13346 pane.update(cx, |pane, _| pane.disable_history());
13347 target_editor.go_to_singleton_buffer_range(range, window, cx);
13348 pane.update(cx, |pane, _| pane.enable_history());
13349 });
13350 });
13351 }
13352 Navigated::Yes
13353 })
13354 })
13355 } else if !definitions.is_empty() {
13356 cx.spawn_in(window, async move |editor, cx| {
13357 let (title, location_tasks, workspace) = editor
13358 .update_in(cx, |editor, window, cx| {
13359 let tab_kind = match kind {
13360 Some(GotoDefinitionKind::Implementation) => "Implementations",
13361 _ => "Definitions",
13362 };
13363 let title = definitions
13364 .iter()
13365 .find_map(|definition| match definition {
13366 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13367 let buffer = origin.buffer.read(cx);
13368 format!(
13369 "{} for {}",
13370 tab_kind,
13371 buffer
13372 .text_for_range(origin.range.clone())
13373 .collect::<String>()
13374 )
13375 }),
13376 HoverLink::InlayHint(_, _) => None,
13377 HoverLink::Url(_) => None,
13378 HoverLink::File(_) => None,
13379 })
13380 .unwrap_or(tab_kind.to_string());
13381 let location_tasks = definitions
13382 .into_iter()
13383 .map(|definition| match definition {
13384 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13385 HoverLink::InlayHint(lsp_location, server_id) => editor
13386 .compute_target_location(lsp_location, server_id, window, cx),
13387 HoverLink::Url(_) => Task::ready(Ok(None)),
13388 HoverLink::File(_) => Task::ready(Ok(None)),
13389 })
13390 .collect::<Vec<_>>();
13391 (title, location_tasks, editor.workspace().clone())
13392 })
13393 .context("location tasks preparation")?;
13394
13395 let locations = future::join_all(location_tasks)
13396 .await
13397 .into_iter()
13398 .filter_map(|location| location.transpose())
13399 .collect::<Result<_>>()
13400 .context("location tasks")?;
13401
13402 let Some(workspace) = workspace else {
13403 return Ok(Navigated::No);
13404 };
13405 let opened = workspace
13406 .update_in(cx, |workspace, window, cx| {
13407 Self::open_locations_in_multibuffer(
13408 workspace,
13409 locations,
13410 title,
13411 split,
13412 MultibufferSelectionMode::First,
13413 window,
13414 cx,
13415 )
13416 })
13417 .ok();
13418
13419 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13420 })
13421 } else {
13422 Task::ready(Ok(Navigated::No))
13423 }
13424 }
13425
13426 fn compute_target_location(
13427 &self,
13428 lsp_location: lsp::Location,
13429 server_id: LanguageServerId,
13430 window: &mut Window,
13431 cx: &mut Context<Self>,
13432 ) -> Task<anyhow::Result<Option<Location>>> {
13433 let Some(project) = self.project.clone() else {
13434 return Task::ready(Ok(None));
13435 };
13436
13437 cx.spawn_in(window, async move |editor, cx| {
13438 let location_task = editor.update(cx, |_, cx| {
13439 project.update(cx, |project, cx| {
13440 let language_server_name = project
13441 .language_server_statuses(cx)
13442 .find(|(id, _)| server_id == *id)
13443 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13444 language_server_name.map(|language_server_name| {
13445 project.open_local_buffer_via_lsp(
13446 lsp_location.uri.clone(),
13447 server_id,
13448 language_server_name,
13449 cx,
13450 )
13451 })
13452 })
13453 })?;
13454 let location = match location_task {
13455 Some(task) => Some({
13456 let target_buffer_handle = task.await.context("open local buffer")?;
13457 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13458 let target_start = target_buffer
13459 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13460 let target_end = target_buffer
13461 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13462 target_buffer.anchor_after(target_start)
13463 ..target_buffer.anchor_before(target_end)
13464 })?;
13465 Location {
13466 buffer: target_buffer_handle,
13467 range,
13468 }
13469 }),
13470 None => None,
13471 };
13472 Ok(location)
13473 })
13474 }
13475
13476 pub fn find_all_references(
13477 &mut self,
13478 _: &FindAllReferences,
13479 window: &mut Window,
13480 cx: &mut Context<Self>,
13481 ) -> Option<Task<Result<Navigated>>> {
13482 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13483
13484 let selection = self.selections.newest::<usize>(cx);
13485 let multi_buffer = self.buffer.read(cx);
13486 let head = selection.head();
13487
13488 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13489 let head_anchor = multi_buffer_snapshot.anchor_at(
13490 head,
13491 if head < selection.tail() {
13492 Bias::Right
13493 } else {
13494 Bias::Left
13495 },
13496 );
13497
13498 match self
13499 .find_all_references_task_sources
13500 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13501 {
13502 Ok(_) => {
13503 log::info!(
13504 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13505 );
13506 return None;
13507 }
13508 Err(i) => {
13509 self.find_all_references_task_sources.insert(i, head_anchor);
13510 }
13511 }
13512
13513 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13514 let workspace = self.workspace()?;
13515 let project = workspace.read(cx).project().clone();
13516 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13517 Some(cx.spawn_in(window, async move |editor, cx| {
13518 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13519 if let Ok(i) = editor
13520 .find_all_references_task_sources
13521 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13522 {
13523 editor.find_all_references_task_sources.remove(i);
13524 }
13525 });
13526
13527 let locations = references.await?;
13528 if locations.is_empty() {
13529 return anyhow::Ok(Navigated::No);
13530 }
13531
13532 workspace.update_in(cx, |workspace, window, cx| {
13533 let title = locations
13534 .first()
13535 .as_ref()
13536 .map(|location| {
13537 let buffer = location.buffer.read(cx);
13538 format!(
13539 "References to `{}`",
13540 buffer
13541 .text_for_range(location.range.clone())
13542 .collect::<String>()
13543 )
13544 })
13545 .unwrap();
13546 Self::open_locations_in_multibuffer(
13547 workspace,
13548 locations,
13549 title,
13550 false,
13551 MultibufferSelectionMode::First,
13552 window,
13553 cx,
13554 );
13555 Navigated::Yes
13556 })
13557 }))
13558 }
13559
13560 /// Opens a multibuffer with the given project locations in it
13561 pub fn open_locations_in_multibuffer(
13562 workspace: &mut Workspace,
13563 mut locations: Vec<Location>,
13564 title: String,
13565 split: bool,
13566 multibuffer_selection_mode: MultibufferSelectionMode,
13567 window: &mut Window,
13568 cx: &mut Context<Workspace>,
13569 ) {
13570 // If there are multiple definitions, open them in a multibuffer
13571 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13572 let mut locations = locations.into_iter().peekable();
13573 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13574 let capability = workspace.project().read(cx).capability();
13575
13576 let excerpt_buffer = cx.new(|cx| {
13577 let mut multibuffer = MultiBuffer::new(capability);
13578 while let Some(location) = locations.next() {
13579 let buffer = location.buffer.read(cx);
13580 let mut ranges_for_buffer = Vec::new();
13581 let range = location.range.to_point(buffer);
13582 ranges_for_buffer.push(range.clone());
13583
13584 while let Some(next_location) = locations.peek() {
13585 if next_location.buffer == location.buffer {
13586 ranges_for_buffer.push(next_location.range.to_point(buffer));
13587 locations.next();
13588 } else {
13589 break;
13590 }
13591 }
13592
13593 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13594 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13595 PathKey::for_buffer(&location.buffer, cx),
13596 location.buffer.clone(),
13597 ranges_for_buffer,
13598 DEFAULT_MULTIBUFFER_CONTEXT,
13599 cx,
13600 );
13601 ranges.extend(new_ranges)
13602 }
13603
13604 multibuffer.with_title(title)
13605 });
13606
13607 let editor = cx.new(|cx| {
13608 Editor::for_multibuffer(
13609 excerpt_buffer,
13610 Some(workspace.project().clone()),
13611 window,
13612 cx,
13613 )
13614 });
13615 editor.update(cx, |editor, cx| {
13616 match multibuffer_selection_mode {
13617 MultibufferSelectionMode::First => {
13618 if let Some(first_range) = ranges.first() {
13619 editor.change_selections(None, window, cx, |selections| {
13620 selections.clear_disjoint();
13621 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13622 });
13623 }
13624 editor.highlight_background::<Self>(
13625 &ranges,
13626 |theme| theme.editor_highlighted_line_background,
13627 cx,
13628 );
13629 }
13630 MultibufferSelectionMode::All => {
13631 editor.change_selections(None, window, cx, |selections| {
13632 selections.clear_disjoint();
13633 selections.select_anchor_ranges(ranges);
13634 });
13635 }
13636 }
13637 editor.register_buffers_with_language_servers(cx);
13638 });
13639
13640 let item = Box::new(editor);
13641 let item_id = item.item_id();
13642
13643 if split {
13644 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13645 } else {
13646 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13647 let (preview_item_id, preview_item_idx) =
13648 workspace.active_pane().update(cx, |pane, _| {
13649 (pane.preview_item_id(), pane.preview_item_idx())
13650 });
13651
13652 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13653
13654 if let Some(preview_item_id) = preview_item_id {
13655 workspace.active_pane().update(cx, |pane, cx| {
13656 pane.remove_item(preview_item_id, false, false, window, cx);
13657 });
13658 }
13659 } else {
13660 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13661 }
13662 }
13663 workspace.active_pane().update(cx, |pane, cx| {
13664 pane.set_preview_item_id(Some(item_id), cx);
13665 });
13666 }
13667
13668 pub fn rename(
13669 &mut self,
13670 _: &Rename,
13671 window: &mut Window,
13672 cx: &mut Context<Self>,
13673 ) -> Option<Task<Result<()>>> {
13674 use language::ToOffset as _;
13675
13676 let provider = self.semantics_provider.clone()?;
13677 let selection = self.selections.newest_anchor().clone();
13678 let (cursor_buffer, cursor_buffer_position) = self
13679 .buffer
13680 .read(cx)
13681 .text_anchor_for_position(selection.head(), cx)?;
13682 let (tail_buffer, cursor_buffer_position_end) = self
13683 .buffer
13684 .read(cx)
13685 .text_anchor_for_position(selection.tail(), cx)?;
13686 if tail_buffer != cursor_buffer {
13687 return None;
13688 }
13689
13690 let snapshot = cursor_buffer.read(cx).snapshot();
13691 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13692 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13693 let prepare_rename = provider
13694 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13695 .unwrap_or_else(|| Task::ready(Ok(None)));
13696 drop(snapshot);
13697
13698 Some(cx.spawn_in(window, async move |this, cx| {
13699 let rename_range = if let Some(range) = prepare_rename.await? {
13700 Some(range)
13701 } else {
13702 this.update(cx, |this, cx| {
13703 let buffer = this.buffer.read(cx).snapshot(cx);
13704 let mut buffer_highlights = this
13705 .document_highlights_for_position(selection.head(), &buffer)
13706 .filter(|highlight| {
13707 highlight.start.excerpt_id == selection.head().excerpt_id
13708 && highlight.end.excerpt_id == selection.head().excerpt_id
13709 });
13710 buffer_highlights
13711 .next()
13712 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13713 })?
13714 };
13715 if let Some(rename_range) = rename_range {
13716 this.update_in(cx, |this, window, cx| {
13717 let snapshot = cursor_buffer.read(cx).snapshot();
13718 let rename_buffer_range = rename_range.to_offset(&snapshot);
13719 let cursor_offset_in_rename_range =
13720 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13721 let cursor_offset_in_rename_range_end =
13722 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13723
13724 this.take_rename(false, window, cx);
13725 let buffer = this.buffer.read(cx).read(cx);
13726 let cursor_offset = selection.head().to_offset(&buffer);
13727 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13728 let rename_end = rename_start + rename_buffer_range.len();
13729 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13730 let mut old_highlight_id = None;
13731 let old_name: Arc<str> = buffer
13732 .chunks(rename_start..rename_end, true)
13733 .map(|chunk| {
13734 if old_highlight_id.is_none() {
13735 old_highlight_id = chunk.syntax_highlight_id;
13736 }
13737 chunk.text
13738 })
13739 .collect::<String>()
13740 .into();
13741
13742 drop(buffer);
13743
13744 // Position the selection in the rename editor so that it matches the current selection.
13745 this.show_local_selections = false;
13746 let rename_editor = cx.new(|cx| {
13747 let mut editor = Editor::single_line(window, cx);
13748 editor.buffer.update(cx, |buffer, cx| {
13749 buffer.edit([(0..0, old_name.clone())], None, cx)
13750 });
13751 let rename_selection_range = match cursor_offset_in_rename_range
13752 .cmp(&cursor_offset_in_rename_range_end)
13753 {
13754 Ordering::Equal => {
13755 editor.select_all(&SelectAll, window, cx);
13756 return editor;
13757 }
13758 Ordering::Less => {
13759 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13760 }
13761 Ordering::Greater => {
13762 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13763 }
13764 };
13765 if rename_selection_range.end > old_name.len() {
13766 editor.select_all(&SelectAll, window, cx);
13767 } else {
13768 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13769 s.select_ranges([rename_selection_range]);
13770 });
13771 }
13772 editor
13773 });
13774 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13775 if e == &EditorEvent::Focused {
13776 cx.emit(EditorEvent::FocusedIn)
13777 }
13778 })
13779 .detach();
13780
13781 let write_highlights =
13782 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13783 let read_highlights =
13784 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13785 let ranges = write_highlights
13786 .iter()
13787 .flat_map(|(_, ranges)| ranges.iter())
13788 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13789 .cloned()
13790 .collect();
13791
13792 this.highlight_text::<Rename>(
13793 ranges,
13794 HighlightStyle {
13795 fade_out: Some(0.6),
13796 ..Default::default()
13797 },
13798 cx,
13799 );
13800 let rename_focus_handle = rename_editor.focus_handle(cx);
13801 window.focus(&rename_focus_handle);
13802 let block_id = this.insert_blocks(
13803 [BlockProperties {
13804 style: BlockStyle::Flex,
13805 placement: BlockPlacement::Below(range.start),
13806 height: Some(1),
13807 render: Arc::new({
13808 let rename_editor = rename_editor.clone();
13809 move |cx: &mut BlockContext| {
13810 let mut text_style = cx.editor_style.text.clone();
13811 if let Some(highlight_style) = old_highlight_id
13812 .and_then(|h| h.style(&cx.editor_style.syntax))
13813 {
13814 text_style = text_style.highlight(highlight_style);
13815 }
13816 div()
13817 .block_mouse_down()
13818 .pl(cx.anchor_x)
13819 .child(EditorElement::new(
13820 &rename_editor,
13821 EditorStyle {
13822 background: cx.theme().system().transparent,
13823 local_player: cx.editor_style.local_player,
13824 text: text_style,
13825 scrollbar_width: cx.editor_style.scrollbar_width,
13826 syntax: cx.editor_style.syntax.clone(),
13827 status: cx.editor_style.status.clone(),
13828 inlay_hints_style: HighlightStyle {
13829 font_weight: Some(FontWeight::BOLD),
13830 ..make_inlay_hints_style(cx.app)
13831 },
13832 inline_completion_styles: make_suggestion_styles(
13833 cx.app,
13834 ),
13835 ..EditorStyle::default()
13836 },
13837 ))
13838 .into_any_element()
13839 }
13840 }),
13841 priority: 0,
13842 }],
13843 Some(Autoscroll::fit()),
13844 cx,
13845 )[0];
13846 this.pending_rename = Some(RenameState {
13847 range,
13848 old_name,
13849 editor: rename_editor,
13850 block_id,
13851 });
13852 })?;
13853 }
13854
13855 Ok(())
13856 }))
13857 }
13858
13859 pub fn confirm_rename(
13860 &mut self,
13861 _: &ConfirmRename,
13862 window: &mut Window,
13863 cx: &mut Context<Self>,
13864 ) -> Option<Task<Result<()>>> {
13865 let rename = self.take_rename(false, window, cx)?;
13866 let workspace = self.workspace()?.downgrade();
13867 let (buffer, start) = self
13868 .buffer
13869 .read(cx)
13870 .text_anchor_for_position(rename.range.start, cx)?;
13871 let (end_buffer, _) = self
13872 .buffer
13873 .read(cx)
13874 .text_anchor_for_position(rename.range.end, cx)?;
13875 if buffer != end_buffer {
13876 return None;
13877 }
13878
13879 let old_name = rename.old_name;
13880 let new_name = rename.editor.read(cx).text(cx);
13881
13882 let rename = self.semantics_provider.as_ref()?.perform_rename(
13883 &buffer,
13884 start,
13885 new_name.clone(),
13886 cx,
13887 )?;
13888
13889 Some(cx.spawn_in(window, async move |editor, cx| {
13890 let project_transaction = rename.await?;
13891 Self::open_project_transaction(
13892 &editor,
13893 workspace,
13894 project_transaction,
13895 format!("Rename: {} → {}", old_name, new_name),
13896 cx,
13897 )
13898 .await?;
13899
13900 editor.update(cx, |editor, cx| {
13901 editor.refresh_document_highlights(cx);
13902 })?;
13903 Ok(())
13904 }))
13905 }
13906
13907 fn take_rename(
13908 &mut self,
13909 moving_cursor: bool,
13910 window: &mut Window,
13911 cx: &mut Context<Self>,
13912 ) -> Option<RenameState> {
13913 let rename = self.pending_rename.take()?;
13914 if rename.editor.focus_handle(cx).is_focused(window) {
13915 window.focus(&self.focus_handle);
13916 }
13917
13918 self.remove_blocks(
13919 [rename.block_id].into_iter().collect(),
13920 Some(Autoscroll::fit()),
13921 cx,
13922 );
13923 self.clear_highlights::<Rename>(cx);
13924 self.show_local_selections = true;
13925
13926 if moving_cursor {
13927 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13928 editor.selections.newest::<usize>(cx).head()
13929 });
13930
13931 // Update the selection to match the position of the selection inside
13932 // the rename editor.
13933 let snapshot = self.buffer.read(cx).read(cx);
13934 let rename_range = rename.range.to_offset(&snapshot);
13935 let cursor_in_editor = snapshot
13936 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13937 .min(rename_range.end);
13938 drop(snapshot);
13939
13940 self.change_selections(None, window, cx, |s| {
13941 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13942 });
13943 } else {
13944 self.refresh_document_highlights(cx);
13945 }
13946
13947 Some(rename)
13948 }
13949
13950 pub fn pending_rename(&self) -> Option<&RenameState> {
13951 self.pending_rename.as_ref()
13952 }
13953
13954 fn format(
13955 &mut self,
13956 _: &Format,
13957 window: &mut Window,
13958 cx: &mut Context<Self>,
13959 ) -> Option<Task<Result<()>>> {
13960 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13961
13962 let project = match &self.project {
13963 Some(project) => project.clone(),
13964 None => return None,
13965 };
13966
13967 Some(self.perform_format(
13968 project,
13969 FormatTrigger::Manual,
13970 FormatTarget::Buffers,
13971 window,
13972 cx,
13973 ))
13974 }
13975
13976 fn format_selections(
13977 &mut self,
13978 _: &FormatSelections,
13979 window: &mut Window,
13980 cx: &mut Context<Self>,
13981 ) -> Option<Task<Result<()>>> {
13982 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13983
13984 let project = match &self.project {
13985 Some(project) => project.clone(),
13986 None => return None,
13987 };
13988
13989 let ranges = self
13990 .selections
13991 .all_adjusted(cx)
13992 .into_iter()
13993 .map(|selection| selection.range())
13994 .collect_vec();
13995
13996 Some(self.perform_format(
13997 project,
13998 FormatTrigger::Manual,
13999 FormatTarget::Ranges(ranges),
14000 window,
14001 cx,
14002 ))
14003 }
14004
14005 fn perform_format(
14006 &mut self,
14007 project: Entity<Project>,
14008 trigger: FormatTrigger,
14009 target: FormatTarget,
14010 window: &mut Window,
14011 cx: &mut Context<Self>,
14012 ) -> Task<Result<()>> {
14013 let buffer = self.buffer.clone();
14014 let (buffers, target) = match target {
14015 FormatTarget::Buffers => {
14016 let mut buffers = buffer.read(cx).all_buffers();
14017 if trigger == FormatTrigger::Save {
14018 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14019 }
14020 (buffers, LspFormatTarget::Buffers)
14021 }
14022 FormatTarget::Ranges(selection_ranges) => {
14023 let multi_buffer = buffer.read(cx);
14024 let snapshot = multi_buffer.read(cx);
14025 let mut buffers = HashSet::default();
14026 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14027 BTreeMap::new();
14028 for selection_range in selection_ranges {
14029 for (buffer, buffer_range, _) in
14030 snapshot.range_to_buffer_ranges(selection_range)
14031 {
14032 let buffer_id = buffer.remote_id();
14033 let start = buffer.anchor_before(buffer_range.start);
14034 let end = buffer.anchor_after(buffer_range.end);
14035 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14036 buffer_id_to_ranges
14037 .entry(buffer_id)
14038 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14039 .or_insert_with(|| vec![start..end]);
14040 }
14041 }
14042 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14043 }
14044 };
14045
14046 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14047 let format = project.update(cx, |project, cx| {
14048 project.format(buffers, target, true, trigger, cx)
14049 });
14050
14051 cx.spawn_in(window, async move |_, cx| {
14052 let transaction = futures::select_biased! {
14053 transaction = format.log_err().fuse() => transaction,
14054 () = timeout => {
14055 log::warn!("timed out waiting for formatting");
14056 None
14057 }
14058 };
14059
14060 buffer
14061 .update(cx, |buffer, cx| {
14062 if let Some(transaction) = transaction {
14063 if !buffer.is_singleton() {
14064 buffer.push_transaction(&transaction.0, cx);
14065 }
14066 }
14067 cx.notify();
14068 })
14069 .ok();
14070
14071 Ok(())
14072 })
14073 }
14074
14075 fn organize_imports(
14076 &mut self,
14077 _: &OrganizeImports,
14078 window: &mut Window,
14079 cx: &mut Context<Self>,
14080 ) -> Option<Task<Result<()>>> {
14081 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14082 let project = match &self.project {
14083 Some(project) => project.clone(),
14084 None => return None,
14085 };
14086 Some(self.perform_code_action_kind(
14087 project,
14088 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14089 window,
14090 cx,
14091 ))
14092 }
14093
14094 fn perform_code_action_kind(
14095 &mut self,
14096 project: Entity<Project>,
14097 kind: CodeActionKind,
14098 window: &mut Window,
14099 cx: &mut Context<Self>,
14100 ) -> Task<Result<()>> {
14101 let buffer = self.buffer.clone();
14102 let buffers = buffer.read(cx).all_buffers();
14103 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14104 let apply_action = project.update(cx, |project, cx| {
14105 project.apply_code_action_kind(buffers, kind, true, cx)
14106 });
14107 cx.spawn_in(window, async move |_, cx| {
14108 let transaction = futures::select_biased! {
14109 () = timeout => {
14110 log::warn!("timed out waiting for executing code action");
14111 None
14112 }
14113 transaction = apply_action.log_err().fuse() => transaction,
14114 };
14115 buffer
14116 .update(cx, |buffer, cx| {
14117 // check if we need this
14118 if let Some(transaction) = transaction {
14119 if !buffer.is_singleton() {
14120 buffer.push_transaction(&transaction.0, cx);
14121 }
14122 }
14123 cx.notify();
14124 })
14125 .ok();
14126 Ok(())
14127 })
14128 }
14129
14130 fn restart_language_server(
14131 &mut self,
14132 _: &RestartLanguageServer,
14133 _: &mut Window,
14134 cx: &mut Context<Self>,
14135 ) {
14136 if let Some(project) = self.project.clone() {
14137 self.buffer.update(cx, |multi_buffer, cx| {
14138 project.update(cx, |project, cx| {
14139 project.restart_language_servers_for_buffers(
14140 multi_buffer.all_buffers().into_iter().collect(),
14141 cx,
14142 );
14143 });
14144 })
14145 }
14146 }
14147
14148 fn cancel_language_server_work(
14149 workspace: &mut Workspace,
14150 _: &actions::CancelLanguageServerWork,
14151 _: &mut Window,
14152 cx: &mut Context<Workspace>,
14153 ) {
14154 let project = workspace.project();
14155 let buffers = workspace
14156 .active_item(cx)
14157 .and_then(|item| item.act_as::<Editor>(cx))
14158 .map_or(HashSet::default(), |editor| {
14159 editor.read(cx).buffer.read(cx).all_buffers()
14160 });
14161 project.update(cx, |project, cx| {
14162 project.cancel_language_server_work_for_buffers(buffers, cx);
14163 });
14164 }
14165
14166 fn show_character_palette(
14167 &mut self,
14168 _: &ShowCharacterPalette,
14169 window: &mut Window,
14170 _: &mut Context<Self>,
14171 ) {
14172 window.show_character_palette();
14173 }
14174
14175 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14176 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14177 let buffer = self.buffer.read(cx).snapshot(cx);
14178 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14179 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14180 let is_valid = buffer
14181 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14182 .any(|entry| {
14183 entry.diagnostic.is_primary
14184 && !entry.range.is_empty()
14185 && entry.range.start == primary_range_start
14186 && entry.diagnostic.message == active_diagnostics.primary_message
14187 });
14188
14189 if is_valid != active_diagnostics.is_valid {
14190 active_diagnostics.is_valid = is_valid;
14191 if is_valid {
14192 let mut new_styles = HashMap::default();
14193 for (block_id, diagnostic) in &active_diagnostics.blocks {
14194 new_styles.insert(
14195 *block_id,
14196 diagnostic_block_renderer(diagnostic.clone(), None, true),
14197 );
14198 }
14199 self.display_map.update(cx, |display_map, _cx| {
14200 display_map.replace_blocks(new_styles);
14201 });
14202 } else {
14203 self.dismiss_diagnostics(cx);
14204 }
14205 }
14206 }
14207 }
14208
14209 fn activate_diagnostics(
14210 &mut self,
14211 buffer_id: BufferId,
14212 group_id: usize,
14213 window: &mut Window,
14214 cx: &mut Context<Self>,
14215 ) {
14216 self.dismiss_diagnostics(cx);
14217 let snapshot = self.snapshot(window, cx);
14218 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14219 let buffer = self.buffer.read(cx).snapshot(cx);
14220
14221 let mut primary_range = None;
14222 let mut primary_message = None;
14223 let diagnostic_group = buffer
14224 .diagnostic_group(buffer_id, group_id)
14225 .filter_map(|entry| {
14226 let start = entry.range.start;
14227 let end = entry.range.end;
14228 if snapshot.is_line_folded(MultiBufferRow(start.row))
14229 && (start.row == end.row
14230 || snapshot.is_line_folded(MultiBufferRow(end.row)))
14231 {
14232 return None;
14233 }
14234 if entry.diagnostic.is_primary {
14235 primary_range = Some(entry.range.clone());
14236 primary_message = Some(entry.diagnostic.message.clone());
14237 }
14238 Some(entry)
14239 })
14240 .collect::<Vec<_>>();
14241 let primary_range = primary_range?;
14242 let primary_message = primary_message?;
14243
14244 let blocks = display_map
14245 .insert_blocks(
14246 diagnostic_group.iter().map(|entry| {
14247 let diagnostic = entry.diagnostic.clone();
14248 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14249 BlockProperties {
14250 style: BlockStyle::Fixed,
14251 placement: BlockPlacement::Below(
14252 buffer.anchor_after(entry.range.start),
14253 ),
14254 height: Some(message_height),
14255 render: diagnostic_block_renderer(diagnostic, None, true),
14256 priority: 0,
14257 }
14258 }),
14259 cx,
14260 )
14261 .into_iter()
14262 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14263 .collect();
14264
14265 Some(ActiveDiagnosticGroup {
14266 primary_range: buffer.anchor_before(primary_range.start)
14267 ..buffer.anchor_after(primary_range.end),
14268 primary_message,
14269 group_id,
14270 blocks,
14271 is_valid: true,
14272 })
14273 });
14274 }
14275
14276 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14277 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14278 self.display_map.update(cx, |display_map, cx| {
14279 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14280 });
14281 cx.notify();
14282 }
14283 }
14284
14285 /// Disable inline diagnostics rendering for this editor.
14286 pub fn disable_inline_diagnostics(&mut self) {
14287 self.inline_diagnostics_enabled = false;
14288 self.inline_diagnostics_update = Task::ready(());
14289 self.inline_diagnostics.clear();
14290 }
14291
14292 pub fn inline_diagnostics_enabled(&self) -> bool {
14293 self.inline_diagnostics_enabled
14294 }
14295
14296 pub fn show_inline_diagnostics(&self) -> bool {
14297 self.show_inline_diagnostics
14298 }
14299
14300 pub fn toggle_inline_diagnostics(
14301 &mut self,
14302 _: &ToggleInlineDiagnostics,
14303 window: &mut Window,
14304 cx: &mut Context<Editor>,
14305 ) {
14306 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14307 self.refresh_inline_diagnostics(false, window, cx);
14308 }
14309
14310 fn refresh_inline_diagnostics(
14311 &mut self,
14312 debounce: bool,
14313 window: &mut Window,
14314 cx: &mut Context<Self>,
14315 ) {
14316 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14317 self.inline_diagnostics_update = Task::ready(());
14318 self.inline_diagnostics.clear();
14319 return;
14320 }
14321
14322 let debounce_ms = ProjectSettings::get_global(cx)
14323 .diagnostics
14324 .inline
14325 .update_debounce_ms;
14326 let debounce = if debounce && debounce_ms > 0 {
14327 Some(Duration::from_millis(debounce_ms))
14328 } else {
14329 None
14330 };
14331 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14332 if let Some(debounce) = debounce {
14333 cx.background_executor().timer(debounce).await;
14334 }
14335 let Some(snapshot) = editor
14336 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14337 .ok()
14338 else {
14339 return;
14340 };
14341
14342 let new_inline_diagnostics = cx
14343 .background_spawn(async move {
14344 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14345 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14346 let message = diagnostic_entry
14347 .diagnostic
14348 .message
14349 .split_once('\n')
14350 .map(|(line, _)| line)
14351 .map(SharedString::new)
14352 .unwrap_or_else(|| {
14353 SharedString::from(diagnostic_entry.diagnostic.message)
14354 });
14355 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14356 let (Ok(i) | Err(i)) = inline_diagnostics
14357 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14358 inline_diagnostics.insert(
14359 i,
14360 (
14361 start_anchor,
14362 InlineDiagnostic {
14363 message,
14364 group_id: diagnostic_entry.diagnostic.group_id,
14365 start: diagnostic_entry.range.start.to_point(&snapshot),
14366 is_primary: diagnostic_entry.diagnostic.is_primary,
14367 severity: diagnostic_entry.diagnostic.severity,
14368 },
14369 ),
14370 );
14371 }
14372 inline_diagnostics
14373 })
14374 .await;
14375
14376 editor
14377 .update(cx, |editor, cx| {
14378 editor.inline_diagnostics = new_inline_diagnostics;
14379 cx.notify();
14380 })
14381 .ok();
14382 });
14383 }
14384
14385 pub fn set_selections_from_remote(
14386 &mut self,
14387 selections: Vec<Selection<Anchor>>,
14388 pending_selection: Option<Selection<Anchor>>,
14389 window: &mut Window,
14390 cx: &mut Context<Self>,
14391 ) {
14392 let old_cursor_position = self.selections.newest_anchor().head();
14393 self.selections.change_with(cx, |s| {
14394 s.select_anchors(selections);
14395 if let Some(pending_selection) = pending_selection {
14396 s.set_pending(pending_selection, SelectMode::Character);
14397 } else {
14398 s.clear_pending();
14399 }
14400 });
14401 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14402 }
14403
14404 fn push_to_selection_history(&mut self) {
14405 self.selection_history.push(SelectionHistoryEntry {
14406 selections: self.selections.disjoint_anchors(),
14407 select_next_state: self.select_next_state.clone(),
14408 select_prev_state: self.select_prev_state.clone(),
14409 add_selections_state: self.add_selections_state.clone(),
14410 });
14411 }
14412
14413 pub fn transact(
14414 &mut self,
14415 window: &mut Window,
14416 cx: &mut Context<Self>,
14417 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14418 ) -> Option<TransactionId> {
14419 self.start_transaction_at(Instant::now(), window, cx);
14420 update(self, window, cx);
14421 self.end_transaction_at(Instant::now(), cx)
14422 }
14423
14424 pub fn start_transaction_at(
14425 &mut self,
14426 now: Instant,
14427 window: &mut Window,
14428 cx: &mut Context<Self>,
14429 ) {
14430 self.end_selection(window, cx);
14431 if let Some(tx_id) = self
14432 .buffer
14433 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14434 {
14435 self.selection_history
14436 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14437 cx.emit(EditorEvent::TransactionBegun {
14438 transaction_id: tx_id,
14439 })
14440 }
14441 }
14442
14443 pub fn end_transaction_at(
14444 &mut self,
14445 now: Instant,
14446 cx: &mut Context<Self>,
14447 ) -> Option<TransactionId> {
14448 if let Some(transaction_id) = self
14449 .buffer
14450 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14451 {
14452 if let Some((_, end_selections)) =
14453 self.selection_history.transaction_mut(transaction_id)
14454 {
14455 *end_selections = Some(self.selections.disjoint_anchors());
14456 } else {
14457 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14458 }
14459
14460 cx.emit(EditorEvent::Edited { transaction_id });
14461 Some(transaction_id)
14462 } else {
14463 None
14464 }
14465 }
14466
14467 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14468 if self.selection_mark_mode {
14469 self.change_selections(None, window, cx, |s| {
14470 s.move_with(|_, sel| {
14471 sel.collapse_to(sel.head(), SelectionGoal::None);
14472 });
14473 })
14474 }
14475 self.selection_mark_mode = true;
14476 cx.notify();
14477 }
14478
14479 pub fn swap_selection_ends(
14480 &mut self,
14481 _: &actions::SwapSelectionEnds,
14482 window: &mut Window,
14483 cx: &mut Context<Self>,
14484 ) {
14485 self.change_selections(None, window, cx, |s| {
14486 s.move_with(|_, sel| {
14487 if sel.start != sel.end {
14488 sel.reversed = !sel.reversed
14489 }
14490 });
14491 });
14492 self.request_autoscroll(Autoscroll::newest(), cx);
14493 cx.notify();
14494 }
14495
14496 pub fn toggle_fold(
14497 &mut self,
14498 _: &actions::ToggleFold,
14499 window: &mut Window,
14500 cx: &mut Context<Self>,
14501 ) {
14502 if self.is_singleton(cx) {
14503 let selection = self.selections.newest::<Point>(cx);
14504
14505 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14506 let range = if selection.is_empty() {
14507 let point = selection.head().to_display_point(&display_map);
14508 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14509 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14510 .to_point(&display_map);
14511 start..end
14512 } else {
14513 selection.range()
14514 };
14515 if display_map.folds_in_range(range).next().is_some() {
14516 self.unfold_lines(&Default::default(), window, cx)
14517 } else {
14518 self.fold(&Default::default(), window, cx)
14519 }
14520 } else {
14521 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14522 let buffer_ids: HashSet<_> = self
14523 .selections
14524 .disjoint_anchor_ranges()
14525 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14526 .collect();
14527
14528 let should_unfold = buffer_ids
14529 .iter()
14530 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14531
14532 for buffer_id in buffer_ids {
14533 if should_unfold {
14534 self.unfold_buffer(buffer_id, cx);
14535 } else {
14536 self.fold_buffer(buffer_id, cx);
14537 }
14538 }
14539 }
14540 }
14541
14542 pub fn toggle_fold_recursive(
14543 &mut self,
14544 _: &actions::ToggleFoldRecursive,
14545 window: &mut Window,
14546 cx: &mut Context<Self>,
14547 ) {
14548 let selection = self.selections.newest::<Point>(cx);
14549
14550 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14551 let range = if selection.is_empty() {
14552 let point = selection.head().to_display_point(&display_map);
14553 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14554 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14555 .to_point(&display_map);
14556 start..end
14557 } else {
14558 selection.range()
14559 };
14560 if display_map.folds_in_range(range).next().is_some() {
14561 self.unfold_recursive(&Default::default(), window, cx)
14562 } else {
14563 self.fold_recursive(&Default::default(), window, cx)
14564 }
14565 }
14566
14567 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14568 if self.is_singleton(cx) {
14569 let mut to_fold = Vec::new();
14570 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14571 let selections = self.selections.all_adjusted(cx);
14572
14573 for selection in selections {
14574 let range = selection.range().sorted();
14575 let buffer_start_row = range.start.row;
14576
14577 if range.start.row != range.end.row {
14578 let mut found = false;
14579 let mut row = range.start.row;
14580 while row <= range.end.row {
14581 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14582 {
14583 found = true;
14584 row = crease.range().end.row + 1;
14585 to_fold.push(crease);
14586 } else {
14587 row += 1
14588 }
14589 }
14590 if found {
14591 continue;
14592 }
14593 }
14594
14595 for row in (0..=range.start.row).rev() {
14596 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14597 if crease.range().end.row >= buffer_start_row {
14598 to_fold.push(crease);
14599 if row <= range.start.row {
14600 break;
14601 }
14602 }
14603 }
14604 }
14605 }
14606
14607 self.fold_creases(to_fold, true, window, cx);
14608 } else {
14609 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14610 let buffer_ids = self
14611 .selections
14612 .disjoint_anchor_ranges()
14613 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14614 .collect::<HashSet<_>>();
14615 for buffer_id in buffer_ids {
14616 self.fold_buffer(buffer_id, cx);
14617 }
14618 }
14619 }
14620
14621 fn fold_at_level(
14622 &mut self,
14623 fold_at: &FoldAtLevel,
14624 window: &mut Window,
14625 cx: &mut Context<Self>,
14626 ) {
14627 if !self.buffer.read(cx).is_singleton() {
14628 return;
14629 }
14630
14631 let fold_at_level = fold_at.0;
14632 let snapshot = self.buffer.read(cx).snapshot(cx);
14633 let mut to_fold = Vec::new();
14634 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14635
14636 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14637 while start_row < end_row {
14638 match self
14639 .snapshot(window, cx)
14640 .crease_for_buffer_row(MultiBufferRow(start_row))
14641 {
14642 Some(crease) => {
14643 let nested_start_row = crease.range().start.row + 1;
14644 let nested_end_row = crease.range().end.row;
14645
14646 if current_level < fold_at_level {
14647 stack.push((nested_start_row, nested_end_row, current_level + 1));
14648 } else if current_level == fold_at_level {
14649 to_fold.push(crease);
14650 }
14651
14652 start_row = nested_end_row + 1;
14653 }
14654 None => start_row += 1,
14655 }
14656 }
14657 }
14658
14659 self.fold_creases(to_fold, true, window, cx);
14660 }
14661
14662 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14663 if self.buffer.read(cx).is_singleton() {
14664 let mut fold_ranges = Vec::new();
14665 let snapshot = self.buffer.read(cx).snapshot(cx);
14666
14667 for row in 0..snapshot.max_row().0 {
14668 if let Some(foldable_range) = self
14669 .snapshot(window, cx)
14670 .crease_for_buffer_row(MultiBufferRow(row))
14671 {
14672 fold_ranges.push(foldable_range);
14673 }
14674 }
14675
14676 self.fold_creases(fold_ranges, true, window, cx);
14677 } else {
14678 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14679 editor
14680 .update_in(cx, |editor, _, cx| {
14681 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14682 editor.fold_buffer(buffer_id, cx);
14683 }
14684 })
14685 .ok();
14686 });
14687 }
14688 }
14689
14690 pub fn fold_function_bodies(
14691 &mut self,
14692 _: &actions::FoldFunctionBodies,
14693 window: &mut Window,
14694 cx: &mut Context<Self>,
14695 ) {
14696 let snapshot = self.buffer.read(cx).snapshot(cx);
14697
14698 let ranges = snapshot
14699 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14700 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14701 .collect::<Vec<_>>();
14702
14703 let creases = ranges
14704 .into_iter()
14705 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14706 .collect();
14707
14708 self.fold_creases(creases, true, window, cx);
14709 }
14710
14711 pub fn fold_recursive(
14712 &mut self,
14713 _: &actions::FoldRecursive,
14714 window: &mut Window,
14715 cx: &mut Context<Self>,
14716 ) {
14717 let mut to_fold = Vec::new();
14718 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14719 let selections = self.selections.all_adjusted(cx);
14720
14721 for selection in selections {
14722 let range = selection.range().sorted();
14723 let buffer_start_row = range.start.row;
14724
14725 if range.start.row != range.end.row {
14726 let mut found = false;
14727 for row in range.start.row..=range.end.row {
14728 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14729 found = true;
14730 to_fold.push(crease);
14731 }
14732 }
14733 if found {
14734 continue;
14735 }
14736 }
14737
14738 for row in (0..=range.start.row).rev() {
14739 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14740 if crease.range().end.row >= buffer_start_row {
14741 to_fold.push(crease);
14742 } else {
14743 break;
14744 }
14745 }
14746 }
14747 }
14748
14749 self.fold_creases(to_fold, true, window, cx);
14750 }
14751
14752 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14753 let buffer_row = fold_at.buffer_row;
14754 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14755
14756 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14757 let autoscroll = self
14758 .selections
14759 .all::<Point>(cx)
14760 .iter()
14761 .any(|selection| crease.range().overlaps(&selection.range()));
14762
14763 self.fold_creases(vec![crease], autoscroll, window, cx);
14764 }
14765 }
14766
14767 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14768 if self.is_singleton(cx) {
14769 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14770 let buffer = &display_map.buffer_snapshot;
14771 let selections = self.selections.all::<Point>(cx);
14772 let ranges = selections
14773 .iter()
14774 .map(|s| {
14775 let range = s.display_range(&display_map).sorted();
14776 let mut start = range.start.to_point(&display_map);
14777 let mut end = range.end.to_point(&display_map);
14778 start.column = 0;
14779 end.column = buffer.line_len(MultiBufferRow(end.row));
14780 start..end
14781 })
14782 .collect::<Vec<_>>();
14783
14784 self.unfold_ranges(&ranges, true, true, cx);
14785 } else {
14786 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14787 let buffer_ids = self
14788 .selections
14789 .disjoint_anchor_ranges()
14790 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14791 .collect::<HashSet<_>>();
14792 for buffer_id in buffer_ids {
14793 self.unfold_buffer(buffer_id, cx);
14794 }
14795 }
14796 }
14797
14798 pub fn unfold_recursive(
14799 &mut self,
14800 _: &UnfoldRecursive,
14801 _window: &mut Window,
14802 cx: &mut Context<Self>,
14803 ) {
14804 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14805 let selections = self.selections.all::<Point>(cx);
14806 let ranges = selections
14807 .iter()
14808 .map(|s| {
14809 let mut range = s.display_range(&display_map).sorted();
14810 *range.start.column_mut() = 0;
14811 *range.end.column_mut() = display_map.line_len(range.end.row());
14812 let start = range.start.to_point(&display_map);
14813 let end = range.end.to_point(&display_map);
14814 start..end
14815 })
14816 .collect::<Vec<_>>();
14817
14818 self.unfold_ranges(&ranges, true, true, cx);
14819 }
14820
14821 pub fn unfold_at(
14822 &mut self,
14823 unfold_at: &UnfoldAt,
14824 _window: &mut Window,
14825 cx: &mut Context<Self>,
14826 ) {
14827 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14828
14829 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14830 ..Point::new(
14831 unfold_at.buffer_row.0,
14832 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14833 );
14834
14835 let autoscroll = self
14836 .selections
14837 .all::<Point>(cx)
14838 .iter()
14839 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14840
14841 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14842 }
14843
14844 pub fn unfold_all(
14845 &mut self,
14846 _: &actions::UnfoldAll,
14847 _window: &mut Window,
14848 cx: &mut Context<Self>,
14849 ) {
14850 if self.buffer.read(cx).is_singleton() {
14851 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14852 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14853 } else {
14854 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14855 editor
14856 .update(cx, |editor, cx| {
14857 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14858 editor.unfold_buffer(buffer_id, cx);
14859 }
14860 })
14861 .ok();
14862 });
14863 }
14864 }
14865
14866 pub fn fold_selected_ranges(
14867 &mut self,
14868 _: &FoldSelectedRanges,
14869 window: &mut Window,
14870 cx: &mut Context<Self>,
14871 ) {
14872 let selections = self.selections.all_adjusted(cx);
14873 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14874 let ranges = selections
14875 .into_iter()
14876 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
14877 .collect::<Vec<_>>();
14878 self.fold_creases(ranges, true, window, cx);
14879 }
14880
14881 pub fn fold_ranges<T: ToOffset + Clone>(
14882 &mut self,
14883 ranges: Vec<Range<T>>,
14884 auto_scroll: bool,
14885 window: &mut Window,
14886 cx: &mut Context<Self>,
14887 ) {
14888 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14889 let ranges = ranges
14890 .into_iter()
14891 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14892 .collect::<Vec<_>>();
14893 self.fold_creases(ranges, auto_scroll, window, cx);
14894 }
14895
14896 pub fn fold_creases<T: ToOffset + Clone>(
14897 &mut self,
14898 creases: Vec<Crease<T>>,
14899 auto_scroll: bool,
14900 window: &mut Window,
14901 cx: &mut Context<Self>,
14902 ) {
14903 if creases.is_empty() {
14904 return;
14905 }
14906
14907 let mut buffers_affected = HashSet::default();
14908 let multi_buffer = self.buffer().read(cx);
14909 for crease in &creases {
14910 if let Some((_, buffer, _)) =
14911 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14912 {
14913 buffers_affected.insert(buffer.read(cx).remote_id());
14914 };
14915 }
14916
14917 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14918
14919 if auto_scroll {
14920 self.request_autoscroll(Autoscroll::fit(), cx);
14921 }
14922
14923 cx.notify();
14924
14925 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14926 // Clear diagnostics block when folding a range that contains it.
14927 let snapshot = self.snapshot(window, cx);
14928 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14929 drop(snapshot);
14930 self.active_diagnostics = Some(active_diagnostics);
14931 self.dismiss_diagnostics(cx);
14932 } else {
14933 self.active_diagnostics = Some(active_diagnostics);
14934 }
14935 }
14936
14937 self.scrollbar_marker_state.dirty = true;
14938 self.folds_did_change(cx);
14939 }
14940
14941 /// Removes any folds whose ranges intersect any of the given ranges.
14942 pub fn unfold_ranges<T: ToOffset + Clone>(
14943 &mut self,
14944 ranges: &[Range<T>],
14945 inclusive: bool,
14946 auto_scroll: bool,
14947 cx: &mut Context<Self>,
14948 ) {
14949 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14950 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14951 });
14952 self.folds_did_change(cx);
14953 }
14954
14955 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14956 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14957 return;
14958 }
14959 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14960 self.display_map.update(cx, |display_map, cx| {
14961 display_map.fold_buffers([buffer_id], cx)
14962 });
14963 cx.emit(EditorEvent::BufferFoldToggled {
14964 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14965 folded: true,
14966 });
14967 cx.notify();
14968 }
14969
14970 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14971 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14972 return;
14973 }
14974 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14975 self.display_map.update(cx, |display_map, cx| {
14976 display_map.unfold_buffers([buffer_id], cx);
14977 });
14978 cx.emit(EditorEvent::BufferFoldToggled {
14979 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14980 folded: false,
14981 });
14982 cx.notify();
14983 }
14984
14985 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14986 self.display_map.read(cx).is_buffer_folded(buffer)
14987 }
14988
14989 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14990 self.display_map.read(cx).folded_buffers()
14991 }
14992
14993 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14994 self.display_map.update(cx, |display_map, cx| {
14995 display_map.disable_header_for_buffer(buffer_id, cx);
14996 });
14997 cx.notify();
14998 }
14999
15000 /// Removes any folds with the given ranges.
15001 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15002 &mut self,
15003 ranges: &[Range<T>],
15004 type_id: TypeId,
15005 auto_scroll: bool,
15006 cx: &mut Context<Self>,
15007 ) {
15008 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15009 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15010 });
15011 self.folds_did_change(cx);
15012 }
15013
15014 fn remove_folds_with<T: ToOffset + Clone>(
15015 &mut self,
15016 ranges: &[Range<T>],
15017 auto_scroll: bool,
15018 cx: &mut Context<Self>,
15019 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15020 ) {
15021 if ranges.is_empty() {
15022 return;
15023 }
15024
15025 let mut buffers_affected = HashSet::default();
15026 let multi_buffer = self.buffer().read(cx);
15027 for range in ranges {
15028 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15029 buffers_affected.insert(buffer.read(cx).remote_id());
15030 };
15031 }
15032
15033 self.display_map.update(cx, update);
15034
15035 if auto_scroll {
15036 self.request_autoscroll(Autoscroll::fit(), cx);
15037 }
15038
15039 cx.notify();
15040 self.scrollbar_marker_state.dirty = true;
15041 self.active_indent_guides_state.dirty = true;
15042 }
15043
15044 pub fn update_fold_widths(
15045 &mut self,
15046 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15047 cx: &mut Context<Self>,
15048 ) -> bool {
15049 self.display_map
15050 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15051 }
15052
15053 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15054 self.display_map.read(cx).fold_placeholder.clone()
15055 }
15056
15057 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15058 self.buffer.update(cx, |buffer, cx| {
15059 buffer.set_all_diff_hunks_expanded(cx);
15060 });
15061 }
15062
15063 pub fn expand_all_diff_hunks(
15064 &mut self,
15065 _: &ExpandAllDiffHunks,
15066 _window: &mut Window,
15067 cx: &mut Context<Self>,
15068 ) {
15069 self.buffer.update(cx, |buffer, cx| {
15070 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15071 });
15072 }
15073
15074 pub fn toggle_selected_diff_hunks(
15075 &mut self,
15076 _: &ToggleSelectedDiffHunks,
15077 _window: &mut Window,
15078 cx: &mut Context<Self>,
15079 ) {
15080 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15081 self.toggle_diff_hunks_in_ranges(ranges, cx);
15082 }
15083
15084 pub fn diff_hunks_in_ranges<'a>(
15085 &'a self,
15086 ranges: &'a [Range<Anchor>],
15087 buffer: &'a MultiBufferSnapshot,
15088 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15089 ranges.iter().flat_map(move |range| {
15090 let end_excerpt_id = range.end.excerpt_id;
15091 let range = range.to_point(buffer);
15092 let mut peek_end = range.end;
15093 if range.end.row < buffer.max_row().0 {
15094 peek_end = Point::new(range.end.row + 1, 0);
15095 }
15096 buffer
15097 .diff_hunks_in_range(range.start..peek_end)
15098 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15099 })
15100 }
15101
15102 pub fn has_stageable_diff_hunks_in_ranges(
15103 &self,
15104 ranges: &[Range<Anchor>],
15105 snapshot: &MultiBufferSnapshot,
15106 ) -> bool {
15107 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15108 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15109 }
15110
15111 pub fn toggle_staged_selected_diff_hunks(
15112 &mut self,
15113 _: &::git::ToggleStaged,
15114 _: &mut Window,
15115 cx: &mut Context<Self>,
15116 ) {
15117 let snapshot = self.buffer.read(cx).snapshot(cx);
15118 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15119 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15120 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15121 }
15122
15123 pub fn set_render_diff_hunk_controls(
15124 &mut self,
15125 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15126 cx: &mut Context<Self>,
15127 ) {
15128 self.render_diff_hunk_controls = render_diff_hunk_controls;
15129 cx.notify();
15130 }
15131
15132 pub fn stage_and_next(
15133 &mut self,
15134 _: &::git::StageAndNext,
15135 window: &mut Window,
15136 cx: &mut Context<Self>,
15137 ) {
15138 self.do_stage_or_unstage_and_next(true, window, cx);
15139 }
15140
15141 pub fn unstage_and_next(
15142 &mut self,
15143 _: &::git::UnstageAndNext,
15144 window: &mut Window,
15145 cx: &mut Context<Self>,
15146 ) {
15147 self.do_stage_or_unstage_and_next(false, window, cx);
15148 }
15149
15150 pub fn stage_or_unstage_diff_hunks(
15151 &mut self,
15152 stage: bool,
15153 ranges: Vec<Range<Anchor>>,
15154 cx: &mut Context<Self>,
15155 ) {
15156 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15157 cx.spawn(async move |this, cx| {
15158 task.await?;
15159 this.update(cx, |this, cx| {
15160 let snapshot = this.buffer.read(cx).snapshot(cx);
15161 let chunk_by = this
15162 .diff_hunks_in_ranges(&ranges, &snapshot)
15163 .chunk_by(|hunk| hunk.buffer_id);
15164 for (buffer_id, hunks) in &chunk_by {
15165 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15166 }
15167 })
15168 })
15169 .detach_and_log_err(cx);
15170 }
15171
15172 fn save_buffers_for_ranges_if_needed(
15173 &mut self,
15174 ranges: &[Range<Anchor>],
15175 cx: &mut Context<Editor>,
15176 ) -> Task<Result<()>> {
15177 let multibuffer = self.buffer.read(cx);
15178 let snapshot = multibuffer.read(cx);
15179 let buffer_ids: HashSet<_> = ranges
15180 .iter()
15181 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15182 .collect();
15183 drop(snapshot);
15184
15185 let mut buffers = HashSet::default();
15186 for buffer_id in buffer_ids {
15187 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15188 let buffer = buffer_entity.read(cx);
15189 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15190 {
15191 buffers.insert(buffer_entity);
15192 }
15193 }
15194 }
15195
15196 if let Some(project) = &self.project {
15197 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15198 } else {
15199 Task::ready(Ok(()))
15200 }
15201 }
15202
15203 fn do_stage_or_unstage_and_next(
15204 &mut self,
15205 stage: bool,
15206 window: &mut Window,
15207 cx: &mut Context<Self>,
15208 ) {
15209 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15210
15211 if ranges.iter().any(|range| range.start != range.end) {
15212 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15213 return;
15214 }
15215
15216 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15217 let snapshot = self.snapshot(window, cx);
15218 let position = self.selections.newest::<Point>(cx).head();
15219 let mut row = snapshot
15220 .buffer_snapshot
15221 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15222 .find(|hunk| hunk.row_range.start.0 > position.row)
15223 .map(|hunk| hunk.row_range.start);
15224
15225 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15226 // Outside of the project diff editor, wrap around to the beginning.
15227 if !all_diff_hunks_expanded {
15228 row = row.or_else(|| {
15229 snapshot
15230 .buffer_snapshot
15231 .diff_hunks_in_range(Point::zero()..position)
15232 .find(|hunk| hunk.row_range.end.0 < position.row)
15233 .map(|hunk| hunk.row_range.start)
15234 });
15235 }
15236
15237 if let Some(row) = row {
15238 let destination = Point::new(row.0, 0);
15239 let autoscroll = Autoscroll::center();
15240
15241 self.unfold_ranges(&[destination..destination], false, false, cx);
15242 self.change_selections(Some(autoscroll), window, cx, |s| {
15243 s.select_ranges([destination..destination]);
15244 });
15245 }
15246 }
15247
15248 fn do_stage_or_unstage(
15249 &self,
15250 stage: bool,
15251 buffer_id: BufferId,
15252 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15253 cx: &mut App,
15254 ) -> Option<()> {
15255 let project = self.project.as_ref()?;
15256 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15257 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15258 let buffer_snapshot = buffer.read(cx).snapshot();
15259 let file_exists = buffer_snapshot
15260 .file()
15261 .is_some_and(|file| file.disk_state().exists());
15262 diff.update(cx, |diff, cx| {
15263 diff.stage_or_unstage_hunks(
15264 stage,
15265 &hunks
15266 .map(|hunk| buffer_diff::DiffHunk {
15267 buffer_range: hunk.buffer_range,
15268 diff_base_byte_range: hunk.diff_base_byte_range,
15269 secondary_status: hunk.secondary_status,
15270 range: Point::zero()..Point::zero(), // unused
15271 })
15272 .collect::<Vec<_>>(),
15273 &buffer_snapshot,
15274 file_exists,
15275 cx,
15276 )
15277 });
15278 None
15279 }
15280
15281 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15282 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15283 self.buffer
15284 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15285 }
15286
15287 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15288 self.buffer.update(cx, |buffer, cx| {
15289 let ranges = vec![Anchor::min()..Anchor::max()];
15290 if !buffer.all_diff_hunks_expanded()
15291 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15292 {
15293 buffer.collapse_diff_hunks(ranges, cx);
15294 true
15295 } else {
15296 false
15297 }
15298 })
15299 }
15300
15301 fn toggle_diff_hunks_in_ranges(
15302 &mut self,
15303 ranges: Vec<Range<Anchor>>,
15304 cx: &mut Context<Editor>,
15305 ) {
15306 self.buffer.update(cx, |buffer, cx| {
15307 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15308 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15309 })
15310 }
15311
15312 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15313 self.buffer.update(cx, |buffer, cx| {
15314 let snapshot = buffer.snapshot(cx);
15315 let excerpt_id = range.end.excerpt_id;
15316 let point_range = range.to_point(&snapshot);
15317 let expand = !buffer.single_hunk_is_expanded(range, cx);
15318 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15319 })
15320 }
15321
15322 pub(crate) fn apply_all_diff_hunks(
15323 &mut self,
15324 _: &ApplyAllDiffHunks,
15325 window: &mut Window,
15326 cx: &mut Context<Self>,
15327 ) {
15328 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15329
15330 let buffers = self.buffer.read(cx).all_buffers();
15331 for branch_buffer in buffers {
15332 branch_buffer.update(cx, |branch_buffer, cx| {
15333 branch_buffer.merge_into_base(Vec::new(), cx);
15334 });
15335 }
15336
15337 if let Some(project) = self.project.clone() {
15338 self.save(true, project, window, cx).detach_and_log_err(cx);
15339 }
15340 }
15341
15342 pub(crate) fn apply_selected_diff_hunks(
15343 &mut self,
15344 _: &ApplyDiffHunk,
15345 window: &mut Window,
15346 cx: &mut Context<Self>,
15347 ) {
15348 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15349 let snapshot = self.snapshot(window, cx);
15350 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15351 let mut ranges_by_buffer = HashMap::default();
15352 self.transact(window, cx, |editor, _window, cx| {
15353 for hunk in hunks {
15354 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15355 ranges_by_buffer
15356 .entry(buffer.clone())
15357 .or_insert_with(Vec::new)
15358 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15359 }
15360 }
15361
15362 for (buffer, ranges) in ranges_by_buffer {
15363 buffer.update(cx, |buffer, cx| {
15364 buffer.merge_into_base(ranges, cx);
15365 });
15366 }
15367 });
15368
15369 if let Some(project) = self.project.clone() {
15370 self.save(true, project, window, cx).detach_and_log_err(cx);
15371 }
15372 }
15373
15374 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15375 if hovered != self.gutter_hovered {
15376 self.gutter_hovered = hovered;
15377 cx.notify();
15378 }
15379 }
15380
15381 pub fn insert_blocks(
15382 &mut self,
15383 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15384 autoscroll: Option<Autoscroll>,
15385 cx: &mut Context<Self>,
15386 ) -> Vec<CustomBlockId> {
15387 let blocks = self
15388 .display_map
15389 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15390 if let Some(autoscroll) = autoscroll {
15391 self.request_autoscroll(autoscroll, cx);
15392 }
15393 cx.notify();
15394 blocks
15395 }
15396
15397 pub fn resize_blocks(
15398 &mut self,
15399 heights: HashMap<CustomBlockId, u32>,
15400 autoscroll: Option<Autoscroll>,
15401 cx: &mut Context<Self>,
15402 ) {
15403 self.display_map
15404 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15405 if let Some(autoscroll) = autoscroll {
15406 self.request_autoscroll(autoscroll, cx);
15407 }
15408 cx.notify();
15409 }
15410
15411 pub fn replace_blocks(
15412 &mut self,
15413 renderers: HashMap<CustomBlockId, RenderBlock>,
15414 autoscroll: Option<Autoscroll>,
15415 cx: &mut Context<Self>,
15416 ) {
15417 self.display_map
15418 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15419 if let Some(autoscroll) = autoscroll {
15420 self.request_autoscroll(autoscroll, cx);
15421 }
15422 cx.notify();
15423 }
15424
15425 pub fn remove_blocks(
15426 &mut self,
15427 block_ids: HashSet<CustomBlockId>,
15428 autoscroll: Option<Autoscroll>,
15429 cx: &mut Context<Self>,
15430 ) {
15431 self.display_map.update(cx, |display_map, cx| {
15432 display_map.remove_blocks(block_ids, cx)
15433 });
15434 if let Some(autoscroll) = autoscroll {
15435 self.request_autoscroll(autoscroll, cx);
15436 }
15437 cx.notify();
15438 }
15439
15440 pub fn row_for_block(
15441 &self,
15442 block_id: CustomBlockId,
15443 cx: &mut Context<Self>,
15444 ) -> Option<DisplayRow> {
15445 self.display_map
15446 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15447 }
15448
15449 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15450 self.focused_block = Some(focused_block);
15451 }
15452
15453 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15454 self.focused_block.take()
15455 }
15456
15457 pub fn insert_creases(
15458 &mut self,
15459 creases: impl IntoIterator<Item = Crease<Anchor>>,
15460 cx: &mut Context<Self>,
15461 ) -> Vec<CreaseId> {
15462 self.display_map
15463 .update(cx, |map, cx| map.insert_creases(creases, cx))
15464 }
15465
15466 pub fn remove_creases(
15467 &mut self,
15468 ids: impl IntoIterator<Item = CreaseId>,
15469 cx: &mut Context<Self>,
15470 ) {
15471 self.display_map
15472 .update(cx, |map, cx| map.remove_creases(ids, cx));
15473 }
15474
15475 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15476 self.display_map
15477 .update(cx, |map, cx| map.snapshot(cx))
15478 .longest_row()
15479 }
15480
15481 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15482 self.display_map
15483 .update(cx, |map, cx| map.snapshot(cx))
15484 .max_point()
15485 }
15486
15487 pub fn text(&self, cx: &App) -> String {
15488 self.buffer.read(cx).read(cx).text()
15489 }
15490
15491 pub fn is_empty(&self, cx: &App) -> bool {
15492 self.buffer.read(cx).read(cx).is_empty()
15493 }
15494
15495 pub fn text_option(&self, cx: &App) -> Option<String> {
15496 let text = self.text(cx);
15497 let text = text.trim();
15498
15499 if text.is_empty() {
15500 return None;
15501 }
15502
15503 Some(text.to_string())
15504 }
15505
15506 pub fn set_text(
15507 &mut self,
15508 text: impl Into<Arc<str>>,
15509 window: &mut Window,
15510 cx: &mut Context<Self>,
15511 ) {
15512 self.transact(window, cx, |this, _, cx| {
15513 this.buffer
15514 .read(cx)
15515 .as_singleton()
15516 .expect("you can only call set_text on editors for singleton buffers")
15517 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15518 });
15519 }
15520
15521 pub fn display_text(&self, cx: &mut App) -> String {
15522 self.display_map
15523 .update(cx, |map, cx| map.snapshot(cx))
15524 .text()
15525 }
15526
15527 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15528 let mut wrap_guides = smallvec::smallvec![];
15529
15530 if self.show_wrap_guides == Some(false) {
15531 return wrap_guides;
15532 }
15533
15534 let settings = self.buffer.read(cx).language_settings(cx);
15535 if settings.show_wrap_guides {
15536 match self.soft_wrap_mode(cx) {
15537 SoftWrap::Column(soft_wrap) => {
15538 wrap_guides.push((soft_wrap as usize, true));
15539 }
15540 SoftWrap::Bounded(soft_wrap) => {
15541 wrap_guides.push((soft_wrap as usize, true));
15542 }
15543 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15544 }
15545 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15546 }
15547
15548 wrap_guides
15549 }
15550
15551 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15552 let settings = self.buffer.read(cx).language_settings(cx);
15553 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15554 match mode {
15555 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15556 SoftWrap::None
15557 }
15558 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15559 language_settings::SoftWrap::PreferredLineLength => {
15560 SoftWrap::Column(settings.preferred_line_length)
15561 }
15562 language_settings::SoftWrap::Bounded => {
15563 SoftWrap::Bounded(settings.preferred_line_length)
15564 }
15565 }
15566 }
15567
15568 pub fn set_soft_wrap_mode(
15569 &mut self,
15570 mode: language_settings::SoftWrap,
15571
15572 cx: &mut Context<Self>,
15573 ) {
15574 self.soft_wrap_mode_override = Some(mode);
15575 cx.notify();
15576 }
15577
15578 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15579 self.hard_wrap = hard_wrap;
15580 cx.notify();
15581 }
15582
15583 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15584 self.text_style_refinement = Some(style);
15585 }
15586
15587 /// called by the Element so we know what style we were most recently rendered with.
15588 pub(crate) fn set_style(
15589 &mut self,
15590 style: EditorStyle,
15591 window: &mut Window,
15592 cx: &mut Context<Self>,
15593 ) {
15594 let rem_size = window.rem_size();
15595 self.display_map.update(cx, |map, cx| {
15596 map.set_font(
15597 style.text.font(),
15598 style.text.font_size.to_pixels(rem_size),
15599 cx,
15600 )
15601 });
15602 self.style = Some(style);
15603 }
15604
15605 pub fn style(&self) -> Option<&EditorStyle> {
15606 self.style.as_ref()
15607 }
15608
15609 // Called by the element. This method is not designed to be called outside of the editor
15610 // element's layout code because it does not notify when rewrapping is computed synchronously.
15611 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15612 self.display_map
15613 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15614 }
15615
15616 pub fn set_soft_wrap(&mut self) {
15617 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15618 }
15619
15620 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15621 if self.soft_wrap_mode_override.is_some() {
15622 self.soft_wrap_mode_override.take();
15623 } else {
15624 let soft_wrap = match self.soft_wrap_mode(cx) {
15625 SoftWrap::GitDiff => return,
15626 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15627 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15628 language_settings::SoftWrap::None
15629 }
15630 };
15631 self.soft_wrap_mode_override = Some(soft_wrap);
15632 }
15633 cx.notify();
15634 }
15635
15636 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15637 let Some(workspace) = self.workspace() else {
15638 return;
15639 };
15640 let fs = workspace.read(cx).app_state().fs.clone();
15641 let current_show = TabBarSettings::get_global(cx).show;
15642 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15643 setting.show = Some(!current_show);
15644 });
15645 }
15646
15647 pub fn toggle_indent_guides(
15648 &mut self,
15649 _: &ToggleIndentGuides,
15650 _: &mut Window,
15651 cx: &mut Context<Self>,
15652 ) {
15653 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15654 self.buffer
15655 .read(cx)
15656 .language_settings(cx)
15657 .indent_guides
15658 .enabled
15659 });
15660 self.show_indent_guides = Some(!currently_enabled);
15661 cx.notify();
15662 }
15663
15664 fn should_show_indent_guides(&self) -> Option<bool> {
15665 self.show_indent_guides
15666 }
15667
15668 pub fn toggle_line_numbers(
15669 &mut self,
15670 _: &ToggleLineNumbers,
15671 _: &mut Window,
15672 cx: &mut Context<Self>,
15673 ) {
15674 let mut editor_settings = EditorSettings::get_global(cx).clone();
15675 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15676 EditorSettings::override_global(editor_settings, cx);
15677 }
15678
15679 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15680 if let Some(show_line_numbers) = self.show_line_numbers {
15681 return show_line_numbers;
15682 }
15683 EditorSettings::get_global(cx).gutter.line_numbers
15684 }
15685
15686 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15687 self.use_relative_line_numbers
15688 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15689 }
15690
15691 pub fn toggle_relative_line_numbers(
15692 &mut self,
15693 _: &ToggleRelativeLineNumbers,
15694 _: &mut Window,
15695 cx: &mut Context<Self>,
15696 ) {
15697 let is_relative = self.should_use_relative_line_numbers(cx);
15698 self.set_relative_line_number(Some(!is_relative), cx)
15699 }
15700
15701 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15702 self.use_relative_line_numbers = is_relative;
15703 cx.notify();
15704 }
15705
15706 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15707 self.show_gutter = show_gutter;
15708 cx.notify();
15709 }
15710
15711 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15712 self.show_scrollbars = show_scrollbars;
15713 cx.notify();
15714 }
15715
15716 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15717 self.show_line_numbers = Some(show_line_numbers);
15718 cx.notify();
15719 }
15720
15721 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15722 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15723 cx.notify();
15724 }
15725
15726 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15727 self.show_code_actions = Some(show_code_actions);
15728 cx.notify();
15729 }
15730
15731 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15732 self.show_runnables = Some(show_runnables);
15733 cx.notify();
15734 }
15735
15736 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15737 self.show_breakpoints = Some(show_breakpoints);
15738 cx.notify();
15739 }
15740
15741 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15742 if self.display_map.read(cx).masked != masked {
15743 self.display_map.update(cx, |map, _| map.masked = masked);
15744 }
15745 cx.notify()
15746 }
15747
15748 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15749 self.show_wrap_guides = Some(show_wrap_guides);
15750 cx.notify();
15751 }
15752
15753 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15754 self.show_indent_guides = Some(show_indent_guides);
15755 cx.notify();
15756 }
15757
15758 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15759 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15760 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15761 if let Some(dir) = file.abs_path(cx).parent() {
15762 return Some(dir.to_owned());
15763 }
15764 }
15765
15766 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15767 return Some(project_path.path.to_path_buf());
15768 }
15769 }
15770
15771 None
15772 }
15773
15774 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15775 self.active_excerpt(cx)?
15776 .1
15777 .read(cx)
15778 .file()
15779 .and_then(|f| f.as_local())
15780 }
15781
15782 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15783 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15784 let buffer = buffer.read(cx);
15785 if let Some(project_path) = buffer.project_path(cx) {
15786 let project = self.project.as_ref()?.read(cx);
15787 project.absolute_path(&project_path, cx)
15788 } else {
15789 buffer
15790 .file()
15791 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15792 }
15793 })
15794 }
15795
15796 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15797 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15798 let project_path = buffer.read(cx).project_path(cx)?;
15799 let project = self.project.as_ref()?.read(cx);
15800 let entry = project.entry_for_path(&project_path, cx)?;
15801 let path = entry.path.to_path_buf();
15802 Some(path)
15803 })
15804 }
15805
15806 pub fn reveal_in_finder(
15807 &mut self,
15808 _: &RevealInFileManager,
15809 _window: &mut Window,
15810 cx: &mut Context<Self>,
15811 ) {
15812 if let Some(target) = self.target_file(cx) {
15813 cx.reveal_path(&target.abs_path(cx));
15814 }
15815 }
15816
15817 pub fn copy_path(
15818 &mut self,
15819 _: &zed_actions::workspace::CopyPath,
15820 _window: &mut Window,
15821 cx: &mut Context<Self>,
15822 ) {
15823 if let Some(path) = self.target_file_abs_path(cx) {
15824 if let Some(path) = path.to_str() {
15825 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15826 }
15827 }
15828 }
15829
15830 pub fn copy_relative_path(
15831 &mut self,
15832 _: &zed_actions::workspace::CopyRelativePath,
15833 _window: &mut Window,
15834 cx: &mut Context<Self>,
15835 ) {
15836 if let Some(path) = self.target_file_path(cx) {
15837 if let Some(path) = path.to_str() {
15838 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15839 }
15840 }
15841 }
15842
15843 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15844 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15845 buffer.read(cx).project_path(cx)
15846 } else {
15847 None
15848 }
15849 }
15850
15851 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15852 let _ = maybe!({
15853 let breakpoint_store = self.breakpoint_store.as_ref()?;
15854
15855 let Some((_, _, active_position)) =
15856 breakpoint_store.read(cx).active_position().cloned()
15857 else {
15858 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15859 return None;
15860 };
15861
15862 let snapshot = self
15863 .project
15864 .as_ref()?
15865 .read(cx)
15866 .buffer_for_id(active_position.buffer_id?, cx)?
15867 .read(cx)
15868 .snapshot();
15869
15870 for (id, ExcerptRange { context, .. }) in self
15871 .buffer
15872 .read(cx)
15873 .excerpts_for_buffer(active_position.buffer_id?, cx)
15874 {
15875 if context.start.cmp(&active_position, &snapshot).is_ge()
15876 || context.end.cmp(&active_position, &snapshot).is_lt()
15877 {
15878 continue;
15879 }
15880 let snapshot = self.buffer.read(cx).snapshot(cx);
15881 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15882
15883 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15884 self.go_to_line::<DebugCurrentRowHighlight>(
15885 multibuffer_anchor,
15886 Some(cx.theme().colors().editor_debugger_active_line_background),
15887 window,
15888 cx,
15889 );
15890
15891 cx.notify();
15892 }
15893
15894 Some(())
15895 });
15896 }
15897
15898 pub fn copy_file_name_without_extension(
15899 &mut self,
15900 _: &CopyFileNameWithoutExtension,
15901 _: &mut Window,
15902 cx: &mut Context<Self>,
15903 ) {
15904 if let Some(file) = self.target_file(cx) {
15905 if let Some(file_stem) = file.path().file_stem() {
15906 if let Some(name) = file_stem.to_str() {
15907 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15908 }
15909 }
15910 }
15911 }
15912
15913 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15914 if let Some(file) = self.target_file(cx) {
15915 if let Some(file_name) = file.path().file_name() {
15916 if let Some(name) = file_name.to_str() {
15917 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15918 }
15919 }
15920 }
15921 }
15922
15923 pub fn toggle_git_blame(
15924 &mut self,
15925 _: &::git::Blame,
15926 window: &mut Window,
15927 cx: &mut Context<Self>,
15928 ) {
15929 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15930
15931 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15932 self.start_git_blame(true, window, cx);
15933 }
15934
15935 cx.notify();
15936 }
15937
15938 pub fn toggle_git_blame_inline(
15939 &mut self,
15940 _: &ToggleGitBlameInline,
15941 window: &mut Window,
15942 cx: &mut Context<Self>,
15943 ) {
15944 self.toggle_git_blame_inline_internal(true, window, cx);
15945 cx.notify();
15946 }
15947
15948 pub fn open_git_blame_commit(
15949 &mut self,
15950 _: &OpenGitBlameCommit,
15951 window: &mut Window,
15952 cx: &mut Context<Self>,
15953 ) {
15954 self.open_git_blame_commit_internal(window, cx);
15955 }
15956
15957 fn open_git_blame_commit_internal(
15958 &mut self,
15959 window: &mut Window,
15960 cx: &mut Context<Self>,
15961 ) -> Option<()> {
15962 let blame = self.blame.as_ref()?;
15963 let snapshot = self.snapshot(window, cx);
15964 let cursor = self.selections.newest::<Point>(cx).head();
15965 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
15966 let blame_entry = blame
15967 .update(cx, |blame, cx| {
15968 blame
15969 .blame_for_rows(
15970 &[RowInfo {
15971 buffer_id: Some(buffer.remote_id()),
15972 buffer_row: Some(point.row),
15973 ..Default::default()
15974 }],
15975 cx,
15976 )
15977 .next()
15978 })
15979 .flatten()?;
15980 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
15981 let repo = blame.read(cx).repository(cx)?;
15982 let workspace = self.workspace()?.downgrade();
15983 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
15984 None
15985 }
15986
15987 pub fn git_blame_inline_enabled(&self) -> bool {
15988 self.git_blame_inline_enabled
15989 }
15990
15991 pub fn toggle_selection_menu(
15992 &mut self,
15993 _: &ToggleSelectionMenu,
15994 _: &mut Window,
15995 cx: &mut Context<Self>,
15996 ) {
15997 self.show_selection_menu = self
15998 .show_selection_menu
15999 .map(|show_selections_menu| !show_selections_menu)
16000 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16001
16002 cx.notify();
16003 }
16004
16005 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16006 self.show_selection_menu
16007 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16008 }
16009
16010 fn start_git_blame(
16011 &mut self,
16012 user_triggered: bool,
16013 window: &mut Window,
16014 cx: &mut Context<Self>,
16015 ) {
16016 if let Some(project) = self.project.as_ref() {
16017 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16018 return;
16019 };
16020
16021 if buffer.read(cx).file().is_none() {
16022 return;
16023 }
16024
16025 let focused = self.focus_handle(cx).contains_focused(window, cx);
16026
16027 let project = project.clone();
16028 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16029 self.blame_subscription =
16030 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16031 self.blame = Some(blame);
16032 }
16033 }
16034
16035 fn toggle_git_blame_inline_internal(
16036 &mut self,
16037 user_triggered: bool,
16038 window: &mut Window,
16039 cx: &mut Context<Self>,
16040 ) {
16041 if self.git_blame_inline_enabled {
16042 self.git_blame_inline_enabled = false;
16043 self.show_git_blame_inline = false;
16044 self.show_git_blame_inline_delay_task.take();
16045 } else {
16046 self.git_blame_inline_enabled = true;
16047 self.start_git_blame_inline(user_triggered, window, cx);
16048 }
16049
16050 cx.notify();
16051 }
16052
16053 fn start_git_blame_inline(
16054 &mut self,
16055 user_triggered: bool,
16056 window: &mut Window,
16057 cx: &mut Context<Self>,
16058 ) {
16059 self.start_git_blame(user_triggered, window, cx);
16060
16061 if ProjectSettings::get_global(cx)
16062 .git
16063 .inline_blame_delay()
16064 .is_some()
16065 {
16066 self.start_inline_blame_timer(window, cx);
16067 } else {
16068 self.show_git_blame_inline = true
16069 }
16070 }
16071
16072 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16073 self.blame.as_ref()
16074 }
16075
16076 pub fn show_git_blame_gutter(&self) -> bool {
16077 self.show_git_blame_gutter
16078 }
16079
16080 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16081 self.show_git_blame_gutter && self.has_blame_entries(cx)
16082 }
16083
16084 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16085 self.show_git_blame_inline
16086 && (self.focus_handle.is_focused(window)
16087 || self
16088 .git_blame_inline_tooltip
16089 .as_ref()
16090 .and_then(|t| t.upgrade())
16091 .is_some())
16092 && !self.newest_selection_head_on_empty_line(cx)
16093 && self.has_blame_entries(cx)
16094 }
16095
16096 fn has_blame_entries(&self, cx: &App) -> bool {
16097 self.blame()
16098 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16099 }
16100
16101 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16102 let cursor_anchor = self.selections.newest_anchor().head();
16103
16104 let snapshot = self.buffer.read(cx).snapshot(cx);
16105 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16106
16107 snapshot.line_len(buffer_row) == 0
16108 }
16109
16110 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16111 let buffer_and_selection = maybe!({
16112 let selection = self.selections.newest::<Point>(cx);
16113 let selection_range = selection.range();
16114
16115 let multi_buffer = self.buffer().read(cx);
16116 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16117 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16118
16119 let (buffer, range, _) = if selection.reversed {
16120 buffer_ranges.first()
16121 } else {
16122 buffer_ranges.last()
16123 }?;
16124
16125 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16126 ..text::ToPoint::to_point(&range.end, &buffer).row;
16127 Some((
16128 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16129 selection,
16130 ))
16131 });
16132
16133 let Some((buffer, selection)) = buffer_and_selection else {
16134 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16135 };
16136
16137 let Some(project) = self.project.as_ref() else {
16138 return Task::ready(Err(anyhow!("editor does not have project")));
16139 };
16140
16141 project.update(cx, |project, cx| {
16142 project.get_permalink_to_line(&buffer, selection, cx)
16143 })
16144 }
16145
16146 pub fn copy_permalink_to_line(
16147 &mut self,
16148 _: &CopyPermalinkToLine,
16149 window: &mut Window,
16150 cx: &mut Context<Self>,
16151 ) {
16152 let permalink_task = self.get_permalink_to_line(cx);
16153 let workspace = self.workspace();
16154
16155 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16156 Ok(permalink) => {
16157 cx.update(|_, cx| {
16158 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16159 })
16160 .ok();
16161 }
16162 Err(err) => {
16163 let message = format!("Failed to copy permalink: {err}");
16164
16165 Err::<(), anyhow::Error>(err).log_err();
16166
16167 if let Some(workspace) = workspace {
16168 workspace
16169 .update_in(cx, |workspace, _, cx| {
16170 struct CopyPermalinkToLine;
16171
16172 workspace.show_toast(
16173 Toast::new(
16174 NotificationId::unique::<CopyPermalinkToLine>(),
16175 message,
16176 ),
16177 cx,
16178 )
16179 })
16180 .ok();
16181 }
16182 }
16183 })
16184 .detach();
16185 }
16186
16187 pub fn copy_file_location(
16188 &mut self,
16189 _: &CopyFileLocation,
16190 _: &mut Window,
16191 cx: &mut Context<Self>,
16192 ) {
16193 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16194 if let Some(file) = self.target_file(cx) {
16195 if let Some(path) = file.path().to_str() {
16196 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16197 }
16198 }
16199 }
16200
16201 pub fn open_permalink_to_line(
16202 &mut self,
16203 _: &OpenPermalinkToLine,
16204 window: &mut Window,
16205 cx: &mut Context<Self>,
16206 ) {
16207 let permalink_task = self.get_permalink_to_line(cx);
16208 let workspace = self.workspace();
16209
16210 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16211 Ok(permalink) => {
16212 cx.update(|_, cx| {
16213 cx.open_url(permalink.as_ref());
16214 })
16215 .ok();
16216 }
16217 Err(err) => {
16218 let message = format!("Failed to open permalink: {err}");
16219
16220 Err::<(), anyhow::Error>(err).log_err();
16221
16222 if let Some(workspace) = workspace {
16223 workspace
16224 .update(cx, |workspace, cx| {
16225 struct OpenPermalinkToLine;
16226
16227 workspace.show_toast(
16228 Toast::new(
16229 NotificationId::unique::<OpenPermalinkToLine>(),
16230 message,
16231 ),
16232 cx,
16233 )
16234 })
16235 .ok();
16236 }
16237 }
16238 })
16239 .detach();
16240 }
16241
16242 pub fn insert_uuid_v4(
16243 &mut self,
16244 _: &InsertUuidV4,
16245 window: &mut Window,
16246 cx: &mut Context<Self>,
16247 ) {
16248 self.insert_uuid(UuidVersion::V4, window, cx);
16249 }
16250
16251 pub fn insert_uuid_v7(
16252 &mut self,
16253 _: &InsertUuidV7,
16254 window: &mut Window,
16255 cx: &mut Context<Self>,
16256 ) {
16257 self.insert_uuid(UuidVersion::V7, window, cx);
16258 }
16259
16260 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16261 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16262 self.transact(window, cx, |this, window, cx| {
16263 let edits = this
16264 .selections
16265 .all::<Point>(cx)
16266 .into_iter()
16267 .map(|selection| {
16268 let uuid = match version {
16269 UuidVersion::V4 => uuid::Uuid::new_v4(),
16270 UuidVersion::V7 => uuid::Uuid::now_v7(),
16271 };
16272
16273 (selection.range(), uuid.to_string())
16274 });
16275 this.edit(edits, cx);
16276 this.refresh_inline_completion(true, false, window, cx);
16277 });
16278 }
16279
16280 pub fn open_selections_in_multibuffer(
16281 &mut self,
16282 _: &OpenSelectionsInMultibuffer,
16283 window: &mut Window,
16284 cx: &mut Context<Self>,
16285 ) {
16286 let multibuffer = self.buffer.read(cx);
16287
16288 let Some(buffer) = multibuffer.as_singleton() else {
16289 return;
16290 };
16291
16292 let Some(workspace) = self.workspace() else {
16293 return;
16294 };
16295
16296 let locations = self
16297 .selections
16298 .disjoint_anchors()
16299 .iter()
16300 .map(|range| Location {
16301 buffer: buffer.clone(),
16302 range: range.start.text_anchor..range.end.text_anchor,
16303 })
16304 .collect::<Vec<_>>();
16305
16306 let title = multibuffer.title(cx).to_string();
16307
16308 cx.spawn_in(window, async move |_, cx| {
16309 workspace.update_in(cx, |workspace, window, cx| {
16310 Self::open_locations_in_multibuffer(
16311 workspace,
16312 locations,
16313 format!("Selections for '{title}'"),
16314 false,
16315 MultibufferSelectionMode::All,
16316 window,
16317 cx,
16318 );
16319 })
16320 })
16321 .detach();
16322 }
16323
16324 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16325 /// last highlight added will be used.
16326 ///
16327 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16328 pub fn highlight_rows<T: 'static>(
16329 &mut self,
16330 range: Range<Anchor>,
16331 color: Hsla,
16332 should_autoscroll: bool,
16333 cx: &mut Context<Self>,
16334 ) {
16335 let snapshot = self.buffer().read(cx).snapshot(cx);
16336 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16337 let ix = row_highlights.binary_search_by(|highlight| {
16338 Ordering::Equal
16339 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16340 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16341 });
16342
16343 if let Err(mut ix) = ix {
16344 let index = post_inc(&mut self.highlight_order);
16345
16346 // If this range intersects with the preceding highlight, then merge it with
16347 // the preceding highlight. Otherwise insert a new highlight.
16348 let mut merged = false;
16349 if ix > 0 {
16350 let prev_highlight = &mut row_highlights[ix - 1];
16351 if prev_highlight
16352 .range
16353 .end
16354 .cmp(&range.start, &snapshot)
16355 .is_ge()
16356 {
16357 ix -= 1;
16358 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16359 prev_highlight.range.end = range.end;
16360 }
16361 merged = true;
16362 prev_highlight.index = index;
16363 prev_highlight.color = color;
16364 prev_highlight.should_autoscroll = should_autoscroll;
16365 }
16366 }
16367
16368 if !merged {
16369 row_highlights.insert(
16370 ix,
16371 RowHighlight {
16372 range: range.clone(),
16373 index,
16374 color,
16375 should_autoscroll,
16376 },
16377 );
16378 }
16379
16380 // If any of the following highlights intersect with this one, merge them.
16381 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16382 let highlight = &row_highlights[ix];
16383 if next_highlight
16384 .range
16385 .start
16386 .cmp(&highlight.range.end, &snapshot)
16387 .is_le()
16388 {
16389 if next_highlight
16390 .range
16391 .end
16392 .cmp(&highlight.range.end, &snapshot)
16393 .is_gt()
16394 {
16395 row_highlights[ix].range.end = next_highlight.range.end;
16396 }
16397 row_highlights.remove(ix + 1);
16398 } else {
16399 break;
16400 }
16401 }
16402 }
16403 }
16404
16405 /// Remove any highlighted row ranges of the given type that intersect the
16406 /// given ranges.
16407 pub fn remove_highlighted_rows<T: 'static>(
16408 &mut self,
16409 ranges_to_remove: Vec<Range<Anchor>>,
16410 cx: &mut Context<Self>,
16411 ) {
16412 let snapshot = self.buffer().read(cx).snapshot(cx);
16413 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16414 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16415 row_highlights.retain(|highlight| {
16416 while let Some(range_to_remove) = ranges_to_remove.peek() {
16417 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16418 Ordering::Less | Ordering::Equal => {
16419 ranges_to_remove.next();
16420 }
16421 Ordering::Greater => {
16422 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16423 Ordering::Less | Ordering::Equal => {
16424 return false;
16425 }
16426 Ordering::Greater => break,
16427 }
16428 }
16429 }
16430 }
16431
16432 true
16433 })
16434 }
16435
16436 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16437 pub fn clear_row_highlights<T: 'static>(&mut self) {
16438 self.highlighted_rows.remove(&TypeId::of::<T>());
16439 }
16440
16441 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16442 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16443 self.highlighted_rows
16444 .get(&TypeId::of::<T>())
16445 .map_or(&[] as &[_], |vec| vec.as_slice())
16446 .iter()
16447 .map(|highlight| (highlight.range.clone(), highlight.color))
16448 }
16449
16450 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16451 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16452 /// Allows to ignore certain kinds of highlights.
16453 pub fn highlighted_display_rows(
16454 &self,
16455 window: &mut Window,
16456 cx: &mut App,
16457 ) -> BTreeMap<DisplayRow, LineHighlight> {
16458 let snapshot = self.snapshot(window, cx);
16459 let mut used_highlight_orders = HashMap::default();
16460 self.highlighted_rows
16461 .iter()
16462 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16463 .fold(
16464 BTreeMap::<DisplayRow, LineHighlight>::new(),
16465 |mut unique_rows, highlight| {
16466 let start = highlight.range.start.to_display_point(&snapshot);
16467 let end = highlight.range.end.to_display_point(&snapshot);
16468 let start_row = start.row().0;
16469 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16470 && end.column() == 0
16471 {
16472 end.row().0.saturating_sub(1)
16473 } else {
16474 end.row().0
16475 };
16476 for row in start_row..=end_row {
16477 let used_index =
16478 used_highlight_orders.entry(row).or_insert(highlight.index);
16479 if highlight.index >= *used_index {
16480 *used_index = highlight.index;
16481 unique_rows.insert(DisplayRow(row), highlight.color.into());
16482 }
16483 }
16484 unique_rows
16485 },
16486 )
16487 }
16488
16489 pub fn highlighted_display_row_for_autoscroll(
16490 &self,
16491 snapshot: &DisplaySnapshot,
16492 ) -> Option<DisplayRow> {
16493 self.highlighted_rows
16494 .values()
16495 .flat_map(|highlighted_rows| highlighted_rows.iter())
16496 .filter_map(|highlight| {
16497 if highlight.should_autoscroll {
16498 Some(highlight.range.start.to_display_point(snapshot).row())
16499 } else {
16500 None
16501 }
16502 })
16503 .min()
16504 }
16505
16506 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16507 self.highlight_background::<SearchWithinRange>(
16508 ranges,
16509 |colors| colors.editor_document_highlight_read_background,
16510 cx,
16511 )
16512 }
16513
16514 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16515 self.breadcrumb_header = Some(new_header);
16516 }
16517
16518 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16519 self.clear_background_highlights::<SearchWithinRange>(cx);
16520 }
16521
16522 pub fn highlight_background<T: 'static>(
16523 &mut self,
16524 ranges: &[Range<Anchor>],
16525 color_fetcher: fn(&ThemeColors) -> Hsla,
16526 cx: &mut Context<Self>,
16527 ) {
16528 self.background_highlights
16529 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16530 self.scrollbar_marker_state.dirty = true;
16531 cx.notify();
16532 }
16533
16534 pub fn clear_background_highlights<T: 'static>(
16535 &mut self,
16536 cx: &mut Context<Self>,
16537 ) -> Option<BackgroundHighlight> {
16538 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16539 if !text_highlights.1.is_empty() {
16540 self.scrollbar_marker_state.dirty = true;
16541 cx.notify();
16542 }
16543 Some(text_highlights)
16544 }
16545
16546 pub fn highlight_gutter<T: 'static>(
16547 &mut self,
16548 ranges: &[Range<Anchor>],
16549 color_fetcher: fn(&App) -> Hsla,
16550 cx: &mut Context<Self>,
16551 ) {
16552 self.gutter_highlights
16553 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16554 cx.notify();
16555 }
16556
16557 pub fn clear_gutter_highlights<T: 'static>(
16558 &mut self,
16559 cx: &mut Context<Self>,
16560 ) -> Option<GutterHighlight> {
16561 cx.notify();
16562 self.gutter_highlights.remove(&TypeId::of::<T>())
16563 }
16564
16565 #[cfg(feature = "test-support")]
16566 pub fn all_text_background_highlights(
16567 &self,
16568 window: &mut Window,
16569 cx: &mut Context<Self>,
16570 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16571 let snapshot = self.snapshot(window, cx);
16572 let buffer = &snapshot.buffer_snapshot;
16573 let start = buffer.anchor_before(0);
16574 let end = buffer.anchor_after(buffer.len());
16575 let theme = cx.theme().colors();
16576 self.background_highlights_in_range(start..end, &snapshot, theme)
16577 }
16578
16579 #[cfg(feature = "test-support")]
16580 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16581 let snapshot = self.buffer().read(cx).snapshot(cx);
16582
16583 let highlights = self
16584 .background_highlights
16585 .get(&TypeId::of::<items::BufferSearchHighlights>());
16586
16587 if let Some((_color, ranges)) = highlights {
16588 ranges
16589 .iter()
16590 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16591 .collect_vec()
16592 } else {
16593 vec![]
16594 }
16595 }
16596
16597 fn document_highlights_for_position<'a>(
16598 &'a self,
16599 position: Anchor,
16600 buffer: &'a MultiBufferSnapshot,
16601 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16602 let read_highlights = self
16603 .background_highlights
16604 .get(&TypeId::of::<DocumentHighlightRead>())
16605 .map(|h| &h.1);
16606 let write_highlights = self
16607 .background_highlights
16608 .get(&TypeId::of::<DocumentHighlightWrite>())
16609 .map(|h| &h.1);
16610 let left_position = position.bias_left(buffer);
16611 let right_position = position.bias_right(buffer);
16612 read_highlights
16613 .into_iter()
16614 .chain(write_highlights)
16615 .flat_map(move |ranges| {
16616 let start_ix = match ranges.binary_search_by(|probe| {
16617 let cmp = probe.end.cmp(&left_position, buffer);
16618 if cmp.is_ge() {
16619 Ordering::Greater
16620 } else {
16621 Ordering::Less
16622 }
16623 }) {
16624 Ok(i) | Err(i) => i,
16625 };
16626
16627 ranges[start_ix..]
16628 .iter()
16629 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16630 })
16631 }
16632
16633 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16634 self.background_highlights
16635 .get(&TypeId::of::<T>())
16636 .map_or(false, |(_, highlights)| !highlights.is_empty())
16637 }
16638
16639 pub fn background_highlights_in_range(
16640 &self,
16641 search_range: Range<Anchor>,
16642 display_snapshot: &DisplaySnapshot,
16643 theme: &ThemeColors,
16644 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16645 let mut results = Vec::new();
16646 for (color_fetcher, ranges) in self.background_highlights.values() {
16647 let color = color_fetcher(theme);
16648 let start_ix = match ranges.binary_search_by(|probe| {
16649 let cmp = probe
16650 .end
16651 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16652 if cmp.is_gt() {
16653 Ordering::Greater
16654 } else {
16655 Ordering::Less
16656 }
16657 }) {
16658 Ok(i) | Err(i) => i,
16659 };
16660 for range in &ranges[start_ix..] {
16661 if range
16662 .start
16663 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16664 .is_ge()
16665 {
16666 break;
16667 }
16668
16669 let start = range.start.to_display_point(display_snapshot);
16670 let end = range.end.to_display_point(display_snapshot);
16671 results.push((start..end, color))
16672 }
16673 }
16674 results
16675 }
16676
16677 pub fn background_highlight_row_ranges<T: 'static>(
16678 &self,
16679 search_range: Range<Anchor>,
16680 display_snapshot: &DisplaySnapshot,
16681 count: usize,
16682 ) -> Vec<RangeInclusive<DisplayPoint>> {
16683 let mut results = Vec::new();
16684 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16685 return vec![];
16686 };
16687
16688 let start_ix = match ranges.binary_search_by(|probe| {
16689 let cmp = probe
16690 .end
16691 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16692 if cmp.is_gt() {
16693 Ordering::Greater
16694 } else {
16695 Ordering::Less
16696 }
16697 }) {
16698 Ok(i) | Err(i) => i,
16699 };
16700 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16701 if let (Some(start_display), Some(end_display)) = (start, end) {
16702 results.push(
16703 start_display.to_display_point(display_snapshot)
16704 ..=end_display.to_display_point(display_snapshot),
16705 );
16706 }
16707 };
16708 let mut start_row: Option<Point> = None;
16709 let mut end_row: Option<Point> = None;
16710 if ranges.len() > count {
16711 return Vec::new();
16712 }
16713 for range in &ranges[start_ix..] {
16714 if range
16715 .start
16716 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16717 .is_ge()
16718 {
16719 break;
16720 }
16721 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16722 if let Some(current_row) = &end_row {
16723 if end.row == current_row.row {
16724 continue;
16725 }
16726 }
16727 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16728 if start_row.is_none() {
16729 assert_eq!(end_row, None);
16730 start_row = Some(start);
16731 end_row = Some(end);
16732 continue;
16733 }
16734 if let Some(current_end) = end_row.as_mut() {
16735 if start.row > current_end.row + 1 {
16736 push_region(start_row, end_row);
16737 start_row = Some(start);
16738 end_row = Some(end);
16739 } else {
16740 // Merge two hunks.
16741 *current_end = end;
16742 }
16743 } else {
16744 unreachable!();
16745 }
16746 }
16747 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16748 push_region(start_row, end_row);
16749 results
16750 }
16751
16752 pub fn gutter_highlights_in_range(
16753 &self,
16754 search_range: Range<Anchor>,
16755 display_snapshot: &DisplaySnapshot,
16756 cx: &App,
16757 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16758 let mut results = Vec::new();
16759 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16760 let color = color_fetcher(cx);
16761 let start_ix = match ranges.binary_search_by(|probe| {
16762 let cmp = probe
16763 .end
16764 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16765 if cmp.is_gt() {
16766 Ordering::Greater
16767 } else {
16768 Ordering::Less
16769 }
16770 }) {
16771 Ok(i) | Err(i) => i,
16772 };
16773 for range in &ranges[start_ix..] {
16774 if range
16775 .start
16776 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16777 .is_ge()
16778 {
16779 break;
16780 }
16781
16782 let start = range.start.to_display_point(display_snapshot);
16783 let end = range.end.to_display_point(display_snapshot);
16784 results.push((start..end, color))
16785 }
16786 }
16787 results
16788 }
16789
16790 /// Get the text ranges corresponding to the redaction query
16791 pub fn redacted_ranges(
16792 &self,
16793 search_range: Range<Anchor>,
16794 display_snapshot: &DisplaySnapshot,
16795 cx: &App,
16796 ) -> Vec<Range<DisplayPoint>> {
16797 display_snapshot
16798 .buffer_snapshot
16799 .redacted_ranges(search_range, |file| {
16800 if let Some(file) = file {
16801 file.is_private()
16802 && EditorSettings::get(
16803 Some(SettingsLocation {
16804 worktree_id: file.worktree_id(cx),
16805 path: file.path().as_ref(),
16806 }),
16807 cx,
16808 )
16809 .redact_private_values
16810 } else {
16811 false
16812 }
16813 })
16814 .map(|range| {
16815 range.start.to_display_point(display_snapshot)
16816 ..range.end.to_display_point(display_snapshot)
16817 })
16818 .collect()
16819 }
16820
16821 pub fn highlight_text<T: 'static>(
16822 &mut self,
16823 ranges: Vec<Range<Anchor>>,
16824 style: HighlightStyle,
16825 cx: &mut Context<Self>,
16826 ) {
16827 self.display_map.update(cx, |map, _| {
16828 map.highlight_text(TypeId::of::<T>(), ranges, style)
16829 });
16830 cx.notify();
16831 }
16832
16833 pub(crate) fn highlight_inlays<T: 'static>(
16834 &mut self,
16835 highlights: Vec<InlayHighlight>,
16836 style: HighlightStyle,
16837 cx: &mut Context<Self>,
16838 ) {
16839 self.display_map.update(cx, |map, _| {
16840 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16841 });
16842 cx.notify();
16843 }
16844
16845 pub fn text_highlights<'a, T: 'static>(
16846 &'a self,
16847 cx: &'a App,
16848 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16849 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16850 }
16851
16852 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16853 let cleared = self
16854 .display_map
16855 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16856 if cleared {
16857 cx.notify();
16858 }
16859 }
16860
16861 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16862 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16863 && self.focus_handle.is_focused(window)
16864 }
16865
16866 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16867 self.show_cursor_when_unfocused = is_enabled;
16868 cx.notify();
16869 }
16870
16871 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16872 cx.notify();
16873 }
16874
16875 fn on_buffer_event(
16876 &mut self,
16877 multibuffer: &Entity<MultiBuffer>,
16878 event: &multi_buffer::Event,
16879 window: &mut Window,
16880 cx: &mut Context<Self>,
16881 ) {
16882 match event {
16883 multi_buffer::Event::Edited {
16884 singleton_buffer_edited,
16885 edited_buffer: buffer_edited,
16886 } => {
16887 self.scrollbar_marker_state.dirty = true;
16888 self.active_indent_guides_state.dirty = true;
16889 self.refresh_active_diagnostics(cx);
16890 self.refresh_code_actions(window, cx);
16891 if self.has_active_inline_completion() {
16892 self.update_visible_inline_completion(window, cx);
16893 }
16894 if let Some(buffer) = buffer_edited {
16895 let buffer_id = buffer.read(cx).remote_id();
16896 if !self.registered_buffers.contains_key(&buffer_id) {
16897 if let Some(project) = self.project.as_ref() {
16898 project.update(cx, |project, cx| {
16899 self.registered_buffers.insert(
16900 buffer_id,
16901 project.register_buffer_with_language_servers(&buffer, cx),
16902 );
16903 })
16904 }
16905 }
16906 }
16907 cx.emit(EditorEvent::BufferEdited);
16908 cx.emit(SearchEvent::MatchesInvalidated);
16909 if *singleton_buffer_edited {
16910 if let Some(project) = &self.project {
16911 #[allow(clippy::mutable_key_type)]
16912 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16913 multibuffer
16914 .all_buffers()
16915 .into_iter()
16916 .filter_map(|buffer| {
16917 buffer.update(cx, |buffer, cx| {
16918 let language = buffer.language()?;
16919 let should_discard = project.update(cx, |project, cx| {
16920 project.is_local()
16921 && !project.has_language_servers_for(buffer, cx)
16922 });
16923 should_discard.not().then_some(language.clone())
16924 })
16925 })
16926 .collect::<HashSet<_>>()
16927 });
16928 if !languages_affected.is_empty() {
16929 self.refresh_inlay_hints(
16930 InlayHintRefreshReason::BufferEdited(languages_affected),
16931 cx,
16932 );
16933 }
16934 }
16935 }
16936
16937 let Some(project) = &self.project else { return };
16938 let (telemetry, is_via_ssh) = {
16939 let project = project.read(cx);
16940 let telemetry = project.client().telemetry().clone();
16941 let is_via_ssh = project.is_via_ssh();
16942 (telemetry, is_via_ssh)
16943 };
16944 refresh_linked_ranges(self, window, cx);
16945 telemetry.log_edit_event("editor", is_via_ssh);
16946 }
16947 multi_buffer::Event::ExcerptsAdded {
16948 buffer,
16949 predecessor,
16950 excerpts,
16951 } => {
16952 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16953 let buffer_id = buffer.read(cx).remote_id();
16954 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16955 if let Some(project) = &self.project {
16956 get_uncommitted_diff_for_buffer(
16957 project,
16958 [buffer.clone()],
16959 self.buffer.clone(),
16960 cx,
16961 )
16962 .detach();
16963 }
16964 }
16965 cx.emit(EditorEvent::ExcerptsAdded {
16966 buffer: buffer.clone(),
16967 predecessor: *predecessor,
16968 excerpts: excerpts.clone(),
16969 });
16970 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16971 }
16972 multi_buffer::Event::ExcerptsRemoved { ids } => {
16973 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16974 let buffer = self.buffer.read(cx);
16975 self.registered_buffers
16976 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16977 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16978 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16979 }
16980 multi_buffer::Event::ExcerptsEdited {
16981 excerpt_ids,
16982 buffer_ids,
16983 } => {
16984 self.display_map.update(cx, |map, cx| {
16985 map.unfold_buffers(buffer_ids.iter().copied(), cx)
16986 });
16987 cx.emit(EditorEvent::ExcerptsEdited {
16988 ids: excerpt_ids.clone(),
16989 })
16990 }
16991 multi_buffer::Event::ExcerptsExpanded { ids } => {
16992 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16993 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16994 }
16995 multi_buffer::Event::Reparsed(buffer_id) => {
16996 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16997 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16998
16999 cx.emit(EditorEvent::Reparsed(*buffer_id));
17000 }
17001 multi_buffer::Event::DiffHunksToggled => {
17002 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17003 }
17004 multi_buffer::Event::LanguageChanged(buffer_id) => {
17005 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17006 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17007 cx.emit(EditorEvent::Reparsed(*buffer_id));
17008 cx.notify();
17009 }
17010 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17011 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17012 multi_buffer::Event::FileHandleChanged
17013 | multi_buffer::Event::Reloaded
17014 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17015 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17016 multi_buffer::Event::DiagnosticsUpdated => {
17017 self.refresh_active_diagnostics(cx);
17018 self.refresh_inline_diagnostics(true, window, cx);
17019 self.scrollbar_marker_state.dirty = true;
17020 cx.notify();
17021 }
17022 _ => {}
17023 };
17024 }
17025
17026 fn on_display_map_changed(
17027 &mut self,
17028 _: Entity<DisplayMap>,
17029 _: &mut Window,
17030 cx: &mut Context<Self>,
17031 ) {
17032 cx.notify();
17033 }
17034
17035 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17036 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17037 self.update_edit_prediction_settings(cx);
17038 self.refresh_inline_completion(true, false, window, cx);
17039 self.refresh_inlay_hints(
17040 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17041 self.selections.newest_anchor().head(),
17042 &self.buffer.read(cx).snapshot(cx),
17043 cx,
17044 )),
17045 cx,
17046 );
17047
17048 let old_cursor_shape = self.cursor_shape;
17049
17050 {
17051 let editor_settings = EditorSettings::get_global(cx);
17052 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17053 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17054 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17055 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17056 }
17057
17058 if old_cursor_shape != self.cursor_shape {
17059 cx.emit(EditorEvent::CursorShapeChanged);
17060 }
17061
17062 let project_settings = ProjectSettings::get_global(cx);
17063 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17064
17065 if self.mode == EditorMode::Full {
17066 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17067 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17068 if self.show_inline_diagnostics != show_inline_diagnostics {
17069 self.show_inline_diagnostics = show_inline_diagnostics;
17070 self.refresh_inline_diagnostics(false, window, cx);
17071 }
17072
17073 if self.git_blame_inline_enabled != inline_blame_enabled {
17074 self.toggle_git_blame_inline_internal(false, window, cx);
17075 }
17076 }
17077
17078 cx.notify();
17079 }
17080
17081 pub fn set_searchable(&mut self, searchable: bool) {
17082 self.searchable = searchable;
17083 }
17084
17085 pub fn searchable(&self) -> bool {
17086 self.searchable
17087 }
17088
17089 fn open_proposed_changes_editor(
17090 &mut self,
17091 _: &OpenProposedChangesEditor,
17092 window: &mut Window,
17093 cx: &mut Context<Self>,
17094 ) {
17095 let Some(workspace) = self.workspace() else {
17096 cx.propagate();
17097 return;
17098 };
17099
17100 let selections = self.selections.all::<usize>(cx);
17101 let multi_buffer = self.buffer.read(cx);
17102 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17103 let mut new_selections_by_buffer = HashMap::default();
17104 for selection in selections {
17105 for (buffer, range, _) in
17106 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17107 {
17108 let mut range = range.to_point(buffer);
17109 range.start.column = 0;
17110 range.end.column = buffer.line_len(range.end.row);
17111 new_selections_by_buffer
17112 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17113 .or_insert(Vec::new())
17114 .push(range)
17115 }
17116 }
17117
17118 let proposed_changes_buffers = new_selections_by_buffer
17119 .into_iter()
17120 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17121 .collect::<Vec<_>>();
17122 let proposed_changes_editor = cx.new(|cx| {
17123 ProposedChangesEditor::new(
17124 "Proposed changes",
17125 proposed_changes_buffers,
17126 self.project.clone(),
17127 window,
17128 cx,
17129 )
17130 });
17131
17132 window.defer(cx, move |window, cx| {
17133 workspace.update(cx, |workspace, cx| {
17134 workspace.active_pane().update(cx, |pane, cx| {
17135 pane.add_item(
17136 Box::new(proposed_changes_editor),
17137 true,
17138 true,
17139 None,
17140 window,
17141 cx,
17142 );
17143 });
17144 });
17145 });
17146 }
17147
17148 pub fn open_excerpts_in_split(
17149 &mut self,
17150 _: &OpenExcerptsSplit,
17151 window: &mut Window,
17152 cx: &mut Context<Self>,
17153 ) {
17154 self.open_excerpts_common(None, true, window, cx)
17155 }
17156
17157 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17158 self.open_excerpts_common(None, false, window, cx)
17159 }
17160
17161 fn open_excerpts_common(
17162 &mut self,
17163 jump_data: Option<JumpData>,
17164 split: bool,
17165 window: &mut Window,
17166 cx: &mut Context<Self>,
17167 ) {
17168 let Some(workspace) = self.workspace() else {
17169 cx.propagate();
17170 return;
17171 };
17172
17173 if self.buffer.read(cx).is_singleton() {
17174 cx.propagate();
17175 return;
17176 }
17177
17178 let mut new_selections_by_buffer = HashMap::default();
17179 match &jump_data {
17180 Some(JumpData::MultiBufferPoint {
17181 excerpt_id,
17182 position,
17183 anchor,
17184 line_offset_from_top,
17185 }) => {
17186 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17187 if let Some(buffer) = multi_buffer_snapshot
17188 .buffer_id_for_excerpt(*excerpt_id)
17189 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17190 {
17191 let buffer_snapshot = buffer.read(cx).snapshot();
17192 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17193 language::ToPoint::to_point(anchor, &buffer_snapshot)
17194 } else {
17195 buffer_snapshot.clip_point(*position, Bias::Left)
17196 };
17197 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17198 new_selections_by_buffer.insert(
17199 buffer,
17200 (
17201 vec![jump_to_offset..jump_to_offset],
17202 Some(*line_offset_from_top),
17203 ),
17204 );
17205 }
17206 }
17207 Some(JumpData::MultiBufferRow {
17208 row,
17209 line_offset_from_top,
17210 }) => {
17211 let point = MultiBufferPoint::new(row.0, 0);
17212 if let Some((buffer, buffer_point, _)) =
17213 self.buffer.read(cx).point_to_buffer_point(point, cx)
17214 {
17215 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17216 new_selections_by_buffer
17217 .entry(buffer)
17218 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17219 .0
17220 .push(buffer_offset..buffer_offset)
17221 }
17222 }
17223 None => {
17224 let selections = self.selections.all::<usize>(cx);
17225 let multi_buffer = self.buffer.read(cx);
17226 for selection in selections {
17227 for (snapshot, range, _, anchor) in multi_buffer
17228 .snapshot(cx)
17229 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17230 {
17231 if let Some(anchor) = anchor {
17232 // selection is in a deleted hunk
17233 let Some(buffer_id) = anchor.buffer_id else {
17234 continue;
17235 };
17236 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17237 continue;
17238 };
17239 let offset = text::ToOffset::to_offset(
17240 &anchor.text_anchor,
17241 &buffer_handle.read(cx).snapshot(),
17242 );
17243 let range = offset..offset;
17244 new_selections_by_buffer
17245 .entry(buffer_handle)
17246 .or_insert((Vec::new(), None))
17247 .0
17248 .push(range)
17249 } else {
17250 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17251 else {
17252 continue;
17253 };
17254 new_selections_by_buffer
17255 .entry(buffer_handle)
17256 .or_insert((Vec::new(), None))
17257 .0
17258 .push(range)
17259 }
17260 }
17261 }
17262 }
17263 }
17264
17265 new_selections_by_buffer
17266 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17267
17268 if new_selections_by_buffer.is_empty() {
17269 return;
17270 }
17271
17272 // We defer the pane interaction because we ourselves are a workspace item
17273 // and activating a new item causes the pane to call a method on us reentrantly,
17274 // which panics if we're on the stack.
17275 window.defer(cx, move |window, cx| {
17276 workspace.update(cx, |workspace, cx| {
17277 let pane = if split {
17278 workspace.adjacent_pane(window, cx)
17279 } else {
17280 workspace.active_pane().clone()
17281 };
17282
17283 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17284 let editor = buffer
17285 .read(cx)
17286 .file()
17287 .is_none()
17288 .then(|| {
17289 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17290 // so `workspace.open_project_item` will never find them, always opening a new editor.
17291 // Instead, we try to activate the existing editor in the pane first.
17292 let (editor, pane_item_index) =
17293 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17294 let editor = item.downcast::<Editor>()?;
17295 let singleton_buffer =
17296 editor.read(cx).buffer().read(cx).as_singleton()?;
17297 if singleton_buffer == buffer {
17298 Some((editor, i))
17299 } else {
17300 None
17301 }
17302 })?;
17303 pane.update(cx, |pane, cx| {
17304 pane.activate_item(pane_item_index, true, true, window, cx)
17305 });
17306 Some(editor)
17307 })
17308 .flatten()
17309 .unwrap_or_else(|| {
17310 workspace.open_project_item::<Self>(
17311 pane.clone(),
17312 buffer,
17313 true,
17314 true,
17315 window,
17316 cx,
17317 )
17318 });
17319
17320 editor.update(cx, |editor, cx| {
17321 let autoscroll = match scroll_offset {
17322 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17323 None => Autoscroll::newest(),
17324 };
17325 let nav_history = editor.nav_history.take();
17326 editor.change_selections(Some(autoscroll), window, cx, |s| {
17327 s.select_ranges(ranges);
17328 });
17329 editor.nav_history = nav_history;
17330 });
17331 }
17332 })
17333 });
17334 }
17335
17336 // For now, don't allow opening excerpts in buffers that aren't backed by
17337 // regular project files.
17338 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17339 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17340 }
17341
17342 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17343 let snapshot = self.buffer.read(cx).read(cx);
17344 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17345 Some(
17346 ranges
17347 .iter()
17348 .map(move |range| {
17349 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17350 })
17351 .collect(),
17352 )
17353 }
17354
17355 fn selection_replacement_ranges(
17356 &self,
17357 range: Range<OffsetUtf16>,
17358 cx: &mut App,
17359 ) -> Vec<Range<OffsetUtf16>> {
17360 let selections = self.selections.all::<OffsetUtf16>(cx);
17361 let newest_selection = selections
17362 .iter()
17363 .max_by_key(|selection| selection.id)
17364 .unwrap();
17365 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17366 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17367 let snapshot = self.buffer.read(cx).read(cx);
17368 selections
17369 .into_iter()
17370 .map(|mut selection| {
17371 selection.start.0 =
17372 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17373 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17374 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17375 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17376 })
17377 .collect()
17378 }
17379
17380 fn report_editor_event(
17381 &self,
17382 event_type: &'static str,
17383 file_extension: Option<String>,
17384 cx: &App,
17385 ) {
17386 if cfg!(any(test, feature = "test-support")) {
17387 return;
17388 }
17389
17390 let Some(project) = &self.project else { return };
17391
17392 // If None, we are in a file without an extension
17393 let file = self
17394 .buffer
17395 .read(cx)
17396 .as_singleton()
17397 .and_then(|b| b.read(cx).file());
17398 let file_extension = file_extension.or(file
17399 .as_ref()
17400 .and_then(|file| Path::new(file.file_name(cx)).extension())
17401 .and_then(|e| e.to_str())
17402 .map(|a| a.to_string()));
17403
17404 let vim_mode = cx
17405 .global::<SettingsStore>()
17406 .raw_user_settings()
17407 .get("vim_mode")
17408 == Some(&serde_json::Value::Bool(true));
17409
17410 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17411 let copilot_enabled = edit_predictions_provider
17412 == language::language_settings::EditPredictionProvider::Copilot;
17413 let copilot_enabled_for_language = self
17414 .buffer
17415 .read(cx)
17416 .language_settings(cx)
17417 .show_edit_predictions;
17418
17419 let project = project.read(cx);
17420 telemetry::event!(
17421 event_type,
17422 file_extension,
17423 vim_mode,
17424 copilot_enabled,
17425 copilot_enabled_for_language,
17426 edit_predictions_provider,
17427 is_via_ssh = project.is_via_ssh(),
17428 );
17429 }
17430
17431 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17432 /// with each line being an array of {text, highlight} objects.
17433 fn copy_highlight_json(
17434 &mut self,
17435 _: &CopyHighlightJson,
17436 window: &mut Window,
17437 cx: &mut Context<Self>,
17438 ) {
17439 #[derive(Serialize)]
17440 struct Chunk<'a> {
17441 text: String,
17442 highlight: Option<&'a str>,
17443 }
17444
17445 let snapshot = self.buffer.read(cx).snapshot(cx);
17446 let range = self
17447 .selected_text_range(false, window, cx)
17448 .and_then(|selection| {
17449 if selection.range.is_empty() {
17450 None
17451 } else {
17452 Some(selection.range)
17453 }
17454 })
17455 .unwrap_or_else(|| 0..snapshot.len());
17456
17457 let chunks = snapshot.chunks(range, true);
17458 let mut lines = Vec::new();
17459 let mut line: VecDeque<Chunk> = VecDeque::new();
17460
17461 let Some(style) = self.style.as_ref() else {
17462 return;
17463 };
17464
17465 for chunk in chunks {
17466 let highlight = chunk
17467 .syntax_highlight_id
17468 .and_then(|id| id.name(&style.syntax));
17469 let mut chunk_lines = chunk.text.split('\n').peekable();
17470 while let Some(text) = chunk_lines.next() {
17471 let mut merged_with_last_token = false;
17472 if let Some(last_token) = line.back_mut() {
17473 if last_token.highlight == highlight {
17474 last_token.text.push_str(text);
17475 merged_with_last_token = true;
17476 }
17477 }
17478
17479 if !merged_with_last_token {
17480 line.push_back(Chunk {
17481 text: text.into(),
17482 highlight,
17483 });
17484 }
17485
17486 if chunk_lines.peek().is_some() {
17487 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17488 line.pop_front();
17489 }
17490 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17491 line.pop_back();
17492 }
17493
17494 lines.push(mem::take(&mut line));
17495 }
17496 }
17497 }
17498
17499 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17500 return;
17501 };
17502 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17503 }
17504
17505 pub fn open_context_menu(
17506 &mut self,
17507 _: &OpenContextMenu,
17508 window: &mut Window,
17509 cx: &mut Context<Self>,
17510 ) {
17511 self.request_autoscroll(Autoscroll::newest(), cx);
17512 let position = self.selections.newest_display(cx).start;
17513 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17514 }
17515
17516 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17517 &self.inlay_hint_cache
17518 }
17519
17520 pub fn replay_insert_event(
17521 &mut self,
17522 text: &str,
17523 relative_utf16_range: Option<Range<isize>>,
17524 window: &mut Window,
17525 cx: &mut Context<Self>,
17526 ) {
17527 if !self.input_enabled {
17528 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17529 return;
17530 }
17531 if let Some(relative_utf16_range) = relative_utf16_range {
17532 let selections = self.selections.all::<OffsetUtf16>(cx);
17533 self.change_selections(None, window, cx, |s| {
17534 let new_ranges = selections.into_iter().map(|range| {
17535 let start = OffsetUtf16(
17536 range
17537 .head()
17538 .0
17539 .saturating_add_signed(relative_utf16_range.start),
17540 );
17541 let end = OffsetUtf16(
17542 range
17543 .head()
17544 .0
17545 .saturating_add_signed(relative_utf16_range.end),
17546 );
17547 start..end
17548 });
17549 s.select_ranges(new_ranges);
17550 });
17551 }
17552
17553 self.handle_input(text, window, cx);
17554 }
17555
17556 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17557 let Some(provider) = self.semantics_provider.as_ref() else {
17558 return false;
17559 };
17560
17561 let mut supports = false;
17562 self.buffer().update(cx, |this, cx| {
17563 this.for_each_buffer(|buffer| {
17564 supports |= provider.supports_inlay_hints(buffer, cx);
17565 });
17566 });
17567
17568 supports
17569 }
17570
17571 pub fn is_focused(&self, window: &Window) -> bool {
17572 self.focus_handle.is_focused(window)
17573 }
17574
17575 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17576 cx.emit(EditorEvent::Focused);
17577
17578 if let Some(descendant) = self
17579 .last_focused_descendant
17580 .take()
17581 .and_then(|descendant| descendant.upgrade())
17582 {
17583 window.focus(&descendant);
17584 } else {
17585 if let Some(blame) = self.blame.as_ref() {
17586 blame.update(cx, GitBlame::focus)
17587 }
17588
17589 self.blink_manager.update(cx, BlinkManager::enable);
17590 self.show_cursor_names(window, cx);
17591 self.buffer.update(cx, |buffer, cx| {
17592 buffer.finalize_last_transaction(cx);
17593 if self.leader_peer_id.is_none() {
17594 buffer.set_active_selections(
17595 &self.selections.disjoint_anchors(),
17596 self.selections.line_mode,
17597 self.cursor_shape,
17598 cx,
17599 );
17600 }
17601 });
17602 }
17603 }
17604
17605 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17606 cx.emit(EditorEvent::FocusedIn)
17607 }
17608
17609 fn handle_focus_out(
17610 &mut self,
17611 event: FocusOutEvent,
17612 _window: &mut Window,
17613 cx: &mut Context<Self>,
17614 ) {
17615 if event.blurred != self.focus_handle {
17616 self.last_focused_descendant = Some(event.blurred);
17617 }
17618 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17619 }
17620
17621 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17622 self.blink_manager.update(cx, BlinkManager::disable);
17623 self.buffer
17624 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17625
17626 if let Some(blame) = self.blame.as_ref() {
17627 blame.update(cx, GitBlame::blur)
17628 }
17629 if !self.hover_state.focused(window, cx) {
17630 hide_hover(self, cx);
17631 }
17632 if !self
17633 .context_menu
17634 .borrow()
17635 .as_ref()
17636 .is_some_and(|context_menu| context_menu.focused(window, cx))
17637 {
17638 self.hide_context_menu(window, cx);
17639 }
17640 self.discard_inline_completion(false, cx);
17641 cx.emit(EditorEvent::Blurred);
17642 cx.notify();
17643 }
17644
17645 pub fn register_action<A: Action>(
17646 &mut self,
17647 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17648 ) -> Subscription {
17649 let id = self.next_editor_action_id.post_inc();
17650 let listener = Arc::new(listener);
17651 self.editor_actions.borrow_mut().insert(
17652 id,
17653 Box::new(move |window, _| {
17654 let listener = listener.clone();
17655 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17656 let action = action.downcast_ref().unwrap();
17657 if phase == DispatchPhase::Bubble {
17658 listener(action, window, cx)
17659 }
17660 })
17661 }),
17662 );
17663
17664 let editor_actions = self.editor_actions.clone();
17665 Subscription::new(move || {
17666 editor_actions.borrow_mut().remove(&id);
17667 })
17668 }
17669
17670 pub fn file_header_size(&self) -> u32 {
17671 FILE_HEADER_HEIGHT
17672 }
17673
17674 pub fn restore(
17675 &mut self,
17676 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17677 window: &mut Window,
17678 cx: &mut Context<Self>,
17679 ) {
17680 let workspace = self.workspace();
17681 let project = self.project.as_ref();
17682 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17683 let mut tasks = Vec::new();
17684 for (buffer_id, changes) in revert_changes {
17685 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17686 buffer.update(cx, |buffer, cx| {
17687 buffer.edit(
17688 changes
17689 .into_iter()
17690 .map(|(range, text)| (range, text.to_string())),
17691 None,
17692 cx,
17693 );
17694 });
17695
17696 if let Some(project) =
17697 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17698 {
17699 project.update(cx, |project, cx| {
17700 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17701 })
17702 }
17703 }
17704 }
17705 tasks
17706 });
17707 cx.spawn_in(window, async move |_, cx| {
17708 for (buffer, task) in save_tasks {
17709 let result = task.await;
17710 if result.is_err() {
17711 let Some(path) = buffer
17712 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17713 .ok()
17714 else {
17715 continue;
17716 };
17717 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17718 let Some(task) = cx
17719 .update_window_entity(&workspace, |workspace, window, cx| {
17720 workspace
17721 .open_path_preview(path, None, false, false, false, window, cx)
17722 })
17723 .ok()
17724 else {
17725 continue;
17726 };
17727 task.await.log_err();
17728 }
17729 }
17730 }
17731 })
17732 .detach();
17733 self.change_selections(None, window, cx, |selections| selections.refresh());
17734 }
17735
17736 pub fn to_pixel_point(
17737 &self,
17738 source: multi_buffer::Anchor,
17739 editor_snapshot: &EditorSnapshot,
17740 window: &mut Window,
17741 ) -> Option<gpui::Point<Pixels>> {
17742 let source_point = source.to_display_point(editor_snapshot);
17743 self.display_to_pixel_point(source_point, editor_snapshot, window)
17744 }
17745
17746 pub fn display_to_pixel_point(
17747 &self,
17748 source: DisplayPoint,
17749 editor_snapshot: &EditorSnapshot,
17750 window: &mut Window,
17751 ) -> Option<gpui::Point<Pixels>> {
17752 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17753 let text_layout_details = self.text_layout_details(window);
17754 let scroll_top = text_layout_details
17755 .scroll_anchor
17756 .scroll_position(editor_snapshot)
17757 .y;
17758
17759 if source.row().as_f32() < scroll_top.floor() {
17760 return None;
17761 }
17762 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17763 let source_y = line_height * (source.row().as_f32() - scroll_top);
17764 Some(gpui::Point::new(source_x, source_y))
17765 }
17766
17767 pub fn has_visible_completions_menu(&self) -> bool {
17768 !self.edit_prediction_preview_is_active()
17769 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17770 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17771 })
17772 }
17773
17774 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17775 self.addons
17776 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17777 }
17778
17779 pub fn unregister_addon<T: Addon>(&mut self) {
17780 self.addons.remove(&std::any::TypeId::of::<T>());
17781 }
17782
17783 pub fn addon<T: Addon>(&self) -> Option<&T> {
17784 let type_id = std::any::TypeId::of::<T>();
17785 self.addons
17786 .get(&type_id)
17787 .and_then(|item| item.to_any().downcast_ref::<T>())
17788 }
17789
17790 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17791 let text_layout_details = self.text_layout_details(window);
17792 let style = &text_layout_details.editor_style;
17793 let font_id = window.text_system().resolve_font(&style.text.font());
17794 let font_size = style.text.font_size.to_pixels(window.rem_size());
17795 let line_height = style.text.line_height_in_pixels(window.rem_size());
17796 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17797
17798 gpui::Size::new(em_width, line_height)
17799 }
17800
17801 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17802 self.load_diff_task.clone()
17803 }
17804
17805 fn read_metadata_from_db(
17806 &mut self,
17807 item_id: u64,
17808 workspace_id: WorkspaceId,
17809 window: &mut Window,
17810 cx: &mut Context<Editor>,
17811 ) {
17812 if self.is_singleton(cx)
17813 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17814 {
17815 let buffer_snapshot = OnceCell::new();
17816
17817 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17818 if !folds.is_empty() {
17819 let snapshot =
17820 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17821 self.fold_ranges(
17822 folds
17823 .into_iter()
17824 .map(|(start, end)| {
17825 snapshot.clip_offset(start, Bias::Left)
17826 ..snapshot.clip_offset(end, Bias::Right)
17827 })
17828 .collect(),
17829 false,
17830 window,
17831 cx,
17832 );
17833 }
17834 }
17835
17836 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17837 if !selections.is_empty() {
17838 let snapshot =
17839 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17840 self.change_selections(None, window, cx, |s| {
17841 s.select_ranges(selections.into_iter().map(|(start, end)| {
17842 snapshot.clip_offset(start, Bias::Left)
17843 ..snapshot.clip_offset(end, Bias::Right)
17844 }));
17845 });
17846 }
17847 };
17848 }
17849
17850 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17851 }
17852}
17853
17854fn insert_extra_newline_brackets(
17855 buffer: &MultiBufferSnapshot,
17856 range: Range<usize>,
17857 language: &language::LanguageScope,
17858) -> bool {
17859 let leading_whitespace_len = buffer
17860 .reversed_chars_at(range.start)
17861 .take_while(|c| c.is_whitespace() && *c != '\n')
17862 .map(|c| c.len_utf8())
17863 .sum::<usize>();
17864 let trailing_whitespace_len = buffer
17865 .chars_at(range.end)
17866 .take_while(|c| c.is_whitespace() && *c != '\n')
17867 .map(|c| c.len_utf8())
17868 .sum::<usize>();
17869 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17870
17871 language.brackets().any(|(pair, enabled)| {
17872 let pair_start = pair.start.trim_end();
17873 let pair_end = pair.end.trim_start();
17874
17875 enabled
17876 && pair.newline
17877 && buffer.contains_str_at(range.end, pair_end)
17878 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17879 })
17880}
17881
17882fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17883 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17884 [(buffer, range, _)] => (*buffer, range.clone()),
17885 _ => return false,
17886 };
17887 let pair = {
17888 let mut result: Option<BracketMatch> = None;
17889
17890 for pair in buffer
17891 .all_bracket_ranges(range.clone())
17892 .filter(move |pair| {
17893 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17894 })
17895 {
17896 let len = pair.close_range.end - pair.open_range.start;
17897
17898 if let Some(existing) = &result {
17899 let existing_len = existing.close_range.end - existing.open_range.start;
17900 if len > existing_len {
17901 continue;
17902 }
17903 }
17904
17905 result = Some(pair);
17906 }
17907
17908 result
17909 };
17910 let Some(pair) = pair else {
17911 return false;
17912 };
17913 pair.newline_only
17914 && buffer
17915 .chars_for_range(pair.open_range.end..range.start)
17916 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17917 .all(|c| c.is_whitespace() && c != '\n')
17918}
17919
17920fn get_uncommitted_diff_for_buffer(
17921 project: &Entity<Project>,
17922 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17923 buffer: Entity<MultiBuffer>,
17924 cx: &mut App,
17925) -> Task<()> {
17926 let mut tasks = Vec::new();
17927 project.update(cx, |project, cx| {
17928 for buffer in buffers {
17929 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
17930 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17931 }
17932 }
17933 });
17934 cx.spawn(async move |cx| {
17935 let diffs = future::join_all(tasks).await;
17936 buffer
17937 .update(cx, |buffer, cx| {
17938 for diff in diffs.into_iter().flatten() {
17939 buffer.add_diff(diff, cx);
17940 }
17941 })
17942 .ok();
17943 })
17944}
17945
17946fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17947 let tab_size = tab_size.get() as usize;
17948 let mut width = offset;
17949
17950 for ch in text.chars() {
17951 width += if ch == '\t' {
17952 tab_size - (width % tab_size)
17953 } else {
17954 1
17955 };
17956 }
17957
17958 width - offset
17959}
17960
17961#[cfg(test)]
17962mod tests {
17963 use super::*;
17964
17965 #[test]
17966 fn test_string_size_with_expanded_tabs() {
17967 let nz = |val| NonZeroU32::new(val).unwrap();
17968 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17969 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17970 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17971 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17972 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17973 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17974 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17975 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17976 }
17977}
17978
17979/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17980struct WordBreakingTokenizer<'a> {
17981 input: &'a str,
17982}
17983
17984impl<'a> WordBreakingTokenizer<'a> {
17985 fn new(input: &'a str) -> Self {
17986 Self { input }
17987 }
17988}
17989
17990fn is_char_ideographic(ch: char) -> bool {
17991 use unicode_script::Script::*;
17992 use unicode_script::UnicodeScript;
17993 matches!(ch.script(), Han | Tangut | Yi)
17994}
17995
17996fn is_grapheme_ideographic(text: &str) -> bool {
17997 text.chars().any(is_char_ideographic)
17998}
17999
18000fn is_grapheme_whitespace(text: &str) -> bool {
18001 text.chars().any(|x| x.is_whitespace())
18002}
18003
18004fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18005 text.chars().next().map_or(false, |ch| {
18006 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18007 })
18008}
18009
18010#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18011enum WordBreakToken<'a> {
18012 Word { token: &'a str, grapheme_len: usize },
18013 InlineWhitespace { token: &'a str, grapheme_len: usize },
18014 Newline,
18015}
18016
18017impl<'a> Iterator for WordBreakingTokenizer<'a> {
18018 /// Yields a span, the count of graphemes in the token, and whether it was
18019 /// whitespace. Note that it also breaks at word boundaries.
18020 type Item = WordBreakToken<'a>;
18021
18022 fn next(&mut self) -> Option<Self::Item> {
18023 use unicode_segmentation::UnicodeSegmentation;
18024 if self.input.is_empty() {
18025 return None;
18026 }
18027
18028 let mut iter = self.input.graphemes(true).peekable();
18029 let mut offset = 0;
18030 let mut grapheme_len = 0;
18031 if let Some(first_grapheme) = iter.next() {
18032 let is_newline = first_grapheme == "\n";
18033 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18034 offset += first_grapheme.len();
18035 grapheme_len += 1;
18036 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18037 if let Some(grapheme) = iter.peek().copied() {
18038 if should_stay_with_preceding_ideograph(grapheme) {
18039 offset += grapheme.len();
18040 grapheme_len += 1;
18041 }
18042 }
18043 } else {
18044 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18045 let mut next_word_bound = words.peek().copied();
18046 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18047 next_word_bound = words.next();
18048 }
18049 while let Some(grapheme) = iter.peek().copied() {
18050 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18051 break;
18052 };
18053 if is_grapheme_whitespace(grapheme) != is_whitespace
18054 || (grapheme == "\n") != is_newline
18055 {
18056 break;
18057 };
18058 offset += grapheme.len();
18059 grapheme_len += 1;
18060 iter.next();
18061 }
18062 }
18063 let token = &self.input[..offset];
18064 self.input = &self.input[offset..];
18065 if token == "\n" {
18066 Some(WordBreakToken::Newline)
18067 } else if is_whitespace {
18068 Some(WordBreakToken::InlineWhitespace {
18069 token,
18070 grapheme_len,
18071 })
18072 } else {
18073 Some(WordBreakToken::Word {
18074 token,
18075 grapheme_len,
18076 })
18077 }
18078 } else {
18079 None
18080 }
18081 }
18082}
18083
18084#[test]
18085fn test_word_breaking_tokenizer() {
18086 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18087 ("", &[]),
18088 (" ", &[whitespace(" ", 2)]),
18089 ("Ʒ", &[word("Ʒ", 1)]),
18090 ("Ǽ", &[word("Ǽ", 1)]),
18091 ("⋑", &[word("⋑", 1)]),
18092 ("⋑⋑", &[word("⋑⋑", 2)]),
18093 (
18094 "原理,进而",
18095 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18096 ),
18097 (
18098 "hello world",
18099 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18100 ),
18101 (
18102 "hello, world",
18103 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18104 ),
18105 (
18106 " hello world",
18107 &[
18108 whitespace(" ", 2),
18109 word("hello", 5),
18110 whitespace(" ", 1),
18111 word("world", 5),
18112 ],
18113 ),
18114 (
18115 "这是什么 \n 钢笔",
18116 &[
18117 word("这", 1),
18118 word("是", 1),
18119 word("什", 1),
18120 word("么", 1),
18121 whitespace(" ", 1),
18122 newline(),
18123 whitespace(" ", 1),
18124 word("钢", 1),
18125 word("笔", 1),
18126 ],
18127 ),
18128 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18129 ];
18130
18131 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18132 WordBreakToken::Word {
18133 token,
18134 grapheme_len,
18135 }
18136 }
18137
18138 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18139 WordBreakToken::InlineWhitespace {
18140 token,
18141 grapheme_len,
18142 }
18143 }
18144
18145 fn newline() -> WordBreakToken<'static> {
18146 WordBreakToken::Newline
18147 }
18148
18149 for (input, result) in tests {
18150 assert_eq!(
18151 WordBreakingTokenizer::new(input)
18152 .collect::<Vec<_>>()
18153 .as_slice(),
18154 *result,
18155 );
18156 }
18157}
18158
18159fn wrap_with_prefix(
18160 line_prefix: String,
18161 unwrapped_text: String,
18162 wrap_column: usize,
18163 tab_size: NonZeroU32,
18164 preserve_existing_whitespace: bool,
18165) -> String {
18166 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18167 let mut wrapped_text = String::new();
18168 let mut current_line = line_prefix.clone();
18169
18170 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18171 let mut current_line_len = line_prefix_len;
18172 let mut in_whitespace = false;
18173 for token in tokenizer {
18174 let have_preceding_whitespace = in_whitespace;
18175 match token {
18176 WordBreakToken::Word {
18177 token,
18178 grapheme_len,
18179 } => {
18180 in_whitespace = false;
18181 if current_line_len + grapheme_len > wrap_column
18182 && current_line_len != line_prefix_len
18183 {
18184 wrapped_text.push_str(current_line.trim_end());
18185 wrapped_text.push('\n');
18186 current_line.truncate(line_prefix.len());
18187 current_line_len = line_prefix_len;
18188 }
18189 current_line.push_str(token);
18190 current_line_len += grapheme_len;
18191 }
18192 WordBreakToken::InlineWhitespace {
18193 mut token,
18194 mut grapheme_len,
18195 } => {
18196 in_whitespace = true;
18197 if have_preceding_whitespace && !preserve_existing_whitespace {
18198 continue;
18199 }
18200 if !preserve_existing_whitespace {
18201 token = " ";
18202 grapheme_len = 1;
18203 }
18204 if current_line_len + grapheme_len > wrap_column {
18205 wrapped_text.push_str(current_line.trim_end());
18206 wrapped_text.push('\n');
18207 current_line.truncate(line_prefix.len());
18208 current_line_len = line_prefix_len;
18209 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18210 current_line.push_str(token);
18211 current_line_len += grapheme_len;
18212 }
18213 }
18214 WordBreakToken::Newline => {
18215 in_whitespace = true;
18216 if preserve_existing_whitespace {
18217 wrapped_text.push_str(current_line.trim_end());
18218 wrapped_text.push('\n');
18219 current_line.truncate(line_prefix.len());
18220 current_line_len = line_prefix_len;
18221 } else if have_preceding_whitespace {
18222 continue;
18223 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18224 {
18225 wrapped_text.push_str(current_line.trim_end());
18226 wrapped_text.push('\n');
18227 current_line.truncate(line_prefix.len());
18228 current_line_len = line_prefix_len;
18229 } else if current_line_len != line_prefix_len {
18230 current_line.push(' ');
18231 current_line_len += 1;
18232 }
18233 }
18234 }
18235 }
18236
18237 if !current_line.is_empty() {
18238 wrapped_text.push_str(¤t_line);
18239 }
18240 wrapped_text
18241}
18242
18243#[test]
18244fn test_wrap_with_prefix() {
18245 assert_eq!(
18246 wrap_with_prefix(
18247 "# ".to_string(),
18248 "abcdefg".to_string(),
18249 4,
18250 NonZeroU32::new(4).unwrap(),
18251 false,
18252 ),
18253 "# abcdefg"
18254 );
18255 assert_eq!(
18256 wrap_with_prefix(
18257 "".to_string(),
18258 "\thello world".to_string(),
18259 8,
18260 NonZeroU32::new(4).unwrap(),
18261 false,
18262 ),
18263 "hello\nworld"
18264 );
18265 assert_eq!(
18266 wrap_with_prefix(
18267 "// ".to_string(),
18268 "xx \nyy zz aa bb cc".to_string(),
18269 12,
18270 NonZeroU32::new(4).unwrap(),
18271 false,
18272 ),
18273 "// xx yy zz\n// aa bb cc"
18274 );
18275 assert_eq!(
18276 wrap_with_prefix(
18277 String::new(),
18278 "这是什么 \n 钢笔".to_string(),
18279 3,
18280 NonZeroU32::new(4).unwrap(),
18281 false,
18282 ),
18283 "这是什\n么 钢\n笔"
18284 );
18285}
18286
18287pub trait CollaborationHub {
18288 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18289 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18290 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18291}
18292
18293impl CollaborationHub for Entity<Project> {
18294 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18295 self.read(cx).collaborators()
18296 }
18297
18298 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18299 self.read(cx).user_store().read(cx).participant_indices()
18300 }
18301
18302 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18303 let this = self.read(cx);
18304 let user_ids = this.collaborators().values().map(|c| c.user_id);
18305 this.user_store().read_with(cx, |user_store, cx| {
18306 user_store.participant_names(user_ids, cx)
18307 })
18308 }
18309}
18310
18311pub trait SemanticsProvider {
18312 fn hover(
18313 &self,
18314 buffer: &Entity<Buffer>,
18315 position: text::Anchor,
18316 cx: &mut App,
18317 ) -> Option<Task<Vec<project::Hover>>>;
18318
18319 fn inlay_hints(
18320 &self,
18321 buffer_handle: Entity<Buffer>,
18322 range: Range<text::Anchor>,
18323 cx: &mut App,
18324 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18325
18326 fn resolve_inlay_hint(
18327 &self,
18328 hint: InlayHint,
18329 buffer_handle: Entity<Buffer>,
18330 server_id: LanguageServerId,
18331 cx: &mut App,
18332 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18333
18334 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18335
18336 fn document_highlights(
18337 &self,
18338 buffer: &Entity<Buffer>,
18339 position: text::Anchor,
18340 cx: &mut App,
18341 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18342
18343 fn definitions(
18344 &self,
18345 buffer: &Entity<Buffer>,
18346 position: text::Anchor,
18347 kind: GotoDefinitionKind,
18348 cx: &mut App,
18349 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18350
18351 fn range_for_rename(
18352 &self,
18353 buffer: &Entity<Buffer>,
18354 position: text::Anchor,
18355 cx: &mut App,
18356 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18357
18358 fn perform_rename(
18359 &self,
18360 buffer: &Entity<Buffer>,
18361 position: text::Anchor,
18362 new_name: String,
18363 cx: &mut App,
18364 ) -> Option<Task<Result<ProjectTransaction>>>;
18365}
18366
18367pub trait CompletionProvider {
18368 fn completions(
18369 &self,
18370 excerpt_id: ExcerptId,
18371 buffer: &Entity<Buffer>,
18372 buffer_position: text::Anchor,
18373 trigger: CompletionContext,
18374 window: &mut Window,
18375 cx: &mut Context<Editor>,
18376 ) -> Task<Result<Option<Vec<Completion>>>>;
18377
18378 fn resolve_completions(
18379 &self,
18380 buffer: Entity<Buffer>,
18381 completion_indices: Vec<usize>,
18382 completions: Rc<RefCell<Box<[Completion]>>>,
18383 cx: &mut Context<Editor>,
18384 ) -> Task<Result<bool>>;
18385
18386 fn apply_additional_edits_for_completion(
18387 &self,
18388 _buffer: Entity<Buffer>,
18389 _completions: Rc<RefCell<Box<[Completion]>>>,
18390 _completion_index: usize,
18391 _push_to_history: bool,
18392 _cx: &mut Context<Editor>,
18393 ) -> Task<Result<Option<language::Transaction>>> {
18394 Task::ready(Ok(None))
18395 }
18396
18397 fn is_completion_trigger(
18398 &self,
18399 buffer: &Entity<Buffer>,
18400 position: language::Anchor,
18401 text: &str,
18402 trigger_in_words: bool,
18403 cx: &mut Context<Editor>,
18404 ) -> bool;
18405
18406 fn sort_completions(&self) -> bool {
18407 true
18408 }
18409
18410 fn filter_completions(&self) -> bool {
18411 true
18412 }
18413}
18414
18415pub trait CodeActionProvider {
18416 fn id(&self) -> Arc<str>;
18417
18418 fn code_actions(
18419 &self,
18420 buffer: &Entity<Buffer>,
18421 range: Range<text::Anchor>,
18422 window: &mut Window,
18423 cx: &mut App,
18424 ) -> Task<Result<Vec<CodeAction>>>;
18425
18426 fn apply_code_action(
18427 &self,
18428 buffer_handle: Entity<Buffer>,
18429 action: CodeAction,
18430 excerpt_id: ExcerptId,
18431 push_to_history: bool,
18432 window: &mut Window,
18433 cx: &mut App,
18434 ) -> Task<Result<ProjectTransaction>>;
18435}
18436
18437impl CodeActionProvider for Entity<Project> {
18438 fn id(&self) -> Arc<str> {
18439 "project".into()
18440 }
18441
18442 fn code_actions(
18443 &self,
18444 buffer: &Entity<Buffer>,
18445 range: Range<text::Anchor>,
18446 _window: &mut Window,
18447 cx: &mut App,
18448 ) -> Task<Result<Vec<CodeAction>>> {
18449 self.update(cx, |project, cx| {
18450 let code_lens = project.code_lens(buffer, range.clone(), cx);
18451 let code_actions = project.code_actions(buffer, range, None, cx);
18452 cx.background_spawn(async move {
18453 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18454 Ok(code_lens
18455 .context("code lens fetch")?
18456 .into_iter()
18457 .chain(code_actions.context("code action fetch")?)
18458 .collect())
18459 })
18460 })
18461 }
18462
18463 fn apply_code_action(
18464 &self,
18465 buffer_handle: Entity<Buffer>,
18466 action: CodeAction,
18467 _excerpt_id: ExcerptId,
18468 push_to_history: bool,
18469 _window: &mut Window,
18470 cx: &mut App,
18471 ) -> Task<Result<ProjectTransaction>> {
18472 self.update(cx, |project, cx| {
18473 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18474 })
18475 }
18476}
18477
18478fn snippet_completions(
18479 project: &Project,
18480 buffer: &Entity<Buffer>,
18481 buffer_position: text::Anchor,
18482 cx: &mut App,
18483) -> Task<Result<Vec<Completion>>> {
18484 let language = buffer.read(cx).language_at(buffer_position);
18485 let language_name = language.as_ref().map(|language| language.lsp_id());
18486 let snippet_store = project.snippets().read(cx);
18487 let snippets = snippet_store.snippets_for(language_name, cx);
18488
18489 if snippets.is_empty() {
18490 return Task::ready(Ok(vec![]));
18491 }
18492 let snapshot = buffer.read(cx).text_snapshot();
18493 let chars: String = snapshot
18494 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18495 .collect();
18496
18497 let scope = language.map(|language| language.default_scope());
18498 let executor = cx.background_executor().clone();
18499
18500 cx.background_spawn(async move {
18501 let classifier = CharClassifier::new(scope).for_completion(true);
18502 let mut last_word = chars
18503 .chars()
18504 .take_while(|c| classifier.is_word(*c))
18505 .collect::<String>();
18506 last_word = last_word.chars().rev().collect();
18507
18508 if last_word.is_empty() {
18509 return Ok(vec![]);
18510 }
18511
18512 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18513 let to_lsp = |point: &text::Anchor| {
18514 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18515 point_to_lsp(end)
18516 };
18517 let lsp_end = to_lsp(&buffer_position);
18518
18519 let candidates = snippets
18520 .iter()
18521 .enumerate()
18522 .flat_map(|(ix, snippet)| {
18523 snippet
18524 .prefix
18525 .iter()
18526 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18527 })
18528 .collect::<Vec<StringMatchCandidate>>();
18529
18530 let mut matches = fuzzy::match_strings(
18531 &candidates,
18532 &last_word,
18533 last_word.chars().any(|c| c.is_uppercase()),
18534 100,
18535 &Default::default(),
18536 executor,
18537 )
18538 .await;
18539
18540 // Remove all candidates where the query's start does not match the start of any word in the candidate
18541 if let Some(query_start) = last_word.chars().next() {
18542 matches.retain(|string_match| {
18543 split_words(&string_match.string).any(|word| {
18544 // Check that the first codepoint of the word as lowercase matches the first
18545 // codepoint of the query as lowercase
18546 word.chars()
18547 .flat_map(|codepoint| codepoint.to_lowercase())
18548 .zip(query_start.to_lowercase())
18549 .all(|(word_cp, query_cp)| word_cp == query_cp)
18550 })
18551 });
18552 }
18553
18554 let matched_strings = matches
18555 .into_iter()
18556 .map(|m| m.string)
18557 .collect::<HashSet<_>>();
18558
18559 let result: Vec<Completion> = snippets
18560 .into_iter()
18561 .filter_map(|snippet| {
18562 let matching_prefix = snippet
18563 .prefix
18564 .iter()
18565 .find(|prefix| matched_strings.contains(*prefix))?;
18566 let start = as_offset - last_word.len();
18567 let start = snapshot.anchor_before(start);
18568 let range = start..buffer_position;
18569 let lsp_start = to_lsp(&start);
18570 let lsp_range = lsp::Range {
18571 start: lsp_start,
18572 end: lsp_end,
18573 };
18574 Some(Completion {
18575 old_range: range,
18576 new_text: snippet.body.clone(),
18577 source: CompletionSource::Lsp {
18578 server_id: LanguageServerId(usize::MAX),
18579 resolved: true,
18580 lsp_completion: Box::new(lsp::CompletionItem {
18581 label: snippet.prefix.first().unwrap().clone(),
18582 kind: Some(CompletionItemKind::SNIPPET),
18583 label_details: snippet.description.as_ref().map(|description| {
18584 lsp::CompletionItemLabelDetails {
18585 detail: Some(description.clone()),
18586 description: None,
18587 }
18588 }),
18589 insert_text_format: Some(InsertTextFormat::SNIPPET),
18590 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18591 lsp::InsertReplaceEdit {
18592 new_text: snippet.body.clone(),
18593 insert: lsp_range,
18594 replace: lsp_range,
18595 },
18596 )),
18597 filter_text: Some(snippet.body.clone()),
18598 sort_text: Some(char::MAX.to_string()),
18599 ..lsp::CompletionItem::default()
18600 }),
18601 lsp_defaults: None,
18602 },
18603 label: CodeLabel {
18604 text: matching_prefix.clone(),
18605 runs: Vec::new(),
18606 filter_range: 0..matching_prefix.len(),
18607 },
18608 icon_path: None,
18609 documentation: snippet
18610 .description
18611 .clone()
18612 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18613 confirm: None,
18614 })
18615 })
18616 .collect();
18617
18618 Ok(result)
18619 })
18620}
18621
18622impl CompletionProvider for Entity<Project> {
18623 fn completions(
18624 &self,
18625 _excerpt_id: ExcerptId,
18626 buffer: &Entity<Buffer>,
18627 buffer_position: text::Anchor,
18628 options: CompletionContext,
18629 _window: &mut Window,
18630 cx: &mut Context<Editor>,
18631 ) -> Task<Result<Option<Vec<Completion>>>> {
18632 self.update(cx, |project, cx| {
18633 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18634 let project_completions = project.completions(buffer, buffer_position, options, cx);
18635 cx.background_spawn(async move {
18636 let snippets_completions = snippets.await?;
18637 match project_completions.await? {
18638 Some(mut completions) => {
18639 completions.extend(snippets_completions);
18640 Ok(Some(completions))
18641 }
18642 None => {
18643 if snippets_completions.is_empty() {
18644 Ok(None)
18645 } else {
18646 Ok(Some(snippets_completions))
18647 }
18648 }
18649 }
18650 })
18651 })
18652 }
18653
18654 fn resolve_completions(
18655 &self,
18656 buffer: Entity<Buffer>,
18657 completion_indices: Vec<usize>,
18658 completions: Rc<RefCell<Box<[Completion]>>>,
18659 cx: &mut Context<Editor>,
18660 ) -> Task<Result<bool>> {
18661 self.update(cx, |project, cx| {
18662 project.lsp_store().update(cx, |lsp_store, cx| {
18663 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18664 })
18665 })
18666 }
18667
18668 fn apply_additional_edits_for_completion(
18669 &self,
18670 buffer: Entity<Buffer>,
18671 completions: Rc<RefCell<Box<[Completion]>>>,
18672 completion_index: usize,
18673 push_to_history: bool,
18674 cx: &mut Context<Editor>,
18675 ) -> Task<Result<Option<language::Transaction>>> {
18676 self.update(cx, |project, cx| {
18677 project.lsp_store().update(cx, |lsp_store, cx| {
18678 lsp_store.apply_additional_edits_for_completion(
18679 buffer,
18680 completions,
18681 completion_index,
18682 push_to_history,
18683 cx,
18684 )
18685 })
18686 })
18687 }
18688
18689 fn is_completion_trigger(
18690 &self,
18691 buffer: &Entity<Buffer>,
18692 position: language::Anchor,
18693 text: &str,
18694 trigger_in_words: bool,
18695 cx: &mut Context<Editor>,
18696 ) -> bool {
18697 let mut chars = text.chars();
18698 let char = if let Some(char) = chars.next() {
18699 char
18700 } else {
18701 return false;
18702 };
18703 if chars.next().is_some() {
18704 return false;
18705 }
18706
18707 let buffer = buffer.read(cx);
18708 let snapshot = buffer.snapshot();
18709 if !snapshot.settings_at(position, cx).show_completions_on_input {
18710 return false;
18711 }
18712 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18713 if trigger_in_words && classifier.is_word(char) {
18714 return true;
18715 }
18716
18717 buffer.completion_triggers().contains(text)
18718 }
18719}
18720
18721impl SemanticsProvider for Entity<Project> {
18722 fn hover(
18723 &self,
18724 buffer: &Entity<Buffer>,
18725 position: text::Anchor,
18726 cx: &mut App,
18727 ) -> Option<Task<Vec<project::Hover>>> {
18728 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18729 }
18730
18731 fn document_highlights(
18732 &self,
18733 buffer: &Entity<Buffer>,
18734 position: text::Anchor,
18735 cx: &mut App,
18736 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18737 Some(self.update(cx, |project, cx| {
18738 project.document_highlights(buffer, position, cx)
18739 }))
18740 }
18741
18742 fn definitions(
18743 &self,
18744 buffer: &Entity<Buffer>,
18745 position: text::Anchor,
18746 kind: GotoDefinitionKind,
18747 cx: &mut App,
18748 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18749 Some(self.update(cx, |project, cx| match kind {
18750 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18751 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18752 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18753 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18754 }))
18755 }
18756
18757 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18758 // TODO: make this work for remote projects
18759 self.update(cx, |this, cx| {
18760 buffer.update(cx, |buffer, cx| {
18761 this.any_language_server_supports_inlay_hints(buffer, cx)
18762 })
18763 })
18764 }
18765
18766 fn inlay_hints(
18767 &self,
18768 buffer_handle: Entity<Buffer>,
18769 range: Range<text::Anchor>,
18770 cx: &mut App,
18771 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18772 Some(self.update(cx, |project, cx| {
18773 project.inlay_hints(buffer_handle, range, cx)
18774 }))
18775 }
18776
18777 fn resolve_inlay_hint(
18778 &self,
18779 hint: InlayHint,
18780 buffer_handle: Entity<Buffer>,
18781 server_id: LanguageServerId,
18782 cx: &mut App,
18783 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18784 Some(self.update(cx, |project, cx| {
18785 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18786 }))
18787 }
18788
18789 fn range_for_rename(
18790 &self,
18791 buffer: &Entity<Buffer>,
18792 position: text::Anchor,
18793 cx: &mut App,
18794 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18795 Some(self.update(cx, |project, cx| {
18796 let buffer = buffer.clone();
18797 let task = project.prepare_rename(buffer.clone(), position, cx);
18798 cx.spawn(async move |_, cx| {
18799 Ok(match task.await? {
18800 PrepareRenameResponse::Success(range) => Some(range),
18801 PrepareRenameResponse::InvalidPosition => None,
18802 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18803 // Fallback on using TreeSitter info to determine identifier range
18804 buffer.update(cx, |buffer, _| {
18805 let snapshot = buffer.snapshot();
18806 let (range, kind) = snapshot.surrounding_word(position);
18807 if kind != Some(CharKind::Word) {
18808 return None;
18809 }
18810 Some(
18811 snapshot.anchor_before(range.start)
18812 ..snapshot.anchor_after(range.end),
18813 )
18814 })?
18815 }
18816 })
18817 })
18818 }))
18819 }
18820
18821 fn perform_rename(
18822 &self,
18823 buffer: &Entity<Buffer>,
18824 position: text::Anchor,
18825 new_name: String,
18826 cx: &mut App,
18827 ) -> Option<Task<Result<ProjectTransaction>>> {
18828 Some(self.update(cx, |project, cx| {
18829 project.perform_rename(buffer.clone(), position, new_name, cx)
18830 }))
18831 }
18832}
18833
18834fn inlay_hint_settings(
18835 location: Anchor,
18836 snapshot: &MultiBufferSnapshot,
18837 cx: &mut Context<Editor>,
18838) -> InlayHintSettings {
18839 let file = snapshot.file_at(location);
18840 let language = snapshot.language_at(location).map(|l| l.name());
18841 language_settings(language, file, cx).inlay_hints
18842}
18843
18844fn consume_contiguous_rows(
18845 contiguous_row_selections: &mut Vec<Selection<Point>>,
18846 selection: &Selection<Point>,
18847 display_map: &DisplaySnapshot,
18848 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18849) -> (MultiBufferRow, MultiBufferRow) {
18850 contiguous_row_selections.push(selection.clone());
18851 let start_row = MultiBufferRow(selection.start.row);
18852 let mut end_row = ending_row(selection, display_map);
18853
18854 while let Some(next_selection) = selections.peek() {
18855 if next_selection.start.row <= end_row.0 {
18856 end_row = ending_row(next_selection, display_map);
18857 contiguous_row_selections.push(selections.next().unwrap().clone());
18858 } else {
18859 break;
18860 }
18861 }
18862 (start_row, end_row)
18863}
18864
18865fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18866 if next_selection.end.column > 0 || next_selection.is_empty() {
18867 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18868 } else {
18869 MultiBufferRow(next_selection.end.row)
18870 }
18871}
18872
18873impl EditorSnapshot {
18874 pub fn remote_selections_in_range<'a>(
18875 &'a self,
18876 range: &'a Range<Anchor>,
18877 collaboration_hub: &dyn CollaborationHub,
18878 cx: &'a App,
18879 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18880 let participant_names = collaboration_hub.user_names(cx);
18881 let participant_indices = collaboration_hub.user_participant_indices(cx);
18882 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18883 let collaborators_by_replica_id = collaborators_by_peer_id
18884 .iter()
18885 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18886 .collect::<HashMap<_, _>>();
18887 self.buffer_snapshot
18888 .selections_in_range(range, false)
18889 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18890 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18891 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18892 let user_name = participant_names.get(&collaborator.user_id).cloned();
18893 Some(RemoteSelection {
18894 replica_id,
18895 selection,
18896 cursor_shape,
18897 line_mode,
18898 participant_index,
18899 peer_id: collaborator.peer_id,
18900 user_name,
18901 })
18902 })
18903 }
18904
18905 pub fn hunks_for_ranges(
18906 &self,
18907 ranges: impl IntoIterator<Item = Range<Point>>,
18908 ) -> Vec<MultiBufferDiffHunk> {
18909 let mut hunks = Vec::new();
18910 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18911 HashMap::default();
18912 for query_range in ranges {
18913 let query_rows =
18914 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18915 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18916 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18917 ) {
18918 // Include deleted hunks that are adjacent to the query range, because
18919 // otherwise they would be missed.
18920 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18921 if hunk.status().is_deleted() {
18922 intersects_range |= hunk.row_range.start == query_rows.end;
18923 intersects_range |= hunk.row_range.end == query_rows.start;
18924 }
18925 if intersects_range {
18926 if !processed_buffer_rows
18927 .entry(hunk.buffer_id)
18928 .or_default()
18929 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18930 {
18931 continue;
18932 }
18933 hunks.push(hunk);
18934 }
18935 }
18936 }
18937
18938 hunks
18939 }
18940
18941 fn display_diff_hunks_for_rows<'a>(
18942 &'a self,
18943 display_rows: Range<DisplayRow>,
18944 folded_buffers: &'a HashSet<BufferId>,
18945 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18946 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18947 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18948
18949 self.buffer_snapshot
18950 .diff_hunks_in_range(buffer_start..buffer_end)
18951 .filter_map(|hunk| {
18952 if folded_buffers.contains(&hunk.buffer_id) {
18953 return None;
18954 }
18955
18956 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18957 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18958
18959 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18960 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18961
18962 let display_hunk = if hunk_display_start.column() != 0 {
18963 DisplayDiffHunk::Folded {
18964 display_row: hunk_display_start.row(),
18965 }
18966 } else {
18967 let mut end_row = hunk_display_end.row();
18968 if hunk_display_end.column() > 0 {
18969 end_row.0 += 1;
18970 }
18971 let is_created_file = hunk.is_created_file();
18972 DisplayDiffHunk::Unfolded {
18973 status: hunk.status(),
18974 diff_base_byte_range: hunk.diff_base_byte_range,
18975 display_row_range: hunk_display_start.row()..end_row,
18976 multi_buffer_range: Anchor::range_in_buffer(
18977 hunk.excerpt_id,
18978 hunk.buffer_id,
18979 hunk.buffer_range,
18980 ),
18981 is_created_file,
18982 }
18983 };
18984
18985 Some(display_hunk)
18986 })
18987 }
18988
18989 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18990 self.display_snapshot.buffer_snapshot.language_at(position)
18991 }
18992
18993 pub fn is_focused(&self) -> bool {
18994 self.is_focused
18995 }
18996
18997 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18998 self.placeholder_text.as_ref()
18999 }
19000
19001 pub fn scroll_position(&self) -> gpui::Point<f32> {
19002 self.scroll_anchor.scroll_position(&self.display_snapshot)
19003 }
19004
19005 fn gutter_dimensions(
19006 &self,
19007 font_id: FontId,
19008 font_size: Pixels,
19009 max_line_number_width: Pixels,
19010 cx: &App,
19011 ) -> Option<GutterDimensions> {
19012 if !self.show_gutter {
19013 return None;
19014 }
19015
19016 let descent = cx.text_system().descent(font_id, font_size);
19017 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19018 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19019
19020 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19021 matches!(
19022 ProjectSettings::get_global(cx).git.git_gutter,
19023 Some(GitGutterSetting::TrackedFiles)
19024 )
19025 });
19026 let gutter_settings = EditorSettings::get_global(cx).gutter;
19027 let show_line_numbers = self
19028 .show_line_numbers
19029 .unwrap_or(gutter_settings.line_numbers);
19030 let line_gutter_width = if show_line_numbers {
19031 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19032 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19033 max_line_number_width.max(min_width_for_number_on_gutter)
19034 } else {
19035 0.0.into()
19036 };
19037
19038 let show_code_actions = self
19039 .show_code_actions
19040 .unwrap_or(gutter_settings.code_actions);
19041
19042 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19043 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19044
19045 let git_blame_entries_width =
19046 self.git_blame_gutter_max_author_length
19047 .map(|max_author_length| {
19048 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19049 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19050
19051 /// The number of characters to dedicate to gaps and margins.
19052 const SPACING_WIDTH: usize = 4;
19053
19054 let max_char_count = max_author_length.min(renderer.max_author_length())
19055 + ::git::SHORT_SHA_LENGTH
19056 + MAX_RELATIVE_TIMESTAMP.len()
19057 + SPACING_WIDTH;
19058
19059 em_advance * max_char_count
19060 });
19061
19062 let is_singleton = self.buffer_snapshot.is_singleton();
19063
19064 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19065 left_padding += if !is_singleton {
19066 em_width * 4.0
19067 } else if show_code_actions || show_runnables || show_breakpoints {
19068 em_width * 3.0
19069 } else if show_git_gutter && show_line_numbers {
19070 em_width * 2.0
19071 } else if show_git_gutter || show_line_numbers {
19072 em_width
19073 } else {
19074 px(0.)
19075 };
19076
19077 let shows_folds = is_singleton && gutter_settings.folds;
19078
19079 let right_padding = if shows_folds && show_line_numbers {
19080 em_width * 4.0
19081 } else if shows_folds || (!is_singleton && show_line_numbers) {
19082 em_width * 3.0
19083 } else if show_line_numbers {
19084 em_width
19085 } else {
19086 px(0.)
19087 };
19088
19089 Some(GutterDimensions {
19090 left_padding,
19091 right_padding,
19092 width: line_gutter_width + left_padding + right_padding,
19093 margin: -descent,
19094 git_blame_entries_width,
19095 })
19096 }
19097
19098 pub fn render_crease_toggle(
19099 &self,
19100 buffer_row: MultiBufferRow,
19101 row_contains_cursor: bool,
19102 editor: Entity<Editor>,
19103 window: &mut Window,
19104 cx: &mut App,
19105 ) -> Option<AnyElement> {
19106 let folded = self.is_line_folded(buffer_row);
19107 let mut is_foldable = false;
19108
19109 if let Some(crease) = self
19110 .crease_snapshot
19111 .query_row(buffer_row, &self.buffer_snapshot)
19112 {
19113 is_foldable = true;
19114 match crease {
19115 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19116 if let Some(render_toggle) = render_toggle {
19117 let toggle_callback =
19118 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19119 if folded {
19120 editor.update(cx, |editor, cx| {
19121 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19122 });
19123 } else {
19124 editor.update(cx, |editor, cx| {
19125 editor.unfold_at(
19126 &crate::UnfoldAt { buffer_row },
19127 window,
19128 cx,
19129 )
19130 });
19131 }
19132 });
19133 return Some((render_toggle)(
19134 buffer_row,
19135 folded,
19136 toggle_callback,
19137 window,
19138 cx,
19139 ));
19140 }
19141 }
19142 }
19143 }
19144
19145 is_foldable |= self.starts_indent(buffer_row);
19146
19147 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19148 Some(
19149 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19150 .toggle_state(folded)
19151 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19152 if folded {
19153 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19154 } else {
19155 this.fold_at(&FoldAt { buffer_row }, window, cx);
19156 }
19157 }))
19158 .into_any_element(),
19159 )
19160 } else {
19161 None
19162 }
19163 }
19164
19165 pub fn render_crease_trailer(
19166 &self,
19167 buffer_row: MultiBufferRow,
19168 window: &mut Window,
19169 cx: &mut App,
19170 ) -> Option<AnyElement> {
19171 let folded = self.is_line_folded(buffer_row);
19172 if let Crease::Inline { render_trailer, .. } = self
19173 .crease_snapshot
19174 .query_row(buffer_row, &self.buffer_snapshot)?
19175 {
19176 let render_trailer = render_trailer.as_ref()?;
19177 Some(render_trailer(buffer_row, folded, window, cx))
19178 } else {
19179 None
19180 }
19181 }
19182}
19183
19184impl Deref for EditorSnapshot {
19185 type Target = DisplaySnapshot;
19186
19187 fn deref(&self) -> &Self::Target {
19188 &self.display_snapshot
19189 }
19190}
19191
19192#[derive(Clone, Debug, PartialEq, Eq)]
19193pub enum EditorEvent {
19194 InputIgnored {
19195 text: Arc<str>,
19196 },
19197 InputHandled {
19198 utf16_range_to_replace: Option<Range<isize>>,
19199 text: Arc<str>,
19200 },
19201 ExcerptsAdded {
19202 buffer: Entity<Buffer>,
19203 predecessor: ExcerptId,
19204 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19205 },
19206 ExcerptsRemoved {
19207 ids: Vec<ExcerptId>,
19208 },
19209 BufferFoldToggled {
19210 ids: Vec<ExcerptId>,
19211 folded: bool,
19212 },
19213 ExcerptsEdited {
19214 ids: Vec<ExcerptId>,
19215 },
19216 ExcerptsExpanded {
19217 ids: Vec<ExcerptId>,
19218 },
19219 BufferEdited,
19220 Edited {
19221 transaction_id: clock::Lamport,
19222 },
19223 Reparsed(BufferId),
19224 Focused,
19225 FocusedIn,
19226 Blurred,
19227 DirtyChanged,
19228 Saved,
19229 TitleChanged,
19230 DiffBaseChanged,
19231 SelectionsChanged {
19232 local: bool,
19233 },
19234 ScrollPositionChanged {
19235 local: bool,
19236 autoscroll: bool,
19237 },
19238 Closed,
19239 TransactionUndone {
19240 transaction_id: clock::Lamport,
19241 },
19242 TransactionBegun {
19243 transaction_id: clock::Lamport,
19244 },
19245 Reloaded,
19246 CursorShapeChanged,
19247 PushedToNavHistory {
19248 anchor: Anchor,
19249 is_deactivate: bool,
19250 },
19251}
19252
19253impl EventEmitter<EditorEvent> for Editor {}
19254
19255impl Focusable for Editor {
19256 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19257 self.focus_handle.clone()
19258 }
19259}
19260
19261impl Render for Editor {
19262 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19263 let settings = ThemeSettings::get_global(cx);
19264
19265 let mut text_style = match self.mode {
19266 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19267 color: cx.theme().colors().editor_foreground,
19268 font_family: settings.ui_font.family.clone(),
19269 font_features: settings.ui_font.features.clone(),
19270 font_fallbacks: settings.ui_font.fallbacks.clone(),
19271 font_size: rems(0.875).into(),
19272 font_weight: settings.ui_font.weight,
19273 line_height: relative(settings.buffer_line_height.value()),
19274 ..Default::default()
19275 },
19276 EditorMode::Full => TextStyle {
19277 color: cx.theme().colors().editor_foreground,
19278 font_family: settings.buffer_font.family.clone(),
19279 font_features: settings.buffer_font.features.clone(),
19280 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19281 font_size: settings.buffer_font_size(cx).into(),
19282 font_weight: settings.buffer_font.weight,
19283 line_height: relative(settings.buffer_line_height.value()),
19284 ..Default::default()
19285 },
19286 };
19287 if let Some(text_style_refinement) = &self.text_style_refinement {
19288 text_style.refine(text_style_refinement)
19289 }
19290
19291 let background = match self.mode {
19292 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19293 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19294 EditorMode::Full => cx.theme().colors().editor_background,
19295 };
19296
19297 EditorElement::new(
19298 &cx.entity(),
19299 EditorStyle {
19300 background,
19301 local_player: cx.theme().players().local(),
19302 text: text_style,
19303 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19304 syntax: cx.theme().syntax().clone(),
19305 status: cx.theme().status().clone(),
19306 inlay_hints_style: make_inlay_hints_style(cx),
19307 inline_completion_styles: make_suggestion_styles(cx),
19308 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19309 },
19310 )
19311 }
19312}
19313
19314impl EntityInputHandler for Editor {
19315 fn text_for_range(
19316 &mut self,
19317 range_utf16: Range<usize>,
19318 adjusted_range: &mut Option<Range<usize>>,
19319 _: &mut Window,
19320 cx: &mut Context<Self>,
19321 ) -> Option<String> {
19322 let snapshot = self.buffer.read(cx).read(cx);
19323 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19324 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19325 if (start.0..end.0) != range_utf16 {
19326 adjusted_range.replace(start.0..end.0);
19327 }
19328 Some(snapshot.text_for_range(start..end).collect())
19329 }
19330
19331 fn selected_text_range(
19332 &mut self,
19333 ignore_disabled_input: bool,
19334 _: &mut Window,
19335 cx: &mut Context<Self>,
19336 ) -> Option<UTF16Selection> {
19337 // Prevent the IME menu from appearing when holding down an alphabetic key
19338 // while input is disabled.
19339 if !ignore_disabled_input && !self.input_enabled {
19340 return None;
19341 }
19342
19343 let selection = self.selections.newest::<OffsetUtf16>(cx);
19344 let range = selection.range();
19345
19346 Some(UTF16Selection {
19347 range: range.start.0..range.end.0,
19348 reversed: selection.reversed,
19349 })
19350 }
19351
19352 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19353 let snapshot = self.buffer.read(cx).read(cx);
19354 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19355 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19356 }
19357
19358 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19359 self.clear_highlights::<InputComposition>(cx);
19360 self.ime_transaction.take();
19361 }
19362
19363 fn replace_text_in_range(
19364 &mut self,
19365 range_utf16: Option<Range<usize>>,
19366 text: &str,
19367 window: &mut Window,
19368 cx: &mut Context<Self>,
19369 ) {
19370 if !self.input_enabled {
19371 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19372 return;
19373 }
19374
19375 self.transact(window, cx, |this, window, cx| {
19376 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19377 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19378 Some(this.selection_replacement_ranges(range_utf16, cx))
19379 } else {
19380 this.marked_text_ranges(cx)
19381 };
19382
19383 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19384 let newest_selection_id = this.selections.newest_anchor().id;
19385 this.selections
19386 .all::<OffsetUtf16>(cx)
19387 .iter()
19388 .zip(ranges_to_replace.iter())
19389 .find_map(|(selection, range)| {
19390 if selection.id == newest_selection_id {
19391 Some(
19392 (range.start.0 as isize - selection.head().0 as isize)
19393 ..(range.end.0 as isize - selection.head().0 as isize),
19394 )
19395 } else {
19396 None
19397 }
19398 })
19399 });
19400
19401 cx.emit(EditorEvent::InputHandled {
19402 utf16_range_to_replace: range_to_replace,
19403 text: text.into(),
19404 });
19405
19406 if let Some(new_selected_ranges) = new_selected_ranges {
19407 this.change_selections(None, window, cx, |selections| {
19408 selections.select_ranges(new_selected_ranges)
19409 });
19410 this.backspace(&Default::default(), window, cx);
19411 }
19412
19413 this.handle_input(text, window, cx);
19414 });
19415
19416 if let Some(transaction) = self.ime_transaction {
19417 self.buffer.update(cx, |buffer, cx| {
19418 buffer.group_until_transaction(transaction, cx);
19419 });
19420 }
19421
19422 self.unmark_text(window, cx);
19423 }
19424
19425 fn replace_and_mark_text_in_range(
19426 &mut self,
19427 range_utf16: Option<Range<usize>>,
19428 text: &str,
19429 new_selected_range_utf16: Option<Range<usize>>,
19430 window: &mut Window,
19431 cx: &mut Context<Self>,
19432 ) {
19433 if !self.input_enabled {
19434 return;
19435 }
19436
19437 let transaction = self.transact(window, cx, |this, window, cx| {
19438 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19439 let snapshot = this.buffer.read(cx).read(cx);
19440 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19441 for marked_range in &mut marked_ranges {
19442 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19443 marked_range.start.0 += relative_range_utf16.start;
19444 marked_range.start =
19445 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19446 marked_range.end =
19447 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19448 }
19449 }
19450 Some(marked_ranges)
19451 } else if let Some(range_utf16) = range_utf16 {
19452 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19453 Some(this.selection_replacement_ranges(range_utf16, cx))
19454 } else {
19455 None
19456 };
19457
19458 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19459 let newest_selection_id = this.selections.newest_anchor().id;
19460 this.selections
19461 .all::<OffsetUtf16>(cx)
19462 .iter()
19463 .zip(ranges_to_replace.iter())
19464 .find_map(|(selection, range)| {
19465 if selection.id == newest_selection_id {
19466 Some(
19467 (range.start.0 as isize - selection.head().0 as isize)
19468 ..(range.end.0 as isize - selection.head().0 as isize),
19469 )
19470 } else {
19471 None
19472 }
19473 })
19474 });
19475
19476 cx.emit(EditorEvent::InputHandled {
19477 utf16_range_to_replace: range_to_replace,
19478 text: text.into(),
19479 });
19480
19481 if let Some(ranges) = ranges_to_replace {
19482 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19483 }
19484
19485 let marked_ranges = {
19486 let snapshot = this.buffer.read(cx).read(cx);
19487 this.selections
19488 .disjoint_anchors()
19489 .iter()
19490 .map(|selection| {
19491 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19492 })
19493 .collect::<Vec<_>>()
19494 };
19495
19496 if text.is_empty() {
19497 this.unmark_text(window, cx);
19498 } else {
19499 this.highlight_text::<InputComposition>(
19500 marked_ranges.clone(),
19501 HighlightStyle {
19502 underline: Some(UnderlineStyle {
19503 thickness: px(1.),
19504 color: None,
19505 wavy: false,
19506 }),
19507 ..Default::default()
19508 },
19509 cx,
19510 );
19511 }
19512
19513 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19514 let use_autoclose = this.use_autoclose;
19515 let use_auto_surround = this.use_auto_surround;
19516 this.set_use_autoclose(false);
19517 this.set_use_auto_surround(false);
19518 this.handle_input(text, window, cx);
19519 this.set_use_autoclose(use_autoclose);
19520 this.set_use_auto_surround(use_auto_surround);
19521
19522 if let Some(new_selected_range) = new_selected_range_utf16 {
19523 let snapshot = this.buffer.read(cx).read(cx);
19524 let new_selected_ranges = marked_ranges
19525 .into_iter()
19526 .map(|marked_range| {
19527 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19528 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19529 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19530 snapshot.clip_offset_utf16(new_start, Bias::Left)
19531 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19532 })
19533 .collect::<Vec<_>>();
19534
19535 drop(snapshot);
19536 this.change_selections(None, window, cx, |selections| {
19537 selections.select_ranges(new_selected_ranges)
19538 });
19539 }
19540 });
19541
19542 self.ime_transaction = self.ime_transaction.or(transaction);
19543 if let Some(transaction) = self.ime_transaction {
19544 self.buffer.update(cx, |buffer, cx| {
19545 buffer.group_until_transaction(transaction, cx);
19546 });
19547 }
19548
19549 if self.text_highlights::<InputComposition>(cx).is_none() {
19550 self.ime_transaction.take();
19551 }
19552 }
19553
19554 fn bounds_for_range(
19555 &mut self,
19556 range_utf16: Range<usize>,
19557 element_bounds: gpui::Bounds<Pixels>,
19558 window: &mut Window,
19559 cx: &mut Context<Self>,
19560 ) -> Option<gpui::Bounds<Pixels>> {
19561 let text_layout_details = self.text_layout_details(window);
19562 let gpui::Size {
19563 width: em_width,
19564 height: line_height,
19565 } = self.character_size(window);
19566
19567 let snapshot = self.snapshot(window, cx);
19568 let scroll_position = snapshot.scroll_position();
19569 let scroll_left = scroll_position.x * em_width;
19570
19571 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19572 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19573 + self.gutter_dimensions.width
19574 + self.gutter_dimensions.margin;
19575 let y = line_height * (start.row().as_f32() - scroll_position.y);
19576
19577 Some(Bounds {
19578 origin: element_bounds.origin + point(x, y),
19579 size: size(em_width, line_height),
19580 })
19581 }
19582
19583 fn character_index_for_point(
19584 &mut self,
19585 point: gpui::Point<Pixels>,
19586 _window: &mut Window,
19587 _cx: &mut Context<Self>,
19588 ) -> Option<usize> {
19589 let position_map = self.last_position_map.as_ref()?;
19590 if !position_map.text_hitbox.contains(&point) {
19591 return None;
19592 }
19593 let display_point = position_map.point_for_position(point).previous_valid;
19594 let anchor = position_map
19595 .snapshot
19596 .display_point_to_anchor(display_point, Bias::Left);
19597 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19598 Some(utf16_offset.0)
19599 }
19600}
19601
19602trait SelectionExt {
19603 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19604 fn spanned_rows(
19605 &self,
19606 include_end_if_at_line_start: bool,
19607 map: &DisplaySnapshot,
19608 ) -> Range<MultiBufferRow>;
19609}
19610
19611impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19612 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19613 let start = self
19614 .start
19615 .to_point(&map.buffer_snapshot)
19616 .to_display_point(map);
19617 let end = self
19618 .end
19619 .to_point(&map.buffer_snapshot)
19620 .to_display_point(map);
19621 if self.reversed {
19622 end..start
19623 } else {
19624 start..end
19625 }
19626 }
19627
19628 fn spanned_rows(
19629 &self,
19630 include_end_if_at_line_start: bool,
19631 map: &DisplaySnapshot,
19632 ) -> Range<MultiBufferRow> {
19633 let start = self.start.to_point(&map.buffer_snapshot);
19634 let mut end = self.end.to_point(&map.buffer_snapshot);
19635 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19636 end.row -= 1;
19637 }
19638
19639 let buffer_start = map.prev_line_boundary(start).0;
19640 let buffer_end = map.next_line_boundary(end).0;
19641 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19642 }
19643}
19644
19645impl<T: InvalidationRegion> InvalidationStack<T> {
19646 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19647 where
19648 S: Clone + ToOffset,
19649 {
19650 while let Some(region) = self.last() {
19651 let all_selections_inside_invalidation_ranges =
19652 if selections.len() == region.ranges().len() {
19653 selections
19654 .iter()
19655 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19656 .all(|(selection, invalidation_range)| {
19657 let head = selection.head().to_offset(buffer);
19658 invalidation_range.start <= head && invalidation_range.end >= head
19659 })
19660 } else {
19661 false
19662 };
19663
19664 if all_selections_inside_invalidation_ranges {
19665 break;
19666 } else {
19667 self.pop();
19668 }
19669 }
19670 }
19671}
19672
19673impl<T> Default for InvalidationStack<T> {
19674 fn default() -> Self {
19675 Self(Default::default())
19676 }
19677}
19678
19679impl<T> Deref for InvalidationStack<T> {
19680 type Target = Vec<T>;
19681
19682 fn deref(&self) -> &Self::Target {
19683 &self.0
19684 }
19685}
19686
19687impl<T> DerefMut for InvalidationStack<T> {
19688 fn deref_mut(&mut self) -> &mut Self::Target {
19689 &mut self.0
19690 }
19691}
19692
19693impl InvalidationRegion for SnippetState {
19694 fn ranges(&self) -> &[Range<Anchor>] {
19695 &self.ranges[self.active_index]
19696 }
19697}
19698
19699pub fn diagnostic_block_renderer(
19700 diagnostic: Diagnostic,
19701 max_message_rows: Option<u8>,
19702 allow_closing: bool,
19703) -> RenderBlock {
19704 let (text_without_backticks, code_ranges) =
19705 highlight_diagnostic_message(&diagnostic, max_message_rows);
19706
19707 Arc::new(move |cx: &mut BlockContext| {
19708 let group_id: SharedString = cx.block_id.to_string().into();
19709
19710 let mut text_style = cx.window.text_style().clone();
19711 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19712 let theme_settings = ThemeSettings::get_global(cx);
19713 text_style.font_family = theme_settings.buffer_font.family.clone();
19714 text_style.font_style = theme_settings.buffer_font.style;
19715 text_style.font_features = theme_settings.buffer_font.features.clone();
19716 text_style.font_weight = theme_settings.buffer_font.weight;
19717
19718 let multi_line_diagnostic = diagnostic.message.contains('\n');
19719
19720 let buttons = |diagnostic: &Diagnostic| {
19721 if multi_line_diagnostic {
19722 v_flex()
19723 } else {
19724 h_flex()
19725 }
19726 .when(allow_closing, |div| {
19727 div.children(diagnostic.is_primary.then(|| {
19728 IconButton::new("close-block", IconName::XCircle)
19729 .icon_color(Color::Muted)
19730 .size(ButtonSize::Compact)
19731 .style(ButtonStyle::Transparent)
19732 .visible_on_hover(group_id.clone())
19733 .on_click(move |_click, window, cx| {
19734 window.dispatch_action(Box::new(Cancel), cx)
19735 })
19736 .tooltip(|window, cx| {
19737 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19738 })
19739 }))
19740 })
19741 .child(
19742 IconButton::new("copy-block", IconName::Copy)
19743 .icon_color(Color::Muted)
19744 .size(ButtonSize::Compact)
19745 .style(ButtonStyle::Transparent)
19746 .visible_on_hover(group_id.clone())
19747 .on_click({
19748 let message = diagnostic.message.clone();
19749 move |_click, _, cx| {
19750 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19751 }
19752 })
19753 .tooltip(Tooltip::text("Copy diagnostic message")),
19754 )
19755 };
19756
19757 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19758 AvailableSpace::min_size(),
19759 cx.window,
19760 cx.app,
19761 );
19762
19763 h_flex()
19764 .id(cx.block_id)
19765 .group(group_id.clone())
19766 .relative()
19767 .size_full()
19768 .block_mouse_down()
19769 .pl(cx.gutter_dimensions.width)
19770 .w(cx.max_width - cx.gutter_dimensions.full_width())
19771 .child(
19772 div()
19773 .flex()
19774 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19775 .flex_shrink(),
19776 )
19777 .child(buttons(&diagnostic))
19778 .child(div().flex().flex_shrink_0().child(
19779 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19780 &text_style,
19781 code_ranges.iter().map(|range| {
19782 (
19783 range.clone(),
19784 HighlightStyle {
19785 font_weight: Some(FontWeight::BOLD),
19786 ..Default::default()
19787 },
19788 )
19789 }),
19790 ),
19791 ))
19792 .into_any_element()
19793 })
19794}
19795
19796fn inline_completion_edit_text(
19797 current_snapshot: &BufferSnapshot,
19798 edits: &[(Range<Anchor>, String)],
19799 edit_preview: &EditPreview,
19800 include_deletions: bool,
19801 cx: &App,
19802) -> HighlightedText {
19803 let edits = edits
19804 .iter()
19805 .map(|(anchor, text)| {
19806 (
19807 anchor.start.text_anchor..anchor.end.text_anchor,
19808 text.clone(),
19809 )
19810 })
19811 .collect::<Vec<_>>();
19812
19813 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19814}
19815
19816pub fn highlight_diagnostic_message(
19817 diagnostic: &Diagnostic,
19818 mut max_message_rows: Option<u8>,
19819) -> (SharedString, Vec<Range<usize>>) {
19820 let mut text_without_backticks = String::new();
19821 let mut code_ranges = Vec::new();
19822
19823 if let Some(source) = &diagnostic.source {
19824 text_without_backticks.push_str(source);
19825 code_ranges.push(0..source.len());
19826 text_without_backticks.push_str(": ");
19827 }
19828
19829 let mut prev_offset = 0;
19830 let mut in_code_block = false;
19831 let has_row_limit = max_message_rows.is_some();
19832 let mut newline_indices = diagnostic
19833 .message
19834 .match_indices('\n')
19835 .filter(|_| has_row_limit)
19836 .map(|(ix, _)| ix)
19837 .fuse()
19838 .peekable();
19839
19840 for (quote_ix, _) in diagnostic
19841 .message
19842 .match_indices('`')
19843 .chain([(diagnostic.message.len(), "")])
19844 {
19845 let mut first_newline_ix = None;
19846 let mut last_newline_ix = None;
19847 while let Some(newline_ix) = newline_indices.peek() {
19848 if *newline_ix < quote_ix {
19849 if first_newline_ix.is_none() {
19850 first_newline_ix = Some(*newline_ix);
19851 }
19852 last_newline_ix = Some(*newline_ix);
19853
19854 if let Some(rows_left) = &mut max_message_rows {
19855 if *rows_left == 0 {
19856 break;
19857 } else {
19858 *rows_left -= 1;
19859 }
19860 }
19861 let _ = newline_indices.next();
19862 } else {
19863 break;
19864 }
19865 }
19866 let prev_len = text_without_backticks.len();
19867 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19868 text_without_backticks.push_str(new_text);
19869 if in_code_block {
19870 code_ranges.push(prev_len..text_without_backticks.len());
19871 }
19872 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19873 in_code_block = !in_code_block;
19874 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19875 text_without_backticks.push_str("...");
19876 break;
19877 }
19878 }
19879
19880 (text_without_backticks.into(), code_ranges)
19881}
19882
19883fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19884 match severity {
19885 DiagnosticSeverity::ERROR => colors.error,
19886 DiagnosticSeverity::WARNING => colors.warning,
19887 DiagnosticSeverity::INFORMATION => colors.info,
19888 DiagnosticSeverity::HINT => colors.info,
19889 _ => colors.ignored,
19890 }
19891}
19892
19893pub fn styled_runs_for_code_label<'a>(
19894 label: &'a CodeLabel,
19895 syntax_theme: &'a theme::SyntaxTheme,
19896) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19897 let fade_out = HighlightStyle {
19898 fade_out: Some(0.35),
19899 ..Default::default()
19900 };
19901
19902 let mut prev_end = label.filter_range.end;
19903 label
19904 .runs
19905 .iter()
19906 .enumerate()
19907 .flat_map(move |(ix, (range, highlight_id))| {
19908 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19909 style
19910 } else {
19911 return Default::default();
19912 };
19913 let mut muted_style = style;
19914 muted_style.highlight(fade_out);
19915
19916 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19917 if range.start >= label.filter_range.end {
19918 if range.start > prev_end {
19919 runs.push((prev_end..range.start, fade_out));
19920 }
19921 runs.push((range.clone(), muted_style));
19922 } else if range.end <= label.filter_range.end {
19923 runs.push((range.clone(), style));
19924 } else {
19925 runs.push((range.start..label.filter_range.end, style));
19926 runs.push((label.filter_range.end..range.end, muted_style));
19927 }
19928 prev_end = cmp::max(prev_end, range.end);
19929
19930 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19931 runs.push((prev_end..label.text.len(), fade_out));
19932 }
19933
19934 runs
19935 })
19936}
19937
19938pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19939 let mut prev_index = 0;
19940 let mut prev_codepoint: Option<char> = None;
19941 text.char_indices()
19942 .chain([(text.len(), '\0')])
19943 .filter_map(move |(index, codepoint)| {
19944 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19945 let is_boundary = index == text.len()
19946 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19947 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19948 if is_boundary {
19949 let chunk = &text[prev_index..index];
19950 prev_index = index;
19951 Some(chunk)
19952 } else {
19953 None
19954 }
19955 })
19956}
19957
19958pub trait RangeToAnchorExt: Sized {
19959 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19960
19961 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19962 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19963 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19964 }
19965}
19966
19967impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19968 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19969 let start_offset = self.start.to_offset(snapshot);
19970 let end_offset = self.end.to_offset(snapshot);
19971 if start_offset == end_offset {
19972 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19973 } else {
19974 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19975 }
19976 }
19977}
19978
19979pub trait RowExt {
19980 fn as_f32(&self) -> f32;
19981
19982 fn next_row(&self) -> Self;
19983
19984 fn previous_row(&self) -> Self;
19985
19986 fn minus(&self, other: Self) -> u32;
19987}
19988
19989impl RowExt for DisplayRow {
19990 fn as_f32(&self) -> f32 {
19991 self.0 as f32
19992 }
19993
19994 fn next_row(&self) -> Self {
19995 Self(self.0 + 1)
19996 }
19997
19998 fn previous_row(&self) -> Self {
19999 Self(self.0.saturating_sub(1))
20000 }
20001
20002 fn minus(&self, other: Self) -> u32 {
20003 self.0 - other.0
20004 }
20005}
20006
20007impl RowExt for MultiBufferRow {
20008 fn as_f32(&self) -> f32 {
20009 self.0 as f32
20010 }
20011
20012 fn next_row(&self) -> Self {
20013 Self(self.0 + 1)
20014 }
20015
20016 fn previous_row(&self) -> Self {
20017 Self(self.0.saturating_sub(1))
20018 }
20019
20020 fn minus(&self, other: Self) -> u32 {
20021 self.0 - other.0
20022 }
20023}
20024
20025trait RowRangeExt {
20026 type Row;
20027
20028 fn len(&self) -> usize;
20029
20030 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20031}
20032
20033impl RowRangeExt for Range<MultiBufferRow> {
20034 type Row = MultiBufferRow;
20035
20036 fn len(&self) -> usize {
20037 (self.end.0 - self.start.0) as usize
20038 }
20039
20040 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20041 (self.start.0..self.end.0).map(MultiBufferRow)
20042 }
20043}
20044
20045impl RowRangeExt for Range<DisplayRow> {
20046 type Row = DisplayRow;
20047
20048 fn len(&self) -> usize {
20049 (self.end.0 - self.start.0) as usize
20050 }
20051
20052 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20053 (self.start.0..self.end.0).map(DisplayRow)
20054 }
20055}
20056
20057/// If select range has more than one line, we
20058/// just point the cursor to range.start.
20059fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20060 if range.start.row == range.end.row {
20061 range
20062 } else {
20063 range.start..range.start
20064 }
20065}
20066pub struct KillRing(ClipboardItem);
20067impl Global for KillRing {}
20068
20069const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20070
20071enum BreakpointPromptEditAction {
20072 Log,
20073 Condition,
20074 HitCondition,
20075}
20076
20077struct BreakpointPromptEditor {
20078 pub(crate) prompt: Entity<Editor>,
20079 editor: WeakEntity<Editor>,
20080 breakpoint_anchor: Anchor,
20081 breakpoint: Breakpoint,
20082 edit_action: BreakpointPromptEditAction,
20083 block_ids: HashSet<CustomBlockId>,
20084 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20085 _subscriptions: Vec<Subscription>,
20086}
20087
20088impl BreakpointPromptEditor {
20089 const MAX_LINES: u8 = 4;
20090
20091 fn new(
20092 editor: WeakEntity<Editor>,
20093 breakpoint_anchor: Anchor,
20094 breakpoint: Breakpoint,
20095 edit_action: BreakpointPromptEditAction,
20096 window: &mut Window,
20097 cx: &mut Context<Self>,
20098 ) -> Self {
20099 let base_text = match edit_action {
20100 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20101 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20102 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20103 }
20104 .map(|msg| msg.to_string())
20105 .unwrap_or_default();
20106
20107 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20108 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20109
20110 let prompt = cx.new(|cx| {
20111 let mut prompt = Editor::new(
20112 EditorMode::AutoHeight {
20113 max_lines: Self::MAX_LINES as usize,
20114 },
20115 buffer,
20116 None,
20117 window,
20118 cx,
20119 );
20120 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20121 prompt.set_show_cursor_when_unfocused(false, cx);
20122 prompt.set_placeholder_text(
20123 match edit_action {
20124 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20125 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20126 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20127 },
20128 cx,
20129 );
20130
20131 prompt
20132 });
20133
20134 Self {
20135 prompt,
20136 editor,
20137 breakpoint_anchor,
20138 breakpoint,
20139 edit_action,
20140 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20141 block_ids: Default::default(),
20142 _subscriptions: vec![],
20143 }
20144 }
20145
20146 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20147 self.block_ids.extend(block_ids)
20148 }
20149
20150 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20151 if let Some(editor) = self.editor.upgrade() {
20152 let message = self
20153 .prompt
20154 .read(cx)
20155 .buffer
20156 .read(cx)
20157 .as_singleton()
20158 .expect("A multi buffer in breakpoint prompt isn't possible")
20159 .read(cx)
20160 .as_rope()
20161 .to_string();
20162
20163 editor.update(cx, |editor, cx| {
20164 editor.edit_breakpoint_at_anchor(
20165 self.breakpoint_anchor,
20166 self.breakpoint.clone(),
20167 match self.edit_action {
20168 BreakpointPromptEditAction::Log => {
20169 BreakpointEditAction::EditLogMessage(message.into())
20170 }
20171 BreakpointPromptEditAction::Condition => {
20172 BreakpointEditAction::EditCondition(message.into())
20173 }
20174 BreakpointPromptEditAction::HitCondition => {
20175 BreakpointEditAction::EditHitCondition(message.into())
20176 }
20177 },
20178 cx,
20179 );
20180
20181 editor.remove_blocks(self.block_ids.clone(), None, cx);
20182 cx.focus_self(window);
20183 });
20184 }
20185 }
20186
20187 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20188 self.editor
20189 .update(cx, |editor, cx| {
20190 editor.remove_blocks(self.block_ids.clone(), None, cx);
20191 window.focus(&editor.focus_handle);
20192 })
20193 .log_err();
20194 }
20195
20196 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20197 let settings = ThemeSettings::get_global(cx);
20198 let text_style = TextStyle {
20199 color: if self.prompt.read(cx).read_only(cx) {
20200 cx.theme().colors().text_disabled
20201 } else {
20202 cx.theme().colors().text
20203 },
20204 font_family: settings.buffer_font.family.clone(),
20205 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20206 font_size: settings.buffer_font_size(cx).into(),
20207 font_weight: settings.buffer_font.weight,
20208 line_height: relative(settings.buffer_line_height.value()),
20209 ..Default::default()
20210 };
20211 EditorElement::new(
20212 &self.prompt,
20213 EditorStyle {
20214 background: cx.theme().colors().editor_background,
20215 local_player: cx.theme().players().local(),
20216 text: text_style,
20217 ..Default::default()
20218 },
20219 )
20220 }
20221}
20222
20223impl Render for BreakpointPromptEditor {
20224 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20225 let gutter_dimensions = *self.gutter_dimensions.lock();
20226 h_flex()
20227 .key_context("Editor")
20228 .bg(cx.theme().colors().editor_background)
20229 .border_y_1()
20230 .border_color(cx.theme().status().info_border)
20231 .size_full()
20232 .py(window.line_height() / 2.5)
20233 .on_action(cx.listener(Self::confirm))
20234 .on_action(cx.listener(Self::cancel))
20235 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20236 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20237 }
20238}
20239
20240impl Focusable for BreakpointPromptEditor {
20241 fn focus_handle(&self, cx: &App) -> FocusHandle {
20242 self.prompt.focus_handle(cx)
20243 }
20244}
20245
20246fn all_edits_insertions_or_deletions(
20247 edits: &Vec<(Range<Anchor>, String)>,
20248 snapshot: &MultiBufferSnapshot,
20249) -> bool {
20250 let mut all_insertions = true;
20251 let mut all_deletions = true;
20252
20253 for (range, new_text) in edits.iter() {
20254 let range_is_empty = range.to_offset(&snapshot).is_empty();
20255 let text_is_empty = new_text.is_empty();
20256
20257 if range_is_empty != text_is_empty {
20258 if range_is_empty {
20259 all_deletions = false;
20260 } else {
20261 all_insertions = false;
20262 }
20263 } else {
20264 return false;
20265 }
20266
20267 if !all_insertions && !all_deletions {
20268 return false;
20269 }
20270 }
20271 all_insertions || all_deletions
20272}
20273
20274struct MissingEditPredictionKeybindingTooltip;
20275
20276impl Render for MissingEditPredictionKeybindingTooltip {
20277 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20278 ui::tooltip_container(window, cx, |container, _, cx| {
20279 container
20280 .flex_shrink_0()
20281 .max_w_80()
20282 .min_h(rems_from_px(124.))
20283 .justify_between()
20284 .child(
20285 v_flex()
20286 .flex_1()
20287 .text_ui_sm(cx)
20288 .child(Label::new("Conflict with Accept Keybinding"))
20289 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20290 )
20291 .child(
20292 h_flex()
20293 .pb_1()
20294 .gap_1()
20295 .items_end()
20296 .w_full()
20297 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20298 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20299 }))
20300 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20301 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20302 })),
20303 )
20304 })
20305 }
20306}
20307
20308#[derive(Debug, Clone, Copy, PartialEq)]
20309pub struct LineHighlight {
20310 pub background: Background,
20311 pub border: Option<gpui::Hsla>,
20312}
20313
20314impl From<Hsla> for LineHighlight {
20315 fn from(hsla: Hsla) -> Self {
20316 Self {
20317 background: hsla.into(),
20318 border: None,
20319 }
20320 }
20321}
20322
20323impl From<Background> for LineHighlight {
20324 fn from(background: Background) -> Self {
20325 Self {
20326 background,
20327 border: None,
20328 }
20329 }
20330}
20331
20332fn render_diff_hunk_controls(
20333 row: u32,
20334 status: &DiffHunkStatus,
20335 hunk_range: Range<Anchor>,
20336 is_created_file: bool,
20337 line_height: Pixels,
20338 editor: &Entity<Editor>,
20339 _window: &mut Window,
20340 cx: &mut App,
20341) -> AnyElement {
20342 h_flex()
20343 .h(line_height)
20344 .mr_1()
20345 .gap_1()
20346 .px_0p5()
20347 .pb_1()
20348 .border_x_1()
20349 .border_b_1()
20350 .border_color(cx.theme().colors().border_variant)
20351 .rounded_b_lg()
20352 .bg(cx.theme().colors().editor_background)
20353 .gap_1()
20354 .occlude()
20355 .shadow_md()
20356 .child(if status.has_secondary_hunk() {
20357 Button::new(("stage", row as u64), "Stage")
20358 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20359 .tooltip({
20360 let focus_handle = editor.focus_handle(cx);
20361 move |window, cx| {
20362 Tooltip::for_action_in(
20363 "Stage Hunk",
20364 &::git::ToggleStaged,
20365 &focus_handle,
20366 window,
20367 cx,
20368 )
20369 }
20370 })
20371 .on_click({
20372 let editor = editor.clone();
20373 move |_event, _window, cx| {
20374 editor.update(cx, |editor, cx| {
20375 editor.stage_or_unstage_diff_hunks(
20376 true,
20377 vec![hunk_range.start..hunk_range.start],
20378 cx,
20379 );
20380 });
20381 }
20382 })
20383 } else {
20384 Button::new(("unstage", row as u64), "Unstage")
20385 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20386 .tooltip({
20387 let focus_handle = editor.focus_handle(cx);
20388 move |window, cx| {
20389 Tooltip::for_action_in(
20390 "Unstage Hunk",
20391 &::git::ToggleStaged,
20392 &focus_handle,
20393 window,
20394 cx,
20395 )
20396 }
20397 })
20398 .on_click({
20399 let editor = editor.clone();
20400 move |_event, _window, cx| {
20401 editor.update(cx, |editor, cx| {
20402 editor.stage_or_unstage_diff_hunks(
20403 false,
20404 vec![hunk_range.start..hunk_range.start],
20405 cx,
20406 );
20407 });
20408 }
20409 })
20410 })
20411 .child(
20412 Button::new(("restore", row as u64), "Restore")
20413 .tooltip({
20414 let focus_handle = editor.focus_handle(cx);
20415 move |window, cx| {
20416 Tooltip::for_action_in(
20417 "Restore Hunk",
20418 &::git::Restore,
20419 &focus_handle,
20420 window,
20421 cx,
20422 )
20423 }
20424 })
20425 .on_click({
20426 let editor = editor.clone();
20427 move |_event, window, cx| {
20428 editor.update(cx, |editor, cx| {
20429 let snapshot = editor.snapshot(window, cx);
20430 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20431 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20432 });
20433 }
20434 })
20435 .disabled(is_created_file),
20436 )
20437 .when(
20438 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20439 |el| {
20440 el.child(
20441 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20442 .shape(IconButtonShape::Square)
20443 .icon_size(IconSize::Small)
20444 // .disabled(!has_multiple_hunks)
20445 .tooltip({
20446 let focus_handle = editor.focus_handle(cx);
20447 move |window, cx| {
20448 Tooltip::for_action_in(
20449 "Next Hunk",
20450 &GoToHunk,
20451 &focus_handle,
20452 window,
20453 cx,
20454 )
20455 }
20456 })
20457 .on_click({
20458 let editor = editor.clone();
20459 move |_event, window, cx| {
20460 editor.update(cx, |editor, cx| {
20461 let snapshot = editor.snapshot(window, cx);
20462 let position =
20463 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20464 editor.go_to_hunk_before_or_after_position(
20465 &snapshot,
20466 position,
20467 Direction::Next,
20468 window,
20469 cx,
20470 );
20471 editor.expand_selected_diff_hunks(cx);
20472 });
20473 }
20474 }),
20475 )
20476 .child(
20477 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20478 .shape(IconButtonShape::Square)
20479 .icon_size(IconSize::Small)
20480 // .disabled(!has_multiple_hunks)
20481 .tooltip({
20482 let focus_handle = editor.focus_handle(cx);
20483 move |window, cx| {
20484 Tooltip::for_action_in(
20485 "Previous Hunk",
20486 &GoToPreviousHunk,
20487 &focus_handle,
20488 window,
20489 cx,
20490 )
20491 }
20492 })
20493 .on_click({
20494 let editor = editor.clone();
20495 move |_event, window, cx| {
20496 editor.update(cx, |editor, cx| {
20497 let snapshot = editor.snapshot(window, cx);
20498 let point =
20499 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20500 editor.go_to_hunk_before_or_after_position(
20501 &snapshot,
20502 point,
20503 Direction::Prev,
20504 window,
20505 cx,
20506 );
20507 editor.expand_selected_diff_hunks(cx);
20508 });
20509 }
20510 }),
20511 )
20512 },
20513 )
20514 .into_any_element()
20515}