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 commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod jsx_tag_auto_close;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51pub(crate) use actions::*;
52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use buffer_diff::DiffHunkStatus;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{
72 future::{self, Shared},
73 FutureExt,
74};
75use fuzzy::StringMatchCandidate;
76
77use ::git::Restore;
78use code_context_menus::{
79 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
80 CompletionsMenu, ContextMenuOrigin,
81};
82use git::blame::GitBlame;
83use gpui::{
84 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
85 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
86 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
87 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
88 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
89 ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
90 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
91 WeakEntity, WeakFocusHandle, Window,
92};
93use highlight_matching_bracket::refresh_matching_bracket_highlights;
94use hover_popover::{hide_hover, HoverState};
95use indent_guides::ActiveIndentGuidesState;
96use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
97pub use inline_completion::Direction;
98use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
99pub use items::MAX_TAB_TITLE_LEN;
100use itertools::Itertools;
101use language::{
102 language_settings::{
103 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
104 },
105 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
106 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
107 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
108 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
109};
110use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
111use linked_editing_ranges::refresh_linked_ranges;
112use mouse_context_menu::MouseContextMenu;
113use persistence::DB;
114pub use proposed_changes_editor::{
115 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
116};
117use smallvec::smallvec;
118use std::iter::Peekable;
119use task::{ResolvedTask, TaskTemplate, TaskVariables};
120
121use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
122pub use lsp::CompletionContext;
123use lsp::{
124 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
125 InsertTextFormat, LanguageServerId, LanguageServerName,
126};
127
128use language::BufferSnapshot;
129use movement::TextLayoutDetails;
130pub use multi_buffer::{
131 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
132 ToOffset, ToPoint,
133};
134use multi_buffer::{
135 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
136 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
137};
138use project::{
139 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
140 project_settings::{GitGutterSetting, ProjectSettings},
141 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
142 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
143};
144use rand::prelude::*;
145use rpc::{proto::*, ErrorExt};
146use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
147use selections_collection::{
148 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
149};
150use serde::{Deserialize, Serialize};
151use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
152use smallvec::SmallVec;
153use snippet::Snippet;
154use std::{
155 any::TypeId,
156 borrow::Cow,
157 cell::RefCell,
158 cmp::{self, Ordering, Reverse},
159 mem,
160 num::NonZeroU32,
161 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
162 path::{Path, PathBuf},
163 rc::Rc,
164 sync::Arc,
165 time::{Duration, Instant},
166};
167pub use sum_tree::Bias;
168use sum_tree::TreeMap;
169use text::{BufferId, OffsetUtf16, Rope};
170use theme::{
171 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
172 ThemeColors, ThemeSettings,
173};
174use ui::{
175 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
176 Tooltip,
177};
178use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
179use workspace::{
180 item::{ItemHandle, PreviewTabsSettings},
181 ItemId, RestoreOnStartupBehavior,
182};
183use workspace::{
184 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
185 WorkspaceSettings,
186};
187use workspace::{
188 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
189};
190use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
191
192use crate::hover_links::{find_url, find_url_from_range};
193use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
194
195pub const FILE_HEADER_HEIGHT: u32 = 2;
196pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
197pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
198pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
199const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
200const MAX_LINE_LEN: usize = 1024;
201const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
202const MAX_SELECTION_HISTORY_LEN: usize = 1024;
203pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
204#[doc(hidden)]
205pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
206
207pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
208pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
209pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
210
211pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
212pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
213
214const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
215 alt: true,
216 shift: true,
217 control: false,
218 platform: false,
219 function: false,
220};
221
222#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
223pub enum InlayId {
224 InlineCompletion(usize),
225 Hint(usize),
226}
227
228impl InlayId {
229 fn id(&self) -> usize {
230 match self {
231 Self::InlineCompletion(id) => *id,
232 Self::Hint(id) => *id,
233 }
234 }
235}
236
237enum DocumentHighlightRead {}
238enum DocumentHighlightWrite {}
239enum InputComposition {}
240enum SelectedTextHighlight {}
241
242#[derive(Debug, Copy, Clone, PartialEq, Eq)]
243pub enum Navigated {
244 Yes,
245 No,
246}
247
248impl Navigated {
249 pub fn from_bool(yes: bool) -> Navigated {
250 if yes {
251 Navigated::Yes
252 } else {
253 Navigated::No
254 }
255 }
256}
257
258#[derive(Debug, Clone, PartialEq, Eq)]
259enum DisplayDiffHunk {
260 Folded {
261 display_row: DisplayRow,
262 },
263 Unfolded {
264 diff_base_byte_range: Range<usize>,
265 display_row_range: Range<DisplayRow>,
266 multi_buffer_range: Range<Anchor>,
267 status: DiffHunkStatus,
268 },
269}
270
271pub fn init_settings(cx: &mut App) {
272 EditorSettings::register(cx);
273}
274
275pub fn init(cx: &mut App) {
276 init_settings(cx);
277
278 workspace::register_project_item::<Editor>(cx);
279 workspace::FollowableViewRegistry::register::<Editor>(cx);
280 workspace::register_serializable_item::<Editor>(cx);
281
282 cx.observe_new(
283 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
284 workspace.register_action(Editor::new_file);
285 workspace.register_action(Editor::new_file_vertical);
286 workspace.register_action(Editor::new_file_horizontal);
287 workspace.register_action(Editor::cancel_language_server_work);
288 },
289 )
290 .detach();
291
292 cx.on_action(move |_: &workspace::NewFile, cx| {
293 let app_state = workspace::AppState::global(cx);
294 if let Some(app_state) = app_state.upgrade() {
295 workspace::open_new(
296 Default::default(),
297 app_state,
298 cx,
299 |workspace, window, cx| {
300 Editor::new_file(workspace, &Default::default(), window, cx)
301 },
302 )
303 .detach();
304 }
305 });
306 cx.on_action(move |_: &workspace::NewWindow, cx| {
307 let app_state = workspace::AppState::global(cx);
308 if let Some(app_state) = app_state.upgrade() {
309 workspace::open_new(
310 Default::default(),
311 app_state,
312 cx,
313 |workspace, window, cx| {
314 cx.activate(true);
315 Editor::new_file(workspace, &Default::default(), window, cx)
316 },
317 )
318 .detach();
319 }
320 });
321}
322
323pub struct SearchWithinRange;
324
325trait InvalidationRegion {
326 fn ranges(&self) -> &[Range<Anchor>];
327}
328
329#[derive(Clone, Debug, PartialEq)]
330pub enum SelectPhase {
331 Begin {
332 position: DisplayPoint,
333 add: bool,
334 click_count: usize,
335 },
336 BeginColumnar {
337 position: DisplayPoint,
338 reset: bool,
339 goal_column: u32,
340 },
341 Extend {
342 position: DisplayPoint,
343 click_count: usize,
344 },
345 Update {
346 position: DisplayPoint,
347 goal_column: u32,
348 scroll_delta: gpui::Point<f32>,
349 },
350 End,
351}
352
353#[derive(Clone, Debug)]
354pub enum SelectMode {
355 Character,
356 Word(Range<Anchor>),
357 Line(Range<Anchor>),
358 All,
359}
360
361#[derive(Copy, Clone, PartialEq, Eq, Debug)]
362pub enum EditorMode {
363 SingleLine { auto_width: bool },
364 AutoHeight { max_lines: usize },
365 Full,
366}
367
368#[derive(Copy, Clone, Debug)]
369pub enum SoftWrap {
370 /// Prefer not to wrap at all.
371 ///
372 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
373 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
374 GitDiff,
375 /// Prefer a single line generally, unless an overly long line is encountered.
376 None,
377 /// Soft wrap lines that exceed the editor width.
378 EditorWidth,
379 /// Soft wrap lines at the preferred line length.
380 Column(u32),
381 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
382 Bounded(u32),
383}
384
385#[derive(Clone)]
386pub struct EditorStyle {
387 pub background: Hsla,
388 pub local_player: PlayerColor,
389 pub text: TextStyle,
390 pub scrollbar_width: Pixels,
391 pub syntax: Arc<SyntaxTheme>,
392 pub status: StatusColors,
393 pub inlay_hints_style: HighlightStyle,
394 pub inline_completion_styles: InlineCompletionStyles,
395 pub unnecessary_code_fade: f32,
396}
397
398impl Default for EditorStyle {
399 fn default() -> Self {
400 Self {
401 background: Hsla::default(),
402 local_player: PlayerColor::default(),
403 text: TextStyle::default(),
404 scrollbar_width: Pixels::default(),
405 syntax: Default::default(),
406 // HACK: Status colors don't have a real default.
407 // We should look into removing the status colors from the editor
408 // style and retrieve them directly from the theme.
409 status: StatusColors::dark(),
410 inlay_hints_style: HighlightStyle::default(),
411 inline_completion_styles: InlineCompletionStyles {
412 insertion: HighlightStyle::default(),
413 whitespace: HighlightStyle::default(),
414 },
415 unnecessary_code_fade: Default::default(),
416 }
417 }
418}
419
420pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
421 let show_background = language_settings::language_settings(None, None, cx)
422 .inlay_hints
423 .show_background;
424
425 HighlightStyle {
426 color: Some(cx.theme().status().hint),
427 background_color: show_background.then(|| cx.theme().status().hint_background),
428 ..HighlightStyle::default()
429 }
430}
431
432pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
433 InlineCompletionStyles {
434 insertion: HighlightStyle {
435 color: Some(cx.theme().status().predictive),
436 ..HighlightStyle::default()
437 },
438 whitespace: HighlightStyle {
439 background_color: Some(cx.theme().status().created_background),
440 ..HighlightStyle::default()
441 },
442 }
443}
444
445type CompletionId = usize;
446
447pub(crate) enum EditDisplayMode {
448 TabAccept,
449 DiffPopover,
450 Inline,
451}
452
453enum InlineCompletion {
454 Edit {
455 edits: Vec<(Range<Anchor>, String)>,
456 edit_preview: Option<EditPreview>,
457 display_mode: EditDisplayMode,
458 snapshot: BufferSnapshot,
459 },
460 Move {
461 target: Anchor,
462 snapshot: BufferSnapshot,
463 },
464}
465
466struct InlineCompletionState {
467 inlay_ids: Vec<InlayId>,
468 completion: InlineCompletion,
469 completion_id: Option<SharedString>,
470 invalidation_range: Range<Anchor>,
471}
472
473enum EditPredictionSettings {
474 Disabled,
475 Enabled {
476 show_in_menu: bool,
477 preview_requires_modifier: bool,
478 },
479}
480
481enum InlineCompletionHighlight {}
482
483#[derive(Debug, Clone)]
484struct InlineDiagnostic {
485 message: SharedString,
486 group_id: usize,
487 is_primary: bool,
488 start: Point,
489 severity: DiagnosticSeverity,
490}
491
492pub enum MenuInlineCompletionsPolicy {
493 Never,
494 ByProvider,
495}
496
497pub enum EditPredictionPreview {
498 /// Modifier is not pressed
499 Inactive { released_too_fast: bool },
500 /// Modifier pressed
501 Active {
502 since: Instant,
503 previous_scroll_position: Option<ScrollAnchor>,
504 },
505}
506
507impl EditPredictionPreview {
508 pub fn released_too_fast(&self) -> bool {
509 match self {
510 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
511 EditPredictionPreview::Active { .. } => false,
512 }
513 }
514
515 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
516 if let EditPredictionPreview::Active {
517 previous_scroll_position,
518 ..
519 } = self
520 {
521 *previous_scroll_position = scroll_position;
522 }
523 }
524}
525
526#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
527struct EditorActionId(usize);
528
529impl EditorActionId {
530 pub fn post_inc(&mut self) -> Self {
531 let answer = self.0;
532
533 *self = Self(answer + 1);
534
535 Self(answer)
536 }
537}
538
539// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
540// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
541
542type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
543type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
544
545#[derive(Default)]
546struct ScrollbarMarkerState {
547 scrollbar_size: Size<Pixels>,
548 dirty: bool,
549 markers: Arc<[PaintQuad]>,
550 pending_refresh: Option<Task<Result<()>>>,
551}
552
553impl ScrollbarMarkerState {
554 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
555 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
556 }
557}
558
559#[derive(Clone, Debug)]
560struct RunnableTasks {
561 templates: Vec<(TaskSourceKind, TaskTemplate)>,
562 offset: multi_buffer::Anchor,
563 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
564 column: u32,
565 // Values of all named captures, including those starting with '_'
566 extra_variables: HashMap<String, String>,
567 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
568 context_range: Range<BufferOffset>,
569}
570
571impl RunnableTasks {
572 fn resolve<'a>(
573 &'a self,
574 cx: &'a task::TaskContext,
575 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
576 self.templates.iter().filter_map(|(kind, template)| {
577 template
578 .resolve_task(&kind.to_id_base(), cx)
579 .map(|task| (kind.clone(), task))
580 })
581 }
582}
583
584#[derive(Clone)]
585struct ResolvedTasks {
586 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
587 position: Anchor,
588}
589#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
590struct BufferOffset(usize);
591
592// Addons allow storing per-editor state in other crates (e.g. Vim)
593pub trait Addon: 'static {
594 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
595
596 fn render_buffer_header_controls(
597 &self,
598 _: &ExcerptInfo,
599 _: &Window,
600 _: &App,
601 ) -> Option<AnyElement> {
602 None
603 }
604
605 fn to_any(&self) -> &dyn std::any::Any;
606}
607
608#[derive(Debug, Copy, Clone, PartialEq, Eq)]
609pub enum IsVimMode {
610 Yes,
611 No,
612}
613
614/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
615///
616/// See the [module level documentation](self) for more information.
617pub struct Editor {
618 focus_handle: FocusHandle,
619 last_focused_descendant: Option<WeakFocusHandle>,
620 /// The text buffer being edited
621 buffer: Entity<MultiBuffer>,
622 /// Map of how text in the buffer should be displayed.
623 /// Handles soft wraps, folds, fake inlay text insertions, etc.
624 pub display_map: Entity<DisplayMap>,
625 pub selections: SelectionsCollection,
626 pub scroll_manager: ScrollManager,
627 /// When inline assist editors are linked, they all render cursors because
628 /// typing enters text into each of them, even the ones that aren't focused.
629 pub(crate) show_cursor_when_unfocused: bool,
630 columnar_selection_tail: Option<Anchor>,
631 add_selections_state: Option<AddSelectionsState>,
632 select_next_state: Option<SelectNextState>,
633 select_prev_state: Option<SelectNextState>,
634 selection_history: SelectionHistory,
635 autoclose_regions: Vec<AutocloseRegion>,
636 snippet_stack: InvalidationStack<SnippetState>,
637 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
638 ime_transaction: Option<TransactionId>,
639 active_diagnostics: Option<ActiveDiagnosticGroup>,
640 show_inline_diagnostics: bool,
641 inline_diagnostics_update: Task<()>,
642 inline_diagnostics_enabled: bool,
643 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
644 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
645
646 // TODO: make this a access method
647 pub project: Option<Entity<Project>>,
648 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
649 completion_provider: Option<Box<dyn CompletionProvider>>,
650 collaboration_hub: Option<Box<dyn CollaborationHub>>,
651 blink_manager: Entity<BlinkManager>,
652 show_cursor_names: bool,
653 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
654 pub show_local_selections: bool,
655 mode: EditorMode,
656 show_breadcrumbs: bool,
657 show_gutter: bool,
658 show_scrollbars: bool,
659 show_line_numbers: Option<bool>,
660 use_relative_line_numbers: Option<bool>,
661 show_git_diff_gutter: Option<bool>,
662 show_code_actions: Option<bool>,
663 show_runnables: Option<bool>,
664 show_wrap_guides: Option<bool>,
665 show_indent_guides: Option<bool>,
666 placeholder_text: Option<Arc<str>>,
667 highlight_order: usize,
668 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
669 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
670 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
671 scrollbar_marker_state: ScrollbarMarkerState,
672 active_indent_guides_state: ActiveIndentGuidesState,
673 nav_history: Option<ItemNavHistory>,
674 context_menu: RefCell<Option<CodeContextMenu>>,
675 mouse_context_menu: Option<MouseContextMenu>,
676 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
677 signature_help_state: SignatureHelpState,
678 auto_signature_help: Option<bool>,
679 find_all_references_task_sources: Vec<Anchor>,
680 next_completion_id: CompletionId,
681 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
682 code_actions_task: Option<Task<Result<()>>>,
683 selection_highlight_task: Option<Task<()>>,
684 document_highlights_task: Option<Task<()>>,
685 linked_editing_range_task: Option<Task<Option<()>>>,
686 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
687 pending_rename: Option<RenameState>,
688 searchable: bool,
689 cursor_shape: CursorShape,
690 current_line_highlight: Option<CurrentLineHighlight>,
691 collapse_matches: bool,
692 autoindent_mode: Option<AutoindentMode>,
693 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
694 input_enabled: bool,
695 use_modal_editing: bool,
696 read_only: bool,
697 leader_peer_id: Option<PeerId>,
698 remote_id: Option<ViewId>,
699 hover_state: HoverState,
700 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
701 gutter_hovered: bool,
702 hovered_link_state: Option<HoveredLinkState>,
703 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
704 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
705 active_inline_completion: Option<InlineCompletionState>,
706 /// Used to prevent flickering as the user types while the menu is open
707 stale_inline_completion_in_menu: Option<InlineCompletionState>,
708 edit_prediction_settings: EditPredictionSettings,
709 inline_completions_hidden_for_vim_mode: bool,
710 show_inline_completions_override: Option<bool>,
711 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
712 edit_prediction_preview: EditPredictionPreview,
713 edit_prediction_indent_conflict: bool,
714 edit_prediction_requires_modifier_in_indent_conflict: bool,
715 inlay_hint_cache: InlayHintCache,
716 next_inlay_id: usize,
717 _subscriptions: Vec<Subscription>,
718 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
719 gutter_dimensions: GutterDimensions,
720 style: Option<EditorStyle>,
721 text_style_refinement: Option<TextStyleRefinement>,
722 next_editor_action_id: EditorActionId,
723 editor_actions:
724 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
725 use_autoclose: bool,
726 use_auto_surround: bool,
727 auto_replace_emoji_shortcode: bool,
728 jsx_tag_auto_close_enabled_in_any_buffer: bool,
729 show_git_blame_gutter: bool,
730 show_git_blame_inline: bool,
731 show_git_blame_inline_delay_task: Option<Task<()>>,
732 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
733 git_blame_inline_enabled: bool,
734 serialize_dirty_buffers: bool,
735 show_selection_menu: Option<bool>,
736 blame: Option<Entity<GitBlame>>,
737 blame_subscription: Option<Subscription>,
738 custom_context_menu: Option<
739 Box<
740 dyn 'static
741 + Fn(
742 &mut Self,
743 DisplayPoint,
744 &mut Window,
745 &mut Context<Self>,
746 ) -> Option<Entity<ui::ContextMenu>>,
747 >,
748 >,
749 last_bounds: Option<Bounds<Pixels>>,
750 last_position_map: Option<Rc<PositionMap>>,
751 expect_bounds_change: Option<Bounds<Pixels>>,
752 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
753 tasks_update_task: Option<Task<()>>,
754 in_project_search: bool,
755 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
756 breadcrumb_header: Option<String>,
757 focused_block: Option<FocusedBlock>,
758 next_scroll_position: NextScrollCursorCenterTopBottom,
759 addons: HashMap<TypeId, Box<dyn Addon>>,
760 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
761 load_diff_task: Option<Shared<Task<()>>>,
762 selection_mark_mode: bool,
763 toggle_fold_multiple_buffers: Task<()>,
764 _scroll_cursor_center_top_bottom_task: Task<()>,
765 serialize_selections: Task<()>,
766}
767
768#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
769enum NextScrollCursorCenterTopBottom {
770 #[default]
771 Center,
772 Top,
773 Bottom,
774}
775
776impl NextScrollCursorCenterTopBottom {
777 fn next(&self) -> Self {
778 match self {
779 Self::Center => Self::Top,
780 Self::Top => Self::Bottom,
781 Self::Bottom => Self::Center,
782 }
783 }
784}
785
786#[derive(Clone)]
787pub struct EditorSnapshot {
788 pub mode: EditorMode,
789 show_gutter: bool,
790 show_line_numbers: Option<bool>,
791 show_git_diff_gutter: Option<bool>,
792 show_code_actions: Option<bool>,
793 show_runnables: Option<bool>,
794 git_blame_gutter_max_author_length: Option<usize>,
795 pub display_snapshot: DisplaySnapshot,
796 pub placeholder_text: Option<Arc<str>>,
797 is_focused: bool,
798 scroll_anchor: ScrollAnchor,
799 ongoing_scroll: OngoingScroll,
800 current_line_highlight: CurrentLineHighlight,
801 gutter_hovered: bool,
802}
803
804const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
805
806#[derive(Default, Debug, Clone, Copy)]
807pub struct GutterDimensions {
808 pub left_padding: Pixels,
809 pub right_padding: Pixels,
810 pub width: Pixels,
811 pub margin: Pixels,
812 pub git_blame_entries_width: Option<Pixels>,
813}
814
815impl GutterDimensions {
816 /// The full width of the space taken up by the gutter.
817 pub fn full_width(&self) -> Pixels {
818 self.margin + self.width
819 }
820
821 /// The width of the space reserved for the fold indicators,
822 /// use alongside 'justify_end' and `gutter_width` to
823 /// right align content with the line numbers
824 pub fn fold_area_width(&self) -> Pixels {
825 self.margin + self.right_padding
826 }
827}
828
829#[derive(Debug)]
830pub struct RemoteSelection {
831 pub replica_id: ReplicaId,
832 pub selection: Selection<Anchor>,
833 pub cursor_shape: CursorShape,
834 pub peer_id: PeerId,
835 pub line_mode: bool,
836 pub participant_index: Option<ParticipantIndex>,
837 pub user_name: Option<SharedString>,
838}
839
840#[derive(Clone, Debug)]
841struct SelectionHistoryEntry {
842 selections: Arc<[Selection<Anchor>]>,
843 select_next_state: Option<SelectNextState>,
844 select_prev_state: Option<SelectNextState>,
845 add_selections_state: Option<AddSelectionsState>,
846}
847
848enum SelectionHistoryMode {
849 Normal,
850 Undoing,
851 Redoing,
852}
853
854#[derive(Clone, PartialEq, Eq, Hash)]
855struct HoveredCursor {
856 replica_id: u16,
857 selection_id: usize,
858}
859
860impl Default for SelectionHistoryMode {
861 fn default() -> Self {
862 Self::Normal
863 }
864}
865
866#[derive(Default)]
867struct SelectionHistory {
868 #[allow(clippy::type_complexity)]
869 selections_by_transaction:
870 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
871 mode: SelectionHistoryMode,
872 undo_stack: VecDeque<SelectionHistoryEntry>,
873 redo_stack: VecDeque<SelectionHistoryEntry>,
874}
875
876impl SelectionHistory {
877 fn insert_transaction(
878 &mut self,
879 transaction_id: TransactionId,
880 selections: Arc<[Selection<Anchor>]>,
881 ) {
882 self.selections_by_transaction
883 .insert(transaction_id, (selections, None));
884 }
885
886 #[allow(clippy::type_complexity)]
887 fn transaction(
888 &self,
889 transaction_id: TransactionId,
890 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
891 self.selections_by_transaction.get(&transaction_id)
892 }
893
894 #[allow(clippy::type_complexity)]
895 fn transaction_mut(
896 &mut self,
897 transaction_id: TransactionId,
898 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
899 self.selections_by_transaction.get_mut(&transaction_id)
900 }
901
902 fn push(&mut self, entry: SelectionHistoryEntry) {
903 if !entry.selections.is_empty() {
904 match self.mode {
905 SelectionHistoryMode::Normal => {
906 self.push_undo(entry);
907 self.redo_stack.clear();
908 }
909 SelectionHistoryMode::Undoing => self.push_redo(entry),
910 SelectionHistoryMode::Redoing => self.push_undo(entry),
911 }
912 }
913 }
914
915 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
916 if self
917 .undo_stack
918 .back()
919 .map_or(true, |e| e.selections != entry.selections)
920 {
921 self.undo_stack.push_back(entry);
922 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
923 self.undo_stack.pop_front();
924 }
925 }
926 }
927
928 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
929 if self
930 .redo_stack
931 .back()
932 .map_or(true, |e| e.selections != entry.selections)
933 {
934 self.redo_stack.push_back(entry);
935 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
936 self.redo_stack.pop_front();
937 }
938 }
939 }
940}
941
942struct RowHighlight {
943 index: usize,
944 range: Range<Anchor>,
945 color: Hsla,
946 should_autoscroll: bool,
947}
948
949#[derive(Clone, Debug)]
950struct AddSelectionsState {
951 above: bool,
952 stack: Vec<usize>,
953}
954
955#[derive(Clone)]
956struct SelectNextState {
957 query: AhoCorasick,
958 wordwise: bool,
959 done: bool,
960}
961
962impl std::fmt::Debug for SelectNextState {
963 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
964 f.debug_struct(std::any::type_name::<Self>())
965 .field("wordwise", &self.wordwise)
966 .field("done", &self.done)
967 .finish()
968 }
969}
970
971#[derive(Debug)]
972struct AutocloseRegion {
973 selection_id: usize,
974 range: Range<Anchor>,
975 pair: BracketPair,
976}
977
978#[derive(Debug)]
979struct SnippetState {
980 ranges: Vec<Vec<Range<Anchor>>>,
981 active_index: usize,
982 choices: Vec<Option<Vec<String>>>,
983}
984
985#[doc(hidden)]
986pub struct RenameState {
987 pub range: Range<Anchor>,
988 pub old_name: Arc<str>,
989 pub editor: Entity<Editor>,
990 block_id: CustomBlockId,
991}
992
993struct InvalidationStack<T>(Vec<T>);
994
995struct RegisteredInlineCompletionProvider {
996 provider: Arc<dyn InlineCompletionProviderHandle>,
997 _subscription: Subscription,
998}
999
1000#[derive(Debug, PartialEq, Eq)]
1001struct ActiveDiagnosticGroup {
1002 primary_range: Range<Anchor>,
1003 primary_message: String,
1004 group_id: usize,
1005 blocks: HashMap<CustomBlockId, Diagnostic>,
1006 is_valid: bool,
1007}
1008
1009#[derive(Serialize, Deserialize, Clone, Debug)]
1010pub struct ClipboardSelection {
1011 /// The number of bytes in this selection.
1012 pub len: usize,
1013 /// Whether this was a full-line selection.
1014 pub is_entire_line: bool,
1015 /// The column where this selection originally started.
1016 pub start_column: u32,
1017}
1018
1019#[derive(Debug)]
1020pub(crate) struct NavigationData {
1021 cursor_anchor: Anchor,
1022 cursor_position: Point,
1023 scroll_anchor: ScrollAnchor,
1024 scroll_top_row: u32,
1025}
1026
1027#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1028pub enum GotoDefinitionKind {
1029 Symbol,
1030 Declaration,
1031 Type,
1032 Implementation,
1033}
1034
1035#[derive(Debug, Clone)]
1036enum InlayHintRefreshReason {
1037 ModifiersChanged(bool),
1038 Toggle(bool),
1039 SettingsChange(InlayHintSettings),
1040 NewLinesShown,
1041 BufferEdited(HashSet<Arc<Language>>),
1042 RefreshRequested,
1043 ExcerptsRemoved(Vec<ExcerptId>),
1044}
1045
1046impl InlayHintRefreshReason {
1047 fn description(&self) -> &'static str {
1048 match self {
1049 Self::ModifiersChanged(_) => "modifiers changed",
1050 Self::Toggle(_) => "toggle",
1051 Self::SettingsChange(_) => "settings change",
1052 Self::NewLinesShown => "new lines shown",
1053 Self::BufferEdited(_) => "buffer edited",
1054 Self::RefreshRequested => "refresh requested",
1055 Self::ExcerptsRemoved(_) => "excerpts removed",
1056 }
1057 }
1058}
1059
1060pub enum FormatTarget {
1061 Buffers,
1062 Ranges(Vec<Range<MultiBufferPoint>>),
1063}
1064
1065pub(crate) struct FocusedBlock {
1066 id: BlockId,
1067 focus_handle: WeakFocusHandle,
1068}
1069
1070#[derive(Clone)]
1071enum JumpData {
1072 MultiBufferRow {
1073 row: MultiBufferRow,
1074 line_offset_from_top: u32,
1075 },
1076 MultiBufferPoint {
1077 excerpt_id: ExcerptId,
1078 position: Point,
1079 anchor: text::Anchor,
1080 line_offset_from_top: u32,
1081 },
1082}
1083
1084pub enum MultibufferSelectionMode {
1085 First,
1086 All,
1087}
1088
1089impl Editor {
1090 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1091 let buffer = cx.new(|cx| Buffer::local("", cx));
1092 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1093 Self::new(
1094 EditorMode::SingleLine { auto_width: false },
1095 buffer,
1096 None,
1097 false,
1098 window,
1099 cx,
1100 )
1101 }
1102
1103 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1104 let buffer = cx.new(|cx| Buffer::local("", cx));
1105 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1106 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1107 }
1108
1109 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1110 let buffer = cx.new(|cx| Buffer::local("", cx));
1111 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1112 Self::new(
1113 EditorMode::SingleLine { auto_width: true },
1114 buffer,
1115 None,
1116 false,
1117 window,
1118 cx,
1119 )
1120 }
1121
1122 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1123 let buffer = cx.new(|cx| Buffer::local("", cx));
1124 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1125 Self::new(
1126 EditorMode::AutoHeight { max_lines },
1127 buffer,
1128 None,
1129 false,
1130 window,
1131 cx,
1132 )
1133 }
1134
1135 pub fn for_buffer(
1136 buffer: Entity<Buffer>,
1137 project: Option<Entity<Project>>,
1138 window: &mut Window,
1139 cx: &mut Context<Self>,
1140 ) -> Self {
1141 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1142 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1143 }
1144
1145 pub fn for_multibuffer(
1146 buffer: Entity<MultiBuffer>,
1147 project: Option<Entity<Project>>,
1148 show_excerpt_controls: bool,
1149 window: &mut Window,
1150 cx: &mut Context<Self>,
1151 ) -> Self {
1152 Self::new(
1153 EditorMode::Full,
1154 buffer,
1155 project,
1156 show_excerpt_controls,
1157 window,
1158 cx,
1159 )
1160 }
1161
1162 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1163 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1164 let mut clone = Self::new(
1165 self.mode,
1166 self.buffer.clone(),
1167 self.project.clone(),
1168 show_excerpt_controls,
1169 window,
1170 cx,
1171 );
1172 self.display_map.update(cx, |display_map, cx| {
1173 let snapshot = display_map.snapshot(cx);
1174 clone.display_map.update(cx, |display_map, cx| {
1175 display_map.set_state(&snapshot, cx);
1176 });
1177 });
1178 clone.selections.clone_state(&self.selections);
1179 clone.scroll_manager.clone_state(&self.scroll_manager);
1180 clone.searchable = self.searchable;
1181 clone
1182 }
1183
1184 pub fn new(
1185 mode: EditorMode,
1186 buffer: Entity<MultiBuffer>,
1187 project: Option<Entity<Project>>,
1188 show_excerpt_controls: bool,
1189 window: &mut Window,
1190 cx: &mut Context<Self>,
1191 ) -> Self {
1192 let style = window.text_style();
1193 let font_size = style.font_size.to_pixels(window.rem_size());
1194 let editor = cx.entity().downgrade();
1195 let fold_placeholder = FoldPlaceholder {
1196 constrain_width: true,
1197 render: Arc::new(move |fold_id, fold_range, cx| {
1198 let editor = editor.clone();
1199 div()
1200 .id(fold_id)
1201 .bg(cx.theme().colors().ghost_element_background)
1202 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1203 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1204 .rounded_xs()
1205 .size_full()
1206 .cursor_pointer()
1207 .child("⋯")
1208 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1209 .on_click(move |_, _window, cx| {
1210 editor
1211 .update(cx, |editor, cx| {
1212 editor.unfold_ranges(
1213 &[fold_range.start..fold_range.end],
1214 true,
1215 false,
1216 cx,
1217 );
1218 cx.stop_propagation();
1219 })
1220 .ok();
1221 })
1222 .into_any()
1223 }),
1224 merge_adjacent: true,
1225 ..Default::default()
1226 };
1227 let display_map = cx.new(|cx| {
1228 DisplayMap::new(
1229 buffer.clone(),
1230 style.font(),
1231 font_size,
1232 None,
1233 show_excerpt_controls,
1234 FILE_HEADER_HEIGHT,
1235 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1236 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1237 fold_placeholder,
1238 cx,
1239 )
1240 });
1241
1242 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1243
1244 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1245
1246 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1247 .then(|| language_settings::SoftWrap::None);
1248
1249 let mut project_subscriptions = Vec::new();
1250 if mode == EditorMode::Full {
1251 if let Some(project) = project.as_ref() {
1252 if buffer.read(cx).is_singleton() {
1253 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1254 cx.emit(EditorEvent::TitleChanged);
1255 }));
1256 }
1257 project_subscriptions.push(cx.subscribe_in(
1258 project,
1259 window,
1260 |editor, _, event, window, cx| {
1261 if let project::Event::RefreshInlayHints = event {
1262 editor
1263 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1264 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1265 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1266 let focus_handle = editor.focus_handle(cx);
1267 if focus_handle.is_focused(window) {
1268 let snapshot = buffer.read(cx).snapshot();
1269 for (range, snippet) in snippet_edits {
1270 let editor_range =
1271 language::range_from_lsp(*range).to_offset(&snapshot);
1272 editor
1273 .insert_snippet(
1274 &[editor_range],
1275 snippet.clone(),
1276 window,
1277 cx,
1278 )
1279 .ok();
1280 }
1281 }
1282 }
1283 }
1284 },
1285 ));
1286 if let Some(task_inventory) = project
1287 .read(cx)
1288 .task_store()
1289 .read(cx)
1290 .task_inventory()
1291 .cloned()
1292 {
1293 project_subscriptions.push(cx.observe_in(
1294 &task_inventory,
1295 window,
1296 |editor, _, window, cx| {
1297 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1298 },
1299 ));
1300 }
1301 }
1302 }
1303
1304 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1305
1306 let inlay_hint_settings =
1307 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1308 let focus_handle = cx.focus_handle();
1309 cx.on_focus(&focus_handle, window, Self::handle_focus)
1310 .detach();
1311 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1312 .detach();
1313 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1314 .detach();
1315 cx.on_blur(&focus_handle, window, Self::handle_blur)
1316 .detach();
1317
1318 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1319 Some(false)
1320 } else {
1321 None
1322 };
1323
1324 let mut code_action_providers = Vec::new();
1325 let mut load_uncommitted_diff = None;
1326 if let Some(project) = project.clone() {
1327 load_uncommitted_diff = Some(
1328 get_uncommitted_diff_for_buffer(
1329 &project,
1330 buffer.read(cx).all_buffers(),
1331 buffer.clone(),
1332 cx,
1333 )
1334 .shared(),
1335 );
1336 code_action_providers.push(Rc::new(project) as Rc<_>);
1337 }
1338
1339 let mut this = Self {
1340 focus_handle,
1341 show_cursor_when_unfocused: false,
1342 last_focused_descendant: None,
1343 buffer: buffer.clone(),
1344 display_map: display_map.clone(),
1345 selections,
1346 scroll_manager: ScrollManager::new(cx),
1347 columnar_selection_tail: None,
1348 add_selections_state: None,
1349 select_next_state: None,
1350 select_prev_state: None,
1351 selection_history: Default::default(),
1352 autoclose_regions: Default::default(),
1353 snippet_stack: Default::default(),
1354 select_larger_syntax_node_stack: Vec::new(),
1355 ime_transaction: Default::default(),
1356 active_diagnostics: None,
1357 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1358 inline_diagnostics_update: Task::ready(()),
1359 inline_diagnostics: Vec::new(),
1360 soft_wrap_mode_override,
1361 completion_provider: project.clone().map(|project| Box::new(project) as _),
1362 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1363 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1364 project,
1365 blink_manager: blink_manager.clone(),
1366 show_local_selections: true,
1367 show_scrollbars: true,
1368 mode,
1369 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1370 show_gutter: mode == EditorMode::Full,
1371 show_line_numbers: None,
1372 use_relative_line_numbers: None,
1373 show_git_diff_gutter: None,
1374 show_code_actions: None,
1375 show_runnables: None,
1376 show_wrap_guides: None,
1377 show_indent_guides,
1378 placeholder_text: None,
1379 highlight_order: 0,
1380 highlighted_rows: HashMap::default(),
1381 background_highlights: Default::default(),
1382 gutter_highlights: TreeMap::default(),
1383 scrollbar_marker_state: ScrollbarMarkerState::default(),
1384 active_indent_guides_state: ActiveIndentGuidesState::default(),
1385 nav_history: None,
1386 context_menu: RefCell::new(None),
1387 mouse_context_menu: None,
1388 completion_tasks: Default::default(),
1389 signature_help_state: SignatureHelpState::default(),
1390 auto_signature_help: None,
1391 find_all_references_task_sources: Vec::new(),
1392 next_completion_id: 0,
1393 next_inlay_id: 0,
1394 code_action_providers,
1395 available_code_actions: Default::default(),
1396 code_actions_task: Default::default(),
1397 selection_highlight_task: Default::default(),
1398 document_highlights_task: Default::default(),
1399 linked_editing_range_task: Default::default(),
1400 pending_rename: Default::default(),
1401 searchable: true,
1402 cursor_shape: EditorSettings::get_global(cx)
1403 .cursor_shape
1404 .unwrap_or_default(),
1405 current_line_highlight: None,
1406 autoindent_mode: Some(AutoindentMode::EachLine),
1407 collapse_matches: false,
1408 workspace: None,
1409 input_enabled: true,
1410 use_modal_editing: mode == EditorMode::Full,
1411 read_only: false,
1412 use_autoclose: true,
1413 use_auto_surround: true,
1414 auto_replace_emoji_shortcode: false,
1415 jsx_tag_auto_close_enabled_in_any_buffer: false,
1416 leader_peer_id: None,
1417 remote_id: None,
1418 hover_state: Default::default(),
1419 pending_mouse_down: None,
1420 hovered_link_state: Default::default(),
1421 edit_prediction_provider: None,
1422 active_inline_completion: None,
1423 stale_inline_completion_in_menu: None,
1424 edit_prediction_preview: EditPredictionPreview::Inactive {
1425 released_too_fast: false,
1426 },
1427 inline_diagnostics_enabled: mode == EditorMode::Full,
1428 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1429
1430 gutter_hovered: false,
1431 pixel_position_of_newest_cursor: None,
1432 last_bounds: None,
1433 last_position_map: None,
1434 expect_bounds_change: None,
1435 gutter_dimensions: GutterDimensions::default(),
1436 style: None,
1437 show_cursor_names: false,
1438 hovered_cursors: Default::default(),
1439 next_editor_action_id: EditorActionId::default(),
1440 editor_actions: Rc::default(),
1441 inline_completions_hidden_for_vim_mode: false,
1442 show_inline_completions_override: None,
1443 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1444 edit_prediction_settings: EditPredictionSettings::Disabled,
1445 edit_prediction_indent_conflict: false,
1446 edit_prediction_requires_modifier_in_indent_conflict: true,
1447 custom_context_menu: None,
1448 show_git_blame_gutter: false,
1449 show_git_blame_inline: false,
1450 show_selection_menu: None,
1451 show_git_blame_inline_delay_task: None,
1452 git_blame_inline_tooltip: None,
1453 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1454 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1455 .session
1456 .restore_unsaved_buffers,
1457 blame: None,
1458 blame_subscription: None,
1459 tasks: Default::default(),
1460 _subscriptions: vec![
1461 cx.observe(&buffer, Self::on_buffer_changed),
1462 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1463 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1464 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1465 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1466 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1467 cx.observe_window_activation(window, |editor, window, cx| {
1468 let active = window.is_window_active();
1469 editor.blink_manager.update(cx, |blink_manager, cx| {
1470 if active {
1471 blink_manager.enable(cx);
1472 } else {
1473 blink_manager.disable(cx);
1474 }
1475 });
1476 }),
1477 ],
1478 tasks_update_task: None,
1479 linked_edit_ranges: Default::default(),
1480 in_project_search: false,
1481 previous_search_ranges: None,
1482 breadcrumb_header: None,
1483 focused_block: None,
1484 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1485 addons: HashMap::default(),
1486 registered_buffers: HashMap::default(),
1487 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1488 selection_mark_mode: false,
1489 toggle_fold_multiple_buffers: Task::ready(()),
1490 serialize_selections: Task::ready(()),
1491 text_style_refinement: None,
1492 load_diff_task: load_uncommitted_diff,
1493 };
1494 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1495 this._subscriptions.extend(project_subscriptions);
1496
1497 this.end_selection(window, cx);
1498 this.scroll_manager.show_scrollbar(window, cx);
1499 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1500
1501 if mode == EditorMode::Full {
1502 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1503 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1504
1505 if this.git_blame_inline_enabled {
1506 this.git_blame_inline_enabled = true;
1507 this.start_git_blame_inline(false, window, cx);
1508 }
1509
1510 if let Some(buffer) = buffer.read(cx).as_singleton() {
1511 if let Some(project) = this.project.as_ref() {
1512 let handle = project.update(cx, |project, cx| {
1513 project.register_buffer_with_language_servers(&buffer, cx)
1514 });
1515 this.registered_buffers
1516 .insert(buffer.read(cx).remote_id(), handle);
1517 }
1518 }
1519 }
1520
1521 this.report_editor_event("Editor Opened", None, cx);
1522 this
1523 }
1524
1525 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1526 self.mouse_context_menu
1527 .as_ref()
1528 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1529 }
1530
1531 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1532 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1533 }
1534
1535 fn key_context_internal(
1536 &self,
1537 has_active_edit_prediction: bool,
1538 window: &Window,
1539 cx: &App,
1540 ) -> KeyContext {
1541 let mut key_context = KeyContext::new_with_defaults();
1542 key_context.add("Editor");
1543 let mode = match self.mode {
1544 EditorMode::SingleLine { .. } => "single_line",
1545 EditorMode::AutoHeight { .. } => "auto_height",
1546 EditorMode::Full => "full",
1547 };
1548
1549 if EditorSettings::jupyter_enabled(cx) {
1550 key_context.add("jupyter");
1551 }
1552
1553 key_context.set("mode", mode);
1554 if self.pending_rename.is_some() {
1555 key_context.add("renaming");
1556 }
1557
1558 match self.context_menu.borrow().as_ref() {
1559 Some(CodeContextMenu::Completions(_)) => {
1560 key_context.add("menu");
1561 key_context.add("showing_completions");
1562 }
1563 Some(CodeContextMenu::CodeActions(_)) => {
1564 key_context.add("menu");
1565 key_context.add("showing_code_actions")
1566 }
1567 None => {}
1568 }
1569
1570 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1571 if !self.focus_handle(cx).contains_focused(window, cx)
1572 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1573 {
1574 for addon in self.addons.values() {
1575 addon.extend_key_context(&mut key_context, cx)
1576 }
1577 }
1578
1579 if let Some(extension) = self
1580 .buffer
1581 .read(cx)
1582 .as_singleton()
1583 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1584 {
1585 key_context.set("extension", extension.to_string());
1586 }
1587
1588 if has_active_edit_prediction {
1589 if self.edit_prediction_in_conflict() {
1590 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1591 } else {
1592 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1593 key_context.add("copilot_suggestion");
1594 }
1595 }
1596
1597 if self.selection_mark_mode {
1598 key_context.add("selection_mode");
1599 }
1600
1601 key_context
1602 }
1603
1604 pub fn edit_prediction_in_conflict(&self) -> bool {
1605 if !self.show_edit_predictions_in_menu() {
1606 return false;
1607 }
1608
1609 let showing_completions = self
1610 .context_menu
1611 .borrow()
1612 .as_ref()
1613 .map_or(false, |context| {
1614 matches!(context, CodeContextMenu::Completions(_))
1615 });
1616
1617 showing_completions
1618 || self.edit_prediction_requires_modifier()
1619 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1620 // bindings to insert tab characters.
1621 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1622 }
1623
1624 pub fn accept_edit_prediction_keybind(
1625 &self,
1626 window: &Window,
1627 cx: &App,
1628 ) -> AcceptEditPredictionBinding {
1629 let key_context = self.key_context_internal(true, window, cx);
1630 let in_conflict = self.edit_prediction_in_conflict();
1631
1632 AcceptEditPredictionBinding(
1633 window
1634 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1635 .into_iter()
1636 .filter(|binding| {
1637 !in_conflict
1638 || binding
1639 .keystrokes()
1640 .first()
1641 .map_or(false, |keystroke| keystroke.modifiers.modified())
1642 })
1643 .rev()
1644 .min_by_key(|binding| {
1645 binding
1646 .keystrokes()
1647 .first()
1648 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1649 }),
1650 )
1651 }
1652
1653 pub fn new_file(
1654 workspace: &mut Workspace,
1655 _: &workspace::NewFile,
1656 window: &mut Window,
1657 cx: &mut Context<Workspace>,
1658 ) {
1659 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1660 "Failed to create buffer",
1661 window,
1662 cx,
1663 |e, _, _| match e.error_code() {
1664 ErrorCode::RemoteUpgradeRequired => Some(format!(
1665 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1666 e.error_tag("required").unwrap_or("the latest version")
1667 )),
1668 _ => None,
1669 },
1670 );
1671 }
1672
1673 pub fn new_in_workspace(
1674 workspace: &mut Workspace,
1675 window: &mut Window,
1676 cx: &mut Context<Workspace>,
1677 ) -> Task<Result<Entity<Editor>>> {
1678 let project = workspace.project().clone();
1679 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1680
1681 cx.spawn_in(window, |workspace, mut cx| async move {
1682 let buffer = create.await?;
1683 workspace.update_in(&mut cx, |workspace, window, cx| {
1684 let editor =
1685 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1686 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1687 editor
1688 })
1689 })
1690 }
1691
1692 fn new_file_vertical(
1693 workspace: &mut Workspace,
1694 _: &workspace::NewFileSplitVertical,
1695 window: &mut Window,
1696 cx: &mut Context<Workspace>,
1697 ) {
1698 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1699 }
1700
1701 fn new_file_horizontal(
1702 workspace: &mut Workspace,
1703 _: &workspace::NewFileSplitHorizontal,
1704 window: &mut Window,
1705 cx: &mut Context<Workspace>,
1706 ) {
1707 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1708 }
1709
1710 fn new_file_in_direction(
1711 workspace: &mut Workspace,
1712 direction: SplitDirection,
1713 window: &mut Window,
1714 cx: &mut Context<Workspace>,
1715 ) {
1716 let project = workspace.project().clone();
1717 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1718
1719 cx.spawn_in(window, |workspace, mut cx| async move {
1720 let buffer = create.await?;
1721 workspace.update_in(&mut cx, move |workspace, window, cx| {
1722 workspace.split_item(
1723 direction,
1724 Box::new(
1725 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1726 ),
1727 window,
1728 cx,
1729 )
1730 })?;
1731 anyhow::Ok(())
1732 })
1733 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1734 match e.error_code() {
1735 ErrorCode::RemoteUpgradeRequired => Some(format!(
1736 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1737 e.error_tag("required").unwrap_or("the latest version")
1738 )),
1739 _ => None,
1740 }
1741 });
1742 }
1743
1744 pub fn leader_peer_id(&self) -> Option<PeerId> {
1745 self.leader_peer_id
1746 }
1747
1748 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1749 &self.buffer
1750 }
1751
1752 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1753 self.workspace.as_ref()?.0.upgrade()
1754 }
1755
1756 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1757 self.buffer().read(cx).title(cx)
1758 }
1759
1760 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1761 let git_blame_gutter_max_author_length = self
1762 .render_git_blame_gutter(cx)
1763 .then(|| {
1764 if let Some(blame) = self.blame.as_ref() {
1765 let max_author_length =
1766 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1767 Some(max_author_length)
1768 } else {
1769 None
1770 }
1771 })
1772 .flatten();
1773
1774 EditorSnapshot {
1775 mode: self.mode,
1776 show_gutter: self.show_gutter,
1777 show_line_numbers: self.show_line_numbers,
1778 show_git_diff_gutter: self.show_git_diff_gutter,
1779 show_code_actions: self.show_code_actions,
1780 show_runnables: self.show_runnables,
1781 git_blame_gutter_max_author_length,
1782 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1783 scroll_anchor: self.scroll_manager.anchor(),
1784 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1785 placeholder_text: self.placeholder_text.clone(),
1786 is_focused: self.focus_handle.is_focused(window),
1787 current_line_highlight: self
1788 .current_line_highlight
1789 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1790 gutter_hovered: self.gutter_hovered,
1791 }
1792 }
1793
1794 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1795 self.buffer.read(cx).language_at(point, cx)
1796 }
1797
1798 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1799 self.buffer.read(cx).read(cx).file_at(point).cloned()
1800 }
1801
1802 pub fn active_excerpt(
1803 &self,
1804 cx: &App,
1805 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1806 self.buffer
1807 .read(cx)
1808 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1809 }
1810
1811 pub fn mode(&self) -> EditorMode {
1812 self.mode
1813 }
1814
1815 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1816 self.collaboration_hub.as_deref()
1817 }
1818
1819 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1820 self.collaboration_hub = Some(hub);
1821 }
1822
1823 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1824 self.in_project_search = in_project_search;
1825 }
1826
1827 pub fn set_custom_context_menu(
1828 &mut self,
1829 f: impl 'static
1830 + Fn(
1831 &mut Self,
1832 DisplayPoint,
1833 &mut Window,
1834 &mut Context<Self>,
1835 ) -> Option<Entity<ui::ContextMenu>>,
1836 ) {
1837 self.custom_context_menu = Some(Box::new(f))
1838 }
1839
1840 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1841 self.completion_provider = provider;
1842 }
1843
1844 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1845 self.semantics_provider.clone()
1846 }
1847
1848 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1849 self.semantics_provider = provider;
1850 }
1851
1852 pub fn set_edit_prediction_provider<T>(
1853 &mut self,
1854 provider: Option<Entity<T>>,
1855 window: &mut Window,
1856 cx: &mut Context<Self>,
1857 ) where
1858 T: EditPredictionProvider,
1859 {
1860 self.edit_prediction_provider =
1861 provider.map(|provider| RegisteredInlineCompletionProvider {
1862 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1863 if this.focus_handle.is_focused(window) {
1864 this.update_visible_inline_completion(window, cx);
1865 }
1866 }),
1867 provider: Arc::new(provider),
1868 });
1869 self.update_edit_prediction_settings(cx);
1870 self.refresh_inline_completion(false, false, window, cx);
1871 }
1872
1873 pub fn placeholder_text(&self) -> Option<&str> {
1874 self.placeholder_text.as_deref()
1875 }
1876
1877 pub fn set_placeholder_text(
1878 &mut self,
1879 placeholder_text: impl Into<Arc<str>>,
1880 cx: &mut Context<Self>,
1881 ) {
1882 let placeholder_text = Some(placeholder_text.into());
1883 if self.placeholder_text != placeholder_text {
1884 self.placeholder_text = placeholder_text;
1885 cx.notify();
1886 }
1887 }
1888
1889 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1890 self.cursor_shape = cursor_shape;
1891
1892 // Disrupt blink for immediate user feedback that the cursor shape has changed
1893 self.blink_manager.update(cx, BlinkManager::show_cursor);
1894
1895 cx.notify();
1896 }
1897
1898 pub fn set_current_line_highlight(
1899 &mut self,
1900 current_line_highlight: Option<CurrentLineHighlight>,
1901 ) {
1902 self.current_line_highlight = current_line_highlight;
1903 }
1904
1905 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1906 self.collapse_matches = collapse_matches;
1907 }
1908
1909 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1910 let buffers = self.buffer.read(cx).all_buffers();
1911 let Some(project) = self.project.as_ref() else {
1912 return;
1913 };
1914 project.update(cx, |project, cx| {
1915 for buffer in buffers {
1916 self.registered_buffers
1917 .entry(buffer.read(cx).remote_id())
1918 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1919 }
1920 })
1921 }
1922
1923 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1924 if self.collapse_matches {
1925 return range.start..range.start;
1926 }
1927 range.clone()
1928 }
1929
1930 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1931 if self.display_map.read(cx).clip_at_line_ends != clip {
1932 self.display_map
1933 .update(cx, |map, _| map.clip_at_line_ends = clip);
1934 }
1935 }
1936
1937 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1938 self.input_enabled = input_enabled;
1939 }
1940
1941 pub fn set_inline_completions_hidden_for_vim_mode(
1942 &mut self,
1943 hidden: bool,
1944 window: &mut Window,
1945 cx: &mut Context<Self>,
1946 ) {
1947 if hidden != self.inline_completions_hidden_for_vim_mode {
1948 self.inline_completions_hidden_for_vim_mode = hidden;
1949 if hidden {
1950 self.update_visible_inline_completion(window, cx);
1951 } else {
1952 self.refresh_inline_completion(true, false, window, cx);
1953 }
1954 }
1955 }
1956
1957 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1958 self.menu_inline_completions_policy = value;
1959 }
1960
1961 pub fn set_autoindent(&mut self, autoindent: bool) {
1962 if autoindent {
1963 self.autoindent_mode = Some(AutoindentMode::EachLine);
1964 } else {
1965 self.autoindent_mode = None;
1966 }
1967 }
1968
1969 pub fn read_only(&self, cx: &App) -> bool {
1970 self.read_only || self.buffer.read(cx).read_only()
1971 }
1972
1973 pub fn set_read_only(&mut self, read_only: bool) {
1974 self.read_only = read_only;
1975 }
1976
1977 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1978 self.use_autoclose = autoclose;
1979 }
1980
1981 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1982 self.use_auto_surround = auto_surround;
1983 }
1984
1985 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1986 self.auto_replace_emoji_shortcode = auto_replace;
1987 }
1988
1989 pub fn toggle_edit_predictions(
1990 &mut self,
1991 _: &ToggleEditPrediction,
1992 window: &mut Window,
1993 cx: &mut Context<Self>,
1994 ) {
1995 if self.show_inline_completions_override.is_some() {
1996 self.set_show_edit_predictions(None, window, cx);
1997 } else {
1998 let show_edit_predictions = !self.edit_predictions_enabled();
1999 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2000 }
2001 }
2002
2003 pub fn set_show_edit_predictions(
2004 &mut self,
2005 show_edit_predictions: Option<bool>,
2006 window: &mut Window,
2007 cx: &mut Context<Self>,
2008 ) {
2009 self.show_inline_completions_override = show_edit_predictions;
2010 self.update_edit_prediction_settings(cx);
2011
2012 if let Some(false) = show_edit_predictions {
2013 self.discard_inline_completion(false, cx);
2014 } else {
2015 self.refresh_inline_completion(false, true, window, cx);
2016 }
2017 }
2018
2019 fn inline_completions_disabled_in_scope(
2020 &self,
2021 buffer: &Entity<Buffer>,
2022 buffer_position: language::Anchor,
2023 cx: &App,
2024 ) -> bool {
2025 let snapshot = buffer.read(cx).snapshot();
2026 let settings = snapshot.settings_at(buffer_position, cx);
2027
2028 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2029 return false;
2030 };
2031
2032 scope.override_name().map_or(false, |scope_name| {
2033 settings
2034 .edit_predictions_disabled_in
2035 .iter()
2036 .any(|s| s == scope_name)
2037 })
2038 }
2039
2040 pub fn set_use_modal_editing(&mut self, to: bool) {
2041 self.use_modal_editing = to;
2042 }
2043
2044 pub fn use_modal_editing(&self) -> bool {
2045 self.use_modal_editing
2046 }
2047
2048 fn selections_did_change(
2049 &mut self,
2050 local: bool,
2051 old_cursor_position: &Anchor,
2052 show_completions: bool,
2053 window: &mut Window,
2054 cx: &mut Context<Self>,
2055 ) {
2056 window.invalidate_character_coordinates();
2057
2058 // Copy selections to primary selection buffer
2059 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2060 if local {
2061 let selections = self.selections.all::<usize>(cx);
2062 let buffer_handle = self.buffer.read(cx).read(cx);
2063
2064 let mut text = String::new();
2065 for (index, selection) in selections.iter().enumerate() {
2066 let text_for_selection = buffer_handle
2067 .text_for_range(selection.start..selection.end)
2068 .collect::<String>();
2069
2070 text.push_str(&text_for_selection);
2071 if index != selections.len() - 1 {
2072 text.push('\n');
2073 }
2074 }
2075
2076 if !text.is_empty() {
2077 cx.write_to_primary(ClipboardItem::new_string(text));
2078 }
2079 }
2080
2081 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2082 self.buffer.update(cx, |buffer, cx| {
2083 buffer.set_active_selections(
2084 &self.selections.disjoint_anchors(),
2085 self.selections.line_mode,
2086 self.cursor_shape,
2087 cx,
2088 )
2089 });
2090 }
2091 let display_map = self
2092 .display_map
2093 .update(cx, |display_map, cx| display_map.snapshot(cx));
2094 let buffer = &display_map.buffer_snapshot;
2095 self.add_selections_state = None;
2096 self.select_next_state = None;
2097 self.select_prev_state = None;
2098 self.select_larger_syntax_node_stack.clear();
2099 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2100 self.snippet_stack
2101 .invalidate(&self.selections.disjoint_anchors(), buffer);
2102 self.take_rename(false, window, cx);
2103
2104 let new_cursor_position = self.selections.newest_anchor().head();
2105
2106 self.push_to_nav_history(
2107 *old_cursor_position,
2108 Some(new_cursor_position.to_point(buffer)),
2109 cx,
2110 );
2111
2112 if local {
2113 let new_cursor_position = self.selections.newest_anchor().head();
2114 let mut context_menu = self.context_menu.borrow_mut();
2115 let completion_menu = match context_menu.as_ref() {
2116 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2117 _ => {
2118 *context_menu = None;
2119 None
2120 }
2121 };
2122 if let Some(buffer_id) = new_cursor_position.buffer_id {
2123 if !self.registered_buffers.contains_key(&buffer_id) {
2124 if let Some(project) = self.project.as_ref() {
2125 project.update(cx, |project, cx| {
2126 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2127 return;
2128 };
2129 self.registered_buffers.insert(
2130 buffer_id,
2131 project.register_buffer_with_language_servers(&buffer, cx),
2132 );
2133 })
2134 }
2135 }
2136 }
2137
2138 if let Some(completion_menu) = completion_menu {
2139 let cursor_position = new_cursor_position.to_offset(buffer);
2140 let (word_range, kind) =
2141 buffer.surrounding_word(completion_menu.initial_position, true);
2142 if kind == Some(CharKind::Word)
2143 && word_range.to_inclusive().contains(&cursor_position)
2144 {
2145 let mut completion_menu = completion_menu.clone();
2146 drop(context_menu);
2147
2148 let query = Self::completion_query(buffer, cursor_position);
2149 cx.spawn(move |this, mut cx| async move {
2150 completion_menu
2151 .filter(query.as_deref(), cx.background_executor().clone())
2152 .await;
2153
2154 this.update(&mut cx, |this, cx| {
2155 let mut context_menu = this.context_menu.borrow_mut();
2156 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2157 else {
2158 return;
2159 };
2160
2161 if menu.id > completion_menu.id {
2162 return;
2163 }
2164
2165 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2166 drop(context_menu);
2167 cx.notify();
2168 })
2169 })
2170 .detach();
2171
2172 if show_completions {
2173 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2174 }
2175 } else {
2176 drop(context_menu);
2177 self.hide_context_menu(window, cx);
2178 }
2179 } else {
2180 drop(context_menu);
2181 }
2182
2183 hide_hover(self, cx);
2184
2185 if old_cursor_position.to_display_point(&display_map).row()
2186 != new_cursor_position.to_display_point(&display_map).row()
2187 {
2188 self.available_code_actions.take();
2189 }
2190 self.refresh_code_actions(window, cx);
2191 self.refresh_document_highlights(cx);
2192 self.refresh_selected_text_highlights(window, cx);
2193 refresh_matching_bracket_highlights(self, window, cx);
2194 self.update_visible_inline_completion(window, cx);
2195 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2196 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2197 if self.git_blame_inline_enabled {
2198 self.start_inline_blame_timer(window, cx);
2199 }
2200 }
2201
2202 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2203 cx.emit(EditorEvent::SelectionsChanged { local });
2204
2205 let selections = &self.selections.disjoint;
2206 if selections.len() == 1 {
2207 cx.emit(SearchEvent::ActiveMatchChanged)
2208 }
2209 if local
2210 && self.is_singleton(cx)
2211 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2212 {
2213 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2214 let background_executor = cx.background_executor().clone();
2215 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2216 let snapshot = self.buffer().read(cx).snapshot(cx);
2217 let selections = selections.clone();
2218 self.serialize_selections = cx.background_spawn(async move {
2219 background_executor.timer(Duration::from_millis(100)).await;
2220 let selections = selections
2221 .iter()
2222 .map(|selection| {
2223 (
2224 selection.start.to_offset(&snapshot),
2225 selection.end.to_offset(&snapshot),
2226 )
2227 })
2228 .collect();
2229 DB.save_editor_selections(editor_id, workspace_id, selections)
2230 .await
2231 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2232 .log_err();
2233 });
2234 }
2235 }
2236
2237 cx.notify();
2238 }
2239
2240 pub fn sync_selections(
2241 &mut self,
2242 other: Entity<Editor>,
2243 cx: &mut Context<Self>,
2244 ) -> gpui::Subscription {
2245 let other_selections = other.read(cx).selections.disjoint.to_vec();
2246 self.selections.change_with(cx, |selections| {
2247 selections.select_anchors(other_selections);
2248 });
2249
2250 let other_subscription =
2251 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2252 EditorEvent::SelectionsChanged { local: true } => {
2253 let other_selections = other.read(cx).selections.disjoint.to_vec();
2254 if other_selections.is_empty() {
2255 return;
2256 }
2257 this.selections.change_with(cx, |selections| {
2258 selections.select_anchors(other_selections);
2259 });
2260 }
2261 _ => {}
2262 });
2263
2264 let this_subscription =
2265 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2266 EditorEvent::SelectionsChanged { local: true } => {
2267 let these_selections = this.selections.disjoint.to_vec();
2268 if these_selections.is_empty() {
2269 return;
2270 }
2271 other.update(cx, |other_editor, cx| {
2272 other_editor.selections.change_with(cx, |selections| {
2273 selections.select_anchors(these_selections);
2274 })
2275 });
2276 }
2277 _ => {}
2278 });
2279
2280 Subscription::join(other_subscription, this_subscription)
2281 }
2282
2283 pub fn change_selections<R>(
2284 &mut self,
2285 autoscroll: Option<Autoscroll>,
2286 window: &mut Window,
2287 cx: &mut Context<Self>,
2288 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2289 ) -> R {
2290 self.change_selections_inner(autoscroll, true, window, cx, change)
2291 }
2292
2293 fn change_selections_inner<R>(
2294 &mut self,
2295 autoscroll: Option<Autoscroll>,
2296 request_completions: bool,
2297 window: &mut Window,
2298 cx: &mut Context<Self>,
2299 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2300 ) -> R {
2301 let old_cursor_position = self.selections.newest_anchor().head();
2302 self.push_to_selection_history();
2303
2304 let (changed, result) = self.selections.change_with(cx, change);
2305
2306 if changed {
2307 if let Some(autoscroll) = autoscroll {
2308 self.request_autoscroll(autoscroll, cx);
2309 }
2310 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2311
2312 if self.should_open_signature_help_automatically(
2313 &old_cursor_position,
2314 self.signature_help_state.backspace_pressed(),
2315 cx,
2316 ) {
2317 self.show_signature_help(&ShowSignatureHelp, window, cx);
2318 }
2319 self.signature_help_state.set_backspace_pressed(false);
2320 }
2321
2322 result
2323 }
2324
2325 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2326 where
2327 I: IntoIterator<Item = (Range<S>, T)>,
2328 S: ToOffset,
2329 T: Into<Arc<str>>,
2330 {
2331 if self.read_only(cx) {
2332 return;
2333 }
2334
2335 self.buffer
2336 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2337 }
2338
2339 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2340 where
2341 I: IntoIterator<Item = (Range<S>, T)>,
2342 S: ToOffset,
2343 T: Into<Arc<str>>,
2344 {
2345 if self.read_only(cx) {
2346 return;
2347 }
2348
2349 self.buffer.update(cx, |buffer, cx| {
2350 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2351 });
2352 }
2353
2354 pub fn edit_with_block_indent<I, S, T>(
2355 &mut self,
2356 edits: I,
2357 original_start_columns: Vec<u32>,
2358 cx: &mut Context<Self>,
2359 ) where
2360 I: IntoIterator<Item = (Range<S>, T)>,
2361 S: ToOffset,
2362 T: Into<Arc<str>>,
2363 {
2364 if self.read_only(cx) {
2365 return;
2366 }
2367
2368 self.buffer.update(cx, |buffer, cx| {
2369 buffer.edit(
2370 edits,
2371 Some(AutoindentMode::Block {
2372 original_start_columns,
2373 }),
2374 cx,
2375 )
2376 });
2377 }
2378
2379 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2380 self.hide_context_menu(window, cx);
2381
2382 match phase {
2383 SelectPhase::Begin {
2384 position,
2385 add,
2386 click_count,
2387 } => self.begin_selection(position, add, click_count, window, cx),
2388 SelectPhase::BeginColumnar {
2389 position,
2390 goal_column,
2391 reset,
2392 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2393 SelectPhase::Extend {
2394 position,
2395 click_count,
2396 } => self.extend_selection(position, click_count, window, cx),
2397 SelectPhase::Update {
2398 position,
2399 goal_column,
2400 scroll_delta,
2401 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2402 SelectPhase::End => self.end_selection(window, cx),
2403 }
2404 }
2405
2406 fn extend_selection(
2407 &mut self,
2408 position: DisplayPoint,
2409 click_count: usize,
2410 window: &mut Window,
2411 cx: &mut Context<Self>,
2412 ) {
2413 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2414 let tail = self.selections.newest::<usize>(cx).tail();
2415 self.begin_selection(position, false, click_count, window, cx);
2416
2417 let position = position.to_offset(&display_map, Bias::Left);
2418 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2419
2420 let mut pending_selection = self
2421 .selections
2422 .pending_anchor()
2423 .expect("extend_selection not called with pending selection");
2424 if position >= tail {
2425 pending_selection.start = tail_anchor;
2426 } else {
2427 pending_selection.end = tail_anchor;
2428 pending_selection.reversed = true;
2429 }
2430
2431 let mut pending_mode = self.selections.pending_mode().unwrap();
2432 match &mut pending_mode {
2433 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2434 _ => {}
2435 }
2436
2437 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2438 s.set_pending(pending_selection, pending_mode)
2439 });
2440 }
2441
2442 fn begin_selection(
2443 &mut self,
2444 position: DisplayPoint,
2445 add: bool,
2446 click_count: usize,
2447 window: &mut Window,
2448 cx: &mut Context<Self>,
2449 ) {
2450 if !self.focus_handle.is_focused(window) {
2451 self.last_focused_descendant = None;
2452 window.focus(&self.focus_handle);
2453 }
2454
2455 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2456 let buffer = &display_map.buffer_snapshot;
2457 let newest_selection = self.selections.newest_anchor().clone();
2458 let position = display_map.clip_point(position, Bias::Left);
2459
2460 let start;
2461 let end;
2462 let mode;
2463 let mut auto_scroll;
2464 match click_count {
2465 1 => {
2466 start = buffer.anchor_before(position.to_point(&display_map));
2467 end = start;
2468 mode = SelectMode::Character;
2469 auto_scroll = true;
2470 }
2471 2 => {
2472 let range = movement::surrounding_word(&display_map, position);
2473 start = buffer.anchor_before(range.start.to_point(&display_map));
2474 end = buffer.anchor_before(range.end.to_point(&display_map));
2475 mode = SelectMode::Word(start..end);
2476 auto_scroll = true;
2477 }
2478 3 => {
2479 let position = display_map
2480 .clip_point(position, Bias::Left)
2481 .to_point(&display_map);
2482 let line_start = display_map.prev_line_boundary(position).0;
2483 let next_line_start = buffer.clip_point(
2484 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2485 Bias::Left,
2486 );
2487 start = buffer.anchor_before(line_start);
2488 end = buffer.anchor_before(next_line_start);
2489 mode = SelectMode::Line(start..end);
2490 auto_scroll = true;
2491 }
2492 _ => {
2493 start = buffer.anchor_before(0);
2494 end = buffer.anchor_before(buffer.len());
2495 mode = SelectMode::All;
2496 auto_scroll = false;
2497 }
2498 }
2499 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2500
2501 let point_to_delete: Option<usize> = {
2502 let selected_points: Vec<Selection<Point>> =
2503 self.selections.disjoint_in_range(start..end, cx);
2504
2505 if !add || click_count > 1 {
2506 None
2507 } else if !selected_points.is_empty() {
2508 Some(selected_points[0].id)
2509 } else {
2510 let clicked_point_already_selected =
2511 self.selections.disjoint.iter().find(|selection| {
2512 selection.start.to_point(buffer) == start.to_point(buffer)
2513 || selection.end.to_point(buffer) == end.to_point(buffer)
2514 });
2515
2516 clicked_point_already_selected.map(|selection| selection.id)
2517 }
2518 };
2519
2520 let selections_count = self.selections.count();
2521
2522 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2523 if let Some(point_to_delete) = point_to_delete {
2524 s.delete(point_to_delete);
2525
2526 if selections_count == 1 {
2527 s.set_pending_anchor_range(start..end, mode);
2528 }
2529 } else {
2530 if !add {
2531 s.clear_disjoint();
2532 } else if click_count > 1 {
2533 s.delete(newest_selection.id)
2534 }
2535
2536 s.set_pending_anchor_range(start..end, mode);
2537 }
2538 });
2539 }
2540
2541 fn begin_columnar_selection(
2542 &mut self,
2543 position: DisplayPoint,
2544 goal_column: u32,
2545 reset: bool,
2546 window: &mut Window,
2547 cx: &mut Context<Self>,
2548 ) {
2549 if !self.focus_handle.is_focused(window) {
2550 self.last_focused_descendant = None;
2551 window.focus(&self.focus_handle);
2552 }
2553
2554 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2555
2556 if reset {
2557 let pointer_position = display_map
2558 .buffer_snapshot
2559 .anchor_before(position.to_point(&display_map));
2560
2561 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2562 s.clear_disjoint();
2563 s.set_pending_anchor_range(
2564 pointer_position..pointer_position,
2565 SelectMode::Character,
2566 );
2567 });
2568 }
2569
2570 let tail = self.selections.newest::<Point>(cx).tail();
2571 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2572
2573 if !reset {
2574 self.select_columns(
2575 tail.to_display_point(&display_map),
2576 position,
2577 goal_column,
2578 &display_map,
2579 window,
2580 cx,
2581 );
2582 }
2583 }
2584
2585 fn update_selection(
2586 &mut self,
2587 position: DisplayPoint,
2588 goal_column: u32,
2589 scroll_delta: gpui::Point<f32>,
2590 window: &mut Window,
2591 cx: &mut Context<Self>,
2592 ) {
2593 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2594
2595 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2596 let tail = tail.to_display_point(&display_map);
2597 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2598 } else if let Some(mut pending) = self.selections.pending_anchor() {
2599 let buffer = self.buffer.read(cx).snapshot(cx);
2600 let head;
2601 let tail;
2602 let mode = self.selections.pending_mode().unwrap();
2603 match &mode {
2604 SelectMode::Character => {
2605 head = position.to_point(&display_map);
2606 tail = pending.tail().to_point(&buffer);
2607 }
2608 SelectMode::Word(original_range) => {
2609 let original_display_range = original_range.start.to_display_point(&display_map)
2610 ..original_range.end.to_display_point(&display_map);
2611 let original_buffer_range = original_display_range.start.to_point(&display_map)
2612 ..original_display_range.end.to_point(&display_map);
2613 if movement::is_inside_word(&display_map, position)
2614 || original_display_range.contains(&position)
2615 {
2616 let word_range = movement::surrounding_word(&display_map, position);
2617 if word_range.start < original_display_range.start {
2618 head = word_range.start.to_point(&display_map);
2619 } else {
2620 head = word_range.end.to_point(&display_map);
2621 }
2622 } else {
2623 head = position.to_point(&display_map);
2624 }
2625
2626 if head <= original_buffer_range.start {
2627 tail = original_buffer_range.end;
2628 } else {
2629 tail = original_buffer_range.start;
2630 }
2631 }
2632 SelectMode::Line(original_range) => {
2633 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2634
2635 let position = display_map
2636 .clip_point(position, Bias::Left)
2637 .to_point(&display_map);
2638 let line_start = display_map.prev_line_boundary(position).0;
2639 let next_line_start = buffer.clip_point(
2640 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2641 Bias::Left,
2642 );
2643
2644 if line_start < original_range.start {
2645 head = line_start
2646 } else {
2647 head = next_line_start
2648 }
2649
2650 if head <= original_range.start {
2651 tail = original_range.end;
2652 } else {
2653 tail = original_range.start;
2654 }
2655 }
2656 SelectMode::All => {
2657 return;
2658 }
2659 };
2660
2661 if head < tail {
2662 pending.start = buffer.anchor_before(head);
2663 pending.end = buffer.anchor_before(tail);
2664 pending.reversed = true;
2665 } else {
2666 pending.start = buffer.anchor_before(tail);
2667 pending.end = buffer.anchor_before(head);
2668 pending.reversed = false;
2669 }
2670
2671 self.change_selections(None, window, cx, |s| {
2672 s.set_pending(pending, mode);
2673 });
2674 } else {
2675 log::error!("update_selection dispatched with no pending selection");
2676 return;
2677 }
2678
2679 self.apply_scroll_delta(scroll_delta, window, cx);
2680 cx.notify();
2681 }
2682
2683 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2684 self.columnar_selection_tail.take();
2685 if self.selections.pending_anchor().is_some() {
2686 let selections = self.selections.all::<usize>(cx);
2687 self.change_selections(None, window, cx, |s| {
2688 s.select(selections);
2689 s.clear_pending();
2690 });
2691 }
2692 }
2693
2694 fn select_columns(
2695 &mut self,
2696 tail: DisplayPoint,
2697 head: DisplayPoint,
2698 goal_column: u32,
2699 display_map: &DisplaySnapshot,
2700 window: &mut Window,
2701 cx: &mut Context<Self>,
2702 ) {
2703 let start_row = cmp::min(tail.row(), head.row());
2704 let end_row = cmp::max(tail.row(), head.row());
2705 let start_column = cmp::min(tail.column(), goal_column);
2706 let end_column = cmp::max(tail.column(), goal_column);
2707 let reversed = start_column < tail.column();
2708
2709 let selection_ranges = (start_row.0..=end_row.0)
2710 .map(DisplayRow)
2711 .filter_map(|row| {
2712 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2713 let start = display_map
2714 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2715 .to_point(display_map);
2716 let end = display_map
2717 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2718 .to_point(display_map);
2719 if reversed {
2720 Some(end..start)
2721 } else {
2722 Some(start..end)
2723 }
2724 } else {
2725 None
2726 }
2727 })
2728 .collect::<Vec<_>>();
2729
2730 self.change_selections(None, window, cx, |s| {
2731 s.select_ranges(selection_ranges);
2732 });
2733 cx.notify();
2734 }
2735
2736 pub fn has_pending_nonempty_selection(&self) -> bool {
2737 let pending_nonempty_selection = match self.selections.pending_anchor() {
2738 Some(Selection { start, end, .. }) => start != end,
2739 None => false,
2740 };
2741
2742 pending_nonempty_selection
2743 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2744 }
2745
2746 pub fn has_pending_selection(&self) -> bool {
2747 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2748 }
2749
2750 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2751 self.selection_mark_mode = false;
2752
2753 if self.clear_expanded_diff_hunks(cx) {
2754 cx.notify();
2755 return;
2756 }
2757 if self.dismiss_menus_and_popups(true, window, cx) {
2758 return;
2759 }
2760
2761 if self.mode == EditorMode::Full
2762 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2763 {
2764 return;
2765 }
2766
2767 cx.propagate();
2768 }
2769
2770 pub fn dismiss_menus_and_popups(
2771 &mut self,
2772 is_user_requested: bool,
2773 window: &mut Window,
2774 cx: &mut Context<Self>,
2775 ) -> bool {
2776 if self.take_rename(false, window, cx).is_some() {
2777 return true;
2778 }
2779
2780 if hide_hover(self, cx) {
2781 return true;
2782 }
2783
2784 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2785 return true;
2786 }
2787
2788 if self.hide_context_menu(window, cx).is_some() {
2789 return true;
2790 }
2791
2792 if self.mouse_context_menu.take().is_some() {
2793 return true;
2794 }
2795
2796 if is_user_requested && self.discard_inline_completion(true, cx) {
2797 return true;
2798 }
2799
2800 if self.snippet_stack.pop().is_some() {
2801 return true;
2802 }
2803
2804 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2805 self.dismiss_diagnostics(cx);
2806 return true;
2807 }
2808
2809 false
2810 }
2811
2812 fn linked_editing_ranges_for(
2813 &self,
2814 selection: Range<text::Anchor>,
2815 cx: &App,
2816 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2817 if self.linked_edit_ranges.is_empty() {
2818 return None;
2819 }
2820 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2821 selection.end.buffer_id.and_then(|end_buffer_id| {
2822 if selection.start.buffer_id != Some(end_buffer_id) {
2823 return None;
2824 }
2825 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2826 let snapshot = buffer.read(cx).snapshot();
2827 self.linked_edit_ranges
2828 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2829 .map(|ranges| (ranges, snapshot, buffer))
2830 })?;
2831 use text::ToOffset as TO;
2832 // find offset from the start of current range to current cursor position
2833 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2834
2835 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2836 let start_difference = start_offset - start_byte_offset;
2837 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2838 let end_difference = end_offset - start_byte_offset;
2839 // Current range has associated linked ranges.
2840 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2841 for range in linked_ranges.iter() {
2842 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2843 let end_offset = start_offset + end_difference;
2844 let start_offset = start_offset + start_difference;
2845 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2846 continue;
2847 }
2848 if self.selections.disjoint_anchor_ranges().any(|s| {
2849 if s.start.buffer_id != selection.start.buffer_id
2850 || s.end.buffer_id != selection.end.buffer_id
2851 {
2852 return false;
2853 }
2854 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2855 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2856 }) {
2857 continue;
2858 }
2859 let start = buffer_snapshot.anchor_after(start_offset);
2860 let end = buffer_snapshot.anchor_after(end_offset);
2861 linked_edits
2862 .entry(buffer.clone())
2863 .or_default()
2864 .push(start..end);
2865 }
2866 Some(linked_edits)
2867 }
2868
2869 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2870 let text: Arc<str> = text.into();
2871
2872 if self.read_only(cx) {
2873 return;
2874 }
2875
2876 let selections = self.selections.all_adjusted(cx);
2877 let mut bracket_inserted = false;
2878 let mut edits = Vec::new();
2879 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2880 let mut new_selections = Vec::with_capacity(selections.len());
2881 let mut new_autoclose_regions = Vec::new();
2882 let snapshot = self.buffer.read(cx).read(cx);
2883
2884 for (selection, autoclose_region) in
2885 self.selections_with_autoclose_regions(selections, &snapshot)
2886 {
2887 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2888 // Determine if the inserted text matches the opening or closing
2889 // bracket of any of this language's bracket pairs.
2890 let mut bracket_pair = None;
2891 let mut is_bracket_pair_start = false;
2892 let mut is_bracket_pair_end = false;
2893 if !text.is_empty() {
2894 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2895 // and they are removing the character that triggered IME popup.
2896 for (pair, enabled) in scope.brackets() {
2897 if !pair.close && !pair.surround {
2898 continue;
2899 }
2900
2901 if enabled && pair.start.ends_with(text.as_ref()) {
2902 let prefix_len = pair.start.len() - text.len();
2903 let preceding_text_matches_prefix = prefix_len == 0
2904 || (selection.start.column >= (prefix_len as u32)
2905 && snapshot.contains_str_at(
2906 Point::new(
2907 selection.start.row,
2908 selection.start.column - (prefix_len as u32),
2909 ),
2910 &pair.start[..prefix_len],
2911 ));
2912 if preceding_text_matches_prefix {
2913 bracket_pair = Some(pair.clone());
2914 is_bracket_pair_start = true;
2915 break;
2916 }
2917 }
2918 if pair.end.as_str() == text.as_ref() {
2919 bracket_pair = Some(pair.clone());
2920 is_bracket_pair_end = true;
2921 break;
2922 }
2923 }
2924 }
2925
2926 if let Some(bracket_pair) = bracket_pair {
2927 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
2928 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2929 let auto_surround =
2930 self.use_auto_surround && snapshot_settings.use_auto_surround;
2931 if selection.is_empty() {
2932 if is_bracket_pair_start {
2933 // If the inserted text is a suffix of an opening bracket and the
2934 // selection is preceded by the rest of the opening bracket, then
2935 // insert the closing bracket.
2936 let following_text_allows_autoclose = snapshot
2937 .chars_at(selection.start)
2938 .next()
2939 .map_or(true, |c| scope.should_autoclose_before(c));
2940
2941 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2942 && bracket_pair.start.len() == 1
2943 {
2944 let target = bracket_pair.start.chars().next().unwrap();
2945 let current_line_count = snapshot
2946 .reversed_chars_at(selection.start)
2947 .take_while(|&c| c != '\n')
2948 .filter(|&c| c == target)
2949 .count();
2950 current_line_count % 2 == 1
2951 } else {
2952 false
2953 };
2954
2955 if autoclose
2956 && bracket_pair.close
2957 && following_text_allows_autoclose
2958 && !is_closing_quote
2959 {
2960 let anchor = snapshot.anchor_before(selection.end);
2961 new_selections.push((selection.map(|_| anchor), text.len()));
2962 new_autoclose_regions.push((
2963 anchor,
2964 text.len(),
2965 selection.id,
2966 bracket_pair.clone(),
2967 ));
2968 edits.push((
2969 selection.range(),
2970 format!("{}{}", text, bracket_pair.end).into(),
2971 ));
2972 bracket_inserted = true;
2973 continue;
2974 }
2975 }
2976
2977 if let Some(region) = autoclose_region {
2978 // If the selection is followed by an auto-inserted closing bracket,
2979 // then don't insert that closing bracket again; just move the selection
2980 // past the closing bracket.
2981 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2982 && text.as_ref() == region.pair.end.as_str();
2983 if should_skip {
2984 let anchor = snapshot.anchor_after(selection.end);
2985 new_selections
2986 .push((selection.map(|_| anchor), region.pair.end.len()));
2987 continue;
2988 }
2989 }
2990
2991 let always_treat_brackets_as_autoclosed = snapshot
2992 .language_settings_at(selection.start, cx)
2993 .always_treat_brackets_as_autoclosed;
2994 if always_treat_brackets_as_autoclosed
2995 && is_bracket_pair_end
2996 && snapshot.contains_str_at(selection.end, text.as_ref())
2997 {
2998 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2999 // and the inserted text is a closing bracket and the selection is followed
3000 // by the closing bracket then move the selection past the closing bracket.
3001 let anchor = snapshot.anchor_after(selection.end);
3002 new_selections.push((selection.map(|_| anchor), text.len()));
3003 continue;
3004 }
3005 }
3006 // If an opening bracket is 1 character long and is typed while
3007 // text is selected, then surround that text with the bracket pair.
3008 else if auto_surround
3009 && bracket_pair.surround
3010 && is_bracket_pair_start
3011 && bracket_pair.start.chars().count() == 1
3012 {
3013 edits.push((selection.start..selection.start, text.clone()));
3014 edits.push((
3015 selection.end..selection.end,
3016 bracket_pair.end.as_str().into(),
3017 ));
3018 bracket_inserted = true;
3019 new_selections.push((
3020 Selection {
3021 id: selection.id,
3022 start: snapshot.anchor_after(selection.start),
3023 end: snapshot.anchor_before(selection.end),
3024 reversed: selection.reversed,
3025 goal: selection.goal,
3026 },
3027 0,
3028 ));
3029 continue;
3030 }
3031 }
3032 }
3033
3034 if self.auto_replace_emoji_shortcode
3035 && selection.is_empty()
3036 && text.as_ref().ends_with(':')
3037 {
3038 if let Some(possible_emoji_short_code) =
3039 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3040 {
3041 if !possible_emoji_short_code.is_empty() {
3042 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3043 let emoji_shortcode_start = Point::new(
3044 selection.start.row,
3045 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3046 );
3047
3048 // Remove shortcode from buffer
3049 edits.push((
3050 emoji_shortcode_start..selection.start,
3051 "".to_string().into(),
3052 ));
3053 new_selections.push((
3054 Selection {
3055 id: selection.id,
3056 start: snapshot.anchor_after(emoji_shortcode_start),
3057 end: snapshot.anchor_before(selection.start),
3058 reversed: selection.reversed,
3059 goal: selection.goal,
3060 },
3061 0,
3062 ));
3063
3064 // Insert emoji
3065 let selection_start_anchor = snapshot.anchor_after(selection.start);
3066 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3067 edits.push((selection.start..selection.end, emoji.to_string().into()));
3068
3069 continue;
3070 }
3071 }
3072 }
3073 }
3074
3075 // If not handling any auto-close operation, then just replace the selected
3076 // text with the given input and move the selection to the end of the
3077 // newly inserted text.
3078 let anchor = snapshot.anchor_after(selection.end);
3079 if !self.linked_edit_ranges.is_empty() {
3080 let start_anchor = snapshot.anchor_before(selection.start);
3081
3082 let is_word_char = text.chars().next().map_or(true, |char| {
3083 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3084 classifier.is_word(char)
3085 });
3086
3087 if is_word_char {
3088 if let Some(ranges) = self
3089 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3090 {
3091 for (buffer, edits) in ranges {
3092 linked_edits
3093 .entry(buffer.clone())
3094 .or_default()
3095 .extend(edits.into_iter().map(|range| (range, text.clone())));
3096 }
3097 }
3098 }
3099 }
3100
3101 new_selections.push((selection.map(|_| anchor), 0));
3102 edits.push((selection.start..selection.end, text.clone()));
3103 }
3104
3105 drop(snapshot);
3106
3107 self.transact(window, cx, |this, window, cx| {
3108 let initial_buffer_versions =
3109 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3110
3111 this.buffer.update(cx, |buffer, cx| {
3112 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3113 });
3114 for (buffer, edits) in linked_edits {
3115 buffer.update(cx, |buffer, cx| {
3116 let snapshot = buffer.snapshot();
3117 let edits = edits
3118 .into_iter()
3119 .map(|(range, text)| {
3120 use text::ToPoint as TP;
3121 let end_point = TP::to_point(&range.end, &snapshot);
3122 let start_point = TP::to_point(&range.start, &snapshot);
3123 (start_point..end_point, text)
3124 })
3125 .sorted_by_key(|(range, _)| range.start)
3126 .collect::<Vec<_>>();
3127 buffer.edit(edits, None, cx);
3128 })
3129 }
3130 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3131 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3132 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3133 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3134 .zip(new_selection_deltas)
3135 .map(|(selection, delta)| Selection {
3136 id: selection.id,
3137 start: selection.start + delta,
3138 end: selection.end + delta,
3139 reversed: selection.reversed,
3140 goal: SelectionGoal::None,
3141 })
3142 .collect::<Vec<_>>();
3143
3144 let mut i = 0;
3145 for (position, delta, selection_id, pair) in new_autoclose_regions {
3146 let position = position.to_offset(&map.buffer_snapshot) + delta;
3147 let start = map.buffer_snapshot.anchor_before(position);
3148 let end = map.buffer_snapshot.anchor_after(position);
3149 while let Some(existing_state) = this.autoclose_regions.get(i) {
3150 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3151 Ordering::Less => i += 1,
3152 Ordering::Greater => break,
3153 Ordering::Equal => {
3154 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3155 Ordering::Less => i += 1,
3156 Ordering::Equal => break,
3157 Ordering::Greater => break,
3158 }
3159 }
3160 }
3161 }
3162 this.autoclose_regions.insert(
3163 i,
3164 AutocloseRegion {
3165 selection_id,
3166 range: start..end,
3167 pair,
3168 },
3169 );
3170 }
3171
3172 let had_active_inline_completion = this.has_active_inline_completion();
3173 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3174 s.select(new_selections)
3175 });
3176
3177 if !bracket_inserted {
3178 if let Some(on_type_format_task) =
3179 this.trigger_on_type_formatting(text.to_string(), window, cx)
3180 {
3181 on_type_format_task.detach_and_log_err(cx);
3182 }
3183 }
3184
3185 let editor_settings = EditorSettings::get_global(cx);
3186 if bracket_inserted
3187 && (editor_settings.auto_signature_help
3188 || editor_settings.show_signature_help_after_edits)
3189 {
3190 this.show_signature_help(&ShowSignatureHelp, window, cx);
3191 }
3192
3193 let trigger_in_words =
3194 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3195 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3196 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3197 this.refresh_inline_completion(true, false, window, cx);
3198 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3199 });
3200 }
3201
3202 fn find_possible_emoji_shortcode_at_position(
3203 snapshot: &MultiBufferSnapshot,
3204 position: Point,
3205 ) -> Option<String> {
3206 let mut chars = Vec::new();
3207 let mut found_colon = false;
3208 for char in snapshot.reversed_chars_at(position).take(100) {
3209 // Found a possible emoji shortcode in the middle of the buffer
3210 if found_colon {
3211 if char.is_whitespace() {
3212 chars.reverse();
3213 return Some(chars.iter().collect());
3214 }
3215 // If the previous character is not a whitespace, we are in the middle of a word
3216 // and we only want to complete the shortcode if the word is made up of other emojis
3217 let mut containing_word = String::new();
3218 for ch in snapshot
3219 .reversed_chars_at(position)
3220 .skip(chars.len() + 1)
3221 .take(100)
3222 {
3223 if ch.is_whitespace() {
3224 break;
3225 }
3226 containing_word.push(ch);
3227 }
3228 let containing_word = containing_word.chars().rev().collect::<String>();
3229 if util::word_consists_of_emojis(containing_word.as_str()) {
3230 chars.reverse();
3231 return Some(chars.iter().collect());
3232 }
3233 }
3234
3235 if char.is_whitespace() || !char.is_ascii() {
3236 return None;
3237 }
3238 if char == ':' {
3239 found_colon = true;
3240 } else {
3241 chars.push(char);
3242 }
3243 }
3244 // Found a possible emoji shortcode at the beginning of the buffer
3245 chars.reverse();
3246 Some(chars.iter().collect())
3247 }
3248
3249 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3250 self.transact(window, cx, |this, window, cx| {
3251 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3252 let selections = this.selections.all::<usize>(cx);
3253 let multi_buffer = this.buffer.read(cx);
3254 let buffer = multi_buffer.snapshot(cx);
3255 selections
3256 .iter()
3257 .map(|selection| {
3258 let start_point = selection.start.to_point(&buffer);
3259 let mut indent =
3260 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3261 indent.len = cmp::min(indent.len, start_point.column);
3262 let start = selection.start;
3263 let end = selection.end;
3264 let selection_is_empty = start == end;
3265 let language_scope = buffer.language_scope_at(start);
3266 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3267 &language_scope
3268 {
3269 let insert_extra_newline =
3270 insert_extra_newline_brackets(&buffer, start..end, language)
3271 || insert_extra_newline_tree_sitter(&buffer, start..end);
3272
3273 // Comment extension on newline is allowed only for cursor selections
3274 let comment_delimiter = maybe!({
3275 if !selection_is_empty {
3276 return None;
3277 }
3278
3279 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3280 return None;
3281 }
3282
3283 let delimiters = language.line_comment_prefixes();
3284 let max_len_of_delimiter =
3285 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3286 let (snapshot, range) =
3287 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3288
3289 let mut index_of_first_non_whitespace = 0;
3290 let comment_candidate = snapshot
3291 .chars_for_range(range)
3292 .skip_while(|c| {
3293 let should_skip = c.is_whitespace();
3294 if should_skip {
3295 index_of_first_non_whitespace += 1;
3296 }
3297 should_skip
3298 })
3299 .take(max_len_of_delimiter)
3300 .collect::<String>();
3301 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3302 comment_candidate.starts_with(comment_prefix.as_ref())
3303 })?;
3304 let cursor_is_placed_after_comment_marker =
3305 index_of_first_non_whitespace + comment_prefix.len()
3306 <= start_point.column as usize;
3307 if cursor_is_placed_after_comment_marker {
3308 Some(comment_prefix.clone())
3309 } else {
3310 None
3311 }
3312 });
3313 (comment_delimiter, insert_extra_newline)
3314 } else {
3315 (None, false)
3316 };
3317
3318 let capacity_for_delimiter = comment_delimiter
3319 .as_deref()
3320 .map(str::len)
3321 .unwrap_or_default();
3322 let mut new_text =
3323 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3324 new_text.push('\n');
3325 new_text.extend(indent.chars());
3326 if let Some(delimiter) = &comment_delimiter {
3327 new_text.push_str(delimiter);
3328 }
3329 if insert_extra_newline {
3330 new_text = new_text.repeat(2);
3331 }
3332
3333 let anchor = buffer.anchor_after(end);
3334 let new_selection = selection.map(|_| anchor);
3335 (
3336 (start..end, new_text),
3337 (insert_extra_newline, new_selection),
3338 )
3339 })
3340 .unzip()
3341 };
3342
3343 this.edit_with_autoindent(edits, cx);
3344 let buffer = this.buffer.read(cx).snapshot(cx);
3345 let new_selections = selection_fixup_info
3346 .into_iter()
3347 .map(|(extra_newline_inserted, new_selection)| {
3348 let mut cursor = new_selection.end.to_point(&buffer);
3349 if extra_newline_inserted {
3350 cursor.row -= 1;
3351 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3352 }
3353 new_selection.map(|_| cursor)
3354 })
3355 .collect();
3356
3357 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3358 s.select(new_selections)
3359 });
3360 this.refresh_inline_completion(true, false, window, cx);
3361 });
3362 }
3363
3364 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3365 let buffer = self.buffer.read(cx);
3366 let snapshot = buffer.snapshot(cx);
3367
3368 let mut edits = Vec::new();
3369 let mut rows = Vec::new();
3370
3371 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3372 let cursor = selection.head();
3373 let row = cursor.row;
3374
3375 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3376
3377 let newline = "\n".to_string();
3378 edits.push((start_of_line..start_of_line, newline));
3379
3380 rows.push(row + rows_inserted as u32);
3381 }
3382
3383 self.transact(window, cx, |editor, window, cx| {
3384 editor.edit(edits, cx);
3385
3386 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3387 let mut index = 0;
3388 s.move_cursors_with(|map, _, _| {
3389 let row = rows[index];
3390 index += 1;
3391
3392 let point = Point::new(row, 0);
3393 let boundary = map.next_line_boundary(point).1;
3394 let clipped = map.clip_point(boundary, Bias::Left);
3395
3396 (clipped, SelectionGoal::None)
3397 });
3398 });
3399
3400 let mut indent_edits = Vec::new();
3401 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3402 for row in rows {
3403 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3404 for (row, indent) in indents {
3405 if indent.len == 0 {
3406 continue;
3407 }
3408
3409 let text = match indent.kind {
3410 IndentKind::Space => " ".repeat(indent.len as usize),
3411 IndentKind::Tab => "\t".repeat(indent.len as usize),
3412 };
3413 let point = Point::new(row.0, 0);
3414 indent_edits.push((point..point, text));
3415 }
3416 }
3417 editor.edit(indent_edits, cx);
3418 });
3419 }
3420
3421 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3422 let buffer = self.buffer.read(cx);
3423 let snapshot = buffer.snapshot(cx);
3424
3425 let mut edits = Vec::new();
3426 let mut rows = Vec::new();
3427 let mut rows_inserted = 0;
3428
3429 for selection in self.selections.all_adjusted(cx) {
3430 let cursor = selection.head();
3431 let row = cursor.row;
3432
3433 let point = Point::new(row + 1, 0);
3434 let start_of_line = snapshot.clip_point(point, Bias::Left);
3435
3436 let newline = "\n".to_string();
3437 edits.push((start_of_line..start_of_line, newline));
3438
3439 rows_inserted += 1;
3440 rows.push(row + rows_inserted);
3441 }
3442
3443 self.transact(window, cx, |editor, window, cx| {
3444 editor.edit(edits, cx);
3445
3446 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3447 let mut index = 0;
3448 s.move_cursors_with(|map, _, _| {
3449 let row = rows[index];
3450 index += 1;
3451
3452 let point = Point::new(row, 0);
3453 let boundary = map.next_line_boundary(point).1;
3454 let clipped = map.clip_point(boundary, Bias::Left);
3455
3456 (clipped, SelectionGoal::None)
3457 });
3458 });
3459
3460 let mut indent_edits = Vec::new();
3461 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3462 for row in rows {
3463 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3464 for (row, indent) in indents {
3465 if indent.len == 0 {
3466 continue;
3467 }
3468
3469 let text = match indent.kind {
3470 IndentKind::Space => " ".repeat(indent.len as usize),
3471 IndentKind::Tab => "\t".repeat(indent.len as usize),
3472 };
3473 let point = Point::new(row.0, 0);
3474 indent_edits.push((point..point, text));
3475 }
3476 }
3477 editor.edit(indent_edits, cx);
3478 });
3479 }
3480
3481 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3482 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3483 original_start_columns: Vec::new(),
3484 });
3485 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3486 }
3487
3488 fn insert_with_autoindent_mode(
3489 &mut self,
3490 text: &str,
3491 autoindent_mode: Option<AutoindentMode>,
3492 window: &mut Window,
3493 cx: &mut Context<Self>,
3494 ) {
3495 if self.read_only(cx) {
3496 return;
3497 }
3498
3499 let text: Arc<str> = text.into();
3500 self.transact(window, cx, |this, window, cx| {
3501 let old_selections = this.selections.all_adjusted(cx);
3502 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3503 let anchors = {
3504 let snapshot = buffer.read(cx);
3505 old_selections
3506 .iter()
3507 .map(|s| {
3508 let anchor = snapshot.anchor_after(s.head());
3509 s.map(|_| anchor)
3510 })
3511 .collect::<Vec<_>>()
3512 };
3513 buffer.edit(
3514 old_selections
3515 .iter()
3516 .map(|s| (s.start..s.end, text.clone())),
3517 autoindent_mode,
3518 cx,
3519 );
3520 anchors
3521 });
3522
3523 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3524 s.select_anchors(selection_anchors);
3525 });
3526
3527 cx.notify();
3528 });
3529 }
3530
3531 fn trigger_completion_on_input(
3532 &mut self,
3533 text: &str,
3534 trigger_in_words: bool,
3535 window: &mut Window,
3536 cx: &mut Context<Self>,
3537 ) {
3538 if self.is_completion_trigger(text, trigger_in_words, cx) {
3539 self.show_completions(
3540 &ShowCompletions {
3541 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3542 },
3543 window,
3544 cx,
3545 );
3546 } else {
3547 self.hide_context_menu(window, cx);
3548 }
3549 }
3550
3551 fn is_completion_trigger(
3552 &self,
3553 text: &str,
3554 trigger_in_words: bool,
3555 cx: &mut Context<Self>,
3556 ) -> bool {
3557 let position = self.selections.newest_anchor().head();
3558 let multibuffer = self.buffer.read(cx);
3559 let Some(buffer) = position
3560 .buffer_id
3561 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3562 else {
3563 return false;
3564 };
3565
3566 if let Some(completion_provider) = &self.completion_provider {
3567 completion_provider.is_completion_trigger(
3568 &buffer,
3569 position.text_anchor,
3570 text,
3571 trigger_in_words,
3572 cx,
3573 )
3574 } else {
3575 false
3576 }
3577 }
3578
3579 /// If any empty selections is touching the start of its innermost containing autoclose
3580 /// region, expand it to select the brackets.
3581 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3582 let selections = self.selections.all::<usize>(cx);
3583 let buffer = self.buffer.read(cx).read(cx);
3584 let new_selections = self
3585 .selections_with_autoclose_regions(selections, &buffer)
3586 .map(|(mut selection, region)| {
3587 if !selection.is_empty() {
3588 return selection;
3589 }
3590
3591 if let Some(region) = region {
3592 let mut range = region.range.to_offset(&buffer);
3593 if selection.start == range.start && range.start >= region.pair.start.len() {
3594 range.start -= region.pair.start.len();
3595 if buffer.contains_str_at(range.start, ®ion.pair.start)
3596 && buffer.contains_str_at(range.end, ®ion.pair.end)
3597 {
3598 range.end += region.pair.end.len();
3599 selection.start = range.start;
3600 selection.end = range.end;
3601
3602 return selection;
3603 }
3604 }
3605 }
3606
3607 let always_treat_brackets_as_autoclosed = buffer
3608 .language_settings_at(selection.start, cx)
3609 .always_treat_brackets_as_autoclosed;
3610
3611 if !always_treat_brackets_as_autoclosed {
3612 return selection;
3613 }
3614
3615 if let Some(scope) = buffer.language_scope_at(selection.start) {
3616 for (pair, enabled) in scope.brackets() {
3617 if !enabled || !pair.close {
3618 continue;
3619 }
3620
3621 if buffer.contains_str_at(selection.start, &pair.end) {
3622 let pair_start_len = pair.start.len();
3623 if buffer.contains_str_at(
3624 selection.start.saturating_sub(pair_start_len),
3625 &pair.start,
3626 ) {
3627 selection.start -= pair_start_len;
3628 selection.end += pair.end.len();
3629
3630 return selection;
3631 }
3632 }
3633 }
3634 }
3635
3636 selection
3637 })
3638 .collect();
3639
3640 drop(buffer);
3641 self.change_selections(None, window, cx, |selections| {
3642 selections.select(new_selections)
3643 });
3644 }
3645
3646 /// Iterate the given selections, and for each one, find the smallest surrounding
3647 /// autoclose region. This uses the ordering of the selections and the autoclose
3648 /// regions to avoid repeated comparisons.
3649 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3650 &'a self,
3651 selections: impl IntoIterator<Item = Selection<D>>,
3652 buffer: &'a MultiBufferSnapshot,
3653 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3654 let mut i = 0;
3655 let mut regions = self.autoclose_regions.as_slice();
3656 selections.into_iter().map(move |selection| {
3657 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3658
3659 let mut enclosing = None;
3660 while let Some(pair_state) = regions.get(i) {
3661 if pair_state.range.end.to_offset(buffer) < range.start {
3662 regions = ®ions[i + 1..];
3663 i = 0;
3664 } else if pair_state.range.start.to_offset(buffer) > range.end {
3665 break;
3666 } else {
3667 if pair_state.selection_id == selection.id {
3668 enclosing = Some(pair_state);
3669 }
3670 i += 1;
3671 }
3672 }
3673
3674 (selection, enclosing)
3675 })
3676 }
3677
3678 /// Remove any autoclose regions that no longer contain their selection.
3679 fn invalidate_autoclose_regions(
3680 &mut self,
3681 mut selections: &[Selection<Anchor>],
3682 buffer: &MultiBufferSnapshot,
3683 ) {
3684 self.autoclose_regions.retain(|state| {
3685 let mut i = 0;
3686 while let Some(selection) = selections.get(i) {
3687 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3688 selections = &selections[1..];
3689 continue;
3690 }
3691 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3692 break;
3693 }
3694 if selection.id == state.selection_id {
3695 return true;
3696 } else {
3697 i += 1;
3698 }
3699 }
3700 false
3701 });
3702 }
3703
3704 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3705 let offset = position.to_offset(buffer);
3706 let (word_range, kind) = buffer.surrounding_word(offset, true);
3707 if offset > word_range.start && kind == Some(CharKind::Word) {
3708 Some(
3709 buffer
3710 .text_for_range(word_range.start..offset)
3711 .collect::<String>(),
3712 )
3713 } else {
3714 None
3715 }
3716 }
3717
3718 pub fn toggle_inlay_hints(
3719 &mut self,
3720 _: &ToggleInlayHints,
3721 _: &mut Window,
3722 cx: &mut Context<Self>,
3723 ) {
3724 self.refresh_inlay_hints(
3725 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3726 cx,
3727 );
3728 }
3729
3730 pub fn inlay_hints_enabled(&self) -> bool {
3731 self.inlay_hint_cache.enabled
3732 }
3733
3734 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3735 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3736 return;
3737 }
3738
3739 let reason_description = reason.description();
3740 let ignore_debounce = matches!(
3741 reason,
3742 InlayHintRefreshReason::SettingsChange(_)
3743 | InlayHintRefreshReason::Toggle(_)
3744 | InlayHintRefreshReason::ExcerptsRemoved(_)
3745 | InlayHintRefreshReason::ModifiersChanged(_)
3746 );
3747 let (invalidate_cache, required_languages) = match reason {
3748 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3749 match self.inlay_hint_cache.modifiers_override(enabled) {
3750 Some(enabled) => {
3751 if enabled {
3752 (InvalidationStrategy::RefreshRequested, None)
3753 } else {
3754 self.splice_inlays(
3755 &self
3756 .visible_inlay_hints(cx)
3757 .iter()
3758 .map(|inlay| inlay.id)
3759 .collect::<Vec<InlayId>>(),
3760 Vec::new(),
3761 cx,
3762 );
3763 return;
3764 }
3765 }
3766 None => return,
3767 }
3768 }
3769 InlayHintRefreshReason::Toggle(enabled) => {
3770 if self.inlay_hint_cache.toggle(enabled) {
3771 if enabled {
3772 (InvalidationStrategy::RefreshRequested, None)
3773 } else {
3774 self.splice_inlays(
3775 &self
3776 .visible_inlay_hints(cx)
3777 .iter()
3778 .map(|inlay| inlay.id)
3779 .collect::<Vec<InlayId>>(),
3780 Vec::new(),
3781 cx,
3782 );
3783 return;
3784 }
3785 } else {
3786 return;
3787 }
3788 }
3789 InlayHintRefreshReason::SettingsChange(new_settings) => {
3790 match self.inlay_hint_cache.update_settings(
3791 &self.buffer,
3792 new_settings,
3793 self.visible_inlay_hints(cx),
3794 cx,
3795 ) {
3796 ControlFlow::Break(Some(InlaySplice {
3797 to_remove,
3798 to_insert,
3799 })) => {
3800 self.splice_inlays(&to_remove, to_insert, cx);
3801 return;
3802 }
3803 ControlFlow::Break(None) => return,
3804 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3805 }
3806 }
3807 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3808 if let Some(InlaySplice {
3809 to_remove,
3810 to_insert,
3811 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3812 {
3813 self.splice_inlays(&to_remove, to_insert, cx);
3814 }
3815 return;
3816 }
3817 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3818 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3819 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3820 }
3821 InlayHintRefreshReason::RefreshRequested => {
3822 (InvalidationStrategy::RefreshRequested, None)
3823 }
3824 };
3825
3826 if let Some(InlaySplice {
3827 to_remove,
3828 to_insert,
3829 }) = self.inlay_hint_cache.spawn_hint_refresh(
3830 reason_description,
3831 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3832 invalidate_cache,
3833 ignore_debounce,
3834 cx,
3835 ) {
3836 self.splice_inlays(&to_remove, to_insert, cx);
3837 }
3838 }
3839
3840 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3841 self.display_map
3842 .read(cx)
3843 .current_inlays()
3844 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3845 .cloned()
3846 .collect()
3847 }
3848
3849 pub fn excerpts_for_inlay_hints_query(
3850 &self,
3851 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3852 cx: &mut Context<Editor>,
3853 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3854 let Some(project) = self.project.as_ref() else {
3855 return HashMap::default();
3856 };
3857 let project = project.read(cx);
3858 let multi_buffer = self.buffer().read(cx);
3859 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3860 let multi_buffer_visible_start = self
3861 .scroll_manager
3862 .anchor()
3863 .anchor
3864 .to_point(&multi_buffer_snapshot);
3865 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3866 multi_buffer_visible_start
3867 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3868 Bias::Left,
3869 );
3870 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3871 multi_buffer_snapshot
3872 .range_to_buffer_ranges(multi_buffer_visible_range)
3873 .into_iter()
3874 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3875 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3876 let buffer_file = project::File::from_dyn(buffer.file())?;
3877 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3878 let worktree_entry = buffer_worktree
3879 .read(cx)
3880 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3881 if worktree_entry.is_ignored {
3882 return None;
3883 }
3884
3885 let language = buffer.language()?;
3886 if let Some(restrict_to_languages) = restrict_to_languages {
3887 if !restrict_to_languages.contains(language) {
3888 return None;
3889 }
3890 }
3891 Some((
3892 excerpt_id,
3893 (
3894 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3895 buffer.version().clone(),
3896 excerpt_visible_range,
3897 ),
3898 ))
3899 })
3900 .collect()
3901 }
3902
3903 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3904 TextLayoutDetails {
3905 text_system: window.text_system().clone(),
3906 editor_style: self.style.clone().unwrap(),
3907 rem_size: window.rem_size(),
3908 scroll_anchor: self.scroll_manager.anchor(),
3909 visible_rows: self.visible_line_count(),
3910 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3911 }
3912 }
3913
3914 pub fn splice_inlays(
3915 &self,
3916 to_remove: &[InlayId],
3917 to_insert: Vec<Inlay>,
3918 cx: &mut Context<Self>,
3919 ) {
3920 self.display_map.update(cx, |display_map, cx| {
3921 display_map.splice_inlays(to_remove, to_insert, cx)
3922 });
3923 cx.notify();
3924 }
3925
3926 fn trigger_on_type_formatting(
3927 &self,
3928 input: String,
3929 window: &mut Window,
3930 cx: &mut Context<Self>,
3931 ) -> Option<Task<Result<()>>> {
3932 if input.len() != 1 {
3933 return None;
3934 }
3935
3936 let project = self.project.as_ref()?;
3937 let position = self.selections.newest_anchor().head();
3938 let (buffer, buffer_position) = self
3939 .buffer
3940 .read(cx)
3941 .text_anchor_for_position(position, cx)?;
3942
3943 let settings = language_settings::language_settings(
3944 buffer
3945 .read(cx)
3946 .language_at(buffer_position)
3947 .map(|l| l.name()),
3948 buffer.read(cx).file(),
3949 cx,
3950 );
3951 if !settings.use_on_type_format {
3952 return None;
3953 }
3954
3955 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3956 // hence we do LSP request & edit on host side only — add formats to host's history.
3957 let push_to_lsp_host_history = true;
3958 // If this is not the host, append its history with new edits.
3959 let push_to_client_history = project.read(cx).is_via_collab();
3960
3961 let on_type_formatting = project.update(cx, |project, cx| {
3962 project.on_type_format(
3963 buffer.clone(),
3964 buffer_position,
3965 input,
3966 push_to_lsp_host_history,
3967 cx,
3968 )
3969 });
3970 Some(cx.spawn_in(window, |editor, mut cx| async move {
3971 if let Some(transaction) = on_type_formatting.await? {
3972 if push_to_client_history {
3973 buffer
3974 .update(&mut cx, |buffer, _| {
3975 buffer.push_transaction(transaction, Instant::now());
3976 })
3977 .ok();
3978 }
3979 editor.update(&mut cx, |editor, cx| {
3980 editor.refresh_document_highlights(cx);
3981 })?;
3982 }
3983 Ok(())
3984 }))
3985 }
3986
3987 pub fn show_completions(
3988 &mut self,
3989 options: &ShowCompletions,
3990 window: &mut Window,
3991 cx: &mut Context<Self>,
3992 ) {
3993 if self.pending_rename.is_some() {
3994 return;
3995 }
3996
3997 let Some(provider) = self.completion_provider.as_ref() else {
3998 return;
3999 };
4000
4001 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4002 return;
4003 }
4004
4005 let position = self.selections.newest_anchor().head();
4006 if position.diff_base_anchor.is_some() {
4007 return;
4008 }
4009 let (buffer, buffer_position) =
4010 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4011 output
4012 } else {
4013 return;
4014 };
4015 let show_completion_documentation = buffer
4016 .read(cx)
4017 .snapshot()
4018 .settings_at(buffer_position, cx)
4019 .show_completion_documentation;
4020
4021 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4022
4023 let trigger_kind = match &options.trigger {
4024 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4025 CompletionTriggerKind::TRIGGER_CHARACTER
4026 }
4027 _ => CompletionTriggerKind::INVOKED,
4028 };
4029 let completion_context = CompletionContext {
4030 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4031 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4032 Some(String::from(trigger))
4033 } else {
4034 None
4035 }
4036 }),
4037 trigger_kind,
4038 };
4039 let completions =
4040 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4041 let sort_completions = provider.sort_completions();
4042
4043 let id = post_inc(&mut self.next_completion_id);
4044 let task = cx.spawn_in(window, |editor, mut cx| {
4045 async move {
4046 editor.update(&mut cx, |this, _| {
4047 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4048 })?;
4049 let completions = completions.await.log_err();
4050 let menu = if let Some(completions) = completions {
4051 let mut menu = CompletionsMenu::new(
4052 id,
4053 sort_completions,
4054 show_completion_documentation,
4055 position,
4056 buffer.clone(),
4057 completions.into(),
4058 );
4059
4060 menu.filter(query.as_deref(), cx.background_executor().clone())
4061 .await;
4062
4063 menu.visible().then_some(menu)
4064 } else {
4065 None
4066 };
4067
4068 editor.update_in(&mut cx, |editor, window, cx| {
4069 match editor.context_menu.borrow().as_ref() {
4070 None => {}
4071 Some(CodeContextMenu::Completions(prev_menu)) => {
4072 if prev_menu.id > id {
4073 return;
4074 }
4075 }
4076 _ => return,
4077 }
4078
4079 if editor.focus_handle.is_focused(window) && menu.is_some() {
4080 let mut menu = menu.unwrap();
4081 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4082
4083 *editor.context_menu.borrow_mut() =
4084 Some(CodeContextMenu::Completions(menu));
4085
4086 if editor.show_edit_predictions_in_menu() {
4087 editor.update_visible_inline_completion(window, cx);
4088 } else {
4089 editor.discard_inline_completion(false, cx);
4090 }
4091
4092 cx.notify();
4093 } else if editor.completion_tasks.len() <= 1 {
4094 // If there are no more completion tasks and the last menu was
4095 // empty, we should hide it.
4096 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4097 // If it was already hidden and we don't show inline
4098 // completions in the menu, we should also show the
4099 // inline-completion when available.
4100 if was_hidden && editor.show_edit_predictions_in_menu() {
4101 editor.update_visible_inline_completion(window, cx);
4102 }
4103 }
4104 })?;
4105
4106 Ok::<_, anyhow::Error>(())
4107 }
4108 .log_err()
4109 });
4110
4111 self.completion_tasks.push((id, task));
4112 }
4113
4114 pub fn confirm_completion(
4115 &mut self,
4116 action: &ConfirmCompletion,
4117 window: &mut Window,
4118 cx: &mut Context<Self>,
4119 ) -> Option<Task<Result<()>>> {
4120 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4121 }
4122
4123 pub fn compose_completion(
4124 &mut self,
4125 action: &ComposeCompletion,
4126 window: &mut Window,
4127 cx: &mut Context<Self>,
4128 ) -> Option<Task<Result<()>>> {
4129 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4130 }
4131
4132 fn do_completion(
4133 &mut self,
4134 item_ix: Option<usize>,
4135 intent: CompletionIntent,
4136 window: &mut Window,
4137 cx: &mut Context<Editor>,
4138 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4139 use language::ToOffset as _;
4140
4141 let completions_menu =
4142 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4143 menu
4144 } else {
4145 return None;
4146 };
4147
4148 let entries = completions_menu.entries.borrow();
4149 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4150 if self.show_edit_predictions_in_menu() {
4151 self.discard_inline_completion(true, cx);
4152 }
4153 let candidate_id = mat.candidate_id;
4154 drop(entries);
4155
4156 let buffer_handle = completions_menu.buffer;
4157 let completion = completions_menu
4158 .completions
4159 .borrow()
4160 .get(candidate_id)?
4161 .clone();
4162 cx.stop_propagation();
4163
4164 let snippet;
4165 let text;
4166
4167 if completion.is_snippet() {
4168 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4169 text = snippet.as_ref().unwrap().text.clone();
4170 } else {
4171 snippet = None;
4172 text = completion.new_text.clone();
4173 };
4174 let selections = self.selections.all::<usize>(cx);
4175 let buffer = buffer_handle.read(cx);
4176 let old_range = completion.old_range.to_offset(buffer);
4177 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4178
4179 let newest_selection = self.selections.newest_anchor();
4180 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4181 return None;
4182 }
4183
4184 let lookbehind = newest_selection
4185 .start
4186 .text_anchor
4187 .to_offset(buffer)
4188 .saturating_sub(old_range.start);
4189 let lookahead = old_range
4190 .end
4191 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4192 let mut common_prefix_len = old_text
4193 .bytes()
4194 .zip(text.bytes())
4195 .take_while(|(a, b)| a == b)
4196 .count();
4197
4198 let snapshot = self.buffer.read(cx).snapshot(cx);
4199 let mut range_to_replace: Option<Range<isize>> = None;
4200 let mut ranges = Vec::new();
4201 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4202 for selection in &selections {
4203 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4204 let start = selection.start.saturating_sub(lookbehind);
4205 let end = selection.end + lookahead;
4206 if selection.id == newest_selection.id {
4207 range_to_replace = Some(
4208 ((start + common_prefix_len) as isize - selection.start as isize)
4209 ..(end as isize - selection.start as isize),
4210 );
4211 }
4212 ranges.push(start + common_prefix_len..end);
4213 } else {
4214 common_prefix_len = 0;
4215 ranges.clear();
4216 ranges.extend(selections.iter().map(|s| {
4217 if s.id == newest_selection.id {
4218 range_to_replace = Some(
4219 old_range.start.to_offset_utf16(&snapshot).0 as isize
4220 - selection.start as isize
4221 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4222 - selection.start as isize,
4223 );
4224 old_range.clone()
4225 } else {
4226 s.start..s.end
4227 }
4228 }));
4229 break;
4230 }
4231 if !self.linked_edit_ranges.is_empty() {
4232 let start_anchor = snapshot.anchor_before(selection.head());
4233 let end_anchor = snapshot.anchor_after(selection.tail());
4234 if let Some(ranges) = self
4235 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4236 {
4237 for (buffer, edits) in ranges {
4238 linked_edits.entry(buffer.clone()).or_default().extend(
4239 edits
4240 .into_iter()
4241 .map(|range| (range, text[common_prefix_len..].to_owned())),
4242 );
4243 }
4244 }
4245 }
4246 }
4247 let text = &text[common_prefix_len..];
4248
4249 cx.emit(EditorEvent::InputHandled {
4250 utf16_range_to_replace: range_to_replace,
4251 text: text.into(),
4252 });
4253
4254 self.transact(window, cx, |this, window, cx| {
4255 if let Some(mut snippet) = snippet {
4256 snippet.text = text.to_string();
4257 for tabstop in snippet
4258 .tabstops
4259 .iter_mut()
4260 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4261 {
4262 tabstop.start -= common_prefix_len as isize;
4263 tabstop.end -= common_prefix_len as isize;
4264 }
4265
4266 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4267 } else {
4268 this.buffer.update(cx, |buffer, cx| {
4269 buffer.edit(
4270 ranges.iter().map(|range| (range.clone(), text)),
4271 this.autoindent_mode.clone(),
4272 cx,
4273 );
4274 });
4275 }
4276 for (buffer, edits) in linked_edits {
4277 buffer.update(cx, |buffer, cx| {
4278 let snapshot = buffer.snapshot();
4279 let edits = edits
4280 .into_iter()
4281 .map(|(range, text)| {
4282 use text::ToPoint as TP;
4283 let end_point = TP::to_point(&range.end, &snapshot);
4284 let start_point = TP::to_point(&range.start, &snapshot);
4285 (start_point..end_point, text)
4286 })
4287 .sorted_by_key(|(range, _)| range.start)
4288 .collect::<Vec<_>>();
4289 buffer.edit(edits, None, cx);
4290 })
4291 }
4292
4293 this.refresh_inline_completion(true, false, window, cx);
4294 });
4295
4296 let show_new_completions_on_confirm = completion
4297 .confirm
4298 .as_ref()
4299 .map_or(false, |confirm| confirm(intent, window, cx));
4300 if show_new_completions_on_confirm {
4301 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4302 }
4303
4304 let provider = self.completion_provider.as_ref()?;
4305 drop(completion);
4306 let apply_edits = provider.apply_additional_edits_for_completion(
4307 buffer_handle,
4308 completions_menu.completions.clone(),
4309 candidate_id,
4310 true,
4311 cx,
4312 );
4313
4314 let editor_settings = EditorSettings::get_global(cx);
4315 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4316 // After the code completion is finished, users often want to know what signatures are needed.
4317 // so we should automatically call signature_help
4318 self.show_signature_help(&ShowSignatureHelp, window, cx);
4319 }
4320
4321 Some(cx.foreground_executor().spawn(async move {
4322 apply_edits.await?;
4323 Ok(())
4324 }))
4325 }
4326
4327 pub fn toggle_code_actions(
4328 &mut self,
4329 action: &ToggleCodeActions,
4330 window: &mut Window,
4331 cx: &mut Context<Self>,
4332 ) {
4333 let mut context_menu = self.context_menu.borrow_mut();
4334 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4335 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4336 // Toggle if we're selecting the same one
4337 *context_menu = None;
4338 cx.notify();
4339 return;
4340 } else {
4341 // Otherwise, clear it and start a new one
4342 *context_menu = None;
4343 cx.notify();
4344 }
4345 }
4346 drop(context_menu);
4347 let snapshot = self.snapshot(window, cx);
4348 let deployed_from_indicator = action.deployed_from_indicator;
4349 let mut task = self.code_actions_task.take();
4350 let action = action.clone();
4351 cx.spawn_in(window, |editor, mut cx| async move {
4352 while let Some(prev_task) = task {
4353 prev_task.await.log_err();
4354 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4355 }
4356
4357 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4358 if editor.focus_handle.is_focused(window) {
4359 let multibuffer_point = action
4360 .deployed_from_indicator
4361 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4362 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4363 let (buffer, buffer_row) = snapshot
4364 .buffer_snapshot
4365 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4366 .and_then(|(buffer_snapshot, range)| {
4367 editor
4368 .buffer
4369 .read(cx)
4370 .buffer(buffer_snapshot.remote_id())
4371 .map(|buffer| (buffer, range.start.row))
4372 })?;
4373 let (_, code_actions) = editor
4374 .available_code_actions
4375 .clone()
4376 .and_then(|(location, code_actions)| {
4377 let snapshot = location.buffer.read(cx).snapshot();
4378 let point_range = location.range.to_point(&snapshot);
4379 let point_range = point_range.start.row..=point_range.end.row;
4380 if point_range.contains(&buffer_row) {
4381 Some((location, code_actions))
4382 } else {
4383 None
4384 }
4385 })
4386 .unzip();
4387 let buffer_id = buffer.read(cx).remote_id();
4388 let tasks = editor
4389 .tasks
4390 .get(&(buffer_id, buffer_row))
4391 .map(|t| Arc::new(t.to_owned()));
4392 if tasks.is_none() && code_actions.is_none() {
4393 return None;
4394 }
4395
4396 editor.completion_tasks.clear();
4397 editor.discard_inline_completion(false, cx);
4398 let task_context =
4399 tasks
4400 .as_ref()
4401 .zip(editor.project.clone())
4402 .map(|(tasks, project)| {
4403 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4404 });
4405
4406 Some(cx.spawn_in(window, |editor, mut cx| async move {
4407 let task_context = match task_context {
4408 Some(task_context) => task_context.await,
4409 None => None,
4410 };
4411 let resolved_tasks =
4412 tasks.zip(task_context).map(|(tasks, task_context)| {
4413 Rc::new(ResolvedTasks {
4414 templates: tasks.resolve(&task_context).collect(),
4415 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4416 multibuffer_point.row,
4417 tasks.column,
4418 )),
4419 })
4420 });
4421 let spawn_straight_away = resolved_tasks
4422 .as_ref()
4423 .map_or(false, |tasks| tasks.templates.len() == 1)
4424 && code_actions
4425 .as_ref()
4426 .map_or(true, |actions| actions.is_empty());
4427 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4428 *editor.context_menu.borrow_mut() =
4429 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4430 buffer,
4431 actions: CodeActionContents {
4432 tasks: resolved_tasks,
4433 actions: code_actions,
4434 },
4435 selected_item: Default::default(),
4436 scroll_handle: UniformListScrollHandle::default(),
4437 deployed_from_indicator,
4438 }));
4439 if spawn_straight_away {
4440 if let Some(task) = editor.confirm_code_action(
4441 &ConfirmCodeAction { item_ix: Some(0) },
4442 window,
4443 cx,
4444 ) {
4445 cx.notify();
4446 return task;
4447 }
4448 }
4449 cx.notify();
4450 Task::ready(Ok(()))
4451 }) {
4452 task.await
4453 } else {
4454 Ok(())
4455 }
4456 }))
4457 } else {
4458 Some(Task::ready(Ok(())))
4459 }
4460 })?;
4461 if let Some(task) = spawned_test_task {
4462 task.await?;
4463 }
4464
4465 Ok::<_, anyhow::Error>(())
4466 })
4467 .detach_and_log_err(cx);
4468 }
4469
4470 pub fn confirm_code_action(
4471 &mut self,
4472 action: &ConfirmCodeAction,
4473 window: &mut Window,
4474 cx: &mut Context<Self>,
4475 ) -> Option<Task<Result<()>>> {
4476 let actions_menu =
4477 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4478 menu
4479 } else {
4480 return None;
4481 };
4482 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4483 let action = actions_menu.actions.get(action_ix)?;
4484 let title = action.label();
4485 let buffer = actions_menu.buffer;
4486 let workspace = self.workspace()?;
4487
4488 match action {
4489 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4490 workspace.update(cx, |workspace, cx| {
4491 workspace::tasks::schedule_resolved_task(
4492 workspace,
4493 task_source_kind,
4494 resolved_task,
4495 false,
4496 cx,
4497 );
4498
4499 Some(Task::ready(Ok(())))
4500 })
4501 }
4502 CodeActionsItem::CodeAction {
4503 excerpt_id,
4504 action,
4505 provider,
4506 } => {
4507 let apply_code_action =
4508 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4509 let workspace = workspace.downgrade();
4510 Some(cx.spawn_in(window, |editor, cx| async move {
4511 let project_transaction = apply_code_action.await?;
4512 Self::open_project_transaction(
4513 &editor,
4514 workspace,
4515 project_transaction,
4516 title,
4517 cx,
4518 )
4519 .await
4520 }))
4521 }
4522 }
4523 }
4524
4525 pub async fn open_project_transaction(
4526 this: &WeakEntity<Editor>,
4527 workspace: WeakEntity<Workspace>,
4528 transaction: ProjectTransaction,
4529 title: String,
4530 mut cx: AsyncWindowContext,
4531 ) -> Result<()> {
4532 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4533 cx.update(|_, cx| {
4534 entries.sort_unstable_by_key(|(buffer, _)| {
4535 buffer.read(cx).file().map(|f| f.path().clone())
4536 });
4537 })?;
4538
4539 // If the project transaction's edits are all contained within this editor, then
4540 // avoid opening a new editor to display them.
4541
4542 if let Some((buffer, transaction)) = entries.first() {
4543 if entries.len() == 1 {
4544 let excerpt = this.update(&mut cx, |editor, cx| {
4545 editor
4546 .buffer()
4547 .read(cx)
4548 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4549 })?;
4550 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4551 if excerpted_buffer == *buffer {
4552 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4553 let excerpt_range = excerpt_range.to_offset(buffer);
4554 buffer
4555 .edited_ranges_for_transaction::<usize>(transaction)
4556 .all(|range| {
4557 excerpt_range.start <= range.start
4558 && excerpt_range.end >= range.end
4559 })
4560 })?;
4561
4562 if all_edits_within_excerpt {
4563 return Ok(());
4564 }
4565 }
4566 }
4567 }
4568 } else {
4569 return Ok(());
4570 }
4571
4572 let mut ranges_to_highlight = Vec::new();
4573 let excerpt_buffer = cx.new(|cx| {
4574 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4575 for (buffer_handle, transaction) in &entries {
4576 let buffer = buffer_handle.read(cx);
4577 ranges_to_highlight.extend(
4578 multibuffer.push_excerpts_with_context_lines(
4579 buffer_handle.clone(),
4580 buffer
4581 .edited_ranges_for_transaction::<usize>(transaction)
4582 .collect(),
4583 DEFAULT_MULTIBUFFER_CONTEXT,
4584 cx,
4585 ),
4586 );
4587 }
4588 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4589 multibuffer
4590 })?;
4591
4592 workspace.update_in(&mut cx, |workspace, window, cx| {
4593 let project = workspace.project().clone();
4594 let editor = cx
4595 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4596 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4597 editor.update(cx, |editor, cx| {
4598 editor.highlight_background::<Self>(
4599 &ranges_to_highlight,
4600 |theme| theme.editor_highlighted_line_background,
4601 cx,
4602 );
4603 });
4604 })?;
4605
4606 Ok(())
4607 }
4608
4609 pub fn clear_code_action_providers(&mut self) {
4610 self.code_action_providers.clear();
4611 self.available_code_actions.take();
4612 }
4613
4614 pub fn add_code_action_provider(
4615 &mut self,
4616 provider: Rc<dyn CodeActionProvider>,
4617 window: &mut Window,
4618 cx: &mut Context<Self>,
4619 ) {
4620 if self
4621 .code_action_providers
4622 .iter()
4623 .any(|existing_provider| existing_provider.id() == provider.id())
4624 {
4625 return;
4626 }
4627
4628 self.code_action_providers.push(provider);
4629 self.refresh_code_actions(window, cx);
4630 }
4631
4632 pub fn remove_code_action_provider(
4633 &mut self,
4634 id: Arc<str>,
4635 window: &mut Window,
4636 cx: &mut Context<Self>,
4637 ) {
4638 self.code_action_providers
4639 .retain(|provider| provider.id() != id);
4640 self.refresh_code_actions(window, cx);
4641 }
4642
4643 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4644 let buffer = self.buffer.read(cx);
4645 let newest_selection = self.selections.newest_anchor().clone();
4646 if newest_selection.head().diff_base_anchor.is_some() {
4647 return None;
4648 }
4649 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4650 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4651 if start_buffer != end_buffer {
4652 return None;
4653 }
4654
4655 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4656 cx.background_executor()
4657 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4658 .await;
4659
4660 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4661 let providers = this.code_action_providers.clone();
4662 let tasks = this
4663 .code_action_providers
4664 .iter()
4665 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4666 .collect::<Vec<_>>();
4667 (providers, tasks)
4668 })?;
4669
4670 let mut actions = Vec::new();
4671 for (provider, provider_actions) in
4672 providers.into_iter().zip(future::join_all(tasks).await)
4673 {
4674 if let Some(provider_actions) = provider_actions.log_err() {
4675 actions.extend(provider_actions.into_iter().map(|action| {
4676 AvailableCodeAction {
4677 excerpt_id: newest_selection.start.excerpt_id,
4678 action,
4679 provider: provider.clone(),
4680 }
4681 }));
4682 }
4683 }
4684
4685 this.update(&mut cx, |this, cx| {
4686 this.available_code_actions = if actions.is_empty() {
4687 None
4688 } else {
4689 Some((
4690 Location {
4691 buffer: start_buffer,
4692 range: start..end,
4693 },
4694 actions.into(),
4695 ))
4696 };
4697 cx.notify();
4698 })
4699 }));
4700 None
4701 }
4702
4703 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4704 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4705 self.show_git_blame_inline = false;
4706
4707 self.show_git_blame_inline_delay_task =
4708 Some(cx.spawn_in(window, |this, mut cx| async move {
4709 cx.background_executor().timer(delay).await;
4710
4711 this.update(&mut cx, |this, cx| {
4712 this.show_git_blame_inline = true;
4713 cx.notify();
4714 })
4715 .log_err();
4716 }));
4717 }
4718 }
4719
4720 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4721 if self.pending_rename.is_some() {
4722 return None;
4723 }
4724
4725 let provider = self.semantics_provider.clone()?;
4726 let buffer = self.buffer.read(cx);
4727 let newest_selection = self.selections.newest_anchor().clone();
4728 let cursor_position = newest_selection.head();
4729 let (cursor_buffer, cursor_buffer_position) =
4730 buffer.text_anchor_for_position(cursor_position, cx)?;
4731 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4732 if cursor_buffer != tail_buffer {
4733 return None;
4734 }
4735 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4736 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4737 cx.background_executor()
4738 .timer(Duration::from_millis(debounce))
4739 .await;
4740
4741 let highlights = if let Some(highlights) = cx
4742 .update(|cx| {
4743 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4744 })
4745 .ok()
4746 .flatten()
4747 {
4748 highlights.await.log_err()
4749 } else {
4750 None
4751 };
4752
4753 if let Some(highlights) = highlights {
4754 this.update(&mut cx, |this, cx| {
4755 if this.pending_rename.is_some() {
4756 return;
4757 }
4758
4759 let buffer_id = cursor_position.buffer_id;
4760 let buffer = this.buffer.read(cx);
4761 if !buffer
4762 .text_anchor_for_position(cursor_position, cx)
4763 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4764 {
4765 return;
4766 }
4767
4768 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4769 let mut write_ranges = Vec::new();
4770 let mut read_ranges = Vec::new();
4771 for highlight in highlights {
4772 for (excerpt_id, excerpt_range) in
4773 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4774 {
4775 let start = highlight
4776 .range
4777 .start
4778 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4779 let end = highlight
4780 .range
4781 .end
4782 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4783 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4784 continue;
4785 }
4786
4787 let range = Anchor {
4788 buffer_id,
4789 excerpt_id,
4790 text_anchor: start,
4791 diff_base_anchor: None,
4792 }..Anchor {
4793 buffer_id,
4794 excerpt_id,
4795 text_anchor: end,
4796 diff_base_anchor: None,
4797 };
4798 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4799 write_ranges.push(range);
4800 } else {
4801 read_ranges.push(range);
4802 }
4803 }
4804 }
4805
4806 this.highlight_background::<DocumentHighlightRead>(
4807 &read_ranges,
4808 |theme| theme.editor_document_highlight_read_background,
4809 cx,
4810 );
4811 this.highlight_background::<DocumentHighlightWrite>(
4812 &write_ranges,
4813 |theme| theme.editor_document_highlight_write_background,
4814 cx,
4815 );
4816 cx.notify();
4817 })
4818 .log_err();
4819 }
4820 }));
4821 None
4822 }
4823
4824 pub fn refresh_selected_text_highlights(
4825 &mut self,
4826 window: &mut Window,
4827 cx: &mut Context<Editor>,
4828 ) {
4829 self.selection_highlight_task.take();
4830 if !EditorSettings::get_global(cx).selection_highlight {
4831 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4832 return;
4833 }
4834 if self.selections.count() != 1 || self.selections.line_mode {
4835 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4836 return;
4837 }
4838 let selection = self.selections.newest::<Point>(cx);
4839 if selection.is_empty() || selection.start.row != selection.end.row {
4840 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4841 return;
4842 }
4843 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4844 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4845 cx.background_executor()
4846 .timer(Duration::from_millis(debounce))
4847 .await;
4848 let Some(Some(matches_task)) = editor
4849 .update_in(&mut cx, |editor, _, cx| {
4850 if editor.selections.count() != 1 || editor.selections.line_mode {
4851 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4852 return None;
4853 }
4854 let selection = editor.selections.newest::<Point>(cx);
4855 if selection.is_empty() || selection.start.row != selection.end.row {
4856 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4857 return None;
4858 }
4859 let buffer = editor.buffer().read(cx).snapshot(cx);
4860 let query = buffer.text_for_range(selection.range()).collect::<String>();
4861 if query.trim().is_empty() {
4862 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4863 return None;
4864 }
4865 Some(cx.background_spawn(async move {
4866 let mut ranges = Vec::new();
4867 let selection_anchors = selection.range().to_anchors(&buffer);
4868 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4869 for (search_buffer, search_range, excerpt_id) in
4870 buffer.range_to_buffer_ranges(range)
4871 {
4872 ranges.extend(
4873 project::search::SearchQuery::text(
4874 query.clone(),
4875 false,
4876 false,
4877 false,
4878 Default::default(),
4879 Default::default(),
4880 None,
4881 )
4882 .unwrap()
4883 .search(search_buffer, Some(search_range.clone()))
4884 .await
4885 .into_iter()
4886 .filter_map(
4887 |match_range| {
4888 let start = search_buffer.anchor_after(
4889 search_range.start + match_range.start,
4890 );
4891 let end = search_buffer.anchor_before(
4892 search_range.start + match_range.end,
4893 );
4894 let range = Anchor::range_in_buffer(
4895 excerpt_id,
4896 search_buffer.remote_id(),
4897 start..end,
4898 );
4899 (range != selection_anchors).then_some(range)
4900 },
4901 ),
4902 );
4903 }
4904 }
4905 ranges
4906 }))
4907 })
4908 .log_err()
4909 else {
4910 return;
4911 };
4912 let matches = matches_task.await;
4913 editor
4914 .update_in(&mut cx, |editor, _, cx| {
4915 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4916 if !matches.is_empty() {
4917 editor.highlight_background::<SelectedTextHighlight>(
4918 &matches,
4919 |theme| theme.editor_document_highlight_bracket_background,
4920 cx,
4921 )
4922 }
4923 })
4924 .log_err();
4925 }));
4926 }
4927
4928 pub fn refresh_inline_completion(
4929 &mut self,
4930 debounce: bool,
4931 user_requested: bool,
4932 window: &mut Window,
4933 cx: &mut Context<Self>,
4934 ) -> Option<()> {
4935 let provider = self.edit_prediction_provider()?;
4936 let cursor = self.selections.newest_anchor().head();
4937 let (buffer, cursor_buffer_position) =
4938 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4939
4940 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4941 self.discard_inline_completion(false, cx);
4942 return None;
4943 }
4944
4945 if !user_requested
4946 && (!self.should_show_edit_predictions()
4947 || !self.is_focused(window)
4948 || buffer.read(cx).is_empty())
4949 {
4950 self.discard_inline_completion(false, cx);
4951 return None;
4952 }
4953
4954 self.update_visible_inline_completion(window, cx);
4955 provider.refresh(
4956 self.project.clone(),
4957 buffer,
4958 cursor_buffer_position,
4959 debounce,
4960 cx,
4961 );
4962 Some(())
4963 }
4964
4965 fn show_edit_predictions_in_menu(&self) -> bool {
4966 match self.edit_prediction_settings {
4967 EditPredictionSettings::Disabled => false,
4968 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4969 }
4970 }
4971
4972 pub fn edit_predictions_enabled(&self) -> bool {
4973 match self.edit_prediction_settings {
4974 EditPredictionSettings::Disabled => false,
4975 EditPredictionSettings::Enabled { .. } => true,
4976 }
4977 }
4978
4979 fn edit_prediction_requires_modifier(&self) -> bool {
4980 match self.edit_prediction_settings {
4981 EditPredictionSettings::Disabled => false,
4982 EditPredictionSettings::Enabled {
4983 preview_requires_modifier,
4984 ..
4985 } => preview_requires_modifier,
4986 }
4987 }
4988
4989 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4990 if self.edit_prediction_provider.is_none() {
4991 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4992 } else {
4993 let selection = self.selections.newest_anchor();
4994 let cursor = selection.head();
4995
4996 if let Some((buffer, cursor_buffer_position)) =
4997 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4998 {
4999 self.edit_prediction_settings =
5000 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5001 }
5002 }
5003 }
5004
5005 fn edit_prediction_settings_at_position(
5006 &self,
5007 buffer: &Entity<Buffer>,
5008 buffer_position: language::Anchor,
5009 cx: &App,
5010 ) -> EditPredictionSettings {
5011 if self.mode != EditorMode::Full
5012 || !self.show_inline_completions_override.unwrap_or(true)
5013 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5014 {
5015 return EditPredictionSettings::Disabled;
5016 }
5017
5018 let buffer = buffer.read(cx);
5019
5020 let file = buffer.file();
5021
5022 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5023 return EditPredictionSettings::Disabled;
5024 };
5025
5026 let by_provider = matches!(
5027 self.menu_inline_completions_policy,
5028 MenuInlineCompletionsPolicy::ByProvider
5029 );
5030
5031 let show_in_menu = by_provider
5032 && self
5033 .edit_prediction_provider
5034 .as_ref()
5035 .map_or(false, |provider| {
5036 provider.provider.show_completions_in_menu()
5037 });
5038
5039 let preview_requires_modifier =
5040 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5041
5042 EditPredictionSettings::Enabled {
5043 show_in_menu,
5044 preview_requires_modifier,
5045 }
5046 }
5047
5048 fn should_show_edit_predictions(&self) -> bool {
5049 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5050 }
5051
5052 pub fn edit_prediction_preview_is_active(&self) -> bool {
5053 matches!(
5054 self.edit_prediction_preview,
5055 EditPredictionPreview::Active { .. }
5056 )
5057 }
5058
5059 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5060 let cursor = self.selections.newest_anchor().head();
5061 if let Some((buffer, cursor_position)) =
5062 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5063 {
5064 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5065 } else {
5066 false
5067 }
5068 }
5069
5070 fn edit_predictions_enabled_in_buffer(
5071 &self,
5072 buffer: &Entity<Buffer>,
5073 buffer_position: language::Anchor,
5074 cx: &App,
5075 ) -> bool {
5076 maybe!({
5077 let provider = self.edit_prediction_provider()?;
5078 if !provider.is_enabled(&buffer, buffer_position, cx) {
5079 return Some(false);
5080 }
5081 let buffer = buffer.read(cx);
5082 let Some(file) = buffer.file() else {
5083 return Some(true);
5084 };
5085 let settings = all_language_settings(Some(file), cx);
5086 Some(settings.edit_predictions_enabled_for_file(file, cx))
5087 })
5088 .unwrap_or(false)
5089 }
5090
5091 fn cycle_inline_completion(
5092 &mut self,
5093 direction: Direction,
5094 window: &mut Window,
5095 cx: &mut Context<Self>,
5096 ) -> Option<()> {
5097 let provider = self.edit_prediction_provider()?;
5098 let cursor = self.selections.newest_anchor().head();
5099 let (buffer, cursor_buffer_position) =
5100 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5101 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5102 return None;
5103 }
5104
5105 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5106 self.update_visible_inline_completion(window, cx);
5107
5108 Some(())
5109 }
5110
5111 pub fn show_inline_completion(
5112 &mut self,
5113 _: &ShowEditPrediction,
5114 window: &mut Window,
5115 cx: &mut Context<Self>,
5116 ) {
5117 if !self.has_active_inline_completion() {
5118 self.refresh_inline_completion(false, true, window, cx);
5119 return;
5120 }
5121
5122 self.update_visible_inline_completion(window, cx);
5123 }
5124
5125 pub fn display_cursor_names(
5126 &mut self,
5127 _: &DisplayCursorNames,
5128 window: &mut Window,
5129 cx: &mut Context<Self>,
5130 ) {
5131 self.show_cursor_names(window, cx);
5132 }
5133
5134 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5135 self.show_cursor_names = true;
5136 cx.notify();
5137 cx.spawn_in(window, |this, mut cx| async move {
5138 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5139 this.update(&mut cx, |this, cx| {
5140 this.show_cursor_names = false;
5141 cx.notify()
5142 })
5143 .ok()
5144 })
5145 .detach();
5146 }
5147
5148 pub fn next_edit_prediction(
5149 &mut self,
5150 _: &NextEditPrediction,
5151 window: &mut Window,
5152 cx: &mut Context<Self>,
5153 ) {
5154 if self.has_active_inline_completion() {
5155 self.cycle_inline_completion(Direction::Next, window, cx);
5156 } else {
5157 let is_copilot_disabled = self
5158 .refresh_inline_completion(false, true, window, cx)
5159 .is_none();
5160 if is_copilot_disabled {
5161 cx.propagate();
5162 }
5163 }
5164 }
5165
5166 pub fn previous_edit_prediction(
5167 &mut self,
5168 _: &PreviousEditPrediction,
5169 window: &mut Window,
5170 cx: &mut Context<Self>,
5171 ) {
5172 if self.has_active_inline_completion() {
5173 self.cycle_inline_completion(Direction::Prev, window, cx);
5174 } else {
5175 let is_copilot_disabled = self
5176 .refresh_inline_completion(false, true, window, cx)
5177 .is_none();
5178 if is_copilot_disabled {
5179 cx.propagate();
5180 }
5181 }
5182 }
5183
5184 pub fn accept_edit_prediction(
5185 &mut self,
5186 _: &AcceptEditPrediction,
5187 window: &mut Window,
5188 cx: &mut Context<Self>,
5189 ) {
5190 if self.show_edit_predictions_in_menu() {
5191 self.hide_context_menu(window, cx);
5192 }
5193
5194 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5195 return;
5196 };
5197
5198 self.report_inline_completion_event(
5199 active_inline_completion.completion_id.clone(),
5200 true,
5201 cx,
5202 );
5203
5204 match &active_inline_completion.completion {
5205 InlineCompletion::Move { target, .. } => {
5206 let target = *target;
5207
5208 if let Some(position_map) = &self.last_position_map {
5209 if position_map
5210 .visible_row_range
5211 .contains(&target.to_display_point(&position_map.snapshot).row())
5212 || !self.edit_prediction_requires_modifier()
5213 {
5214 self.unfold_ranges(&[target..target], true, false, cx);
5215 // Note that this is also done in vim's handler of the Tab action.
5216 self.change_selections(
5217 Some(Autoscroll::newest()),
5218 window,
5219 cx,
5220 |selections| {
5221 selections.select_anchor_ranges([target..target]);
5222 },
5223 );
5224 self.clear_row_highlights::<EditPredictionPreview>();
5225
5226 self.edit_prediction_preview
5227 .set_previous_scroll_position(None);
5228 } else {
5229 self.edit_prediction_preview
5230 .set_previous_scroll_position(Some(
5231 position_map.snapshot.scroll_anchor,
5232 ));
5233
5234 self.highlight_rows::<EditPredictionPreview>(
5235 target..target,
5236 cx.theme().colors().editor_highlighted_line_background,
5237 true,
5238 cx,
5239 );
5240 self.request_autoscroll(Autoscroll::fit(), cx);
5241 }
5242 }
5243 }
5244 InlineCompletion::Edit { edits, .. } => {
5245 if let Some(provider) = self.edit_prediction_provider() {
5246 provider.accept(cx);
5247 }
5248
5249 let snapshot = self.buffer.read(cx).snapshot(cx);
5250 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5251
5252 self.buffer.update(cx, |buffer, cx| {
5253 buffer.edit(edits.iter().cloned(), None, cx)
5254 });
5255
5256 self.change_selections(None, window, cx, |s| {
5257 s.select_anchor_ranges([last_edit_end..last_edit_end])
5258 });
5259
5260 self.update_visible_inline_completion(window, cx);
5261 if self.active_inline_completion.is_none() {
5262 self.refresh_inline_completion(true, true, window, cx);
5263 }
5264
5265 cx.notify();
5266 }
5267 }
5268
5269 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5270 }
5271
5272 pub fn accept_partial_inline_completion(
5273 &mut self,
5274 _: &AcceptPartialEditPrediction,
5275 window: &mut Window,
5276 cx: &mut Context<Self>,
5277 ) {
5278 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5279 return;
5280 };
5281 if self.selections.count() != 1 {
5282 return;
5283 }
5284
5285 self.report_inline_completion_event(
5286 active_inline_completion.completion_id.clone(),
5287 true,
5288 cx,
5289 );
5290
5291 match &active_inline_completion.completion {
5292 InlineCompletion::Move { target, .. } => {
5293 let target = *target;
5294 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5295 selections.select_anchor_ranges([target..target]);
5296 });
5297 }
5298 InlineCompletion::Edit { edits, .. } => {
5299 // Find an insertion that starts at the cursor position.
5300 let snapshot = self.buffer.read(cx).snapshot(cx);
5301 let cursor_offset = self.selections.newest::<usize>(cx).head();
5302 let insertion = edits.iter().find_map(|(range, text)| {
5303 let range = range.to_offset(&snapshot);
5304 if range.is_empty() && range.start == cursor_offset {
5305 Some(text)
5306 } else {
5307 None
5308 }
5309 });
5310
5311 if let Some(text) = insertion {
5312 let mut partial_completion = text
5313 .chars()
5314 .by_ref()
5315 .take_while(|c| c.is_alphabetic())
5316 .collect::<String>();
5317 if partial_completion.is_empty() {
5318 partial_completion = text
5319 .chars()
5320 .by_ref()
5321 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5322 .collect::<String>();
5323 }
5324
5325 cx.emit(EditorEvent::InputHandled {
5326 utf16_range_to_replace: None,
5327 text: partial_completion.clone().into(),
5328 });
5329
5330 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5331
5332 self.refresh_inline_completion(true, true, window, cx);
5333 cx.notify();
5334 } else {
5335 self.accept_edit_prediction(&Default::default(), window, cx);
5336 }
5337 }
5338 }
5339 }
5340
5341 fn discard_inline_completion(
5342 &mut self,
5343 should_report_inline_completion_event: bool,
5344 cx: &mut Context<Self>,
5345 ) -> bool {
5346 if should_report_inline_completion_event {
5347 let completion_id = self
5348 .active_inline_completion
5349 .as_ref()
5350 .and_then(|active_completion| active_completion.completion_id.clone());
5351
5352 self.report_inline_completion_event(completion_id, false, cx);
5353 }
5354
5355 if let Some(provider) = self.edit_prediction_provider() {
5356 provider.discard(cx);
5357 }
5358
5359 self.take_active_inline_completion(cx)
5360 }
5361
5362 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5363 let Some(provider) = self.edit_prediction_provider() else {
5364 return;
5365 };
5366
5367 let Some((_, buffer, _)) = self
5368 .buffer
5369 .read(cx)
5370 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5371 else {
5372 return;
5373 };
5374
5375 let extension = buffer
5376 .read(cx)
5377 .file()
5378 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5379
5380 let event_type = match accepted {
5381 true => "Edit Prediction Accepted",
5382 false => "Edit Prediction Discarded",
5383 };
5384 telemetry::event!(
5385 event_type,
5386 provider = provider.name(),
5387 prediction_id = id,
5388 suggestion_accepted = accepted,
5389 file_extension = extension,
5390 );
5391 }
5392
5393 pub fn has_active_inline_completion(&self) -> bool {
5394 self.active_inline_completion.is_some()
5395 }
5396
5397 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5398 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5399 return false;
5400 };
5401
5402 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5403 self.clear_highlights::<InlineCompletionHighlight>(cx);
5404 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5405 true
5406 }
5407
5408 /// Returns true when we're displaying the edit prediction popover below the cursor
5409 /// like we are not previewing and the LSP autocomplete menu is visible
5410 /// or we are in `when_holding_modifier` mode.
5411 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5412 if self.edit_prediction_preview_is_active()
5413 || !self.show_edit_predictions_in_menu()
5414 || !self.edit_predictions_enabled()
5415 {
5416 return false;
5417 }
5418
5419 if self.has_visible_completions_menu() {
5420 return true;
5421 }
5422
5423 has_completion && self.edit_prediction_requires_modifier()
5424 }
5425
5426 fn handle_modifiers_changed(
5427 &mut self,
5428 modifiers: Modifiers,
5429 position_map: &PositionMap,
5430 window: &mut Window,
5431 cx: &mut Context<Self>,
5432 ) {
5433 if self.show_edit_predictions_in_menu() {
5434 self.update_edit_prediction_preview(&modifiers, window, cx);
5435 }
5436
5437 self.update_selection_mode(&modifiers, position_map, window, cx);
5438
5439 let mouse_position = window.mouse_position();
5440 if !position_map.text_hitbox.is_hovered(window) {
5441 return;
5442 }
5443
5444 self.update_hovered_link(
5445 position_map.point_for_position(mouse_position),
5446 &position_map.snapshot,
5447 modifiers,
5448 window,
5449 cx,
5450 )
5451 }
5452
5453 fn update_selection_mode(
5454 &mut self,
5455 modifiers: &Modifiers,
5456 position_map: &PositionMap,
5457 window: &mut Window,
5458 cx: &mut Context<Self>,
5459 ) {
5460 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5461 return;
5462 }
5463
5464 let mouse_position = window.mouse_position();
5465 let point_for_position = position_map.point_for_position(mouse_position);
5466 let position = point_for_position.previous_valid;
5467
5468 self.select(
5469 SelectPhase::BeginColumnar {
5470 position,
5471 reset: false,
5472 goal_column: point_for_position.exact_unclipped.column(),
5473 },
5474 window,
5475 cx,
5476 );
5477 }
5478
5479 fn update_edit_prediction_preview(
5480 &mut self,
5481 modifiers: &Modifiers,
5482 window: &mut Window,
5483 cx: &mut Context<Self>,
5484 ) {
5485 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5486 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5487 return;
5488 };
5489
5490 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5491 if matches!(
5492 self.edit_prediction_preview,
5493 EditPredictionPreview::Inactive { .. }
5494 ) {
5495 self.edit_prediction_preview = EditPredictionPreview::Active {
5496 previous_scroll_position: None,
5497 since: Instant::now(),
5498 };
5499
5500 self.update_visible_inline_completion(window, cx);
5501 cx.notify();
5502 }
5503 } else if let EditPredictionPreview::Active {
5504 previous_scroll_position,
5505 since,
5506 } = self.edit_prediction_preview
5507 {
5508 if let (Some(previous_scroll_position), Some(position_map)) =
5509 (previous_scroll_position, self.last_position_map.as_ref())
5510 {
5511 self.set_scroll_position(
5512 previous_scroll_position
5513 .scroll_position(&position_map.snapshot.display_snapshot),
5514 window,
5515 cx,
5516 );
5517 }
5518
5519 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5520 released_too_fast: since.elapsed() < Duration::from_millis(200),
5521 };
5522 self.clear_row_highlights::<EditPredictionPreview>();
5523 self.update_visible_inline_completion(window, cx);
5524 cx.notify();
5525 }
5526 }
5527
5528 fn update_visible_inline_completion(
5529 &mut self,
5530 _window: &mut Window,
5531 cx: &mut Context<Self>,
5532 ) -> Option<()> {
5533 let selection = self.selections.newest_anchor();
5534 let cursor = selection.head();
5535 let multibuffer = self.buffer.read(cx).snapshot(cx);
5536 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5537 let excerpt_id = cursor.excerpt_id;
5538
5539 let show_in_menu = self.show_edit_predictions_in_menu();
5540 let completions_menu_has_precedence = !show_in_menu
5541 && (self.context_menu.borrow().is_some()
5542 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5543
5544 if completions_menu_has_precedence
5545 || !offset_selection.is_empty()
5546 || self
5547 .active_inline_completion
5548 .as_ref()
5549 .map_or(false, |completion| {
5550 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5551 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5552 !invalidation_range.contains(&offset_selection.head())
5553 })
5554 {
5555 self.discard_inline_completion(false, cx);
5556 return None;
5557 }
5558
5559 self.take_active_inline_completion(cx);
5560 let Some(provider) = self.edit_prediction_provider() else {
5561 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5562 return None;
5563 };
5564
5565 let (buffer, cursor_buffer_position) =
5566 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5567
5568 self.edit_prediction_settings =
5569 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5570
5571 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5572
5573 if self.edit_prediction_indent_conflict {
5574 let cursor_point = cursor.to_point(&multibuffer);
5575
5576 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5577
5578 if let Some((_, indent)) = indents.iter().next() {
5579 if indent.len == cursor_point.column {
5580 self.edit_prediction_indent_conflict = false;
5581 }
5582 }
5583 }
5584
5585 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5586 let edits = inline_completion
5587 .edits
5588 .into_iter()
5589 .flat_map(|(range, new_text)| {
5590 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5591 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5592 Some((start..end, new_text))
5593 })
5594 .collect::<Vec<_>>();
5595 if edits.is_empty() {
5596 return None;
5597 }
5598
5599 let first_edit_start = edits.first().unwrap().0.start;
5600 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5601 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5602
5603 let last_edit_end = edits.last().unwrap().0.end;
5604 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5605 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5606
5607 let cursor_row = cursor.to_point(&multibuffer).row;
5608
5609 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5610
5611 let mut inlay_ids = Vec::new();
5612 let invalidation_row_range;
5613 let move_invalidation_row_range = if cursor_row < edit_start_row {
5614 Some(cursor_row..edit_end_row)
5615 } else if cursor_row > edit_end_row {
5616 Some(edit_start_row..cursor_row)
5617 } else {
5618 None
5619 };
5620 let is_move =
5621 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5622 let completion = if is_move {
5623 invalidation_row_range =
5624 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5625 let target = first_edit_start;
5626 InlineCompletion::Move { target, snapshot }
5627 } else {
5628 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5629 && !self.inline_completions_hidden_for_vim_mode;
5630
5631 if show_completions_in_buffer {
5632 if edits
5633 .iter()
5634 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5635 {
5636 let mut inlays = Vec::new();
5637 for (range, new_text) in &edits {
5638 let inlay = Inlay::inline_completion(
5639 post_inc(&mut self.next_inlay_id),
5640 range.start,
5641 new_text.as_str(),
5642 );
5643 inlay_ids.push(inlay.id);
5644 inlays.push(inlay);
5645 }
5646
5647 self.splice_inlays(&[], inlays, cx);
5648 } else {
5649 let background_color = cx.theme().status().deleted_background;
5650 self.highlight_text::<InlineCompletionHighlight>(
5651 edits.iter().map(|(range, _)| range.clone()).collect(),
5652 HighlightStyle {
5653 background_color: Some(background_color),
5654 ..Default::default()
5655 },
5656 cx,
5657 );
5658 }
5659 }
5660
5661 invalidation_row_range = edit_start_row..edit_end_row;
5662
5663 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5664 if provider.show_tab_accept_marker() {
5665 EditDisplayMode::TabAccept
5666 } else {
5667 EditDisplayMode::Inline
5668 }
5669 } else {
5670 EditDisplayMode::DiffPopover
5671 };
5672
5673 InlineCompletion::Edit {
5674 edits,
5675 edit_preview: inline_completion.edit_preview,
5676 display_mode,
5677 snapshot,
5678 }
5679 };
5680
5681 let invalidation_range = multibuffer
5682 .anchor_before(Point::new(invalidation_row_range.start, 0))
5683 ..multibuffer.anchor_after(Point::new(
5684 invalidation_row_range.end,
5685 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5686 ));
5687
5688 self.stale_inline_completion_in_menu = None;
5689 self.active_inline_completion = Some(InlineCompletionState {
5690 inlay_ids,
5691 completion,
5692 completion_id: inline_completion.id,
5693 invalidation_range,
5694 });
5695
5696 cx.notify();
5697
5698 Some(())
5699 }
5700
5701 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5702 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5703 }
5704
5705 fn render_code_actions_indicator(
5706 &self,
5707 _style: &EditorStyle,
5708 row: DisplayRow,
5709 is_active: bool,
5710 cx: &mut Context<Self>,
5711 ) -> Option<IconButton> {
5712 if self.available_code_actions.is_some() {
5713 Some(
5714 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5715 .shape(ui::IconButtonShape::Square)
5716 .icon_size(IconSize::XSmall)
5717 .icon_color(Color::Muted)
5718 .toggle_state(is_active)
5719 .tooltip({
5720 let focus_handle = self.focus_handle.clone();
5721 move |window, cx| {
5722 Tooltip::for_action_in(
5723 "Toggle Code Actions",
5724 &ToggleCodeActions {
5725 deployed_from_indicator: None,
5726 },
5727 &focus_handle,
5728 window,
5729 cx,
5730 )
5731 }
5732 })
5733 .on_click(cx.listener(move |editor, _e, window, cx| {
5734 window.focus(&editor.focus_handle(cx));
5735 editor.toggle_code_actions(
5736 &ToggleCodeActions {
5737 deployed_from_indicator: Some(row),
5738 },
5739 window,
5740 cx,
5741 );
5742 })),
5743 )
5744 } else {
5745 None
5746 }
5747 }
5748
5749 fn clear_tasks(&mut self) {
5750 self.tasks.clear()
5751 }
5752
5753 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5754 if self.tasks.insert(key, value).is_some() {
5755 // This case should hopefully be rare, but just in case...
5756 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5757 }
5758 }
5759
5760 fn build_tasks_context(
5761 project: &Entity<Project>,
5762 buffer: &Entity<Buffer>,
5763 buffer_row: u32,
5764 tasks: &Arc<RunnableTasks>,
5765 cx: &mut Context<Self>,
5766 ) -> Task<Option<task::TaskContext>> {
5767 let position = Point::new(buffer_row, tasks.column);
5768 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5769 let location = Location {
5770 buffer: buffer.clone(),
5771 range: range_start..range_start,
5772 };
5773 // Fill in the environmental variables from the tree-sitter captures
5774 let mut captured_task_variables = TaskVariables::default();
5775 for (capture_name, value) in tasks.extra_variables.clone() {
5776 captured_task_variables.insert(
5777 task::VariableName::Custom(capture_name.into()),
5778 value.clone(),
5779 );
5780 }
5781 project.update(cx, |project, cx| {
5782 project.task_store().update(cx, |task_store, cx| {
5783 task_store.task_context_for_location(captured_task_variables, location, cx)
5784 })
5785 })
5786 }
5787
5788 pub fn spawn_nearest_task(
5789 &mut self,
5790 action: &SpawnNearestTask,
5791 window: &mut Window,
5792 cx: &mut Context<Self>,
5793 ) {
5794 let Some((workspace, _)) = self.workspace.clone() else {
5795 return;
5796 };
5797 let Some(project) = self.project.clone() else {
5798 return;
5799 };
5800
5801 // Try to find a closest, enclosing node using tree-sitter that has a
5802 // task
5803 let Some((buffer, buffer_row, tasks)) = self
5804 .find_enclosing_node_task(cx)
5805 // Or find the task that's closest in row-distance.
5806 .or_else(|| self.find_closest_task(cx))
5807 else {
5808 return;
5809 };
5810
5811 let reveal_strategy = action.reveal;
5812 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5813 cx.spawn_in(window, |_, mut cx| async move {
5814 let context = task_context.await?;
5815 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5816
5817 let resolved = resolved_task.resolved.as_mut()?;
5818 resolved.reveal = reveal_strategy;
5819
5820 workspace
5821 .update(&mut cx, |workspace, cx| {
5822 workspace::tasks::schedule_resolved_task(
5823 workspace,
5824 task_source_kind,
5825 resolved_task,
5826 false,
5827 cx,
5828 );
5829 })
5830 .ok()
5831 })
5832 .detach();
5833 }
5834
5835 fn find_closest_task(
5836 &mut self,
5837 cx: &mut Context<Self>,
5838 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5839 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5840
5841 let ((buffer_id, row), tasks) = self
5842 .tasks
5843 .iter()
5844 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5845
5846 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5847 let tasks = Arc::new(tasks.to_owned());
5848 Some((buffer, *row, tasks))
5849 }
5850
5851 fn find_enclosing_node_task(
5852 &mut self,
5853 cx: &mut Context<Self>,
5854 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5855 let snapshot = self.buffer.read(cx).snapshot(cx);
5856 let offset = self.selections.newest::<usize>(cx).head();
5857 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5858 let buffer_id = excerpt.buffer().remote_id();
5859
5860 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5861 let mut cursor = layer.node().walk();
5862
5863 while cursor.goto_first_child_for_byte(offset).is_some() {
5864 if cursor.node().end_byte() == offset {
5865 cursor.goto_next_sibling();
5866 }
5867 }
5868
5869 // Ascend to the smallest ancestor that contains the range and has a task.
5870 loop {
5871 let node = cursor.node();
5872 let node_range = node.byte_range();
5873 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5874
5875 // Check if this node contains our offset
5876 if node_range.start <= offset && node_range.end >= offset {
5877 // If it contains offset, check for task
5878 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5879 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5880 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5881 }
5882 }
5883
5884 if !cursor.goto_parent() {
5885 break;
5886 }
5887 }
5888 None
5889 }
5890
5891 fn render_run_indicator(
5892 &self,
5893 _style: &EditorStyle,
5894 is_active: bool,
5895 row: DisplayRow,
5896 cx: &mut Context<Self>,
5897 ) -> IconButton {
5898 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5899 .shape(ui::IconButtonShape::Square)
5900 .icon_size(IconSize::XSmall)
5901 .icon_color(Color::Muted)
5902 .toggle_state(is_active)
5903 .on_click(cx.listener(move |editor, _e, window, cx| {
5904 window.focus(&editor.focus_handle(cx));
5905 editor.toggle_code_actions(
5906 &ToggleCodeActions {
5907 deployed_from_indicator: Some(row),
5908 },
5909 window,
5910 cx,
5911 );
5912 }))
5913 }
5914
5915 pub fn context_menu_visible(&self) -> bool {
5916 !self.edit_prediction_preview_is_active()
5917 && self
5918 .context_menu
5919 .borrow()
5920 .as_ref()
5921 .map_or(false, |menu| menu.visible())
5922 }
5923
5924 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5925 self.context_menu
5926 .borrow()
5927 .as_ref()
5928 .map(|menu| menu.origin())
5929 }
5930
5931 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5932 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5933
5934 #[allow(clippy::too_many_arguments)]
5935 fn render_edit_prediction_popover(
5936 &mut self,
5937 text_bounds: &Bounds<Pixels>,
5938 content_origin: gpui::Point<Pixels>,
5939 editor_snapshot: &EditorSnapshot,
5940 visible_row_range: Range<DisplayRow>,
5941 scroll_top: f32,
5942 scroll_bottom: f32,
5943 line_layouts: &[LineWithInvisibles],
5944 line_height: Pixels,
5945 scroll_pixel_position: gpui::Point<Pixels>,
5946 newest_selection_head: Option<DisplayPoint>,
5947 editor_width: Pixels,
5948 style: &EditorStyle,
5949 window: &mut Window,
5950 cx: &mut App,
5951 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5952 let active_inline_completion = self.active_inline_completion.as_ref()?;
5953
5954 if self.edit_prediction_visible_in_cursor_popover(true) {
5955 return None;
5956 }
5957
5958 match &active_inline_completion.completion {
5959 InlineCompletion::Move { target, .. } => {
5960 let target_display_point = target.to_display_point(editor_snapshot);
5961
5962 if self.edit_prediction_requires_modifier() {
5963 if !self.edit_prediction_preview_is_active() {
5964 return None;
5965 }
5966
5967 self.render_edit_prediction_modifier_jump_popover(
5968 text_bounds,
5969 content_origin,
5970 visible_row_range,
5971 line_layouts,
5972 line_height,
5973 scroll_pixel_position,
5974 newest_selection_head,
5975 target_display_point,
5976 window,
5977 cx,
5978 )
5979 } else {
5980 self.render_edit_prediction_eager_jump_popover(
5981 text_bounds,
5982 content_origin,
5983 editor_snapshot,
5984 visible_row_range,
5985 scroll_top,
5986 scroll_bottom,
5987 line_height,
5988 scroll_pixel_position,
5989 target_display_point,
5990 editor_width,
5991 window,
5992 cx,
5993 )
5994 }
5995 }
5996 InlineCompletion::Edit {
5997 display_mode: EditDisplayMode::Inline,
5998 ..
5999 } => None,
6000 InlineCompletion::Edit {
6001 display_mode: EditDisplayMode::TabAccept,
6002 edits,
6003 ..
6004 } => {
6005 let range = &edits.first()?.0;
6006 let target_display_point = range.end.to_display_point(editor_snapshot);
6007
6008 self.render_edit_prediction_end_of_line_popover(
6009 "Accept",
6010 editor_snapshot,
6011 visible_row_range,
6012 target_display_point,
6013 line_height,
6014 scroll_pixel_position,
6015 content_origin,
6016 editor_width,
6017 window,
6018 cx,
6019 )
6020 }
6021 InlineCompletion::Edit {
6022 edits,
6023 edit_preview,
6024 display_mode: EditDisplayMode::DiffPopover,
6025 snapshot,
6026 } => self.render_edit_prediction_diff_popover(
6027 text_bounds,
6028 content_origin,
6029 editor_snapshot,
6030 visible_row_range,
6031 line_layouts,
6032 line_height,
6033 scroll_pixel_position,
6034 newest_selection_head,
6035 editor_width,
6036 style,
6037 edits,
6038 edit_preview,
6039 snapshot,
6040 window,
6041 cx,
6042 ),
6043 }
6044 }
6045
6046 #[allow(clippy::too_many_arguments)]
6047 fn render_edit_prediction_modifier_jump_popover(
6048 &mut self,
6049 text_bounds: &Bounds<Pixels>,
6050 content_origin: gpui::Point<Pixels>,
6051 visible_row_range: Range<DisplayRow>,
6052 line_layouts: &[LineWithInvisibles],
6053 line_height: Pixels,
6054 scroll_pixel_position: gpui::Point<Pixels>,
6055 newest_selection_head: Option<DisplayPoint>,
6056 target_display_point: DisplayPoint,
6057 window: &mut Window,
6058 cx: &mut App,
6059 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6060 let scrolled_content_origin =
6061 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6062
6063 const SCROLL_PADDING_Y: Pixels = px(12.);
6064
6065 if target_display_point.row() < visible_row_range.start {
6066 return self.render_edit_prediction_scroll_popover(
6067 |_| SCROLL_PADDING_Y,
6068 IconName::ArrowUp,
6069 visible_row_range,
6070 line_layouts,
6071 newest_selection_head,
6072 scrolled_content_origin,
6073 window,
6074 cx,
6075 );
6076 } else if target_display_point.row() >= visible_row_range.end {
6077 return self.render_edit_prediction_scroll_popover(
6078 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6079 IconName::ArrowDown,
6080 visible_row_range,
6081 line_layouts,
6082 newest_selection_head,
6083 scrolled_content_origin,
6084 window,
6085 cx,
6086 );
6087 }
6088
6089 const POLE_WIDTH: Pixels = px(2.);
6090
6091 let line_layout =
6092 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6093 let target_column = target_display_point.column() as usize;
6094
6095 let target_x = line_layout.x_for_index(target_column);
6096 let target_y =
6097 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6098
6099 let flag_on_right = target_x < text_bounds.size.width / 2.;
6100
6101 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6102 border_color.l += 0.001;
6103
6104 let mut element = v_flex()
6105 .items_end()
6106 .when(flag_on_right, |el| el.items_start())
6107 .child(if flag_on_right {
6108 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6109 .rounded_bl(px(0.))
6110 .rounded_tl(px(0.))
6111 .border_l_2()
6112 .border_color(border_color)
6113 } else {
6114 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6115 .rounded_br(px(0.))
6116 .rounded_tr(px(0.))
6117 .border_r_2()
6118 .border_color(border_color)
6119 })
6120 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6121 .into_any();
6122
6123 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6124
6125 let mut origin = scrolled_content_origin + point(target_x, target_y)
6126 - point(
6127 if flag_on_right {
6128 POLE_WIDTH
6129 } else {
6130 size.width - POLE_WIDTH
6131 },
6132 size.height - line_height,
6133 );
6134
6135 origin.x = origin.x.max(content_origin.x);
6136
6137 element.prepaint_at(origin, window, cx);
6138
6139 Some((element, origin))
6140 }
6141
6142 #[allow(clippy::too_many_arguments)]
6143 fn render_edit_prediction_scroll_popover(
6144 &mut self,
6145 to_y: impl Fn(Size<Pixels>) -> Pixels,
6146 scroll_icon: IconName,
6147 visible_row_range: Range<DisplayRow>,
6148 line_layouts: &[LineWithInvisibles],
6149 newest_selection_head: Option<DisplayPoint>,
6150 scrolled_content_origin: gpui::Point<Pixels>,
6151 window: &mut Window,
6152 cx: &mut App,
6153 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6154 let mut element = self
6155 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6156 .into_any();
6157
6158 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6159
6160 let cursor = newest_selection_head?;
6161 let cursor_row_layout =
6162 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6163 let cursor_column = cursor.column() as usize;
6164
6165 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6166
6167 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6168
6169 element.prepaint_at(origin, window, cx);
6170 Some((element, origin))
6171 }
6172
6173 #[allow(clippy::too_many_arguments)]
6174 fn render_edit_prediction_eager_jump_popover(
6175 &mut self,
6176 text_bounds: &Bounds<Pixels>,
6177 content_origin: gpui::Point<Pixels>,
6178 editor_snapshot: &EditorSnapshot,
6179 visible_row_range: Range<DisplayRow>,
6180 scroll_top: f32,
6181 scroll_bottom: f32,
6182 line_height: Pixels,
6183 scroll_pixel_position: gpui::Point<Pixels>,
6184 target_display_point: DisplayPoint,
6185 editor_width: Pixels,
6186 window: &mut Window,
6187 cx: &mut App,
6188 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6189 if target_display_point.row().as_f32() < scroll_top {
6190 let mut element = self
6191 .render_edit_prediction_line_popover(
6192 "Jump to Edit",
6193 Some(IconName::ArrowUp),
6194 window,
6195 cx,
6196 )?
6197 .into_any();
6198
6199 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6200 let offset = point(
6201 (text_bounds.size.width - size.width) / 2.,
6202 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6203 );
6204
6205 let origin = text_bounds.origin + offset;
6206 element.prepaint_at(origin, window, cx);
6207 Some((element, origin))
6208 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6209 let mut element = self
6210 .render_edit_prediction_line_popover(
6211 "Jump to Edit",
6212 Some(IconName::ArrowDown),
6213 window,
6214 cx,
6215 )?
6216 .into_any();
6217
6218 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6219 let offset = point(
6220 (text_bounds.size.width - size.width) / 2.,
6221 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6222 );
6223
6224 let origin = text_bounds.origin + offset;
6225 element.prepaint_at(origin, window, cx);
6226 Some((element, origin))
6227 } else {
6228 self.render_edit_prediction_end_of_line_popover(
6229 "Jump to Edit",
6230 editor_snapshot,
6231 visible_row_range,
6232 target_display_point,
6233 line_height,
6234 scroll_pixel_position,
6235 content_origin,
6236 editor_width,
6237 window,
6238 cx,
6239 )
6240 }
6241 }
6242
6243 #[allow(clippy::too_many_arguments)]
6244 fn render_edit_prediction_end_of_line_popover(
6245 self: &mut Editor,
6246 label: &'static str,
6247 editor_snapshot: &EditorSnapshot,
6248 visible_row_range: Range<DisplayRow>,
6249 target_display_point: DisplayPoint,
6250 line_height: Pixels,
6251 scroll_pixel_position: gpui::Point<Pixels>,
6252 content_origin: gpui::Point<Pixels>,
6253 editor_width: Pixels,
6254 window: &mut Window,
6255 cx: &mut App,
6256 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6257 let target_line_end = DisplayPoint::new(
6258 target_display_point.row(),
6259 editor_snapshot.line_len(target_display_point.row()),
6260 );
6261
6262 let mut element = self
6263 .render_edit_prediction_line_popover(label, None, window, cx)?
6264 .into_any();
6265
6266 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6267
6268 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6269
6270 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6271 let mut origin = start_point
6272 + line_origin
6273 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6274 origin.x = origin.x.max(content_origin.x);
6275
6276 let max_x = content_origin.x + editor_width - size.width;
6277
6278 if origin.x > max_x {
6279 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6280
6281 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6282 origin.y += offset;
6283 IconName::ArrowUp
6284 } else {
6285 origin.y -= offset;
6286 IconName::ArrowDown
6287 };
6288
6289 element = self
6290 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6291 .into_any();
6292
6293 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6294
6295 origin.x = content_origin.x + editor_width - size.width - px(2.);
6296 }
6297
6298 element.prepaint_at(origin, window, cx);
6299 Some((element, origin))
6300 }
6301
6302 #[allow(clippy::too_many_arguments)]
6303 fn render_edit_prediction_diff_popover(
6304 self: &Editor,
6305 text_bounds: &Bounds<Pixels>,
6306 content_origin: gpui::Point<Pixels>,
6307 editor_snapshot: &EditorSnapshot,
6308 visible_row_range: Range<DisplayRow>,
6309 line_layouts: &[LineWithInvisibles],
6310 line_height: Pixels,
6311 scroll_pixel_position: gpui::Point<Pixels>,
6312 newest_selection_head: Option<DisplayPoint>,
6313 editor_width: Pixels,
6314 style: &EditorStyle,
6315 edits: &Vec<(Range<Anchor>, String)>,
6316 edit_preview: &Option<language::EditPreview>,
6317 snapshot: &language::BufferSnapshot,
6318 window: &mut Window,
6319 cx: &mut App,
6320 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6321 let edit_start = edits
6322 .first()
6323 .unwrap()
6324 .0
6325 .start
6326 .to_display_point(editor_snapshot);
6327 let edit_end = edits
6328 .last()
6329 .unwrap()
6330 .0
6331 .end
6332 .to_display_point(editor_snapshot);
6333
6334 let is_visible = visible_row_range.contains(&edit_start.row())
6335 || visible_row_range.contains(&edit_end.row());
6336 if !is_visible {
6337 return None;
6338 }
6339
6340 let highlighted_edits =
6341 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6342
6343 let styled_text = highlighted_edits.to_styled_text(&style.text);
6344 let line_count = highlighted_edits.text.lines().count();
6345
6346 const BORDER_WIDTH: Pixels = px(1.);
6347
6348 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6349 let has_keybind = keybind.is_some();
6350
6351 let mut element = h_flex()
6352 .items_start()
6353 .child(
6354 h_flex()
6355 .bg(cx.theme().colors().editor_background)
6356 .border(BORDER_WIDTH)
6357 .shadow_sm()
6358 .border_color(cx.theme().colors().border)
6359 .rounded_l_lg()
6360 .when(line_count > 1, |el| el.rounded_br_lg())
6361 .pr_1()
6362 .child(styled_text),
6363 )
6364 .child(
6365 h_flex()
6366 .h(line_height + BORDER_WIDTH * px(2.))
6367 .px_1p5()
6368 .gap_1()
6369 // Workaround: For some reason, there's a gap if we don't do this
6370 .ml(-BORDER_WIDTH)
6371 .shadow(smallvec![gpui::BoxShadow {
6372 color: gpui::black().opacity(0.05),
6373 offset: point(px(1.), px(1.)),
6374 blur_radius: px(2.),
6375 spread_radius: px(0.),
6376 }])
6377 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6378 .border(BORDER_WIDTH)
6379 .border_color(cx.theme().colors().border)
6380 .rounded_r_lg()
6381 .id("edit_prediction_diff_popover_keybind")
6382 .when(!has_keybind, |el| {
6383 let status_colors = cx.theme().status();
6384
6385 el.bg(status_colors.error_background)
6386 .border_color(status_colors.error.opacity(0.6))
6387 .child(Icon::new(IconName::Info).color(Color::Error))
6388 .cursor_default()
6389 .hoverable_tooltip(move |_window, cx| {
6390 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6391 })
6392 })
6393 .children(keybind),
6394 )
6395 .into_any();
6396
6397 let longest_row =
6398 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6399 let longest_line_width = if visible_row_range.contains(&longest_row) {
6400 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6401 } else {
6402 layout_line(
6403 longest_row,
6404 editor_snapshot,
6405 style,
6406 editor_width,
6407 |_| false,
6408 window,
6409 cx,
6410 )
6411 .width
6412 };
6413
6414 let viewport_bounds =
6415 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6416 right: -EditorElement::SCROLLBAR_WIDTH,
6417 ..Default::default()
6418 });
6419
6420 let x_after_longest =
6421 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6422 - scroll_pixel_position.x;
6423
6424 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6425
6426 // Fully visible if it can be displayed within the window (allow overlapping other
6427 // panes). However, this is only allowed if the popover starts within text_bounds.
6428 let can_position_to_the_right = x_after_longest < text_bounds.right()
6429 && x_after_longest + element_bounds.width < viewport_bounds.right();
6430
6431 let mut origin = if can_position_to_the_right {
6432 point(
6433 x_after_longest,
6434 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6435 - scroll_pixel_position.y,
6436 )
6437 } else {
6438 let cursor_row = newest_selection_head.map(|head| head.row());
6439 let above_edit = edit_start
6440 .row()
6441 .0
6442 .checked_sub(line_count as u32)
6443 .map(DisplayRow);
6444 let below_edit = Some(edit_end.row() + 1);
6445 let above_cursor =
6446 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6447 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6448
6449 // Place the edit popover adjacent to the edit if there is a location
6450 // available that is onscreen and does not obscure the cursor. Otherwise,
6451 // place it adjacent to the cursor.
6452 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6453 .into_iter()
6454 .flatten()
6455 .find(|&start_row| {
6456 let end_row = start_row + line_count as u32;
6457 visible_row_range.contains(&start_row)
6458 && visible_row_range.contains(&end_row)
6459 && cursor_row.map_or(true, |cursor_row| {
6460 !((start_row..end_row).contains(&cursor_row))
6461 })
6462 })?;
6463
6464 content_origin
6465 + point(
6466 -scroll_pixel_position.x,
6467 row_target.as_f32() * line_height - scroll_pixel_position.y,
6468 )
6469 };
6470
6471 origin.x -= BORDER_WIDTH;
6472
6473 window.defer_draw(element, origin, 1);
6474
6475 // Do not return an element, since it will already be drawn due to defer_draw.
6476 None
6477 }
6478
6479 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6480 px(30.)
6481 }
6482
6483 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6484 if self.read_only(cx) {
6485 cx.theme().players().read_only()
6486 } else {
6487 self.style.as_ref().unwrap().local_player
6488 }
6489 }
6490
6491 fn render_edit_prediction_accept_keybind(
6492 &self,
6493 window: &mut Window,
6494 cx: &App,
6495 ) -> Option<AnyElement> {
6496 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6497 let accept_keystroke = accept_binding.keystroke()?;
6498
6499 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6500
6501 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6502 Color::Accent
6503 } else {
6504 Color::Muted
6505 };
6506
6507 h_flex()
6508 .px_0p5()
6509 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6510 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6511 .text_size(TextSize::XSmall.rems(cx))
6512 .child(h_flex().children(ui::render_modifiers(
6513 &accept_keystroke.modifiers,
6514 PlatformStyle::platform(),
6515 Some(modifiers_color),
6516 Some(IconSize::XSmall.rems().into()),
6517 true,
6518 )))
6519 .when(is_platform_style_mac, |parent| {
6520 parent.child(accept_keystroke.key.clone())
6521 })
6522 .when(!is_platform_style_mac, |parent| {
6523 parent.child(
6524 Key::new(
6525 util::capitalize(&accept_keystroke.key),
6526 Some(Color::Default),
6527 )
6528 .size(Some(IconSize::XSmall.rems().into())),
6529 )
6530 })
6531 .into_any()
6532 .into()
6533 }
6534
6535 fn render_edit_prediction_line_popover(
6536 &self,
6537 label: impl Into<SharedString>,
6538 icon: Option<IconName>,
6539 window: &mut Window,
6540 cx: &App,
6541 ) -> Option<Stateful<Div>> {
6542 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6543
6544 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6545 let has_keybind = keybind.is_some();
6546
6547 let result = h_flex()
6548 .id("ep-line-popover")
6549 .py_0p5()
6550 .pl_1()
6551 .pr(padding_right)
6552 .gap_1()
6553 .rounded(px(6.))
6554 .border_1()
6555 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6556 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6557 .shadow_sm()
6558 .when(!has_keybind, |el| {
6559 let status_colors = cx.theme().status();
6560
6561 el.bg(status_colors.error_background)
6562 .border_color(status_colors.error.opacity(0.6))
6563 .pl_2()
6564 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
6565 .cursor_default()
6566 .hoverable_tooltip(move |_window, cx| {
6567 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6568 })
6569 })
6570 .children(keybind)
6571 .child(
6572 Label::new(label)
6573 .size(LabelSize::Small)
6574 .when(!has_keybind, |el| {
6575 el.color(cx.theme().status().error.into()).strikethrough()
6576 }),
6577 )
6578 .when(!has_keybind, |el| {
6579 el.child(
6580 h_flex().ml_1().child(
6581 Icon::new(IconName::Info)
6582 .size(IconSize::Small)
6583 .color(cx.theme().status().error.into()),
6584 ),
6585 )
6586 })
6587 .when_some(icon, |element, icon| {
6588 element.child(
6589 div()
6590 .mt(px(1.5))
6591 .child(Icon::new(icon).size(IconSize::Small)),
6592 )
6593 });
6594
6595 Some(result)
6596 }
6597
6598 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6599 let accent_color = cx.theme().colors().text_accent;
6600 let editor_bg_color = cx.theme().colors().editor_background;
6601 editor_bg_color.blend(accent_color.opacity(0.1))
6602 }
6603
6604 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6605 let accent_color = cx.theme().colors().text_accent;
6606 let editor_bg_color = cx.theme().colors().editor_background;
6607 editor_bg_color.blend(accent_color.opacity(0.6))
6608 }
6609
6610 #[allow(clippy::too_many_arguments)]
6611 fn render_edit_prediction_cursor_popover(
6612 &self,
6613 min_width: Pixels,
6614 max_width: Pixels,
6615 cursor_point: Point,
6616 style: &EditorStyle,
6617 accept_keystroke: Option<&gpui::Keystroke>,
6618 _window: &Window,
6619 cx: &mut Context<Editor>,
6620 ) -> Option<AnyElement> {
6621 let provider = self.edit_prediction_provider.as_ref()?;
6622
6623 if provider.provider.needs_terms_acceptance(cx) {
6624 return Some(
6625 h_flex()
6626 .min_w(min_width)
6627 .flex_1()
6628 .px_2()
6629 .py_1()
6630 .gap_3()
6631 .elevation_2(cx)
6632 .hover(|style| style.bg(cx.theme().colors().element_hover))
6633 .id("accept-terms")
6634 .cursor_pointer()
6635 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6636 .on_click(cx.listener(|this, _event, window, cx| {
6637 cx.stop_propagation();
6638 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6639 window.dispatch_action(
6640 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6641 cx,
6642 );
6643 }))
6644 .child(
6645 h_flex()
6646 .flex_1()
6647 .gap_2()
6648 .child(Icon::new(IconName::ZedPredict))
6649 .child(Label::new("Accept Terms of Service"))
6650 .child(div().w_full())
6651 .child(
6652 Icon::new(IconName::ArrowUpRight)
6653 .color(Color::Muted)
6654 .size(IconSize::Small),
6655 )
6656 .into_any_element(),
6657 )
6658 .into_any(),
6659 );
6660 }
6661
6662 let is_refreshing = provider.provider.is_refreshing(cx);
6663
6664 fn pending_completion_container() -> Div {
6665 h_flex()
6666 .h_full()
6667 .flex_1()
6668 .gap_2()
6669 .child(Icon::new(IconName::ZedPredict))
6670 }
6671
6672 let completion = match &self.active_inline_completion {
6673 Some(prediction) => {
6674 if !self.has_visible_completions_menu() {
6675 const RADIUS: Pixels = px(6.);
6676 const BORDER_WIDTH: Pixels = px(1.);
6677
6678 return Some(
6679 h_flex()
6680 .elevation_2(cx)
6681 .border(BORDER_WIDTH)
6682 .border_color(cx.theme().colors().border)
6683 .when(accept_keystroke.is_none(), |el| {
6684 el.border_color(cx.theme().status().error)
6685 })
6686 .rounded(RADIUS)
6687 .rounded_tl(px(0.))
6688 .overflow_hidden()
6689 .child(div().px_1p5().child(match &prediction.completion {
6690 InlineCompletion::Move { target, snapshot } => {
6691 use text::ToPoint as _;
6692 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6693 {
6694 Icon::new(IconName::ZedPredictDown)
6695 } else {
6696 Icon::new(IconName::ZedPredictUp)
6697 }
6698 }
6699 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6700 }))
6701 .child(
6702 h_flex()
6703 .gap_1()
6704 .py_1()
6705 .px_2()
6706 .rounded_r(RADIUS - BORDER_WIDTH)
6707 .border_l_1()
6708 .border_color(cx.theme().colors().border)
6709 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6710 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6711 el.child(
6712 Label::new("Hold")
6713 .size(LabelSize::Small)
6714 .when(accept_keystroke.is_none(), |el| {
6715 el.strikethrough()
6716 })
6717 .line_height_style(LineHeightStyle::UiLabel),
6718 )
6719 })
6720 .id("edit_prediction_cursor_popover_keybind")
6721 .when(accept_keystroke.is_none(), |el| {
6722 let status_colors = cx.theme().status();
6723
6724 el.bg(status_colors.error_background)
6725 .border_color(status_colors.error.opacity(0.6))
6726 .child(Icon::new(IconName::Info).color(Color::Error))
6727 .cursor_default()
6728 .hoverable_tooltip(move |_window, cx| {
6729 cx.new(|_| MissingEditPredictionKeybindingTooltip)
6730 .into()
6731 })
6732 })
6733 .when_some(
6734 accept_keystroke.as_ref(),
6735 |el, accept_keystroke| {
6736 el.child(h_flex().children(ui::render_modifiers(
6737 &accept_keystroke.modifiers,
6738 PlatformStyle::platform(),
6739 Some(Color::Default),
6740 Some(IconSize::XSmall.rems().into()),
6741 false,
6742 )))
6743 },
6744 ),
6745 )
6746 .into_any(),
6747 );
6748 }
6749
6750 self.render_edit_prediction_cursor_popover_preview(
6751 prediction,
6752 cursor_point,
6753 style,
6754 cx,
6755 )?
6756 }
6757
6758 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6759 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6760 stale_completion,
6761 cursor_point,
6762 style,
6763 cx,
6764 )?,
6765
6766 None => {
6767 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6768 }
6769 },
6770
6771 None => pending_completion_container().child(Label::new("No Prediction")),
6772 };
6773
6774 let completion = if is_refreshing {
6775 completion
6776 .with_animation(
6777 "loading-completion",
6778 Animation::new(Duration::from_secs(2))
6779 .repeat()
6780 .with_easing(pulsating_between(0.4, 0.8)),
6781 |label, delta| label.opacity(delta),
6782 )
6783 .into_any_element()
6784 } else {
6785 completion.into_any_element()
6786 };
6787
6788 let has_completion = self.active_inline_completion.is_some();
6789
6790 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6791 Some(
6792 h_flex()
6793 .min_w(min_width)
6794 .max_w(max_width)
6795 .flex_1()
6796 .elevation_2(cx)
6797 .border_color(cx.theme().colors().border)
6798 .child(
6799 div()
6800 .flex_1()
6801 .py_1()
6802 .px_2()
6803 .overflow_hidden()
6804 .child(completion),
6805 )
6806 .when_some(accept_keystroke, |el, accept_keystroke| {
6807 if !accept_keystroke.modifiers.modified() {
6808 return el;
6809 }
6810
6811 el.child(
6812 h_flex()
6813 .h_full()
6814 .border_l_1()
6815 .rounded_r_lg()
6816 .border_color(cx.theme().colors().border)
6817 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6818 .gap_1()
6819 .py_1()
6820 .px_2()
6821 .child(
6822 h_flex()
6823 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6824 .when(is_platform_style_mac, |parent| parent.gap_1())
6825 .child(h_flex().children(ui::render_modifiers(
6826 &accept_keystroke.modifiers,
6827 PlatformStyle::platform(),
6828 Some(if !has_completion {
6829 Color::Muted
6830 } else {
6831 Color::Default
6832 }),
6833 None,
6834 false,
6835 ))),
6836 )
6837 .child(Label::new("Preview").into_any_element())
6838 .opacity(if has_completion { 1.0 } else { 0.4 }),
6839 )
6840 })
6841 .into_any(),
6842 )
6843 }
6844
6845 fn render_edit_prediction_cursor_popover_preview(
6846 &self,
6847 completion: &InlineCompletionState,
6848 cursor_point: Point,
6849 style: &EditorStyle,
6850 cx: &mut Context<Editor>,
6851 ) -> Option<Div> {
6852 use text::ToPoint as _;
6853
6854 fn render_relative_row_jump(
6855 prefix: impl Into<String>,
6856 current_row: u32,
6857 target_row: u32,
6858 ) -> Div {
6859 let (row_diff, arrow) = if target_row < current_row {
6860 (current_row - target_row, IconName::ArrowUp)
6861 } else {
6862 (target_row - current_row, IconName::ArrowDown)
6863 };
6864
6865 h_flex()
6866 .child(
6867 Label::new(format!("{}{}", prefix.into(), row_diff))
6868 .color(Color::Muted)
6869 .size(LabelSize::Small),
6870 )
6871 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6872 }
6873
6874 match &completion.completion {
6875 InlineCompletion::Move {
6876 target, snapshot, ..
6877 } => Some(
6878 h_flex()
6879 .px_2()
6880 .gap_2()
6881 .flex_1()
6882 .child(
6883 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6884 Icon::new(IconName::ZedPredictDown)
6885 } else {
6886 Icon::new(IconName::ZedPredictUp)
6887 },
6888 )
6889 .child(Label::new("Jump to Edit")),
6890 ),
6891
6892 InlineCompletion::Edit {
6893 edits,
6894 edit_preview,
6895 snapshot,
6896 display_mode: _,
6897 } => {
6898 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6899
6900 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6901 &snapshot,
6902 &edits,
6903 edit_preview.as_ref()?,
6904 true,
6905 cx,
6906 )
6907 .first_line_preview();
6908
6909 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6910 .with_default_highlights(&style.text, highlighted_edits.highlights);
6911
6912 let preview = h_flex()
6913 .gap_1()
6914 .min_w_16()
6915 .child(styled_text)
6916 .when(has_more_lines, |parent| parent.child("…"));
6917
6918 let left = if first_edit_row != cursor_point.row {
6919 render_relative_row_jump("", cursor_point.row, first_edit_row)
6920 .into_any_element()
6921 } else {
6922 Icon::new(IconName::ZedPredict).into_any_element()
6923 };
6924
6925 Some(
6926 h_flex()
6927 .h_full()
6928 .flex_1()
6929 .gap_2()
6930 .pr_1()
6931 .overflow_x_hidden()
6932 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6933 .child(left)
6934 .child(preview),
6935 )
6936 }
6937 }
6938 }
6939
6940 fn render_context_menu(
6941 &self,
6942 style: &EditorStyle,
6943 max_height_in_lines: u32,
6944 y_flipped: bool,
6945 window: &mut Window,
6946 cx: &mut Context<Editor>,
6947 ) -> Option<AnyElement> {
6948 let menu = self.context_menu.borrow();
6949 let menu = menu.as_ref()?;
6950 if !menu.visible() {
6951 return None;
6952 };
6953 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6954 }
6955
6956 fn render_context_menu_aside(
6957 &mut self,
6958 max_size: Size<Pixels>,
6959 window: &mut Window,
6960 cx: &mut Context<Editor>,
6961 ) -> Option<AnyElement> {
6962 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6963 if menu.visible() {
6964 menu.render_aside(self, max_size, window, cx)
6965 } else {
6966 None
6967 }
6968 })
6969 }
6970
6971 fn hide_context_menu(
6972 &mut self,
6973 window: &mut Window,
6974 cx: &mut Context<Self>,
6975 ) -> Option<CodeContextMenu> {
6976 cx.notify();
6977 self.completion_tasks.clear();
6978 let context_menu = self.context_menu.borrow_mut().take();
6979 self.stale_inline_completion_in_menu.take();
6980 self.update_visible_inline_completion(window, cx);
6981 context_menu
6982 }
6983
6984 fn show_snippet_choices(
6985 &mut self,
6986 choices: &Vec<String>,
6987 selection: Range<Anchor>,
6988 cx: &mut Context<Self>,
6989 ) {
6990 if selection.start.buffer_id.is_none() {
6991 return;
6992 }
6993 let buffer_id = selection.start.buffer_id.unwrap();
6994 let buffer = self.buffer().read(cx).buffer(buffer_id);
6995 let id = post_inc(&mut self.next_completion_id);
6996
6997 if let Some(buffer) = buffer {
6998 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6999 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7000 ));
7001 }
7002 }
7003
7004 pub fn insert_snippet(
7005 &mut self,
7006 insertion_ranges: &[Range<usize>],
7007 snippet: Snippet,
7008 window: &mut Window,
7009 cx: &mut Context<Self>,
7010 ) -> Result<()> {
7011 struct Tabstop<T> {
7012 is_end_tabstop: bool,
7013 ranges: Vec<Range<T>>,
7014 choices: Option<Vec<String>>,
7015 }
7016
7017 let tabstops = self.buffer.update(cx, |buffer, cx| {
7018 let snippet_text: Arc<str> = snippet.text.clone().into();
7019 buffer.edit(
7020 insertion_ranges
7021 .iter()
7022 .cloned()
7023 .map(|range| (range, snippet_text.clone())),
7024 Some(AutoindentMode::EachLine),
7025 cx,
7026 );
7027
7028 let snapshot = &*buffer.read(cx);
7029 let snippet = &snippet;
7030 snippet
7031 .tabstops
7032 .iter()
7033 .map(|tabstop| {
7034 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7035 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7036 });
7037 let mut tabstop_ranges = tabstop
7038 .ranges
7039 .iter()
7040 .flat_map(|tabstop_range| {
7041 let mut delta = 0_isize;
7042 insertion_ranges.iter().map(move |insertion_range| {
7043 let insertion_start = insertion_range.start as isize + delta;
7044 delta +=
7045 snippet.text.len() as isize - insertion_range.len() as isize;
7046
7047 let start = ((insertion_start + tabstop_range.start) as usize)
7048 .min(snapshot.len());
7049 let end = ((insertion_start + tabstop_range.end) as usize)
7050 .min(snapshot.len());
7051 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7052 })
7053 })
7054 .collect::<Vec<_>>();
7055 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7056
7057 Tabstop {
7058 is_end_tabstop,
7059 ranges: tabstop_ranges,
7060 choices: tabstop.choices.clone(),
7061 }
7062 })
7063 .collect::<Vec<_>>()
7064 });
7065 if let Some(tabstop) = tabstops.first() {
7066 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7067 s.select_ranges(tabstop.ranges.iter().cloned());
7068 });
7069
7070 if let Some(choices) = &tabstop.choices {
7071 if let Some(selection) = tabstop.ranges.first() {
7072 self.show_snippet_choices(choices, selection.clone(), cx)
7073 }
7074 }
7075
7076 // If we're already at the last tabstop and it's at the end of the snippet,
7077 // we're done, we don't need to keep the state around.
7078 if !tabstop.is_end_tabstop {
7079 let choices = tabstops
7080 .iter()
7081 .map(|tabstop| tabstop.choices.clone())
7082 .collect();
7083
7084 let ranges = tabstops
7085 .into_iter()
7086 .map(|tabstop| tabstop.ranges)
7087 .collect::<Vec<_>>();
7088
7089 self.snippet_stack.push(SnippetState {
7090 active_index: 0,
7091 ranges,
7092 choices,
7093 });
7094 }
7095
7096 // Check whether the just-entered snippet ends with an auto-closable bracket.
7097 if self.autoclose_regions.is_empty() {
7098 let snapshot = self.buffer.read(cx).snapshot(cx);
7099 for selection in &mut self.selections.all::<Point>(cx) {
7100 let selection_head = selection.head();
7101 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7102 continue;
7103 };
7104
7105 let mut bracket_pair = None;
7106 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7107 let prev_chars = snapshot
7108 .reversed_chars_at(selection_head)
7109 .collect::<String>();
7110 for (pair, enabled) in scope.brackets() {
7111 if enabled
7112 && pair.close
7113 && prev_chars.starts_with(pair.start.as_str())
7114 && next_chars.starts_with(pair.end.as_str())
7115 {
7116 bracket_pair = Some(pair.clone());
7117 break;
7118 }
7119 }
7120 if let Some(pair) = bracket_pair {
7121 let start = snapshot.anchor_after(selection_head);
7122 let end = snapshot.anchor_after(selection_head);
7123 self.autoclose_regions.push(AutocloseRegion {
7124 selection_id: selection.id,
7125 range: start..end,
7126 pair,
7127 });
7128 }
7129 }
7130 }
7131 }
7132 Ok(())
7133 }
7134
7135 pub fn move_to_next_snippet_tabstop(
7136 &mut self,
7137 window: &mut Window,
7138 cx: &mut Context<Self>,
7139 ) -> bool {
7140 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7141 }
7142
7143 pub fn move_to_prev_snippet_tabstop(
7144 &mut self,
7145 window: &mut Window,
7146 cx: &mut Context<Self>,
7147 ) -> bool {
7148 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7149 }
7150
7151 pub fn move_to_snippet_tabstop(
7152 &mut self,
7153 bias: Bias,
7154 window: &mut Window,
7155 cx: &mut Context<Self>,
7156 ) -> bool {
7157 if let Some(mut snippet) = self.snippet_stack.pop() {
7158 match bias {
7159 Bias::Left => {
7160 if snippet.active_index > 0 {
7161 snippet.active_index -= 1;
7162 } else {
7163 self.snippet_stack.push(snippet);
7164 return false;
7165 }
7166 }
7167 Bias::Right => {
7168 if snippet.active_index + 1 < snippet.ranges.len() {
7169 snippet.active_index += 1;
7170 } else {
7171 self.snippet_stack.push(snippet);
7172 return false;
7173 }
7174 }
7175 }
7176 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7177 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7178 s.select_anchor_ranges(current_ranges.iter().cloned())
7179 });
7180
7181 if let Some(choices) = &snippet.choices[snippet.active_index] {
7182 if let Some(selection) = current_ranges.first() {
7183 self.show_snippet_choices(&choices, selection.clone(), cx);
7184 }
7185 }
7186
7187 // If snippet state is not at the last tabstop, push it back on the stack
7188 if snippet.active_index + 1 < snippet.ranges.len() {
7189 self.snippet_stack.push(snippet);
7190 }
7191 return true;
7192 }
7193 }
7194
7195 false
7196 }
7197
7198 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7199 self.transact(window, cx, |this, window, cx| {
7200 this.select_all(&SelectAll, window, cx);
7201 this.insert("", window, cx);
7202 });
7203 }
7204
7205 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7206 self.transact(window, cx, |this, window, cx| {
7207 this.select_autoclose_pair(window, cx);
7208 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7209 if !this.linked_edit_ranges.is_empty() {
7210 let selections = this.selections.all::<MultiBufferPoint>(cx);
7211 let snapshot = this.buffer.read(cx).snapshot(cx);
7212
7213 for selection in selections.iter() {
7214 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7215 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7216 if selection_start.buffer_id != selection_end.buffer_id {
7217 continue;
7218 }
7219 if let Some(ranges) =
7220 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7221 {
7222 for (buffer, entries) in ranges {
7223 linked_ranges.entry(buffer).or_default().extend(entries);
7224 }
7225 }
7226 }
7227 }
7228
7229 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7230 if !this.selections.line_mode {
7231 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7232 for selection in &mut selections {
7233 if selection.is_empty() {
7234 let old_head = selection.head();
7235 let mut new_head =
7236 movement::left(&display_map, old_head.to_display_point(&display_map))
7237 .to_point(&display_map);
7238 if let Some((buffer, line_buffer_range)) = display_map
7239 .buffer_snapshot
7240 .buffer_line_for_row(MultiBufferRow(old_head.row))
7241 {
7242 let indent_size =
7243 buffer.indent_size_for_line(line_buffer_range.start.row);
7244 let indent_len = match indent_size.kind {
7245 IndentKind::Space => {
7246 buffer.settings_at(line_buffer_range.start, cx).tab_size
7247 }
7248 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7249 };
7250 if old_head.column <= indent_size.len && old_head.column > 0 {
7251 let indent_len = indent_len.get();
7252 new_head = cmp::min(
7253 new_head,
7254 MultiBufferPoint::new(
7255 old_head.row,
7256 ((old_head.column - 1) / indent_len) * indent_len,
7257 ),
7258 );
7259 }
7260 }
7261
7262 selection.set_head(new_head, SelectionGoal::None);
7263 }
7264 }
7265 }
7266
7267 this.signature_help_state.set_backspace_pressed(true);
7268 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7269 s.select(selections)
7270 });
7271 this.insert("", window, cx);
7272 let empty_str: Arc<str> = Arc::from("");
7273 for (buffer, edits) in linked_ranges {
7274 let snapshot = buffer.read(cx).snapshot();
7275 use text::ToPoint as TP;
7276
7277 let edits = edits
7278 .into_iter()
7279 .map(|range| {
7280 let end_point = TP::to_point(&range.end, &snapshot);
7281 let mut start_point = TP::to_point(&range.start, &snapshot);
7282
7283 if end_point == start_point {
7284 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7285 .saturating_sub(1);
7286 start_point =
7287 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7288 };
7289
7290 (start_point..end_point, empty_str.clone())
7291 })
7292 .sorted_by_key(|(range, _)| range.start)
7293 .collect::<Vec<_>>();
7294 buffer.update(cx, |this, cx| {
7295 this.edit(edits, None, cx);
7296 })
7297 }
7298 this.refresh_inline_completion(true, false, window, cx);
7299 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7300 });
7301 }
7302
7303 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7304 self.transact(window, cx, |this, window, cx| {
7305 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7306 let line_mode = s.line_mode;
7307 s.move_with(|map, selection| {
7308 if selection.is_empty() && !line_mode {
7309 let cursor = movement::right(map, selection.head());
7310 selection.end = cursor;
7311 selection.reversed = true;
7312 selection.goal = SelectionGoal::None;
7313 }
7314 })
7315 });
7316 this.insert("", window, cx);
7317 this.refresh_inline_completion(true, false, window, cx);
7318 });
7319 }
7320
7321 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7322 if self.move_to_prev_snippet_tabstop(window, cx) {
7323 return;
7324 }
7325
7326 self.outdent(&Outdent, window, cx);
7327 }
7328
7329 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7330 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7331 return;
7332 }
7333
7334 let mut selections = self.selections.all_adjusted(cx);
7335 let buffer = self.buffer.read(cx);
7336 let snapshot = buffer.snapshot(cx);
7337 let rows_iter = selections.iter().map(|s| s.head().row);
7338 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7339
7340 let mut edits = Vec::new();
7341 let mut prev_edited_row = 0;
7342 let mut row_delta = 0;
7343 for selection in &mut selections {
7344 if selection.start.row != prev_edited_row {
7345 row_delta = 0;
7346 }
7347 prev_edited_row = selection.end.row;
7348
7349 // If the selection is non-empty, then increase the indentation of the selected lines.
7350 if !selection.is_empty() {
7351 row_delta =
7352 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7353 continue;
7354 }
7355
7356 // If the selection is empty and the cursor is in the leading whitespace before the
7357 // suggested indentation, then auto-indent the line.
7358 let cursor = selection.head();
7359 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7360 if let Some(suggested_indent) =
7361 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7362 {
7363 if cursor.column < suggested_indent.len
7364 && cursor.column <= current_indent.len
7365 && current_indent.len <= suggested_indent.len
7366 {
7367 selection.start = Point::new(cursor.row, suggested_indent.len);
7368 selection.end = selection.start;
7369 if row_delta == 0 {
7370 edits.extend(Buffer::edit_for_indent_size_adjustment(
7371 cursor.row,
7372 current_indent,
7373 suggested_indent,
7374 ));
7375 row_delta = suggested_indent.len - current_indent.len;
7376 }
7377 continue;
7378 }
7379 }
7380
7381 // Otherwise, insert a hard or soft tab.
7382 let settings = buffer.language_settings_at(cursor, cx);
7383 let tab_size = if settings.hard_tabs {
7384 IndentSize::tab()
7385 } else {
7386 let tab_size = settings.tab_size.get();
7387 let char_column = snapshot
7388 .text_for_range(Point::new(cursor.row, 0)..cursor)
7389 .flat_map(str::chars)
7390 .count()
7391 + row_delta as usize;
7392 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7393 IndentSize::spaces(chars_to_next_tab_stop)
7394 };
7395 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7396 selection.end = selection.start;
7397 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7398 row_delta += tab_size.len;
7399 }
7400
7401 self.transact(window, cx, |this, window, cx| {
7402 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7403 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7404 s.select(selections)
7405 });
7406 this.refresh_inline_completion(true, false, window, cx);
7407 });
7408 }
7409
7410 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7411 if self.read_only(cx) {
7412 return;
7413 }
7414 let mut selections = self.selections.all::<Point>(cx);
7415 let mut prev_edited_row = 0;
7416 let mut row_delta = 0;
7417 let mut edits = Vec::new();
7418 let buffer = self.buffer.read(cx);
7419 let snapshot = buffer.snapshot(cx);
7420 for selection in &mut selections {
7421 if selection.start.row != prev_edited_row {
7422 row_delta = 0;
7423 }
7424 prev_edited_row = selection.end.row;
7425
7426 row_delta =
7427 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7428 }
7429
7430 self.transact(window, cx, |this, window, cx| {
7431 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7432 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7433 s.select(selections)
7434 });
7435 });
7436 }
7437
7438 fn indent_selection(
7439 buffer: &MultiBuffer,
7440 snapshot: &MultiBufferSnapshot,
7441 selection: &mut Selection<Point>,
7442 edits: &mut Vec<(Range<Point>, String)>,
7443 delta_for_start_row: u32,
7444 cx: &App,
7445 ) -> u32 {
7446 let settings = buffer.language_settings_at(selection.start, cx);
7447 let tab_size = settings.tab_size.get();
7448 let indent_kind = if settings.hard_tabs {
7449 IndentKind::Tab
7450 } else {
7451 IndentKind::Space
7452 };
7453 let mut start_row = selection.start.row;
7454 let mut end_row = selection.end.row + 1;
7455
7456 // If a selection ends at the beginning of a line, don't indent
7457 // that last line.
7458 if selection.end.column == 0 && selection.end.row > selection.start.row {
7459 end_row -= 1;
7460 }
7461
7462 // Avoid re-indenting a row that has already been indented by a
7463 // previous selection, but still update this selection's column
7464 // to reflect that indentation.
7465 if delta_for_start_row > 0 {
7466 start_row += 1;
7467 selection.start.column += delta_for_start_row;
7468 if selection.end.row == selection.start.row {
7469 selection.end.column += delta_for_start_row;
7470 }
7471 }
7472
7473 let mut delta_for_end_row = 0;
7474 let has_multiple_rows = start_row + 1 != end_row;
7475 for row in start_row..end_row {
7476 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7477 let indent_delta = match (current_indent.kind, indent_kind) {
7478 (IndentKind::Space, IndentKind::Space) => {
7479 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7480 IndentSize::spaces(columns_to_next_tab_stop)
7481 }
7482 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7483 (_, IndentKind::Tab) => IndentSize::tab(),
7484 };
7485
7486 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7487 0
7488 } else {
7489 selection.start.column
7490 };
7491 let row_start = Point::new(row, start);
7492 edits.push((
7493 row_start..row_start,
7494 indent_delta.chars().collect::<String>(),
7495 ));
7496
7497 // Update this selection's endpoints to reflect the indentation.
7498 if row == selection.start.row {
7499 selection.start.column += indent_delta.len;
7500 }
7501 if row == selection.end.row {
7502 selection.end.column += indent_delta.len;
7503 delta_for_end_row = indent_delta.len;
7504 }
7505 }
7506
7507 if selection.start.row == selection.end.row {
7508 delta_for_start_row + delta_for_end_row
7509 } else {
7510 delta_for_end_row
7511 }
7512 }
7513
7514 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7515 if self.read_only(cx) {
7516 return;
7517 }
7518 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7519 let selections = self.selections.all::<Point>(cx);
7520 let mut deletion_ranges = Vec::new();
7521 let mut last_outdent = None;
7522 {
7523 let buffer = self.buffer.read(cx);
7524 let snapshot = buffer.snapshot(cx);
7525 for selection in &selections {
7526 let settings = buffer.language_settings_at(selection.start, cx);
7527 let tab_size = settings.tab_size.get();
7528 let mut rows = selection.spanned_rows(false, &display_map);
7529
7530 // Avoid re-outdenting a row that has already been outdented by a
7531 // previous selection.
7532 if let Some(last_row) = last_outdent {
7533 if last_row == rows.start {
7534 rows.start = rows.start.next_row();
7535 }
7536 }
7537 let has_multiple_rows = rows.len() > 1;
7538 for row in rows.iter_rows() {
7539 let indent_size = snapshot.indent_size_for_line(row);
7540 if indent_size.len > 0 {
7541 let deletion_len = match indent_size.kind {
7542 IndentKind::Space => {
7543 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7544 if columns_to_prev_tab_stop == 0 {
7545 tab_size
7546 } else {
7547 columns_to_prev_tab_stop
7548 }
7549 }
7550 IndentKind::Tab => 1,
7551 };
7552 let start = if has_multiple_rows
7553 || deletion_len > selection.start.column
7554 || indent_size.len < selection.start.column
7555 {
7556 0
7557 } else {
7558 selection.start.column - deletion_len
7559 };
7560 deletion_ranges.push(
7561 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7562 );
7563 last_outdent = Some(row);
7564 }
7565 }
7566 }
7567 }
7568
7569 self.transact(window, cx, |this, window, cx| {
7570 this.buffer.update(cx, |buffer, cx| {
7571 let empty_str: Arc<str> = Arc::default();
7572 buffer.edit(
7573 deletion_ranges
7574 .into_iter()
7575 .map(|range| (range, empty_str.clone())),
7576 None,
7577 cx,
7578 );
7579 });
7580 let selections = this.selections.all::<usize>(cx);
7581 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7582 s.select(selections)
7583 });
7584 });
7585 }
7586
7587 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7588 if self.read_only(cx) {
7589 return;
7590 }
7591 let selections = self
7592 .selections
7593 .all::<usize>(cx)
7594 .into_iter()
7595 .map(|s| s.range());
7596
7597 self.transact(window, cx, |this, window, cx| {
7598 this.buffer.update(cx, |buffer, cx| {
7599 buffer.autoindent_ranges(selections, cx);
7600 });
7601 let selections = this.selections.all::<usize>(cx);
7602 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7603 s.select(selections)
7604 });
7605 });
7606 }
7607
7608 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7609 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7610 let selections = self.selections.all::<Point>(cx);
7611
7612 let mut new_cursors = Vec::new();
7613 let mut edit_ranges = Vec::new();
7614 let mut selections = selections.iter().peekable();
7615 while let Some(selection) = selections.next() {
7616 let mut rows = selection.spanned_rows(false, &display_map);
7617 let goal_display_column = selection.head().to_display_point(&display_map).column();
7618
7619 // Accumulate contiguous regions of rows that we want to delete.
7620 while let Some(next_selection) = selections.peek() {
7621 let next_rows = next_selection.spanned_rows(false, &display_map);
7622 if next_rows.start <= rows.end {
7623 rows.end = next_rows.end;
7624 selections.next().unwrap();
7625 } else {
7626 break;
7627 }
7628 }
7629
7630 let buffer = &display_map.buffer_snapshot;
7631 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7632 let edit_end;
7633 let cursor_buffer_row;
7634 if buffer.max_point().row >= rows.end.0 {
7635 // If there's a line after the range, delete the \n from the end of the row range
7636 // and position the cursor on the next line.
7637 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7638 cursor_buffer_row = rows.end;
7639 } else {
7640 // If there isn't a line after the range, delete the \n from the line before the
7641 // start of the row range and position the cursor there.
7642 edit_start = edit_start.saturating_sub(1);
7643 edit_end = buffer.len();
7644 cursor_buffer_row = rows.start.previous_row();
7645 }
7646
7647 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7648 *cursor.column_mut() =
7649 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7650
7651 new_cursors.push((
7652 selection.id,
7653 buffer.anchor_after(cursor.to_point(&display_map)),
7654 ));
7655 edit_ranges.push(edit_start..edit_end);
7656 }
7657
7658 self.transact(window, cx, |this, window, cx| {
7659 let buffer = this.buffer.update(cx, |buffer, cx| {
7660 let empty_str: Arc<str> = Arc::default();
7661 buffer.edit(
7662 edit_ranges
7663 .into_iter()
7664 .map(|range| (range, empty_str.clone())),
7665 None,
7666 cx,
7667 );
7668 buffer.snapshot(cx)
7669 });
7670 let new_selections = new_cursors
7671 .into_iter()
7672 .map(|(id, cursor)| {
7673 let cursor = cursor.to_point(&buffer);
7674 Selection {
7675 id,
7676 start: cursor,
7677 end: cursor,
7678 reversed: false,
7679 goal: SelectionGoal::None,
7680 }
7681 })
7682 .collect();
7683
7684 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7685 s.select(new_selections);
7686 });
7687 });
7688 }
7689
7690 pub fn join_lines_impl(
7691 &mut self,
7692 insert_whitespace: bool,
7693 window: &mut Window,
7694 cx: &mut Context<Self>,
7695 ) {
7696 if self.read_only(cx) {
7697 return;
7698 }
7699 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7700 for selection in self.selections.all::<Point>(cx) {
7701 let start = MultiBufferRow(selection.start.row);
7702 // Treat single line selections as if they include the next line. Otherwise this action
7703 // would do nothing for single line selections individual cursors.
7704 let end = if selection.start.row == selection.end.row {
7705 MultiBufferRow(selection.start.row + 1)
7706 } else {
7707 MultiBufferRow(selection.end.row)
7708 };
7709
7710 if let Some(last_row_range) = row_ranges.last_mut() {
7711 if start <= last_row_range.end {
7712 last_row_range.end = end;
7713 continue;
7714 }
7715 }
7716 row_ranges.push(start..end);
7717 }
7718
7719 let snapshot = self.buffer.read(cx).snapshot(cx);
7720 let mut cursor_positions = Vec::new();
7721 for row_range in &row_ranges {
7722 let anchor = snapshot.anchor_before(Point::new(
7723 row_range.end.previous_row().0,
7724 snapshot.line_len(row_range.end.previous_row()),
7725 ));
7726 cursor_positions.push(anchor..anchor);
7727 }
7728
7729 self.transact(window, cx, |this, window, cx| {
7730 for row_range in row_ranges.into_iter().rev() {
7731 for row in row_range.iter_rows().rev() {
7732 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7733 let next_line_row = row.next_row();
7734 let indent = snapshot.indent_size_for_line(next_line_row);
7735 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7736
7737 let replace =
7738 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7739 " "
7740 } else {
7741 ""
7742 };
7743
7744 this.buffer.update(cx, |buffer, cx| {
7745 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7746 });
7747 }
7748 }
7749
7750 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7751 s.select_anchor_ranges(cursor_positions)
7752 });
7753 });
7754 }
7755
7756 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7757 self.join_lines_impl(true, window, cx);
7758 }
7759
7760 pub fn sort_lines_case_sensitive(
7761 &mut self,
7762 _: &SortLinesCaseSensitive,
7763 window: &mut Window,
7764 cx: &mut Context<Self>,
7765 ) {
7766 self.manipulate_lines(window, cx, |lines| lines.sort())
7767 }
7768
7769 pub fn sort_lines_case_insensitive(
7770 &mut self,
7771 _: &SortLinesCaseInsensitive,
7772 window: &mut Window,
7773 cx: &mut Context<Self>,
7774 ) {
7775 self.manipulate_lines(window, cx, |lines| {
7776 lines.sort_by_key(|line| line.to_lowercase())
7777 })
7778 }
7779
7780 pub fn unique_lines_case_insensitive(
7781 &mut self,
7782 _: &UniqueLinesCaseInsensitive,
7783 window: &mut Window,
7784 cx: &mut Context<Self>,
7785 ) {
7786 self.manipulate_lines(window, cx, |lines| {
7787 let mut seen = HashSet::default();
7788 lines.retain(|line| seen.insert(line.to_lowercase()));
7789 })
7790 }
7791
7792 pub fn unique_lines_case_sensitive(
7793 &mut self,
7794 _: &UniqueLinesCaseSensitive,
7795 window: &mut Window,
7796 cx: &mut Context<Self>,
7797 ) {
7798 self.manipulate_lines(window, cx, |lines| {
7799 let mut seen = HashSet::default();
7800 lines.retain(|line| seen.insert(*line));
7801 })
7802 }
7803
7804 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7805 let Some(project) = self.project.clone() else {
7806 return;
7807 };
7808 self.reload(project, window, cx)
7809 .detach_and_notify_err(window, cx);
7810 }
7811
7812 pub fn restore_file(
7813 &mut self,
7814 _: &::git::RestoreFile,
7815 window: &mut Window,
7816 cx: &mut Context<Self>,
7817 ) {
7818 let mut buffer_ids = HashSet::default();
7819 let snapshot = self.buffer().read(cx).snapshot(cx);
7820 for selection in self.selections.all::<usize>(cx) {
7821 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7822 }
7823
7824 let buffer = self.buffer().read(cx);
7825 let ranges = buffer_ids
7826 .into_iter()
7827 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7828 .collect::<Vec<_>>();
7829
7830 self.restore_hunks_in_ranges(ranges, window, cx);
7831 }
7832
7833 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7834 let selections = self
7835 .selections
7836 .all(cx)
7837 .into_iter()
7838 .map(|s| s.range())
7839 .collect();
7840 self.restore_hunks_in_ranges(selections, window, cx);
7841 }
7842
7843 fn restore_hunks_in_ranges(
7844 &mut self,
7845 ranges: Vec<Range<Point>>,
7846 window: &mut Window,
7847 cx: &mut Context<Editor>,
7848 ) {
7849 let mut revert_changes = HashMap::default();
7850 let chunk_by = self
7851 .snapshot(window, cx)
7852 .hunks_for_ranges(ranges)
7853 .into_iter()
7854 .chunk_by(|hunk| hunk.buffer_id);
7855 for (buffer_id, hunks) in &chunk_by {
7856 let hunks = hunks.collect::<Vec<_>>();
7857 for hunk in &hunks {
7858 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7859 }
7860 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7861 }
7862 drop(chunk_by);
7863 if !revert_changes.is_empty() {
7864 self.transact(window, cx, |editor, window, cx| {
7865 editor.restore(revert_changes, window, cx);
7866 });
7867 }
7868 }
7869
7870 pub fn open_active_item_in_terminal(
7871 &mut self,
7872 _: &OpenInTerminal,
7873 window: &mut Window,
7874 cx: &mut Context<Self>,
7875 ) {
7876 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7877 let project_path = buffer.read(cx).project_path(cx)?;
7878 let project = self.project.as_ref()?.read(cx);
7879 let entry = project.entry_for_path(&project_path, cx)?;
7880 let parent = match &entry.canonical_path {
7881 Some(canonical_path) => canonical_path.to_path_buf(),
7882 None => project.absolute_path(&project_path, cx)?,
7883 }
7884 .parent()?
7885 .to_path_buf();
7886 Some(parent)
7887 }) {
7888 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7889 }
7890 }
7891
7892 pub fn prepare_restore_change(
7893 &self,
7894 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7895 hunk: &MultiBufferDiffHunk,
7896 cx: &mut App,
7897 ) -> Option<()> {
7898 let buffer = self.buffer.read(cx);
7899 let diff = buffer.diff_for(hunk.buffer_id)?;
7900 let buffer = buffer.buffer(hunk.buffer_id)?;
7901 let buffer = buffer.read(cx);
7902 let original_text = diff
7903 .read(cx)
7904 .base_text()
7905 .as_rope()
7906 .slice(hunk.diff_base_byte_range.clone());
7907 let buffer_snapshot = buffer.snapshot();
7908 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7909 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7910 probe
7911 .0
7912 .start
7913 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7914 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7915 }) {
7916 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7917 Some(())
7918 } else {
7919 None
7920 }
7921 }
7922
7923 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7924 self.manipulate_lines(window, cx, |lines| lines.reverse())
7925 }
7926
7927 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7928 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7929 }
7930
7931 fn manipulate_lines<Fn>(
7932 &mut self,
7933 window: &mut Window,
7934 cx: &mut Context<Self>,
7935 mut callback: Fn,
7936 ) where
7937 Fn: FnMut(&mut Vec<&str>),
7938 {
7939 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7940 let buffer = self.buffer.read(cx).snapshot(cx);
7941
7942 let mut edits = Vec::new();
7943
7944 let selections = self.selections.all::<Point>(cx);
7945 let mut selections = selections.iter().peekable();
7946 let mut contiguous_row_selections = Vec::new();
7947 let mut new_selections = Vec::new();
7948 let mut added_lines = 0;
7949 let mut removed_lines = 0;
7950
7951 while let Some(selection) = selections.next() {
7952 let (start_row, end_row) = consume_contiguous_rows(
7953 &mut contiguous_row_selections,
7954 selection,
7955 &display_map,
7956 &mut selections,
7957 );
7958
7959 let start_point = Point::new(start_row.0, 0);
7960 let end_point = Point::new(
7961 end_row.previous_row().0,
7962 buffer.line_len(end_row.previous_row()),
7963 );
7964 let text = buffer
7965 .text_for_range(start_point..end_point)
7966 .collect::<String>();
7967
7968 let mut lines = text.split('\n').collect_vec();
7969
7970 let lines_before = lines.len();
7971 callback(&mut lines);
7972 let lines_after = lines.len();
7973
7974 edits.push((start_point..end_point, lines.join("\n")));
7975
7976 // Selections must change based on added and removed line count
7977 let start_row =
7978 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7979 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7980 new_selections.push(Selection {
7981 id: selection.id,
7982 start: start_row,
7983 end: end_row,
7984 goal: SelectionGoal::None,
7985 reversed: selection.reversed,
7986 });
7987
7988 if lines_after > lines_before {
7989 added_lines += lines_after - lines_before;
7990 } else if lines_before > lines_after {
7991 removed_lines += lines_before - lines_after;
7992 }
7993 }
7994
7995 self.transact(window, cx, |this, window, cx| {
7996 let buffer = this.buffer.update(cx, |buffer, cx| {
7997 buffer.edit(edits, None, cx);
7998 buffer.snapshot(cx)
7999 });
8000
8001 // Recalculate offsets on newly edited buffer
8002 let new_selections = new_selections
8003 .iter()
8004 .map(|s| {
8005 let start_point = Point::new(s.start.0, 0);
8006 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8007 Selection {
8008 id: s.id,
8009 start: buffer.point_to_offset(start_point),
8010 end: buffer.point_to_offset(end_point),
8011 goal: s.goal,
8012 reversed: s.reversed,
8013 }
8014 })
8015 .collect();
8016
8017 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8018 s.select(new_selections);
8019 });
8020
8021 this.request_autoscroll(Autoscroll::fit(), cx);
8022 });
8023 }
8024
8025 pub fn convert_to_upper_case(
8026 &mut self,
8027 _: &ConvertToUpperCase,
8028 window: &mut Window,
8029 cx: &mut Context<Self>,
8030 ) {
8031 self.manipulate_text(window, cx, |text| text.to_uppercase())
8032 }
8033
8034 pub fn convert_to_lower_case(
8035 &mut self,
8036 _: &ConvertToLowerCase,
8037 window: &mut Window,
8038 cx: &mut Context<Self>,
8039 ) {
8040 self.manipulate_text(window, cx, |text| text.to_lowercase())
8041 }
8042
8043 pub fn convert_to_title_case(
8044 &mut self,
8045 _: &ConvertToTitleCase,
8046 window: &mut Window,
8047 cx: &mut Context<Self>,
8048 ) {
8049 self.manipulate_text(window, cx, |text| {
8050 text.split('\n')
8051 .map(|line| line.to_case(Case::Title))
8052 .join("\n")
8053 })
8054 }
8055
8056 pub fn convert_to_snake_case(
8057 &mut self,
8058 _: &ConvertToSnakeCase,
8059 window: &mut Window,
8060 cx: &mut Context<Self>,
8061 ) {
8062 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8063 }
8064
8065 pub fn convert_to_kebab_case(
8066 &mut self,
8067 _: &ConvertToKebabCase,
8068 window: &mut Window,
8069 cx: &mut Context<Self>,
8070 ) {
8071 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8072 }
8073
8074 pub fn convert_to_upper_camel_case(
8075 &mut self,
8076 _: &ConvertToUpperCamelCase,
8077 window: &mut Window,
8078 cx: &mut Context<Self>,
8079 ) {
8080 self.manipulate_text(window, cx, |text| {
8081 text.split('\n')
8082 .map(|line| line.to_case(Case::UpperCamel))
8083 .join("\n")
8084 })
8085 }
8086
8087 pub fn convert_to_lower_camel_case(
8088 &mut self,
8089 _: &ConvertToLowerCamelCase,
8090 window: &mut Window,
8091 cx: &mut Context<Self>,
8092 ) {
8093 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8094 }
8095
8096 pub fn convert_to_opposite_case(
8097 &mut self,
8098 _: &ConvertToOppositeCase,
8099 window: &mut Window,
8100 cx: &mut Context<Self>,
8101 ) {
8102 self.manipulate_text(window, cx, |text| {
8103 text.chars()
8104 .fold(String::with_capacity(text.len()), |mut t, c| {
8105 if c.is_uppercase() {
8106 t.extend(c.to_lowercase());
8107 } else {
8108 t.extend(c.to_uppercase());
8109 }
8110 t
8111 })
8112 })
8113 }
8114
8115 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8116 where
8117 Fn: FnMut(&str) -> String,
8118 {
8119 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8120 let buffer = self.buffer.read(cx).snapshot(cx);
8121
8122 let mut new_selections = Vec::new();
8123 let mut edits = Vec::new();
8124 let mut selection_adjustment = 0i32;
8125
8126 for selection in self.selections.all::<usize>(cx) {
8127 let selection_is_empty = selection.is_empty();
8128
8129 let (start, end) = if selection_is_empty {
8130 let word_range = movement::surrounding_word(
8131 &display_map,
8132 selection.start.to_display_point(&display_map),
8133 );
8134 let start = word_range.start.to_offset(&display_map, Bias::Left);
8135 let end = word_range.end.to_offset(&display_map, Bias::Left);
8136 (start, end)
8137 } else {
8138 (selection.start, selection.end)
8139 };
8140
8141 let text = buffer.text_for_range(start..end).collect::<String>();
8142 let old_length = text.len() as i32;
8143 let text = callback(&text);
8144
8145 new_selections.push(Selection {
8146 start: (start as i32 - selection_adjustment) as usize,
8147 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8148 goal: SelectionGoal::None,
8149 ..selection
8150 });
8151
8152 selection_adjustment += old_length - text.len() as i32;
8153
8154 edits.push((start..end, text));
8155 }
8156
8157 self.transact(window, cx, |this, window, cx| {
8158 this.buffer.update(cx, |buffer, cx| {
8159 buffer.edit(edits, None, cx);
8160 });
8161
8162 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8163 s.select(new_selections);
8164 });
8165
8166 this.request_autoscroll(Autoscroll::fit(), cx);
8167 });
8168 }
8169
8170 pub fn duplicate(
8171 &mut self,
8172 upwards: bool,
8173 whole_lines: bool,
8174 window: &mut Window,
8175 cx: &mut Context<Self>,
8176 ) {
8177 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8178 let buffer = &display_map.buffer_snapshot;
8179 let selections = self.selections.all::<Point>(cx);
8180
8181 let mut edits = Vec::new();
8182 let mut selections_iter = selections.iter().peekable();
8183 while let Some(selection) = selections_iter.next() {
8184 let mut rows = selection.spanned_rows(false, &display_map);
8185 // duplicate line-wise
8186 if whole_lines || selection.start == selection.end {
8187 // Avoid duplicating the same lines twice.
8188 while let Some(next_selection) = selections_iter.peek() {
8189 let next_rows = next_selection.spanned_rows(false, &display_map);
8190 if next_rows.start < rows.end {
8191 rows.end = next_rows.end;
8192 selections_iter.next().unwrap();
8193 } else {
8194 break;
8195 }
8196 }
8197
8198 // Copy the text from the selected row region and splice it either at the start
8199 // or end of the region.
8200 let start = Point::new(rows.start.0, 0);
8201 let end = Point::new(
8202 rows.end.previous_row().0,
8203 buffer.line_len(rows.end.previous_row()),
8204 );
8205 let text = buffer
8206 .text_for_range(start..end)
8207 .chain(Some("\n"))
8208 .collect::<String>();
8209 let insert_location = if upwards {
8210 Point::new(rows.end.0, 0)
8211 } else {
8212 start
8213 };
8214 edits.push((insert_location..insert_location, text));
8215 } else {
8216 // duplicate character-wise
8217 let start = selection.start;
8218 let end = selection.end;
8219 let text = buffer.text_for_range(start..end).collect::<String>();
8220 edits.push((selection.end..selection.end, text));
8221 }
8222 }
8223
8224 self.transact(window, cx, |this, _, cx| {
8225 this.buffer.update(cx, |buffer, cx| {
8226 buffer.edit(edits, None, cx);
8227 });
8228
8229 this.request_autoscroll(Autoscroll::fit(), cx);
8230 });
8231 }
8232
8233 pub fn duplicate_line_up(
8234 &mut self,
8235 _: &DuplicateLineUp,
8236 window: &mut Window,
8237 cx: &mut Context<Self>,
8238 ) {
8239 self.duplicate(true, true, window, cx);
8240 }
8241
8242 pub fn duplicate_line_down(
8243 &mut self,
8244 _: &DuplicateLineDown,
8245 window: &mut Window,
8246 cx: &mut Context<Self>,
8247 ) {
8248 self.duplicate(false, true, window, cx);
8249 }
8250
8251 pub fn duplicate_selection(
8252 &mut self,
8253 _: &DuplicateSelection,
8254 window: &mut Window,
8255 cx: &mut Context<Self>,
8256 ) {
8257 self.duplicate(false, false, window, cx);
8258 }
8259
8260 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8261 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8262 let buffer = self.buffer.read(cx).snapshot(cx);
8263
8264 let mut edits = Vec::new();
8265 let mut unfold_ranges = Vec::new();
8266 let mut refold_creases = Vec::new();
8267
8268 let selections = self.selections.all::<Point>(cx);
8269 let mut selections = selections.iter().peekable();
8270 let mut contiguous_row_selections = Vec::new();
8271 let mut new_selections = Vec::new();
8272
8273 while let Some(selection) = selections.next() {
8274 // Find all the selections that span a contiguous row range
8275 let (start_row, end_row) = consume_contiguous_rows(
8276 &mut contiguous_row_selections,
8277 selection,
8278 &display_map,
8279 &mut selections,
8280 );
8281
8282 // Move the text spanned by the row range to be before the line preceding the row range
8283 if start_row.0 > 0 {
8284 let range_to_move = Point::new(
8285 start_row.previous_row().0,
8286 buffer.line_len(start_row.previous_row()),
8287 )
8288 ..Point::new(
8289 end_row.previous_row().0,
8290 buffer.line_len(end_row.previous_row()),
8291 );
8292 let insertion_point = display_map
8293 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8294 .0;
8295
8296 // Don't move lines across excerpts
8297 if buffer
8298 .excerpt_containing(insertion_point..range_to_move.end)
8299 .is_some()
8300 {
8301 let text = buffer
8302 .text_for_range(range_to_move.clone())
8303 .flat_map(|s| s.chars())
8304 .skip(1)
8305 .chain(['\n'])
8306 .collect::<String>();
8307
8308 edits.push((
8309 buffer.anchor_after(range_to_move.start)
8310 ..buffer.anchor_before(range_to_move.end),
8311 String::new(),
8312 ));
8313 let insertion_anchor = buffer.anchor_after(insertion_point);
8314 edits.push((insertion_anchor..insertion_anchor, text));
8315
8316 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8317
8318 // Move selections up
8319 new_selections.extend(contiguous_row_selections.drain(..).map(
8320 |mut selection| {
8321 selection.start.row -= row_delta;
8322 selection.end.row -= row_delta;
8323 selection
8324 },
8325 ));
8326
8327 // Move folds up
8328 unfold_ranges.push(range_to_move.clone());
8329 for fold in display_map.folds_in_range(
8330 buffer.anchor_before(range_to_move.start)
8331 ..buffer.anchor_after(range_to_move.end),
8332 ) {
8333 let mut start = fold.range.start.to_point(&buffer);
8334 let mut end = fold.range.end.to_point(&buffer);
8335 start.row -= row_delta;
8336 end.row -= row_delta;
8337 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8338 }
8339 }
8340 }
8341
8342 // If we didn't move line(s), preserve the existing selections
8343 new_selections.append(&mut contiguous_row_selections);
8344 }
8345
8346 self.transact(window, cx, |this, window, cx| {
8347 this.unfold_ranges(&unfold_ranges, true, true, cx);
8348 this.buffer.update(cx, |buffer, cx| {
8349 for (range, text) in edits {
8350 buffer.edit([(range, text)], None, cx);
8351 }
8352 });
8353 this.fold_creases(refold_creases, true, window, cx);
8354 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8355 s.select(new_selections);
8356 })
8357 });
8358 }
8359
8360 pub fn move_line_down(
8361 &mut self,
8362 _: &MoveLineDown,
8363 window: &mut Window,
8364 cx: &mut Context<Self>,
8365 ) {
8366 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8367 let buffer = self.buffer.read(cx).snapshot(cx);
8368
8369 let mut edits = Vec::new();
8370 let mut unfold_ranges = Vec::new();
8371 let mut refold_creases = Vec::new();
8372
8373 let selections = self.selections.all::<Point>(cx);
8374 let mut selections = selections.iter().peekable();
8375 let mut contiguous_row_selections = Vec::new();
8376 let mut new_selections = Vec::new();
8377
8378 while let Some(selection) = selections.next() {
8379 // Find all the selections that span a contiguous row range
8380 let (start_row, end_row) = consume_contiguous_rows(
8381 &mut contiguous_row_selections,
8382 selection,
8383 &display_map,
8384 &mut selections,
8385 );
8386
8387 // Move the text spanned by the row range to be after the last line of the row range
8388 if end_row.0 <= buffer.max_point().row {
8389 let range_to_move =
8390 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8391 let insertion_point = display_map
8392 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8393 .0;
8394
8395 // Don't move lines across excerpt boundaries
8396 if buffer
8397 .excerpt_containing(range_to_move.start..insertion_point)
8398 .is_some()
8399 {
8400 let mut text = String::from("\n");
8401 text.extend(buffer.text_for_range(range_to_move.clone()));
8402 text.pop(); // Drop trailing newline
8403 edits.push((
8404 buffer.anchor_after(range_to_move.start)
8405 ..buffer.anchor_before(range_to_move.end),
8406 String::new(),
8407 ));
8408 let insertion_anchor = buffer.anchor_after(insertion_point);
8409 edits.push((insertion_anchor..insertion_anchor, text));
8410
8411 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8412
8413 // Move selections down
8414 new_selections.extend(contiguous_row_selections.drain(..).map(
8415 |mut selection| {
8416 selection.start.row += row_delta;
8417 selection.end.row += row_delta;
8418 selection
8419 },
8420 ));
8421
8422 // Move folds down
8423 unfold_ranges.push(range_to_move.clone());
8424 for fold in display_map.folds_in_range(
8425 buffer.anchor_before(range_to_move.start)
8426 ..buffer.anchor_after(range_to_move.end),
8427 ) {
8428 let mut start = fold.range.start.to_point(&buffer);
8429 let mut end = fold.range.end.to_point(&buffer);
8430 start.row += row_delta;
8431 end.row += row_delta;
8432 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8433 }
8434 }
8435 }
8436
8437 // If we didn't move line(s), preserve the existing selections
8438 new_selections.append(&mut contiguous_row_selections);
8439 }
8440
8441 self.transact(window, cx, |this, window, cx| {
8442 this.unfold_ranges(&unfold_ranges, true, true, cx);
8443 this.buffer.update(cx, |buffer, cx| {
8444 for (range, text) in edits {
8445 buffer.edit([(range, text)], None, cx);
8446 }
8447 });
8448 this.fold_creases(refold_creases, true, window, cx);
8449 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8450 s.select(new_selections)
8451 });
8452 });
8453 }
8454
8455 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8456 let text_layout_details = &self.text_layout_details(window);
8457 self.transact(window, cx, |this, window, cx| {
8458 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8459 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8460 let line_mode = s.line_mode;
8461 s.move_with(|display_map, selection| {
8462 if !selection.is_empty() || line_mode {
8463 return;
8464 }
8465
8466 let mut head = selection.head();
8467 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8468 if head.column() == display_map.line_len(head.row()) {
8469 transpose_offset = display_map
8470 .buffer_snapshot
8471 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8472 }
8473
8474 if transpose_offset == 0 {
8475 return;
8476 }
8477
8478 *head.column_mut() += 1;
8479 head = display_map.clip_point(head, Bias::Right);
8480 let goal = SelectionGoal::HorizontalPosition(
8481 display_map
8482 .x_for_display_point(head, text_layout_details)
8483 .into(),
8484 );
8485 selection.collapse_to(head, goal);
8486
8487 let transpose_start = display_map
8488 .buffer_snapshot
8489 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8490 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8491 let transpose_end = display_map
8492 .buffer_snapshot
8493 .clip_offset(transpose_offset + 1, Bias::Right);
8494 if let Some(ch) =
8495 display_map.buffer_snapshot.chars_at(transpose_start).next()
8496 {
8497 edits.push((transpose_start..transpose_offset, String::new()));
8498 edits.push((transpose_end..transpose_end, ch.to_string()));
8499 }
8500 }
8501 });
8502 edits
8503 });
8504 this.buffer
8505 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8506 let selections = this.selections.all::<usize>(cx);
8507 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8508 s.select(selections);
8509 });
8510 });
8511 }
8512
8513 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8514 self.rewrap_impl(IsVimMode::No, cx)
8515 }
8516
8517 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8518 let buffer = self.buffer.read(cx).snapshot(cx);
8519 let selections = self.selections.all::<Point>(cx);
8520 let mut selections = selections.iter().peekable();
8521
8522 let mut edits = Vec::new();
8523 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8524
8525 while let Some(selection) = selections.next() {
8526 let mut start_row = selection.start.row;
8527 let mut end_row = selection.end.row;
8528
8529 // Skip selections that overlap with a range that has already been rewrapped.
8530 let selection_range = start_row..end_row;
8531 if rewrapped_row_ranges
8532 .iter()
8533 .any(|range| range.overlaps(&selection_range))
8534 {
8535 continue;
8536 }
8537
8538 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
8539
8540 // Since not all lines in the selection may be at the same indent
8541 // level, choose the indent size that is the most common between all
8542 // of the lines.
8543 //
8544 // If there is a tie, we use the deepest indent.
8545 let (indent_size, indent_end) = {
8546 let mut indent_size_occurrences = HashMap::default();
8547 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8548
8549 for row in start_row..=end_row {
8550 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8551 rows_by_indent_size.entry(indent).or_default().push(row);
8552 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8553 }
8554
8555 let indent_size = indent_size_occurrences
8556 .into_iter()
8557 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8558 .map(|(indent, _)| indent)
8559 .unwrap_or_default();
8560 let row = rows_by_indent_size[&indent_size][0];
8561 let indent_end = Point::new(row, indent_size.len);
8562
8563 (indent_size, indent_end)
8564 };
8565
8566 let mut line_prefix = indent_size.chars().collect::<String>();
8567
8568 let mut inside_comment = false;
8569 if let Some(comment_prefix) =
8570 buffer
8571 .language_scope_at(selection.head())
8572 .and_then(|language| {
8573 language
8574 .line_comment_prefixes()
8575 .iter()
8576 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8577 .cloned()
8578 })
8579 {
8580 line_prefix.push_str(&comment_prefix);
8581 inside_comment = true;
8582 }
8583
8584 let language_settings = buffer.language_settings_at(selection.head(), cx);
8585 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8586 RewrapBehavior::InComments => inside_comment,
8587 RewrapBehavior::InSelections => !selection.is_empty(),
8588 RewrapBehavior::Anywhere => true,
8589 };
8590
8591 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8592 if !should_rewrap {
8593 continue;
8594 }
8595
8596 if selection.is_empty() {
8597 'expand_upwards: while start_row > 0 {
8598 let prev_row = start_row - 1;
8599 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8600 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8601 {
8602 start_row = prev_row;
8603 } else {
8604 break 'expand_upwards;
8605 }
8606 }
8607
8608 'expand_downwards: while end_row < buffer.max_point().row {
8609 let next_row = end_row + 1;
8610 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8611 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8612 {
8613 end_row = next_row;
8614 } else {
8615 break 'expand_downwards;
8616 }
8617 }
8618 }
8619
8620 let start = Point::new(start_row, 0);
8621 let start_offset = start.to_offset(&buffer);
8622 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8623 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8624 let Some(lines_without_prefixes) = selection_text
8625 .lines()
8626 .map(|line| {
8627 line.strip_prefix(&line_prefix)
8628 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8629 .ok_or_else(|| {
8630 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8631 })
8632 })
8633 .collect::<Result<Vec<_>, _>>()
8634 .log_err()
8635 else {
8636 continue;
8637 };
8638
8639 let wrap_column = buffer
8640 .language_settings_at(Point::new(start_row, 0), cx)
8641 .preferred_line_length as usize;
8642 let wrapped_text = wrap_with_prefix(
8643 line_prefix,
8644 lines_without_prefixes.join(" "),
8645 wrap_column,
8646 tab_size,
8647 );
8648
8649 // TODO: should always use char-based diff while still supporting cursor behavior that
8650 // matches vim.
8651 let mut diff_options = DiffOptions::default();
8652 if is_vim_mode == IsVimMode::Yes {
8653 diff_options.max_word_diff_len = 0;
8654 diff_options.max_word_diff_line_count = 0;
8655 } else {
8656 diff_options.max_word_diff_len = usize::MAX;
8657 diff_options.max_word_diff_line_count = usize::MAX;
8658 }
8659
8660 for (old_range, new_text) in
8661 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8662 {
8663 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8664 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8665 edits.push((edit_start..edit_end, new_text));
8666 }
8667
8668 rewrapped_row_ranges.push(start_row..=end_row);
8669 }
8670
8671 self.buffer
8672 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8673 }
8674
8675 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8676 let mut text = String::new();
8677 let buffer = self.buffer.read(cx).snapshot(cx);
8678 let mut selections = self.selections.all::<Point>(cx);
8679 let mut clipboard_selections = Vec::with_capacity(selections.len());
8680 {
8681 let max_point = buffer.max_point();
8682 let mut is_first = true;
8683 for selection in &mut selections {
8684 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8685 if is_entire_line {
8686 selection.start = Point::new(selection.start.row, 0);
8687 if !selection.is_empty() && selection.end.column == 0 {
8688 selection.end = cmp::min(max_point, selection.end);
8689 } else {
8690 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8691 }
8692 selection.goal = SelectionGoal::None;
8693 }
8694 if is_first {
8695 is_first = false;
8696 } else {
8697 text += "\n";
8698 }
8699 let mut len = 0;
8700 for chunk in buffer.text_for_range(selection.start..selection.end) {
8701 text.push_str(chunk);
8702 len += chunk.len();
8703 }
8704 clipboard_selections.push(ClipboardSelection {
8705 len,
8706 is_entire_line,
8707 start_column: selection.start.column,
8708 });
8709 }
8710 }
8711
8712 self.transact(window, cx, |this, window, cx| {
8713 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8714 s.select(selections);
8715 });
8716 this.insert("", window, cx);
8717 });
8718 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8719 }
8720
8721 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8722 let item = self.cut_common(window, cx);
8723 cx.write_to_clipboard(item);
8724 }
8725
8726 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8727 self.change_selections(None, window, cx, |s| {
8728 s.move_with(|snapshot, sel| {
8729 if sel.is_empty() {
8730 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8731 }
8732 });
8733 });
8734 let item = self.cut_common(window, cx);
8735 cx.set_global(KillRing(item))
8736 }
8737
8738 pub fn kill_ring_yank(
8739 &mut self,
8740 _: &KillRingYank,
8741 window: &mut Window,
8742 cx: &mut Context<Self>,
8743 ) {
8744 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8745 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8746 (kill_ring.text().to_string(), kill_ring.metadata_json())
8747 } else {
8748 return;
8749 }
8750 } else {
8751 return;
8752 };
8753 self.do_paste(&text, metadata, false, window, cx);
8754 }
8755
8756 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8757 let selections = self.selections.all::<Point>(cx);
8758 let buffer = self.buffer.read(cx).read(cx);
8759 let mut text = String::new();
8760
8761 let mut clipboard_selections = Vec::with_capacity(selections.len());
8762 {
8763 let max_point = buffer.max_point();
8764 let mut is_first = true;
8765 for selection in selections.iter() {
8766 let mut start = selection.start;
8767 let mut end = selection.end;
8768 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8769 if is_entire_line {
8770 start = Point::new(start.row, 0);
8771 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8772 }
8773 if is_first {
8774 is_first = false;
8775 } else {
8776 text += "\n";
8777 }
8778 let mut len = 0;
8779 for chunk in buffer.text_for_range(start..end) {
8780 text.push_str(chunk);
8781 len += chunk.len();
8782 }
8783 clipboard_selections.push(ClipboardSelection {
8784 len,
8785 is_entire_line,
8786 start_column: start.column,
8787 });
8788 }
8789 }
8790
8791 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8792 text,
8793 clipboard_selections,
8794 ));
8795 }
8796
8797 pub fn do_paste(
8798 &mut self,
8799 text: &String,
8800 clipboard_selections: Option<Vec<ClipboardSelection>>,
8801 handle_entire_lines: bool,
8802 window: &mut Window,
8803 cx: &mut Context<Self>,
8804 ) {
8805 if self.read_only(cx) {
8806 return;
8807 }
8808
8809 let clipboard_text = Cow::Borrowed(text);
8810
8811 self.transact(window, cx, |this, window, cx| {
8812 if let Some(mut clipboard_selections) = clipboard_selections {
8813 let old_selections = this.selections.all::<usize>(cx);
8814 let all_selections_were_entire_line =
8815 clipboard_selections.iter().all(|s| s.is_entire_line);
8816 let first_selection_start_column =
8817 clipboard_selections.first().map(|s| s.start_column);
8818 if clipboard_selections.len() != old_selections.len() {
8819 clipboard_selections.drain(..);
8820 }
8821 let cursor_offset = this.selections.last::<usize>(cx).head();
8822 let mut auto_indent_on_paste = true;
8823
8824 this.buffer.update(cx, |buffer, cx| {
8825 let snapshot = buffer.read(cx);
8826 auto_indent_on_paste = snapshot
8827 .language_settings_at(cursor_offset, cx)
8828 .auto_indent_on_paste;
8829
8830 let mut start_offset = 0;
8831 let mut edits = Vec::new();
8832 let mut original_start_columns = Vec::new();
8833 for (ix, selection) in old_selections.iter().enumerate() {
8834 let to_insert;
8835 let entire_line;
8836 let original_start_column;
8837 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8838 let end_offset = start_offset + clipboard_selection.len;
8839 to_insert = &clipboard_text[start_offset..end_offset];
8840 entire_line = clipboard_selection.is_entire_line;
8841 start_offset = end_offset + 1;
8842 original_start_column = Some(clipboard_selection.start_column);
8843 } else {
8844 to_insert = clipboard_text.as_str();
8845 entire_line = all_selections_were_entire_line;
8846 original_start_column = first_selection_start_column
8847 }
8848
8849 // If the corresponding selection was empty when this slice of the
8850 // clipboard text was written, then the entire line containing the
8851 // selection was copied. If this selection is also currently empty,
8852 // then paste the line before the current line of the buffer.
8853 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8854 let column = selection.start.to_point(&snapshot).column as usize;
8855 let line_start = selection.start - column;
8856 line_start..line_start
8857 } else {
8858 selection.range()
8859 };
8860
8861 edits.push((range, to_insert));
8862 original_start_columns.extend(original_start_column);
8863 }
8864 drop(snapshot);
8865
8866 buffer.edit(
8867 edits,
8868 if auto_indent_on_paste {
8869 Some(AutoindentMode::Block {
8870 original_start_columns,
8871 })
8872 } else {
8873 None
8874 },
8875 cx,
8876 );
8877 });
8878
8879 let selections = this.selections.all::<usize>(cx);
8880 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8881 s.select(selections)
8882 });
8883 } else {
8884 this.insert(&clipboard_text, window, cx);
8885 }
8886 });
8887 }
8888
8889 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8890 if let Some(item) = cx.read_from_clipboard() {
8891 let entries = item.entries();
8892
8893 match entries.first() {
8894 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8895 // of all the pasted entries.
8896 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8897 .do_paste(
8898 clipboard_string.text(),
8899 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8900 true,
8901 window,
8902 cx,
8903 ),
8904 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8905 }
8906 }
8907 }
8908
8909 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8910 if self.read_only(cx) {
8911 return;
8912 }
8913
8914 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8915 if let Some((selections, _)) =
8916 self.selection_history.transaction(transaction_id).cloned()
8917 {
8918 self.change_selections(None, window, cx, |s| {
8919 s.select_anchors(selections.to_vec());
8920 });
8921 } else {
8922 log::error!(
8923 "No entry in selection_history found for undo. \
8924 This may correspond to a bug where undo does not update the selection. \
8925 If this is occurring, please add details to \
8926 https://github.com/zed-industries/zed/issues/22692"
8927 );
8928 }
8929 self.request_autoscroll(Autoscroll::fit(), cx);
8930 self.unmark_text(window, cx);
8931 self.refresh_inline_completion(true, false, window, cx);
8932 cx.emit(EditorEvent::Edited { transaction_id });
8933 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8934 }
8935 }
8936
8937 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8938 if self.read_only(cx) {
8939 return;
8940 }
8941
8942 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8943 if let Some((_, Some(selections))) =
8944 self.selection_history.transaction(transaction_id).cloned()
8945 {
8946 self.change_selections(None, window, cx, |s| {
8947 s.select_anchors(selections.to_vec());
8948 });
8949 } else {
8950 log::error!(
8951 "No entry in selection_history found for redo. \
8952 This may correspond to a bug where undo does not update the selection. \
8953 If this is occurring, please add details to \
8954 https://github.com/zed-industries/zed/issues/22692"
8955 );
8956 }
8957 self.request_autoscroll(Autoscroll::fit(), cx);
8958 self.unmark_text(window, cx);
8959 self.refresh_inline_completion(true, false, window, cx);
8960 cx.emit(EditorEvent::Edited { transaction_id });
8961 }
8962 }
8963
8964 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8965 self.buffer
8966 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8967 }
8968
8969 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8970 self.buffer
8971 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8972 }
8973
8974 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8976 let line_mode = s.line_mode;
8977 s.move_with(|map, selection| {
8978 let cursor = if selection.is_empty() && !line_mode {
8979 movement::left(map, selection.start)
8980 } else {
8981 selection.start
8982 };
8983 selection.collapse_to(cursor, SelectionGoal::None);
8984 });
8985 })
8986 }
8987
8988 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8989 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8990 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8991 })
8992 }
8993
8994 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8995 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8996 let line_mode = s.line_mode;
8997 s.move_with(|map, selection| {
8998 let cursor = if selection.is_empty() && !line_mode {
8999 movement::right(map, selection.end)
9000 } else {
9001 selection.end
9002 };
9003 selection.collapse_to(cursor, SelectionGoal::None)
9004 });
9005 })
9006 }
9007
9008 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9009 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9010 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9011 })
9012 }
9013
9014 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9015 if self.take_rename(true, window, cx).is_some() {
9016 return;
9017 }
9018
9019 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9020 cx.propagate();
9021 return;
9022 }
9023
9024 let text_layout_details = &self.text_layout_details(window);
9025 let selection_count = self.selections.count();
9026 let first_selection = self.selections.first_anchor();
9027
9028 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9029 let line_mode = s.line_mode;
9030 s.move_with(|map, selection| {
9031 if !selection.is_empty() && !line_mode {
9032 selection.goal = SelectionGoal::None;
9033 }
9034 let (cursor, goal) = movement::up(
9035 map,
9036 selection.start,
9037 selection.goal,
9038 false,
9039 text_layout_details,
9040 );
9041 selection.collapse_to(cursor, goal);
9042 });
9043 });
9044
9045 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9046 {
9047 cx.propagate();
9048 }
9049 }
9050
9051 pub fn move_up_by_lines(
9052 &mut self,
9053 action: &MoveUpByLines,
9054 window: &mut Window,
9055 cx: &mut Context<Self>,
9056 ) {
9057 if self.take_rename(true, window, cx).is_some() {
9058 return;
9059 }
9060
9061 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9062 cx.propagate();
9063 return;
9064 }
9065
9066 let text_layout_details = &self.text_layout_details(window);
9067
9068 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9069 let line_mode = s.line_mode;
9070 s.move_with(|map, selection| {
9071 if !selection.is_empty() && !line_mode {
9072 selection.goal = SelectionGoal::None;
9073 }
9074 let (cursor, goal) = movement::up_by_rows(
9075 map,
9076 selection.start,
9077 action.lines,
9078 selection.goal,
9079 false,
9080 text_layout_details,
9081 );
9082 selection.collapse_to(cursor, goal);
9083 });
9084 })
9085 }
9086
9087 pub fn move_down_by_lines(
9088 &mut self,
9089 action: &MoveDownByLines,
9090 window: &mut Window,
9091 cx: &mut Context<Self>,
9092 ) {
9093 if self.take_rename(true, window, cx).is_some() {
9094 return;
9095 }
9096
9097 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9098 cx.propagate();
9099 return;
9100 }
9101
9102 let text_layout_details = &self.text_layout_details(window);
9103
9104 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9105 let line_mode = s.line_mode;
9106 s.move_with(|map, selection| {
9107 if !selection.is_empty() && !line_mode {
9108 selection.goal = SelectionGoal::None;
9109 }
9110 let (cursor, goal) = movement::down_by_rows(
9111 map,
9112 selection.start,
9113 action.lines,
9114 selection.goal,
9115 false,
9116 text_layout_details,
9117 );
9118 selection.collapse_to(cursor, goal);
9119 });
9120 })
9121 }
9122
9123 pub fn select_down_by_lines(
9124 &mut self,
9125 action: &SelectDownByLines,
9126 window: &mut Window,
9127 cx: &mut Context<Self>,
9128 ) {
9129 let text_layout_details = &self.text_layout_details(window);
9130 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9131 s.move_heads_with(|map, head, goal| {
9132 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9133 })
9134 })
9135 }
9136
9137 pub fn select_up_by_lines(
9138 &mut self,
9139 action: &SelectUpByLines,
9140 window: &mut Window,
9141 cx: &mut Context<Self>,
9142 ) {
9143 let text_layout_details = &self.text_layout_details(window);
9144 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9145 s.move_heads_with(|map, head, goal| {
9146 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9147 })
9148 })
9149 }
9150
9151 pub fn select_page_up(
9152 &mut self,
9153 _: &SelectPageUp,
9154 window: &mut Window,
9155 cx: &mut Context<Self>,
9156 ) {
9157 let Some(row_count) = self.visible_row_count() else {
9158 return;
9159 };
9160
9161 let text_layout_details = &self.text_layout_details(window);
9162
9163 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9164 s.move_heads_with(|map, head, goal| {
9165 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9166 })
9167 })
9168 }
9169
9170 pub fn move_page_up(
9171 &mut self,
9172 action: &MovePageUp,
9173 window: &mut Window,
9174 cx: &mut Context<Self>,
9175 ) {
9176 if self.take_rename(true, window, cx).is_some() {
9177 return;
9178 }
9179
9180 if self
9181 .context_menu
9182 .borrow_mut()
9183 .as_mut()
9184 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9185 .unwrap_or(false)
9186 {
9187 return;
9188 }
9189
9190 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9191 cx.propagate();
9192 return;
9193 }
9194
9195 let Some(row_count) = self.visible_row_count() else {
9196 return;
9197 };
9198
9199 let autoscroll = if action.center_cursor {
9200 Autoscroll::center()
9201 } else {
9202 Autoscroll::fit()
9203 };
9204
9205 let text_layout_details = &self.text_layout_details(window);
9206
9207 self.change_selections(Some(autoscroll), window, cx, |s| {
9208 let line_mode = s.line_mode;
9209 s.move_with(|map, selection| {
9210 if !selection.is_empty() && !line_mode {
9211 selection.goal = SelectionGoal::None;
9212 }
9213 let (cursor, goal) = movement::up_by_rows(
9214 map,
9215 selection.end,
9216 row_count,
9217 selection.goal,
9218 false,
9219 text_layout_details,
9220 );
9221 selection.collapse_to(cursor, goal);
9222 });
9223 });
9224 }
9225
9226 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9227 let text_layout_details = &self.text_layout_details(window);
9228 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9229 s.move_heads_with(|map, head, goal| {
9230 movement::up(map, head, goal, false, text_layout_details)
9231 })
9232 })
9233 }
9234
9235 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9236 self.take_rename(true, window, cx);
9237
9238 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9239 cx.propagate();
9240 return;
9241 }
9242
9243 let text_layout_details = &self.text_layout_details(window);
9244 let selection_count = self.selections.count();
9245 let first_selection = self.selections.first_anchor();
9246
9247 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9248 let line_mode = s.line_mode;
9249 s.move_with(|map, selection| {
9250 if !selection.is_empty() && !line_mode {
9251 selection.goal = SelectionGoal::None;
9252 }
9253 let (cursor, goal) = movement::down(
9254 map,
9255 selection.end,
9256 selection.goal,
9257 false,
9258 text_layout_details,
9259 );
9260 selection.collapse_to(cursor, goal);
9261 });
9262 });
9263
9264 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9265 {
9266 cx.propagate();
9267 }
9268 }
9269
9270 pub fn select_page_down(
9271 &mut self,
9272 _: &SelectPageDown,
9273 window: &mut Window,
9274 cx: &mut Context<Self>,
9275 ) {
9276 let Some(row_count) = self.visible_row_count() else {
9277 return;
9278 };
9279
9280 let text_layout_details = &self.text_layout_details(window);
9281
9282 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9283 s.move_heads_with(|map, head, goal| {
9284 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9285 })
9286 })
9287 }
9288
9289 pub fn move_page_down(
9290 &mut self,
9291 action: &MovePageDown,
9292 window: &mut Window,
9293 cx: &mut Context<Self>,
9294 ) {
9295 if self.take_rename(true, window, cx).is_some() {
9296 return;
9297 }
9298
9299 if self
9300 .context_menu
9301 .borrow_mut()
9302 .as_mut()
9303 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9304 .unwrap_or(false)
9305 {
9306 return;
9307 }
9308
9309 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9310 cx.propagate();
9311 return;
9312 }
9313
9314 let Some(row_count) = self.visible_row_count() else {
9315 return;
9316 };
9317
9318 let autoscroll = if action.center_cursor {
9319 Autoscroll::center()
9320 } else {
9321 Autoscroll::fit()
9322 };
9323
9324 let text_layout_details = &self.text_layout_details(window);
9325 self.change_selections(Some(autoscroll), window, cx, |s| {
9326 let line_mode = s.line_mode;
9327 s.move_with(|map, selection| {
9328 if !selection.is_empty() && !line_mode {
9329 selection.goal = SelectionGoal::None;
9330 }
9331 let (cursor, goal) = movement::down_by_rows(
9332 map,
9333 selection.end,
9334 row_count,
9335 selection.goal,
9336 false,
9337 text_layout_details,
9338 );
9339 selection.collapse_to(cursor, goal);
9340 });
9341 });
9342 }
9343
9344 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9345 let text_layout_details = &self.text_layout_details(window);
9346 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9347 s.move_heads_with(|map, head, goal| {
9348 movement::down(map, head, goal, false, text_layout_details)
9349 })
9350 });
9351 }
9352
9353 pub fn context_menu_first(
9354 &mut self,
9355 _: &ContextMenuFirst,
9356 _window: &mut Window,
9357 cx: &mut Context<Self>,
9358 ) {
9359 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9360 context_menu.select_first(self.completion_provider.as_deref(), cx);
9361 }
9362 }
9363
9364 pub fn context_menu_prev(
9365 &mut self,
9366 _: &ContextMenuPrevious,
9367 _window: &mut Window,
9368 cx: &mut Context<Self>,
9369 ) {
9370 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9371 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9372 }
9373 }
9374
9375 pub fn context_menu_next(
9376 &mut self,
9377 _: &ContextMenuNext,
9378 _window: &mut Window,
9379 cx: &mut Context<Self>,
9380 ) {
9381 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9382 context_menu.select_next(self.completion_provider.as_deref(), cx);
9383 }
9384 }
9385
9386 pub fn context_menu_last(
9387 &mut self,
9388 _: &ContextMenuLast,
9389 _window: &mut Window,
9390 cx: &mut Context<Self>,
9391 ) {
9392 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9393 context_menu.select_last(self.completion_provider.as_deref(), cx);
9394 }
9395 }
9396
9397 pub fn move_to_previous_word_start(
9398 &mut self,
9399 _: &MoveToPreviousWordStart,
9400 window: &mut Window,
9401 cx: &mut Context<Self>,
9402 ) {
9403 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9404 s.move_cursors_with(|map, head, _| {
9405 (
9406 movement::previous_word_start(map, head),
9407 SelectionGoal::None,
9408 )
9409 });
9410 })
9411 }
9412
9413 pub fn move_to_previous_subword_start(
9414 &mut self,
9415 _: &MoveToPreviousSubwordStart,
9416 window: &mut Window,
9417 cx: &mut Context<Self>,
9418 ) {
9419 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9420 s.move_cursors_with(|map, head, _| {
9421 (
9422 movement::previous_subword_start(map, head),
9423 SelectionGoal::None,
9424 )
9425 });
9426 })
9427 }
9428
9429 pub fn select_to_previous_word_start(
9430 &mut self,
9431 _: &SelectToPreviousWordStart,
9432 window: &mut Window,
9433 cx: &mut Context<Self>,
9434 ) {
9435 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9436 s.move_heads_with(|map, head, _| {
9437 (
9438 movement::previous_word_start(map, head),
9439 SelectionGoal::None,
9440 )
9441 });
9442 })
9443 }
9444
9445 pub fn select_to_previous_subword_start(
9446 &mut self,
9447 _: &SelectToPreviousSubwordStart,
9448 window: &mut Window,
9449 cx: &mut Context<Self>,
9450 ) {
9451 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9452 s.move_heads_with(|map, head, _| {
9453 (
9454 movement::previous_subword_start(map, head),
9455 SelectionGoal::None,
9456 )
9457 });
9458 })
9459 }
9460
9461 pub fn delete_to_previous_word_start(
9462 &mut self,
9463 action: &DeleteToPreviousWordStart,
9464 window: &mut Window,
9465 cx: &mut Context<Self>,
9466 ) {
9467 self.transact(window, cx, |this, window, cx| {
9468 this.select_autoclose_pair(window, cx);
9469 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9470 let line_mode = s.line_mode;
9471 s.move_with(|map, selection| {
9472 if selection.is_empty() && !line_mode {
9473 let cursor = if action.ignore_newlines {
9474 movement::previous_word_start(map, selection.head())
9475 } else {
9476 movement::previous_word_start_or_newline(map, selection.head())
9477 };
9478 selection.set_head(cursor, SelectionGoal::None);
9479 }
9480 });
9481 });
9482 this.insert("", window, cx);
9483 });
9484 }
9485
9486 pub fn delete_to_previous_subword_start(
9487 &mut self,
9488 _: &DeleteToPreviousSubwordStart,
9489 window: &mut Window,
9490 cx: &mut Context<Self>,
9491 ) {
9492 self.transact(window, cx, |this, window, cx| {
9493 this.select_autoclose_pair(window, cx);
9494 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9495 let line_mode = s.line_mode;
9496 s.move_with(|map, selection| {
9497 if selection.is_empty() && !line_mode {
9498 let cursor = movement::previous_subword_start(map, selection.head());
9499 selection.set_head(cursor, SelectionGoal::None);
9500 }
9501 });
9502 });
9503 this.insert("", window, cx);
9504 });
9505 }
9506
9507 pub fn move_to_next_word_end(
9508 &mut self,
9509 _: &MoveToNextWordEnd,
9510 window: &mut Window,
9511 cx: &mut Context<Self>,
9512 ) {
9513 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9514 s.move_cursors_with(|map, head, _| {
9515 (movement::next_word_end(map, head), SelectionGoal::None)
9516 });
9517 })
9518 }
9519
9520 pub fn move_to_next_subword_end(
9521 &mut self,
9522 _: &MoveToNextSubwordEnd,
9523 window: &mut Window,
9524 cx: &mut Context<Self>,
9525 ) {
9526 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9527 s.move_cursors_with(|map, head, _| {
9528 (movement::next_subword_end(map, head), SelectionGoal::None)
9529 });
9530 })
9531 }
9532
9533 pub fn select_to_next_word_end(
9534 &mut self,
9535 _: &SelectToNextWordEnd,
9536 window: &mut Window,
9537 cx: &mut Context<Self>,
9538 ) {
9539 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9540 s.move_heads_with(|map, head, _| {
9541 (movement::next_word_end(map, head), SelectionGoal::None)
9542 });
9543 })
9544 }
9545
9546 pub fn select_to_next_subword_end(
9547 &mut self,
9548 _: &SelectToNextSubwordEnd,
9549 window: &mut Window,
9550 cx: &mut Context<Self>,
9551 ) {
9552 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9553 s.move_heads_with(|map, head, _| {
9554 (movement::next_subword_end(map, head), SelectionGoal::None)
9555 });
9556 })
9557 }
9558
9559 pub fn delete_to_next_word_end(
9560 &mut self,
9561 action: &DeleteToNextWordEnd,
9562 window: &mut Window,
9563 cx: &mut Context<Self>,
9564 ) {
9565 self.transact(window, cx, |this, window, cx| {
9566 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9567 let line_mode = s.line_mode;
9568 s.move_with(|map, selection| {
9569 if selection.is_empty() && !line_mode {
9570 let cursor = if action.ignore_newlines {
9571 movement::next_word_end(map, selection.head())
9572 } else {
9573 movement::next_word_end_or_newline(map, selection.head())
9574 };
9575 selection.set_head(cursor, SelectionGoal::None);
9576 }
9577 });
9578 });
9579 this.insert("", window, cx);
9580 });
9581 }
9582
9583 pub fn delete_to_next_subword_end(
9584 &mut self,
9585 _: &DeleteToNextSubwordEnd,
9586 window: &mut Window,
9587 cx: &mut Context<Self>,
9588 ) {
9589 self.transact(window, cx, |this, window, cx| {
9590 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9591 s.move_with(|map, selection| {
9592 if selection.is_empty() {
9593 let cursor = movement::next_subword_end(map, selection.head());
9594 selection.set_head(cursor, SelectionGoal::None);
9595 }
9596 });
9597 });
9598 this.insert("", window, cx);
9599 });
9600 }
9601
9602 pub fn move_to_beginning_of_line(
9603 &mut self,
9604 action: &MoveToBeginningOfLine,
9605 window: &mut Window,
9606 cx: &mut Context<Self>,
9607 ) {
9608 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9609 s.move_cursors_with(|map, head, _| {
9610 (
9611 movement::indented_line_beginning(
9612 map,
9613 head,
9614 action.stop_at_soft_wraps,
9615 action.stop_at_indent,
9616 ),
9617 SelectionGoal::None,
9618 )
9619 });
9620 })
9621 }
9622
9623 pub fn select_to_beginning_of_line(
9624 &mut self,
9625 action: &SelectToBeginningOfLine,
9626 window: &mut Window,
9627 cx: &mut Context<Self>,
9628 ) {
9629 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9630 s.move_heads_with(|map, head, _| {
9631 (
9632 movement::indented_line_beginning(
9633 map,
9634 head,
9635 action.stop_at_soft_wraps,
9636 action.stop_at_indent,
9637 ),
9638 SelectionGoal::None,
9639 )
9640 });
9641 });
9642 }
9643
9644 pub fn delete_to_beginning_of_line(
9645 &mut self,
9646 action: &DeleteToBeginningOfLine,
9647 window: &mut Window,
9648 cx: &mut Context<Self>,
9649 ) {
9650 self.transact(window, cx, |this, window, cx| {
9651 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9652 s.move_with(|_, selection| {
9653 selection.reversed = true;
9654 });
9655 });
9656
9657 this.select_to_beginning_of_line(
9658 &SelectToBeginningOfLine {
9659 stop_at_soft_wraps: false,
9660 stop_at_indent: action.stop_at_indent,
9661 },
9662 window,
9663 cx,
9664 );
9665 this.backspace(&Backspace, window, cx);
9666 });
9667 }
9668
9669 pub fn move_to_end_of_line(
9670 &mut self,
9671 action: &MoveToEndOfLine,
9672 window: &mut Window,
9673 cx: &mut Context<Self>,
9674 ) {
9675 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9676 s.move_cursors_with(|map, head, _| {
9677 (
9678 movement::line_end(map, head, action.stop_at_soft_wraps),
9679 SelectionGoal::None,
9680 )
9681 });
9682 })
9683 }
9684
9685 pub fn select_to_end_of_line(
9686 &mut self,
9687 action: &SelectToEndOfLine,
9688 window: &mut Window,
9689 cx: &mut Context<Self>,
9690 ) {
9691 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9692 s.move_heads_with(|map, head, _| {
9693 (
9694 movement::line_end(map, head, action.stop_at_soft_wraps),
9695 SelectionGoal::None,
9696 )
9697 });
9698 })
9699 }
9700
9701 pub fn delete_to_end_of_line(
9702 &mut self,
9703 _: &DeleteToEndOfLine,
9704 window: &mut Window,
9705 cx: &mut Context<Self>,
9706 ) {
9707 self.transact(window, cx, |this, window, cx| {
9708 this.select_to_end_of_line(
9709 &SelectToEndOfLine {
9710 stop_at_soft_wraps: false,
9711 },
9712 window,
9713 cx,
9714 );
9715 this.delete(&Delete, window, cx);
9716 });
9717 }
9718
9719 pub fn cut_to_end_of_line(
9720 &mut self,
9721 _: &CutToEndOfLine,
9722 window: &mut Window,
9723 cx: &mut Context<Self>,
9724 ) {
9725 self.transact(window, cx, |this, window, cx| {
9726 this.select_to_end_of_line(
9727 &SelectToEndOfLine {
9728 stop_at_soft_wraps: false,
9729 },
9730 window,
9731 cx,
9732 );
9733 this.cut(&Cut, window, cx);
9734 });
9735 }
9736
9737 pub fn move_to_start_of_paragraph(
9738 &mut self,
9739 _: &MoveToStartOfParagraph,
9740 window: &mut Window,
9741 cx: &mut Context<Self>,
9742 ) {
9743 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9744 cx.propagate();
9745 return;
9746 }
9747
9748 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9749 s.move_with(|map, selection| {
9750 selection.collapse_to(
9751 movement::start_of_paragraph(map, selection.head(), 1),
9752 SelectionGoal::None,
9753 )
9754 });
9755 })
9756 }
9757
9758 pub fn move_to_end_of_paragraph(
9759 &mut self,
9760 _: &MoveToEndOfParagraph,
9761 window: &mut Window,
9762 cx: &mut Context<Self>,
9763 ) {
9764 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9765 cx.propagate();
9766 return;
9767 }
9768
9769 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9770 s.move_with(|map, selection| {
9771 selection.collapse_to(
9772 movement::end_of_paragraph(map, selection.head(), 1),
9773 SelectionGoal::None,
9774 )
9775 });
9776 })
9777 }
9778
9779 pub fn select_to_start_of_paragraph(
9780 &mut self,
9781 _: &SelectToStartOfParagraph,
9782 window: &mut Window,
9783 cx: &mut Context<Self>,
9784 ) {
9785 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9786 cx.propagate();
9787 return;
9788 }
9789
9790 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9791 s.move_heads_with(|map, head, _| {
9792 (
9793 movement::start_of_paragraph(map, head, 1),
9794 SelectionGoal::None,
9795 )
9796 });
9797 })
9798 }
9799
9800 pub fn select_to_end_of_paragraph(
9801 &mut self,
9802 _: &SelectToEndOfParagraph,
9803 window: &mut Window,
9804 cx: &mut Context<Self>,
9805 ) {
9806 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9807 cx.propagate();
9808 return;
9809 }
9810
9811 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9812 s.move_heads_with(|map, head, _| {
9813 (
9814 movement::end_of_paragraph(map, head, 1),
9815 SelectionGoal::None,
9816 )
9817 });
9818 })
9819 }
9820
9821 pub fn move_to_start_of_excerpt(
9822 &mut self,
9823 _: &MoveToStartOfExcerpt,
9824 window: &mut Window,
9825 cx: &mut Context<Self>,
9826 ) {
9827 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9828 cx.propagate();
9829 return;
9830 }
9831
9832 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9833 s.move_with(|map, selection| {
9834 selection.collapse_to(
9835 movement::start_of_excerpt(
9836 map,
9837 selection.head(),
9838 workspace::searchable::Direction::Prev,
9839 ),
9840 SelectionGoal::None,
9841 )
9842 });
9843 })
9844 }
9845
9846 pub fn move_to_end_of_excerpt(
9847 &mut self,
9848 _: &MoveToEndOfExcerpt,
9849 window: &mut Window,
9850 cx: &mut Context<Self>,
9851 ) {
9852 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9853 cx.propagate();
9854 return;
9855 }
9856
9857 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9858 s.move_with(|map, selection| {
9859 selection.collapse_to(
9860 movement::end_of_excerpt(
9861 map,
9862 selection.head(),
9863 workspace::searchable::Direction::Next,
9864 ),
9865 SelectionGoal::None,
9866 )
9867 });
9868 })
9869 }
9870
9871 pub fn select_to_start_of_excerpt(
9872 &mut self,
9873 _: &SelectToStartOfExcerpt,
9874 window: &mut Window,
9875 cx: &mut Context<Self>,
9876 ) {
9877 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9878 cx.propagate();
9879 return;
9880 }
9881
9882 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9883 s.move_heads_with(|map, head, _| {
9884 (
9885 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9886 SelectionGoal::None,
9887 )
9888 });
9889 })
9890 }
9891
9892 pub fn select_to_end_of_excerpt(
9893 &mut self,
9894 _: &SelectToEndOfExcerpt,
9895 window: &mut Window,
9896 cx: &mut Context<Self>,
9897 ) {
9898 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9899 cx.propagate();
9900 return;
9901 }
9902
9903 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9904 s.move_heads_with(|map, head, _| {
9905 (
9906 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9907 SelectionGoal::None,
9908 )
9909 });
9910 })
9911 }
9912
9913 pub fn move_to_beginning(
9914 &mut self,
9915 _: &MoveToBeginning,
9916 window: &mut Window,
9917 cx: &mut Context<Self>,
9918 ) {
9919 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9920 cx.propagate();
9921 return;
9922 }
9923
9924 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9925 s.select_ranges(vec![0..0]);
9926 });
9927 }
9928
9929 pub fn select_to_beginning(
9930 &mut self,
9931 _: &SelectToBeginning,
9932 window: &mut Window,
9933 cx: &mut Context<Self>,
9934 ) {
9935 let mut selection = self.selections.last::<Point>(cx);
9936 selection.set_head(Point::zero(), SelectionGoal::None);
9937
9938 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9939 s.select(vec![selection]);
9940 });
9941 }
9942
9943 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9944 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9945 cx.propagate();
9946 return;
9947 }
9948
9949 let cursor = self.buffer.read(cx).read(cx).len();
9950 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9951 s.select_ranges(vec![cursor..cursor])
9952 });
9953 }
9954
9955 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9956 self.nav_history = nav_history;
9957 }
9958
9959 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9960 self.nav_history.as_ref()
9961 }
9962
9963 fn push_to_nav_history(
9964 &mut self,
9965 cursor_anchor: Anchor,
9966 new_position: Option<Point>,
9967 cx: &mut Context<Self>,
9968 ) {
9969 if let Some(nav_history) = self.nav_history.as_mut() {
9970 let buffer = self.buffer.read(cx).read(cx);
9971 let cursor_position = cursor_anchor.to_point(&buffer);
9972 let scroll_state = self.scroll_manager.anchor();
9973 let scroll_top_row = scroll_state.top_row(&buffer);
9974 drop(buffer);
9975
9976 if let Some(new_position) = new_position {
9977 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9978 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9979 return;
9980 }
9981 }
9982
9983 nav_history.push(
9984 Some(NavigationData {
9985 cursor_anchor,
9986 cursor_position,
9987 scroll_anchor: scroll_state,
9988 scroll_top_row,
9989 }),
9990 cx,
9991 );
9992 }
9993 }
9994
9995 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9996 let buffer = self.buffer.read(cx).snapshot(cx);
9997 let mut selection = self.selections.first::<usize>(cx);
9998 selection.set_head(buffer.len(), SelectionGoal::None);
9999 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10000 s.select(vec![selection]);
10001 });
10002 }
10003
10004 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10005 let end = self.buffer.read(cx).read(cx).len();
10006 self.change_selections(None, window, cx, |s| {
10007 s.select_ranges(vec![0..end]);
10008 });
10009 }
10010
10011 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10012 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10013 let mut selections = self.selections.all::<Point>(cx);
10014 let max_point = display_map.buffer_snapshot.max_point();
10015 for selection in &mut selections {
10016 let rows = selection.spanned_rows(true, &display_map);
10017 selection.start = Point::new(rows.start.0, 0);
10018 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10019 selection.reversed = false;
10020 }
10021 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10022 s.select(selections);
10023 });
10024 }
10025
10026 pub fn split_selection_into_lines(
10027 &mut self,
10028 _: &SplitSelectionIntoLines,
10029 window: &mut Window,
10030 cx: &mut Context<Self>,
10031 ) {
10032 let selections = self
10033 .selections
10034 .all::<Point>(cx)
10035 .into_iter()
10036 .map(|selection| selection.start..selection.end)
10037 .collect::<Vec<_>>();
10038 self.unfold_ranges(&selections, true, true, cx);
10039
10040 let mut new_selection_ranges = Vec::new();
10041 {
10042 let buffer = self.buffer.read(cx).read(cx);
10043 for selection in selections {
10044 for row in selection.start.row..selection.end.row {
10045 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10046 new_selection_ranges.push(cursor..cursor);
10047 }
10048
10049 let is_multiline_selection = selection.start.row != selection.end.row;
10050 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10051 // so this action feels more ergonomic when paired with other selection operations
10052 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10053 if !should_skip_last {
10054 new_selection_ranges.push(selection.end..selection.end);
10055 }
10056 }
10057 }
10058 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10059 s.select_ranges(new_selection_ranges);
10060 });
10061 }
10062
10063 pub fn add_selection_above(
10064 &mut self,
10065 _: &AddSelectionAbove,
10066 window: &mut Window,
10067 cx: &mut Context<Self>,
10068 ) {
10069 self.add_selection(true, window, cx);
10070 }
10071
10072 pub fn add_selection_below(
10073 &mut self,
10074 _: &AddSelectionBelow,
10075 window: &mut Window,
10076 cx: &mut Context<Self>,
10077 ) {
10078 self.add_selection(false, window, cx);
10079 }
10080
10081 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10082 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10083 let mut selections = self.selections.all::<Point>(cx);
10084 let text_layout_details = self.text_layout_details(window);
10085 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10086 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10087 let range = oldest_selection.display_range(&display_map).sorted();
10088
10089 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10090 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10091 let positions = start_x.min(end_x)..start_x.max(end_x);
10092
10093 selections.clear();
10094 let mut stack = Vec::new();
10095 for row in range.start.row().0..=range.end.row().0 {
10096 if let Some(selection) = self.selections.build_columnar_selection(
10097 &display_map,
10098 DisplayRow(row),
10099 &positions,
10100 oldest_selection.reversed,
10101 &text_layout_details,
10102 ) {
10103 stack.push(selection.id);
10104 selections.push(selection);
10105 }
10106 }
10107
10108 if above {
10109 stack.reverse();
10110 }
10111
10112 AddSelectionsState { above, stack }
10113 });
10114
10115 let last_added_selection = *state.stack.last().unwrap();
10116 let mut new_selections = Vec::new();
10117 if above == state.above {
10118 let end_row = if above {
10119 DisplayRow(0)
10120 } else {
10121 display_map.max_point().row()
10122 };
10123
10124 'outer: for selection in selections {
10125 if selection.id == last_added_selection {
10126 let range = selection.display_range(&display_map).sorted();
10127 debug_assert_eq!(range.start.row(), range.end.row());
10128 let mut row = range.start.row();
10129 let positions =
10130 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10131 px(start)..px(end)
10132 } else {
10133 let start_x =
10134 display_map.x_for_display_point(range.start, &text_layout_details);
10135 let end_x =
10136 display_map.x_for_display_point(range.end, &text_layout_details);
10137 start_x.min(end_x)..start_x.max(end_x)
10138 };
10139
10140 while row != end_row {
10141 if above {
10142 row.0 -= 1;
10143 } else {
10144 row.0 += 1;
10145 }
10146
10147 if let Some(new_selection) = self.selections.build_columnar_selection(
10148 &display_map,
10149 row,
10150 &positions,
10151 selection.reversed,
10152 &text_layout_details,
10153 ) {
10154 state.stack.push(new_selection.id);
10155 if above {
10156 new_selections.push(new_selection);
10157 new_selections.push(selection);
10158 } else {
10159 new_selections.push(selection);
10160 new_selections.push(new_selection);
10161 }
10162
10163 continue 'outer;
10164 }
10165 }
10166 }
10167
10168 new_selections.push(selection);
10169 }
10170 } else {
10171 new_selections = selections;
10172 new_selections.retain(|s| s.id != last_added_selection);
10173 state.stack.pop();
10174 }
10175
10176 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10177 s.select(new_selections);
10178 });
10179 if state.stack.len() > 1 {
10180 self.add_selections_state = Some(state);
10181 }
10182 }
10183
10184 pub fn select_next_match_internal(
10185 &mut self,
10186 display_map: &DisplaySnapshot,
10187 replace_newest: bool,
10188 autoscroll: Option<Autoscroll>,
10189 window: &mut Window,
10190 cx: &mut Context<Self>,
10191 ) -> Result<()> {
10192 fn select_next_match_ranges(
10193 this: &mut Editor,
10194 range: Range<usize>,
10195 replace_newest: bool,
10196 auto_scroll: Option<Autoscroll>,
10197 window: &mut Window,
10198 cx: &mut Context<Editor>,
10199 ) {
10200 this.unfold_ranges(&[range.clone()], false, true, cx);
10201 this.change_selections(auto_scroll, window, cx, |s| {
10202 if replace_newest {
10203 s.delete(s.newest_anchor().id);
10204 }
10205 s.insert_range(range.clone());
10206 });
10207 }
10208
10209 let buffer = &display_map.buffer_snapshot;
10210 let mut selections = self.selections.all::<usize>(cx);
10211 if let Some(mut select_next_state) = self.select_next_state.take() {
10212 let query = &select_next_state.query;
10213 if !select_next_state.done {
10214 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10215 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10216 let mut next_selected_range = None;
10217
10218 let bytes_after_last_selection =
10219 buffer.bytes_in_range(last_selection.end..buffer.len());
10220 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10221 let query_matches = query
10222 .stream_find_iter(bytes_after_last_selection)
10223 .map(|result| (last_selection.end, result))
10224 .chain(
10225 query
10226 .stream_find_iter(bytes_before_first_selection)
10227 .map(|result| (0, result)),
10228 );
10229
10230 for (start_offset, query_match) in query_matches {
10231 let query_match = query_match.unwrap(); // can only fail due to I/O
10232 let offset_range =
10233 start_offset + query_match.start()..start_offset + query_match.end();
10234 let display_range = offset_range.start.to_display_point(display_map)
10235 ..offset_range.end.to_display_point(display_map);
10236
10237 if !select_next_state.wordwise
10238 || (!movement::is_inside_word(display_map, display_range.start)
10239 && !movement::is_inside_word(display_map, display_range.end))
10240 {
10241 // TODO: This is n^2, because we might check all the selections
10242 if !selections
10243 .iter()
10244 .any(|selection| selection.range().overlaps(&offset_range))
10245 {
10246 next_selected_range = Some(offset_range);
10247 break;
10248 }
10249 }
10250 }
10251
10252 if let Some(next_selected_range) = next_selected_range {
10253 select_next_match_ranges(
10254 self,
10255 next_selected_range,
10256 replace_newest,
10257 autoscroll,
10258 window,
10259 cx,
10260 );
10261 } else {
10262 select_next_state.done = true;
10263 }
10264 }
10265
10266 self.select_next_state = Some(select_next_state);
10267 } else {
10268 let mut only_carets = true;
10269 let mut same_text_selected = true;
10270 let mut selected_text = None;
10271
10272 let mut selections_iter = selections.iter().peekable();
10273 while let Some(selection) = selections_iter.next() {
10274 if selection.start != selection.end {
10275 only_carets = false;
10276 }
10277
10278 if same_text_selected {
10279 if selected_text.is_none() {
10280 selected_text =
10281 Some(buffer.text_for_range(selection.range()).collect::<String>());
10282 }
10283
10284 if let Some(next_selection) = selections_iter.peek() {
10285 if next_selection.range().len() == selection.range().len() {
10286 let next_selected_text = buffer
10287 .text_for_range(next_selection.range())
10288 .collect::<String>();
10289 if Some(next_selected_text) != selected_text {
10290 same_text_selected = false;
10291 selected_text = None;
10292 }
10293 } else {
10294 same_text_selected = false;
10295 selected_text = None;
10296 }
10297 }
10298 }
10299 }
10300
10301 if only_carets {
10302 for selection in &mut selections {
10303 let word_range = movement::surrounding_word(
10304 display_map,
10305 selection.start.to_display_point(display_map),
10306 );
10307 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10308 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10309 selection.goal = SelectionGoal::None;
10310 selection.reversed = false;
10311 select_next_match_ranges(
10312 self,
10313 selection.start..selection.end,
10314 replace_newest,
10315 autoscroll,
10316 window,
10317 cx,
10318 );
10319 }
10320
10321 if selections.len() == 1 {
10322 let selection = selections
10323 .last()
10324 .expect("ensured that there's only one selection");
10325 let query = buffer
10326 .text_for_range(selection.start..selection.end)
10327 .collect::<String>();
10328 let is_empty = query.is_empty();
10329 let select_state = SelectNextState {
10330 query: AhoCorasick::new(&[query])?,
10331 wordwise: true,
10332 done: is_empty,
10333 };
10334 self.select_next_state = Some(select_state);
10335 } else {
10336 self.select_next_state = None;
10337 }
10338 } else if let Some(selected_text) = selected_text {
10339 self.select_next_state = Some(SelectNextState {
10340 query: AhoCorasick::new(&[selected_text])?,
10341 wordwise: false,
10342 done: false,
10343 });
10344 self.select_next_match_internal(
10345 display_map,
10346 replace_newest,
10347 autoscroll,
10348 window,
10349 cx,
10350 )?;
10351 }
10352 }
10353 Ok(())
10354 }
10355
10356 pub fn select_all_matches(
10357 &mut self,
10358 _action: &SelectAllMatches,
10359 window: &mut Window,
10360 cx: &mut Context<Self>,
10361 ) -> Result<()> {
10362 self.push_to_selection_history();
10363 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10364
10365 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10366 let Some(select_next_state) = self.select_next_state.as_mut() else {
10367 return Ok(());
10368 };
10369 if select_next_state.done {
10370 return Ok(());
10371 }
10372
10373 let mut new_selections = self.selections.all::<usize>(cx);
10374
10375 let buffer = &display_map.buffer_snapshot;
10376 let query_matches = select_next_state
10377 .query
10378 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10379
10380 for query_match in query_matches {
10381 let query_match = query_match.unwrap(); // can only fail due to I/O
10382 let offset_range = query_match.start()..query_match.end();
10383 let display_range = offset_range.start.to_display_point(&display_map)
10384 ..offset_range.end.to_display_point(&display_map);
10385
10386 if !select_next_state.wordwise
10387 || (!movement::is_inside_word(&display_map, display_range.start)
10388 && !movement::is_inside_word(&display_map, display_range.end))
10389 {
10390 self.selections.change_with(cx, |selections| {
10391 new_selections.push(Selection {
10392 id: selections.new_selection_id(),
10393 start: offset_range.start,
10394 end: offset_range.end,
10395 reversed: false,
10396 goal: SelectionGoal::None,
10397 });
10398 });
10399 }
10400 }
10401
10402 new_selections.sort_by_key(|selection| selection.start);
10403 let mut ix = 0;
10404 while ix + 1 < new_selections.len() {
10405 let current_selection = &new_selections[ix];
10406 let next_selection = &new_selections[ix + 1];
10407 if current_selection.range().overlaps(&next_selection.range()) {
10408 if current_selection.id < next_selection.id {
10409 new_selections.remove(ix + 1);
10410 } else {
10411 new_selections.remove(ix);
10412 }
10413 } else {
10414 ix += 1;
10415 }
10416 }
10417
10418 let reversed = self.selections.oldest::<usize>(cx).reversed;
10419
10420 for selection in new_selections.iter_mut() {
10421 selection.reversed = reversed;
10422 }
10423
10424 select_next_state.done = true;
10425 self.unfold_ranges(
10426 &new_selections
10427 .iter()
10428 .map(|selection| selection.range())
10429 .collect::<Vec<_>>(),
10430 false,
10431 false,
10432 cx,
10433 );
10434 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10435 selections.select(new_selections)
10436 });
10437
10438 Ok(())
10439 }
10440
10441 pub fn select_next(
10442 &mut self,
10443 action: &SelectNext,
10444 window: &mut Window,
10445 cx: &mut Context<Self>,
10446 ) -> Result<()> {
10447 self.push_to_selection_history();
10448 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10449 self.select_next_match_internal(
10450 &display_map,
10451 action.replace_newest,
10452 Some(Autoscroll::newest()),
10453 window,
10454 cx,
10455 )?;
10456 Ok(())
10457 }
10458
10459 pub fn select_previous(
10460 &mut self,
10461 action: &SelectPrevious,
10462 window: &mut Window,
10463 cx: &mut Context<Self>,
10464 ) -> Result<()> {
10465 self.push_to_selection_history();
10466 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10467 let buffer = &display_map.buffer_snapshot;
10468 let mut selections = self.selections.all::<usize>(cx);
10469 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10470 let query = &select_prev_state.query;
10471 if !select_prev_state.done {
10472 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10473 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10474 let mut next_selected_range = None;
10475 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10476 let bytes_before_last_selection =
10477 buffer.reversed_bytes_in_range(0..last_selection.start);
10478 let bytes_after_first_selection =
10479 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10480 let query_matches = query
10481 .stream_find_iter(bytes_before_last_selection)
10482 .map(|result| (last_selection.start, result))
10483 .chain(
10484 query
10485 .stream_find_iter(bytes_after_first_selection)
10486 .map(|result| (buffer.len(), result)),
10487 );
10488 for (end_offset, query_match) in query_matches {
10489 let query_match = query_match.unwrap(); // can only fail due to I/O
10490 let offset_range =
10491 end_offset - query_match.end()..end_offset - query_match.start();
10492 let display_range = offset_range.start.to_display_point(&display_map)
10493 ..offset_range.end.to_display_point(&display_map);
10494
10495 if !select_prev_state.wordwise
10496 || (!movement::is_inside_word(&display_map, display_range.start)
10497 && !movement::is_inside_word(&display_map, display_range.end))
10498 {
10499 next_selected_range = Some(offset_range);
10500 break;
10501 }
10502 }
10503
10504 if let Some(next_selected_range) = next_selected_range {
10505 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10506 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10507 if action.replace_newest {
10508 s.delete(s.newest_anchor().id);
10509 }
10510 s.insert_range(next_selected_range);
10511 });
10512 } else {
10513 select_prev_state.done = true;
10514 }
10515 }
10516
10517 self.select_prev_state = Some(select_prev_state);
10518 } else {
10519 let mut only_carets = true;
10520 let mut same_text_selected = true;
10521 let mut selected_text = None;
10522
10523 let mut selections_iter = selections.iter().peekable();
10524 while let Some(selection) = selections_iter.next() {
10525 if selection.start != selection.end {
10526 only_carets = false;
10527 }
10528
10529 if same_text_selected {
10530 if selected_text.is_none() {
10531 selected_text =
10532 Some(buffer.text_for_range(selection.range()).collect::<String>());
10533 }
10534
10535 if let Some(next_selection) = selections_iter.peek() {
10536 if next_selection.range().len() == selection.range().len() {
10537 let next_selected_text = buffer
10538 .text_for_range(next_selection.range())
10539 .collect::<String>();
10540 if Some(next_selected_text) != selected_text {
10541 same_text_selected = false;
10542 selected_text = None;
10543 }
10544 } else {
10545 same_text_selected = false;
10546 selected_text = None;
10547 }
10548 }
10549 }
10550 }
10551
10552 if only_carets {
10553 for selection in &mut selections {
10554 let word_range = movement::surrounding_word(
10555 &display_map,
10556 selection.start.to_display_point(&display_map),
10557 );
10558 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10559 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10560 selection.goal = SelectionGoal::None;
10561 selection.reversed = false;
10562 }
10563 if selections.len() == 1 {
10564 let selection = selections
10565 .last()
10566 .expect("ensured that there's only one selection");
10567 let query = buffer
10568 .text_for_range(selection.start..selection.end)
10569 .collect::<String>();
10570 let is_empty = query.is_empty();
10571 let select_state = SelectNextState {
10572 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10573 wordwise: true,
10574 done: is_empty,
10575 };
10576 self.select_prev_state = Some(select_state);
10577 } else {
10578 self.select_prev_state = None;
10579 }
10580
10581 self.unfold_ranges(
10582 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10583 false,
10584 true,
10585 cx,
10586 );
10587 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10588 s.select(selections);
10589 });
10590 } else if let Some(selected_text) = selected_text {
10591 self.select_prev_state = Some(SelectNextState {
10592 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10593 wordwise: false,
10594 done: false,
10595 });
10596 self.select_previous(action, window, cx)?;
10597 }
10598 }
10599 Ok(())
10600 }
10601
10602 pub fn toggle_comments(
10603 &mut self,
10604 action: &ToggleComments,
10605 window: &mut Window,
10606 cx: &mut Context<Self>,
10607 ) {
10608 if self.read_only(cx) {
10609 return;
10610 }
10611 let text_layout_details = &self.text_layout_details(window);
10612 self.transact(window, cx, |this, window, cx| {
10613 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10614 let mut edits = Vec::new();
10615 let mut selection_edit_ranges = Vec::new();
10616 let mut last_toggled_row = None;
10617 let snapshot = this.buffer.read(cx).read(cx);
10618 let empty_str: Arc<str> = Arc::default();
10619 let mut suffixes_inserted = Vec::new();
10620 let ignore_indent = action.ignore_indent;
10621
10622 fn comment_prefix_range(
10623 snapshot: &MultiBufferSnapshot,
10624 row: MultiBufferRow,
10625 comment_prefix: &str,
10626 comment_prefix_whitespace: &str,
10627 ignore_indent: bool,
10628 ) -> Range<Point> {
10629 let indent_size = if ignore_indent {
10630 0
10631 } else {
10632 snapshot.indent_size_for_line(row).len
10633 };
10634
10635 let start = Point::new(row.0, indent_size);
10636
10637 let mut line_bytes = snapshot
10638 .bytes_in_range(start..snapshot.max_point())
10639 .flatten()
10640 .copied();
10641
10642 // If this line currently begins with the line comment prefix, then record
10643 // the range containing the prefix.
10644 if line_bytes
10645 .by_ref()
10646 .take(comment_prefix.len())
10647 .eq(comment_prefix.bytes())
10648 {
10649 // Include any whitespace that matches the comment prefix.
10650 let matching_whitespace_len = line_bytes
10651 .zip(comment_prefix_whitespace.bytes())
10652 .take_while(|(a, b)| a == b)
10653 .count() as u32;
10654 let end = Point::new(
10655 start.row,
10656 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10657 );
10658 start..end
10659 } else {
10660 start..start
10661 }
10662 }
10663
10664 fn comment_suffix_range(
10665 snapshot: &MultiBufferSnapshot,
10666 row: MultiBufferRow,
10667 comment_suffix: &str,
10668 comment_suffix_has_leading_space: bool,
10669 ) -> Range<Point> {
10670 let end = Point::new(row.0, snapshot.line_len(row));
10671 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10672
10673 let mut line_end_bytes = snapshot
10674 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10675 .flatten()
10676 .copied();
10677
10678 let leading_space_len = if suffix_start_column > 0
10679 && line_end_bytes.next() == Some(b' ')
10680 && comment_suffix_has_leading_space
10681 {
10682 1
10683 } else {
10684 0
10685 };
10686
10687 // If this line currently begins with the line comment prefix, then record
10688 // the range containing the prefix.
10689 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10690 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10691 start..end
10692 } else {
10693 end..end
10694 }
10695 }
10696
10697 // TODO: Handle selections that cross excerpts
10698 for selection in &mut selections {
10699 let start_column = snapshot
10700 .indent_size_for_line(MultiBufferRow(selection.start.row))
10701 .len;
10702 let language = if let Some(language) =
10703 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10704 {
10705 language
10706 } else {
10707 continue;
10708 };
10709
10710 selection_edit_ranges.clear();
10711
10712 // If multiple selections contain a given row, avoid processing that
10713 // row more than once.
10714 let mut start_row = MultiBufferRow(selection.start.row);
10715 if last_toggled_row == Some(start_row) {
10716 start_row = start_row.next_row();
10717 }
10718 let end_row =
10719 if selection.end.row > selection.start.row && selection.end.column == 0 {
10720 MultiBufferRow(selection.end.row - 1)
10721 } else {
10722 MultiBufferRow(selection.end.row)
10723 };
10724 last_toggled_row = Some(end_row);
10725
10726 if start_row > end_row {
10727 continue;
10728 }
10729
10730 // If the language has line comments, toggle those.
10731 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10732
10733 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10734 if ignore_indent {
10735 full_comment_prefixes = full_comment_prefixes
10736 .into_iter()
10737 .map(|s| Arc::from(s.trim_end()))
10738 .collect();
10739 }
10740
10741 if !full_comment_prefixes.is_empty() {
10742 let first_prefix = full_comment_prefixes
10743 .first()
10744 .expect("prefixes is non-empty");
10745 let prefix_trimmed_lengths = full_comment_prefixes
10746 .iter()
10747 .map(|p| p.trim_end_matches(' ').len())
10748 .collect::<SmallVec<[usize; 4]>>();
10749
10750 let mut all_selection_lines_are_comments = true;
10751
10752 for row in start_row.0..=end_row.0 {
10753 let row = MultiBufferRow(row);
10754 if start_row < end_row && snapshot.is_line_blank(row) {
10755 continue;
10756 }
10757
10758 let prefix_range = full_comment_prefixes
10759 .iter()
10760 .zip(prefix_trimmed_lengths.iter().copied())
10761 .map(|(prefix, trimmed_prefix_len)| {
10762 comment_prefix_range(
10763 snapshot.deref(),
10764 row,
10765 &prefix[..trimmed_prefix_len],
10766 &prefix[trimmed_prefix_len..],
10767 ignore_indent,
10768 )
10769 })
10770 .max_by_key(|range| range.end.column - range.start.column)
10771 .expect("prefixes is non-empty");
10772
10773 if prefix_range.is_empty() {
10774 all_selection_lines_are_comments = false;
10775 }
10776
10777 selection_edit_ranges.push(prefix_range);
10778 }
10779
10780 if all_selection_lines_are_comments {
10781 edits.extend(
10782 selection_edit_ranges
10783 .iter()
10784 .cloned()
10785 .map(|range| (range, empty_str.clone())),
10786 );
10787 } else {
10788 let min_column = selection_edit_ranges
10789 .iter()
10790 .map(|range| range.start.column)
10791 .min()
10792 .unwrap_or(0);
10793 edits.extend(selection_edit_ranges.iter().map(|range| {
10794 let position = Point::new(range.start.row, min_column);
10795 (position..position, first_prefix.clone())
10796 }));
10797 }
10798 } else if let Some((full_comment_prefix, comment_suffix)) =
10799 language.block_comment_delimiters()
10800 {
10801 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10802 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10803 let prefix_range = comment_prefix_range(
10804 snapshot.deref(),
10805 start_row,
10806 comment_prefix,
10807 comment_prefix_whitespace,
10808 ignore_indent,
10809 );
10810 let suffix_range = comment_suffix_range(
10811 snapshot.deref(),
10812 end_row,
10813 comment_suffix.trim_start_matches(' '),
10814 comment_suffix.starts_with(' '),
10815 );
10816
10817 if prefix_range.is_empty() || suffix_range.is_empty() {
10818 edits.push((
10819 prefix_range.start..prefix_range.start,
10820 full_comment_prefix.clone(),
10821 ));
10822 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10823 suffixes_inserted.push((end_row, comment_suffix.len()));
10824 } else {
10825 edits.push((prefix_range, empty_str.clone()));
10826 edits.push((suffix_range, empty_str.clone()));
10827 }
10828 } else {
10829 continue;
10830 }
10831 }
10832
10833 drop(snapshot);
10834 this.buffer.update(cx, |buffer, cx| {
10835 buffer.edit(edits, None, cx);
10836 });
10837
10838 // Adjust selections so that they end before any comment suffixes that
10839 // were inserted.
10840 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10841 let mut selections = this.selections.all::<Point>(cx);
10842 let snapshot = this.buffer.read(cx).read(cx);
10843 for selection in &mut selections {
10844 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10845 match row.cmp(&MultiBufferRow(selection.end.row)) {
10846 Ordering::Less => {
10847 suffixes_inserted.next();
10848 continue;
10849 }
10850 Ordering::Greater => break,
10851 Ordering::Equal => {
10852 if selection.end.column == snapshot.line_len(row) {
10853 if selection.is_empty() {
10854 selection.start.column -= suffix_len as u32;
10855 }
10856 selection.end.column -= suffix_len as u32;
10857 }
10858 break;
10859 }
10860 }
10861 }
10862 }
10863
10864 drop(snapshot);
10865 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10866 s.select(selections)
10867 });
10868
10869 let selections = this.selections.all::<Point>(cx);
10870 let selections_on_single_row = selections.windows(2).all(|selections| {
10871 selections[0].start.row == selections[1].start.row
10872 && selections[0].end.row == selections[1].end.row
10873 && selections[0].start.row == selections[0].end.row
10874 });
10875 let selections_selecting = selections
10876 .iter()
10877 .any(|selection| selection.start != selection.end);
10878 let advance_downwards = action.advance_downwards
10879 && selections_on_single_row
10880 && !selections_selecting
10881 && !matches!(this.mode, EditorMode::SingleLine { .. });
10882
10883 if advance_downwards {
10884 let snapshot = this.buffer.read(cx).snapshot(cx);
10885
10886 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10887 s.move_cursors_with(|display_snapshot, display_point, _| {
10888 let mut point = display_point.to_point(display_snapshot);
10889 point.row += 1;
10890 point = snapshot.clip_point(point, Bias::Left);
10891 let display_point = point.to_display_point(display_snapshot);
10892 let goal = SelectionGoal::HorizontalPosition(
10893 display_snapshot
10894 .x_for_display_point(display_point, text_layout_details)
10895 .into(),
10896 );
10897 (display_point, goal)
10898 })
10899 });
10900 }
10901 });
10902 }
10903
10904 pub fn select_enclosing_symbol(
10905 &mut self,
10906 _: &SelectEnclosingSymbol,
10907 window: &mut Window,
10908 cx: &mut Context<Self>,
10909 ) {
10910 let buffer = self.buffer.read(cx).snapshot(cx);
10911 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10912
10913 fn update_selection(
10914 selection: &Selection<usize>,
10915 buffer_snap: &MultiBufferSnapshot,
10916 ) -> Option<Selection<usize>> {
10917 let cursor = selection.head();
10918 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10919 for symbol in symbols.iter().rev() {
10920 let start = symbol.range.start.to_offset(buffer_snap);
10921 let end = symbol.range.end.to_offset(buffer_snap);
10922 let new_range = start..end;
10923 if start < selection.start || end > selection.end {
10924 return Some(Selection {
10925 id: selection.id,
10926 start: new_range.start,
10927 end: new_range.end,
10928 goal: SelectionGoal::None,
10929 reversed: selection.reversed,
10930 });
10931 }
10932 }
10933 None
10934 }
10935
10936 let mut selected_larger_symbol = false;
10937 let new_selections = old_selections
10938 .iter()
10939 .map(|selection| match update_selection(selection, &buffer) {
10940 Some(new_selection) => {
10941 if new_selection.range() != selection.range() {
10942 selected_larger_symbol = true;
10943 }
10944 new_selection
10945 }
10946 None => selection.clone(),
10947 })
10948 .collect::<Vec<_>>();
10949
10950 if selected_larger_symbol {
10951 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10952 s.select(new_selections);
10953 });
10954 }
10955 }
10956
10957 pub fn select_larger_syntax_node(
10958 &mut self,
10959 _: &SelectLargerSyntaxNode,
10960 window: &mut Window,
10961 cx: &mut Context<Self>,
10962 ) {
10963 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10964 let buffer = self.buffer.read(cx).snapshot(cx);
10965 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10966
10967 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10968 let mut selected_larger_node = false;
10969 let new_selections = old_selections
10970 .iter()
10971 .map(|selection| {
10972 let old_range = selection.start..selection.end;
10973 let mut new_range = old_range.clone();
10974 let mut new_node = None;
10975 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10976 {
10977 new_node = Some(node);
10978 new_range = match containing_range {
10979 MultiOrSingleBufferOffsetRange::Single(_) => break,
10980 MultiOrSingleBufferOffsetRange::Multi(range) => range,
10981 };
10982 if !display_map.intersects_fold(new_range.start)
10983 && !display_map.intersects_fold(new_range.end)
10984 {
10985 break;
10986 }
10987 }
10988
10989 if let Some(node) = new_node {
10990 // Log the ancestor, to support using this action as a way to explore TreeSitter
10991 // nodes. Parent and grandparent are also logged because this operation will not
10992 // visit nodes that have the same range as their parent.
10993 log::info!("Node: {node:?}");
10994 let parent = node.parent();
10995 log::info!("Parent: {parent:?}");
10996 let grandparent = parent.and_then(|x| x.parent());
10997 log::info!("Grandparent: {grandparent:?}");
10998 }
10999
11000 selected_larger_node |= new_range != old_range;
11001 Selection {
11002 id: selection.id,
11003 start: new_range.start,
11004 end: new_range.end,
11005 goal: SelectionGoal::None,
11006 reversed: selection.reversed,
11007 }
11008 })
11009 .collect::<Vec<_>>();
11010
11011 if selected_larger_node {
11012 stack.push(old_selections);
11013 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11014 s.select(new_selections);
11015 });
11016 }
11017 self.select_larger_syntax_node_stack = stack;
11018 }
11019
11020 pub fn select_smaller_syntax_node(
11021 &mut self,
11022 _: &SelectSmallerSyntaxNode,
11023 window: &mut Window,
11024 cx: &mut Context<Self>,
11025 ) {
11026 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11027 if let Some(selections) = stack.pop() {
11028 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11029 s.select(selections.to_vec());
11030 });
11031 }
11032 self.select_larger_syntax_node_stack = stack;
11033 }
11034
11035 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11036 if !EditorSettings::get_global(cx).gutter.runnables {
11037 self.clear_tasks();
11038 return Task::ready(());
11039 }
11040 let project = self.project.as_ref().map(Entity::downgrade);
11041 cx.spawn_in(window, |this, mut cx| async move {
11042 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11043 let Some(project) = project.and_then(|p| p.upgrade()) else {
11044 return;
11045 };
11046 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11047 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11048 }) else {
11049 return;
11050 };
11051
11052 let hide_runnables = project
11053 .update(&mut cx, |project, cx| {
11054 // Do not display any test indicators in non-dev server remote projects.
11055 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11056 })
11057 .unwrap_or(true);
11058 if hide_runnables {
11059 return;
11060 }
11061 let new_rows =
11062 cx.background_spawn({
11063 let snapshot = display_snapshot.clone();
11064 async move {
11065 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11066 }
11067 })
11068 .await;
11069
11070 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11071 this.update(&mut cx, |this, _| {
11072 this.clear_tasks();
11073 for (key, value) in rows {
11074 this.insert_tasks(key, value);
11075 }
11076 })
11077 .ok();
11078 })
11079 }
11080 fn fetch_runnable_ranges(
11081 snapshot: &DisplaySnapshot,
11082 range: Range<Anchor>,
11083 ) -> Vec<language::RunnableRange> {
11084 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11085 }
11086
11087 fn runnable_rows(
11088 project: Entity<Project>,
11089 snapshot: DisplaySnapshot,
11090 runnable_ranges: Vec<RunnableRange>,
11091 mut cx: AsyncWindowContext,
11092 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11093 runnable_ranges
11094 .into_iter()
11095 .filter_map(|mut runnable| {
11096 let tasks = cx
11097 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11098 .ok()?;
11099 if tasks.is_empty() {
11100 return None;
11101 }
11102
11103 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11104
11105 let row = snapshot
11106 .buffer_snapshot
11107 .buffer_line_for_row(MultiBufferRow(point.row))?
11108 .1
11109 .start
11110 .row;
11111
11112 let context_range =
11113 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11114 Some((
11115 (runnable.buffer_id, row),
11116 RunnableTasks {
11117 templates: tasks,
11118 offset: snapshot
11119 .buffer_snapshot
11120 .anchor_before(runnable.run_range.start),
11121 context_range,
11122 column: point.column,
11123 extra_variables: runnable.extra_captures,
11124 },
11125 ))
11126 })
11127 .collect()
11128 }
11129
11130 fn templates_with_tags(
11131 project: &Entity<Project>,
11132 runnable: &mut Runnable,
11133 cx: &mut App,
11134 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11135 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11136 let (worktree_id, file) = project
11137 .buffer_for_id(runnable.buffer, cx)
11138 .and_then(|buffer| buffer.read(cx).file())
11139 .map(|file| (file.worktree_id(cx), file.clone()))
11140 .unzip();
11141
11142 (
11143 project.task_store().read(cx).task_inventory().cloned(),
11144 worktree_id,
11145 file,
11146 )
11147 });
11148
11149 let tags = mem::take(&mut runnable.tags);
11150 let mut tags: Vec<_> = tags
11151 .into_iter()
11152 .flat_map(|tag| {
11153 let tag = tag.0.clone();
11154 inventory
11155 .as_ref()
11156 .into_iter()
11157 .flat_map(|inventory| {
11158 inventory.read(cx).list_tasks(
11159 file.clone(),
11160 Some(runnable.language.clone()),
11161 worktree_id,
11162 cx,
11163 )
11164 })
11165 .filter(move |(_, template)| {
11166 template.tags.iter().any(|source_tag| source_tag == &tag)
11167 })
11168 })
11169 .sorted_by_key(|(kind, _)| kind.to_owned())
11170 .collect();
11171 if let Some((leading_tag_source, _)) = tags.first() {
11172 // Strongest source wins; if we have worktree tag binding, prefer that to
11173 // global and language bindings;
11174 // if we have a global binding, prefer that to language binding.
11175 let first_mismatch = tags
11176 .iter()
11177 .position(|(tag_source, _)| tag_source != leading_tag_source);
11178 if let Some(index) = first_mismatch {
11179 tags.truncate(index);
11180 }
11181 }
11182
11183 tags
11184 }
11185
11186 pub fn move_to_enclosing_bracket(
11187 &mut self,
11188 _: &MoveToEnclosingBracket,
11189 window: &mut Window,
11190 cx: &mut Context<Self>,
11191 ) {
11192 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11193 s.move_offsets_with(|snapshot, selection| {
11194 let Some(enclosing_bracket_ranges) =
11195 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11196 else {
11197 return;
11198 };
11199
11200 let mut best_length = usize::MAX;
11201 let mut best_inside = false;
11202 let mut best_in_bracket_range = false;
11203 let mut best_destination = None;
11204 for (open, close) in enclosing_bracket_ranges {
11205 let close = close.to_inclusive();
11206 let length = close.end() - open.start;
11207 let inside = selection.start >= open.end && selection.end <= *close.start();
11208 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11209 || close.contains(&selection.head());
11210
11211 // If best is next to a bracket and current isn't, skip
11212 if !in_bracket_range && best_in_bracket_range {
11213 continue;
11214 }
11215
11216 // Prefer smaller lengths unless best is inside and current isn't
11217 if length > best_length && (best_inside || !inside) {
11218 continue;
11219 }
11220
11221 best_length = length;
11222 best_inside = inside;
11223 best_in_bracket_range = in_bracket_range;
11224 best_destination = Some(
11225 if close.contains(&selection.start) && close.contains(&selection.end) {
11226 if inside {
11227 open.end
11228 } else {
11229 open.start
11230 }
11231 } else if inside {
11232 *close.start()
11233 } else {
11234 *close.end()
11235 },
11236 );
11237 }
11238
11239 if let Some(destination) = best_destination {
11240 selection.collapse_to(destination, SelectionGoal::None);
11241 }
11242 })
11243 });
11244 }
11245
11246 pub fn undo_selection(
11247 &mut self,
11248 _: &UndoSelection,
11249 window: &mut Window,
11250 cx: &mut Context<Self>,
11251 ) {
11252 self.end_selection(window, cx);
11253 self.selection_history.mode = SelectionHistoryMode::Undoing;
11254 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11255 self.change_selections(None, window, cx, |s| {
11256 s.select_anchors(entry.selections.to_vec())
11257 });
11258 self.select_next_state = entry.select_next_state;
11259 self.select_prev_state = entry.select_prev_state;
11260 self.add_selections_state = entry.add_selections_state;
11261 self.request_autoscroll(Autoscroll::newest(), cx);
11262 }
11263 self.selection_history.mode = SelectionHistoryMode::Normal;
11264 }
11265
11266 pub fn redo_selection(
11267 &mut self,
11268 _: &RedoSelection,
11269 window: &mut Window,
11270 cx: &mut Context<Self>,
11271 ) {
11272 self.end_selection(window, cx);
11273 self.selection_history.mode = SelectionHistoryMode::Redoing;
11274 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11275 self.change_selections(None, window, cx, |s| {
11276 s.select_anchors(entry.selections.to_vec())
11277 });
11278 self.select_next_state = entry.select_next_state;
11279 self.select_prev_state = entry.select_prev_state;
11280 self.add_selections_state = entry.add_selections_state;
11281 self.request_autoscroll(Autoscroll::newest(), cx);
11282 }
11283 self.selection_history.mode = SelectionHistoryMode::Normal;
11284 }
11285
11286 pub fn expand_excerpts(
11287 &mut self,
11288 action: &ExpandExcerpts,
11289 _: &mut Window,
11290 cx: &mut Context<Self>,
11291 ) {
11292 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11293 }
11294
11295 pub fn expand_excerpts_down(
11296 &mut self,
11297 action: &ExpandExcerptsDown,
11298 _: &mut Window,
11299 cx: &mut Context<Self>,
11300 ) {
11301 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11302 }
11303
11304 pub fn expand_excerpts_up(
11305 &mut self,
11306 action: &ExpandExcerptsUp,
11307 _: &mut Window,
11308 cx: &mut Context<Self>,
11309 ) {
11310 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11311 }
11312
11313 pub fn expand_excerpts_for_direction(
11314 &mut self,
11315 lines: u32,
11316 direction: ExpandExcerptDirection,
11317
11318 cx: &mut Context<Self>,
11319 ) {
11320 let selections = self.selections.disjoint_anchors();
11321
11322 let lines = if lines == 0 {
11323 EditorSettings::get_global(cx).expand_excerpt_lines
11324 } else {
11325 lines
11326 };
11327
11328 self.buffer.update(cx, |buffer, cx| {
11329 let snapshot = buffer.snapshot(cx);
11330 let mut excerpt_ids = selections
11331 .iter()
11332 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11333 .collect::<Vec<_>>();
11334 excerpt_ids.sort();
11335 excerpt_ids.dedup();
11336 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11337 })
11338 }
11339
11340 pub fn expand_excerpt(
11341 &mut self,
11342 excerpt: ExcerptId,
11343 direction: ExpandExcerptDirection,
11344 cx: &mut Context<Self>,
11345 ) {
11346 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11347 self.buffer.update(cx, |buffer, cx| {
11348 buffer.expand_excerpts([excerpt], lines, direction, cx)
11349 })
11350 }
11351
11352 pub fn go_to_singleton_buffer_point(
11353 &mut self,
11354 point: Point,
11355 window: &mut Window,
11356 cx: &mut Context<Self>,
11357 ) {
11358 self.go_to_singleton_buffer_range(point..point, window, cx);
11359 }
11360
11361 pub fn go_to_singleton_buffer_range(
11362 &mut self,
11363 range: Range<Point>,
11364 window: &mut Window,
11365 cx: &mut Context<Self>,
11366 ) {
11367 let multibuffer = self.buffer().read(cx);
11368 let Some(buffer) = multibuffer.as_singleton() else {
11369 return;
11370 };
11371 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11372 return;
11373 };
11374 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11375 return;
11376 };
11377 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11378 s.select_anchor_ranges([start..end])
11379 });
11380 }
11381
11382 fn go_to_diagnostic(
11383 &mut self,
11384 _: &GoToDiagnostic,
11385 window: &mut Window,
11386 cx: &mut Context<Self>,
11387 ) {
11388 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11389 }
11390
11391 fn go_to_prev_diagnostic(
11392 &mut self,
11393 _: &GoToPreviousDiagnostic,
11394 window: &mut Window,
11395 cx: &mut Context<Self>,
11396 ) {
11397 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11398 }
11399
11400 pub fn go_to_diagnostic_impl(
11401 &mut self,
11402 direction: Direction,
11403 window: &mut Window,
11404 cx: &mut Context<Self>,
11405 ) {
11406 let buffer = self.buffer.read(cx).snapshot(cx);
11407 let selection = self.selections.newest::<usize>(cx);
11408
11409 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11410 if direction == Direction::Next {
11411 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11412 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11413 return;
11414 };
11415 self.activate_diagnostics(
11416 buffer_id,
11417 popover.local_diagnostic.diagnostic.group_id,
11418 window,
11419 cx,
11420 );
11421 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11422 let primary_range_start = active_diagnostics.primary_range.start;
11423 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11424 let mut new_selection = s.newest_anchor().clone();
11425 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11426 s.select_anchors(vec![new_selection.clone()]);
11427 });
11428 self.refresh_inline_completion(false, true, window, cx);
11429 }
11430 return;
11431 }
11432 }
11433
11434 let active_group_id = self
11435 .active_diagnostics
11436 .as_ref()
11437 .map(|active_group| active_group.group_id);
11438 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11439 active_diagnostics
11440 .primary_range
11441 .to_offset(&buffer)
11442 .to_inclusive()
11443 });
11444 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11445 if active_primary_range.contains(&selection.head()) {
11446 *active_primary_range.start()
11447 } else {
11448 selection.head()
11449 }
11450 } else {
11451 selection.head()
11452 };
11453
11454 let snapshot = self.snapshot(window, cx);
11455 let primary_diagnostics_before = buffer
11456 .diagnostics_in_range::<usize>(0..search_start)
11457 .filter(|entry| entry.diagnostic.is_primary)
11458 .filter(|entry| entry.range.start != entry.range.end)
11459 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11460 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11461 .collect::<Vec<_>>();
11462 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11463 primary_diagnostics_before
11464 .iter()
11465 .position(|entry| entry.diagnostic.group_id == active_group_id)
11466 });
11467
11468 let primary_diagnostics_after = buffer
11469 .diagnostics_in_range::<usize>(search_start..buffer.len())
11470 .filter(|entry| entry.diagnostic.is_primary)
11471 .filter(|entry| entry.range.start != entry.range.end)
11472 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11473 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11474 .collect::<Vec<_>>();
11475 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11476 primary_diagnostics_after
11477 .iter()
11478 .enumerate()
11479 .rev()
11480 .find_map(|(i, entry)| {
11481 if entry.diagnostic.group_id == active_group_id {
11482 Some(i)
11483 } else {
11484 None
11485 }
11486 })
11487 });
11488
11489 let next_primary_diagnostic = match direction {
11490 Direction::Prev => primary_diagnostics_before
11491 .iter()
11492 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11493 .rev()
11494 .next(),
11495 Direction::Next => primary_diagnostics_after
11496 .iter()
11497 .skip(
11498 last_same_group_diagnostic_after
11499 .map(|index| index + 1)
11500 .unwrap_or(0),
11501 )
11502 .next(),
11503 };
11504
11505 // Cycle around to the start of the buffer, potentially moving back to the start of
11506 // the currently active diagnostic.
11507 let cycle_around = || match direction {
11508 Direction::Prev => primary_diagnostics_after
11509 .iter()
11510 .rev()
11511 .chain(primary_diagnostics_before.iter().rev())
11512 .next(),
11513 Direction::Next => primary_diagnostics_before
11514 .iter()
11515 .chain(primary_diagnostics_after.iter())
11516 .next(),
11517 };
11518
11519 if let Some((primary_range, group_id)) = next_primary_diagnostic
11520 .or_else(cycle_around)
11521 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11522 {
11523 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11524 return;
11525 };
11526 self.activate_diagnostics(buffer_id, group_id, window, cx);
11527 if self.active_diagnostics.is_some() {
11528 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11529 s.select(vec![Selection {
11530 id: selection.id,
11531 start: primary_range.start,
11532 end: primary_range.start,
11533 reversed: false,
11534 goal: SelectionGoal::None,
11535 }]);
11536 });
11537 self.refresh_inline_completion(false, true, window, cx);
11538 }
11539 }
11540 }
11541
11542 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11543 let snapshot = self.snapshot(window, cx);
11544 let selection = self.selections.newest::<Point>(cx);
11545 self.go_to_hunk_after_or_before_position(
11546 &snapshot,
11547 selection.head(),
11548 Direction::Next,
11549 window,
11550 cx,
11551 );
11552 }
11553
11554 fn go_to_hunk_after_or_before_position(
11555 &mut self,
11556 snapshot: &EditorSnapshot,
11557 position: Point,
11558 direction: Direction,
11559 window: &mut Window,
11560 cx: &mut Context<Editor>,
11561 ) {
11562 let row = if direction == Direction::Next {
11563 self.hunk_after_position(snapshot, position)
11564 .map(|hunk| hunk.row_range.start)
11565 } else {
11566 self.hunk_before_position(snapshot, position)
11567 };
11568
11569 if let Some(row) = row {
11570 let destination = Point::new(row.0, 0);
11571 let autoscroll = Autoscroll::center();
11572
11573 self.unfold_ranges(&[destination..destination], false, false, cx);
11574 self.change_selections(Some(autoscroll), window, cx, |s| {
11575 s.select_ranges([destination..destination]);
11576 });
11577 }
11578 }
11579
11580 fn hunk_after_position(
11581 &mut self,
11582 snapshot: &EditorSnapshot,
11583 position: Point,
11584 ) -> Option<MultiBufferDiffHunk> {
11585 snapshot
11586 .buffer_snapshot
11587 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11588 .find(|hunk| hunk.row_range.start.0 > position.row)
11589 .or_else(|| {
11590 snapshot
11591 .buffer_snapshot
11592 .diff_hunks_in_range(Point::zero()..position)
11593 .find(|hunk| hunk.row_range.end.0 < position.row)
11594 })
11595 }
11596
11597 fn go_to_prev_hunk(
11598 &mut self,
11599 _: &GoToPreviousHunk,
11600 window: &mut Window,
11601 cx: &mut Context<Self>,
11602 ) {
11603 let snapshot = self.snapshot(window, cx);
11604 let selection = self.selections.newest::<Point>(cx);
11605 self.go_to_hunk_after_or_before_position(
11606 &snapshot,
11607 selection.head(),
11608 Direction::Prev,
11609 window,
11610 cx,
11611 );
11612 }
11613
11614 fn hunk_before_position(
11615 &mut self,
11616 snapshot: &EditorSnapshot,
11617 position: Point,
11618 ) -> Option<MultiBufferRow> {
11619 snapshot
11620 .buffer_snapshot
11621 .diff_hunk_before(position)
11622 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11623 }
11624
11625 pub fn go_to_definition(
11626 &mut self,
11627 _: &GoToDefinition,
11628 window: &mut Window,
11629 cx: &mut Context<Self>,
11630 ) -> Task<Result<Navigated>> {
11631 let definition =
11632 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11633 cx.spawn_in(window, |editor, mut cx| async move {
11634 if definition.await? == Navigated::Yes {
11635 return Ok(Navigated::Yes);
11636 }
11637 match editor.update_in(&mut cx, |editor, window, cx| {
11638 editor.find_all_references(&FindAllReferences, window, cx)
11639 })? {
11640 Some(references) => references.await,
11641 None => Ok(Navigated::No),
11642 }
11643 })
11644 }
11645
11646 pub fn go_to_declaration(
11647 &mut self,
11648 _: &GoToDeclaration,
11649 window: &mut Window,
11650 cx: &mut Context<Self>,
11651 ) -> Task<Result<Navigated>> {
11652 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11653 }
11654
11655 pub fn go_to_declaration_split(
11656 &mut self,
11657 _: &GoToDeclaration,
11658 window: &mut Window,
11659 cx: &mut Context<Self>,
11660 ) -> Task<Result<Navigated>> {
11661 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11662 }
11663
11664 pub fn go_to_implementation(
11665 &mut self,
11666 _: &GoToImplementation,
11667 window: &mut Window,
11668 cx: &mut Context<Self>,
11669 ) -> Task<Result<Navigated>> {
11670 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11671 }
11672
11673 pub fn go_to_implementation_split(
11674 &mut self,
11675 _: &GoToImplementationSplit,
11676 window: &mut Window,
11677 cx: &mut Context<Self>,
11678 ) -> Task<Result<Navigated>> {
11679 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11680 }
11681
11682 pub fn go_to_type_definition(
11683 &mut self,
11684 _: &GoToTypeDefinition,
11685 window: &mut Window,
11686 cx: &mut Context<Self>,
11687 ) -> Task<Result<Navigated>> {
11688 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11689 }
11690
11691 pub fn go_to_definition_split(
11692 &mut self,
11693 _: &GoToDefinitionSplit,
11694 window: &mut Window,
11695 cx: &mut Context<Self>,
11696 ) -> Task<Result<Navigated>> {
11697 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11698 }
11699
11700 pub fn go_to_type_definition_split(
11701 &mut self,
11702 _: &GoToTypeDefinitionSplit,
11703 window: &mut Window,
11704 cx: &mut Context<Self>,
11705 ) -> Task<Result<Navigated>> {
11706 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11707 }
11708
11709 fn go_to_definition_of_kind(
11710 &mut self,
11711 kind: GotoDefinitionKind,
11712 split: bool,
11713 window: &mut Window,
11714 cx: &mut Context<Self>,
11715 ) -> Task<Result<Navigated>> {
11716 let Some(provider) = self.semantics_provider.clone() else {
11717 return Task::ready(Ok(Navigated::No));
11718 };
11719 let head = self.selections.newest::<usize>(cx).head();
11720 let buffer = self.buffer.read(cx);
11721 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11722 text_anchor
11723 } else {
11724 return Task::ready(Ok(Navigated::No));
11725 };
11726
11727 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11728 return Task::ready(Ok(Navigated::No));
11729 };
11730
11731 cx.spawn_in(window, |editor, mut cx| async move {
11732 let definitions = definitions.await?;
11733 let navigated = editor
11734 .update_in(&mut cx, |editor, window, cx| {
11735 editor.navigate_to_hover_links(
11736 Some(kind),
11737 definitions
11738 .into_iter()
11739 .filter(|location| {
11740 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11741 })
11742 .map(HoverLink::Text)
11743 .collect::<Vec<_>>(),
11744 split,
11745 window,
11746 cx,
11747 )
11748 })?
11749 .await?;
11750 anyhow::Ok(navigated)
11751 })
11752 }
11753
11754 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11755 let selection = self.selections.newest_anchor();
11756 let head = selection.head();
11757 let tail = selection.tail();
11758
11759 let Some((buffer, start_position)) =
11760 self.buffer.read(cx).text_anchor_for_position(head, cx)
11761 else {
11762 return;
11763 };
11764
11765 let end_position = if head != tail {
11766 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11767 return;
11768 };
11769 Some(pos)
11770 } else {
11771 None
11772 };
11773
11774 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11775 let url = if let Some(end_pos) = end_position {
11776 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11777 } else {
11778 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11779 };
11780
11781 if let Some(url) = url {
11782 editor.update(&mut cx, |_, cx| {
11783 cx.open_url(&url);
11784 })
11785 } else {
11786 Ok(())
11787 }
11788 });
11789
11790 url_finder.detach();
11791 }
11792
11793 pub fn open_selected_filename(
11794 &mut self,
11795 _: &OpenSelectedFilename,
11796 window: &mut Window,
11797 cx: &mut Context<Self>,
11798 ) {
11799 let Some(workspace) = self.workspace() else {
11800 return;
11801 };
11802
11803 let position = self.selections.newest_anchor().head();
11804
11805 let Some((buffer, buffer_position)) =
11806 self.buffer.read(cx).text_anchor_for_position(position, cx)
11807 else {
11808 return;
11809 };
11810
11811 let project = self.project.clone();
11812
11813 cx.spawn_in(window, |_, mut cx| async move {
11814 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11815
11816 if let Some((_, path)) = result {
11817 workspace
11818 .update_in(&mut cx, |workspace, window, cx| {
11819 workspace.open_resolved_path(path, window, cx)
11820 })?
11821 .await?;
11822 }
11823 anyhow::Ok(())
11824 })
11825 .detach();
11826 }
11827
11828 pub(crate) fn navigate_to_hover_links(
11829 &mut self,
11830 kind: Option<GotoDefinitionKind>,
11831 mut definitions: Vec<HoverLink>,
11832 split: bool,
11833 window: &mut Window,
11834 cx: &mut Context<Editor>,
11835 ) -> Task<Result<Navigated>> {
11836 // If there is one definition, just open it directly
11837 if definitions.len() == 1 {
11838 let definition = definitions.pop().unwrap();
11839
11840 enum TargetTaskResult {
11841 Location(Option<Location>),
11842 AlreadyNavigated,
11843 }
11844
11845 let target_task = match definition {
11846 HoverLink::Text(link) => {
11847 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11848 }
11849 HoverLink::InlayHint(lsp_location, server_id) => {
11850 let computation =
11851 self.compute_target_location(lsp_location, server_id, window, cx);
11852 cx.background_spawn(async move {
11853 let location = computation.await?;
11854 Ok(TargetTaskResult::Location(location))
11855 })
11856 }
11857 HoverLink::Url(url) => {
11858 cx.open_url(&url);
11859 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11860 }
11861 HoverLink::File(path) => {
11862 if let Some(workspace) = self.workspace() {
11863 cx.spawn_in(window, |_, mut cx| async move {
11864 workspace
11865 .update_in(&mut cx, |workspace, window, cx| {
11866 workspace.open_resolved_path(path, window, cx)
11867 })?
11868 .await
11869 .map(|_| TargetTaskResult::AlreadyNavigated)
11870 })
11871 } else {
11872 Task::ready(Ok(TargetTaskResult::Location(None)))
11873 }
11874 }
11875 };
11876 cx.spawn_in(window, |editor, mut cx| async move {
11877 let target = match target_task.await.context("target resolution task")? {
11878 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11879 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11880 TargetTaskResult::Location(Some(target)) => target,
11881 };
11882
11883 editor.update_in(&mut cx, |editor, window, cx| {
11884 let Some(workspace) = editor.workspace() else {
11885 return Navigated::No;
11886 };
11887 let pane = workspace.read(cx).active_pane().clone();
11888
11889 let range = target.range.to_point(target.buffer.read(cx));
11890 let range = editor.range_for_match(&range);
11891 let range = collapse_multiline_range(range);
11892
11893 if !split
11894 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11895 {
11896 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11897 } else {
11898 window.defer(cx, move |window, cx| {
11899 let target_editor: Entity<Self> =
11900 workspace.update(cx, |workspace, cx| {
11901 let pane = if split {
11902 workspace.adjacent_pane(window, cx)
11903 } else {
11904 workspace.active_pane().clone()
11905 };
11906
11907 workspace.open_project_item(
11908 pane,
11909 target.buffer.clone(),
11910 true,
11911 true,
11912 window,
11913 cx,
11914 )
11915 });
11916 target_editor.update(cx, |target_editor, cx| {
11917 // When selecting a definition in a different buffer, disable the nav history
11918 // to avoid creating a history entry at the previous cursor location.
11919 pane.update(cx, |pane, _| pane.disable_history());
11920 target_editor.go_to_singleton_buffer_range(range, window, cx);
11921 pane.update(cx, |pane, _| pane.enable_history());
11922 });
11923 });
11924 }
11925 Navigated::Yes
11926 })
11927 })
11928 } else if !definitions.is_empty() {
11929 cx.spawn_in(window, |editor, mut cx| async move {
11930 let (title, location_tasks, workspace) = editor
11931 .update_in(&mut cx, |editor, window, cx| {
11932 let tab_kind = match kind {
11933 Some(GotoDefinitionKind::Implementation) => "Implementations",
11934 _ => "Definitions",
11935 };
11936 let title = definitions
11937 .iter()
11938 .find_map(|definition| match definition {
11939 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11940 let buffer = origin.buffer.read(cx);
11941 format!(
11942 "{} for {}",
11943 tab_kind,
11944 buffer
11945 .text_for_range(origin.range.clone())
11946 .collect::<String>()
11947 )
11948 }),
11949 HoverLink::InlayHint(_, _) => None,
11950 HoverLink::Url(_) => None,
11951 HoverLink::File(_) => None,
11952 })
11953 .unwrap_or(tab_kind.to_string());
11954 let location_tasks = definitions
11955 .into_iter()
11956 .map(|definition| match definition {
11957 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11958 HoverLink::InlayHint(lsp_location, server_id) => editor
11959 .compute_target_location(lsp_location, server_id, window, cx),
11960 HoverLink::Url(_) => Task::ready(Ok(None)),
11961 HoverLink::File(_) => Task::ready(Ok(None)),
11962 })
11963 .collect::<Vec<_>>();
11964 (title, location_tasks, editor.workspace().clone())
11965 })
11966 .context("location tasks preparation")?;
11967
11968 let locations = future::join_all(location_tasks)
11969 .await
11970 .into_iter()
11971 .filter_map(|location| location.transpose())
11972 .collect::<Result<_>>()
11973 .context("location tasks")?;
11974
11975 let Some(workspace) = workspace else {
11976 return Ok(Navigated::No);
11977 };
11978 let opened = workspace
11979 .update_in(&mut cx, |workspace, window, cx| {
11980 Self::open_locations_in_multibuffer(
11981 workspace,
11982 locations,
11983 title,
11984 split,
11985 MultibufferSelectionMode::First,
11986 window,
11987 cx,
11988 )
11989 })
11990 .ok();
11991
11992 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11993 })
11994 } else {
11995 Task::ready(Ok(Navigated::No))
11996 }
11997 }
11998
11999 fn compute_target_location(
12000 &self,
12001 lsp_location: lsp::Location,
12002 server_id: LanguageServerId,
12003 window: &mut Window,
12004 cx: &mut Context<Self>,
12005 ) -> Task<anyhow::Result<Option<Location>>> {
12006 let Some(project) = self.project.clone() else {
12007 return Task::ready(Ok(None));
12008 };
12009
12010 cx.spawn_in(window, move |editor, mut cx| async move {
12011 let location_task = editor.update(&mut cx, |_, cx| {
12012 project.update(cx, |project, cx| {
12013 let language_server_name = project
12014 .language_server_statuses(cx)
12015 .find(|(id, _)| server_id == *id)
12016 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12017 language_server_name.map(|language_server_name| {
12018 project.open_local_buffer_via_lsp(
12019 lsp_location.uri.clone(),
12020 server_id,
12021 language_server_name,
12022 cx,
12023 )
12024 })
12025 })
12026 })?;
12027 let location = match location_task {
12028 Some(task) => Some({
12029 let target_buffer_handle = task.await.context("open local buffer")?;
12030 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12031 let target_start = target_buffer
12032 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12033 let target_end = target_buffer
12034 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12035 target_buffer.anchor_after(target_start)
12036 ..target_buffer.anchor_before(target_end)
12037 })?;
12038 Location {
12039 buffer: target_buffer_handle,
12040 range,
12041 }
12042 }),
12043 None => None,
12044 };
12045 Ok(location)
12046 })
12047 }
12048
12049 pub fn find_all_references(
12050 &mut self,
12051 _: &FindAllReferences,
12052 window: &mut Window,
12053 cx: &mut Context<Self>,
12054 ) -> Option<Task<Result<Navigated>>> {
12055 let selection = self.selections.newest::<usize>(cx);
12056 let multi_buffer = self.buffer.read(cx);
12057 let head = selection.head();
12058
12059 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12060 let head_anchor = multi_buffer_snapshot.anchor_at(
12061 head,
12062 if head < selection.tail() {
12063 Bias::Right
12064 } else {
12065 Bias::Left
12066 },
12067 );
12068
12069 match self
12070 .find_all_references_task_sources
12071 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12072 {
12073 Ok(_) => {
12074 log::info!(
12075 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12076 );
12077 return None;
12078 }
12079 Err(i) => {
12080 self.find_all_references_task_sources.insert(i, head_anchor);
12081 }
12082 }
12083
12084 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12085 let workspace = self.workspace()?;
12086 let project = workspace.read(cx).project().clone();
12087 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12088 Some(cx.spawn_in(window, |editor, mut cx| async move {
12089 let _cleanup = defer({
12090 let mut cx = cx.clone();
12091 move || {
12092 let _ = editor.update(&mut cx, |editor, _| {
12093 if let Ok(i) =
12094 editor
12095 .find_all_references_task_sources
12096 .binary_search_by(|anchor| {
12097 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12098 })
12099 {
12100 editor.find_all_references_task_sources.remove(i);
12101 }
12102 });
12103 }
12104 });
12105
12106 let locations = references.await?;
12107 if locations.is_empty() {
12108 return anyhow::Ok(Navigated::No);
12109 }
12110
12111 workspace.update_in(&mut cx, |workspace, window, cx| {
12112 let title = locations
12113 .first()
12114 .as_ref()
12115 .map(|location| {
12116 let buffer = location.buffer.read(cx);
12117 format!(
12118 "References to `{}`",
12119 buffer
12120 .text_for_range(location.range.clone())
12121 .collect::<String>()
12122 )
12123 })
12124 .unwrap();
12125 Self::open_locations_in_multibuffer(
12126 workspace,
12127 locations,
12128 title,
12129 false,
12130 MultibufferSelectionMode::First,
12131 window,
12132 cx,
12133 );
12134 Navigated::Yes
12135 })
12136 }))
12137 }
12138
12139 /// Opens a multibuffer with the given project locations in it
12140 pub fn open_locations_in_multibuffer(
12141 workspace: &mut Workspace,
12142 mut locations: Vec<Location>,
12143 title: String,
12144 split: bool,
12145 multibuffer_selection_mode: MultibufferSelectionMode,
12146 window: &mut Window,
12147 cx: &mut Context<Workspace>,
12148 ) {
12149 // If there are multiple definitions, open them in a multibuffer
12150 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12151 let mut locations = locations.into_iter().peekable();
12152 let mut ranges = Vec::new();
12153 let capability = workspace.project().read(cx).capability();
12154
12155 let excerpt_buffer = cx.new(|cx| {
12156 let mut multibuffer = MultiBuffer::new(capability);
12157 while let Some(location) = locations.next() {
12158 let buffer = location.buffer.read(cx);
12159 let mut ranges_for_buffer = Vec::new();
12160 let range = location.range.to_offset(buffer);
12161 ranges_for_buffer.push(range.clone());
12162
12163 while let Some(next_location) = locations.peek() {
12164 if next_location.buffer == location.buffer {
12165 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12166 locations.next();
12167 } else {
12168 break;
12169 }
12170 }
12171
12172 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12173 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12174 location.buffer.clone(),
12175 ranges_for_buffer,
12176 DEFAULT_MULTIBUFFER_CONTEXT,
12177 cx,
12178 ))
12179 }
12180
12181 multibuffer.with_title(title)
12182 });
12183
12184 let editor = cx.new(|cx| {
12185 Editor::for_multibuffer(
12186 excerpt_buffer,
12187 Some(workspace.project().clone()),
12188 true,
12189 window,
12190 cx,
12191 )
12192 });
12193 editor.update(cx, |editor, cx| {
12194 match multibuffer_selection_mode {
12195 MultibufferSelectionMode::First => {
12196 if let Some(first_range) = ranges.first() {
12197 editor.change_selections(None, window, cx, |selections| {
12198 selections.clear_disjoint();
12199 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12200 });
12201 }
12202 editor.highlight_background::<Self>(
12203 &ranges,
12204 |theme| theme.editor_highlighted_line_background,
12205 cx,
12206 );
12207 }
12208 MultibufferSelectionMode::All => {
12209 editor.change_selections(None, window, cx, |selections| {
12210 selections.clear_disjoint();
12211 selections.select_anchor_ranges(ranges);
12212 });
12213 }
12214 }
12215 editor.register_buffers_with_language_servers(cx);
12216 });
12217
12218 let item = Box::new(editor);
12219 let item_id = item.item_id();
12220
12221 if split {
12222 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12223 } else {
12224 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12225 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12226 pane.close_current_preview_item(window, cx)
12227 } else {
12228 None
12229 }
12230 });
12231 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12232 }
12233 workspace.active_pane().update(cx, |pane, cx| {
12234 pane.set_preview_item_id(Some(item_id), cx);
12235 });
12236 }
12237
12238 pub fn rename(
12239 &mut self,
12240 _: &Rename,
12241 window: &mut Window,
12242 cx: &mut Context<Self>,
12243 ) -> Option<Task<Result<()>>> {
12244 use language::ToOffset as _;
12245
12246 let provider = self.semantics_provider.clone()?;
12247 let selection = self.selections.newest_anchor().clone();
12248 let (cursor_buffer, cursor_buffer_position) = self
12249 .buffer
12250 .read(cx)
12251 .text_anchor_for_position(selection.head(), cx)?;
12252 let (tail_buffer, cursor_buffer_position_end) = self
12253 .buffer
12254 .read(cx)
12255 .text_anchor_for_position(selection.tail(), cx)?;
12256 if tail_buffer != cursor_buffer {
12257 return None;
12258 }
12259
12260 let snapshot = cursor_buffer.read(cx).snapshot();
12261 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12262 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12263 let prepare_rename = provider
12264 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12265 .unwrap_or_else(|| Task::ready(Ok(None)));
12266 drop(snapshot);
12267
12268 Some(cx.spawn_in(window, |this, mut cx| async move {
12269 let rename_range = if let Some(range) = prepare_rename.await? {
12270 Some(range)
12271 } else {
12272 this.update(&mut cx, |this, cx| {
12273 let buffer = this.buffer.read(cx).snapshot(cx);
12274 let mut buffer_highlights = this
12275 .document_highlights_for_position(selection.head(), &buffer)
12276 .filter(|highlight| {
12277 highlight.start.excerpt_id == selection.head().excerpt_id
12278 && highlight.end.excerpt_id == selection.head().excerpt_id
12279 });
12280 buffer_highlights
12281 .next()
12282 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12283 })?
12284 };
12285 if let Some(rename_range) = rename_range {
12286 this.update_in(&mut cx, |this, window, cx| {
12287 let snapshot = cursor_buffer.read(cx).snapshot();
12288 let rename_buffer_range = rename_range.to_offset(&snapshot);
12289 let cursor_offset_in_rename_range =
12290 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12291 let cursor_offset_in_rename_range_end =
12292 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12293
12294 this.take_rename(false, window, cx);
12295 let buffer = this.buffer.read(cx).read(cx);
12296 let cursor_offset = selection.head().to_offset(&buffer);
12297 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12298 let rename_end = rename_start + rename_buffer_range.len();
12299 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12300 let mut old_highlight_id = None;
12301 let old_name: Arc<str> = buffer
12302 .chunks(rename_start..rename_end, true)
12303 .map(|chunk| {
12304 if old_highlight_id.is_none() {
12305 old_highlight_id = chunk.syntax_highlight_id;
12306 }
12307 chunk.text
12308 })
12309 .collect::<String>()
12310 .into();
12311
12312 drop(buffer);
12313
12314 // Position the selection in the rename editor so that it matches the current selection.
12315 this.show_local_selections = false;
12316 let rename_editor = cx.new(|cx| {
12317 let mut editor = Editor::single_line(window, cx);
12318 editor.buffer.update(cx, |buffer, cx| {
12319 buffer.edit([(0..0, old_name.clone())], None, cx)
12320 });
12321 let rename_selection_range = match cursor_offset_in_rename_range
12322 .cmp(&cursor_offset_in_rename_range_end)
12323 {
12324 Ordering::Equal => {
12325 editor.select_all(&SelectAll, window, cx);
12326 return editor;
12327 }
12328 Ordering::Less => {
12329 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12330 }
12331 Ordering::Greater => {
12332 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12333 }
12334 };
12335 if rename_selection_range.end > old_name.len() {
12336 editor.select_all(&SelectAll, window, cx);
12337 } else {
12338 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12339 s.select_ranges([rename_selection_range]);
12340 });
12341 }
12342 editor
12343 });
12344 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12345 if e == &EditorEvent::Focused {
12346 cx.emit(EditorEvent::FocusedIn)
12347 }
12348 })
12349 .detach();
12350
12351 let write_highlights =
12352 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12353 let read_highlights =
12354 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12355 let ranges = write_highlights
12356 .iter()
12357 .flat_map(|(_, ranges)| ranges.iter())
12358 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12359 .cloned()
12360 .collect();
12361
12362 this.highlight_text::<Rename>(
12363 ranges,
12364 HighlightStyle {
12365 fade_out: Some(0.6),
12366 ..Default::default()
12367 },
12368 cx,
12369 );
12370 let rename_focus_handle = rename_editor.focus_handle(cx);
12371 window.focus(&rename_focus_handle);
12372 let block_id = this.insert_blocks(
12373 [BlockProperties {
12374 style: BlockStyle::Flex,
12375 placement: BlockPlacement::Below(range.start),
12376 height: 1,
12377 render: Arc::new({
12378 let rename_editor = rename_editor.clone();
12379 move |cx: &mut BlockContext| {
12380 let mut text_style = cx.editor_style.text.clone();
12381 if let Some(highlight_style) = old_highlight_id
12382 .and_then(|h| h.style(&cx.editor_style.syntax))
12383 {
12384 text_style = text_style.highlight(highlight_style);
12385 }
12386 div()
12387 .block_mouse_down()
12388 .pl(cx.anchor_x)
12389 .child(EditorElement::new(
12390 &rename_editor,
12391 EditorStyle {
12392 background: cx.theme().system().transparent,
12393 local_player: cx.editor_style.local_player,
12394 text: text_style,
12395 scrollbar_width: cx.editor_style.scrollbar_width,
12396 syntax: cx.editor_style.syntax.clone(),
12397 status: cx.editor_style.status.clone(),
12398 inlay_hints_style: HighlightStyle {
12399 font_weight: Some(FontWeight::BOLD),
12400 ..make_inlay_hints_style(cx.app)
12401 },
12402 inline_completion_styles: make_suggestion_styles(
12403 cx.app,
12404 ),
12405 ..EditorStyle::default()
12406 },
12407 ))
12408 .into_any_element()
12409 }
12410 }),
12411 priority: 0,
12412 }],
12413 Some(Autoscroll::fit()),
12414 cx,
12415 )[0];
12416 this.pending_rename = Some(RenameState {
12417 range,
12418 old_name,
12419 editor: rename_editor,
12420 block_id,
12421 });
12422 })?;
12423 }
12424
12425 Ok(())
12426 }))
12427 }
12428
12429 pub fn confirm_rename(
12430 &mut self,
12431 _: &ConfirmRename,
12432 window: &mut Window,
12433 cx: &mut Context<Self>,
12434 ) -> Option<Task<Result<()>>> {
12435 let rename = self.take_rename(false, window, cx)?;
12436 let workspace = self.workspace()?.downgrade();
12437 let (buffer, start) = self
12438 .buffer
12439 .read(cx)
12440 .text_anchor_for_position(rename.range.start, cx)?;
12441 let (end_buffer, _) = self
12442 .buffer
12443 .read(cx)
12444 .text_anchor_for_position(rename.range.end, cx)?;
12445 if buffer != end_buffer {
12446 return None;
12447 }
12448
12449 let old_name = rename.old_name;
12450 let new_name = rename.editor.read(cx).text(cx);
12451
12452 let rename = self.semantics_provider.as_ref()?.perform_rename(
12453 &buffer,
12454 start,
12455 new_name.clone(),
12456 cx,
12457 )?;
12458
12459 Some(cx.spawn_in(window, |editor, mut cx| async move {
12460 let project_transaction = rename.await?;
12461 Self::open_project_transaction(
12462 &editor,
12463 workspace,
12464 project_transaction,
12465 format!("Rename: {} → {}", old_name, new_name),
12466 cx.clone(),
12467 )
12468 .await?;
12469
12470 editor.update(&mut cx, |editor, cx| {
12471 editor.refresh_document_highlights(cx);
12472 })?;
12473 Ok(())
12474 }))
12475 }
12476
12477 fn take_rename(
12478 &mut self,
12479 moving_cursor: bool,
12480 window: &mut Window,
12481 cx: &mut Context<Self>,
12482 ) -> Option<RenameState> {
12483 let rename = self.pending_rename.take()?;
12484 if rename.editor.focus_handle(cx).is_focused(window) {
12485 window.focus(&self.focus_handle);
12486 }
12487
12488 self.remove_blocks(
12489 [rename.block_id].into_iter().collect(),
12490 Some(Autoscroll::fit()),
12491 cx,
12492 );
12493 self.clear_highlights::<Rename>(cx);
12494 self.show_local_selections = true;
12495
12496 if moving_cursor {
12497 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12498 editor.selections.newest::<usize>(cx).head()
12499 });
12500
12501 // Update the selection to match the position of the selection inside
12502 // the rename editor.
12503 let snapshot = self.buffer.read(cx).read(cx);
12504 let rename_range = rename.range.to_offset(&snapshot);
12505 let cursor_in_editor = snapshot
12506 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12507 .min(rename_range.end);
12508 drop(snapshot);
12509
12510 self.change_selections(None, window, cx, |s| {
12511 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12512 });
12513 } else {
12514 self.refresh_document_highlights(cx);
12515 }
12516
12517 Some(rename)
12518 }
12519
12520 pub fn pending_rename(&self) -> Option<&RenameState> {
12521 self.pending_rename.as_ref()
12522 }
12523
12524 fn format(
12525 &mut self,
12526 _: &Format,
12527 window: &mut Window,
12528 cx: &mut Context<Self>,
12529 ) -> Option<Task<Result<()>>> {
12530 let project = match &self.project {
12531 Some(project) => project.clone(),
12532 None => return None,
12533 };
12534
12535 Some(self.perform_format(
12536 project,
12537 FormatTrigger::Manual,
12538 FormatTarget::Buffers,
12539 window,
12540 cx,
12541 ))
12542 }
12543
12544 fn format_selections(
12545 &mut self,
12546 _: &FormatSelections,
12547 window: &mut Window,
12548 cx: &mut Context<Self>,
12549 ) -> Option<Task<Result<()>>> {
12550 let project = match &self.project {
12551 Some(project) => project.clone(),
12552 None => return None,
12553 };
12554
12555 let ranges = self
12556 .selections
12557 .all_adjusted(cx)
12558 .into_iter()
12559 .map(|selection| selection.range())
12560 .collect_vec();
12561
12562 Some(self.perform_format(
12563 project,
12564 FormatTrigger::Manual,
12565 FormatTarget::Ranges(ranges),
12566 window,
12567 cx,
12568 ))
12569 }
12570
12571 fn perform_format(
12572 &mut self,
12573 project: Entity<Project>,
12574 trigger: FormatTrigger,
12575 target: FormatTarget,
12576 window: &mut Window,
12577 cx: &mut Context<Self>,
12578 ) -> Task<Result<()>> {
12579 let buffer = self.buffer.clone();
12580 let (buffers, target) = match target {
12581 FormatTarget::Buffers => {
12582 let mut buffers = buffer.read(cx).all_buffers();
12583 if trigger == FormatTrigger::Save {
12584 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12585 }
12586 (buffers, LspFormatTarget::Buffers)
12587 }
12588 FormatTarget::Ranges(selection_ranges) => {
12589 let multi_buffer = buffer.read(cx);
12590 let snapshot = multi_buffer.read(cx);
12591 let mut buffers = HashSet::default();
12592 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12593 BTreeMap::new();
12594 for selection_range in selection_ranges {
12595 for (buffer, buffer_range, _) in
12596 snapshot.range_to_buffer_ranges(selection_range)
12597 {
12598 let buffer_id = buffer.remote_id();
12599 let start = buffer.anchor_before(buffer_range.start);
12600 let end = buffer.anchor_after(buffer_range.end);
12601 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12602 buffer_id_to_ranges
12603 .entry(buffer_id)
12604 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12605 .or_insert_with(|| vec![start..end]);
12606 }
12607 }
12608 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12609 }
12610 };
12611
12612 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12613 let format = project.update(cx, |project, cx| {
12614 project.format(buffers, target, true, trigger, cx)
12615 });
12616
12617 cx.spawn_in(window, |_, mut cx| async move {
12618 let transaction = futures::select_biased! {
12619 () = timeout => {
12620 log::warn!("timed out waiting for formatting");
12621 None
12622 }
12623 transaction = format.log_err().fuse() => transaction,
12624 };
12625
12626 buffer
12627 .update(&mut cx, |buffer, cx| {
12628 if let Some(transaction) = transaction {
12629 if !buffer.is_singleton() {
12630 buffer.push_transaction(&transaction.0, cx);
12631 }
12632 }
12633 cx.notify();
12634 })
12635 .ok();
12636
12637 Ok(())
12638 })
12639 }
12640
12641 fn organize_imports(
12642 &mut self,
12643 _: &OrganizeImports,
12644 window: &mut Window,
12645 cx: &mut Context<Self>,
12646 ) -> Option<Task<Result<()>>> {
12647 let project = match &self.project {
12648 Some(project) => project.clone(),
12649 None => return None,
12650 };
12651 Some(self.perform_code_action_kind(
12652 project,
12653 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12654 window,
12655 cx,
12656 ))
12657 }
12658
12659 fn perform_code_action_kind(
12660 &mut self,
12661 project: Entity<Project>,
12662 kind: CodeActionKind,
12663 window: &mut Window,
12664 cx: &mut Context<Self>,
12665 ) -> Task<Result<()>> {
12666 let buffer = self.buffer.clone();
12667 let buffers = buffer.read(cx).all_buffers();
12668 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12669 let apply_action = project.update(cx, |project, cx| {
12670 project.apply_code_action_kind(buffers, kind, true, cx)
12671 });
12672 cx.spawn_in(window, |_, mut cx| async move {
12673 let transaction = futures::select_biased! {
12674 () = timeout => {
12675 log::warn!("timed out waiting for executing code action");
12676 None
12677 }
12678 transaction = apply_action.log_err().fuse() => transaction,
12679 };
12680 buffer
12681 .update(&mut cx, |buffer, cx| {
12682 // check if we need this
12683 if let Some(transaction) = transaction {
12684 if !buffer.is_singleton() {
12685 buffer.push_transaction(&transaction.0, cx);
12686 }
12687 }
12688 cx.notify();
12689 })
12690 .ok();
12691 Ok(())
12692 })
12693 }
12694
12695 fn restart_language_server(
12696 &mut self,
12697 _: &RestartLanguageServer,
12698 _: &mut Window,
12699 cx: &mut Context<Self>,
12700 ) {
12701 if let Some(project) = self.project.clone() {
12702 self.buffer.update(cx, |multi_buffer, cx| {
12703 project.update(cx, |project, cx| {
12704 project.restart_language_servers_for_buffers(
12705 multi_buffer.all_buffers().into_iter().collect(),
12706 cx,
12707 );
12708 });
12709 })
12710 }
12711 }
12712
12713 fn cancel_language_server_work(
12714 workspace: &mut Workspace,
12715 _: &actions::CancelLanguageServerWork,
12716 _: &mut Window,
12717 cx: &mut Context<Workspace>,
12718 ) {
12719 let project = workspace.project();
12720 let buffers = workspace
12721 .active_item(cx)
12722 .and_then(|item| item.act_as::<Editor>(cx))
12723 .map_or(HashSet::default(), |editor| {
12724 editor.read(cx).buffer.read(cx).all_buffers()
12725 });
12726 project.update(cx, |project, cx| {
12727 project.cancel_language_server_work_for_buffers(buffers, cx);
12728 });
12729 }
12730
12731 fn show_character_palette(
12732 &mut self,
12733 _: &ShowCharacterPalette,
12734 window: &mut Window,
12735 _: &mut Context<Self>,
12736 ) {
12737 window.show_character_palette();
12738 }
12739
12740 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12741 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12742 let buffer = self.buffer.read(cx).snapshot(cx);
12743 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12744 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12745 let is_valid = buffer
12746 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12747 .any(|entry| {
12748 entry.diagnostic.is_primary
12749 && !entry.range.is_empty()
12750 && entry.range.start == primary_range_start
12751 && entry.diagnostic.message == active_diagnostics.primary_message
12752 });
12753
12754 if is_valid != active_diagnostics.is_valid {
12755 active_diagnostics.is_valid = is_valid;
12756 if is_valid {
12757 let mut new_styles = HashMap::default();
12758 for (block_id, diagnostic) in &active_diagnostics.blocks {
12759 new_styles.insert(
12760 *block_id,
12761 diagnostic_block_renderer(diagnostic.clone(), None, true),
12762 );
12763 }
12764 self.display_map.update(cx, |display_map, _cx| {
12765 display_map.replace_blocks(new_styles);
12766 });
12767 } else {
12768 self.dismiss_diagnostics(cx);
12769 }
12770 }
12771 }
12772 }
12773
12774 fn activate_diagnostics(
12775 &mut self,
12776 buffer_id: BufferId,
12777 group_id: usize,
12778 window: &mut Window,
12779 cx: &mut Context<Self>,
12780 ) {
12781 self.dismiss_diagnostics(cx);
12782 let snapshot = self.snapshot(window, cx);
12783 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12784 let buffer = self.buffer.read(cx).snapshot(cx);
12785
12786 let mut primary_range = None;
12787 let mut primary_message = None;
12788 let diagnostic_group = buffer
12789 .diagnostic_group(buffer_id, group_id)
12790 .filter_map(|entry| {
12791 let start = entry.range.start;
12792 let end = entry.range.end;
12793 if snapshot.is_line_folded(MultiBufferRow(start.row))
12794 && (start.row == end.row
12795 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12796 {
12797 return None;
12798 }
12799 if entry.diagnostic.is_primary {
12800 primary_range = Some(entry.range.clone());
12801 primary_message = Some(entry.diagnostic.message.clone());
12802 }
12803 Some(entry)
12804 })
12805 .collect::<Vec<_>>();
12806 let primary_range = primary_range?;
12807 let primary_message = primary_message?;
12808
12809 let blocks = display_map
12810 .insert_blocks(
12811 diagnostic_group.iter().map(|entry| {
12812 let diagnostic = entry.diagnostic.clone();
12813 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12814 BlockProperties {
12815 style: BlockStyle::Fixed,
12816 placement: BlockPlacement::Below(
12817 buffer.anchor_after(entry.range.start),
12818 ),
12819 height: message_height,
12820 render: diagnostic_block_renderer(diagnostic, None, true),
12821 priority: 0,
12822 }
12823 }),
12824 cx,
12825 )
12826 .into_iter()
12827 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12828 .collect();
12829
12830 Some(ActiveDiagnosticGroup {
12831 primary_range: buffer.anchor_before(primary_range.start)
12832 ..buffer.anchor_after(primary_range.end),
12833 primary_message,
12834 group_id,
12835 blocks,
12836 is_valid: true,
12837 })
12838 });
12839 }
12840
12841 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12842 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12843 self.display_map.update(cx, |display_map, cx| {
12844 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12845 });
12846 cx.notify();
12847 }
12848 }
12849
12850 /// Disable inline diagnostics rendering for this editor.
12851 pub fn disable_inline_diagnostics(&mut self) {
12852 self.inline_diagnostics_enabled = false;
12853 self.inline_diagnostics_update = Task::ready(());
12854 self.inline_diagnostics.clear();
12855 }
12856
12857 pub fn inline_diagnostics_enabled(&self) -> bool {
12858 self.inline_diagnostics_enabled
12859 }
12860
12861 pub fn show_inline_diagnostics(&self) -> bool {
12862 self.show_inline_diagnostics
12863 }
12864
12865 pub fn toggle_inline_diagnostics(
12866 &mut self,
12867 _: &ToggleInlineDiagnostics,
12868 window: &mut Window,
12869 cx: &mut Context<'_, Editor>,
12870 ) {
12871 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12872 self.refresh_inline_diagnostics(false, window, cx);
12873 }
12874
12875 fn refresh_inline_diagnostics(
12876 &mut self,
12877 debounce: bool,
12878 window: &mut Window,
12879 cx: &mut Context<Self>,
12880 ) {
12881 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12882 self.inline_diagnostics_update = Task::ready(());
12883 self.inline_diagnostics.clear();
12884 return;
12885 }
12886
12887 let debounce_ms = ProjectSettings::get_global(cx)
12888 .diagnostics
12889 .inline
12890 .update_debounce_ms;
12891 let debounce = if debounce && debounce_ms > 0 {
12892 Some(Duration::from_millis(debounce_ms))
12893 } else {
12894 None
12895 };
12896 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12897 if let Some(debounce) = debounce {
12898 cx.background_executor().timer(debounce).await;
12899 }
12900 let Some(snapshot) = editor
12901 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12902 .ok()
12903 else {
12904 return;
12905 };
12906
12907 let new_inline_diagnostics = cx
12908 .background_spawn(async move {
12909 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12910 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12911 let message = diagnostic_entry
12912 .diagnostic
12913 .message
12914 .split_once('\n')
12915 .map(|(line, _)| line)
12916 .map(SharedString::new)
12917 .unwrap_or_else(|| {
12918 SharedString::from(diagnostic_entry.diagnostic.message)
12919 });
12920 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12921 let (Ok(i) | Err(i)) = inline_diagnostics
12922 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12923 inline_diagnostics.insert(
12924 i,
12925 (
12926 start_anchor,
12927 InlineDiagnostic {
12928 message,
12929 group_id: diagnostic_entry.diagnostic.group_id,
12930 start: diagnostic_entry.range.start.to_point(&snapshot),
12931 is_primary: diagnostic_entry.diagnostic.is_primary,
12932 severity: diagnostic_entry.diagnostic.severity,
12933 },
12934 ),
12935 );
12936 }
12937 inline_diagnostics
12938 })
12939 .await;
12940
12941 editor
12942 .update(&mut cx, |editor, cx| {
12943 editor.inline_diagnostics = new_inline_diagnostics;
12944 cx.notify();
12945 })
12946 .ok();
12947 });
12948 }
12949
12950 pub fn set_selections_from_remote(
12951 &mut self,
12952 selections: Vec<Selection<Anchor>>,
12953 pending_selection: Option<Selection<Anchor>>,
12954 window: &mut Window,
12955 cx: &mut Context<Self>,
12956 ) {
12957 let old_cursor_position = self.selections.newest_anchor().head();
12958 self.selections.change_with(cx, |s| {
12959 s.select_anchors(selections);
12960 if let Some(pending_selection) = pending_selection {
12961 s.set_pending(pending_selection, SelectMode::Character);
12962 } else {
12963 s.clear_pending();
12964 }
12965 });
12966 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12967 }
12968
12969 fn push_to_selection_history(&mut self) {
12970 self.selection_history.push(SelectionHistoryEntry {
12971 selections: self.selections.disjoint_anchors(),
12972 select_next_state: self.select_next_state.clone(),
12973 select_prev_state: self.select_prev_state.clone(),
12974 add_selections_state: self.add_selections_state.clone(),
12975 });
12976 }
12977
12978 pub fn transact(
12979 &mut self,
12980 window: &mut Window,
12981 cx: &mut Context<Self>,
12982 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12983 ) -> Option<TransactionId> {
12984 self.start_transaction_at(Instant::now(), window, cx);
12985 update(self, window, cx);
12986 self.end_transaction_at(Instant::now(), cx)
12987 }
12988
12989 pub fn start_transaction_at(
12990 &mut self,
12991 now: Instant,
12992 window: &mut Window,
12993 cx: &mut Context<Self>,
12994 ) {
12995 self.end_selection(window, cx);
12996 if let Some(tx_id) = self
12997 .buffer
12998 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12999 {
13000 self.selection_history
13001 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13002 cx.emit(EditorEvent::TransactionBegun {
13003 transaction_id: tx_id,
13004 })
13005 }
13006 }
13007
13008 pub fn end_transaction_at(
13009 &mut self,
13010 now: Instant,
13011 cx: &mut Context<Self>,
13012 ) -> Option<TransactionId> {
13013 if let Some(transaction_id) = self
13014 .buffer
13015 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13016 {
13017 if let Some((_, end_selections)) =
13018 self.selection_history.transaction_mut(transaction_id)
13019 {
13020 *end_selections = Some(self.selections.disjoint_anchors());
13021 } else {
13022 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13023 }
13024
13025 cx.emit(EditorEvent::Edited { transaction_id });
13026 Some(transaction_id)
13027 } else {
13028 None
13029 }
13030 }
13031
13032 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13033 if self.selection_mark_mode {
13034 self.change_selections(None, window, cx, |s| {
13035 s.move_with(|_, sel| {
13036 sel.collapse_to(sel.head(), SelectionGoal::None);
13037 });
13038 })
13039 }
13040 self.selection_mark_mode = true;
13041 cx.notify();
13042 }
13043
13044 pub fn swap_selection_ends(
13045 &mut self,
13046 _: &actions::SwapSelectionEnds,
13047 window: &mut Window,
13048 cx: &mut Context<Self>,
13049 ) {
13050 self.change_selections(None, window, cx, |s| {
13051 s.move_with(|_, sel| {
13052 if sel.start != sel.end {
13053 sel.reversed = !sel.reversed
13054 }
13055 });
13056 });
13057 self.request_autoscroll(Autoscroll::newest(), cx);
13058 cx.notify();
13059 }
13060
13061 pub fn toggle_fold(
13062 &mut self,
13063 _: &actions::ToggleFold,
13064 window: &mut Window,
13065 cx: &mut Context<Self>,
13066 ) {
13067 if self.is_singleton(cx) {
13068 let selection = self.selections.newest::<Point>(cx);
13069
13070 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13071 let range = if selection.is_empty() {
13072 let point = selection.head().to_display_point(&display_map);
13073 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13074 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13075 .to_point(&display_map);
13076 start..end
13077 } else {
13078 selection.range()
13079 };
13080 if display_map.folds_in_range(range).next().is_some() {
13081 self.unfold_lines(&Default::default(), window, cx)
13082 } else {
13083 self.fold(&Default::default(), window, cx)
13084 }
13085 } else {
13086 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13087 let buffer_ids: HashSet<_> = self
13088 .selections
13089 .disjoint_anchor_ranges()
13090 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13091 .collect();
13092
13093 let should_unfold = buffer_ids
13094 .iter()
13095 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13096
13097 for buffer_id in buffer_ids {
13098 if should_unfold {
13099 self.unfold_buffer(buffer_id, cx);
13100 } else {
13101 self.fold_buffer(buffer_id, cx);
13102 }
13103 }
13104 }
13105 }
13106
13107 pub fn toggle_fold_recursive(
13108 &mut self,
13109 _: &actions::ToggleFoldRecursive,
13110 window: &mut Window,
13111 cx: &mut Context<Self>,
13112 ) {
13113 let selection = self.selections.newest::<Point>(cx);
13114
13115 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13116 let range = if selection.is_empty() {
13117 let point = selection.head().to_display_point(&display_map);
13118 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13119 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13120 .to_point(&display_map);
13121 start..end
13122 } else {
13123 selection.range()
13124 };
13125 if display_map.folds_in_range(range).next().is_some() {
13126 self.unfold_recursive(&Default::default(), window, cx)
13127 } else {
13128 self.fold_recursive(&Default::default(), window, cx)
13129 }
13130 }
13131
13132 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13133 if self.is_singleton(cx) {
13134 let mut to_fold = Vec::new();
13135 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13136 let selections = self.selections.all_adjusted(cx);
13137
13138 for selection in selections {
13139 let range = selection.range().sorted();
13140 let buffer_start_row = range.start.row;
13141
13142 if range.start.row != range.end.row {
13143 let mut found = false;
13144 let mut row = range.start.row;
13145 while row <= range.end.row {
13146 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13147 {
13148 found = true;
13149 row = crease.range().end.row + 1;
13150 to_fold.push(crease);
13151 } else {
13152 row += 1
13153 }
13154 }
13155 if found {
13156 continue;
13157 }
13158 }
13159
13160 for row in (0..=range.start.row).rev() {
13161 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13162 if crease.range().end.row >= buffer_start_row {
13163 to_fold.push(crease);
13164 if row <= range.start.row {
13165 break;
13166 }
13167 }
13168 }
13169 }
13170 }
13171
13172 self.fold_creases(to_fold, true, window, cx);
13173 } else {
13174 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13175 let buffer_ids = self
13176 .selections
13177 .disjoint_anchor_ranges()
13178 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13179 .collect::<HashSet<_>>();
13180 for buffer_id in buffer_ids {
13181 self.fold_buffer(buffer_id, cx);
13182 }
13183 }
13184 }
13185
13186 fn fold_at_level(
13187 &mut self,
13188 fold_at: &FoldAtLevel,
13189 window: &mut Window,
13190 cx: &mut Context<Self>,
13191 ) {
13192 if !self.buffer.read(cx).is_singleton() {
13193 return;
13194 }
13195
13196 let fold_at_level = fold_at.0;
13197 let snapshot = self.buffer.read(cx).snapshot(cx);
13198 let mut to_fold = Vec::new();
13199 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13200
13201 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13202 while start_row < end_row {
13203 match self
13204 .snapshot(window, cx)
13205 .crease_for_buffer_row(MultiBufferRow(start_row))
13206 {
13207 Some(crease) => {
13208 let nested_start_row = crease.range().start.row + 1;
13209 let nested_end_row = crease.range().end.row;
13210
13211 if current_level < fold_at_level {
13212 stack.push((nested_start_row, nested_end_row, current_level + 1));
13213 } else if current_level == fold_at_level {
13214 to_fold.push(crease);
13215 }
13216
13217 start_row = nested_end_row + 1;
13218 }
13219 None => start_row += 1,
13220 }
13221 }
13222 }
13223
13224 self.fold_creases(to_fold, true, window, cx);
13225 }
13226
13227 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13228 if self.buffer.read(cx).is_singleton() {
13229 let mut fold_ranges = Vec::new();
13230 let snapshot = self.buffer.read(cx).snapshot(cx);
13231
13232 for row in 0..snapshot.max_row().0 {
13233 if let Some(foldable_range) = self
13234 .snapshot(window, cx)
13235 .crease_for_buffer_row(MultiBufferRow(row))
13236 {
13237 fold_ranges.push(foldable_range);
13238 }
13239 }
13240
13241 self.fold_creases(fold_ranges, true, window, cx);
13242 } else {
13243 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13244 editor
13245 .update_in(&mut cx, |editor, _, cx| {
13246 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13247 editor.fold_buffer(buffer_id, cx);
13248 }
13249 })
13250 .ok();
13251 });
13252 }
13253 }
13254
13255 pub fn fold_function_bodies(
13256 &mut self,
13257 _: &actions::FoldFunctionBodies,
13258 window: &mut Window,
13259 cx: &mut Context<Self>,
13260 ) {
13261 let snapshot = self.buffer.read(cx).snapshot(cx);
13262
13263 let ranges = snapshot
13264 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13265 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13266 .collect::<Vec<_>>();
13267
13268 let creases = ranges
13269 .into_iter()
13270 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13271 .collect();
13272
13273 self.fold_creases(creases, true, window, cx);
13274 }
13275
13276 pub fn fold_recursive(
13277 &mut self,
13278 _: &actions::FoldRecursive,
13279 window: &mut Window,
13280 cx: &mut Context<Self>,
13281 ) {
13282 let mut to_fold = Vec::new();
13283 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13284 let selections = self.selections.all_adjusted(cx);
13285
13286 for selection in selections {
13287 let range = selection.range().sorted();
13288 let buffer_start_row = range.start.row;
13289
13290 if range.start.row != range.end.row {
13291 let mut found = false;
13292 for row in range.start.row..=range.end.row {
13293 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13294 found = true;
13295 to_fold.push(crease);
13296 }
13297 }
13298 if found {
13299 continue;
13300 }
13301 }
13302
13303 for row in (0..=range.start.row).rev() {
13304 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13305 if crease.range().end.row >= buffer_start_row {
13306 to_fold.push(crease);
13307 } else {
13308 break;
13309 }
13310 }
13311 }
13312 }
13313
13314 self.fold_creases(to_fold, true, window, cx);
13315 }
13316
13317 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13318 let buffer_row = fold_at.buffer_row;
13319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13320
13321 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13322 let autoscroll = self
13323 .selections
13324 .all::<Point>(cx)
13325 .iter()
13326 .any(|selection| crease.range().overlaps(&selection.range()));
13327
13328 self.fold_creases(vec![crease], autoscroll, window, cx);
13329 }
13330 }
13331
13332 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13333 if self.is_singleton(cx) {
13334 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13335 let buffer = &display_map.buffer_snapshot;
13336 let selections = self.selections.all::<Point>(cx);
13337 let ranges = selections
13338 .iter()
13339 .map(|s| {
13340 let range = s.display_range(&display_map).sorted();
13341 let mut start = range.start.to_point(&display_map);
13342 let mut end = range.end.to_point(&display_map);
13343 start.column = 0;
13344 end.column = buffer.line_len(MultiBufferRow(end.row));
13345 start..end
13346 })
13347 .collect::<Vec<_>>();
13348
13349 self.unfold_ranges(&ranges, true, true, cx);
13350 } else {
13351 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13352 let buffer_ids = self
13353 .selections
13354 .disjoint_anchor_ranges()
13355 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13356 .collect::<HashSet<_>>();
13357 for buffer_id in buffer_ids {
13358 self.unfold_buffer(buffer_id, cx);
13359 }
13360 }
13361 }
13362
13363 pub fn unfold_recursive(
13364 &mut self,
13365 _: &UnfoldRecursive,
13366 _window: &mut Window,
13367 cx: &mut Context<Self>,
13368 ) {
13369 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13370 let selections = self.selections.all::<Point>(cx);
13371 let ranges = selections
13372 .iter()
13373 .map(|s| {
13374 let mut range = s.display_range(&display_map).sorted();
13375 *range.start.column_mut() = 0;
13376 *range.end.column_mut() = display_map.line_len(range.end.row());
13377 let start = range.start.to_point(&display_map);
13378 let end = range.end.to_point(&display_map);
13379 start..end
13380 })
13381 .collect::<Vec<_>>();
13382
13383 self.unfold_ranges(&ranges, true, true, cx);
13384 }
13385
13386 pub fn unfold_at(
13387 &mut self,
13388 unfold_at: &UnfoldAt,
13389 _window: &mut Window,
13390 cx: &mut Context<Self>,
13391 ) {
13392 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13393
13394 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13395 ..Point::new(
13396 unfold_at.buffer_row.0,
13397 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13398 );
13399
13400 let autoscroll = self
13401 .selections
13402 .all::<Point>(cx)
13403 .iter()
13404 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13405
13406 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13407 }
13408
13409 pub fn unfold_all(
13410 &mut self,
13411 _: &actions::UnfoldAll,
13412 _window: &mut Window,
13413 cx: &mut Context<Self>,
13414 ) {
13415 if self.buffer.read(cx).is_singleton() {
13416 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13417 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13418 } else {
13419 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13420 editor
13421 .update(&mut cx, |editor, cx| {
13422 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13423 editor.unfold_buffer(buffer_id, cx);
13424 }
13425 })
13426 .ok();
13427 });
13428 }
13429 }
13430
13431 pub fn fold_selected_ranges(
13432 &mut self,
13433 _: &FoldSelectedRanges,
13434 window: &mut Window,
13435 cx: &mut Context<Self>,
13436 ) {
13437 let selections = self.selections.all::<Point>(cx);
13438 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13439 let line_mode = self.selections.line_mode;
13440 let ranges = selections
13441 .into_iter()
13442 .map(|s| {
13443 if line_mode {
13444 let start = Point::new(s.start.row, 0);
13445 let end = Point::new(
13446 s.end.row,
13447 display_map
13448 .buffer_snapshot
13449 .line_len(MultiBufferRow(s.end.row)),
13450 );
13451 Crease::simple(start..end, display_map.fold_placeholder.clone())
13452 } else {
13453 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13454 }
13455 })
13456 .collect::<Vec<_>>();
13457 self.fold_creases(ranges, true, window, cx);
13458 }
13459
13460 pub fn fold_ranges<T: ToOffset + Clone>(
13461 &mut self,
13462 ranges: Vec<Range<T>>,
13463 auto_scroll: bool,
13464 window: &mut Window,
13465 cx: &mut Context<Self>,
13466 ) {
13467 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13468 let ranges = ranges
13469 .into_iter()
13470 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13471 .collect::<Vec<_>>();
13472 self.fold_creases(ranges, auto_scroll, window, cx);
13473 }
13474
13475 pub fn fold_creases<T: ToOffset + Clone>(
13476 &mut self,
13477 creases: Vec<Crease<T>>,
13478 auto_scroll: bool,
13479 window: &mut Window,
13480 cx: &mut Context<Self>,
13481 ) {
13482 if creases.is_empty() {
13483 return;
13484 }
13485
13486 let mut buffers_affected = HashSet::default();
13487 let multi_buffer = self.buffer().read(cx);
13488 for crease in &creases {
13489 if let Some((_, buffer, _)) =
13490 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13491 {
13492 buffers_affected.insert(buffer.read(cx).remote_id());
13493 };
13494 }
13495
13496 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13497
13498 if auto_scroll {
13499 self.request_autoscroll(Autoscroll::fit(), cx);
13500 }
13501
13502 cx.notify();
13503
13504 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13505 // Clear diagnostics block when folding a range that contains it.
13506 let snapshot = self.snapshot(window, cx);
13507 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13508 drop(snapshot);
13509 self.active_diagnostics = Some(active_diagnostics);
13510 self.dismiss_diagnostics(cx);
13511 } else {
13512 self.active_diagnostics = Some(active_diagnostics);
13513 }
13514 }
13515
13516 self.scrollbar_marker_state.dirty = true;
13517 }
13518
13519 /// Removes any folds whose ranges intersect any of the given ranges.
13520 pub fn unfold_ranges<T: ToOffset + Clone>(
13521 &mut self,
13522 ranges: &[Range<T>],
13523 inclusive: bool,
13524 auto_scroll: bool,
13525 cx: &mut Context<Self>,
13526 ) {
13527 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13528 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13529 });
13530 }
13531
13532 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13533 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13534 return;
13535 }
13536 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13537 self.display_map.update(cx, |display_map, cx| {
13538 display_map.fold_buffers([buffer_id], cx)
13539 });
13540 cx.emit(EditorEvent::BufferFoldToggled {
13541 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13542 folded: true,
13543 });
13544 cx.notify();
13545 }
13546
13547 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13548 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13549 return;
13550 }
13551 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13552 self.display_map.update(cx, |display_map, cx| {
13553 display_map.unfold_buffers([buffer_id], cx);
13554 });
13555 cx.emit(EditorEvent::BufferFoldToggled {
13556 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13557 folded: false,
13558 });
13559 cx.notify();
13560 }
13561
13562 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13563 self.display_map.read(cx).is_buffer_folded(buffer)
13564 }
13565
13566 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13567 self.display_map.read(cx).folded_buffers()
13568 }
13569
13570 /// Removes any folds with the given ranges.
13571 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13572 &mut self,
13573 ranges: &[Range<T>],
13574 type_id: TypeId,
13575 auto_scroll: bool,
13576 cx: &mut Context<Self>,
13577 ) {
13578 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13579 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13580 });
13581 }
13582
13583 fn remove_folds_with<T: ToOffset + Clone>(
13584 &mut self,
13585 ranges: &[Range<T>],
13586 auto_scroll: bool,
13587 cx: &mut Context<Self>,
13588 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13589 ) {
13590 if ranges.is_empty() {
13591 return;
13592 }
13593
13594 let mut buffers_affected = HashSet::default();
13595 let multi_buffer = self.buffer().read(cx);
13596 for range in ranges {
13597 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13598 buffers_affected.insert(buffer.read(cx).remote_id());
13599 };
13600 }
13601
13602 self.display_map.update(cx, update);
13603
13604 if auto_scroll {
13605 self.request_autoscroll(Autoscroll::fit(), cx);
13606 }
13607
13608 cx.notify();
13609 self.scrollbar_marker_state.dirty = true;
13610 self.active_indent_guides_state.dirty = true;
13611 }
13612
13613 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13614 self.display_map.read(cx).fold_placeholder.clone()
13615 }
13616
13617 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13618 self.buffer.update(cx, |buffer, cx| {
13619 buffer.set_all_diff_hunks_expanded(cx);
13620 });
13621 }
13622
13623 pub fn expand_all_diff_hunks(
13624 &mut self,
13625 _: &ExpandAllDiffHunks,
13626 _window: &mut Window,
13627 cx: &mut Context<Self>,
13628 ) {
13629 self.buffer.update(cx, |buffer, cx| {
13630 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13631 });
13632 }
13633
13634 pub fn toggle_selected_diff_hunks(
13635 &mut self,
13636 _: &ToggleSelectedDiffHunks,
13637 _window: &mut Window,
13638 cx: &mut Context<Self>,
13639 ) {
13640 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13641 self.toggle_diff_hunks_in_ranges(ranges, cx);
13642 }
13643
13644 pub fn diff_hunks_in_ranges<'a>(
13645 &'a self,
13646 ranges: &'a [Range<Anchor>],
13647 buffer: &'a MultiBufferSnapshot,
13648 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13649 ranges.iter().flat_map(move |range| {
13650 let end_excerpt_id = range.end.excerpt_id;
13651 let range = range.to_point(buffer);
13652 let mut peek_end = range.end;
13653 if range.end.row < buffer.max_row().0 {
13654 peek_end = Point::new(range.end.row + 1, 0);
13655 }
13656 buffer
13657 .diff_hunks_in_range(range.start..peek_end)
13658 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13659 })
13660 }
13661
13662 pub fn has_stageable_diff_hunks_in_ranges(
13663 &self,
13664 ranges: &[Range<Anchor>],
13665 snapshot: &MultiBufferSnapshot,
13666 ) -> bool {
13667 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13668 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13669 }
13670
13671 pub fn toggle_staged_selected_diff_hunks(
13672 &mut self,
13673 _: &::git::ToggleStaged,
13674 _: &mut Window,
13675 cx: &mut Context<Self>,
13676 ) {
13677 let snapshot = self.buffer.read(cx).snapshot(cx);
13678 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13679 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13680 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13681 }
13682
13683 pub fn stage_and_next(
13684 &mut self,
13685 _: &::git::StageAndNext,
13686 window: &mut Window,
13687 cx: &mut Context<Self>,
13688 ) {
13689 self.do_stage_or_unstage_and_next(true, window, cx);
13690 }
13691
13692 pub fn unstage_and_next(
13693 &mut self,
13694 _: &::git::UnstageAndNext,
13695 window: &mut Window,
13696 cx: &mut Context<Self>,
13697 ) {
13698 self.do_stage_or_unstage_and_next(false, window, cx);
13699 }
13700
13701 pub fn stage_or_unstage_diff_hunks(
13702 &mut self,
13703 stage: bool,
13704 ranges: Vec<Range<Anchor>>,
13705 cx: &mut Context<Self>,
13706 ) {
13707 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13708 cx.spawn(|this, mut cx| async move {
13709 task.await?;
13710 this.update(&mut cx, |this, cx| {
13711 let snapshot = this.buffer.read(cx).snapshot(cx);
13712 let chunk_by = this
13713 .diff_hunks_in_ranges(&ranges, &snapshot)
13714 .chunk_by(|hunk| hunk.buffer_id);
13715 for (buffer_id, hunks) in &chunk_by {
13716 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13717 }
13718 })
13719 })
13720 .detach_and_log_err(cx);
13721 }
13722
13723 fn save_buffers_for_ranges_if_needed(
13724 &mut self,
13725 ranges: &[Range<Anchor>],
13726 cx: &mut Context<'_, Editor>,
13727 ) -> Task<Result<()>> {
13728 let multibuffer = self.buffer.read(cx);
13729 let snapshot = multibuffer.read(cx);
13730 let buffer_ids: HashSet<_> = ranges
13731 .iter()
13732 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13733 .collect();
13734 drop(snapshot);
13735
13736 let mut buffers = HashSet::default();
13737 for buffer_id in buffer_ids {
13738 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13739 let buffer = buffer_entity.read(cx);
13740 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13741 {
13742 buffers.insert(buffer_entity);
13743 }
13744 }
13745 }
13746
13747 if let Some(project) = &self.project {
13748 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13749 } else {
13750 Task::ready(Ok(()))
13751 }
13752 }
13753
13754 fn do_stage_or_unstage_and_next(
13755 &mut self,
13756 stage: bool,
13757 window: &mut Window,
13758 cx: &mut Context<Self>,
13759 ) {
13760 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13761
13762 if ranges.iter().any(|range| range.start != range.end) {
13763 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13764 return;
13765 }
13766
13767 let snapshot = self.snapshot(window, cx);
13768 let newest_range = self.selections.newest::<Point>(cx).range();
13769
13770 let run_twice = snapshot
13771 .hunks_for_ranges([newest_range])
13772 .first()
13773 .is_some_and(|hunk| {
13774 let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13775 self.hunk_after_position(&snapshot, next_line)
13776 .is_some_and(|other| other.row_range == hunk.row_range)
13777 });
13778
13779 if run_twice {
13780 self.go_to_next_hunk(&GoToHunk, window, cx);
13781 }
13782 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13783 self.go_to_next_hunk(&GoToHunk, window, cx);
13784 }
13785
13786 fn do_stage_or_unstage(
13787 &self,
13788 stage: bool,
13789 buffer_id: BufferId,
13790 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13791 cx: &mut App,
13792 ) -> Option<()> {
13793 let project = self.project.as_ref()?;
13794 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13795 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13796 let buffer_snapshot = buffer.read(cx).snapshot();
13797 let file_exists = buffer_snapshot
13798 .file()
13799 .is_some_and(|file| file.disk_state().exists());
13800 diff.update(cx, |diff, cx| {
13801 diff.stage_or_unstage_hunks(
13802 stage,
13803 &hunks
13804 .map(|hunk| buffer_diff::DiffHunk {
13805 buffer_range: hunk.buffer_range,
13806 diff_base_byte_range: hunk.diff_base_byte_range,
13807 secondary_status: hunk.secondary_status,
13808 range: Point::zero()..Point::zero(), // unused
13809 })
13810 .collect::<Vec<_>>(),
13811 &buffer_snapshot,
13812 file_exists,
13813 cx,
13814 )
13815 });
13816 None
13817 }
13818
13819 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13820 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13821 self.buffer
13822 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13823 }
13824
13825 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13826 self.buffer.update(cx, |buffer, cx| {
13827 let ranges = vec![Anchor::min()..Anchor::max()];
13828 if !buffer.all_diff_hunks_expanded()
13829 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13830 {
13831 buffer.collapse_diff_hunks(ranges, cx);
13832 true
13833 } else {
13834 false
13835 }
13836 })
13837 }
13838
13839 fn toggle_diff_hunks_in_ranges(
13840 &mut self,
13841 ranges: Vec<Range<Anchor>>,
13842 cx: &mut Context<'_, Editor>,
13843 ) {
13844 self.buffer.update(cx, |buffer, cx| {
13845 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13846 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13847 })
13848 }
13849
13850 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13851 self.buffer.update(cx, |buffer, cx| {
13852 let snapshot = buffer.snapshot(cx);
13853 let excerpt_id = range.end.excerpt_id;
13854 let point_range = range.to_point(&snapshot);
13855 let expand = !buffer.single_hunk_is_expanded(range, cx);
13856 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13857 })
13858 }
13859
13860 pub(crate) fn apply_all_diff_hunks(
13861 &mut self,
13862 _: &ApplyAllDiffHunks,
13863 window: &mut Window,
13864 cx: &mut Context<Self>,
13865 ) {
13866 let buffers = self.buffer.read(cx).all_buffers();
13867 for branch_buffer in buffers {
13868 branch_buffer.update(cx, |branch_buffer, cx| {
13869 branch_buffer.merge_into_base(Vec::new(), cx);
13870 });
13871 }
13872
13873 if let Some(project) = self.project.clone() {
13874 self.save(true, project, window, cx).detach_and_log_err(cx);
13875 }
13876 }
13877
13878 pub(crate) fn apply_selected_diff_hunks(
13879 &mut self,
13880 _: &ApplyDiffHunk,
13881 window: &mut Window,
13882 cx: &mut Context<Self>,
13883 ) {
13884 let snapshot = self.snapshot(window, cx);
13885 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13886 let mut ranges_by_buffer = HashMap::default();
13887 self.transact(window, cx, |editor, _window, cx| {
13888 for hunk in hunks {
13889 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13890 ranges_by_buffer
13891 .entry(buffer.clone())
13892 .or_insert_with(Vec::new)
13893 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13894 }
13895 }
13896
13897 for (buffer, ranges) in ranges_by_buffer {
13898 buffer.update(cx, |buffer, cx| {
13899 buffer.merge_into_base(ranges, cx);
13900 });
13901 }
13902 });
13903
13904 if let Some(project) = self.project.clone() {
13905 self.save(true, project, window, cx).detach_and_log_err(cx);
13906 }
13907 }
13908
13909 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13910 if hovered != self.gutter_hovered {
13911 self.gutter_hovered = hovered;
13912 cx.notify();
13913 }
13914 }
13915
13916 pub fn insert_blocks(
13917 &mut self,
13918 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13919 autoscroll: Option<Autoscroll>,
13920 cx: &mut Context<Self>,
13921 ) -> Vec<CustomBlockId> {
13922 let blocks = self
13923 .display_map
13924 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13925 if let Some(autoscroll) = autoscroll {
13926 self.request_autoscroll(autoscroll, cx);
13927 }
13928 cx.notify();
13929 blocks
13930 }
13931
13932 pub fn resize_blocks(
13933 &mut self,
13934 heights: HashMap<CustomBlockId, u32>,
13935 autoscroll: Option<Autoscroll>,
13936 cx: &mut Context<Self>,
13937 ) {
13938 self.display_map
13939 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13940 if let Some(autoscroll) = autoscroll {
13941 self.request_autoscroll(autoscroll, cx);
13942 }
13943 cx.notify();
13944 }
13945
13946 pub fn replace_blocks(
13947 &mut self,
13948 renderers: HashMap<CustomBlockId, RenderBlock>,
13949 autoscroll: Option<Autoscroll>,
13950 cx: &mut Context<Self>,
13951 ) {
13952 self.display_map
13953 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13954 if let Some(autoscroll) = autoscroll {
13955 self.request_autoscroll(autoscroll, cx);
13956 }
13957 cx.notify();
13958 }
13959
13960 pub fn remove_blocks(
13961 &mut self,
13962 block_ids: HashSet<CustomBlockId>,
13963 autoscroll: Option<Autoscroll>,
13964 cx: &mut Context<Self>,
13965 ) {
13966 self.display_map.update(cx, |display_map, cx| {
13967 display_map.remove_blocks(block_ids, cx)
13968 });
13969 if let Some(autoscroll) = autoscroll {
13970 self.request_autoscroll(autoscroll, cx);
13971 }
13972 cx.notify();
13973 }
13974
13975 pub fn row_for_block(
13976 &self,
13977 block_id: CustomBlockId,
13978 cx: &mut Context<Self>,
13979 ) -> Option<DisplayRow> {
13980 self.display_map
13981 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13982 }
13983
13984 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13985 self.focused_block = Some(focused_block);
13986 }
13987
13988 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13989 self.focused_block.take()
13990 }
13991
13992 pub fn insert_creases(
13993 &mut self,
13994 creases: impl IntoIterator<Item = Crease<Anchor>>,
13995 cx: &mut Context<Self>,
13996 ) -> Vec<CreaseId> {
13997 self.display_map
13998 .update(cx, |map, cx| map.insert_creases(creases, cx))
13999 }
14000
14001 pub fn remove_creases(
14002 &mut self,
14003 ids: impl IntoIterator<Item = CreaseId>,
14004 cx: &mut Context<Self>,
14005 ) {
14006 self.display_map
14007 .update(cx, |map, cx| map.remove_creases(ids, cx));
14008 }
14009
14010 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14011 self.display_map
14012 .update(cx, |map, cx| map.snapshot(cx))
14013 .longest_row()
14014 }
14015
14016 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14017 self.display_map
14018 .update(cx, |map, cx| map.snapshot(cx))
14019 .max_point()
14020 }
14021
14022 pub fn text(&self, cx: &App) -> String {
14023 self.buffer.read(cx).read(cx).text()
14024 }
14025
14026 pub fn is_empty(&self, cx: &App) -> bool {
14027 self.buffer.read(cx).read(cx).is_empty()
14028 }
14029
14030 pub fn text_option(&self, cx: &App) -> Option<String> {
14031 let text = self.text(cx);
14032 let text = text.trim();
14033
14034 if text.is_empty() {
14035 return None;
14036 }
14037
14038 Some(text.to_string())
14039 }
14040
14041 pub fn set_text(
14042 &mut self,
14043 text: impl Into<Arc<str>>,
14044 window: &mut Window,
14045 cx: &mut Context<Self>,
14046 ) {
14047 self.transact(window, cx, |this, _, cx| {
14048 this.buffer
14049 .read(cx)
14050 .as_singleton()
14051 .expect("you can only call set_text on editors for singleton buffers")
14052 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14053 });
14054 }
14055
14056 pub fn display_text(&self, cx: &mut App) -> String {
14057 self.display_map
14058 .update(cx, |map, cx| map.snapshot(cx))
14059 .text()
14060 }
14061
14062 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14063 let mut wrap_guides = smallvec::smallvec![];
14064
14065 if self.show_wrap_guides == Some(false) {
14066 return wrap_guides;
14067 }
14068
14069 let settings = self.buffer.read(cx).language_settings(cx);
14070 if settings.show_wrap_guides {
14071 match self.soft_wrap_mode(cx) {
14072 SoftWrap::Column(soft_wrap) => {
14073 wrap_guides.push((soft_wrap as usize, true));
14074 }
14075 SoftWrap::Bounded(soft_wrap) => {
14076 wrap_guides.push((soft_wrap as usize, true));
14077 }
14078 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14079 }
14080 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14081 }
14082
14083 wrap_guides
14084 }
14085
14086 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14087 let settings = self.buffer.read(cx).language_settings(cx);
14088 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14089 match mode {
14090 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14091 SoftWrap::None
14092 }
14093 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14094 language_settings::SoftWrap::PreferredLineLength => {
14095 SoftWrap::Column(settings.preferred_line_length)
14096 }
14097 language_settings::SoftWrap::Bounded => {
14098 SoftWrap::Bounded(settings.preferred_line_length)
14099 }
14100 }
14101 }
14102
14103 pub fn set_soft_wrap_mode(
14104 &mut self,
14105 mode: language_settings::SoftWrap,
14106
14107 cx: &mut Context<Self>,
14108 ) {
14109 self.soft_wrap_mode_override = Some(mode);
14110 cx.notify();
14111 }
14112
14113 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14114 self.text_style_refinement = Some(style);
14115 }
14116
14117 /// called by the Element so we know what style we were most recently rendered with.
14118 pub(crate) fn set_style(
14119 &mut self,
14120 style: EditorStyle,
14121 window: &mut Window,
14122 cx: &mut Context<Self>,
14123 ) {
14124 let rem_size = window.rem_size();
14125 self.display_map.update(cx, |map, cx| {
14126 map.set_font(
14127 style.text.font(),
14128 style.text.font_size.to_pixels(rem_size),
14129 cx,
14130 )
14131 });
14132 self.style = Some(style);
14133 }
14134
14135 pub fn style(&self) -> Option<&EditorStyle> {
14136 self.style.as_ref()
14137 }
14138
14139 // Called by the element. This method is not designed to be called outside of the editor
14140 // element's layout code because it does not notify when rewrapping is computed synchronously.
14141 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14142 self.display_map
14143 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14144 }
14145
14146 pub fn set_soft_wrap(&mut self) {
14147 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14148 }
14149
14150 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14151 if self.soft_wrap_mode_override.is_some() {
14152 self.soft_wrap_mode_override.take();
14153 } else {
14154 let soft_wrap = match self.soft_wrap_mode(cx) {
14155 SoftWrap::GitDiff => return,
14156 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14157 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14158 language_settings::SoftWrap::None
14159 }
14160 };
14161 self.soft_wrap_mode_override = Some(soft_wrap);
14162 }
14163 cx.notify();
14164 }
14165
14166 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14167 let Some(workspace) = self.workspace() else {
14168 return;
14169 };
14170 let fs = workspace.read(cx).app_state().fs.clone();
14171 let current_show = TabBarSettings::get_global(cx).show;
14172 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14173 setting.show = Some(!current_show);
14174 });
14175 }
14176
14177 pub fn toggle_indent_guides(
14178 &mut self,
14179 _: &ToggleIndentGuides,
14180 _: &mut Window,
14181 cx: &mut Context<Self>,
14182 ) {
14183 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14184 self.buffer
14185 .read(cx)
14186 .language_settings(cx)
14187 .indent_guides
14188 .enabled
14189 });
14190 self.show_indent_guides = Some(!currently_enabled);
14191 cx.notify();
14192 }
14193
14194 fn should_show_indent_guides(&self) -> Option<bool> {
14195 self.show_indent_guides
14196 }
14197
14198 pub fn toggle_line_numbers(
14199 &mut self,
14200 _: &ToggleLineNumbers,
14201 _: &mut Window,
14202 cx: &mut Context<Self>,
14203 ) {
14204 let mut editor_settings = EditorSettings::get_global(cx).clone();
14205 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14206 EditorSettings::override_global(editor_settings, cx);
14207 }
14208
14209 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14210 self.use_relative_line_numbers
14211 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14212 }
14213
14214 pub fn toggle_relative_line_numbers(
14215 &mut self,
14216 _: &ToggleRelativeLineNumbers,
14217 _: &mut Window,
14218 cx: &mut Context<Self>,
14219 ) {
14220 let is_relative = self.should_use_relative_line_numbers(cx);
14221 self.set_relative_line_number(Some(!is_relative), cx)
14222 }
14223
14224 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14225 self.use_relative_line_numbers = is_relative;
14226 cx.notify();
14227 }
14228
14229 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14230 self.show_gutter = show_gutter;
14231 cx.notify();
14232 }
14233
14234 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14235 self.show_scrollbars = show_scrollbars;
14236 cx.notify();
14237 }
14238
14239 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14240 self.show_line_numbers = Some(show_line_numbers);
14241 cx.notify();
14242 }
14243
14244 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14245 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14246 cx.notify();
14247 }
14248
14249 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14250 self.show_code_actions = Some(show_code_actions);
14251 cx.notify();
14252 }
14253
14254 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14255 self.show_runnables = Some(show_runnables);
14256 cx.notify();
14257 }
14258
14259 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14260 if self.display_map.read(cx).masked != masked {
14261 self.display_map.update(cx, |map, _| map.masked = masked);
14262 }
14263 cx.notify()
14264 }
14265
14266 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14267 self.show_wrap_guides = Some(show_wrap_guides);
14268 cx.notify();
14269 }
14270
14271 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14272 self.show_indent_guides = Some(show_indent_guides);
14273 cx.notify();
14274 }
14275
14276 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14277 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14278 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14279 if let Some(dir) = file.abs_path(cx).parent() {
14280 return Some(dir.to_owned());
14281 }
14282 }
14283
14284 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14285 return Some(project_path.path.to_path_buf());
14286 }
14287 }
14288
14289 None
14290 }
14291
14292 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14293 self.active_excerpt(cx)?
14294 .1
14295 .read(cx)
14296 .file()
14297 .and_then(|f| f.as_local())
14298 }
14299
14300 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14301 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14302 let buffer = buffer.read(cx);
14303 if let Some(project_path) = buffer.project_path(cx) {
14304 let project = self.project.as_ref()?.read(cx);
14305 project.absolute_path(&project_path, cx)
14306 } else {
14307 buffer
14308 .file()
14309 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14310 }
14311 })
14312 }
14313
14314 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14315 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14316 let project_path = buffer.read(cx).project_path(cx)?;
14317 let project = self.project.as_ref()?.read(cx);
14318 let entry = project.entry_for_path(&project_path, cx)?;
14319 let path = entry.path.to_path_buf();
14320 Some(path)
14321 })
14322 }
14323
14324 pub fn reveal_in_finder(
14325 &mut self,
14326 _: &RevealInFileManager,
14327 _window: &mut Window,
14328 cx: &mut Context<Self>,
14329 ) {
14330 if let Some(target) = self.target_file(cx) {
14331 cx.reveal_path(&target.abs_path(cx));
14332 }
14333 }
14334
14335 pub fn copy_path(
14336 &mut self,
14337 _: &zed_actions::workspace::CopyPath,
14338 _window: &mut Window,
14339 cx: &mut Context<Self>,
14340 ) {
14341 if let Some(path) = self.target_file_abs_path(cx) {
14342 if let Some(path) = path.to_str() {
14343 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14344 }
14345 }
14346 }
14347
14348 pub fn copy_relative_path(
14349 &mut self,
14350 _: &zed_actions::workspace::CopyRelativePath,
14351 _window: &mut Window,
14352 cx: &mut Context<Self>,
14353 ) {
14354 if let Some(path) = self.target_file_path(cx) {
14355 if let Some(path) = path.to_str() {
14356 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14357 }
14358 }
14359 }
14360
14361 pub fn copy_file_name_without_extension(
14362 &mut self,
14363 _: &CopyFileNameWithoutExtension,
14364 _: &mut Window,
14365 cx: &mut Context<Self>,
14366 ) {
14367 if let Some(file) = self.target_file(cx) {
14368 if let Some(file_stem) = file.path().file_stem() {
14369 if let Some(name) = file_stem.to_str() {
14370 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14371 }
14372 }
14373 }
14374 }
14375
14376 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14377 if let Some(file) = self.target_file(cx) {
14378 if let Some(file_name) = file.path().file_name() {
14379 if let Some(name) = file_name.to_str() {
14380 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14381 }
14382 }
14383 }
14384 }
14385
14386 pub fn toggle_git_blame(
14387 &mut self,
14388 _: &ToggleGitBlame,
14389 window: &mut Window,
14390 cx: &mut Context<Self>,
14391 ) {
14392 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14393
14394 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14395 self.start_git_blame(true, window, cx);
14396 }
14397
14398 cx.notify();
14399 }
14400
14401 pub fn toggle_git_blame_inline(
14402 &mut self,
14403 _: &ToggleGitBlameInline,
14404 window: &mut Window,
14405 cx: &mut Context<Self>,
14406 ) {
14407 self.toggle_git_blame_inline_internal(true, window, cx);
14408 cx.notify();
14409 }
14410
14411 pub fn git_blame_inline_enabled(&self) -> bool {
14412 self.git_blame_inline_enabled
14413 }
14414
14415 pub fn toggle_selection_menu(
14416 &mut self,
14417 _: &ToggleSelectionMenu,
14418 _: &mut Window,
14419 cx: &mut Context<Self>,
14420 ) {
14421 self.show_selection_menu = self
14422 .show_selection_menu
14423 .map(|show_selections_menu| !show_selections_menu)
14424 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14425
14426 cx.notify();
14427 }
14428
14429 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14430 self.show_selection_menu
14431 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14432 }
14433
14434 fn start_git_blame(
14435 &mut self,
14436 user_triggered: bool,
14437 window: &mut Window,
14438 cx: &mut Context<Self>,
14439 ) {
14440 if let Some(project) = self.project.as_ref() {
14441 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14442 return;
14443 };
14444
14445 if buffer.read(cx).file().is_none() {
14446 return;
14447 }
14448
14449 let focused = self.focus_handle(cx).contains_focused(window, cx);
14450
14451 let project = project.clone();
14452 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14453 self.blame_subscription =
14454 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14455 self.blame = Some(blame);
14456 }
14457 }
14458
14459 fn toggle_git_blame_inline_internal(
14460 &mut self,
14461 user_triggered: bool,
14462 window: &mut Window,
14463 cx: &mut Context<Self>,
14464 ) {
14465 if self.git_blame_inline_enabled {
14466 self.git_blame_inline_enabled = false;
14467 self.show_git_blame_inline = false;
14468 self.show_git_blame_inline_delay_task.take();
14469 } else {
14470 self.git_blame_inline_enabled = true;
14471 self.start_git_blame_inline(user_triggered, window, cx);
14472 }
14473
14474 cx.notify();
14475 }
14476
14477 fn start_git_blame_inline(
14478 &mut self,
14479 user_triggered: bool,
14480 window: &mut Window,
14481 cx: &mut Context<Self>,
14482 ) {
14483 self.start_git_blame(user_triggered, window, cx);
14484
14485 if ProjectSettings::get_global(cx)
14486 .git
14487 .inline_blame_delay()
14488 .is_some()
14489 {
14490 self.start_inline_blame_timer(window, cx);
14491 } else {
14492 self.show_git_blame_inline = true
14493 }
14494 }
14495
14496 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14497 self.blame.as_ref()
14498 }
14499
14500 pub fn show_git_blame_gutter(&self) -> bool {
14501 self.show_git_blame_gutter
14502 }
14503
14504 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14505 self.show_git_blame_gutter && self.has_blame_entries(cx)
14506 }
14507
14508 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14509 self.show_git_blame_inline
14510 && (self.focus_handle.is_focused(window)
14511 || self
14512 .git_blame_inline_tooltip
14513 .as_ref()
14514 .and_then(|t| t.upgrade())
14515 .is_some())
14516 && !self.newest_selection_head_on_empty_line(cx)
14517 && self.has_blame_entries(cx)
14518 }
14519
14520 fn has_blame_entries(&self, cx: &App) -> bool {
14521 self.blame()
14522 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14523 }
14524
14525 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14526 let cursor_anchor = self.selections.newest_anchor().head();
14527
14528 let snapshot = self.buffer.read(cx).snapshot(cx);
14529 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14530
14531 snapshot.line_len(buffer_row) == 0
14532 }
14533
14534 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14535 let buffer_and_selection = maybe!({
14536 let selection = self.selections.newest::<Point>(cx);
14537 let selection_range = selection.range();
14538
14539 let multi_buffer = self.buffer().read(cx);
14540 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14541 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14542
14543 let (buffer, range, _) = if selection.reversed {
14544 buffer_ranges.first()
14545 } else {
14546 buffer_ranges.last()
14547 }?;
14548
14549 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14550 ..text::ToPoint::to_point(&range.end, &buffer).row;
14551 Some((
14552 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14553 selection,
14554 ))
14555 });
14556
14557 let Some((buffer, selection)) = buffer_and_selection else {
14558 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14559 };
14560
14561 let Some(project) = self.project.as_ref() else {
14562 return Task::ready(Err(anyhow!("editor does not have project")));
14563 };
14564
14565 project.update(cx, |project, cx| {
14566 project.get_permalink_to_line(&buffer, selection, cx)
14567 })
14568 }
14569
14570 pub fn copy_permalink_to_line(
14571 &mut self,
14572 _: &CopyPermalinkToLine,
14573 window: &mut Window,
14574 cx: &mut Context<Self>,
14575 ) {
14576 let permalink_task = self.get_permalink_to_line(cx);
14577 let workspace = self.workspace();
14578
14579 cx.spawn_in(window, |_, mut cx| async move {
14580 match permalink_task.await {
14581 Ok(permalink) => {
14582 cx.update(|_, cx| {
14583 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14584 })
14585 .ok();
14586 }
14587 Err(err) => {
14588 let message = format!("Failed to copy permalink: {err}");
14589
14590 Err::<(), anyhow::Error>(err).log_err();
14591
14592 if let Some(workspace) = workspace {
14593 workspace
14594 .update_in(&mut cx, |workspace, _, cx| {
14595 struct CopyPermalinkToLine;
14596
14597 workspace.show_toast(
14598 Toast::new(
14599 NotificationId::unique::<CopyPermalinkToLine>(),
14600 message,
14601 ),
14602 cx,
14603 )
14604 })
14605 .ok();
14606 }
14607 }
14608 }
14609 })
14610 .detach();
14611 }
14612
14613 pub fn copy_file_location(
14614 &mut self,
14615 _: &CopyFileLocation,
14616 _: &mut Window,
14617 cx: &mut Context<Self>,
14618 ) {
14619 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14620 if let Some(file) = self.target_file(cx) {
14621 if let Some(path) = file.path().to_str() {
14622 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14623 }
14624 }
14625 }
14626
14627 pub fn open_permalink_to_line(
14628 &mut self,
14629 _: &OpenPermalinkToLine,
14630 window: &mut Window,
14631 cx: &mut Context<Self>,
14632 ) {
14633 let permalink_task = self.get_permalink_to_line(cx);
14634 let workspace = self.workspace();
14635
14636 cx.spawn_in(window, |_, mut cx| async move {
14637 match permalink_task.await {
14638 Ok(permalink) => {
14639 cx.update(|_, cx| {
14640 cx.open_url(permalink.as_ref());
14641 })
14642 .ok();
14643 }
14644 Err(err) => {
14645 let message = format!("Failed to open permalink: {err}");
14646
14647 Err::<(), anyhow::Error>(err).log_err();
14648
14649 if let Some(workspace) = workspace {
14650 workspace
14651 .update(&mut cx, |workspace, cx| {
14652 struct OpenPermalinkToLine;
14653
14654 workspace.show_toast(
14655 Toast::new(
14656 NotificationId::unique::<OpenPermalinkToLine>(),
14657 message,
14658 ),
14659 cx,
14660 )
14661 })
14662 .ok();
14663 }
14664 }
14665 }
14666 })
14667 .detach();
14668 }
14669
14670 pub fn insert_uuid_v4(
14671 &mut self,
14672 _: &InsertUuidV4,
14673 window: &mut Window,
14674 cx: &mut Context<Self>,
14675 ) {
14676 self.insert_uuid(UuidVersion::V4, window, cx);
14677 }
14678
14679 pub fn insert_uuid_v7(
14680 &mut self,
14681 _: &InsertUuidV7,
14682 window: &mut Window,
14683 cx: &mut Context<Self>,
14684 ) {
14685 self.insert_uuid(UuidVersion::V7, window, cx);
14686 }
14687
14688 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14689 self.transact(window, cx, |this, window, cx| {
14690 let edits = this
14691 .selections
14692 .all::<Point>(cx)
14693 .into_iter()
14694 .map(|selection| {
14695 let uuid = match version {
14696 UuidVersion::V4 => uuid::Uuid::new_v4(),
14697 UuidVersion::V7 => uuid::Uuid::now_v7(),
14698 };
14699
14700 (selection.range(), uuid.to_string())
14701 });
14702 this.edit(edits, cx);
14703 this.refresh_inline_completion(true, false, window, cx);
14704 });
14705 }
14706
14707 pub fn open_selections_in_multibuffer(
14708 &mut self,
14709 _: &OpenSelectionsInMultibuffer,
14710 window: &mut Window,
14711 cx: &mut Context<Self>,
14712 ) {
14713 let multibuffer = self.buffer.read(cx);
14714
14715 let Some(buffer) = multibuffer.as_singleton() else {
14716 return;
14717 };
14718
14719 let Some(workspace) = self.workspace() else {
14720 return;
14721 };
14722
14723 let locations = self
14724 .selections
14725 .disjoint_anchors()
14726 .iter()
14727 .map(|range| Location {
14728 buffer: buffer.clone(),
14729 range: range.start.text_anchor..range.end.text_anchor,
14730 })
14731 .collect::<Vec<_>>();
14732
14733 let title = multibuffer.title(cx).to_string();
14734
14735 cx.spawn_in(window, |_, mut cx| async move {
14736 workspace.update_in(&mut cx, |workspace, window, cx| {
14737 Self::open_locations_in_multibuffer(
14738 workspace,
14739 locations,
14740 format!("Selections for '{title}'"),
14741 false,
14742 MultibufferSelectionMode::All,
14743 window,
14744 cx,
14745 );
14746 })
14747 })
14748 .detach();
14749 }
14750
14751 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14752 /// last highlight added will be used.
14753 ///
14754 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14755 pub fn highlight_rows<T: 'static>(
14756 &mut self,
14757 range: Range<Anchor>,
14758 color: Hsla,
14759 should_autoscroll: bool,
14760 cx: &mut Context<Self>,
14761 ) {
14762 let snapshot = self.buffer().read(cx).snapshot(cx);
14763 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14764 let ix = row_highlights.binary_search_by(|highlight| {
14765 Ordering::Equal
14766 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14767 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14768 });
14769
14770 if let Err(mut ix) = ix {
14771 let index = post_inc(&mut self.highlight_order);
14772
14773 // If this range intersects with the preceding highlight, then merge it with
14774 // the preceding highlight. Otherwise insert a new highlight.
14775 let mut merged = false;
14776 if ix > 0 {
14777 let prev_highlight = &mut row_highlights[ix - 1];
14778 if prev_highlight
14779 .range
14780 .end
14781 .cmp(&range.start, &snapshot)
14782 .is_ge()
14783 {
14784 ix -= 1;
14785 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14786 prev_highlight.range.end = range.end;
14787 }
14788 merged = true;
14789 prev_highlight.index = index;
14790 prev_highlight.color = color;
14791 prev_highlight.should_autoscroll = should_autoscroll;
14792 }
14793 }
14794
14795 if !merged {
14796 row_highlights.insert(
14797 ix,
14798 RowHighlight {
14799 range: range.clone(),
14800 index,
14801 color,
14802 should_autoscroll,
14803 },
14804 );
14805 }
14806
14807 // If any of the following highlights intersect with this one, merge them.
14808 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14809 let highlight = &row_highlights[ix];
14810 if next_highlight
14811 .range
14812 .start
14813 .cmp(&highlight.range.end, &snapshot)
14814 .is_le()
14815 {
14816 if next_highlight
14817 .range
14818 .end
14819 .cmp(&highlight.range.end, &snapshot)
14820 .is_gt()
14821 {
14822 row_highlights[ix].range.end = next_highlight.range.end;
14823 }
14824 row_highlights.remove(ix + 1);
14825 } else {
14826 break;
14827 }
14828 }
14829 }
14830 }
14831
14832 /// Remove any highlighted row ranges of the given type that intersect the
14833 /// given ranges.
14834 pub fn remove_highlighted_rows<T: 'static>(
14835 &mut self,
14836 ranges_to_remove: Vec<Range<Anchor>>,
14837 cx: &mut Context<Self>,
14838 ) {
14839 let snapshot = self.buffer().read(cx).snapshot(cx);
14840 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14841 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14842 row_highlights.retain(|highlight| {
14843 while let Some(range_to_remove) = ranges_to_remove.peek() {
14844 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14845 Ordering::Less | Ordering::Equal => {
14846 ranges_to_remove.next();
14847 }
14848 Ordering::Greater => {
14849 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14850 Ordering::Less | Ordering::Equal => {
14851 return false;
14852 }
14853 Ordering::Greater => break,
14854 }
14855 }
14856 }
14857 }
14858
14859 true
14860 })
14861 }
14862
14863 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14864 pub fn clear_row_highlights<T: 'static>(&mut self) {
14865 self.highlighted_rows.remove(&TypeId::of::<T>());
14866 }
14867
14868 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14869 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14870 self.highlighted_rows
14871 .get(&TypeId::of::<T>())
14872 .map_or(&[] as &[_], |vec| vec.as_slice())
14873 .iter()
14874 .map(|highlight| (highlight.range.clone(), highlight.color))
14875 }
14876
14877 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14878 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14879 /// Allows to ignore certain kinds of highlights.
14880 pub fn highlighted_display_rows(
14881 &self,
14882 window: &mut Window,
14883 cx: &mut App,
14884 ) -> BTreeMap<DisplayRow, Background> {
14885 let snapshot = self.snapshot(window, cx);
14886 let mut used_highlight_orders = HashMap::default();
14887 self.highlighted_rows
14888 .iter()
14889 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14890 .fold(
14891 BTreeMap::<DisplayRow, Background>::new(),
14892 |mut unique_rows, highlight| {
14893 let start = highlight.range.start.to_display_point(&snapshot);
14894 let end = highlight.range.end.to_display_point(&snapshot);
14895 let start_row = start.row().0;
14896 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14897 && end.column() == 0
14898 {
14899 end.row().0.saturating_sub(1)
14900 } else {
14901 end.row().0
14902 };
14903 for row in start_row..=end_row {
14904 let used_index =
14905 used_highlight_orders.entry(row).or_insert(highlight.index);
14906 if highlight.index >= *used_index {
14907 *used_index = highlight.index;
14908 unique_rows.insert(DisplayRow(row), highlight.color.into());
14909 }
14910 }
14911 unique_rows
14912 },
14913 )
14914 }
14915
14916 pub fn highlighted_display_row_for_autoscroll(
14917 &self,
14918 snapshot: &DisplaySnapshot,
14919 ) -> Option<DisplayRow> {
14920 self.highlighted_rows
14921 .values()
14922 .flat_map(|highlighted_rows| highlighted_rows.iter())
14923 .filter_map(|highlight| {
14924 if highlight.should_autoscroll {
14925 Some(highlight.range.start.to_display_point(snapshot).row())
14926 } else {
14927 None
14928 }
14929 })
14930 .min()
14931 }
14932
14933 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14934 self.highlight_background::<SearchWithinRange>(
14935 ranges,
14936 |colors| colors.editor_document_highlight_read_background,
14937 cx,
14938 )
14939 }
14940
14941 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14942 self.breadcrumb_header = Some(new_header);
14943 }
14944
14945 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14946 self.clear_background_highlights::<SearchWithinRange>(cx);
14947 }
14948
14949 pub fn highlight_background<T: 'static>(
14950 &mut self,
14951 ranges: &[Range<Anchor>],
14952 color_fetcher: fn(&ThemeColors) -> Hsla,
14953 cx: &mut Context<Self>,
14954 ) {
14955 self.background_highlights
14956 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14957 self.scrollbar_marker_state.dirty = true;
14958 cx.notify();
14959 }
14960
14961 pub fn clear_background_highlights<T: 'static>(
14962 &mut self,
14963 cx: &mut Context<Self>,
14964 ) -> Option<BackgroundHighlight> {
14965 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14966 if !text_highlights.1.is_empty() {
14967 self.scrollbar_marker_state.dirty = true;
14968 cx.notify();
14969 }
14970 Some(text_highlights)
14971 }
14972
14973 pub fn highlight_gutter<T: 'static>(
14974 &mut self,
14975 ranges: &[Range<Anchor>],
14976 color_fetcher: fn(&App) -> Hsla,
14977 cx: &mut Context<Self>,
14978 ) {
14979 self.gutter_highlights
14980 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14981 cx.notify();
14982 }
14983
14984 pub fn clear_gutter_highlights<T: 'static>(
14985 &mut self,
14986 cx: &mut Context<Self>,
14987 ) -> Option<GutterHighlight> {
14988 cx.notify();
14989 self.gutter_highlights.remove(&TypeId::of::<T>())
14990 }
14991
14992 #[cfg(feature = "test-support")]
14993 pub fn all_text_background_highlights(
14994 &self,
14995 window: &mut Window,
14996 cx: &mut Context<Self>,
14997 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14998 let snapshot = self.snapshot(window, cx);
14999 let buffer = &snapshot.buffer_snapshot;
15000 let start = buffer.anchor_before(0);
15001 let end = buffer.anchor_after(buffer.len());
15002 let theme = cx.theme().colors();
15003 self.background_highlights_in_range(start..end, &snapshot, theme)
15004 }
15005
15006 #[cfg(feature = "test-support")]
15007 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15008 let snapshot = self.buffer().read(cx).snapshot(cx);
15009
15010 let highlights = self
15011 .background_highlights
15012 .get(&TypeId::of::<items::BufferSearchHighlights>());
15013
15014 if let Some((_color, ranges)) = highlights {
15015 ranges
15016 .iter()
15017 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15018 .collect_vec()
15019 } else {
15020 vec![]
15021 }
15022 }
15023
15024 fn document_highlights_for_position<'a>(
15025 &'a self,
15026 position: Anchor,
15027 buffer: &'a MultiBufferSnapshot,
15028 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15029 let read_highlights = self
15030 .background_highlights
15031 .get(&TypeId::of::<DocumentHighlightRead>())
15032 .map(|h| &h.1);
15033 let write_highlights = self
15034 .background_highlights
15035 .get(&TypeId::of::<DocumentHighlightWrite>())
15036 .map(|h| &h.1);
15037 let left_position = position.bias_left(buffer);
15038 let right_position = position.bias_right(buffer);
15039 read_highlights
15040 .into_iter()
15041 .chain(write_highlights)
15042 .flat_map(move |ranges| {
15043 let start_ix = match ranges.binary_search_by(|probe| {
15044 let cmp = probe.end.cmp(&left_position, buffer);
15045 if cmp.is_ge() {
15046 Ordering::Greater
15047 } else {
15048 Ordering::Less
15049 }
15050 }) {
15051 Ok(i) | Err(i) => i,
15052 };
15053
15054 ranges[start_ix..]
15055 .iter()
15056 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15057 })
15058 }
15059
15060 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15061 self.background_highlights
15062 .get(&TypeId::of::<T>())
15063 .map_or(false, |(_, highlights)| !highlights.is_empty())
15064 }
15065
15066 pub fn background_highlights_in_range(
15067 &self,
15068 search_range: Range<Anchor>,
15069 display_snapshot: &DisplaySnapshot,
15070 theme: &ThemeColors,
15071 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15072 let mut results = Vec::new();
15073 for (color_fetcher, ranges) in self.background_highlights.values() {
15074 let color = color_fetcher(theme);
15075 let start_ix = match ranges.binary_search_by(|probe| {
15076 let cmp = probe
15077 .end
15078 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15079 if cmp.is_gt() {
15080 Ordering::Greater
15081 } else {
15082 Ordering::Less
15083 }
15084 }) {
15085 Ok(i) | Err(i) => i,
15086 };
15087 for range in &ranges[start_ix..] {
15088 if range
15089 .start
15090 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15091 .is_ge()
15092 {
15093 break;
15094 }
15095
15096 let start = range.start.to_display_point(display_snapshot);
15097 let end = range.end.to_display_point(display_snapshot);
15098 results.push((start..end, color))
15099 }
15100 }
15101 results
15102 }
15103
15104 pub fn background_highlight_row_ranges<T: 'static>(
15105 &self,
15106 search_range: Range<Anchor>,
15107 display_snapshot: &DisplaySnapshot,
15108 count: usize,
15109 ) -> Vec<RangeInclusive<DisplayPoint>> {
15110 let mut results = Vec::new();
15111 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15112 return vec![];
15113 };
15114
15115 let start_ix = match ranges.binary_search_by(|probe| {
15116 let cmp = probe
15117 .end
15118 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15119 if cmp.is_gt() {
15120 Ordering::Greater
15121 } else {
15122 Ordering::Less
15123 }
15124 }) {
15125 Ok(i) | Err(i) => i,
15126 };
15127 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15128 if let (Some(start_display), Some(end_display)) = (start, end) {
15129 results.push(
15130 start_display.to_display_point(display_snapshot)
15131 ..=end_display.to_display_point(display_snapshot),
15132 );
15133 }
15134 };
15135 let mut start_row: Option<Point> = None;
15136 let mut end_row: Option<Point> = None;
15137 if ranges.len() > count {
15138 return Vec::new();
15139 }
15140 for range in &ranges[start_ix..] {
15141 if range
15142 .start
15143 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15144 .is_ge()
15145 {
15146 break;
15147 }
15148 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15149 if let Some(current_row) = &end_row {
15150 if end.row == current_row.row {
15151 continue;
15152 }
15153 }
15154 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15155 if start_row.is_none() {
15156 assert_eq!(end_row, None);
15157 start_row = Some(start);
15158 end_row = Some(end);
15159 continue;
15160 }
15161 if let Some(current_end) = end_row.as_mut() {
15162 if start.row > current_end.row + 1 {
15163 push_region(start_row, end_row);
15164 start_row = Some(start);
15165 end_row = Some(end);
15166 } else {
15167 // Merge two hunks.
15168 *current_end = end;
15169 }
15170 } else {
15171 unreachable!();
15172 }
15173 }
15174 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15175 push_region(start_row, end_row);
15176 results
15177 }
15178
15179 pub fn gutter_highlights_in_range(
15180 &self,
15181 search_range: Range<Anchor>,
15182 display_snapshot: &DisplaySnapshot,
15183 cx: &App,
15184 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15185 let mut results = Vec::new();
15186 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15187 let color = color_fetcher(cx);
15188 let start_ix = match ranges.binary_search_by(|probe| {
15189 let cmp = probe
15190 .end
15191 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15192 if cmp.is_gt() {
15193 Ordering::Greater
15194 } else {
15195 Ordering::Less
15196 }
15197 }) {
15198 Ok(i) | Err(i) => i,
15199 };
15200 for range in &ranges[start_ix..] {
15201 if range
15202 .start
15203 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15204 .is_ge()
15205 {
15206 break;
15207 }
15208
15209 let start = range.start.to_display_point(display_snapshot);
15210 let end = range.end.to_display_point(display_snapshot);
15211 results.push((start..end, color))
15212 }
15213 }
15214 results
15215 }
15216
15217 /// Get the text ranges corresponding to the redaction query
15218 pub fn redacted_ranges(
15219 &self,
15220 search_range: Range<Anchor>,
15221 display_snapshot: &DisplaySnapshot,
15222 cx: &App,
15223 ) -> Vec<Range<DisplayPoint>> {
15224 display_snapshot
15225 .buffer_snapshot
15226 .redacted_ranges(search_range, |file| {
15227 if let Some(file) = file {
15228 file.is_private()
15229 && EditorSettings::get(
15230 Some(SettingsLocation {
15231 worktree_id: file.worktree_id(cx),
15232 path: file.path().as_ref(),
15233 }),
15234 cx,
15235 )
15236 .redact_private_values
15237 } else {
15238 false
15239 }
15240 })
15241 .map(|range| {
15242 range.start.to_display_point(display_snapshot)
15243 ..range.end.to_display_point(display_snapshot)
15244 })
15245 .collect()
15246 }
15247
15248 pub fn highlight_text<T: 'static>(
15249 &mut self,
15250 ranges: Vec<Range<Anchor>>,
15251 style: HighlightStyle,
15252 cx: &mut Context<Self>,
15253 ) {
15254 self.display_map.update(cx, |map, _| {
15255 map.highlight_text(TypeId::of::<T>(), ranges, style)
15256 });
15257 cx.notify();
15258 }
15259
15260 pub(crate) fn highlight_inlays<T: 'static>(
15261 &mut self,
15262 highlights: Vec<InlayHighlight>,
15263 style: HighlightStyle,
15264 cx: &mut Context<Self>,
15265 ) {
15266 self.display_map.update(cx, |map, _| {
15267 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15268 });
15269 cx.notify();
15270 }
15271
15272 pub fn text_highlights<'a, T: 'static>(
15273 &'a self,
15274 cx: &'a App,
15275 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15276 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15277 }
15278
15279 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15280 let cleared = self
15281 .display_map
15282 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15283 if cleared {
15284 cx.notify();
15285 }
15286 }
15287
15288 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15289 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15290 && self.focus_handle.is_focused(window)
15291 }
15292
15293 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15294 self.show_cursor_when_unfocused = is_enabled;
15295 cx.notify();
15296 }
15297
15298 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15299 cx.notify();
15300 }
15301
15302 fn on_buffer_event(
15303 &mut self,
15304 multibuffer: &Entity<MultiBuffer>,
15305 event: &multi_buffer::Event,
15306 window: &mut Window,
15307 cx: &mut Context<Self>,
15308 ) {
15309 match event {
15310 multi_buffer::Event::Edited {
15311 singleton_buffer_edited,
15312 edited_buffer: buffer_edited,
15313 } => {
15314 self.scrollbar_marker_state.dirty = true;
15315 self.active_indent_guides_state.dirty = true;
15316 self.refresh_active_diagnostics(cx);
15317 self.refresh_code_actions(window, cx);
15318 if self.has_active_inline_completion() {
15319 self.update_visible_inline_completion(window, cx);
15320 }
15321 if let Some(buffer) = buffer_edited {
15322 let buffer_id = buffer.read(cx).remote_id();
15323 if !self.registered_buffers.contains_key(&buffer_id) {
15324 if let Some(project) = self.project.as_ref() {
15325 project.update(cx, |project, cx| {
15326 self.registered_buffers.insert(
15327 buffer_id,
15328 project.register_buffer_with_language_servers(&buffer, cx),
15329 );
15330 })
15331 }
15332 }
15333 }
15334 cx.emit(EditorEvent::BufferEdited);
15335 cx.emit(SearchEvent::MatchesInvalidated);
15336 if *singleton_buffer_edited {
15337 if let Some(project) = &self.project {
15338 #[allow(clippy::mutable_key_type)]
15339 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15340 multibuffer
15341 .all_buffers()
15342 .into_iter()
15343 .filter_map(|buffer| {
15344 buffer.update(cx, |buffer, cx| {
15345 let language = buffer.language()?;
15346 let should_discard = project.update(cx, |project, cx| {
15347 project.is_local()
15348 && !project.has_language_servers_for(buffer, cx)
15349 });
15350 should_discard.not().then_some(language.clone())
15351 })
15352 })
15353 .collect::<HashSet<_>>()
15354 });
15355 if !languages_affected.is_empty() {
15356 self.refresh_inlay_hints(
15357 InlayHintRefreshReason::BufferEdited(languages_affected),
15358 cx,
15359 );
15360 }
15361 }
15362 }
15363
15364 let Some(project) = &self.project else { return };
15365 let (telemetry, is_via_ssh) = {
15366 let project = project.read(cx);
15367 let telemetry = project.client().telemetry().clone();
15368 let is_via_ssh = project.is_via_ssh();
15369 (telemetry, is_via_ssh)
15370 };
15371 refresh_linked_ranges(self, window, cx);
15372 telemetry.log_edit_event("editor", is_via_ssh);
15373 }
15374 multi_buffer::Event::ExcerptsAdded {
15375 buffer,
15376 predecessor,
15377 excerpts,
15378 } => {
15379 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15380 let buffer_id = buffer.read(cx).remote_id();
15381 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15382 if let Some(project) = &self.project {
15383 get_uncommitted_diff_for_buffer(
15384 project,
15385 [buffer.clone()],
15386 self.buffer.clone(),
15387 cx,
15388 )
15389 .detach();
15390 }
15391 }
15392 cx.emit(EditorEvent::ExcerptsAdded {
15393 buffer: buffer.clone(),
15394 predecessor: *predecessor,
15395 excerpts: excerpts.clone(),
15396 });
15397 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15398 }
15399 multi_buffer::Event::ExcerptsRemoved { ids } => {
15400 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15401 let buffer = self.buffer.read(cx);
15402 self.registered_buffers
15403 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15404 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15405 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15406 }
15407 multi_buffer::Event::ExcerptsEdited {
15408 excerpt_ids,
15409 buffer_ids,
15410 } => {
15411 self.display_map.update(cx, |map, cx| {
15412 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15413 });
15414 cx.emit(EditorEvent::ExcerptsEdited {
15415 ids: excerpt_ids.clone(),
15416 })
15417 }
15418 multi_buffer::Event::ExcerptsExpanded { ids } => {
15419 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15420 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15421 }
15422 multi_buffer::Event::Reparsed(buffer_id) => {
15423 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15424 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15425
15426 cx.emit(EditorEvent::Reparsed(*buffer_id));
15427 }
15428 multi_buffer::Event::DiffHunksToggled => {
15429 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15430 }
15431 multi_buffer::Event::LanguageChanged(buffer_id) => {
15432 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15433 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15434 cx.emit(EditorEvent::Reparsed(*buffer_id));
15435 cx.notify();
15436 }
15437 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15438 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15439 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15440 cx.emit(EditorEvent::TitleChanged)
15441 }
15442 // multi_buffer::Event::DiffBaseChanged => {
15443 // self.scrollbar_marker_state.dirty = true;
15444 // cx.emit(EditorEvent::DiffBaseChanged);
15445 // cx.notify();
15446 // }
15447 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15448 multi_buffer::Event::DiagnosticsUpdated => {
15449 self.refresh_active_diagnostics(cx);
15450 self.refresh_inline_diagnostics(true, window, cx);
15451 self.scrollbar_marker_state.dirty = true;
15452 cx.notify();
15453 }
15454 _ => {}
15455 };
15456 }
15457
15458 fn on_display_map_changed(
15459 &mut self,
15460 _: Entity<DisplayMap>,
15461 _: &mut Window,
15462 cx: &mut Context<Self>,
15463 ) {
15464 cx.notify();
15465 }
15466
15467 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15468 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15469 self.update_edit_prediction_settings(cx);
15470 self.refresh_inline_completion(true, false, window, cx);
15471 self.refresh_inlay_hints(
15472 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15473 self.selections.newest_anchor().head(),
15474 &self.buffer.read(cx).snapshot(cx),
15475 cx,
15476 )),
15477 cx,
15478 );
15479
15480 let old_cursor_shape = self.cursor_shape;
15481
15482 {
15483 let editor_settings = EditorSettings::get_global(cx);
15484 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15485 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15486 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15487 }
15488
15489 if old_cursor_shape != self.cursor_shape {
15490 cx.emit(EditorEvent::CursorShapeChanged);
15491 }
15492
15493 let project_settings = ProjectSettings::get_global(cx);
15494 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15495
15496 if self.mode == EditorMode::Full {
15497 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15498 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15499 if self.show_inline_diagnostics != show_inline_diagnostics {
15500 self.show_inline_diagnostics = show_inline_diagnostics;
15501 self.refresh_inline_diagnostics(false, window, cx);
15502 }
15503
15504 if self.git_blame_inline_enabled != inline_blame_enabled {
15505 self.toggle_git_blame_inline_internal(false, window, cx);
15506 }
15507 }
15508
15509 cx.notify();
15510 }
15511
15512 pub fn set_searchable(&mut self, searchable: bool) {
15513 self.searchable = searchable;
15514 }
15515
15516 pub fn searchable(&self) -> bool {
15517 self.searchable
15518 }
15519
15520 fn open_proposed_changes_editor(
15521 &mut self,
15522 _: &OpenProposedChangesEditor,
15523 window: &mut Window,
15524 cx: &mut Context<Self>,
15525 ) {
15526 let Some(workspace) = self.workspace() else {
15527 cx.propagate();
15528 return;
15529 };
15530
15531 let selections = self.selections.all::<usize>(cx);
15532 let multi_buffer = self.buffer.read(cx);
15533 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15534 let mut new_selections_by_buffer = HashMap::default();
15535 for selection in selections {
15536 for (buffer, range, _) in
15537 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15538 {
15539 let mut range = range.to_point(buffer);
15540 range.start.column = 0;
15541 range.end.column = buffer.line_len(range.end.row);
15542 new_selections_by_buffer
15543 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15544 .or_insert(Vec::new())
15545 .push(range)
15546 }
15547 }
15548
15549 let proposed_changes_buffers = new_selections_by_buffer
15550 .into_iter()
15551 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15552 .collect::<Vec<_>>();
15553 let proposed_changes_editor = cx.new(|cx| {
15554 ProposedChangesEditor::new(
15555 "Proposed changes",
15556 proposed_changes_buffers,
15557 self.project.clone(),
15558 window,
15559 cx,
15560 )
15561 });
15562
15563 window.defer(cx, move |window, cx| {
15564 workspace.update(cx, |workspace, cx| {
15565 workspace.active_pane().update(cx, |pane, cx| {
15566 pane.add_item(
15567 Box::new(proposed_changes_editor),
15568 true,
15569 true,
15570 None,
15571 window,
15572 cx,
15573 );
15574 });
15575 });
15576 });
15577 }
15578
15579 pub fn open_excerpts_in_split(
15580 &mut self,
15581 _: &OpenExcerptsSplit,
15582 window: &mut Window,
15583 cx: &mut Context<Self>,
15584 ) {
15585 self.open_excerpts_common(None, true, window, cx)
15586 }
15587
15588 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15589 self.open_excerpts_common(None, false, window, cx)
15590 }
15591
15592 fn open_excerpts_common(
15593 &mut self,
15594 jump_data: Option<JumpData>,
15595 split: bool,
15596 window: &mut Window,
15597 cx: &mut Context<Self>,
15598 ) {
15599 let Some(workspace) = self.workspace() else {
15600 cx.propagate();
15601 return;
15602 };
15603
15604 if self.buffer.read(cx).is_singleton() {
15605 cx.propagate();
15606 return;
15607 }
15608
15609 let mut new_selections_by_buffer = HashMap::default();
15610 match &jump_data {
15611 Some(JumpData::MultiBufferPoint {
15612 excerpt_id,
15613 position,
15614 anchor,
15615 line_offset_from_top,
15616 }) => {
15617 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15618 if let Some(buffer) = multi_buffer_snapshot
15619 .buffer_id_for_excerpt(*excerpt_id)
15620 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15621 {
15622 let buffer_snapshot = buffer.read(cx).snapshot();
15623 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15624 language::ToPoint::to_point(anchor, &buffer_snapshot)
15625 } else {
15626 buffer_snapshot.clip_point(*position, Bias::Left)
15627 };
15628 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15629 new_selections_by_buffer.insert(
15630 buffer,
15631 (
15632 vec![jump_to_offset..jump_to_offset],
15633 Some(*line_offset_from_top),
15634 ),
15635 );
15636 }
15637 }
15638 Some(JumpData::MultiBufferRow {
15639 row,
15640 line_offset_from_top,
15641 }) => {
15642 let point = MultiBufferPoint::new(row.0, 0);
15643 if let Some((buffer, buffer_point, _)) =
15644 self.buffer.read(cx).point_to_buffer_point(point, cx)
15645 {
15646 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15647 new_selections_by_buffer
15648 .entry(buffer)
15649 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15650 .0
15651 .push(buffer_offset..buffer_offset)
15652 }
15653 }
15654 None => {
15655 let selections = self.selections.all::<usize>(cx);
15656 let multi_buffer = self.buffer.read(cx);
15657 for selection in selections {
15658 for (snapshot, range, _, anchor) in multi_buffer
15659 .snapshot(cx)
15660 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15661 {
15662 if let Some(anchor) = anchor {
15663 // selection is in a deleted hunk
15664 let Some(buffer_id) = anchor.buffer_id else {
15665 continue;
15666 };
15667 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15668 continue;
15669 };
15670 let offset = text::ToOffset::to_offset(
15671 &anchor.text_anchor,
15672 &buffer_handle.read(cx).snapshot(),
15673 );
15674 let range = offset..offset;
15675 new_selections_by_buffer
15676 .entry(buffer_handle)
15677 .or_insert((Vec::new(), None))
15678 .0
15679 .push(range)
15680 } else {
15681 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15682 else {
15683 continue;
15684 };
15685 new_selections_by_buffer
15686 .entry(buffer_handle)
15687 .or_insert((Vec::new(), None))
15688 .0
15689 .push(range)
15690 }
15691 }
15692 }
15693 }
15694 }
15695
15696 if new_selections_by_buffer.is_empty() {
15697 return;
15698 }
15699
15700 // We defer the pane interaction because we ourselves are a workspace item
15701 // and activating a new item causes the pane to call a method on us reentrantly,
15702 // which panics if we're on the stack.
15703 window.defer(cx, move |window, cx| {
15704 workspace.update(cx, |workspace, cx| {
15705 let pane = if split {
15706 workspace.adjacent_pane(window, cx)
15707 } else {
15708 workspace.active_pane().clone()
15709 };
15710
15711 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15712 let editor = buffer
15713 .read(cx)
15714 .file()
15715 .is_none()
15716 .then(|| {
15717 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15718 // so `workspace.open_project_item` will never find them, always opening a new editor.
15719 // Instead, we try to activate the existing editor in the pane first.
15720 let (editor, pane_item_index) =
15721 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15722 let editor = item.downcast::<Editor>()?;
15723 let singleton_buffer =
15724 editor.read(cx).buffer().read(cx).as_singleton()?;
15725 if singleton_buffer == buffer {
15726 Some((editor, i))
15727 } else {
15728 None
15729 }
15730 })?;
15731 pane.update(cx, |pane, cx| {
15732 pane.activate_item(pane_item_index, true, true, window, cx)
15733 });
15734 Some(editor)
15735 })
15736 .flatten()
15737 .unwrap_or_else(|| {
15738 workspace.open_project_item::<Self>(
15739 pane.clone(),
15740 buffer,
15741 true,
15742 true,
15743 window,
15744 cx,
15745 )
15746 });
15747
15748 editor.update(cx, |editor, cx| {
15749 let autoscroll = match scroll_offset {
15750 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15751 None => Autoscroll::newest(),
15752 };
15753 let nav_history = editor.nav_history.take();
15754 editor.change_selections(Some(autoscroll), window, cx, |s| {
15755 s.select_ranges(ranges);
15756 });
15757 editor.nav_history = nav_history;
15758 });
15759 }
15760 })
15761 });
15762 }
15763
15764 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15765 let snapshot = self.buffer.read(cx).read(cx);
15766 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15767 Some(
15768 ranges
15769 .iter()
15770 .map(move |range| {
15771 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15772 })
15773 .collect(),
15774 )
15775 }
15776
15777 fn selection_replacement_ranges(
15778 &self,
15779 range: Range<OffsetUtf16>,
15780 cx: &mut App,
15781 ) -> Vec<Range<OffsetUtf16>> {
15782 let selections = self.selections.all::<OffsetUtf16>(cx);
15783 let newest_selection = selections
15784 .iter()
15785 .max_by_key(|selection| selection.id)
15786 .unwrap();
15787 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15788 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15789 let snapshot = self.buffer.read(cx).read(cx);
15790 selections
15791 .into_iter()
15792 .map(|mut selection| {
15793 selection.start.0 =
15794 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15795 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15796 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15797 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15798 })
15799 .collect()
15800 }
15801
15802 fn report_editor_event(
15803 &self,
15804 event_type: &'static str,
15805 file_extension: Option<String>,
15806 cx: &App,
15807 ) {
15808 if cfg!(any(test, feature = "test-support")) {
15809 return;
15810 }
15811
15812 let Some(project) = &self.project else { return };
15813
15814 // If None, we are in a file without an extension
15815 let file = self
15816 .buffer
15817 .read(cx)
15818 .as_singleton()
15819 .and_then(|b| b.read(cx).file());
15820 let file_extension = file_extension.or(file
15821 .as_ref()
15822 .and_then(|file| Path::new(file.file_name(cx)).extension())
15823 .and_then(|e| e.to_str())
15824 .map(|a| a.to_string()));
15825
15826 let vim_mode = cx
15827 .global::<SettingsStore>()
15828 .raw_user_settings()
15829 .get("vim_mode")
15830 == Some(&serde_json::Value::Bool(true));
15831
15832 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15833 let copilot_enabled = edit_predictions_provider
15834 == language::language_settings::EditPredictionProvider::Copilot;
15835 let copilot_enabled_for_language = self
15836 .buffer
15837 .read(cx)
15838 .language_settings(cx)
15839 .show_edit_predictions;
15840
15841 let project = project.read(cx);
15842 telemetry::event!(
15843 event_type,
15844 file_extension,
15845 vim_mode,
15846 copilot_enabled,
15847 copilot_enabled_for_language,
15848 edit_predictions_provider,
15849 is_via_ssh = project.is_via_ssh(),
15850 );
15851 }
15852
15853 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15854 /// with each line being an array of {text, highlight} objects.
15855 fn copy_highlight_json(
15856 &mut self,
15857 _: &CopyHighlightJson,
15858 window: &mut Window,
15859 cx: &mut Context<Self>,
15860 ) {
15861 #[derive(Serialize)]
15862 struct Chunk<'a> {
15863 text: String,
15864 highlight: Option<&'a str>,
15865 }
15866
15867 let snapshot = self.buffer.read(cx).snapshot(cx);
15868 let range = self
15869 .selected_text_range(false, window, cx)
15870 .and_then(|selection| {
15871 if selection.range.is_empty() {
15872 None
15873 } else {
15874 Some(selection.range)
15875 }
15876 })
15877 .unwrap_or_else(|| 0..snapshot.len());
15878
15879 let chunks = snapshot.chunks(range, true);
15880 let mut lines = Vec::new();
15881 let mut line: VecDeque<Chunk> = VecDeque::new();
15882
15883 let Some(style) = self.style.as_ref() else {
15884 return;
15885 };
15886
15887 for chunk in chunks {
15888 let highlight = chunk
15889 .syntax_highlight_id
15890 .and_then(|id| id.name(&style.syntax));
15891 let mut chunk_lines = chunk.text.split('\n').peekable();
15892 while let Some(text) = chunk_lines.next() {
15893 let mut merged_with_last_token = false;
15894 if let Some(last_token) = line.back_mut() {
15895 if last_token.highlight == highlight {
15896 last_token.text.push_str(text);
15897 merged_with_last_token = true;
15898 }
15899 }
15900
15901 if !merged_with_last_token {
15902 line.push_back(Chunk {
15903 text: text.into(),
15904 highlight,
15905 });
15906 }
15907
15908 if chunk_lines.peek().is_some() {
15909 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15910 line.pop_front();
15911 }
15912 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15913 line.pop_back();
15914 }
15915
15916 lines.push(mem::take(&mut line));
15917 }
15918 }
15919 }
15920
15921 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15922 return;
15923 };
15924 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15925 }
15926
15927 pub fn open_context_menu(
15928 &mut self,
15929 _: &OpenContextMenu,
15930 window: &mut Window,
15931 cx: &mut Context<Self>,
15932 ) {
15933 self.request_autoscroll(Autoscroll::newest(), cx);
15934 let position = self.selections.newest_display(cx).start;
15935 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15936 }
15937
15938 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15939 &self.inlay_hint_cache
15940 }
15941
15942 pub fn replay_insert_event(
15943 &mut self,
15944 text: &str,
15945 relative_utf16_range: Option<Range<isize>>,
15946 window: &mut Window,
15947 cx: &mut Context<Self>,
15948 ) {
15949 if !self.input_enabled {
15950 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15951 return;
15952 }
15953 if let Some(relative_utf16_range) = relative_utf16_range {
15954 let selections = self.selections.all::<OffsetUtf16>(cx);
15955 self.change_selections(None, window, cx, |s| {
15956 let new_ranges = selections.into_iter().map(|range| {
15957 let start = OffsetUtf16(
15958 range
15959 .head()
15960 .0
15961 .saturating_add_signed(relative_utf16_range.start),
15962 );
15963 let end = OffsetUtf16(
15964 range
15965 .head()
15966 .0
15967 .saturating_add_signed(relative_utf16_range.end),
15968 );
15969 start..end
15970 });
15971 s.select_ranges(new_ranges);
15972 });
15973 }
15974
15975 self.handle_input(text, window, cx);
15976 }
15977
15978 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15979 let Some(provider) = self.semantics_provider.as_ref() else {
15980 return false;
15981 };
15982
15983 let mut supports = false;
15984 self.buffer().update(cx, |this, cx| {
15985 this.for_each_buffer(|buffer| {
15986 supports |= provider.supports_inlay_hints(buffer, cx);
15987 });
15988 });
15989
15990 supports
15991 }
15992
15993 pub fn is_focused(&self, window: &Window) -> bool {
15994 self.focus_handle.is_focused(window)
15995 }
15996
15997 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15998 cx.emit(EditorEvent::Focused);
15999
16000 if let Some(descendant) = self
16001 .last_focused_descendant
16002 .take()
16003 .and_then(|descendant| descendant.upgrade())
16004 {
16005 window.focus(&descendant);
16006 } else {
16007 if let Some(blame) = self.blame.as_ref() {
16008 blame.update(cx, GitBlame::focus)
16009 }
16010
16011 self.blink_manager.update(cx, BlinkManager::enable);
16012 self.show_cursor_names(window, cx);
16013 self.buffer.update(cx, |buffer, cx| {
16014 buffer.finalize_last_transaction(cx);
16015 if self.leader_peer_id.is_none() {
16016 buffer.set_active_selections(
16017 &self.selections.disjoint_anchors(),
16018 self.selections.line_mode,
16019 self.cursor_shape,
16020 cx,
16021 );
16022 }
16023 });
16024 }
16025 }
16026
16027 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16028 cx.emit(EditorEvent::FocusedIn)
16029 }
16030
16031 fn handle_focus_out(
16032 &mut self,
16033 event: FocusOutEvent,
16034 _window: &mut Window,
16035 cx: &mut Context<Self>,
16036 ) {
16037 if event.blurred != self.focus_handle {
16038 self.last_focused_descendant = Some(event.blurred);
16039 }
16040 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16041 }
16042
16043 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16044 self.blink_manager.update(cx, BlinkManager::disable);
16045 self.buffer
16046 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16047
16048 if let Some(blame) = self.blame.as_ref() {
16049 blame.update(cx, GitBlame::blur)
16050 }
16051 if !self.hover_state.focused(window, cx) {
16052 hide_hover(self, cx);
16053 }
16054 if !self
16055 .context_menu
16056 .borrow()
16057 .as_ref()
16058 .is_some_and(|context_menu| context_menu.focused(window, cx))
16059 {
16060 self.hide_context_menu(window, cx);
16061 }
16062 self.discard_inline_completion(false, cx);
16063 cx.emit(EditorEvent::Blurred);
16064 cx.notify();
16065 }
16066
16067 pub fn register_action<A: Action>(
16068 &mut self,
16069 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16070 ) -> Subscription {
16071 let id = self.next_editor_action_id.post_inc();
16072 let listener = Arc::new(listener);
16073 self.editor_actions.borrow_mut().insert(
16074 id,
16075 Box::new(move |window, _| {
16076 let listener = listener.clone();
16077 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16078 let action = action.downcast_ref().unwrap();
16079 if phase == DispatchPhase::Bubble {
16080 listener(action, window, cx)
16081 }
16082 })
16083 }),
16084 );
16085
16086 let editor_actions = self.editor_actions.clone();
16087 Subscription::new(move || {
16088 editor_actions.borrow_mut().remove(&id);
16089 })
16090 }
16091
16092 pub fn file_header_size(&self) -> u32 {
16093 FILE_HEADER_HEIGHT
16094 }
16095
16096 pub fn restore(
16097 &mut self,
16098 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16099 window: &mut Window,
16100 cx: &mut Context<Self>,
16101 ) {
16102 let workspace = self.workspace();
16103 let project = self.project.as_ref();
16104 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16105 let mut tasks = Vec::new();
16106 for (buffer_id, changes) in revert_changes {
16107 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16108 buffer.update(cx, |buffer, cx| {
16109 buffer.edit(
16110 changes
16111 .into_iter()
16112 .map(|(range, text)| (range, text.to_string())),
16113 None,
16114 cx,
16115 );
16116 });
16117
16118 if let Some(project) =
16119 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16120 {
16121 project.update(cx, |project, cx| {
16122 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16123 })
16124 }
16125 }
16126 }
16127 tasks
16128 });
16129 cx.spawn_in(window, |_, mut cx| async move {
16130 for (buffer, task) in save_tasks {
16131 let result = task.await;
16132 if result.is_err() {
16133 let Some(path) = buffer
16134 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16135 .ok()
16136 else {
16137 continue;
16138 };
16139 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16140 let Some(task) = cx
16141 .update_window_entity(&workspace, |workspace, window, cx| {
16142 workspace
16143 .open_path_preview(path, None, false, false, false, window, cx)
16144 })
16145 .ok()
16146 else {
16147 continue;
16148 };
16149 task.await.log_err();
16150 }
16151 }
16152 }
16153 })
16154 .detach();
16155 self.change_selections(None, window, cx, |selections| selections.refresh());
16156 }
16157
16158 pub fn to_pixel_point(
16159 &self,
16160 source: multi_buffer::Anchor,
16161 editor_snapshot: &EditorSnapshot,
16162 window: &mut Window,
16163 ) -> Option<gpui::Point<Pixels>> {
16164 let source_point = source.to_display_point(editor_snapshot);
16165 self.display_to_pixel_point(source_point, editor_snapshot, window)
16166 }
16167
16168 pub fn display_to_pixel_point(
16169 &self,
16170 source: DisplayPoint,
16171 editor_snapshot: &EditorSnapshot,
16172 window: &mut Window,
16173 ) -> Option<gpui::Point<Pixels>> {
16174 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16175 let text_layout_details = self.text_layout_details(window);
16176 let scroll_top = text_layout_details
16177 .scroll_anchor
16178 .scroll_position(editor_snapshot)
16179 .y;
16180
16181 if source.row().as_f32() < scroll_top.floor() {
16182 return None;
16183 }
16184 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16185 let source_y = line_height * (source.row().as_f32() - scroll_top);
16186 Some(gpui::Point::new(source_x, source_y))
16187 }
16188
16189 pub fn has_visible_completions_menu(&self) -> bool {
16190 !self.edit_prediction_preview_is_active()
16191 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16192 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16193 })
16194 }
16195
16196 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16197 self.addons
16198 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16199 }
16200
16201 pub fn unregister_addon<T: Addon>(&mut self) {
16202 self.addons.remove(&std::any::TypeId::of::<T>());
16203 }
16204
16205 pub fn addon<T: Addon>(&self) -> Option<&T> {
16206 let type_id = std::any::TypeId::of::<T>();
16207 self.addons
16208 .get(&type_id)
16209 .and_then(|item| item.to_any().downcast_ref::<T>())
16210 }
16211
16212 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16213 let text_layout_details = self.text_layout_details(window);
16214 let style = &text_layout_details.editor_style;
16215 let font_id = window.text_system().resolve_font(&style.text.font());
16216 let font_size = style.text.font_size.to_pixels(window.rem_size());
16217 let line_height = style.text.line_height_in_pixels(window.rem_size());
16218 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16219
16220 gpui::Size::new(em_width, line_height)
16221 }
16222
16223 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16224 self.load_diff_task.clone()
16225 }
16226
16227 fn read_selections_from_db(
16228 &mut self,
16229 item_id: u64,
16230 workspace_id: WorkspaceId,
16231 window: &mut Window,
16232 cx: &mut Context<Editor>,
16233 ) {
16234 if !self.is_singleton(cx)
16235 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16236 {
16237 return;
16238 }
16239 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16240 return;
16241 };
16242 if selections.is_empty() {
16243 return;
16244 }
16245
16246 let snapshot = self.buffer.read(cx).snapshot(cx);
16247 self.change_selections(None, window, cx, |s| {
16248 s.select_ranges(selections.into_iter().map(|(start, end)| {
16249 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16250 }));
16251 });
16252 }
16253}
16254
16255fn insert_extra_newline_brackets(
16256 buffer: &MultiBufferSnapshot,
16257 range: Range<usize>,
16258 language: &language::LanguageScope,
16259) -> bool {
16260 let leading_whitespace_len = buffer
16261 .reversed_chars_at(range.start)
16262 .take_while(|c| c.is_whitespace() && *c != '\n')
16263 .map(|c| c.len_utf8())
16264 .sum::<usize>();
16265 let trailing_whitespace_len = buffer
16266 .chars_at(range.end)
16267 .take_while(|c| c.is_whitespace() && *c != '\n')
16268 .map(|c| c.len_utf8())
16269 .sum::<usize>();
16270 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16271
16272 language.brackets().any(|(pair, enabled)| {
16273 let pair_start = pair.start.trim_end();
16274 let pair_end = pair.end.trim_start();
16275
16276 enabled
16277 && pair.newline
16278 && buffer.contains_str_at(range.end, pair_end)
16279 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16280 })
16281}
16282
16283fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16284 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16285 [(buffer, range, _)] => (*buffer, range.clone()),
16286 _ => return false,
16287 };
16288 let pair = {
16289 let mut result: Option<BracketMatch> = None;
16290
16291 for pair in buffer
16292 .all_bracket_ranges(range.clone())
16293 .filter(move |pair| {
16294 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16295 })
16296 {
16297 let len = pair.close_range.end - pair.open_range.start;
16298
16299 if let Some(existing) = &result {
16300 let existing_len = existing.close_range.end - existing.open_range.start;
16301 if len > existing_len {
16302 continue;
16303 }
16304 }
16305
16306 result = Some(pair);
16307 }
16308
16309 result
16310 };
16311 let Some(pair) = pair else {
16312 return false;
16313 };
16314 pair.newline_only
16315 && buffer
16316 .chars_for_range(pair.open_range.end..range.start)
16317 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16318 .all(|c| c.is_whitespace() && c != '\n')
16319}
16320
16321fn get_uncommitted_diff_for_buffer(
16322 project: &Entity<Project>,
16323 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16324 buffer: Entity<MultiBuffer>,
16325 cx: &mut App,
16326) -> Task<()> {
16327 let mut tasks = Vec::new();
16328 project.update(cx, |project, cx| {
16329 for buffer in buffers {
16330 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16331 }
16332 });
16333 cx.spawn(|mut cx| async move {
16334 let diffs = future::join_all(tasks).await;
16335 buffer
16336 .update(&mut cx, |buffer, cx| {
16337 for diff in diffs.into_iter().flatten() {
16338 buffer.add_diff(diff, cx);
16339 }
16340 })
16341 .ok();
16342 })
16343}
16344
16345fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16346 let tab_size = tab_size.get() as usize;
16347 let mut width = offset;
16348
16349 for ch in text.chars() {
16350 width += if ch == '\t' {
16351 tab_size - (width % tab_size)
16352 } else {
16353 1
16354 };
16355 }
16356
16357 width - offset
16358}
16359
16360#[cfg(test)]
16361mod tests {
16362 use super::*;
16363
16364 #[test]
16365 fn test_string_size_with_expanded_tabs() {
16366 let nz = |val| NonZeroU32::new(val).unwrap();
16367 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16368 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16369 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16370 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16371 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16372 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16373 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16374 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16375 }
16376}
16377
16378/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16379struct WordBreakingTokenizer<'a> {
16380 input: &'a str,
16381}
16382
16383impl<'a> WordBreakingTokenizer<'a> {
16384 fn new(input: &'a str) -> Self {
16385 Self { input }
16386 }
16387}
16388
16389fn is_char_ideographic(ch: char) -> bool {
16390 use unicode_script::Script::*;
16391 use unicode_script::UnicodeScript;
16392 matches!(ch.script(), Han | Tangut | Yi)
16393}
16394
16395fn is_grapheme_ideographic(text: &str) -> bool {
16396 text.chars().any(is_char_ideographic)
16397}
16398
16399fn is_grapheme_whitespace(text: &str) -> bool {
16400 text.chars().any(|x| x.is_whitespace())
16401}
16402
16403fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16404 text.chars().next().map_or(false, |ch| {
16405 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16406 })
16407}
16408
16409#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16410struct WordBreakToken<'a> {
16411 token: &'a str,
16412 grapheme_len: usize,
16413 is_whitespace: bool,
16414}
16415
16416impl<'a> Iterator for WordBreakingTokenizer<'a> {
16417 /// Yields a span, the count of graphemes in the token, and whether it was
16418 /// whitespace. Note that it also breaks at word boundaries.
16419 type Item = WordBreakToken<'a>;
16420
16421 fn next(&mut self) -> Option<Self::Item> {
16422 use unicode_segmentation::UnicodeSegmentation;
16423 if self.input.is_empty() {
16424 return None;
16425 }
16426
16427 let mut iter = self.input.graphemes(true).peekable();
16428 let mut offset = 0;
16429 let mut graphemes = 0;
16430 if let Some(first_grapheme) = iter.next() {
16431 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16432 offset += first_grapheme.len();
16433 graphemes += 1;
16434 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16435 if let Some(grapheme) = iter.peek().copied() {
16436 if should_stay_with_preceding_ideograph(grapheme) {
16437 offset += grapheme.len();
16438 graphemes += 1;
16439 }
16440 }
16441 } else {
16442 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16443 let mut next_word_bound = words.peek().copied();
16444 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16445 next_word_bound = words.next();
16446 }
16447 while let Some(grapheme) = iter.peek().copied() {
16448 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16449 break;
16450 };
16451 if is_grapheme_whitespace(grapheme) != is_whitespace {
16452 break;
16453 };
16454 offset += grapheme.len();
16455 graphemes += 1;
16456 iter.next();
16457 }
16458 }
16459 let token = &self.input[..offset];
16460 self.input = &self.input[offset..];
16461 if is_whitespace {
16462 Some(WordBreakToken {
16463 token: " ",
16464 grapheme_len: 1,
16465 is_whitespace: true,
16466 })
16467 } else {
16468 Some(WordBreakToken {
16469 token,
16470 grapheme_len: graphemes,
16471 is_whitespace: false,
16472 })
16473 }
16474 } else {
16475 None
16476 }
16477 }
16478}
16479
16480#[test]
16481fn test_word_breaking_tokenizer() {
16482 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16483 ("", &[]),
16484 (" ", &[(" ", 1, true)]),
16485 ("Ʒ", &[("Ʒ", 1, false)]),
16486 ("Ǽ", &[("Ǽ", 1, false)]),
16487 ("⋑", &[("⋑", 1, false)]),
16488 ("⋑⋑", &[("⋑⋑", 2, false)]),
16489 (
16490 "原理,进而",
16491 &[
16492 ("原", 1, false),
16493 ("理,", 2, false),
16494 ("进", 1, false),
16495 ("而", 1, false),
16496 ],
16497 ),
16498 (
16499 "hello world",
16500 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16501 ),
16502 (
16503 "hello, world",
16504 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16505 ),
16506 (
16507 " hello world",
16508 &[
16509 (" ", 1, true),
16510 ("hello", 5, false),
16511 (" ", 1, true),
16512 ("world", 5, false),
16513 ],
16514 ),
16515 (
16516 "这是什么 \n 钢笔",
16517 &[
16518 ("这", 1, false),
16519 ("是", 1, false),
16520 ("什", 1, false),
16521 ("么", 1, false),
16522 (" ", 1, true),
16523 ("钢", 1, false),
16524 ("笔", 1, false),
16525 ],
16526 ),
16527 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16528 ];
16529
16530 for (input, result) in tests {
16531 assert_eq!(
16532 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16533 result
16534 .iter()
16535 .copied()
16536 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16537 token,
16538 grapheme_len,
16539 is_whitespace,
16540 })
16541 .collect::<Vec<_>>()
16542 );
16543 }
16544}
16545
16546fn wrap_with_prefix(
16547 line_prefix: String,
16548 unwrapped_text: String,
16549 wrap_column: usize,
16550 tab_size: NonZeroU32,
16551) -> String {
16552 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16553 let mut wrapped_text = String::new();
16554 let mut current_line = line_prefix.clone();
16555
16556 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16557 let mut current_line_len = line_prefix_len;
16558 for WordBreakToken {
16559 token,
16560 grapheme_len,
16561 is_whitespace,
16562 } in tokenizer
16563 {
16564 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16565 wrapped_text.push_str(current_line.trim_end());
16566 wrapped_text.push('\n');
16567 current_line.truncate(line_prefix.len());
16568 current_line_len = line_prefix_len;
16569 if !is_whitespace {
16570 current_line.push_str(token);
16571 current_line_len += grapheme_len;
16572 }
16573 } else if !is_whitespace {
16574 current_line.push_str(token);
16575 current_line_len += grapheme_len;
16576 } else if current_line_len != line_prefix_len {
16577 current_line.push(' ');
16578 current_line_len += 1;
16579 }
16580 }
16581
16582 if !current_line.is_empty() {
16583 wrapped_text.push_str(¤t_line);
16584 }
16585 wrapped_text
16586}
16587
16588#[test]
16589fn test_wrap_with_prefix() {
16590 assert_eq!(
16591 wrap_with_prefix(
16592 "# ".to_string(),
16593 "abcdefg".to_string(),
16594 4,
16595 NonZeroU32::new(4).unwrap()
16596 ),
16597 "# abcdefg"
16598 );
16599 assert_eq!(
16600 wrap_with_prefix(
16601 "".to_string(),
16602 "\thello world".to_string(),
16603 8,
16604 NonZeroU32::new(4).unwrap()
16605 ),
16606 "hello\nworld"
16607 );
16608 assert_eq!(
16609 wrap_with_prefix(
16610 "// ".to_string(),
16611 "xx \nyy zz aa bb cc".to_string(),
16612 12,
16613 NonZeroU32::new(4).unwrap()
16614 ),
16615 "// xx yy zz\n// aa bb cc"
16616 );
16617 assert_eq!(
16618 wrap_with_prefix(
16619 String::new(),
16620 "这是什么 \n 钢笔".to_string(),
16621 3,
16622 NonZeroU32::new(4).unwrap()
16623 ),
16624 "这是什\n么 钢\n笔"
16625 );
16626}
16627
16628pub trait CollaborationHub {
16629 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16630 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16631 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16632}
16633
16634impl CollaborationHub for Entity<Project> {
16635 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16636 self.read(cx).collaborators()
16637 }
16638
16639 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16640 self.read(cx).user_store().read(cx).participant_indices()
16641 }
16642
16643 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16644 let this = self.read(cx);
16645 let user_ids = this.collaborators().values().map(|c| c.user_id);
16646 this.user_store().read_with(cx, |user_store, cx| {
16647 user_store.participant_names(user_ids, cx)
16648 })
16649 }
16650}
16651
16652pub trait SemanticsProvider {
16653 fn hover(
16654 &self,
16655 buffer: &Entity<Buffer>,
16656 position: text::Anchor,
16657 cx: &mut App,
16658 ) -> Option<Task<Vec<project::Hover>>>;
16659
16660 fn inlay_hints(
16661 &self,
16662 buffer_handle: Entity<Buffer>,
16663 range: Range<text::Anchor>,
16664 cx: &mut App,
16665 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16666
16667 fn resolve_inlay_hint(
16668 &self,
16669 hint: InlayHint,
16670 buffer_handle: Entity<Buffer>,
16671 server_id: LanguageServerId,
16672 cx: &mut App,
16673 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16674
16675 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16676
16677 fn document_highlights(
16678 &self,
16679 buffer: &Entity<Buffer>,
16680 position: text::Anchor,
16681 cx: &mut App,
16682 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16683
16684 fn definitions(
16685 &self,
16686 buffer: &Entity<Buffer>,
16687 position: text::Anchor,
16688 kind: GotoDefinitionKind,
16689 cx: &mut App,
16690 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16691
16692 fn range_for_rename(
16693 &self,
16694 buffer: &Entity<Buffer>,
16695 position: text::Anchor,
16696 cx: &mut App,
16697 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16698
16699 fn perform_rename(
16700 &self,
16701 buffer: &Entity<Buffer>,
16702 position: text::Anchor,
16703 new_name: String,
16704 cx: &mut App,
16705 ) -> Option<Task<Result<ProjectTransaction>>>;
16706}
16707
16708pub trait CompletionProvider {
16709 fn completions(
16710 &self,
16711 buffer: &Entity<Buffer>,
16712 buffer_position: text::Anchor,
16713 trigger: CompletionContext,
16714 window: &mut Window,
16715 cx: &mut Context<Editor>,
16716 ) -> Task<Result<Vec<Completion>>>;
16717
16718 fn resolve_completions(
16719 &self,
16720 buffer: Entity<Buffer>,
16721 completion_indices: Vec<usize>,
16722 completions: Rc<RefCell<Box<[Completion]>>>,
16723 cx: &mut Context<Editor>,
16724 ) -> Task<Result<bool>>;
16725
16726 fn apply_additional_edits_for_completion(
16727 &self,
16728 _buffer: Entity<Buffer>,
16729 _completions: Rc<RefCell<Box<[Completion]>>>,
16730 _completion_index: usize,
16731 _push_to_history: bool,
16732 _cx: &mut Context<Editor>,
16733 ) -> Task<Result<Option<language::Transaction>>> {
16734 Task::ready(Ok(None))
16735 }
16736
16737 fn is_completion_trigger(
16738 &self,
16739 buffer: &Entity<Buffer>,
16740 position: language::Anchor,
16741 text: &str,
16742 trigger_in_words: bool,
16743 cx: &mut Context<Editor>,
16744 ) -> bool;
16745
16746 fn sort_completions(&self) -> bool {
16747 true
16748 }
16749}
16750
16751pub trait CodeActionProvider {
16752 fn id(&self) -> Arc<str>;
16753
16754 fn code_actions(
16755 &self,
16756 buffer: &Entity<Buffer>,
16757 range: Range<text::Anchor>,
16758 window: &mut Window,
16759 cx: &mut App,
16760 ) -> Task<Result<Vec<CodeAction>>>;
16761
16762 fn apply_code_action(
16763 &self,
16764 buffer_handle: Entity<Buffer>,
16765 action: CodeAction,
16766 excerpt_id: ExcerptId,
16767 push_to_history: bool,
16768 window: &mut Window,
16769 cx: &mut App,
16770 ) -> Task<Result<ProjectTransaction>>;
16771}
16772
16773impl CodeActionProvider for Entity<Project> {
16774 fn id(&self) -> Arc<str> {
16775 "project".into()
16776 }
16777
16778 fn code_actions(
16779 &self,
16780 buffer: &Entity<Buffer>,
16781 range: Range<text::Anchor>,
16782 _window: &mut Window,
16783 cx: &mut App,
16784 ) -> Task<Result<Vec<CodeAction>>> {
16785 self.update(cx, |project, cx| {
16786 project.code_actions(buffer, range, None, cx)
16787 })
16788 }
16789
16790 fn apply_code_action(
16791 &self,
16792 buffer_handle: Entity<Buffer>,
16793 action: CodeAction,
16794 _excerpt_id: ExcerptId,
16795 push_to_history: bool,
16796 _window: &mut Window,
16797 cx: &mut App,
16798 ) -> Task<Result<ProjectTransaction>> {
16799 self.update(cx, |project, cx| {
16800 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16801 })
16802 }
16803}
16804
16805fn snippet_completions(
16806 project: &Project,
16807 buffer: &Entity<Buffer>,
16808 buffer_position: text::Anchor,
16809 cx: &mut App,
16810) -> Task<Result<Vec<Completion>>> {
16811 let language = buffer.read(cx).language_at(buffer_position);
16812 let language_name = language.as_ref().map(|language| language.lsp_id());
16813 let snippet_store = project.snippets().read(cx);
16814 let snippets = snippet_store.snippets_for(language_name, cx);
16815
16816 if snippets.is_empty() {
16817 return Task::ready(Ok(vec![]));
16818 }
16819 let snapshot = buffer.read(cx).text_snapshot();
16820 let chars: String = snapshot
16821 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16822 .collect();
16823
16824 let scope = language.map(|language| language.default_scope());
16825 let executor = cx.background_executor().clone();
16826
16827 cx.background_spawn(async move {
16828 let classifier = CharClassifier::new(scope).for_completion(true);
16829 let mut last_word = chars
16830 .chars()
16831 .take_while(|c| classifier.is_word(*c))
16832 .collect::<String>();
16833 last_word = last_word.chars().rev().collect();
16834
16835 if last_word.is_empty() {
16836 return Ok(vec![]);
16837 }
16838
16839 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16840 let to_lsp = |point: &text::Anchor| {
16841 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16842 point_to_lsp(end)
16843 };
16844 let lsp_end = to_lsp(&buffer_position);
16845
16846 let candidates = snippets
16847 .iter()
16848 .enumerate()
16849 .flat_map(|(ix, snippet)| {
16850 snippet
16851 .prefix
16852 .iter()
16853 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16854 })
16855 .collect::<Vec<StringMatchCandidate>>();
16856
16857 let mut matches = fuzzy::match_strings(
16858 &candidates,
16859 &last_word,
16860 last_word.chars().any(|c| c.is_uppercase()),
16861 100,
16862 &Default::default(),
16863 executor,
16864 )
16865 .await;
16866
16867 // Remove all candidates where the query's start does not match the start of any word in the candidate
16868 if let Some(query_start) = last_word.chars().next() {
16869 matches.retain(|string_match| {
16870 split_words(&string_match.string).any(|word| {
16871 // Check that the first codepoint of the word as lowercase matches the first
16872 // codepoint of the query as lowercase
16873 word.chars()
16874 .flat_map(|codepoint| codepoint.to_lowercase())
16875 .zip(query_start.to_lowercase())
16876 .all(|(word_cp, query_cp)| word_cp == query_cp)
16877 })
16878 });
16879 }
16880
16881 let matched_strings = matches
16882 .into_iter()
16883 .map(|m| m.string)
16884 .collect::<HashSet<_>>();
16885
16886 let result: Vec<Completion> = snippets
16887 .into_iter()
16888 .filter_map(|snippet| {
16889 let matching_prefix = snippet
16890 .prefix
16891 .iter()
16892 .find(|prefix| matched_strings.contains(*prefix))?;
16893 let start = as_offset - last_word.len();
16894 let start = snapshot.anchor_before(start);
16895 let range = start..buffer_position;
16896 let lsp_start = to_lsp(&start);
16897 let lsp_range = lsp::Range {
16898 start: lsp_start,
16899 end: lsp_end,
16900 };
16901 Some(Completion {
16902 old_range: range,
16903 new_text: snippet.body.clone(),
16904 resolved: false,
16905 label: CodeLabel {
16906 text: matching_prefix.clone(),
16907 runs: vec![],
16908 filter_range: 0..matching_prefix.len(),
16909 },
16910 server_id: LanguageServerId(usize::MAX),
16911 documentation: snippet
16912 .description
16913 .clone()
16914 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16915 lsp_completion: lsp::CompletionItem {
16916 label: snippet.prefix.first().unwrap().clone(),
16917 kind: Some(CompletionItemKind::SNIPPET),
16918 label_details: snippet.description.as_ref().map(|description| {
16919 lsp::CompletionItemLabelDetails {
16920 detail: Some(description.clone()),
16921 description: None,
16922 }
16923 }),
16924 insert_text_format: Some(InsertTextFormat::SNIPPET),
16925 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16926 lsp::InsertReplaceEdit {
16927 new_text: snippet.body.clone(),
16928 insert: lsp_range,
16929 replace: lsp_range,
16930 },
16931 )),
16932 filter_text: Some(snippet.body.clone()),
16933 sort_text: Some(char::MAX.to_string()),
16934 ..Default::default()
16935 },
16936 confirm: None,
16937 })
16938 })
16939 .collect();
16940
16941 Ok(result)
16942 })
16943}
16944
16945impl CompletionProvider for Entity<Project> {
16946 fn completions(
16947 &self,
16948 buffer: &Entity<Buffer>,
16949 buffer_position: text::Anchor,
16950 options: CompletionContext,
16951 _window: &mut Window,
16952 cx: &mut Context<Editor>,
16953 ) -> Task<Result<Vec<Completion>>> {
16954 self.update(cx, |project, cx| {
16955 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16956 let project_completions = project.completions(buffer, buffer_position, options, cx);
16957 cx.background_spawn(async move {
16958 let mut completions = project_completions.await?;
16959 let snippets_completions = snippets.await?;
16960 completions.extend(snippets_completions);
16961 Ok(completions)
16962 })
16963 })
16964 }
16965
16966 fn resolve_completions(
16967 &self,
16968 buffer: Entity<Buffer>,
16969 completion_indices: Vec<usize>,
16970 completions: Rc<RefCell<Box<[Completion]>>>,
16971 cx: &mut Context<Editor>,
16972 ) -> Task<Result<bool>> {
16973 self.update(cx, |project, cx| {
16974 project.lsp_store().update(cx, |lsp_store, cx| {
16975 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16976 })
16977 })
16978 }
16979
16980 fn apply_additional_edits_for_completion(
16981 &self,
16982 buffer: Entity<Buffer>,
16983 completions: Rc<RefCell<Box<[Completion]>>>,
16984 completion_index: usize,
16985 push_to_history: bool,
16986 cx: &mut Context<Editor>,
16987 ) -> Task<Result<Option<language::Transaction>>> {
16988 self.update(cx, |project, cx| {
16989 project.lsp_store().update(cx, |lsp_store, cx| {
16990 lsp_store.apply_additional_edits_for_completion(
16991 buffer,
16992 completions,
16993 completion_index,
16994 push_to_history,
16995 cx,
16996 )
16997 })
16998 })
16999 }
17000
17001 fn is_completion_trigger(
17002 &self,
17003 buffer: &Entity<Buffer>,
17004 position: language::Anchor,
17005 text: &str,
17006 trigger_in_words: bool,
17007 cx: &mut Context<Editor>,
17008 ) -> bool {
17009 let mut chars = text.chars();
17010 let char = if let Some(char) = chars.next() {
17011 char
17012 } else {
17013 return false;
17014 };
17015 if chars.next().is_some() {
17016 return false;
17017 }
17018
17019 let buffer = buffer.read(cx);
17020 let snapshot = buffer.snapshot();
17021 if !snapshot.settings_at(position, cx).show_completions_on_input {
17022 return false;
17023 }
17024 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17025 if trigger_in_words && classifier.is_word(char) {
17026 return true;
17027 }
17028
17029 buffer.completion_triggers().contains(text)
17030 }
17031}
17032
17033impl SemanticsProvider for Entity<Project> {
17034 fn hover(
17035 &self,
17036 buffer: &Entity<Buffer>,
17037 position: text::Anchor,
17038 cx: &mut App,
17039 ) -> Option<Task<Vec<project::Hover>>> {
17040 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17041 }
17042
17043 fn document_highlights(
17044 &self,
17045 buffer: &Entity<Buffer>,
17046 position: text::Anchor,
17047 cx: &mut App,
17048 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17049 Some(self.update(cx, |project, cx| {
17050 project.document_highlights(buffer, position, cx)
17051 }))
17052 }
17053
17054 fn definitions(
17055 &self,
17056 buffer: &Entity<Buffer>,
17057 position: text::Anchor,
17058 kind: GotoDefinitionKind,
17059 cx: &mut App,
17060 ) -> Option<Task<Result<Vec<LocationLink>>>> {
17061 Some(self.update(cx, |project, cx| match kind {
17062 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17063 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17064 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17065 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17066 }))
17067 }
17068
17069 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17070 // TODO: make this work for remote projects
17071 self.update(cx, |this, cx| {
17072 buffer.update(cx, |buffer, cx| {
17073 this.any_language_server_supports_inlay_hints(buffer, cx)
17074 })
17075 })
17076 }
17077
17078 fn inlay_hints(
17079 &self,
17080 buffer_handle: Entity<Buffer>,
17081 range: Range<text::Anchor>,
17082 cx: &mut App,
17083 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17084 Some(self.update(cx, |project, cx| {
17085 project.inlay_hints(buffer_handle, range, cx)
17086 }))
17087 }
17088
17089 fn resolve_inlay_hint(
17090 &self,
17091 hint: InlayHint,
17092 buffer_handle: Entity<Buffer>,
17093 server_id: LanguageServerId,
17094 cx: &mut App,
17095 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17096 Some(self.update(cx, |project, cx| {
17097 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17098 }))
17099 }
17100
17101 fn range_for_rename(
17102 &self,
17103 buffer: &Entity<Buffer>,
17104 position: text::Anchor,
17105 cx: &mut App,
17106 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17107 Some(self.update(cx, |project, cx| {
17108 let buffer = buffer.clone();
17109 let task = project.prepare_rename(buffer.clone(), position, cx);
17110 cx.spawn(|_, mut cx| async move {
17111 Ok(match task.await? {
17112 PrepareRenameResponse::Success(range) => Some(range),
17113 PrepareRenameResponse::InvalidPosition => None,
17114 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17115 // Fallback on using TreeSitter info to determine identifier range
17116 buffer.update(&mut cx, |buffer, _| {
17117 let snapshot = buffer.snapshot();
17118 let (range, kind) = snapshot.surrounding_word(position);
17119 if kind != Some(CharKind::Word) {
17120 return None;
17121 }
17122 Some(
17123 snapshot.anchor_before(range.start)
17124 ..snapshot.anchor_after(range.end),
17125 )
17126 })?
17127 }
17128 })
17129 })
17130 }))
17131 }
17132
17133 fn perform_rename(
17134 &self,
17135 buffer: &Entity<Buffer>,
17136 position: text::Anchor,
17137 new_name: String,
17138 cx: &mut App,
17139 ) -> Option<Task<Result<ProjectTransaction>>> {
17140 Some(self.update(cx, |project, cx| {
17141 project.perform_rename(buffer.clone(), position, new_name, cx)
17142 }))
17143 }
17144}
17145
17146fn inlay_hint_settings(
17147 location: Anchor,
17148 snapshot: &MultiBufferSnapshot,
17149 cx: &mut Context<Editor>,
17150) -> InlayHintSettings {
17151 let file = snapshot.file_at(location);
17152 let language = snapshot.language_at(location).map(|l| l.name());
17153 language_settings(language, file, cx).inlay_hints
17154}
17155
17156fn consume_contiguous_rows(
17157 contiguous_row_selections: &mut Vec<Selection<Point>>,
17158 selection: &Selection<Point>,
17159 display_map: &DisplaySnapshot,
17160 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17161) -> (MultiBufferRow, MultiBufferRow) {
17162 contiguous_row_selections.push(selection.clone());
17163 let start_row = MultiBufferRow(selection.start.row);
17164 let mut end_row = ending_row(selection, display_map);
17165
17166 while let Some(next_selection) = selections.peek() {
17167 if next_selection.start.row <= end_row.0 {
17168 end_row = ending_row(next_selection, display_map);
17169 contiguous_row_selections.push(selections.next().unwrap().clone());
17170 } else {
17171 break;
17172 }
17173 }
17174 (start_row, end_row)
17175}
17176
17177fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17178 if next_selection.end.column > 0 || next_selection.is_empty() {
17179 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17180 } else {
17181 MultiBufferRow(next_selection.end.row)
17182 }
17183}
17184
17185impl EditorSnapshot {
17186 pub fn remote_selections_in_range<'a>(
17187 &'a self,
17188 range: &'a Range<Anchor>,
17189 collaboration_hub: &dyn CollaborationHub,
17190 cx: &'a App,
17191 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17192 let participant_names = collaboration_hub.user_names(cx);
17193 let participant_indices = collaboration_hub.user_participant_indices(cx);
17194 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17195 let collaborators_by_replica_id = collaborators_by_peer_id
17196 .iter()
17197 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17198 .collect::<HashMap<_, _>>();
17199 self.buffer_snapshot
17200 .selections_in_range(range, false)
17201 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17202 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17203 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17204 let user_name = participant_names.get(&collaborator.user_id).cloned();
17205 Some(RemoteSelection {
17206 replica_id,
17207 selection,
17208 cursor_shape,
17209 line_mode,
17210 participant_index,
17211 peer_id: collaborator.peer_id,
17212 user_name,
17213 })
17214 })
17215 }
17216
17217 pub fn hunks_for_ranges(
17218 &self,
17219 ranges: impl IntoIterator<Item = Range<Point>>,
17220 ) -> Vec<MultiBufferDiffHunk> {
17221 let mut hunks = Vec::new();
17222 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17223 HashMap::default();
17224 for query_range in ranges {
17225 let query_rows =
17226 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17227 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17228 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17229 ) {
17230 // Include deleted hunks that are adjacent to the query range, because
17231 // otherwise they would be missed.
17232 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17233 if hunk.status().is_deleted() {
17234 intersects_range |= hunk.row_range.start == query_rows.end;
17235 intersects_range |= hunk.row_range.end == query_rows.start;
17236 }
17237 if intersects_range {
17238 if !processed_buffer_rows
17239 .entry(hunk.buffer_id)
17240 .or_default()
17241 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17242 {
17243 continue;
17244 }
17245 hunks.push(hunk);
17246 }
17247 }
17248 }
17249
17250 hunks
17251 }
17252
17253 fn display_diff_hunks_for_rows<'a>(
17254 &'a self,
17255 display_rows: Range<DisplayRow>,
17256 folded_buffers: &'a HashSet<BufferId>,
17257 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17258 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17259 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17260
17261 self.buffer_snapshot
17262 .diff_hunks_in_range(buffer_start..buffer_end)
17263 .filter_map(|hunk| {
17264 if folded_buffers.contains(&hunk.buffer_id) {
17265 return None;
17266 }
17267
17268 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17269 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17270
17271 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17272 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17273
17274 let display_hunk = if hunk_display_start.column() != 0 {
17275 DisplayDiffHunk::Folded {
17276 display_row: hunk_display_start.row(),
17277 }
17278 } else {
17279 let mut end_row = hunk_display_end.row();
17280 if hunk_display_end.column() > 0 {
17281 end_row.0 += 1;
17282 }
17283 DisplayDiffHunk::Unfolded {
17284 status: hunk.status(),
17285 diff_base_byte_range: hunk.diff_base_byte_range,
17286 display_row_range: hunk_display_start.row()..end_row,
17287 multi_buffer_range: Anchor::range_in_buffer(
17288 hunk.excerpt_id,
17289 hunk.buffer_id,
17290 hunk.buffer_range,
17291 ),
17292 }
17293 };
17294
17295 Some(display_hunk)
17296 })
17297 }
17298
17299 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17300 self.display_snapshot.buffer_snapshot.language_at(position)
17301 }
17302
17303 pub fn is_focused(&self) -> bool {
17304 self.is_focused
17305 }
17306
17307 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17308 self.placeholder_text.as_ref()
17309 }
17310
17311 pub fn scroll_position(&self) -> gpui::Point<f32> {
17312 self.scroll_anchor.scroll_position(&self.display_snapshot)
17313 }
17314
17315 fn gutter_dimensions(
17316 &self,
17317 font_id: FontId,
17318 font_size: Pixels,
17319 max_line_number_width: Pixels,
17320 cx: &App,
17321 ) -> Option<GutterDimensions> {
17322 if !self.show_gutter {
17323 return None;
17324 }
17325
17326 let descent = cx.text_system().descent(font_id, font_size);
17327 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17328 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17329
17330 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17331 matches!(
17332 ProjectSettings::get_global(cx).git.git_gutter,
17333 Some(GitGutterSetting::TrackedFiles)
17334 )
17335 });
17336 let gutter_settings = EditorSettings::get_global(cx).gutter;
17337 let show_line_numbers = self
17338 .show_line_numbers
17339 .unwrap_or(gutter_settings.line_numbers);
17340 let line_gutter_width = if show_line_numbers {
17341 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17342 let min_width_for_number_on_gutter = em_advance * 4.0;
17343 max_line_number_width.max(min_width_for_number_on_gutter)
17344 } else {
17345 0.0.into()
17346 };
17347
17348 let show_code_actions = self
17349 .show_code_actions
17350 .unwrap_or(gutter_settings.code_actions);
17351
17352 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17353
17354 let git_blame_entries_width =
17355 self.git_blame_gutter_max_author_length
17356 .map(|max_author_length| {
17357 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17358
17359 /// The number of characters to dedicate to gaps and margins.
17360 const SPACING_WIDTH: usize = 4;
17361
17362 let max_char_count = max_author_length
17363 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17364 + ::git::SHORT_SHA_LENGTH
17365 + MAX_RELATIVE_TIMESTAMP.len()
17366 + SPACING_WIDTH;
17367
17368 em_advance * max_char_count
17369 });
17370
17371 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17372 left_padding += if show_code_actions || show_runnables {
17373 em_width * 3.0
17374 } else if show_git_gutter && show_line_numbers {
17375 em_width * 2.0
17376 } else if show_git_gutter || show_line_numbers {
17377 em_width
17378 } else {
17379 px(0.)
17380 };
17381
17382 let right_padding = if gutter_settings.folds && show_line_numbers {
17383 em_width * 4.0
17384 } else if gutter_settings.folds {
17385 em_width * 3.0
17386 } else if show_line_numbers {
17387 em_width
17388 } else {
17389 px(0.)
17390 };
17391
17392 Some(GutterDimensions {
17393 left_padding,
17394 right_padding,
17395 width: line_gutter_width + left_padding + right_padding,
17396 margin: -descent,
17397 git_blame_entries_width,
17398 })
17399 }
17400
17401 pub fn render_crease_toggle(
17402 &self,
17403 buffer_row: MultiBufferRow,
17404 row_contains_cursor: bool,
17405 editor: Entity<Editor>,
17406 window: &mut Window,
17407 cx: &mut App,
17408 ) -> Option<AnyElement> {
17409 let folded = self.is_line_folded(buffer_row);
17410 let mut is_foldable = false;
17411
17412 if let Some(crease) = self
17413 .crease_snapshot
17414 .query_row(buffer_row, &self.buffer_snapshot)
17415 {
17416 is_foldable = true;
17417 match crease {
17418 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17419 if let Some(render_toggle) = render_toggle {
17420 let toggle_callback =
17421 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17422 if folded {
17423 editor.update(cx, |editor, cx| {
17424 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17425 });
17426 } else {
17427 editor.update(cx, |editor, cx| {
17428 editor.unfold_at(
17429 &crate::UnfoldAt { buffer_row },
17430 window,
17431 cx,
17432 )
17433 });
17434 }
17435 });
17436 return Some((render_toggle)(
17437 buffer_row,
17438 folded,
17439 toggle_callback,
17440 window,
17441 cx,
17442 ));
17443 }
17444 }
17445 }
17446 }
17447
17448 is_foldable |= self.starts_indent(buffer_row);
17449
17450 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17451 Some(
17452 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17453 .toggle_state(folded)
17454 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17455 if folded {
17456 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17457 } else {
17458 this.fold_at(&FoldAt { buffer_row }, window, cx);
17459 }
17460 }))
17461 .into_any_element(),
17462 )
17463 } else {
17464 None
17465 }
17466 }
17467
17468 pub fn render_crease_trailer(
17469 &self,
17470 buffer_row: MultiBufferRow,
17471 window: &mut Window,
17472 cx: &mut App,
17473 ) -> Option<AnyElement> {
17474 let folded = self.is_line_folded(buffer_row);
17475 if let Crease::Inline { render_trailer, .. } = self
17476 .crease_snapshot
17477 .query_row(buffer_row, &self.buffer_snapshot)?
17478 {
17479 let render_trailer = render_trailer.as_ref()?;
17480 Some(render_trailer(buffer_row, folded, window, cx))
17481 } else {
17482 None
17483 }
17484 }
17485}
17486
17487impl Deref for EditorSnapshot {
17488 type Target = DisplaySnapshot;
17489
17490 fn deref(&self) -> &Self::Target {
17491 &self.display_snapshot
17492 }
17493}
17494
17495#[derive(Clone, Debug, PartialEq, Eq)]
17496pub enum EditorEvent {
17497 InputIgnored {
17498 text: Arc<str>,
17499 },
17500 InputHandled {
17501 utf16_range_to_replace: Option<Range<isize>>,
17502 text: Arc<str>,
17503 },
17504 ExcerptsAdded {
17505 buffer: Entity<Buffer>,
17506 predecessor: ExcerptId,
17507 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17508 },
17509 ExcerptsRemoved {
17510 ids: Vec<ExcerptId>,
17511 },
17512 BufferFoldToggled {
17513 ids: Vec<ExcerptId>,
17514 folded: bool,
17515 },
17516 ExcerptsEdited {
17517 ids: Vec<ExcerptId>,
17518 },
17519 ExcerptsExpanded {
17520 ids: Vec<ExcerptId>,
17521 },
17522 BufferEdited,
17523 Edited {
17524 transaction_id: clock::Lamport,
17525 },
17526 Reparsed(BufferId),
17527 Focused,
17528 FocusedIn,
17529 Blurred,
17530 DirtyChanged,
17531 Saved,
17532 TitleChanged,
17533 DiffBaseChanged,
17534 SelectionsChanged {
17535 local: bool,
17536 },
17537 ScrollPositionChanged {
17538 local: bool,
17539 autoscroll: bool,
17540 },
17541 Closed,
17542 TransactionUndone {
17543 transaction_id: clock::Lamport,
17544 },
17545 TransactionBegun {
17546 transaction_id: clock::Lamport,
17547 },
17548 Reloaded,
17549 CursorShapeChanged,
17550}
17551
17552impl EventEmitter<EditorEvent> for Editor {}
17553
17554impl Focusable for Editor {
17555 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17556 self.focus_handle.clone()
17557 }
17558}
17559
17560impl Render for Editor {
17561 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17562 let settings = ThemeSettings::get_global(cx);
17563
17564 let mut text_style = match self.mode {
17565 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17566 color: cx.theme().colors().editor_foreground,
17567 font_family: settings.ui_font.family.clone(),
17568 font_features: settings.ui_font.features.clone(),
17569 font_fallbacks: settings.ui_font.fallbacks.clone(),
17570 font_size: rems(0.875).into(),
17571 font_weight: settings.ui_font.weight,
17572 line_height: relative(settings.buffer_line_height.value()),
17573 ..Default::default()
17574 },
17575 EditorMode::Full => TextStyle {
17576 color: cx.theme().colors().editor_foreground,
17577 font_family: settings.buffer_font.family.clone(),
17578 font_features: settings.buffer_font.features.clone(),
17579 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17580 font_size: settings.buffer_font_size(cx).into(),
17581 font_weight: settings.buffer_font.weight,
17582 line_height: relative(settings.buffer_line_height.value()),
17583 ..Default::default()
17584 },
17585 };
17586 if let Some(text_style_refinement) = &self.text_style_refinement {
17587 text_style.refine(text_style_refinement)
17588 }
17589
17590 let background = match self.mode {
17591 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17592 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17593 EditorMode::Full => cx.theme().colors().editor_background,
17594 };
17595
17596 EditorElement::new(
17597 &cx.entity(),
17598 EditorStyle {
17599 background,
17600 local_player: cx.theme().players().local(),
17601 text: text_style,
17602 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17603 syntax: cx.theme().syntax().clone(),
17604 status: cx.theme().status().clone(),
17605 inlay_hints_style: make_inlay_hints_style(cx),
17606 inline_completion_styles: make_suggestion_styles(cx),
17607 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17608 },
17609 )
17610 }
17611}
17612
17613impl EntityInputHandler for Editor {
17614 fn text_for_range(
17615 &mut self,
17616 range_utf16: Range<usize>,
17617 adjusted_range: &mut Option<Range<usize>>,
17618 _: &mut Window,
17619 cx: &mut Context<Self>,
17620 ) -> Option<String> {
17621 let snapshot = self.buffer.read(cx).read(cx);
17622 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17623 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17624 if (start.0..end.0) != range_utf16 {
17625 adjusted_range.replace(start.0..end.0);
17626 }
17627 Some(snapshot.text_for_range(start..end).collect())
17628 }
17629
17630 fn selected_text_range(
17631 &mut self,
17632 ignore_disabled_input: bool,
17633 _: &mut Window,
17634 cx: &mut Context<Self>,
17635 ) -> Option<UTF16Selection> {
17636 // Prevent the IME menu from appearing when holding down an alphabetic key
17637 // while input is disabled.
17638 if !ignore_disabled_input && !self.input_enabled {
17639 return None;
17640 }
17641
17642 let selection = self.selections.newest::<OffsetUtf16>(cx);
17643 let range = selection.range();
17644
17645 Some(UTF16Selection {
17646 range: range.start.0..range.end.0,
17647 reversed: selection.reversed,
17648 })
17649 }
17650
17651 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17652 let snapshot = self.buffer.read(cx).read(cx);
17653 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17654 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17655 }
17656
17657 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17658 self.clear_highlights::<InputComposition>(cx);
17659 self.ime_transaction.take();
17660 }
17661
17662 fn replace_text_in_range(
17663 &mut self,
17664 range_utf16: Option<Range<usize>>,
17665 text: &str,
17666 window: &mut Window,
17667 cx: &mut Context<Self>,
17668 ) {
17669 if !self.input_enabled {
17670 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17671 return;
17672 }
17673
17674 self.transact(window, cx, |this, window, cx| {
17675 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17676 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17677 Some(this.selection_replacement_ranges(range_utf16, cx))
17678 } else {
17679 this.marked_text_ranges(cx)
17680 };
17681
17682 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17683 let newest_selection_id = this.selections.newest_anchor().id;
17684 this.selections
17685 .all::<OffsetUtf16>(cx)
17686 .iter()
17687 .zip(ranges_to_replace.iter())
17688 .find_map(|(selection, range)| {
17689 if selection.id == newest_selection_id {
17690 Some(
17691 (range.start.0 as isize - selection.head().0 as isize)
17692 ..(range.end.0 as isize - selection.head().0 as isize),
17693 )
17694 } else {
17695 None
17696 }
17697 })
17698 });
17699
17700 cx.emit(EditorEvent::InputHandled {
17701 utf16_range_to_replace: range_to_replace,
17702 text: text.into(),
17703 });
17704
17705 if let Some(new_selected_ranges) = new_selected_ranges {
17706 this.change_selections(None, window, cx, |selections| {
17707 selections.select_ranges(new_selected_ranges)
17708 });
17709 this.backspace(&Default::default(), window, cx);
17710 }
17711
17712 this.handle_input(text, window, cx);
17713 });
17714
17715 if let Some(transaction) = self.ime_transaction {
17716 self.buffer.update(cx, |buffer, cx| {
17717 buffer.group_until_transaction(transaction, cx);
17718 });
17719 }
17720
17721 self.unmark_text(window, cx);
17722 }
17723
17724 fn replace_and_mark_text_in_range(
17725 &mut self,
17726 range_utf16: Option<Range<usize>>,
17727 text: &str,
17728 new_selected_range_utf16: Option<Range<usize>>,
17729 window: &mut Window,
17730 cx: &mut Context<Self>,
17731 ) {
17732 if !self.input_enabled {
17733 return;
17734 }
17735
17736 let transaction = self.transact(window, cx, |this, window, cx| {
17737 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17738 let snapshot = this.buffer.read(cx).read(cx);
17739 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17740 for marked_range in &mut marked_ranges {
17741 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17742 marked_range.start.0 += relative_range_utf16.start;
17743 marked_range.start =
17744 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17745 marked_range.end =
17746 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17747 }
17748 }
17749 Some(marked_ranges)
17750 } else if let Some(range_utf16) = range_utf16 {
17751 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17752 Some(this.selection_replacement_ranges(range_utf16, cx))
17753 } else {
17754 None
17755 };
17756
17757 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17758 let newest_selection_id = this.selections.newest_anchor().id;
17759 this.selections
17760 .all::<OffsetUtf16>(cx)
17761 .iter()
17762 .zip(ranges_to_replace.iter())
17763 .find_map(|(selection, range)| {
17764 if selection.id == newest_selection_id {
17765 Some(
17766 (range.start.0 as isize - selection.head().0 as isize)
17767 ..(range.end.0 as isize - selection.head().0 as isize),
17768 )
17769 } else {
17770 None
17771 }
17772 })
17773 });
17774
17775 cx.emit(EditorEvent::InputHandled {
17776 utf16_range_to_replace: range_to_replace,
17777 text: text.into(),
17778 });
17779
17780 if let Some(ranges) = ranges_to_replace {
17781 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17782 }
17783
17784 let marked_ranges = {
17785 let snapshot = this.buffer.read(cx).read(cx);
17786 this.selections
17787 .disjoint_anchors()
17788 .iter()
17789 .map(|selection| {
17790 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17791 })
17792 .collect::<Vec<_>>()
17793 };
17794
17795 if text.is_empty() {
17796 this.unmark_text(window, cx);
17797 } else {
17798 this.highlight_text::<InputComposition>(
17799 marked_ranges.clone(),
17800 HighlightStyle {
17801 underline: Some(UnderlineStyle {
17802 thickness: px(1.),
17803 color: None,
17804 wavy: false,
17805 }),
17806 ..Default::default()
17807 },
17808 cx,
17809 );
17810 }
17811
17812 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17813 let use_autoclose = this.use_autoclose;
17814 let use_auto_surround = this.use_auto_surround;
17815 this.set_use_autoclose(false);
17816 this.set_use_auto_surround(false);
17817 this.handle_input(text, window, cx);
17818 this.set_use_autoclose(use_autoclose);
17819 this.set_use_auto_surround(use_auto_surround);
17820
17821 if let Some(new_selected_range) = new_selected_range_utf16 {
17822 let snapshot = this.buffer.read(cx).read(cx);
17823 let new_selected_ranges = marked_ranges
17824 .into_iter()
17825 .map(|marked_range| {
17826 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17827 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17828 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17829 snapshot.clip_offset_utf16(new_start, Bias::Left)
17830 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17831 })
17832 .collect::<Vec<_>>();
17833
17834 drop(snapshot);
17835 this.change_selections(None, window, cx, |selections| {
17836 selections.select_ranges(new_selected_ranges)
17837 });
17838 }
17839 });
17840
17841 self.ime_transaction = self.ime_transaction.or(transaction);
17842 if let Some(transaction) = self.ime_transaction {
17843 self.buffer.update(cx, |buffer, cx| {
17844 buffer.group_until_transaction(transaction, cx);
17845 });
17846 }
17847
17848 if self.text_highlights::<InputComposition>(cx).is_none() {
17849 self.ime_transaction.take();
17850 }
17851 }
17852
17853 fn bounds_for_range(
17854 &mut self,
17855 range_utf16: Range<usize>,
17856 element_bounds: gpui::Bounds<Pixels>,
17857 window: &mut Window,
17858 cx: &mut Context<Self>,
17859 ) -> Option<gpui::Bounds<Pixels>> {
17860 let text_layout_details = self.text_layout_details(window);
17861 let gpui::Size {
17862 width: em_width,
17863 height: line_height,
17864 } = self.character_size(window);
17865
17866 let snapshot = self.snapshot(window, cx);
17867 let scroll_position = snapshot.scroll_position();
17868 let scroll_left = scroll_position.x * em_width;
17869
17870 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17871 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17872 + self.gutter_dimensions.width
17873 + self.gutter_dimensions.margin;
17874 let y = line_height * (start.row().as_f32() - scroll_position.y);
17875
17876 Some(Bounds {
17877 origin: element_bounds.origin + point(x, y),
17878 size: size(em_width, line_height),
17879 })
17880 }
17881
17882 fn character_index_for_point(
17883 &mut self,
17884 point: gpui::Point<Pixels>,
17885 _window: &mut Window,
17886 _cx: &mut Context<Self>,
17887 ) -> Option<usize> {
17888 let position_map = self.last_position_map.as_ref()?;
17889 if !position_map.text_hitbox.contains(&point) {
17890 return None;
17891 }
17892 let display_point = position_map.point_for_position(point).previous_valid;
17893 let anchor = position_map
17894 .snapshot
17895 .display_point_to_anchor(display_point, Bias::Left);
17896 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17897 Some(utf16_offset.0)
17898 }
17899}
17900
17901trait SelectionExt {
17902 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17903 fn spanned_rows(
17904 &self,
17905 include_end_if_at_line_start: bool,
17906 map: &DisplaySnapshot,
17907 ) -> Range<MultiBufferRow>;
17908}
17909
17910impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17911 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17912 let start = self
17913 .start
17914 .to_point(&map.buffer_snapshot)
17915 .to_display_point(map);
17916 let end = self
17917 .end
17918 .to_point(&map.buffer_snapshot)
17919 .to_display_point(map);
17920 if self.reversed {
17921 end..start
17922 } else {
17923 start..end
17924 }
17925 }
17926
17927 fn spanned_rows(
17928 &self,
17929 include_end_if_at_line_start: bool,
17930 map: &DisplaySnapshot,
17931 ) -> Range<MultiBufferRow> {
17932 let start = self.start.to_point(&map.buffer_snapshot);
17933 let mut end = self.end.to_point(&map.buffer_snapshot);
17934 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17935 end.row -= 1;
17936 }
17937
17938 let buffer_start = map.prev_line_boundary(start).0;
17939 let buffer_end = map.next_line_boundary(end).0;
17940 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17941 }
17942}
17943
17944impl<T: InvalidationRegion> InvalidationStack<T> {
17945 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17946 where
17947 S: Clone + ToOffset,
17948 {
17949 while let Some(region) = self.last() {
17950 let all_selections_inside_invalidation_ranges =
17951 if selections.len() == region.ranges().len() {
17952 selections
17953 .iter()
17954 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17955 .all(|(selection, invalidation_range)| {
17956 let head = selection.head().to_offset(buffer);
17957 invalidation_range.start <= head && invalidation_range.end >= head
17958 })
17959 } else {
17960 false
17961 };
17962
17963 if all_selections_inside_invalidation_ranges {
17964 break;
17965 } else {
17966 self.pop();
17967 }
17968 }
17969 }
17970}
17971
17972impl<T> Default for InvalidationStack<T> {
17973 fn default() -> Self {
17974 Self(Default::default())
17975 }
17976}
17977
17978impl<T> Deref for InvalidationStack<T> {
17979 type Target = Vec<T>;
17980
17981 fn deref(&self) -> &Self::Target {
17982 &self.0
17983 }
17984}
17985
17986impl<T> DerefMut for InvalidationStack<T> {
17987 fn deref_mut(&mut self) -> &mut Self::Target {
17988 &mut self.0
17989 }
17990}
17991
17992impl InvalidationRegion for SnippetState {
17993 fn ranges(&self) -> &[Range<Anchor>] {
17994 &self.ranges[self.active_index]
17995 }
17996}
17997
17998pub fn diagnostic_block_renderer(
17999 diagnostic: Diagnostic,
18000 max_message_rows: Option<u8>,
18001 allow_closing: bool,
18002) -> RenderBlock {
18003 let (text_without_backticks, code_ranges) =
18004 highlight_diagnostic_message(&diagnostic, max_message_rows);
18005
18006 Arc::new(move |cx: &mut BlockContext| {
18007 let group_id: SharedString = cx.block_id.to_string().into();
18008
18009 let mut text_style = cx.window.text_style().clone();
18010 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18011 let theme_settings = ThemeSettings::get_global(cx);
18012 text_style.font_family = theme_settings.buffer_font.family.clone();
18013 text_style.font_style = theme_settings.buffer_font.style;
18014 text_style.font_features = theme_settings.buffer_font.features.clone();
18015 text_style.font_weight = theme_settings.buffer_font.weight;
18016
18017 let multi_line_diagnostic = diagnostic.message.contains('\n');
18018
18019 let buttons = |diagnostic: &Diagnostic| {
18020 if multi_line_diagnostic {
18021 v_flex()
18022 } else {
18023 h_flex()
18024 }
18025 .when(allow_closing, |div| {
18026 div.children(diagnostic.is_primary.then(|| {
18027 IconButton::new("close-block", IconName::XCircle)
18028 .icon_color(Color::Muted)
18029 .size(ButtonSize::Compact)
18030 .style(ButtonStyle::Transparent)
18031 .visible_on_hover(group_id.clone())
18032 .on_click(move |_click, window, cx| {
18033 window.dispatch_action(Box::new(Cancel), cx)
18034 })
18035 .tooltip(|window, cx| {
18036 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18037 })
18038 }))
18039 })
18040 .child(
18041 IconButton::new("copy-block", IconName::Copy)
18042 .icon_color(Color::Muted)
18043 .size(ButtonSize::Compact)
18044 .style(ButtonStyle::Transparent)
18045 .visible_on_hover(group_id.clone())
18046 .on_click({
18047 let message = diagnostic.message.clone();
18048 move |_click, _, cx| {
18049 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18050 }
18051 })
18052 .tooltip(Tooltip::text("Copy diagnostic message")),
18053 )
18054 };
18055
18056 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18057 AvailableSpace::min_size(),
18058 cx.window,
18059 cx.app,
18060 );
18061
18062 h_flex()
18063 .id(cx.block_id)
18064 .group(group_id.clone())
18065 .relative()
18066 .size_full()
18067 .block_mouse_down()
18068 .pl(cx.gutter_dimensions.width)
18069 .w(cx.max_width - cx.gutter_dimensions.full_width())
18070 .child(
18071 div()
18072 .flex()
18073 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18074 .flex_shrink(),
18075 )
18076 .child(buttons(&diagnostic))
18077 .child(div().flex().flex_shrink_0().child(
18078 StyledText::new(text_without_backticks.clone()).with_default_highlights(
18079 &text_style,
18080 code_ranges.iter().map(|range| {
18081 (
18082 range.clone(),
18083 HighlightStyle {
18084 font_weight: Some(FontWeight::BOLD),
18085 ..Default::default()
18086 },
18087 )
18088 }),
18089 ),
18090 ))
18091 .into_any_element()
18092 })
18093}
18094
18095fn inline_completion_edit_text(
18096 current_snapshot: &BufferSnapshot,
18097 edits: &[(Range<Anchor>, String)],
18098 edit_preview: &EditPreview,
18099 include_deletions: bool,
18100 cx: &App,
18101) -> HighlightedText {
18102 let edits = edits
18103 .iter()
18104 .map(|(anchor, text)| {
18105 (
18106 anchor.start.text_anchor..anchor.end.text_anchor,
18107 text.clone(),
18108 )
18109 })
18110 .collect::<Vec<_>>();
18111
18112 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18113}
18114
18115pub fn highlight_diagnostic_message(
18116 diagnostic: &Diagnostic,
18117 mut max_message_rows: Option<u8>,
18118) -> (SharedString, Vec<Range<usize>>) {
18119 let mut text_without_backticks = String::new();
18120 let mut code_ranges = Vec::new();
18121
18122 if let Some(source) = &diagnostic.source {
18123 text_without_backticks.push_str(source);
18124 code_ranges.push(0..source.len());
18125 text_without_backticks.push_str(": ");
18126 }
18127
18128 let mut prev_offset = 0;
18129 let mut in_code_block = false;
18130 let has_row_limit = max_message_rows.is_some();
18131 let mut newline_indices = diagnostic
18132 .message
18133 .match_indices('\n')
18134 .filter(|_| has_row_limit)
18135 .map(|(ix, _)| ix)
18136 .fuse()
18137 .peekable();
18138
18139 for (quote_ix, _) in diagnostic
18140 .message
18141 .match_indices('`')
18142 .chain([(diagnostic.message.len(), "")])
18143 {
18144 let mut first_newline_ix = None;
18145 let mut last_newline_ix = None;
18146 while let Some(newline_ix) = newline_indices.peek() {
18147 if *newline_ix < quote_ix {
18148 if first_newline_ix.is_none() {
18149 first_newline_ix = Some(*newline_ix);
18150 }
18151 last_newline_ix = Some(*newline_ix);
18152
18153 if let Some(rows_left) = &mut max_message_rows {
18154 if *rows_left == 0 {
18155 break;
18156 } else {
18157 *rows_left -= 1;
18158 }
18159 }
18160 let _ = newline_indices.next();
18161 } else {
18162 break;
18163 }
18164 }
18165 let prev_len = text_without_backticks.len();
18166 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18167 text_without_backticks.push_str(new_text);
18168 if in_code_block {
18169 code_ranges.push(prev_len..text_without_backticks.len());
18170 }
18171 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18172 in_code_block = !in_code_block;
18173 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18174 text_without_backticks.push_str("...");
18175 break;
18176 }
18177 }
18178
18179 (text_without_backticks.into(), code_ranges)
18180}
18181
18182fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18183 match severity {
18184 DiagnosticSeverity::ERROR => colors.error,
18185 DiagnosticSeverity::WARNING => colors.warning,
18186 DiagnosticSeverity::INFORMATION => colors.info,
18187 DiagnosticSeverity::HINT => colors.info,
18188 _ => colors.ignored,
18189 }
18190}
18191
18192pub fn styled_runs_for_code_label<'a>(
18193 label: &'a CodeLabel,
18194 syntax_theme: &'a theme::SyntaxTheme,
18195) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18196 let fade_out = HighlightStyle {
18197 fade_out: Some(0.35),
18198 ..Default::default()
18199 };
18200
18201 let mut prev_end = label.filter_range.end;
18202 label
18203 .runs
18204 .iter()
18205 .enumerate()
18206 .flat_map(move |(ix, (range, highlight_id))| {
18207 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18208 style
18209 } else {
18210 return Default::default();
18211 };
18212 let mut muted_style = style;
18213 muted_style.highlight(fade_out);
18214
18215 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18216 if range.start >= label.filter_range.end {
18217 if range.start > prev_end {
18218 runs.push((prev_end..range.start, fade_out));
18219 }
18220 runs.push((range.clone(), muted_style));
18221 } else if range.end <= label.filter_range.end {
18222 runs.push((range.clone(), style));
18223 } else {
18224 runs.push((range.start..label.filter_range.end, style));
18225 runs.push((label.filter_range.end..range.end, muted_style));
18226 }
18227 prev_end = cmp::max(prev_end, range.end);
18228
18229 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18230 runs.push((prev_end..label.text.len(), fade_out));
18231 }
18232
18233 runs
18234 })
18235}
18236
18237pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18238 let mut prev_index = 0;
18239 let mut prev_codepoint: Option<char> = None;
18240 text.char_indices()
18241 .chain([(text.len(), '\0')])
18242 .filter_map(move |(index, codepoint)| {
18243 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18244 let is_boundary = index == text.len()
18245 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18246 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18247 if is_boundary {
18248 let chunk = &text[prev_index..index];
18249 prev_index = index;
18250 Some(chunk)
18251 } else {
18252 None
18253 }
18254 })
18255}
18256
18257pub trait RangeToAnchorExt: Sized {
18258 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18259
18260 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18261 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18262 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18263 }
18264}
18265
18266impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18267 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18268 let start_offset = self.start.to_offset(snapshot);
18269 let end_offset = self.end.to_offset(snapshot);
18270 if start_offset == end_offset {
18271 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18272 } else {
18273 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18274 }
18275 }
18276}
18277
18278pub trait RowExt {
18279 fn as_f32(&self) -> f32;
18280
18281 fn next_row(&self) -> Self;
18282
18283 fn previous_row(&self) -> Self;
18284
18285 fn minus(&self, other: Self) -> u32;
18286}
18287
18288impl RowExt for DisplayRow {
18289 fn as_f32(&self) -> f32 {
18290 self.0 as f32
18291 }
18292
18293 fn next_row(&self) -> Self {
18294 Self(self.0 + 1)
18295 }
18296
18297 fn previous_row(&self) -> Self {
18298 Self(self.0.saturating_sub(1))
18299 }
18300
18301 fn minus(&self, other: Self) -> u32 {
18302 self.0 - other.0
18303 }
18304}
18305
18306impl RowExt for MultiBufferRow {
18307 fn as_f32(&self) -> f32 {
18308 self.0 as f32
18309 }
18310
18311 fn next_row(&self) -> Self {
18312 Self(self.0 + 1)
18313 }
18314
18315 fn previous_row(&self) -> Self {
18316 Self(self.0.saturating_sub(1))
18317 }
18318
18319 fn minus(&self, other: Self) -> u32 {
18320 self.0 - other.0
18321 }
18322}
18323
18324trait RowRangeExt {
18325 type Row;
18326
18327 fn len(&self) -> usize;
18328
18329 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18330}
18331
18332impl RowRangeExt for Range<MultiBufferRow> {
18333 type Row = MultiBufferRow;
18334
18335 fn len(&self) -> usize {
18336 (self.end.0 - self.start.0) as usize
18337 }
18338
18339 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18340 (self.start.0..self.end.0).map(MultiBufferRow)
18341 }
18342}
18343
18344impl RowRangeExt for Range<DisplayRow> {
18345 type Row = DisplayRow;
18346
18347 fn len(&self) -> usize {
18348 (self.end.0 - self.start.0) as usize
18349 }
18350
18351 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18352 (self.start.0..self.end.0).map(DisplayRow)
18353 }
18354}
18355
18356/// If select range has more than one line, we
18357/// just point the cursor to range.start.
18358fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18359 if range.start.row == range.end.row {
18360 range
18361 } else {
18362 range.start..range.start
18363 }
18364}
18365pub struct KillRing(ClipboardItem);
18366impl Global for KillRing {}
18367
18368const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18369
18370fn all_edits_insertions_or_deletions(
18371 edits: &Vec<(Range<Anchor>, String)>,
18372 snapshot: &MultiBufferSnapshot,
18373) -> bool {
18374 let mut all_insertions = true;
18375 let mut all_deletions = true;
18376
18377 for (range, new_text) in edits.iter() {
18378 let range_is_empty = range.to_offset(&snapshot).is_empty();
18379 let text_is_empty = new_text.is_empty();
18380
18381 if range_is_empty != text_is_empty {
18382 if range_is_empty {
18383 all_deletions = false;
18384 } else {
18385 all_insertions = false;
18386 }
18387 } else {
18388 return false;
18389 }
18390
18391 if !all_insertions && !all_deletions {
18392 return false;
18393 }
18394 }
18395 all_insertions || all_deletions
18396}
18397
18398struct MissingEditPredictionKeybindingTooltip;
18399
18400impl Render for MissingEditPredictionKeybindingTooltip {
18401 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18402 ui::tooltip_container(window, cx, |container, _, cx| {
18403 container
18404 .flex_shrink_0()
18405 .max_w_80()
18406 .min_h(rems_from_px(124.))
18407 .justify_between()
18408 .child(
18409 v_flex()
18410 .flex_1()
18411 .text_ui_sm(cx)
18412 .child(Label::new("Conflict with Accept Keybinding"))
18413 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18414 )
18415 .child(
18416 h_flex()
18417 .pb_1()
18418 .gap_1()
18419 .items_end()
18420 .w_full()
18421 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18422 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18423 }))
18424 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18425 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18426 })),
18427 )
18428 })
18429 }
18430}