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 WordsCompletionMode,
105 },
106 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
107 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
108 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
109 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
110};
111use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
112use linked_editing_ranges::refresh_linked_ranges;
113use mouse_context_menu::MouseContextMenu;
114use persistence::DB;
115pub use proposed_changes_editor::{
116 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
117};
118use smallvec::smallvec;
119use std::iter::Peekable;
120use task::{ResolvedTask, TaskTemplate, TaskVariables};
121
122use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
123pub use lsp::CompletionContext;
124use lsp::{
125 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
126 InsertTextFormat, LanguageServerId, LanguageServerName,
127};
128
129use language::BufferSnapshot;
130use movement::TextLayoutDetails;
131pub use multi_buffer::{
132 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
133 ToOffset, ToPoint,
134};
135use multi_buffer::{
136 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
137 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
138};
139use project::{
140 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
141 project_settings::{GitGutterSetting, ProjectSettings},
142 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
143 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
144 TaskSourceKind,
145};
146use rand::prelude::*;
147use rpc::{proto::*, ErrorExt};
148use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
149use selections_collection::{
150 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
151};
152use serde::{Deserialize, Serialize};
153use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
154use smallvec::SmallVec;
155use snippet::Snippet;
156use std::{
157 any::TypeId,
158 borrow::Cow,
159 cell::RefCell,
160 cmp::{self, Ordering, Reverse},
161 mem,
162 num::NonZeroU32,
163 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
164 path::{Path, PathBuf},
165 rc::Rc,
166 sync::Arc,
167 time::{Duration, Instant},
168};
169pub use sum_tree::Bias;
170use sum_tree::TreeMap;
171use text::{BufferId, OffsetUtf16, Rope};
172use theme::{
173 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
174 ThemeColors, ThemeSettings,
175};
176use ui::{
177 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
178 Tooltip,
179};
180use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
181use workspace::{
182 item::{ItemHandle, PreviewTabsSettings},
183 ItemId, RestoreOnStartupBehavior,
184};
185use workspace::{
186 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
187 WorkspaceSettings,
188};
189use workspace::{
190 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
191};
192use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
193
194use crate::hover_links::{find_url, find_url_from_range};
195use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
196
197pub const FILE_HEADER_HEIGHT: u32 = 2;
198pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
199pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
200pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
201const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
202const MAX_LINE_LEN: usize = 1024;
203const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
204const MAX_SELECTION_HISTORY_LEN: usize = 1024;
205pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
206#[doc(hidden)]
207pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
208
209pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
210pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
211pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
212
213pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
214pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
215
216const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
217 alt: true,
218 shift: true,
219 control: false,
220 platform: false,
221 function: false,
222};
223
224#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
225pub enum InlayId {
226 InlineCompletion(usize),
227 Hint(usize),
228}
229
230impl InlayId {
231 fn id(&self) -> usize {
232 match self {
233 Self::InlineCompletion(id) => *id,
234 Self::Hint(id) => *id,
235 }
236 }
237}
238
239enum DocumentHighlightRead {}
240enum DocumentHighlightWrite {}
241enum InputComposition {}
242enum SelectedTextHighlight {}
243
244#[derive(Debug, Copy, Clone, PartialEq, Eq)]
245pub enum Navigated {
246 Yes,
247 No,
248}
249
250impl Navigated {
251 pub fn from_bool(yes: bool) -> Navigated {
252 if yes {
253 Navigated::Yes
254 } else {
255 Navigated::No
256 }
257 }
258}
259
260#[derive(Debug, Clone, PartialEq, Eq)]
261enum DisplayDiffHunk {
262 Folded {
263 display_row: DisplayRow,
264 },
265 Unfolded {
266 is_created_file: bool,
267 diff_base_byte_range: Range<usize>,
268 display_row_range: Range<DisplayRow>,
269 multi_buffer_range: Range<Anchor>,
270 status: DiffHunkStatus,
271 },
272}
273
274pub fn init_settings(cx: &mut App) {
275 EditorSettings::register(cx);
276}
277
278pub fn init(cx: &mut App) {
279 init_settings(cx);
280
281 workspace::register_project_item::<Editor>(cx);
282 workspace::FollowableViewRegistry::register::<Editor>(cx);
283 workspace::register_serializable_item::<Editor>(cx);
284
285 cx.observe_new(
286 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
287 workspace.register_action(Editor::new_file);
288 workspace.register_action(Editor::new_file_vertical);
289 workspace.register_action(Editor::new_file_horizontal);
290 workspace.register_action(Editor::cancel_language_server_work);
291 },
292 )
293 .detach();
294
295 cx.on_action(move |_: &workspace::NewFile, cx| {
296 let app_state = workspace::AppState::global(cx);
297 if let Some(app_state) = app_state.upgrade() {
298 workspace::open_new(
299 Default::default(),
300 app_state,
301 cx,
302 |workspace, window, cx| {
303 Editor::new_file(workspace, &Default::default(), window, cx)
304 },
305 )
306 .detach();
307 }
308 });
309 cx.on_action(move |_: &workspace::NewWindow, cx| {
310 let app_state = workspace::AppState::global(cx);
311 if let Some(app_state) = app_state.upgrade() {
312 workspace::open_new(
313 Default::default(),
314 app_state,
315 cx,
316 |workspace, window, cx| {
317 cx.activate(true);
318 Editor::new_file(workspace, &Default::default(), window, cx)
319 },
320 )
321 .detach();
322 }
323 });
324}
325
326pub struct SearchWithinRange;
327
328trait InvalidationRegion {
329 fn ranges(&self) -> &[Range<Anchor>];
330}
331
332#[derive(Clone, Debug, PartialEq)]
333pub enum SelectPhase {
334 Begin {
335 position: DisplayPoint,
336 add: bool,
337 click_count: usize,
338 },
339 BeginColumnar {
340 position: DisplayPoint,
341 reset: bool,
342 goal_column: u32,
343 },
344 Extend {
345 position: DisplayPoint,
346 click_count: usize,
347 },
348 Update {
349 position: DisplayPoint,
350 goal_column: u32,
351 scroll_delta: gpui::Point<f32>,
352 },
353 End,
354}
355
356#[derive(Clone, Debug)]
357pub enum SelectMode {
358 Character,
359 Word(Range<Anchor>),
360 Line(Range<Anchor>),
361 All,
362}
363
364#[derive(Copy, Clone, PartialEq, Eq, Debug)]
365pub enum EditorMode {
366 SingleLine { auto_width: bool },
367 AutoHeight { max_lines: usize },
368 Full,
369}
370
371#[derive(Copy, Clone, Debug)]
372pub enum SoftWrap {
373 /// Prefer not to wrap at all.
374 ///
375 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
376 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
377 GitDiff,
378 /// Prefer a single line generally, unless an overly long line is encountered.
379 None,
380 /// Soft wrap lines that exceed the editor width.
381 EditorWidth,
382 /// Soft wrap lines at the preferred line length.
383 Column(u32),
384 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
385 Bounded(u32),
386}
387
388#[derive(Clone)]
389pub struct EditorStyle {
390 pub background: Hsla,
391 pub local_player: PlayerColor,
392 pub text: TextStyle,
393 pub scrollbar_width: Pixels,
394 pub syntax: Arc<SyntaxTheme>,
395 pub status: StatusColors,
396 pub inlay_hints_style: HighlightStyle,
397 pub inline_completion_styles: InlineCompletionStyles,
398 pub unnecessary_code_fade: f32,
399}
400
401impl Default for EditorStyle {
402 fn default() -> Self {
403 Self {
404 background: Hsla::default(),
405 local_player: PlayerColor::default(),
406 text: TextStyle::default(),
407 scrollbar_width: Pixels::default(),
408 syntax: Default::default(),
409 // HACK: Status colors don't have a real default.
410 // We should look into removing the status colors from the editor
411 // style and retrieve them directly from the theme.
412 status: StatusColors::dark(),
413 inlay_hints_style: HighlightStyle::default(),
414 inline_completion_styles: InlineCompletionStyles {
415 insertion: HighlightStyle::default(),
416 whitespace: HighlightStyle::default(),
417 },
418 unnecessary_code_fade: Default::default(),
419 }
420 }
421}
422
423pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
424 let show_background = language_settings::language_settings(None, None, cx)
425 .inlay_hints
426 .show_background;
427
428 HighlightStyle {
429 color: Some(cx.theme().status().hint),
430 background_color: show_background.then(|| cx.theme().status().hint_background),
431 ..HighlightStyle::default()
432 }
433}
434
435pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
436 InlineCompletionStyles {
437 insertion: HighlightStyle {
438 color: Some(cx.theme().status().predictive),
439 ..HighlightStyle::default()
440 },
441 whitespace: HighlightStyle {
442 background_color: Some(cx.theme().status().created_background),
443 ..HighlightStyle::default()
444 },
445 }
446}
447
448type CompletionId = usize;
449
450pub(crate) enum EditDisplayMode {
451 TabAccept,
452 DiffPopover,
453 Inline,
454}
455
456enum InlineCompletion {
457 Edit {
458 edits: Vec<(Range<Anchor>, String)>,
459 edit_preview: Option<EditPreview>,
460 display_mode: EditDisplayMode,
461 snapshot: BufferSnapshot,
462 },
463 Move {
464 target: Anchor,
465 snapshot: BufferSnapshot,
466 },
467}
468
469struct InlineCompletionState {
470 inlay_ids: Vec<InlayId>,
471 completion: InlineCompletion,
472 completion_id: Option<SharedString>,
473 invalidation_range: Range<Anchor>,
474}
475
476enum EditPredictionSettings {
477 Disabled,
478 Enabled {
479 show_in_menu: bool,
480 preview_requires_modifier: bool,
481 },
482}
483
484enum InlineCompletionHighlight {}
485
486#[derive(Debug, Clone)]
487struct InlineDiagnostic {
488 message: SharedString,
489 group_id: usize,
490 is_primary: bool,
491 start: Point,
492 severity: DiagnosticSeverity,
493}
494
495pub enum MenuInlineCompletionsPolicy {
496 Never,
497 ByProvider,
498}
499
500pub enum EditPredictionPreview {
501 /// Modifier is not pressed
502 Inactive { released_too_fast: bool },
503 /// Modifier pressed
504 Active {
505 since: Instant,
506 previous_scroll_position: Option<ScrollAnchor>,
507 },
508}
509
510impl EditPredictionPreview {
511 pub fn released_too_fast(&self) -> bool {
512 match self {
513 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
514 EditPredictionPreview::Active { .. } => false,
515 }
516 }
517
518 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
519 if let EditPredictionPreview::Active {
520 previous_scroll_position,
521 ..
522 } = self
523 {
524 *previous_scroll_position = scroll_position;
525 }
526 }
527}
528
529#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
530struct EditorActionId(usize);
531
532impl EditorActionId {
533 pub fn post_inc(&mut self) -> Self {
534 let answer = self.0;
535
536 *self = Self(answer + 1);
537
538 Self(answer)
539 }
540}
541
542// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
543// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
544
545type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
546type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
547
548#[derive(Default)]
549struct ScrollbarMarkerState {
550 scrollbar_size: Size<Pixels>,
551 dirty: bool,
552 markers: Arc<[PaintQuad]>,
553 pending_refresh: Option<Task<Result<()>>>,
554}
555
556impl ScrollbarMarkerState {
557 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
558 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
559 }
560}
561
562#[derive(Clone, Debug)]
563struct RunnableTasks {
564 templates: Vec<(TaskSourceKind, TaskTemplate)>,
565 offset: multi_buffer::Anchor,
566 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
567 column: u32,
568 // Values of all named captures, including those starting with '_'
569 extra_variables: HashMap<String, String>,
570 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
571 context_range: Range<BufferOffset>,
572}
573
574impl RunnableTasks {
575 fn resolve<'a>(
576 &'a self,
577 cx: &'a task::TaskContext,
578 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
579 self.templates.iter().filter_map(|(kind, template)| {
580 template
581 .resolve_task(&kind.to_id_base(), cx)
582 .map(|task| (kind.clone(), task))
583 })
584 }
585}
586
587#[derive(Clone)]
588struct ResolvedTasks {
589 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
590 position: Anchor,
591}
592#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
593struct BufferOffset(usize);
594
595// Addons allow storing per-editor state in other crates (e.g. Vim)
596pub trait Addon: 'static {
597 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
598
599 fn render_buffer_header_controls(
600 &self,
601 _: &ExcerptInfo,
602 _: &Window,
603 _: &App,
604 ) -> Option<AnyElement> {
605 None
606 }
607
608 fn to_any(&self) -> &dyn std::any::Any;
609}
610
611/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
612///
613/// See the [module level documentation](self) for more information.
614pub struct Editor {
615 focus_handle: FocusHandle,
616 last_focused_descendant: Option<WeakFocusHandle>,
617 /// The text buffer being edited
618 buffer: Entity<MultiBuffer>,
619 /// Map of how text in the buffer should be displayed.
620 /// Handles soft wraps, folds, fake inlay text insertions, etc.
621 pub display_map: Entity<DisplayMap>,
622 pub selections: SelectionsCollection,
623 pub scroll_manager: ScrollManager,
624 /// When inline assist editors are linked, they all render cursors because
625 /// typing enters text into each of them, even the ones that aren't focused.
626 pub(crate) show_cursor_when_unfocused: bool,
627 columnar_selection_tail: Option<Anchor>,
628 add_selections_state: Option<AddSelectionsState>,
629 select_next_state: Option<SelectNextState>,
630 select_prev_state: Option<SelectNextState>,
631 selection_history: SelectionHistory,
632 autoclose_regions: Vec<AutocloseRegion>,
633 snippet_stack: InvalidationStack<SnippetState>,
634 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
635 ime_transaction: Option<TransactionId>,
636 active_diagnostics: Option<ActiveDiagnosticGroup>,
637 show_inline_diagnostics: bool,
638 inline_diagnostics_update: Task<()>,
639 inline_diagnostics_enabled: bool,
640 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
641 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
642 hard_wrap: Option<usize>,
643
644 // TODO: make this a access method
645 pub project: Option<Entity<Project>>,
646 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
647 completion_provider: Option<Box<dyn CompletionProvider>>,
648 collaboration_hub: Option<Box<dyn CollaborationHub>>,
649 blink_manager: Entity<BlinkManager>,
650 show_cursor_names: bool,
651 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
652 pub show_local_selections: bool,
653 mode: EditorMode,
654 show_breadcrumbs: bool,
655 show_gutter: bool,
656 show_scrollbars: bool,
657 show_line_numbers: Option<bool>,
658 use_relative_line_numbers: Option<bool>,
659 show_git_diff_gutter: Option<bool>,
660 show_code_actions: Option<bool>,
661 show_runnables: Option<bool>,
662 show_wrap_guides: Option<bool>,
663 show_indent_guides: Option<bool>,
664 placeholder_text: Option<Arc<str>>,
665 highlight_order: usize,
666 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
667 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
668 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
669 scrollbar_marker_state: ScrollbarMarkerState,
670 active_indent_guides_state: ActiveIndentGuidesState,
671 nav_history: Option<ItemNavHistory>,
672 context_menu: RefCell<Option<CodeContextMenu>>,
673 mouse_context_menu: Option<MouseContextMenu>,
674 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
675 signature_help_state: SignatureHelpState,
676 auto_signature_help: Option<bool>,
677 find_all_references_task_sources: Vec<Anchor>,
678 next_completion_id: CompletionId,
679 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
680 code_actions_task: Option<Task<Result<()>>>,
681 selection_highlight_task: Option<Task<()>>,
682 document_highlights_task: Option<Task<()>>,
683 linked_editing_range_task: Option<Task<Option<()>>>,
684 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
685 pending_rename: Option<RenameState>,
686 searchable: bool,
687 cursor_shape: CursorShape,
688 current_line_highlight: Option<CurrentLineHighlight>,
689 collapse_matches: bool,
690 autoindent_mode: Option<AutoindentMode>,
691 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
692 input_enabled: bool,
693 use_modal_editing: bool,
694 read_only: bool,
695 leader_peer_id: Option<PeerId>,
696 remote_id: Option<ViewId>,
697 hover_state: HoverState,
698 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
699 gutter_hovered: bool,
700 hovered_link_state: Option<HoveredLinkState>,
701 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
702 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
703 active_inline_completion: Option<InlineCompletionState>,
704 /// Used to prevent flickering as the user types while the menu is open
705 stale_inline_completion_in_menu: Option<InlineCompletionState>,
706 edit_prediction_settings: EditPredictionSettings,
707 inline_completions_hidden_for_vim_mode: bool,
708 show_inline_completions_override: Option<bool>,
709 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
710 edit_prediction_preview: EditPredictionPreview,
711 edit_prediction_indent_conflict: bool,
712 edit_prediction_requires_modifier_in_indent_conflict: bool,
713 inlay_hint_cache: InlayHintCache,
714 next_inlay_id: usize,
715 _subscriptions: Vec<Subscription>,
716 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
717 gutter_dimensions: GutterDimensions,
718 style: Option<EditorStyle>,
719 text_style_refinement: Option<TextStyleRefinement>,
720 next_editor_action_id: EditorActionId,
721 editor_actions:
722 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
723 use_autoclose: bool,
724 use_auto_surround: bool,
725 auto_replace_emoji_shortcode: bool,
726 jsx_tag_auto_close_enabled_in_any_buffer: bool,
727 show_git_blame_gutter: bool,
728 show_git_blame_inline: bool,
729 show_git_blame_inline_delay_task: Option<Task<()>>,
730 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
731 git_blame_inline_enabled: bool,
732 serialize_dirty_buffers: bool,
733 show_selection_menu: Option<bool>,
734 blame: Option<Entity<GitBlame>>,
735 blame_subscription: Option<Subscription>,
736 custom_context_menu: Option<
737 Box<
738 dyn 'static
739 + Fn(
740 &mut Self,
741 DisplayPoint,
742 &mut Window,
743 &mut Context<Self>,
744 ) -> Option<Entity<ui::ContextMenu>>,
745 >,
746 >,
747 last_bounds: Option<Bounds<Pixels>>,
748 last_position_map: Option<Rc<PositionMap>>,
749 expect_bounds_change: Option<Bounds<Pixels>>,
750 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
751 tasks_update_task: Option<Task<()>>,
752 in_project_search: bool,
753 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
754 breadcrumb_header: Option<String>,
755 focused_block: Option<FocusedBlock>,
756 next_scroll_position: NextScrollCursorCenterTopBottom,
757 addons: HashMap<TypeId, Box<dyn Addon>>,
758 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
759 load_diff_task: Option<Shared<Task<()>>>,
760 selection_mark_mode: bool,
761 toggle_fold_multiple_buffers: Task<()>,
762 _scroll_cursor_center_top_bottom_task: Task<()>,
763 serialize_selections: Task<()>,
764}
765
766#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
767enum NextScrollCursorCenterTopBottom {
768 #[default]
769 Center,
770 Top,
771 Bottom,
772}
773
774impl NextScrollCursorCenterTopBottom {
775 fn next(&self) -> Self {
776 match self {
777 Self::Center => Self::Top,
778 Self::Top => Self::Bottom,
779 Self::Bottom => Self::Center,
780 }
781 }
782}
783
784#[derive(Clone)]
785pub struct EditorSnapshot {
786 pub mode: EditorMode,
787 show_gutter: bool,
788 show_line_numbers: Option<bool>,
789 show_git_diff_gutter: Option<bool>,
790 show_code_actions: Option<bool>,
791 show_runnables: Option<bool>,
792 git_blame_gutter_max_author_length: Option<usize>,
793 pub display_snapshot: DisplaySnapshot,
794 pub placeholder_text: Option<Arc<str>>,
795 is_focused: bool,
796 scroll_anchor: ScrollAnchor,
797 ongoing_scroll: OngoingScroll,
798 current_line_highlight: CurrentLineHighlight,
799 gutter_hovered: bool,
800}
801
802const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
803
804#[derive(Default, Debug, Clone, Copy)]
805pub struct GutterDimensions {
806 pub left_padding: Pixels,
807 pub right_padding: Pixels,
808 pub width: Pixels,
809 pub margin: Pixels,
810 pub git_blame_entries_width: Option<Pixels>,
811}
812
813impl GutterDimensions {
814 /// The full width of the space taken up by the gutter.
815 pub fn full_width(&self) -> Pixels {
816 self.margin + self.width
817 }
818
819 /// The width of the space reserved for the fold indicators,
820 /// use alongside 'justify_end' and `gutter_width` to
821 /// right align content with the line numbers
822 pub fn fold_area_width(&self) -> Pixels {
823 self.margin + self.right_padding
824 }
825}
826
827#[derive(Debug)]
828pub struct RemoteSelection {
829 pub replica_id: ReplicaId,
830 pub selection: Selection<Anchor>,
831 pub cursor_shape: CursorShape,
832 pub peer_id: PeerId,
833 pub line_mode: bool,
834 pub participant_index: Option<ParticipantIndex>,
835 pub user_name: Option<SharedString>,
836}
837
838#[derive(Clone, Debug)]
839struct SelectionHistoryEntry {
840 selections: Arc<[Selection<Anchor>]>,
841 select_next_state: Option<SelectNextState>,
842 select_prev_state: Option<SelectNextState>,
843 add_selections_state: Option<AddSelectionsState>,
844}
845
846enum SelectionHistoryMode {
847 Normal,
848 Undoing,
849 Redoing,
850}
851
852#[derive(Clone, PartialEq, Eq, Hash)]
853struct HoveredCursor {
854 replica_id: u16,
855 selection_id: usize,
856}
857
858impl Default for SelectionHistoryMode {
859 fn default() -> Self {
860 Self::Normal
861 }
862}
863
864#[derive(Default)]
865struct SelectionHistory {
866 #[allow(clippy::type_complexity)]
867 selections_by_transaction:
868 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
869 mode: SelectionHistoryMode,
870 undo_stack: VecDeque<SelectionHistoryEntry>,
871 redo_stack: VecDeque<SelectionHistoryEntry>,
872}
873
874impl SelectionHistory {
875 fn insert_transaction(
876 &mut self,
877 transaction_id: TransactionId,
878 selections: Arc<[Selection<Anchor>]>,
879 ) {
880 self.selections_by_transaction
881 .insert(transaction_id, (selections, None));
882 }
883
884 #[allow(clippy::type_complexity)]
885 fn transaction(
886 &self,
887 transaction_id: TransactionId,
888 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
889 self.selections_by_transaction.get(&transaction_id)
890 }
891
892 #[allow(clippy::type_complexity)]
893 fn transaction_mut(
894 &mut self,
895 transaction_id: TransactionId,
896 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
897 self.selections_by_transaction.get_mut(&transaction_id)
898 }
899
900 fn push(&mut self, entry: SelectionHistoryEntry) {
901 if !entry.selections.is_empty() {
902 match self.mode {
903 SelectionHistoryMode::Normal => {
904 self.push_undo(entry);
905 self.redo_stack.clear();
906 }
907 SelectionHistoryMode::Undoing => self.push_redo(entry),
908 SelectionHistoryMode::Redoing => self.push_undo(entry),
909 }
910 }
911 }
912
913 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
914 if self
915 .undo_stack
916 .back()
917 .map_or(true, |e| e.selections != entry.selections)
918 {
919 self.undo_stack.push_back(entry);
920 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
921 self.undo_stack.pop_front();
922 }
923 }
924 }
925
926 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
927 if self
928 .redo_stack
929 .back()
930 .map_or(true, |e| e.selections != entry.selections)
931 {
932 self.redo_stack.push_back(entry);
933 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
934 self.redo_stack.pop_front();
935 }
936 }
937 }
938}
939
940struct RowHighlight {
941 index: usize,
942 range: Range<Anchor>,
943 color: Hsla,
944 should_autoscroll: bool,
945}
946
947#[derive(Clone, Debug)]
948struct AddSelectionsState {
949 above: bool,
950 stack: Vec<usize>,
951}
952
953#[derive(Clone)]
954struct SelectNextState {
955 query: AhoCorasick,
956 wordwise: bool,
957 done: bool,
958}
959
960impl std::fmt::Debug for SelectNextState {
961 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
962 f.debug_struct(std::any::type_name::<Self>())
963 .field("wordwise", &self.wordwise)
964 .field("done", &self.done)
965 .finish()
966 }
967}
968
969#[derive(Debug)]
970struct AutocloseRegion {
971 selection_id: usize,
972 range: Range<Anchor>,
973 pair: BracketPair,
974}
975
976#[derive(Debug)]
977struct SnippetState {
978 ranges: Vec<Vec<Range<Anchor>>>,
979 active_index: usize,
980 choices: Vec<Option<Vec<String>>>,
981}
982
983#[doc(hidden)]
984pub struct RenameState {
985 pub range: Range<Anchor>,
986 pub old_name: Arc<str>,
987 pub editor: Entity<Editor>,
988 block_id: CustomBlockId,
989}
990
991struct InvalidationStack<T>(Vec<T>);
992
993struct RegisteredInlineCompletionProvider {
994 provider: Arc<dyn InlineCompletionProviderHandle>,
995 _subscription: Subscription,
996}
997
998#[derive(Debug, PartialEq, Eq)]
999struct ActiveDiagnosticGroup {
1000 primary_range: Range<Anchor>,
1001 primary_message: String,
1002 group_id: usize,
1003 blocks: HashMap<CustomBlockId, Diagnostic>,
1004 is_valid: bool,
1005}
1006
1007#[derive(Serialize, Deserialize, Clone, Debug)]
1008pub struct ClipboardSelection {
1009 /// The number of bytes in this selection.
1010 pub len: usize,
1011 /// Whether this was a full-line selection.
1012 pub is_entire_line: bool,
1013 /// The indentation of the first line when this content was originally copied.
1014 pub first_line_indent: u32,
1015}
1016
1017#[derive(Debug)]
1018pub(crate) struct NavigationData {
1019 cursor_anchor: Anchor,
1020 cursor_position: Point,
1021 scroll_anchor: ScrollAnchor,
1022 scroll_top_row: u32,
1023}
1024
1025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1026pub enum GotoDefinitionKind {
1027 Symbol,
1028 Declaration,
1029 Type,
1030 Implementation,
1031}
1032
1033#[derive(Debug, Clone)]
1034enum InlayHintRefreshReason {
1035 ModifiersChanged(bool),
1036 Toggle(bool),
1037 SettingsChange(InlayHintSettings),
1038 NewLinesShown,
1039 BufferEdited(HashSet<Arc<Language>>),
1040 RefreshRequested,
1041 ExcerptsRemoved(Vec<ExcerptId>),
1042}
1043
1044impl InlayHintRefreshReason {
1045 fn description(&self) -> &'static str {
1046 match self {
1047 Self::ModifiersChanged(_) => "modifiers changed",
1048 Self::Toggle(_) => "toggle",
1049 Self::SettingsChange(_) => "settings change",
1050 Self::NewLinesShown => "new lines shown",
1051 Self::BufferEdited(_) => "buffer edited",
1052 Self::RefreshRequested => "refresh requested",
1053 Self::ExcerptsRemoved(_) => "excerpts removed",
1054 }
1055 }
1056}
1057
1058pub enum FormatTarget {
1059 Buffers,
1060 Ranges(Vec<Range<MultiBufferPoint>>),
1061}
1062
1063pub(crate) struct FocusedBlock {
1064 id: BlockId,
1065 focus_handle: WeakFocusHandle,
1066}
1067
1068#[derive(Clone)]
1069enum JumpData {
1070 MultiBufferRow {
1071 row: MultiBufferRow,
1072 line_offset_from_top: u32,
1073 },
1074 MultiBufferPoint {
1075 excerpt_id: ExcerptId,
1076 position: Point,
1077 anchor: text::Anchor,
1078 line_offset_from_top: u32,
1079 },
1080}
1081
1082pub enum MultibufferSelectionMode {
1083 First,
1084 All,
1085}
1086
1087impl Editor {
1088 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1089 let buffer = cx.new(|cx| Buffer::local("", cx));
1090 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1091 Self::new(
1092 EditorMode::SingleLine { auto_width: false },
1093 buffer,
1094 None,
1095 false,
1096 window,
1097 cx,
1098 )
1099 }
1100
1101 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1102 let buffer = cx.new(|cx| Buffer::local("", cx));
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1105 }
1106
1107 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1108 let buffer = cx.new(|cx| Buffer::local("", cx));
1109 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1110 Self::new(
1111 EditorMode::SingleLine { auto_width: true },
1112 buffer,
1113 None,
1114 false,
1115 window,
1116 cx,
1117 )
1118 }
1119
1120 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1121 let buffer = cx.new(|cx| Buffer::local("", cx));
1122 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1123 Self::new(
1124 EditorMode::AutoHeight { max_lines },
1125 buffer,
1126 None,
1127 false,
1128 window,
1129 cx,
1130 )
1131 }
1132
1133 pub fn for_buffer(
1134 buffer: Entity<Buffer>,
1135 project: Option<Entity<Project>>,
1136 window: &mut Window,
1137 cx: &mut Context<Self>,
1138 ) -> Self {
1139 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1140 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1141 }
1142
1143 pub fn for_multibuffer(
1144 buffer: Entity<MultiBuffer>,
1145 project: Option<Entity<Project>>,
1146 show_excerpt_controls: bool,
1147 window: &mut Window,
1148 cx: &mut Context<Self>,
1149 ) -> Self {
1150 Self::new(
1151 EditorMode::Full,
1152 buffer,
1153 project,
1154 show_excerpt_controls,
1155 window,
1156 cx,
1157 )
1158 }
1159
1160 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1161 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1162 let mut clone = Self::new(
1163 self.mode,
1164 self.buffer.clone(),
1165 self.project.clone(),
1166 show_excerpt_controls,
1167 window,
1168 cx,
1169 );
1170 self.display_map.update(cx, |display_map, cx| {
1171 let snapshot = display_map.snapshot(cx);
1172 clone.display_map.update(cx, |display_map, cx| {
1173 display_map.set_state(&snapshot, cx);
1174 });
1175 });
1176 clone.selections.clone_state(&self.selections);
1177 clone.scroll_manager.clone_state(&self.scroll_manager);
1178 clone.searchable = self.searchable;
1179 clone
1180 }
1181
1182 pub fn new(
1183 mode: EditorMode,
1184 buffer: Entity<MultiBuffer>,
1185 project: Option<Entity<Project>>,
1186 show_excerpt_controls: bool,
1187 window: &mut Window,
1188 cx: &mut Context<Self>,
1189 ) -> Self {
1190 let style = window.text_style();
1191 let font_size = style.font_size.to_pixels(window.rem_size());
1192 let editor = cx.entity().downgrade();
1193 let fold_placeholder = FoldPlaceholder {
1194 constrain_width: true,
1195 render: Arc::new(move |fold_id, fold_range, cx| {
1196 let editor = editor.clone();
1197 div()
1198 .id(fold_id)
1199 .bg(cx.theme().colors().ghost_element_background)
1200 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1201 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1202 .rounded_xs()
1203 .size_full()
1204 .cursor_pointer()
1205 .child("⋯")
1206 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1207 .on_click(move |_, _window, cx| {
1208 editor
1209 .update(cx, |editor, cx| {
1210 editor.unfold_ranges(
1211 &[fold_range.start..fold_range.end],
1212 true,
1213 false,
1214 cx,
1215 );
1216 cx.stop_propagation();
1217 })
1218 .ok();
1219 })
1220 .into_any()
1221 }),
1222 merge_adjacent: true,
1223 ..Default::default()
1224 };
1225 let display_map = cx.new(|cx| {
1226 DisplayMap::new(
1227 buffer.clone(),
1228 style.font(),
1229 font_size,
1230 None,
1231 show_excerpt_controls,
1232 FILE_HEADER_HEIGHT,
1233 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1234 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1235 fold_placeholder,
1236 cx,
1237 )
1238 });
1239
1240 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1241
1242 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1243
1244 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1245 .then(|| language_settings::SoftWrap::None);
1246
1247 let mut project_subscriptions = Vec::new();
1248 if mode == EditorMode::Full {
1249 if let Some(project) = project.as_ref() {
1250 project_subscriptions.push(cx.subscribe_in(
1251 project,
1252 window,
1253 |editor, _, event, window, cx| {
1254 if let project::Event::RefreshInlayHints = event {
1255 editor
1256 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1257 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1258 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1259 let focus_handle = editor.focus_handle(cx);
1260 if focus_handle.is_focused(window) {
1261 let snapshot = buffer.read(cx).snapshot();
1262 for (range, snippet) in snippet_edits {
1263 let editor_range =
1264 language::range_from_lsp(*range).to_offset(&snapshot);
1265 editor
1266 .insert_snippet(
1267 &[editor_range],
1268 snippet.clone(),
1269 window,
1270 cx,
1271 )
1272 .ok();
1273 }
1274 }
1275 }
1276 }
1277 },
1278 ));
1279 if let Some(task_inventory) = project
1280 .read(cx)
1281 .task_store()
1282 .read(cx)
1283 .task_inventory()
1284 .cloned()
1285 {
1286 project_subscriptions.push(cx.observe_in(
1287 &task_inventory,
1288 window,
1289 |editor, _, window, cx| {
1290 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1291 },
1292 ));
1293 }
1294 }
1295 }
1296
1297 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1298
1299 let inlay_hint_settings =
1300 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1301 let focus_handle = cx.focus_handle();
1302 cx.on_focus(&focus_handle, window, Self::handle_focus)
1303 .detach();
1304 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1305 .detach();
1306 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1307 .detach();
1308 cx.on_blur(&focus_handle, window, Self::handle_blur)
1309 .detach();
1310
1311 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1312 Some(false)
1313 } else {
1314 None
1315 };
1316
1317 let mut code_action_providers = Vec::new();
1318 let mut load_uncommitted_diff = None;
1319 if let Some(project) = project.clone() {
1320 load_uncommitted_diff = Some(
1321 get_uncommitted_diff_for_buffer(
1322 &project,
1323 buffer.read(cx).all_buffers(),
1324 buffer.clone(),
1325 cx,
1326 )
1327 .shared(),
1328 );
1329 code_action_providers.push(Rc::new(project) as Rc<_>);
1330 }
1331
1332 let mut this = Self {
1333 focus_handle,
1334 show_cursor_when_unfocused: false,
1335 last_focused_descendant: None,
1336 buffer: buffer.clone(),
1337 display_map: display_map.clone(),
1338 selections,
1339 scroll_manager: ScrollManager::new(cx),
1340 columnar_selection_tail: None,
1341 add_selections_state: None,
1342 select_next_state: None,
1343 select_prev_state: None,
1344 selection_history: Default::default(),
1345 autoclose_regions: Default::default(),
1346 snippet_stack: Default::default(),
1347 select_larger_syntax_node_stack: Vec::new(),
1348 ime_transaction: Default::default(),
1349 active_diagnostics: None,
1350 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1351 inline_diagnostics_update: Task::ready(()),
1352 inline_diagnostics: Vec::new(),
1353 soft_wrap_mode_override,
1354 hard_wrap: None,
1355 completion_provider: project.clone().map(|project| Box::new(project) as _),
1356 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1357 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1358 project,
1359 blink_manager: blink_manager.clone(),
1360 show_local_selections: true,
1361 show_scrollbars: true,
1362 mode,
1363 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1364 show_gutter: mode == EditorMode::Full,
1365 show_line_numbers: None,
1366 use_relative_line_numbers: None,
1367 show_git_diff_gutter: None,
1368 show_code_actions: None,
1369 show_runnables: None,
1370 show_wrap_guides: None,
1371 show_indent_guides,
1372 placeholder_text: None,
1373 highlight_order: 0,
1374 highlighted_rows: HashMap::default(),
1375 background_highlights: Default::default(),
1376 gutter_highlights: TreeMap::default(),
1377 scrollbar_marker_state: ScrollbarMarkerState::default(),
1378 active_indent_guides_state: ActiveIndentGuidesState::default(),
1379 nav_history: None,
1380 context_menu: RefCell::new(None),
1381 mouse_context_menu: None,
1382 completion_tasks: Default::default(),
1383 signature_help_state: SignatureHelpState::default(),
1384 auto_signature_help: None,
1385 find_all_references_task_sources: Vec::new(),
1386 next_completion_id: 0,
1387 next_inlay_id: 0,
1388 code_action_providers,
1389 available_code_actions: Default::default(),
1390 code_actions_task: Default::default(),
1391 selection_highlight_task: Default::default(),
1392 document_highlights_task: Default::default(),
1393 linked_editing_range_task: Default::default(),
1394 pending_rename: Default::default(),
1395 searchable: true,
1396 cursor_shape: EditorSettings::get_global(cx)
1397 .cursor_shape
1398 .unwrap_or_default(),
1399 current_line_highlight: None,
1400 autoindent_mode: Some(AutoindentMode::EachLine),
1401 collapse_matches: false,
1402 workspace: None,
1403 input_enabled: true,
1404 use_modal_editing: mode == EditorMode::Full,
1405 read_only: false,
1406 use_autoclose: true,
1407 use_auto_surround: true,
1408 auto_replace_emoji_shortcode: false,
1409 jsx_tag_auto_close_enabled_in_any_buffer: false,
1410 leader_peer_id: None,
1411 remote_id: None,
1412 hover_state: Default::default(),
1413 pending_mouse_down: None,
1414 hovered_link_state: Default::default(),
1415 edit_prediction_provider: None,
1416 active_inline_completion: None,
1417 stale_inline_completion_in_menu: None,
1418 edit_prediction_preview: EditPredictionPreview::Inactive {
1419 released_too_fast: false,
1420 },
1421 inline_diagnostics_enabled: mode == EditorMode::Full,
1422 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1423
1424 gutter_hovered: false,
1425 pixel_position_of_newest_cursor: None,
1426 last_bounds: None,
1427 last_position_map: None,
1428 expect_bounds_change: None,
1429 gutter_dimensions: GutterDimensions::default(),
1430 style: None,
1431 show_cursor_names: false,
1432 hovered_cursors: Default::default(),
1433 next_editor_action_id: EditorActionId::default(),
1434 editor_actions: Rc::default(),
1435 inline_completions_hidden_for_vim_mode: false,
1436 show_inline_completions_override: None,
1437 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1438 edit_prediction_settings: EditPredictionSettings::Disabled,
1439 edit_prediction_indent_conflict: false,
1440 edit_prediction_requires_modifier_in_indent_conflict: true,
1441 custom_context_menu: None,
1442 show_git_blame_gutter: false,
1443 show_git_blame_inline: false,
1444 show_selection_menu: None,
1445 show_git_blame_inline_delay_task: None,
1446 git_blame_inline_tooltip: None,
1447 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1448 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1449 .session
1450 .restore_unsaved_buffers,
1451 blame: None,
1452 blame_subscription: None,
1453 tasks: Default::default(),
1454 _subscriptions: vec![
1455 cx.observe(&buffer, Self::on_buffer_changed),
1456 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1457 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1458 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1459 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1460 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1461 cx.observe_window_activation(window, |editor, window, cx| {
1462 let active = window.is_window_active();
1463 editor.blink_manager.update(cx, |blink_manager, cx| {
1464 if active {
1465 blink_manager.enable(cx);
1466 } else {
1467 blink_manager.disable(cx);
1468 }
1469 });
1470 }),
1471 ],
1472 tasks_update_task: None,
1473 linked_edit_ranges: Default::default(),
1474 in_project_search: false,
1475 previous_search_ranges: None,
1476 breadcrumb_header: None,
1477 focused_block: None,
1478 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1479 addons: HashMap::default(),
1480 registered_buffers: HashMap::default(),
1481 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1482 selection_mark_mode: false,
1483 toggle_fold_multiple_buffers: Task::ready(()),
1484 serialize_selections: Task::ready(()),
1485 text_style_refinement: None,
1486 load_diff_task: load_uncommitted_diff,
1487 };
1488 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1489 this._subscriptions.extend(project_subscriptions);
1490
1491 this.end_selection(window, cx);
1492 this.scroll_manager.show_scrollbar(window, cx);
1493 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1494
1495 if mode == EditorMode::Full {
1496 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1497 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1498
1499 if this.git_blame_inline_enabled {
1500 this.git_blame_inline_enabled = true;
1501 this.start_git_blame_inline(false, window, cx);
1502 }
1503
1504 if let Some(buffer) = buffer.read(cx).as_singleton() {
1505 if let Some(project) = this.project.as_ref() {
1506 let handle = project.update(cx, |project, cx| {
1507 project.register_buffer_with_language_servers(&buffer, cx)
1508 });
1509 this.registered_buffers
1510 .insert(buffer.read(cx).remote_id(), handle);
1511 }
1512 }
1513 }
1514
1515 this.report_editor_event("Editor Opened", None, cx);
1516 this
1517 }
1518
1519 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1520 self.mouse_context_menu
1521 .as_ref()
1522 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1523 }
1524
1525 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1526 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1527 }
1528
1529 fn key_context_internal(
1530 &self,
1531 has_active_edit_prediction: bool,
1532 window: &Window,
1533 cx: &App,
1534 ) -> KeyContext {
1535 let mut key_context = KeyContext::new_with_defaults();
1536 key_context.add("Editor");
1537 let mode = match self.mode {
1538 EditorMode::SingleLine { .. } => "single_line",
1539 EditorMode::AutoHeight { .. } => "auto_height",
1540 EditorMode::Full => "full",
1541 };
1542
1543 if EditorSettings::jupyter_enabled(cx) {
1544 key_context.add("jupyter");
1545 }
1546
1547 key_context.set("mode", mode);
1548 if self.pending_rename.is_some() {
1549 key_context.add("renaming");
1550 }
1551
1552 match self.context_menu.borrow().as_ref() {
1553 Some(CodeContextMenu::Completions(_)) => {
1554 key_context.add("menu");
1555 key_context.add("showing_completions");
1556 }
1557 Some(CodeContextMenu::CodeActions(_)) => {
1558 key_context.add("menu");
1559 key_context.add("showing_code_actions")
1560 }
1561 None => {}
1562 }
1563
1564 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1565 if !self.focus_handle(cx).contains_focused(window, cx)
1566 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1567 {
1568 for addon in self.addons.values() {
1569 addon.extend_key_context(&mut key_context, cx)
1570 }
1571 }
1572
1573 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1574 if let Some(extension) = singleton_buffer
1575 .read(cx)
1576 .file()
1577 .and_then(|file| file.path().extension()?.to_str())
1578 {
1579 key_context.set("extension", extension.to_string());
1580 }
1581 } else {
1582 key_context.add("multibuffer");
1583 }
1584
1585 if has_active_edit_prediction {
1586 if self.edit_prediction_in_conflict() {
1587 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1588 } else {
1589 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1590 key_context.add("copilot_suggestion");
1591 }
1592 }
1593
1594 if self.selection_mark_mode {
1595 key_context.add("selection_mode");
1596 }
1597
1598 key_context
1599 }
1600
1601 pub fn edit_prediction_in_conflict(&self) -> bool {
1602 if !self.show_edit_predictions_in_menu() {
1603 return false;
1604 }
1605
1606 let showing_completions = self
1607 .context_menu
1608 .borrow()
1609 .as_ref()
1610 .map_or(false, |context| {
1611 matches!(context, CodeContextMenu::Completions(_))
1612 });
1613
1614 showing_completions
1615 || self.edit_prediction_requires_modifier()
1616 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1617 // bindings to insert tab characters.
1618 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1619 }
1620
1621 pub fn accept_edit_prediction_keybind(
1622 &self,
1623 window: &Window,
1624 cx: &App,
1625 ) -> AcceptEditPredictionBinding {
1626 let key_context = self.key_context_internal(true, window, cx);
1627 let in_conflict = self.edit_prediction_in_conflict();
1628
1629 AcceptEditPredictionBinding(
1630 window
1631 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1632 .into_iter()
1633 .filter(|binding| {
1634 !in_conflict
1635 || binding
1636 .keystrokes()
1637 .first()
1638 .map_or(false, |keystroke| keystroke.modifiers.modified())
1639 })
1640 .rev()
1641 .min_by_key(|binding| {
1642 binding
1643 .keystrokes()
1644 .first()
1645 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1646 }),
1647 )
1648 }
1649
1650 pub fn new_file(
1651 workspace: &mut Workspace,
1652 _: &workspace::NewFile,
1653 window: &mut Window,
1654 cx: &mut Context<Workspace>,
1655 ) {
1656 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1657 "Failed to create buffer",
1658 window,
1659 cx,
1660 |e, _, _| match e.error_code() {
1661 ErrorCode::RemoteUpgradeRequired => Some(format!(
1662 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1663 e.error_tag("required").unwrap_or("the latest version")
1664 )),
1665 _ => None,
1666 },
1667 );
1668 }
1669
1670 pub fn new_in_workspace(
1671 workspace: &mut Workspace,
1672 window: &mut Window,
1673 cx: &mut Context<Workspace>,
1674 ) -> Task<Result<Entity<Editor>>> {
1675 let project = workspace.project().clone();
1676 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1677
1678 cx.spawn_in(window, |workspace, mut cx| async move {
1679 let buffer = create.await?;
1680 workspace.update_in(&mut cx, |workspace, window, cx| {
1681 let editor =
1682 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1683 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1684 editor
1685 })
1686 })
1687 }
1688
1689 fn new_file_vertical(
1690 workspace: &mut Workspace,
1691 _: &workspace::NewFileSplitVertical,
1692 window: &mut Window,
1693 cx: &mut Context<Workspace>,
1694 ) {
1695 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1696 }
1697
1698 fn new_file_horizontal(
1699 workspace: &mut Workspace,
1700 _: &workspace::NewFileSplitHorizontal,
1701 window: &mut Window,
1702 cx: &mut Context<Workspace>,
1703 ) {
1704 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1705 }
1706
1707 fn new_file_in_direction(
1708 workspace: &mut Workspace,
1709 direction: SplitDirection,
1710 window: &mut Window,
1711 cx: &mut Context<Workspace>,
1712 ) {
1713 let project = workspace.project().clone();
1714 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1715
1716 cx.spawn_in(window, |workspace, mut cx| async move {
1717 let buffer = create.await?;
1718 workspace.update_in(&mut cx, move |workspace, window, cx| {
1719 workspace.split_item(
1720 direction,
1721 Box::new(
1722 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1723 ),
1724 window,
1725 cx,
1726 )
1727 })?;
1728 anyhow::Ok(())
1729 })
1730 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1731 match e.error_code() {
1732 ErrorCode::RemoteUpgradeRequired => Some(format!(
1733 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1734 e.error_tag("required").unwrap_or("the latest version")
1735 )),
1736 _ => None,
1737 }
1738 });
1739 }
1740
1741 pub fn leader_peer_id(&self) -> Option<PeerId> {
1742 self.leader_peer_id
1743 }
1744
1745 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1746 &self.buffer
1747 }
1748
1749 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1750 self.workspace.as_ref()?.0.upgrade()
1751 }
1752
1753 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1754 self.buffer().read(cx).title(cx)
1755 }
1756
1757 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1758 let git_blame_gutter_max_author_length = self
1759 .render_git_blame_gutter(cx)
1760 .then(|| {
1761 if let Some(blame) = self.blame.as_ref() {
1762 let max_author_length =
1763 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1764 Some(max_author_length)
1765 } else {
1766 None
1767 }
1768 })
1769 .flatten();
1770
1771 EditorSnapshot {
1772 mode: self.mode,
1773 show_gutter: self.show_gutter,
1774 show_line_numbers: self.show_line_numbers,
1775 show_git_diff_gutter: self.show_git_diff_gutter,
1776 show_code_actions: self.show_code_actions,
1777 show_runnables: self.show_runnables,
1778 git_blame_gutter_max_author_length,
1779 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1780 scroll_anchor: self.scroll_manager.anchor(),
1781 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1782 placeholder_text: self.placeholder_text.clone(),
1783 is_focused: self.focus_handle.is_focused(window),
1784 current_line_highlight: self
1785 .current_line_highlight
1786 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1787 gutter_hovered: self.gutter_hovered,
1788 }
1789 }
1790
1791 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1792 self.buffer.read(cx).language_at(point, cx)
1793 }
1794
1795 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1796 self.buffer.read(cx).read(cx).file_at(point).cloned()
1797 }
1798
1799 pub fn active_excerpt(
1800 &self,
1801 cx: &App,
1802 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1803 self.buffer
1804 .read(cx)
1805 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1806 }
1807
1808 pub fn mode(&self) -> EditorMode {
1809 self.mode
1810 }
1811
1812 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1813 self.collaboration_hub.as_deref()
1814 }
1815
1816 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1817 self.collaboration_hub = Some(hub);
1818 }
1819
1820 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1821 self.in_project_search = in_project_search;
1822 }
1823
1824 pub fn set_custom_context_menu(
1825 &mut self,
1826 f: impl 'static
1827 + Fn(
1828 &mut Self,
1829 DisplayPoint,
1830 &mut Window,
1831 &mut Context<Self>,
1832 ) -> Option<Entity<ui::ContextMenu>>,
1833 ) {
1834 self.custom_context_menu = Some(Box::new(f))
1835 }
1836
1837 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1838 self.completion_provider = provider;
1839 }
1840
1841 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1842 self.semantics_provider.clone()
1843 }
1844
1845 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1846 self.semantics_provider = provider;
1847 }
1848
1849 pub fn set_edit_prediction_provider<T>(
1850 &mut self,
1851 provider: Option<Entity<T>>,
1852 window: &mut Window,
1853 cx: &mut Context<Self>,
1854 ) where
1855 T: EditPredictionProvider,
1856 {
1857 self.edit_prediction_provider =
1858 provider.map(|provider| RegisteredInlineCompletionProvider {
1859 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1860 if this.focus_handle.is_focused(window) {
1861 this.update_visible_inline_completion(window, cx);
1862 }
1863 }),
1864 provider: Arc::new(provider),
1865 });
1866 self.update_edit_prediction_settings(cx);
1867 self.refresh_inline_completion(false, false, window, cx);
1868 }
1869
1870 pub fn placeholder_text(&self) -> Option<&str> {
1871 self.placeholder_text.as_deref()
1872 }
1873
1874 pub fn set_placeholder_text(
1875 &mut self,
1876 placeholder_text: impl Into<Arc<str>>,
1877 cx: &mut Context<Self>,
1878 ) {
1879 let placeholder_text = Some(placeholder_text.into());
1880 if self.placeholder_text != placeholder_text {
1881 self.placeholder_text = placeholder_text;
1882 cx.notify();
1883 }
1884 }
1885
1886 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1887 self.cursor_shape = cursor_shape;
1888
1889 // Disrupt blink for immediate user feedback that the cursor shape has changed
1890 self.blink_manager.update(cx, BlinkManager::show_cursor);
1891
1892 cx.notify();
1893 }
1894
1895 pub fn set_current_line_highlight(
1896 &mut self,
1897 current_line_highlight: Option<CurrentLineHighlight>,
1898 ) {
1899 self.current_line_highlight = current_line_highlight;
1900 }
1901
1902 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1903 self.collapse_matches = collapse_matches;
1904 }
1905
1906 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1907 let buffers = self.buffer.read(cx).all_buffers();
1908 let Some(project) = self.project.as_ref() else {
1909 return;
1910 };
1911 project.update(cx, |project, cx| {
1912 for buffer in buffers {
1913 self.registered_buffers
1914 .entry(buffer.read(cx).remote_id())
1915 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1916 }
1917 })
1918 }
1919
1920 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1921 if self.collapse_matches {
1922 return range.start..range.start;
1923 }
1924 range.clone()
1925 }
1926
1927 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1928 if self.display_map.read(cx).clip_at_line_ends != clip {
1929 self.display_map
1930 .update(cx, |map, _| map.clip_at_line_ends = clip);
1931 }
1932 }
1933
1934 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1935 self.input_enabled = input_enabled;
1936 }
1937
1938 pub fn set_inline_completions_hidden_for_vim_mode(
1939 &mut self,
1940 hidden: bool,
1941 window: &mut Window,
1942 cx: &mut Context<Self>,
1943 ) {
1944 if hidden != self.inline_completions_hidden_for_vim_mode {
1945 self.inline_completions_hidden_for_vim_mode = hidden;
1946 if hidden {
1947 self.update_visible_inline_completion(window, cx);
1948 } else {
1949 self.refresh_inline_completion(true, false, window, cx);
1950 }
1951 }
1952 }
1953
1954 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1955 self.menu_inline_completions_policy = value;
1956 }
1957
1958 pub fn set_autoindent(&mut self, autoindent: bool) {
1959 if autoindent {
1960 self.autoindent_mode = Some(AutoindentMode::EachLine);
1961 } else {
1962 self.autoindent_mode = None;
1963 }
1964 }
1965
1966 pub fn read_only(&self, cx: &App) -> bool {
1967 self.read_only || self.buffer.read(cx).read_only()
1968 }
1969
1970 pub fn set_read_only(&mut self, read_only: bool) {
1971 self.read_only = read_only;
1972 }
1973
1974 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1975 self.use_autoclose = autoclose;
1976 }
1977
1978 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1979 self.use_auto_surround = auto_surround;
1980 }
1981
1982 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1983 self.auto_replace_emoji_shortcode = auto_replace;
1984 }
1985
1986 pub fn toggle_edit_predictions(
1987 &mut self,
1988 _: &ToggleEditPrediction,
1989 window: &mut Window,
1990 cx: &mut Context<Self>,
1991 ) {
1992 if self.show_inline_completions_override.is_some() {
1993 self.set_show_edit_predictions(None, window, cx);
1994 } else {
1995 let show_edit_predictions = !self.edit_predictions_enabled();
1996 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1997 }
1998 }
1999
2000 pub fn set_show_edit_predictions(
2001 &mut self,
2002 show_edit_predictions: Option<bool>,
2003 window: &mut Window,
2004 cx: &mut Context<Self>,
2005 ) {
2006 self.show_inline_completions_override = show_edit_predictions;
2007 self.update_edit_prediction_settings(cx);
2008
2009 if let Some(false) = show_edit_predictions {
2010 self.discard_inline_completion(false, cx);
2011 } else {
2012 self.refresh_inline_completion(false, true, window, cx);
2013 }
2014 }
2015
2016 fn inline_completions_disabled_in_scope(
2017 &self,
2018 buffer: &Entity<Buffer>,
2019 buffer_position: language::Anchor,
2020 cx: &App,
2021 ) -> bool {
2022 let snapshot = buffer.read(cx).snapshot();
2023 let settings = snapshot.settings_at(buffer_position, cx);
2024
2025 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2026 return false;
2027 };
2028
2029 scope.override_name().map_or(false, |scope_name| {
2030 settings
2031 .edit_predictions_disabled_in
2032 .iter()
2033 .any(|s| s == scope_name)
2034 })
2035 }
2036
2037 pub fn set_use_modal_editing(&mut self, to: bool) {
2038 self.use_modal_editing = to;
2039 }
2040
2041 pub fn use_modal_editing(&self) -> bool {
2042 self.use_modal_editing
2043 }
2044
2045 fn selections_did_change(
2046 &mut self,
2047 local: bool,
2048 old_cursor_position: &Anchor,
2049 show_completions: bool,
2050 window: &mut Window,
2051 cx: &mut Context<Self>,
2052 ) {
2053 window.invalidate_character_coordinates();
2054
2055 // Copy selections to primary selection buffer
2056 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2057 if local {
2058 let selections = self.selections.all::<usize>(cx);
2059 let buffer_handle = self.buffer.read(cx).read(cx);
2060
2061 let mut text = String::new();
2062 for (index, selection) in selections.iter().enumerate() {
2063 let text_for_selection = buffer_handle
2064 .text_for_range(selection.start..selection.end)
2065 .collect::<String>();
2066
2067 text.push_str(&text_for_selection);
2068 if index != selections.len() - 1 {
2069 text.push('\n');
2070 }
2071 }
2072
2073 if !text.is_empty() {
2074 cx.write_to_primary(ClipboardItem::new_string(text));
2075 }
2076 }
2077
2078 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2079 self.buffer.update(cx, |buffer, cx| {
2080 buffer.set_active_selections(
2081 &self.selections.disjoint_anchors(),
2082 self.selections.line_mode,
2083 self.cursor_shape,
2084 cx,
2085 )
2086 });
2087 }
2088 let display_map = self
2089 .display_map
2090 .update(cx, |display_map, cx| display_map.snapshot(cx));
2091 let buffer = &display_map.buffer_snapshot;
2092 self.add_selections_state = None;
2093 self.select_next_state = None;
2094 self.select_prev_state = None;
2095 self.select_larger_syntax_node_stack.clear();
2096 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2097 self.snippet_stack
2098 .invalidate(&self.selections.disjoint_anchors(), buffer);
2099 self.take_rename(false, window, cx);
2100
2101 let new_cursor_position = self.selections.newest_anchor().head();
2102
2103 self.push_to_nav_history(
2104 *old_cursor_position,
2105 Some(new_cursor_position.to_point(buffer)),
2106 cx,
2107 );
2108
2109 if local {
2110 let new_cursor_position = self.selections.newest_anchor().head();
2111 let mut context_menu = self.context_menu.borrow_mut();
2112 let completion_menu = match context_menu.as_ref() {
2113 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2114 _ => {
2115 *context_menu = None;
2116 None
2117 }
2118 };
2119 if let Some(buffer_id) = new_cursor_position.buffer_id {
2120 if !self.registered_buffers.contains_key(&buffer_id) {
2121 if let Some(project) = self.project.as_ref() {
2122 project.update(cx, |project, cx| {
2123 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2124 return;
2125 };
2126 self.registered_buffers.insert(
2127 buffer_id,
2128 project.register_buffer_with_language_servers(&buffer, cx),
2129 );
2130 })
2131 }
2132 }
2133 }
2134
2135 if let Some(completion_menu) = completion_menu {
2136 let cursor_position = new_cursor_position.to_offset(buffer);
2137 let (word_range, kind) =
2138 buffer.surrounding_word(completion_menu.initial_position, true);
2139 if kind == Some(CharKind::Word)
2140 && word_range.to_inclusive().contains(&cursor_position)
2141 {
2142 let mut completion_menu = completion_menu.clone();
2143 drop(context_menu);
2144
2145 let query = Self::completion_query(buffer, cursor_position);
2146 cx.spawn(move |this, mut cx| async move {
2147 completion_menu
2148 .filter(query.as_deref(), cx.background_executor().clone())
2149 .await;
2150
2151 this.update(&mut cx, |this, cx| {
2152 let mut context_menu = this.context_menu.borrow_mut();
2153 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2154 else {
2155 return;
2156 };
2157
2158 if menu.id > completion_menu.id {
2159 return;
2160 }
2161
2162 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2163 drop(context_menu);
2164 cx.notify();
2165 })
2166 })
2167 .detach();
2168
2169 if show_completions {
2170 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2171 }
2172 } else {
2173 drop(context_menu);
2174 self.hide_context_menu(window, cx);
2175 }
2176 } else {
2177 drop(context_menu);
2178 }
2179
2180 hide_hover(self, cx);
2181
2182 if old_cursor_position.to_display_point(&display_map).row()
2183 != new_cursor_position.to_display_point(&display_map).row()
2184 {
2185 self.available_code_actions.take();
2186 }
2187 self.refresh_code_actions(window, cx);
2188 self.refresh_document_highlights(cx);
2189 self.refresh_selected_text_highlights(window, cx);
2190 refresh_matching_bracket_highlights(self, window, cx);
2191 self.update_visible_inline_completion(window, cx);
2192 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2193 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2194 if self.git_blame_inline_enabled {
2195 self.start_inline_blame_timer(window, cx);
2196 }
2197 }
2198
2199 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2200 cx.emit(EditorEvent::SelectionsChanged { local });
2201
2202 let selections = &self.selections.disjoint;
2203 if selections.len() == 1 {
2204 cx.emit(SearchEvent::ActiveMatchChanged)
2205 }
2206 if local
2207 && self.is_singleton(cx)
2208 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2209 {
2210 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2211 let background_executor = cx.background_executor().clone();
2212 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2213 let snapshot = self.buffer().read(cx).snapshot(cx);
2214 let selections = selections.clone();
2215 self.serialize_selections = cx.background_spawn(async move {
2216 background_executor.timer(Duration::from_millis(100)).await;
2217 let selections = selections
2218 .iter()
2219 .map(|selection| {
2220 (
2221 selection.start.to_offset(&snapshot),
2222 selection.end.to_offset(&snapshot),
2223 )
2224 })
2225 .collect();
2226 DB.save_editor_selections(editor_id, workspace_id, selections)
2227 .await
2228 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2229 .log_err();
2230 });
2231 }
2232 }
2233
2234 cx.notify();
2235 }
2236
2237 pub fn sync_selections(
2238 &mut self,
2239 other: Entity<Editor>,
2240 cx: &mut Context<Self>,
2241 ) -> gpui::Subscription {
2242 let other_selections = other.read(cx).selections.disjoint.to_vec();
2243 self.selections.change_with(cx, |selections| {
2244 selections.select_anchors(other_selections);
2245 });
2246
2247 let other_subscription =
2248 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2249 EditorEvent::SelectionsChanged { local: true } => {
2250 let other_selections = other.read(cx).selections.disjoint.to_vec();
2251 if other_selections.is_empty() {
2252 return;
2253 }
2254 this.selections.change_with(cx, |selections| {
2255 selections.select_anchors(other_selections);
2256 });
2257 }
2258 _ => {}
2259 });
2260
2261 let this_subscription =
2262 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2263 EditorEvent::SelectionsChanged { local: true } => {
2264 let these_selections = this.selections.disjoint.to_vec();
2265 if these_selections.is_empty() {
2266 return;
2267 }
2268 other.update(cx, |other_editor, cx| {
2269 other_editor.selections.change_with(cx, |selections| {
2270 selections.select_anchors(these_selections);
2271 })
2272 });
2273 }
2274 _ => {}
2275 });
2276
2277 Subscription::join(other_subscription, this_subscription)
2278 }
2279
2280 pub fn change_selections<R>(
2281 &mut self,
2282 autoscroll: Option<Autoscroll>,
2283 window: &mut Window,
2284 cx: &mut Context<Self>,
2285 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2286 ) -> R {
2287 self.change_selections_inner(autoscroll, true, window, cx, change)
2288 }
2289
2290 fn change_selections_inner<R>(
2291 &mut self,
2292 autoscroll: Option<Autoscroll>,
2293 request_completions: bool,
2294 window: &mut Window,
2295 cx: &mut Context<Self>,
2296 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2297 ) -> R {
2298 let old_cursor_position = self.selections.newest_anchor().head();
2299 self.push_to_selection_history();
2300
2301 let (changed, result) = self.selections.change_with(cx, change);
2302
2303 if changed {
2304 if let Some(autoscroll) = autoscroll {
2305 self.request_autoscroll(autoscroll, cx);
2306 }
2307 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2308
2309 if self.should_open_signature_help_automatically(
2310 &old_cursor_position,
2311 self.signature_help_state.backspace_pressed(),
2312 cx,
2313 ) {
2314 self.show_signature_help(&ShowSignatureHelp, window, cx);
2315 }
2316 self.signature_help_state.set_backspace_pressed(false);
2317 }
2318
2319 result
2320 }
2321
2322 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2323 where
2324 I: IntoIterator<Item = (Range<S>, T)>,
2325 S: ToOffset,
2326 T: Into<Arc<str>>,
2327 {
2328 if self.read_only(cx) {
2329 return;
2330 }
2331
2332 self.buffer
2333 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2334 }
2335
2336 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2337 where
2338 I: IntoIterator<Item = (Range<S>, T)>,
2339 S: ToOffset,
2340 T: Into<Arc<str>>,
2341 {
2342 if self.read_only(cx) {
2343 return;
2344 }
2345
2346 self.buffer.update(cx, |buffer, cx| {
2347 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2348 });
2349 }
2350
2351 pub fn edit_with_block_indent<I, S, T>(
2352 &mut self,
2353 edits: I,
2354 original_indent_columns: Vec<Option<u32>>,
2355 cx: &mut Context<Self>,
2356 ) where
2357 I: IntoIterator<Item = (Range<S>, T)>,
2358 S: ToOffset,
2359 T: Into<Arc<str>>,
2360 {
2361 if self.read_only(cx) {
2362 return;
2363 }
2364
2365 self.buffer.update(cx, |buffer, cx| {
2366 buffer.edit(
2367 edits,
2368 Some(AutoindentMode::Block {
2369 original_indent_columns,
2370 }),
2371 cx,
2372 )
2373 });
2374 }
2375
2376 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2377 self.hide_context_menu(window, cx);
2378
2379 match phase {
2380 SelectPhase::Begin {
2381 position,
2382 add,
2383 click_count,
2384 } => self.begin_selection(position, add, click_count, window, cx),
2385 SelectPhase::BeginColumnar {
2386 position,
2387 goal_column,
2388 reset,
2389 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2390 SelectPhase::Extend {
2391 position,
2392 click_count,
2393 } => self.extend_selection(position, click_count, window, cx),
2394 SelectPhase::Update {
2395 position,
2396 goal_column,
2397 scroll_delta,
2398 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2399 SelectPhase::End => self.end_selection(window, cx),
2400 }
2401 }
2402
2403 fn extend_selection(
2404 &mut self,
2405 position: DisplayPoint,
2406 click_count: usize,
2407 window: &mut Window,
2408 cx: &mut Context<Self>,
2409 ) {
2410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2411 let tail = self.selections.newest::<usize>(cx).tail();
2412 self.begin_selection(position, false, click_count, window, cx);
2413
2414 let position = position.to_offset(&display_map, Bias::Left);
2415 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2416
2417 let mut pending_selection = self
2418 .selections
2419 .pending_anchor()
2420 .expect("extend_selection not called with pending selection");
2421 if position >= tail {
2422 pending_selection.start = tail_anchor;
2423 } else {
2424 pending_selection.end = tail_anchor;
2425 pending_selection.reversed = true;
2426 }
2427
2428 let mut pending_mode = self.selections.pending_mode().unwrap();
2429 match &mut pending_mode {
2430 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2431 _ => {}
2432 }
2433
2434 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2435 s.set_pending(pending_selection, pending_mode)
2436 });
2437 }
2438
2439 fn begin_selection(
2440 &mut self,
2441 position: DisplayPoint,
2442 add: bool,
2443 click_count: usize,
2444 window: &mut Window,
2445 cx: &mut Context<Self>,
2446 ) {
2447 if !self.focus_handle.is_focused(window) {
2448 self.last_focused_descendant = None;
2449 window.focus(&self.focus_handle);
2450 }
2451
2452 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2453 let buffer = &display_map.buffer_snapshot;
2454 let newest_selection = self.selections.newest_anchor().clone();
2455 let position = display_map.clip_point(position, Bias::Left);
2456
2457 let start;
2458 let end;
2459 let mode;
2460 let mut auto_scroll;
2461 match click_count {
2462 1 => {
2463 start = buffer.anchor_before(position.to_point(&display_map));
2464 end = start;
2465 mode = SelectMode::Character;
2466 auto_scroll = true;
2467 }
2468 2 => {
2469 let range = movement::surrounding_word(&display_map, position);
2470 start = buffer.anchor_before(range.start.to_point(&display_map));
2471 end = buffer.anchor_before(range.end.to_point(&display_map));
2472 mode = SelectMode::Word(start..end);
2473 auto_scroll = true;
2474 }
2475 3 => {
2476 let position = display_map
2477 .clip_point(position, Bias::Left)
2478 .to_point(&display_map);
2479 let line_start = display_map.prev_line_boundary(position).0;
2480 let next_line_start = buffer.clip_point(
2481 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2482 Bias::Left,
2483 );
2484 start = buffer.anchor_before(line_start);
2485 end = buffer.anchor_before(next_line_start);
2486 mode = SelectMode::Line(start..end);
2487 auto_scroll = true;
2488 }
2489 _ => {
2490 start = buffer.anchor_before(0);
2491 end = buffer.anchor_before(buffer.len());
2492 mode = SelectMode::All;
2493 auto_scroll = false;
2494 }
2495 }
2496 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2497
2498 let point_to_delete: Option<usize> = {
2499 let selected_points: Vec<Selection<Point>> =
2500 self.selections.disjoint_in_range(start..end, cx);
2501
2502 if !add || click_count > 1 {
2503 None
2504 } else if !selected_points.is_empty() {
2505 Some(selected_points[0].id)
2506 } else {
2507 let clicked_point_already_selected =
2508 self.selections.disjoint.iter().find(|selection| {
2509 selection.start.to_point(buffer) == start.to_point(buffer)
2510 || selection.end.to_point(buffer) == end.to_point(buffer)
2511 });
2512
2513 clicked_point_already_selected.map(|selection| selection.id)
2514 }
2515 };
2516
2517 let selections_count = self.selections.count();
2518
2519 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2520 if let Some(point_to_delete) = point_to_delete {
2521 s.delete(point_to_delete);
2522
2523 if selections_count == 1 {
2524 s.set_pending_anchor_range(start..end, mode);
2525 }
2526 } else {
2527 if !add {
2528 s.clear_disjoint();
2529 } else if click_count > 1 {
2530 s.delete(newest_selection.id)
2531 }
2532
2533 s.set_pending_anchor_range(start..end, mode);
2534 }
2535 });
2536 }
2537
2538 fn begin_columnar_selection(
2539 &mut self,
2540 position: DisplayPoint,
2541 goal_column: u32,
2542 reset: bool,
2543 window: &mut Window,
2544 cx: &mut Context<Self>,
2545 ) {
2546 if !self.focus_handle.is_focused(window) {
2547 self.last_focused_descendant = None;
2548 window.focus(&self.focus_handle);
2549 }
2550
2551 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2552
2553 if reset {
2554 let pointer_position = display_map
2555 .buffer_snapshot
2556 .anchor_before(position.to_point(&display_map));
2557
2558 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2559 s.clear_disjoint();
2560 s.set_pending_anchor_range(
2561 pointer_position..pointer_position,
2562 SelectMode::Character,
2563 );
2564 });
2565 }
2566
2567 let tail = self.selections.newest::<Point>(cx).tail();
2568 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2569
2570 if !reset {
2571 self.select_columns(
2572 tail.to_display_point(&display_map),
2573 position,
2574 goal_column,
2575 &display_map,
2576 window,
2577 cx,
2578 );
2579 }
2580 }
2581
2582 fn update_selection(
2583 &mut self,
2584 position: DisplayPoint,
2585 goal_column: u32,
2586 scroll_delta: gpui::Point<f32>,
2587 window: &mut Window,
2588 cx: &mut Context<Self>,
2589 ) {
2590 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2591
2592 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2593 let tail = tail.to_display_point(&display_map);
2594 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2595 } else if let Some(mut pending) = self.selections.pending_anchor() {
2596 let buffer = self.buffer.read(cx).snapshot(cx);
2597 let head;
2598 let tail;
2599 let mode = self.selections.pending_mode().unwrap();
2600 match &mode {
2601 SelectMode::Character => {
2602 head = position.to_point(&display_map);
2603 tail = pending.tail().to_point(&buffer);
2604 }
2605 SelectMode::Word(original_range) => {
2606 let original_display_range = original_range.start.to_display_point(&display_map)
2607 ..original_range.end.to_display_point(&display_map);
2608 let original_buffer_range = original_display_range.start.to_point(&display_map)
2609 ..original_display_range.end.to_point(&display_map);
2610 if movement::is_inside_word(&display_map, position)
2611 || original_display_range.contains(&position)
2612 {
2613 let word_range = movement::surrounding_word(&display_map, position);
2614 if word_range.start < original_display_range.start {
2615 head = word_range.start.to_point(&display_map);
2616 } else {
2617 head = word_range.end.to_point(&display_map);
2618 }
2619 } else {
2620 head = position.to_point(&display_map);
2621 }
2622
2623 if head <= original_buffer_range.start {
2624 tail = original_buffer_range.end;
2625 } else {
2626 tail = original_buffer_range.start;
2627 }
2628 }
2629 SelectMode::Line(original_range) => {
2630 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2631
2632 let position = display_map
2633 .clip_point(position, Bias::Left)
2634 .to_point(&display_map);
2635 let line_start = display_map.prev_line_boundary(position).0;
2636 let next_line_start = buffer.clip_point(
2637 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2638 Bias::Left,
2639 );
2640
2641 if line_start < original_range.start {
2642 head = line_start
2643 } else {
2644 head = next_line_start
2645 }
2646
2647 if head <= original_range.start {
2648 tail = original_range.end;
2649 } else {
2650 tail = original_range.start;
2651 }
2652 }
2653 SelectMode::All => {
2654 return;
2655 }
2656 };
2657
2658 if head < tail {
2659 pending.start = buffer.anchor_before(head);
2660 pending.end = buffer.anchor_before(tail);
2661 pending.reversed = true;
2662 } else {
2663 pending.start = buffer.anchor_before(tail);
2664 pending.end = buffer.anchor_before(head);
2665 pending.reversed = false;
2666 }
2667
2668 self.change_selections(None, window, cx, |s| {
2669 s.set_pending(pending, mode);
2670 });
2671 } else {
2672 log::error!("update_selection dispatched with no pending selection");
2673 return;
2674 }
2675
2676 self.apply_scroll_delta(scroll_delta, window, cx);
2677 cx.notify();
2678 }
2679
2680 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2681 self.columnar_selection_tail.take();
2682 if self.selections.pending_anchor().is_some() {
2683 let selections = self.selections.all::<usize>(cx);
2684 self.change_selections(None, window, cx, |s| {
2685 s.select(selections);
2686 s.clear_pending();
2687 });
2688 }
2689 }
2690
2691 fn select_columns(
2692 &mut self,
2693 tail: DisplayPoint,
2694 head: DisplayPoint,
2695 goal_column: u32,
2696 display_map: &DisplaySnapshot,
2697 window: &mut Window,
2698 cx: &mut Context<Self>,
2699 ) {
2700 let start_row = cmp::min(tail.row(), head.row());
2701 let end_row = cmp::max(tail.row(), head.row());
2702 let start_column = cmp::min(tail.column(), goal_column);
2703 let end_column = cmp::max(tail.column(), goal_column);
2704 let reversed = start_column < tail.column();
2705
2706 let selection_ranges = (start_row.0..=end_row.0)
2707 .map(DisplayRow)
2708 .filter_map(|row| {
2709 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2710 let start = display_map
2711 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2712 .to_point(display_map);
2713 let end = display_map
2714 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2715 .to_point(display_map);
2716 if reversed {
2717 Some(end..start)
2718 } else {
2719 Some(start..end)
2720 }
2721 } else {
2722 None
2723 }
2724 })
2725 .collect::<Vec<_>>();
2726
2727 self.change_selections(None, window, cx, |s| {
2728 s.select_ranges(selection_ranges);
2729 });
2730 cx.notify();
2731 }
2732
2733 pub fn has_pending_nonempty_selection(&self) -> bool {
2734 let pending_nonempty_selection = match self.selections.pending_anchor() {
2735 Some(Selection { start, end, .. }) => start != end,
2736 None => false,
2737 };
2738
2739 pending_nonempty_selection
2740 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2741 }
2742
2743 pub fn has_pending_selection(&self) -> bool {
2744 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2745 }
2746
2747 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2748 self.selection_mark_mode = false;
2749
2750 if self.clear_expanded_diff_hunks(cx) {
2751 cx.notify();
2752 return;
2753 }
2754 if self.dismiss_menus_and_popups(true, window, cx) {
2755 return;
2756 }
2757
2758 if self.mode == EditorMode::Full
2759 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2760 {
2761 return;
2762 }
2763
2764 cx.propagate();
2765 }
2766
2767 pub fn dismiss_menus_and_popups(
2768 &mut self,
2769 is_user_requested: bool,
2770 window: &mut Window,
2771 cx: &mut Context<Self>,
2772 ) -> bool {
2773 if self.take_rename(false, window, cx).is_some() {
2774 return true;
2775 }
2776
2777 if hide_hover(self, cx) {
2778 return true;
2779 }
2780
2781 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2782 return true;
2783 }
2784
2785 if self.hide_context_menu(window, cx).is_some() {
2786 return true;
2787 }
2788
2789 if self.mouse_context_menu.take().is_some() {
2790 return true;
2791 }
2792
2793 if is_user_requested && self.discard_inline_completion(true, cx) {
2794 return true;
2795 }
2796
2797 if self.snippet_stack.pop().is_some() {
2798 return true;
2799 }
2800
2801 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2802 self.dismiss_diagnostics(cx);
2803 return true;
2804 }
2805
2806 false
2807 }
2808
2809 fn linked_editing_ranges_for(
2810 &self,
2811 selection: Range<text::Anchor>,
2812 cx: &App,
2813 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2814 if self.linked_edit_ranges.is_empty() {
2815 return None;
2816 }
2817 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2818 selection.end.buffer_id.and_then(|end_buffer_id| {
2819 if selection.start.buffer_id != Some(end_buffer_id) {
2820 return None;
2821 }
2822 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2823 let snapshot = buffer.read(cx).snapshot();
2824 self.linked_edit_ranges
2825 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2826 .map(|ranges| (ranges, snapshot, buffer))
2827 })?;
2828 use text::ToOffset as TO;
2829 // find offset from the start of current range to current cursor position
2830 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2831
2832 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2833 let start_difference = start_offset - start_byte_offset;
2834 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2835 let end_difference = end_offset - start_byte_offset;
2836 // Current range has associated linked ranges.
2837 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2838 for range in linked_ranges.iter() {
2839 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2840 let end_offset = start_offset + end_difference;
2841 let start_offset = start_offset + start_difference;
2842 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2843 continue;
2844 }
2845 if self.selections.disjoint_anchor_ranges().any(|s| {
2846 if s.start.buffer_id != selection.start.buffer_id
2847 || s.end.buffer_id != selection.end.buffer_id
2848 {
2849 return false;
2850 }
2851 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2852 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2853 }) {
2854 continue;
2855 }
2856 let start = buffer_snapshot.anchor_after(start_offset);
2857 let end = buffer_snapshot.anchor_after(end_offset);
2858 linked_edits
2859 .entry(buffer.clone())
2860 .or_default()
2861 .push(start..end);
2862 }
2863 Some(linked_edits)
2864 }
2865
2866 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2867 let text: Arc<str> = text.into();
2868
2869 if self.read_only(cx) {
2870 return;
2871 }
2872
2873 let selections = self.selections.all_adjusted(cx);
2874 let mut bracket_inserted = false;
2875 let mut edits = Vec::new();
2876 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2877 let mut new_selections = Vec::with_capacity(selections.len());
2878 let mut new_autoclose_regions = Vec::new();
2879 let snapshot = self.buffer.read(cx).read(cx);
2880
2881 for (selection, autoclose_region) in
2882 self.selections_with_autoclose_regions(selections, &snapshot)
2883 {
2884 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2885 // Determine if the inserted text matches the opening or closing
2886 // bracket of any of this language's bracket pairs.
2887 let mut bracket_pair = None;
2888 let mut is_bracket_pair_start = false;
2889 let mut is_bracket_pair_end = false;
2890 if !text.is_empty() {
2891 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2892 // and they are removing the character that triggered IME popup.
2893 for (pair, enabled) in scope.brackets() {
2894 if !pair.close && !pair.surround {
2895 continue;
2896 }
2897
2898 if enabled && pair.start.ends_with(text.as_ref()) {
2899 let prefix_len = pair.start.len() - text.len();
2900 let preceding_text_matches_prefix = prefix_len == 0
2901 || (selection.start.column >= (prefix_len as u32)
2902 && snapshot.contains_str_at(
2903 Point::new(
2904 selection.start.row,
2905 selection.start.column - (prefix_len as u32),
2906 ),
2907 &pair.start[..prefix_len],
2908 ));
2909 if preceding_text_matches_prefix {
2910 bracket_pair = Some(pair.clone());
2911 is_bracket_pair_start = true;
2912 break;
2913 }
2914 }
2915 if pair.end.as_str() == text.as_ref() {
2916 bracket_pair = Some(pair.clone());
2917 is_bracket_pair_end = true;
2918 break;
2919 }
2920 }
2921 }
2922
2923 if let Some(bracket_pair) = bracket_pair {
2924 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
2925 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2926 let auto_surround =
2927 self.use_auto_surround && snapshot_settings.use_auto_surround;
2928 if selection.is_empty() {
2929 if is_bracket_pair_start {
2930 // If the inserted text is a suffix of an opening bracket and the
2931 // selection is preceded by the rest of the opening bracket, then
2932 // insert the closing bracket.
2933 let following_text_allows_autoclose = snapshot
2934 .chars_at(selection.start)
2935 .next()
2936 .map_or(true, |c| scope.should_autoclose_before(c));
2937
2938 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2939 && bracket_pair.start.len() == 1
2940 {
2941 let target = bracket_pair.start.chars().next().unwrap();
2942 let current_line_count = snapshot
2943 .reversed_chars_at(selection.start)
2944 .take_while(|&c| c != '\n')
2945 .filter(|&c| c == target)
2946 .count();
2947 current_line_count % 2 == 1
2948 } else {
2949 false
2950 };
2951
2952 if autoclose
2953 && bracket_pair.close
2954 && following_text_allows_autoclose
2955 && !is_closing_quote
2956 {
2957 let anchor = snapshot.anchor_before(selection.end);
2958 new_selections.push((selection.map(|_| anchor), text.len()));
2959 new_autoclose_regions.push((
2960 anchor,
2961 text.len(),
2962 selection.id,
2963 bracket_pair.clone(),
2964 ));
2965 edits.push((
2966 selection.range(),
2967 format!("{}{}", text, bracket_pair.end).into(),
2968 ));
2969 bracket_inserted = true;
2970 continue;
2971 }
2972 }
2973
2974 if let Some(region) = autoclose_region {
2975 // If the selection is followed by an auto-inserted closing bracket,
2976 // then don't insert that closing bracket again; just move the selection
2977 // past the closing bracket.
2978 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2979 && text.as_ref() == region.pair.end.as_str();
2980 if should_skip {
2981 let anchor = snapshot.anchor_after(selection.end);
2982 new_selections
2983 .push((selection.map(|_| anchor), region.pair.end.len()));
2984 continue;
2985 }
2986 }
2987
2988 let always_treat_brackets_as_autoclosed = snapshot
2989 .language_settings_at(selection.start, cx)
2990 .always_treat_brackets_as_autoclosed;
2991 if always_treat_brackets_as_autoclosed
2992 && is_bracket_pair_end
2993 && snapshot.contains_str_at(selection.end, text.as_ref())
2994 {
2995 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2996 // and the inserted text is a closing bracket and the selection is followed
2997 // by the closing bracket then move the selection past the closing bracket.
2998 let anchor = snapshot.anchor_after(selection.end);
2999 new_selections.push((selection.map(|_| anchor), text.len()));
3000 continue;
3001 }
3002 }
3003 // If an opening bracket is 1 character long and is typed while
3004 // text is selected, then surround that text with the bracket pair.
3005 else if auto_surround
3006 && bracket_pair.surround
3007 && is_bracket_pair_start
3008 && bracket_pair.start.chars().count() == 1
3009 {
3010 edits.push((selection.start..selection.start, text.clone()));
3011 edits.push((
3012 selection.end..selection.end,
3013 bracket_pair.end.as_str().into(),
3014 ));
3015 bracket_inserted = true;
3016 new_selections.push((
3017 Selection {
3018 id: selection.id,
3019 start: snapshot.anchor_after(selection.start),
3020 end: snapshot.anchor_before(selection.end),
3021 reversed: selection.reversed,
3022 goal: selection.goal,
3023 },
3024 0,
3025 ));
3026 continue;
3027 }
3028 }
3029 }
3030
3031 if self.auto_replace_emoji_shortcode
3032 && selection.is_empty()
3033 && text.as_ref().ends_with(':')
3034 {
3035 if let Some(possible_emoji_short_code) =
3036 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3037 {
3038 if !possible_emoji_short_code.is_empty() {
3039 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3040 let emoji_shortcode_start = Point::new(
3041 selection.start.row,
3042 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3043 );
3044
3045 // Remove shortcode from buffer
3046 edits.push((
3047 emoji_shortcode_start..selection.start,
3048 "".to_string().into(),
3049 ));
3050 new_selections.push((
3051 Selection {
3052 id: selection.id,
3053 start: snapshot.anchor_after(emoji_shortcode_start),
3054 end: snapshot.anchor_before(selection.start),
3055 reversed: selection.reversed,
3056 goal: selection.goal,
3057 },
3058 0,
3059 ));
3060
3061 // Insert emoji
3062 let selection_start_anchor = snapshot.anchor_after(selection.start);
3063 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3064 edits.push((selection.start..selection.end, emoji.to_string().into()));
3065
3066 continue;
3067 }
3068 }
3069 }
3070 }
3071
3072 // If not handling any auto-close operation, then just replace the selected
3073 // text with the given input and move the selection to the end of the
3074 // newly inserted text.
3075 let anchor = snapshot.anchor_after(selection.end);
3076 if !self.linked_edit_ranges.is_empty() {
3077 let start_anchor = snapshot.anchor_before(selection.start);
3078
3079 let is_word_char = text.chars().next().map_or(true, |char| {
3080 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3081 classifier.is_word(char)
3082 });
3083
3084 if is_word_char {
3085 if let Some(ranges) = self
3086 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3087 {
3088 for (buffer, edits) in ranges {
3089 linked_edits
3090 .entry(buffer.clone())
3091 .or_default()
3092 .extend(edits.into_iter().map(|range| (range, text.clone())));
3093 }
3094 }
3095 }
3096 }
3097
3098 new_selections.push((selection.map(|_| anchor), 0));
3099 edits.push((selection.start..selection.end, text.clone()));
3100 }
3101
3102 drop(snapshot);
3103
3104 self.transact(window, cx, |this, window, cx| {
3105 let initial_buffer_versions =
3106 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3107
3108 this.buffer.update(cx, |buffer, cx| {
3109 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3110 });
3111 for (buffer, edits) in linked_edits {
3112 buffer.update(cx, |buffer, cx| {
3113 let snapshot = buffer.snapshot();
3114 let edits = edits
3115 .into_iter()
3116 .map(|(range, text)| {
3117 use text::ToPoint as TP;
3118 let end_point = TP::to_point(&range.end, &snapshot);
3119 let start_point = TP::to_point(&range.start, &snapshot);
3120 (start_point..end_point, text)
3121 })
3122 .sorted_by_key(|(range, _)| range.start)
3123 .collect::<Vec<_>>();
3124 buffer.edit(edits, None, cx);
3125 })
3126 }
3127 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3128 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3129 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3130 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3131 .zip(new_selection_deltas)
3132 .map(|(selection, delta)| Selection {
3133 id: selection.id,
3134 start: selection.start + delta,
3135 end: selection.end + delta,
3136 reversed: selection.reversed,
3137 goal: SelectionGoal::None,
3138 })
3139 .collect::<Vec<_>>();
3140
3141 let mut i = 0;
3142 for (position, delta, selection_id, pair) in new_autoclose_regions {
3143 let position = position.to_offset(&map.buffer_snapshot) + delta;
3144 let start = map.buffer_snapshot.anchor_before(position);
3145 let end = map.buffer_snapshot.anchor_after(position);
3146 while let Some(existing_state) = this.autoclose_regions.get(i) {
3147 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3148 Ordering::Less => i += 1,
3149 Ordering::Greater => break,
3150 Ordering::Equal => {
3151 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3152 Ordering::Less => i += 1,
3153 Ordering::Equal => break,
3154 Ordering::Greater => break,
3155 }
3156 }
3157 }
3158 }
3159 this.autoclose_regions.insert(
3160 i,
3161 AutocloseRegion {
3162 selection_id,
3163 range: start..end,
3164 pair,
3165 },
3166 );
3167 }
3168
3169 let had_active_inline_completion = this.has_active_inline_completion();
3170 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3171 s.select(new_selections)
3172 });
3173
3174 if !bracket_inserted {
3175 if let Some(on_type_format_task) =
3176 this.trigger_on_type_formatting(text.to_string(), window, cx)
3177 {
3178 on_type_format_task.detach_and_log_err(cx);
3179 }
3180 }
3181
3182 let editor_settings = EditorSettings::get_global(cx);
3183 if bracket_inserted
3184 && (editor_settings.auto_signature_help
3185 || editor_settings.show_signature_help_after_edits)
3186 {
3187 this.show_signature_help(&ShowSignatureHelp, window, cx);
3188 }
3189
3190 let trigger_in_words =
3191 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3192 if this.hard_wrap.is_some() {
3193 let latest: Range<Point> = this.selections.newest(cx).range();
3194 if latest.is_empty()
3195 && this
3196 .buffer()
3197 .read(cx)
3198 .snapshot(cx)
3199 .line_len(MultiBufferRow(latest.start.row))
3200 == latest.start.column
3201 {
3202 this.rewrap_impl(true, cx)
3203 }
3204 }
3205 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3206 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3207 this.refresh_inline_completion(true, false, window, cx);
3208 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3209 });
3210 }
3211
3212 fn find_possible_emoji_shortcode_at_position(
3213 snapshot: &MultiBufferSnapshot,
3214 position: Point,
3215 ) -> Option<String> {
3216 let mut chars = Vec::new();
3217 let mut found_colon = false;
3218 for char in snapshot.reversed_chars_at(position).take(100) {
3219 // Found a possible emoji shortcode in the middle of the buffer
3220 if found_colon {
3221 if char.is_whitespace() {
3222 chars.reverse();
3223 return Some(chars.iter().collect());
3224 }
3225 // If the previous character is not a whitespace, we are in the middle of a word
3226 // and we only want to complete the shortcode if the word is made up of other emojis
3227 let mut containing_word = String::new();
3228 for ch in snapshot
3229 .reversed_chars_at(position)
3230 .skip(chars.len() + 1)
3231 .take(100)
3232 {
3233 if ch.is_whitespace() {
3234 break;
3235 }
3236 containing_word.push(ch);
3237 }
3238 let containing_word = containing_word.chars().rev().collect::<String>();
3239 if util::word_consists_of_emojis(containing_word.as_str()) {
3240 chars.reverse();
3241 return Some(chars.iter().collect());
3242 }
3243 }
3244
3245 if char.is_whitespace() || !char.is_ascii() {
3246 return None;
3247 }
3248 if char == ':' {
3249 found_colon = true;
3250 } else {
3251 chars.push(char);
3252 }
3253 }
3254 // Found a possible emoji shortcode at the beginning of the buffer
3255 chars.reverse();
3256 Some(chars.iter().collect())
3257 }
3258
3259 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3260 self.transact(window, cx, |this, window, cx| {
3261 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3262 let selections = this.selections.all::<usize>(cx);
3263 let multi_buffer = this.buffer.read(cx);
3264 let buffer = multi_buffer.snapshot(cx);
3265 selections
3266 .iter()
3267 .map(|selection| {
3268 let start_point = selection.start.to_point(&buffer);
3269 let mut indent =
3270 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3271 indent.len = cmp::min(indent.len, start_point.column);
3272 let start = selection.start;
3273 let end = selection.end;
3274 let selection_is_empty = start == end;
3275 let language_scope = buffer.language_scope_at(start);
3276 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3277 &language_scope
3278 {
3279 let insert_extra_newline =
3280 insert_extra_newline_brackets(&buffer, start..end, language)
3281 || insert_extra_newline_tree_sitter(&buffer, start..end);
3282
3283 // Comment extension on newline is allowed only for cursor selections
3284 let comment_delimiter = maybe!({
3285 if !selection_is_empty {
3286 return None;
3287 }
3288
3289 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3290 return None;
3291 }
3292
3293 let delimiters = language.line_comment_prefixes();
3294 let max_len_of_delimiter =
3295 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3296 let (snapshot, range) =
3297 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3298
3299 let mut index_of_first_non_whitespace = 0;
3300 let comment_candidate = snapshot
3301 .chars_for_range(range)
3302 .skip_while(|c| {
3303 let should_skip = c.is_whitespace();
3304 if should_skip {
3305 index_of_first_non_whitespace += 1;
3306 }
3307 should_skip
3308 })
3309 .take(max_len_of_delimiter)
3310 .collect::<String>();
3311 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3312 comment_candidate.starts_with(comment_prefix.as_ref())
3313 })?;
3314 let cursor_is_placed_after_comment_marker =
3315 index_of_first_non_whitespace + comment_prefix.len()
3316 <= start_point.column as usize;
3317 if cursor_is_placed_after_comment_marker {
3318 Some(comment_prefix.clone())
3319 } else {
3320 None
3321 }
3322 });
3323 (comment_delimiter, insert_extra_newline)
3324 } else {
3325 (None, false)
3326 };
3327
3328 let capacity_for_delimiter = comment_delimiter
3329 .as_deref()
3330 .map(str::len)
3331 .unwrap_or_default();
3332 let mut new_text =
3333 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3334 new_text.push('\n');
3335 new_text.extend(indent.chars());
3336 if let Some(delimiter) = &comment_delimiter {
3337 new_text.push_str(delimiter);
3338 }
3339 if insert_extra_newline {
3340 new_text = new_text.repeat(2);
3341 }
3342
3343 let anchor = buffer.anchor_after(end);
3344 let new_selection = selection.map(|_| anchor);
3345 (
3346 (start..end, new_text),
3347 (insert_extra_newline, new_selection),
3348 )
3349 })
3350 .unzip()
3351 };
3352
3353 this.edit_with_autoindent(edits, cx);
3354 let buffer = this.buffer.read(cx).snapshot(cx);
3355 let new_selections = selection_fixup_info
3356 .into_iter()
3357 .map(|(extra_newline_inserted, new_selection)| {
3358 let mut cursor = new_selection.end.to_point(&buffer);
3359 if extra_newline_inserted {
3360 cursor.row -= 1;
3361 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3362 }
3363 new_selection.map(|_| cursor)
3364 })
3365 .collect();
3366
3367 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3368 s.select(new_selections)
3369 });
3370 this.refresh_inline_completion(true, false, window, cx);
3371 });
3372 }
3373
3374 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3375 let buffer = self.buffer.read(cx);
3376 let snapshot = buffer.snapshot(cx);
3377
3378 let mut edits = Vec::new();
3379 let mut rows = Vec::new();
3380
3381 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3382 let cursor = selection.head();
3383 let row = cursor.row;
3384
3385 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3386
3387 let newline = "\n".to_string();
3388 edits.push((start_of_line..start_of_line, newline));
3389
3390 rows.push(row + rows_inserted as u32);
3391 }
3392
3393 self.transact(window, cx, |editor, window, cx| {
3394 editor.edit(edits, cx);
3395
3396 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3397 let mut index = 0;
3398 s.move_cursors_with(|map, _, _| {
3399 let row = rows[index];
3400 index += 1;
3401
3402 let point = Point::new(row, 0);
3403 let boundary = map.next_line_boundary(point).1;
3404 let clipped = map.clip_point(boundary, Bias::Left);
3405
3406 (clipped, SelectionGoal::None)
3407 });
3408 });
3409
3410 let mut indent_edits = Vec::new();
3411 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3412 for row in rows {
3413 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3414 for (row, indent) in indents {
3415 if indent.len == 0 {
3416 continue;
3417 }
3418
3419 let text = match indent.kind {
3420 IndentKind::Space => " ".repeat(indent.len as usize),
3421 IndentKind::Tab => "\t".repeat(indent.len as usize),
3422 };
3423 let point = Point::new(row.0, 0);
3424 indent_edits.push((point..point, text));
3425 }
3426 }
3427 editor.edit(indent_edits, cx);
3428 });
3429 }
3430
3431 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3432 let buffer = self.buffer.read(cx);
3433 let snapshot = buffer.snapshot(cx);
3434
3435 let mut edits = Vec::new();
3436 let mut rows = Vec::new();
3437 let mut rows_inserted = 0;
3438
3439 for selection in self.selections.all_adjusted(cx) {
3440 let cursor = selection.head();
3441 let row = cursor.row;
3442
3443 let point = Point::new(row + 1, 0);
3444 let start_of_line = snapshot.clip_point(point, Bias::Left);
3445
3446 let newline = "\n".to_string();
3447 edits.push((start_of_line..start_of_line, newline));
3448
3449 rows_inserted += 1;
3450 rows.push(row + rows_inserted);
3451 }
3452
3453 self.transact(window, cx, |editor, window, cx| {
3454 editor.edit(edits, cx);
3455
3456 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3457 let mut index = 0;
3458 s.move_cursors_with(|map, _, _| {
3459 let row = rows[index];
3460 index += 1;
3461
3462 let point = Point::new(row, 0);
3463 let boundary = map.next_line_boundary(point).1;
3464 let clipped = map.clip_point(boundary, Bias::Left);
3465
3466 (clipped, SelectionGoal::None)
3467 });
3468 });
3469
3470 let mut indent_edits = Vec::new();
3471 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3472 for row in rows {
3473 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3474 for (row, indent) in indents {
3475 if indent.len == 0 {
3476 continue;
3477 }
3478
3479 let text = match indent.kind {
3480 IndentKind::Space => " ".repeat(indent.len as usize),
3481 IndentKind::Tab => "\t".repeat(indent.len as usize),
3482 };
3483 let point = Point::new(row.0, 0);
3484 indent_edits.push((point..point, text));
3485 }
3486 }
3487 editor.edit(indent_edits, cx);
3488 });
3489 }
3490
3491 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3492 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3493 original_indent_columns: Vec::new(),
3494 });
3495 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3496 }
3497
3498 fn insert_with_autoindent_mode(
3499 &mut self,
3500 text: &str,
3501 autoindent_mode: Option<AutoindentMode>,
3502 window: &mut Window,
3503 cx: &mut Context<Self>,
3504 ) {
3505 if self.read_only(cx) {
3506 return;
3507 }
3508
3509 let text: Arc<str> = text.into();
3510 self.transact(window, cx, |this, window, cx| {
3511 let old_selections = this.selections.all_adjusted(cx);
3512 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3513 let anchors = {
3514 let snapshot = buffer.read(cx);
3515 old_selections
3516 .iter()
3517 .map(|s| {
3518 let anchor = snapshot.anchor_after(s.head());
3519 s.map(|_| anchor)
3520 })
3521 .collect::<Vec<_>>()
3522 };
3523 buffer.edit(
3524 old_selections
3525 .iter()
3526 .map(|s| (s.start..s.end, text.clone())),
3527 autoindent_mode,
3528 cx,
3529 );
3530 anchors
3531 });
3532
3533 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3534 s.select_anchors(selection_anchors);
3535 });
3536
3537 cx.notify();
3538 });
3539 }
3540
3541 fn trigger_completion_on_input(
3542 &mut self,
3543 text: &str,
3544 trigger_in_words: bool,
3545 window: &mut Window,
3546 cx: &mut Context<Self>,
3547 ) {
3548 if self.is_completion_trigger(text, trigger_in_words, cx) {
3549 self.show_completions(
3550 &ShowCompletions {
3551 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3552 },
3553 window,
3554 cx,
3555 );
3556 } else {
3557 self.hide_context_menu(window, cx);
3558 }
3559 }
3560
3561 fn is_completion_trigger(
3562 &self,
3563 text: &str,
3564 trigger_in_words: bool,
3565 cx: &mut Context<Self>,
3566 ) -> bool {
3567 let position = self.selections.newest_anchor().head();
3568 let multibuffer = self.buffer.read(cx);
3569 let Some(buffer) = position
3570 .buffer_id
3571 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3572 else {
3573 return false;
3574 };
3575
3576 if let Some(completion_provider) = &self.completion_provider {
3577 completion_provider.is_completion_trigger(
3578 &buffer,
3579 position.text_anchor,
3580 text,
3581 trigger_in_words,
3582 cx,
3583 )
3584 } else {
3585 false
3586 }
3587 }
3588
3589 /// If any empty selections is touching the start of its innermost containing autoclose
3590 /// region, expand it to select the brackets.
3591 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3592 let selections = self.selections.all::<usize>(cx);
3593 let buffer = self.buffer.read(cx).read(cx);
3594 let new_selections = self
3595 .selections_with_autoclose_regions(selections, &buffer)
3596 .map(|(mut selection, region)| {
3597 if !selection.is_empty() {
3598 return selection;
3599 }
3600
3601 if let Some(region) = region {
3602 let mut range = region.range.to_offset(&buffer);
3603 if selection.start == range.start && range.start >= region.pair.start.len() {
3604 range.start -= region.pair.start.len();
3605 if buffer.contains_str_at(range.start, ®ion.pair.start)
3606 && buffer.contains_str_at(range.end, ®ion.pair.end)
3607 {
3608 range.end += region.pair.end.len();
3609 selection.start = range.start;
3610 selection.end = range.end;
3611
3612 return selection;
3613 }
3614 }
3615 }
3616
3617 let always_treat_brackets_as_autoclosed = buffer
3618 .language_settings_at(selection.start, cx)
3619 .always_treat_brackets_as_autoclosed;
3620
3621 if !always_treat_brackets_as_autoclosed {
3622 return selection;
3623 }
3624
3625 if let Some(scope) = buffer.language_scope_at(selection.start) {
3626 for (pair, enabled) in scope.brackets() {
3627 if !enabled || !pair.close {
3628 continue;
3629 }
3630
3631 if buffer.contains_str_at(selection.start, &pair.end) {
3632 let pair_start_len = pair.start.len();
3633 if buffer.contains_str_at(
3634 selection.start.saturating_sub(pair_start_len),
3635 &pair.start,
3636 ) {
3637 selection.start -= pair_start_len;
3638 selection.end += pair.end.len();
3639
3640 return selection;
3641 }
3642 }
3643 }
3644 }
3645
3646 selection
3647 })
3648 .collect();
3649
3650 drop(buffer);
3651 self.change_selections(None, window, cx, |selections| {
3652 selections.select(new_selections)
3653 });
3654 }
3655
3656 /// Iterate the given selections, and for each one, find the smallest surrounding
3657 /// autoclose region. This uses the ordering of the selections and the autoclose
3658 /// regions to avoid repeated comparisons.
3659 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3660 &'a self,
3661 selections: impl IntoIterator<Item = Selection<D>>,
3662 buffer: &'a MultiBufferSnapshot,
3663 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3664 let mut i = 0;
3665 let mut regions = self.autoclose_regions.as_slice();
3666 selections.into_iter().map(move |selection| {
3667 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3668
3669 let mut enclosing = None;
3670 while let Some(pair_state) = regions.get(i) {
3671 if pair_state.range.end.to_offset(buffer) < range.start {
3672 regions = ®ions[i + 1..];
3673 i = 0;
3674 } else if pair_state.range.start.to_offset(buffer) > range.end {
3675 break;
3676 } else {
3677 if pair_state.selection_id == selection.id {
3678 enclosing = Some(pair_state);
3679 }
3680 i += 1;
3681 }
3682 }
3683
3684 (selection, enclosing)
3685 })
3686 }
3687
3688 /// Remove any autoclose regions that no longer contain their selection.
3689 fn invalidate_autoclose_regions(
3690 &mut self,
3691 mut selections: &[Selection<Anchor>],
3692 buffer: &MultiBufferSnapshot,
3693 ) {
3694 self.autoclose_regions.retain(|state| {
3695 let mut i = 0;
3696 while let Some(selection) = selections.get(i) {
3697 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3698 selections = &selections[1..];
3699 continue;
3700 }
3701 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3702 break;
3703 }
3704 if selection.id == state.selection_id {
3705 return true;
3706 } else {
3707 i += 1;
3708 }
3709 }
3710 false
3711 });
3712 }
3713
3714 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3715 let offset = position.to_offset(buffer);
3716 let (word_range, kind) = buffer.surrounding_word(offset, true);
3717 if offset > word_range.start && kind == Some(CharKind::Word) {
3718 Some(
3719 buffer
3720 .text_for_range(word_range.start..offset)
3721 .collect::<String>(),
3722 )
3723 } else {
3724 None
3725 }
3726 }
3727
3728 pub fn toggle_inlay_hints(
3729 &mut self,
3730 _: &ToggleInlayHints,
3731 _: &mut Window,
3732 cx: &mut Context<Self>,
3733 ) {
3734 self.refresh_inlay_hints(
3735 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3736 cx,
3737 );
3738 }
3739
3740 pub fn inlay_hints_enabled(&self) -> bool {
3741 self.inlay_hint_cache.enabled
3742 }
3743
3744 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3745 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3746 return;
3747 }
3748
3749 let reason_description = reason.description();
3750 let ignore_debounce = matches!(
3751 reason,
3752 InlayHintRefreshReason::SettingsChange(_)
3753 | InlayHintRefreshReason::Toggle(_)
3754 | InlayHintRefreshReason::ExcerptsRemoved(_)
3755 | InlayHintRefreshReason::ModifiersChanged(_)
3756 );
3757 let (invalidate_cache, required_languages) = match reason {
3758 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3759 match self.inlay_hint_cache.modifiers_override(enabled) {
3760 Some(enabled) => {
3761 if enabled {
3762 (InvalidationStrategy::RefreshRequested, None)
3763 } else {
3764 self.splice_inlays(
3765 &self
3766 .visible_inlay_hints(cx)
3767 .iter()
3768 .map(|inlay| inlay.id)
3769 .collect::<Vec<InlayId>>(),
3770 Vec::new(),
3771 cx,
3772 );
3773 return;
3774 }
3775 }
3776 None => return,
3777 }
3778 }
3779 InlayHintRefreshReason::Toggle(enabled) => {
3780 if self.inlay_hint_cache.toggle(enabled) {
3781 if enabled {
3782 (InvalidationStrategy::RefreshRequested, None)
3783 } else {
3784 self.splice_inlays(
3785 &self
3786 .visible_inlay_hints(cx)
3787 .iter()
3788 .map(|inlay| inlay.id)
3789 .collect::<Vec<InlayId>>(),
3790 Vec::new(),
3791 cx,
3792 );
3793 return;
3794 }
3795 } else {
3796 return;
3797 }
3798 }
3799 InlayHintRefreshReason::SettingsChange(new_settings) => {
3800 match self.inlay_hint_cache.update_settings(
3801 &self.buffer,
3802 new_settings,
3803 self.visible_inlay_hints(cx),
3804 cx,
3805 ) {
3806 ControlFlow::Break(Some(InlaySplice {
3807 to_remove,
3808 to_insert,
3809 })) => {
3810 self.splice_inlays(&to_remove, to_insert, cx);
3811 return;
3812 }
3813 ControlFlow::Break(None) => return,
3814 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3815 }
3816 }
3817 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3818 if let Some(InlaySplice {
3819 to_remove,
3820 to_insert,
3821 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3822 {
3823 self.splice_inlays(&to_remove, to_insert, cx);
3824 }
3825 return;
3826 }
3827 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3828 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3829 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3830 }
3831 InlayHintRefreshReason::RefreshRequested => {
3832 (InvalidationStrategy::RefreshRequested, None)
3833 }
3834 };
3835
3836 if let Some(InlaySplice {
3837 to_remove,
3838 to_insert,
3839 }) = self.inlay_hint_cache.spawn_hint_refresh(
3840 reason_description,
3841 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3842 invalidate_cache,
3843 ignore_debounce,
3844 cx,
3845 ) {
3846 self.splice_inlays(&to_remove, to_insert, cx);
3847 }
3848 }
3849
3850 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3851 self.display_map
3852 .read(cx)
3853 .current_inlays()
3854 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3855 .cloned()
3856 .collect()
3857 }
3858
3859 pub fn excerpts_for_inlay_hints_query(
3860 &self,
3861 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3862 cx: &mut Context<Editor>,
3863 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3864 let Some(project) = self.project.as_ref() else {
3865 return HashMap::default();
3866 };
3867 let project = project.read(cx);
3868 let multi_buffer = self.buffer().read(cx);
3869 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3870 let multi_buffer_visible_start = self
3871 .scroll_manager
3872 .anchor()
3873 .anchor
3874 .to_point(&multi_buffer_snapshot);
3875 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3876 multi_buffer_visible_start
3877 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3878 Bias::Left,
3879 );
3880 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3881 multi_buffer_snapshot
3882 .range_to_buffer_ranges(multi_buffer_visible_range)
3883 .into_iter()
3884 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3885 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3886 let buffer_file = project::File::from_dyn(buffer.file())?;
3887 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3888 let worktree_entry = buffer_worktree
3889 .read(cx)
3890 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3891 if worktree_entry.is_ignored {
3892 return None;
3893 }
3894
3895 let language = buffer.language()?;
3896 if let Some(restrict_to_languages) = restrict_to_languages {
3897 if !restrict_to_languages.contains(language) {
3898 return None;
3899 }
3900 }
3901 Some((
3902 excerpt_id,
3903 (
3904 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3905 buffer.version().clone(),
3906 excerpt_visible_range,
3907 ),
3908 ))
3909 })
3910 .collect()
3911 }
3912
3913 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3914 TextLayoutDetails {
3915 text_system: window.text_system().clone(),
3916 editor_style: self.style.clone().unwrap(),
3917 rem_size: window.rem_size(),
3918 scroll_anchor: self.scroll_manager.anchor(),
3919 visible_rows: self.visible_line_count(),
3920 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3921 }
3922 }
3923
3924 pub fn splice_inlays(
3925 &self,
3926 to_remove: &[InlayId],
3927 to_insert: Vec<Inlay>,
3928 cx: &mut Context<Self>,
3929 ) {
3930 self.display_map.update(cx, |display_map, cx| {
3931 display_map.splice_inlays(to_remove, to_insert, cx)
3932 });
3933 cx.notify();
3934 }
3935
3936 fn trigger_on_type_formatting(
3937 &self,
3938 input: String,
3939 window: &mut Window,
3940 cx: &mut Context<Self>,
3941 ) -> Option<Task<Result<()>>> {
3942 if input.len() != 1 {
3943 return None;
3944 }
3945
3946 let project = self.project.as_ref()?;
3947 let position = self.selections.newest_anchor().head();
3948 let (buffer, buffer_position) = self
3949 .buffer
3950 .read(cx)
3951 .text_anchor_for_position(position, cx)?;
3952
3953 let settings = language_settings::language_settings(
3954 buffer
3955 .read(cx)
3956 .language_at(buffer_position)
3957 .map(|l| l.name()),
3958 buffer.read(cx).file(),
3959 cx,
3960 );
3961 if !settings.use_on_type_format {
3962 return None;
3963 }
3964
3965 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3966 // hence we do LSP request & edit on host side only — add formats to host's history.
3967 let push_to_lsp_host_history = true;
3968 // If this is not the host, append its history with new edits.
3969 let push_to_client_history = project.read(cx).is_via_collab();
3970
3971 let on_type_formatting = project.update(cx, |project, cx| {
3972 project.on_type_format(
3973 buffer.clone(),
3974 buffer_position,
3975 input,
3976 push_to_lsp_host_history,
3977 cx,
3978 )
3979 });
3980 Some(cx.spawn_in(window, |editor, mut cx| async move {
3981 if let Some(transaction) = on_type_formatting.await? {
3982 if push_to_client_history {
3983 buffer
3984 .update(&mut cx, |buffer, _| {
3985 buffer.push_transaction(transaction, Instant::now());
3986 })
3987 .ok();
3988 }
3989 editor.update(&mut cx, |editor, cx| {
3990 editor.refresh_document_highlights(cx);
3991 })?;
3992 }
3993 Ok(())
3994 }))
3995 }
3996
3997 pub fn show_completions(
3998 &mut self,
3999 options: &ShowCompletions,
4000 window: &mut Window,
4001 cx: &mut Context<Self>,
4002 ) {
4003 if self.pending_rename.is_some() {
4004 return;
4005 }
4006
4007 let Some(provider) = self.completion_provider.as_ref() else {
4008 return;
4009 };
4010
4011 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4012 return;
4013 }
4014
4015 let position = self.selections.newest_anchor().head();
4016 if position.diff_base_anchor.is_some() {
4017 return;
4018 }
4019 let (buffer, buffer_position) =
4020 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4021 output
4022 } else {
4023 return;
4024 };
4025 let buffer_snapshot = buffer.read(cx).snapshot();
4026 let show_completion_documentation = buffer_snapshot
4027 .settings_at(buffer_position, cx)
4028 .show_completion_documentation;
4029
4030 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4031
4032 let trigger_kind = match &options.trigger {
4033 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4034 CompletionTriggerKind::TRIGGER_CHARACTER
4035 }
4036 _ => CompletionTriggerKind::INVOKED,
4037 };
4038 let completion_context = CompletionContext {
4039 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4040 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4041 Some(String::from(trigger))
4042 } else {
4043 None
4044 }
4045 }),
4046 trigger_kind,
4047 };
4048 let completions =
4049 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4050 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4051 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4052 let word_to_exclude = buffer_snapshot
4053 .text_for_range(old_range.clone())
4054 .collect::<String>();
4055 (
4056 buffer_snapshot.anchor_before(old_range.start)
4057 ..buffer_snapshot.anchor_after(old_range.end),
4058 Some(word_to_exclude),
4059 )
4060 } else {
4061 (buffer_position..buffer_position, None)
4062 };
4063
4064 let completion_settings = language_settings(
4065 buffer_snapshot
4066 .language_at(buffer_position)
4067 .map(|language| language.name()),
4068 buffer_snapshot.file(),
4069 cx,
4070 )
4071 .completions;
4072
4073 // The document can be large, so stay in reasonable bounds when searching for words,
4074 // otherwise completion pop-up might be slow to appear.
4075 const WORD_LOOKUP_ROWS: u32 = 5_000;
4076 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4077 let min_word_search = buffer_snapshot.clip_point(
4078 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4079 Bias::Left,
4080 );
4081 let max_word_search = buffer_snapshot.clip_point(
4082 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4083 Bias::Right,
4084 );
4085 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4086 ..buffer_snapshot.point_to_offset(max_word_search);
4087 let words = match completion_settings.words {
4088 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4089 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => {
4090 cx.background_spawn(async move {
4091 buffer_snapshot.words_in_range(None, word_search_range)
4092 })
4093 }
4094 };
4095 let sort_completions = provider.sort_completions();
4096
4097 let id = post_inc(&mut self.next_completion_id);
4098 let task = cx.spawn_in(window, |editor, mut cx| {
4099 async move {
4100 editor.update(&mut cx, |this, _| {
4101 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4102 })?;
4103 let mut completions = completions.await.log_err().unwrap_or_default();
4104
4105 match completion_settings.words {
4106 WordsCompletionMode::Enabled => {
4107 completions.extend(
4108 words
4109 .await
4110 .into_iter()
4111 .filter(|(word, _)| word_to_exclude.as_ref() != Some(word))
4112 .map(|(word, word_range)| Completion {
4113 old_range: old_range.clone(),
4114 new_text: word.clone(),
4115 label: CodeLabel::plain(word, None),
4116 documentation: None,
4117 source: CompletionSource::BufferWord {
4118 word_range,
4119 resolved: false,
4120 },
4121 confirm: None,
4122 }),
4123 );
4124 }
4125 WordsCompletionMode::Fallback => {
4126 if completions.is_empty() {
4127 completions.extend(
4128 words
4129 .await
4130 .into_iter()
4131 .filter(|(word, _)| word_to_exclude.as_ref() != Some(word))
4132 .map(|(word, word_range)| Completion {
4133 old_range: old_range.clone(),
4134 new_text: word.clone(),
4135 label: CodeLabel::plain(word, None),
4136 documentation: None,
4137 source: CompletionSource::BufferWord {
4138 word_range,
4139 resolved: false,
4140 },
4141 confirm: None,
4142 }),
4143 );
4144 }
4145 }
4146 WordsCompletionMode::Disabled => {}
4147 }
4148
4149 let menu = if completions.is_empty() {
4150 None
4151 } else {
4152 let mut menu = CompletionsMenu::new(
4153 id,
4154 sort_completions,
4155 show_completion_documentation,
4156 position,
4157 buffer.clone(),
4158 completions.into(),
4159 );
4160
4161 menu.filter(query.as_deref(), cx.background_executor().clone())
4162 .await;
4163
4164 menu.visible().then_some(menu)
4165 };
4166
4167 editor.update_in(&mut cx, |editor, window, cx| {
4168 match editor.context_menu.borrow().as_ref() {
4169 None => {}
4170 Some(CodeContextMenu::Completions(prev_menu)) => {
4171 if prev_menu.id > id {
4172 return;
4173 }
4174 }
4175 _ => return,
4176 }
4177
4178 if editor.focus_handle.is_focused(window) && menu.is_some() {
4179 let mut menu = menu.unwrap();
4180 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4181
4182 *editor.context_menu.borrow_mut() =
4183 Some(CodeContextMenu::Completions(menu));
4184
4185 if editor.show_edit_predictions_in_menu() {
4186 editor.update_visible_inline_completion(window, cx);
4187 } else {
4188 editor.discard_inline_completion(false, cx);
4189 }
4190
4191 cx.notify();
4192 } else if editor.completion_tasks.len() <= 1 {
4193 // If there are no more completion tasks and the last menu was
4194 // empty, we should hide it.
4195 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4196 // If it was already hidden and we don't show inline
4197 // completions in the menu, we should also show the
4198 // inline-completion when available.
4199 if was_hidden && editor.show_edit_predictions_in_menu() {
4200 editor.update_visible_inline_completion(window, cx);
4201 }
4202 }
4203 })?;
4204
4205 Ok::<_, anyhow::Error>(())
4206 }
4207 .log_err()
4208 });
4209
4210 self.completion_tasks.push((id, task));
4211 }
4212
4213 pub fn confirm_completion(
4214 &mut self,
4215 action: &ConfirmCompletion,
4216 window: &mut Window,
4217 cx: &mut Context<Self>,
4218 ) -> Option<Task<Result<()>>> {
4219 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4220 }
4221
4222 pub fn compose_completion(
4223 &mut self,
4224 action: &ComposeCompletion,
4225 window: &mut Window,
4226 cx: &mut Context<Self>,
4227 ) -> Option<Task<Result<()>>> {
4228 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4229 }
4230
4231 fn do_completion(
4232 &mut self,
4233 item_ix: Option<usize>,
4234 intent: CompletionIntent,
4235 window: &mut Window,
4236 cx: &mut Context<Editor>,
4237 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4238 use language::ToOffset as _;
4239
4240 let completions_menu =
4241 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4242 menu
4243 } else {
4244 return None;
4245 };
4246
4247 let entries = completions_menu.entries.borrow();
4248 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4249 if self.show_edit_predictions_in_menu() {
4250 self.discard_inline_completion(true, cx);
4251 }
4252 let candidate_id = mat.candidate_id;
4253 drop(entries);
4254
4255 let buffer_handle = completions_menu.buffer;
4256 let completion = completions_menu
4257 .completions
4258 .borrow()
4259 .get(candidate_id)?
4260 .clone();
4261 cx.stop_propagation();
4262
4263 let snippet;
4264 let text;
4265
4266 if completion.is_snippet() {
4267 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4268 text = snippet.as_ref().unwrap().text.clone();
4269 } else {
4270 snippet = None;
4271 text = completion.new_text.clone();
4272 };
4273 let selections = self.selections.all::<usize>(cx);
4274 let buffer = buffer_handle.read(cx);
4275 let old_range = completion.old_range.to_offset(buffer);
4276 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4277
4278 let newest_selection = self.selections.newest_anchor();
4279 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4280 return None;
4281 }
4282
4283 let lookbehind = newest_selection
4284 .start
4285 .text_anchor
4286 .to_offset(buffer)
4287 .saturating_sub(old_range.start);
4288 let lookahead = old_range
4289 .end
4290 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4291 let mut common_prefix_len = old_text
4292 .bytes()
4293 .zip(text.bytes())
4294 .take_while(|(a, b)| a == b)
4295 .count();
4296
4297 let snapshot = self.buffer.read(cx).snapshot(cx);
4298 let mut range_to_replace: Option<Range<isize>> = None;
4299 let mut ranges = Vec::new();
4300 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4301 for selection in &selections {
4302 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4303 let start = selection.start.saturating_sub(lookbehind);
4304 let end = selection.end + lookahead;
4305 if selection.id == newest_selection.id {
4306 range_to_replace = Some(
4307 ((start + common_prefix_len) as isize - selection.start as isize)
4308 ..(end as isize - selection.start as isize),
4309 );
4310 }
4311 ranges.push(start + common_prefix_len..end);
4312 } else {
4313 common_prefix_len = 0;
4314 ranges.clear();
4315 ranges.extend(selections.iter().map(|s| {
4316 if s.id == newest_selection.id {
4317 range_to_replace = Some(
4318 old_range.start.to_offset_utf16(&snapshot).0 as isize
4319 - selection.start as isize
4320 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4321 - selection.start as isize,
4322 );
4323 old_range.clone()
4324 } else {
4325 s.start..s.end
4326 }
4327 }));
4328 break;
4329 }
4330 if !self.linked_edit_ranges.is_empty() {
4331 let start_anchor = snapshot.anchor_before(selection.head());
4332 let end_anchor = snapshot.anchor_after(selection.tail());
4333 if let Some(ranges) = self
4334 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4335 {
4336 for (buffer, edits) in ranges {
4337 linked_edits.entry(buffer.clone()).or_default().extend(
4338 edits
4339 .into_iter()
4340 .map(|range| (range, text[common_prefix_len..].to_owned())),
4341 );
4342 }
4343 }
4344 }
4345 }
4346 let text = &text[common_prefix_len..];
4347
4348 cx.emit(EditorEvent::InputHandled {
4349 utf16_range_to_replace: range_to_replace,
4350 text: text.into(),
4351 });
4352
4353 self.transact(window, cx, |this, window, cx| {
4354 if let Some(mut snippet) = snippet {
4355 snippet.text = text.to_string();
4356 for tabstop in snippet
4357 .tabstops
4358 .iter_mut()
4359 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4360 {
4361 tabstop.start -= common_prefix_len as isize;
4362 tabstop.end -= common_prefix_len as isize;
4363 }
4364
4365 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4366 } else {
4367 this.buffer.update(cx, |buffer, cx| {
4368 buffer.edit(
4369 ranges.iter().map(|range| (range.clone(), text)),
4370 this.autoindent_mode.clone(),
4371 cx,
4372 );
4373 });
4374 }
4375 for (buffer, edits) in linked_edits {
4376 buffer.update(cx, |buffer, cx| {
4377 let snapshot = buffer.snapshot();
4378 let edits = edits
4379 .into_iter()
4380 .map(|(range, text)| {
4381 use text::ToPoint as TP;
4382 let end_point = TP::to_point(&range.end, &snapshot);
4383 let start_point = TP::to_point(&range.start, &snapshot);
4384 (start_point..end_point, text)
4385 })
4386 .sorted_by_key(|(range, _)| range.start)
4387 .collect::<Vec<_>>();
4388 buffer.edit(edits, None, cx);
4389 })
4390 }
4391
4392 this.refresh_inline_completion(true, false, window, cx);
4393 });
4394
4395 let show_new_completions_on_confirm = completion
4396 .confirm
4397 .as_ref()
4398 .map_or(false, |confirm| confirm(intent, window, cx));
4399 if show_new_completions_on_confirm {
4400 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4401 }
4402
4403 let provider = self.completion_provider.as_ref()?;
4404 drop(completion);
4405 let apply_edits = provider.apply_additional_edits_for_completion(
4406 buffer_handle,
4407 completions_menu.completions.clone(),
4408 candidate_id,
4409 true,
4410 cx,
4411 );
4412
4413 let editor_settings = EditorSettings::get_global(cx);
4414 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4415 // After the code completion is finished, users often want to know what signatures are needed.
4416 // so we should automatically call signature_help
4417 self.show_signature_help(&ShowSignatureHelp, window, cx);
4418 }
4419
4420 Some(cx.foreground_executor().spawn(async move {
4421 apply_edits.await?;
4422 Ok(())
4423 }))
4424 }
4425
4426 pub fn toggle_code_actions(
4427 &mut self,
4428 action: &ToggleCodeActions,
4429 window: &mut Window,
4430 cx: &mut Context<Self>,
4431 ) {
4432 let mut context_menu = self.context_menu.borrow_mut();
4433 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4434 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4435 // Toggle if we're selecting the same one
4436 *context_menu = None;
4437 cx.notify();
4438 return;
4439 } else {
4440 // Otherwise, clear it and start a new one
4441 *context_menu = None;
4442 cx.notify();
4443 }
4444 }
4445 drop(context_menu);
4446 let snapshot = self.snapshot(window, cx);
4447 let deployed_from_indicator = action.deployed_from_indicator;
4448 let mut task = self.code_actions_task.take();
4449 let action = action.clone();
4450 cx.spawn_in(window, |editor, mut cx| async move {
4451 while let Some(prev_task) = task {
4452 prev_task.await.log_err();
4453 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4454 }
4455
4456 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4457 if editor.focus_handle.is_focused(window) {
4458 let multibuffer_point = action
4459 .deployed_from_indicator
4460 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4461 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4462 let (buffer, buffer_row) = snapshot
4463 .buffer_snapshot
4464 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4465 .and_then(|(buffer_snapshot, range)| {
4466 editor
4467 .buffer
4468 .read(cx)
4469 .buffer(buffer_snapshot.remote_id())
4470 .map(|buffer| (buffer, range.start.row))
4471 })?;
4472 let (_, code_actions) = editor
4473 .available_code_actions
4474 .clone()
4475 .and_then(|(location, code_actions)| {
4476 let snapshot = location.buffer.read(cx).snapshot();
4477 let point_range = location.range.to_point(&snapshot);
4478 let point_range = point_range.start.row..=point_range.end.row;
4479 if point_range.contains(&buffer_row) {
4480 Some((location, code_actions))
4481 } else {
4482 None
4483 }
4484 })
4485 .unzip();
4486 let buffer_id = buffer.read(cx).remote_id();
4487 let tasks = editor
4488 .tasks
4489 .get(&(buffer_id, buffer_row))
4490 .map(|t| Arc::new(t.to_owned()));
4491 if tasks.is_none() && code_actions.is_none() {
4492 return None;
4493 }
4494
4495 editor.completion_tasks.clear();
4496 editor.discard_inline_completion(false, cx);
4497 let task_context =
4498 tasks
4499 .as_ref()
4500 .zip(editor.project.clone())
4501 .map(|(tasks, project)| {
4502 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4503 });
4504
4505 Some(cx.spawn_in(window, |editor, mut cx| async move {
4506 let task_context = match task_context {
4507 Some(task_context) => task_context.await,
4508 None => None,
4509 };
4510 let resolved_tasks =
4511 tasks.zip(task_context).map(|(tasks, task_context)| {
4512 Rc::new(ResolvedTasks {
4513 templates: tasks.resolve(&task_context).collect(),
4514 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4515 multibuffer_point.row,
4516 tasks.column,
4517 )),
4518 })
4519 });
4520 let spawn_straight_away = resolved_tasks
4521 .as_ref()
4522 .map_or(false, |tasks| tasks.templates.len() == 1)
4523 && code_actions
4524 .as_ref()
4525 .map_or(true, |actions| actions.is_empty());
4526 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4527 *editor.context_menu.borrow_mut() =
4528 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4529 buffer,
4530 actions: CodeActionContents {
4531 tasks: resolved_tasks,
4532 actions: code_actions,
4533 },
4534 selected_item: Default::default(),
4535 scroll_handle: UniformListScrollHandle::default(),
4536 deployed_from_indicator,
4537 }));
4538 if spawn_straight_away {
4539 if let Some(task) = editor.confirm_code_action(
4540 &ConfirmCodeAction { item_ix: Some(0) },
4541 window,
4542 cx,
4543 ) {
4544 cx.notify();
4545 return task;
4546 }
4547 }
4548 cx.notify();
4549 Task::ready(Ok(()))
4550 }) {
4551 task.await
4552 } else {
4553 Ok(())
4554 }
4555 }))
4556 } else {
4557 Some(Task::ready(Ok(())))
4558 }
4559 })?;
4560 if let Some(task) = spawned_test_task {
4561 task.await?;
4562 }
4563
4564 Ok::<_, anyhow::Error>(())
4565 })
4566 .detach_and_log_err(cx);
4567 }
4568
4569 pub fn confirm_code_action(
4570 &mut self,
4571 action: &ConfirmCodeAction,
4572 window: &mut Window,
4573 cx: &mut Context<Self>,
4574 ) -> Option<Task<Result<()>>> {
4575 let actions_menu =
4576 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4577 menu
4578 } else {
4579 return None;
4580 };
4581 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4582 let action = actions_menu.actions.get(action_ix)?;
4583 let title = action.label();
4584 let buffer = actions_menu.buffer;
4585 let workspace = self.workspace()?;
4586
4587 match action {
4588 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4589 workspace.update(cx, |workspace, cx| {
4590 workspace::tasks::schedule_resolved_task(
4591 workspace,
4592 task_source_kind,
4593 resolved_task,
4594 false,
4595 cx,
4596 );
4597
4598 Some(Task::ready(Ok(())))
4599 })
4600 }
4601 CodeActionsItem::CodeAction {
4602 excerpt_id,
4603 action,
4604 provider,
4605 } => {
4606 let apply_code_action =
4607 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4608 let workspace = workspace.downgrade();
4609 Some(cx.spawn_in(window, |editor, cx| async move {
4610 let project_transaction = apply_code_action.await?;
4611 Self::open_project_transaction(
4612 &editor,
4613 workspace,
4614 project_transaction,
4615 title,
4616 cx,
4617 )
4618 .await
4619 }))
4620 }
4621 }
4622 }
4623
4624 pub async fn open_project_transaction(
4625 this: &WeakEntity<Editor>,
4626 workspace: WeakEntity<Workspace>,
4627 transaction: ProjectTransaction,
4628 title: String,
4629 mut cx: AsyncWindowContext,
4630 ) -> Result<()> {
4631 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4632 cx.update(|_, cx| {
4633 entries.sort_unstable_by_key(|(buffer, _)| {
4634 buffer.read(cx).file().map(|f| f.path().clone())
4635 });
4636 })?;
4637
4638 // If the project transaction's edits are all contained within this editor, then
4639 // avoid opening a new editor to display them.
4640
4641 if let Some((buffer, transaction)) = entries.first() {
4642 if entries.len() == 1 {
4643 let excerpt = this.update(&mut cx, |editor, cx| {
4644 editor
4645 .buffer()
4646 .read(cx)
4647 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4648 })?;
4649 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4650 if excerpted_buffer == *buffer {
4651 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4652 let excerpt_range = excerpt_range.to_offset(buffer);
4653 buffer
4654 .edited_ranges_for_transaction::<usize>(transaction)
4655 .all(|range| {
4656 excerpt_range.start <= range.start
4657 && excerpt_range.end >= range.end
4658 })
4659 })?;
4660
4661 if all_edits_within_excerpt {
4662 return Ok(());
4663 }
4664 }
4665 }
4666 }
4667 } else {
4668 return Ok(());
4669 }
4670
4671 let mut ranges_to_highlight = Vec::new();
4672 let excerpt_buffer = cx.new(|cx| {
4673 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4674 for (buffer_handle, transaction) in &entries {
4675 let buffer = buffer_handle.read(cx);
4676 ranges_to_highlight.extend(
4677 multibuffer.push_excerpts_with_context_lines(
4678 buffer_handle.clone(),
4679 buffer
4680 .edited_ranges_for_transaction::<usize>(transaction)
4681 .collect(),
4682 DEFAULT_MULTIBUFFER_CONTEXT,
4683 cx,
4684 ),
4685 );
4686 }
4687 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4688 multibuffer
4689 })?;
4690
4691 workspace.update_in(&mut cx, |workspace, window, cx| {
4692 let project = workspace.project().clone();
4693 let editor = cx
4694 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4695 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4696 editor.update(cx, |editor, cx| {
4697 editor.highlight_background::<Self>(
4698 &ranges_to_highlight,
4699 |theme| theme.editor_highlighted_line_background,
4700 cx,
4701 );
4702 });
4703 })?;
4704
4705 Ok(())
4706 }
4707
4708 pub fn clear_code_action_providers(&mut self) {
4709 self.code_action_providers.clear();
4710 self.available_code_actions.take();
4711 }
4712
4713 pub fn add_code_action_provider(
4714 &mut self,
4715 provider: Rc<dyn CodeActionProvider>,
4716 window: &mut Window,
4717 cx: &mut Context<Self>,
4718 ) {
4719 if self
4720 .code_action_providers
4721 .iter()
4722 .any(|existing_provider| existing_provider.id() == provider.id())
4723 {
4724 return;
4725 }
4726
4727 self.code_action_providers.push(provider);
4728 self.refresh_code_actions(window, cx);
4729 }
4730
4731 pub fn remove_code_action_provider(
4732 &mut self,
4733 id: Arc<str>,
4734 window: &mut Window,
4735 cx: &mut Context<Self>,
4736 ) {
4737 self.code_action_providers
4738 .retain(|provider| provider.id() != id);
4739 self.refresh_code_actions(window, cx);
4740 }
4741
4742 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4743 let buffer = self.buffer.read(cx);
4744 let newest_selection = self.selections.newest_anchor().clone();
4745 if newest_selection.head().diff_base_anchor.is_some() {
4746 return None;
4747 }
4748 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4749 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4750 if start_buffer != end_buffer {
4751 return None;
4752 }
4753
4754 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4755 cx.background_executor()
4756 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4757 .await;
4758
4759 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4760 let providers = this.code_action_providers.clone();
4761 let tasks = this
4762 .code_action_providers
4763 .iter()
4764 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4765 .collect::<Vec<_>>();
4766 (providers, tasks)
4767 })?;
4768
4769 let mut actions = Vec::new();
4770 for (provider, provider_actions) in
4771 providers.into_iter().zip(future::join_all(tasks).await)
4772 {
4773 if let Some(provider_actions) = provider_actions.log_err() {
4774 actions.extend(provider_actions.into_iter().map(|action| {
4775 AvailableCodeAction {
4776 excerpt_id: newest_selection.start.excerpt_id,
4777 action,
4778 provider: provider.clone(),
4779 }
4780 }));
4781 }
4782 }
4783
4784 this.update(&mut cx, |this, cx| {
4785 this.available_code_actions = if actions.is_empty() {
4786 None
4787 } else {
4788 Some((
4789 Location {
4790 buffer: start_buffer,
4791 range: start..end,
4792 },
4793 actions.into(),
4794 ))
4795 };
4796 cx.notify();
4797 })
4798 }));
4799 None
4800 }
4801
4802 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4803 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4804 self.show_git_blame_inline = false;
4805
4806 self.show_git_blame_inline_delay_task =
4807 Some(cx.spawn_in(window, |this, mut cx| async move {
4808 cx.background_executor().timer(delay).await;
4809
4810 this.update(&mut cx, |this, cx| {
4811 this.show_git_blame_inline = true;
4812 cx.notify();
4813 })
4814 .log_err();
4815 }));
4816 }
4817 }
4818
4819 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4820 if self.pending_rename.is_some() {
4821 return None;
4822 }
4823
4824 let provider = self.semantics_provider.clone()?;
4825 let buffer = self.buffer.read(cx);
4826 let newest_selection = self.selections.newest_anchor().clone();
4827 let cursor_position = newest_selection.head();
4828 let (cursor_buffer, cursor_buffer_position) =
4829 buffer.text_anchor_for_position(cursor_position, cx)?;
4830 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4831 if cursor_buffer != tail_buffer {
4832 return None;
4833 }
4834 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4835 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4836 cx.background_executor()
4837 .timer(Duration::from_millis(debounce))
4838 .await;
4839
4840 let highlights = if let Some(highlights) = cx
4841 .update(|cx| {
4842 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4843 })
4844 .ok()
4845 .flatten()
4846 {
4847 highlights.await.log_err()
4848 } else {
4849 None
4850 };
4851
4852 if let Some(highlights) = highlights {
4853 this.update(&mut cx, |this, cx| {
4854 if this.pending_rename.is_some() {
4855 return;
4856 }
4857
4858 let buffer_id = cursor_position.buffer_id;
4859 let buffer = this.buffer.read(cx);
4860 if !buffer
4861 .text_anchor_for_position(cursor_position, cx)
4862 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4863 {
4864 return;
4865 }
4866
4867 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4868 let mut write_ranges = Vec::new();
4869 let mut read_ranges = Vec::new();
4870 for highlight in highlights {
4871 for (excerpt_id, excerpt_range) in
4872 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4873 {
4874 let start = highlight
4875 .range
4876 .start
4877 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4878 let end = highlight
4879 .range
4880 .end
4881 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4882 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4883 continue;
4884 }
4885
4886 let range = Anchor {
4887 buffer_id,
4888 excerpt_id,
4889 text_anchor: start,
4890 diff_base_anchor: None,
4891 }..Anchor {
4892 buffer_id,
4893 excerpt_id,
4894 text_anchor: end,
4895 diff_base_anchor: None,
4896 };
4897 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4898 write_ranges.push(range);
4899 } else {
4900 read_ranges.push(range);
4901 }
4902 }
4903 }
4904
4905 this.highlight_background::<DocumentHighlightRead>(
4906 &read_ranges,
4907 |theme| theme.editor_document_highlight_read_background,
4908 cx,
4909 );
4910 this.highlight_background::<DocumentHighlightWrite>(
4911 &write_ranges,
4912 |theme| theme.editor_document_highlight_write_background,
4913 cx,
4914 );
4915 cx.notify();
4916 })
4917 .log_err();
4918 }
4919 }));
4920 None
4921 }
4922
4923 pub fn refresh_selected_text_highlights(
4924 &mut self,
4925 window: &mut Window,
4926 cx: &mut Context<Editor>,
4927 ) {
4928 self.selection_highlight_task.take();
4929 if !EditorSettings::get_global(cx).selection_highlight {
4930 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4931 return;
4932 }
4933 if self.selections.count() != 1 || self.selections.line_mode {
4934 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4935 return;
4936 }
4937 let selection = self.selections.newest::<Point>(cx);
4938 if selection.is_empty() || selection.start.row != selection.end.row {
4939 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4940 return;
4941 }
4942 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4943 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4944 cx.background_executor()
4945 .timer(Duration::from_millis(debounce))
4946 .await;
4947 let Some(Some(matches_task)) = editor
4948 .update_in(&mut cx, |editor, _, cx| {
4949 if editor.selections.count() != 1 || editor.selections.line_mode {
4950 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4951 return None;
4952 }
4953 let selection = editor.selections.newest::<Point>(cx);
4954 if selection.is_empty() || selection.start.row != selection.end.row {
4955 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4956 return None;
4957 }
4958 let buffer = editor.buffer().read(cx).snapshot(cx);
4959 let query = buffer.text_for_range(selection.range()).collect::<String>();
4960 if query.trim().is_empty() {
4961 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4962 return None;
4963 }
4964 Some(cx.background_spawn(async move {
4965 let mut ranges = Vec::new();
4966 let selection_anchors = selection.range().to_anchors(&buffer);
4967 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4968 for (search_buffer, search_range, excerpt_id) in
4969 buffer.range_to_buffer_ranges(range)
4970 {
4971 ranges.extend(
4972 project::search::SearchQuery::text(
4973 query.clone(),
4974 false,
4975 false,
4976 false,
4977 Default::default(),
4978 Default::default(),
4979 None,
4980 )
4981 .unwrap()
4982 .search(search_buffer, Some(search_range.clone()))
4983 .await
4984 .into_iter()
4985 .filter_map(
4986 |match_range| {
4987 let start = search_buffer.anchor_after(
4988 search_range.start + match_range.start,
4989 );
4990 let end = search_buffer.anchor_before(
4991 search_range.start + match_range.end,
4992 );
4993 let range = Anchor::range_in_buffer(
4994 excerpt_id,
4995 search_buffer.remote_id(),
4996 start..end,
4997 );
4998 (range != selection_anchors).then_some(range)
4999 },
5000 ),
5001 );
5002 }
5003 }
5004 ranges
5005 }))
5006 })
5007 .log_err()
5008 else {
5009 return;
5010 };
5011 let matches = matches_task.await;
5012 editor
5013 .update_in(&mut cx, |editor, _, cx| {
5014 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5015 if !matches.is_empty() {
5016 editor.highlight_background::<SelectedTextHighlight>(
5017 &matches,
5018 |theme| theme.editor_document_highlight_bracket_background,
5019 cx,
5020 )
5021 }
5022 })
5023 .log_err();
5024 }));
5025 }
5026
5027 pub fn refresh_inline_completion(
5028 &mut self,
5029 debounce: bool,
5030 user_requested: bool,
5031 window: &mut Window,
5032 cx: &mut Context<Self>,
5033 ) -> Option<()> {
5034 let provider = self.edit_prediction_provider()?;
5035 let cursor = self.selections.newest_anchor().head();
5036 let (buffer, cursor_buffer_position) =
5037 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5038
5039 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5040 self.discard_inline_completion(false, cx);
5041 return None;
5042 }
5043
5044 if !user_requested
5045 && (!self.should_show_edit_predictions()
5046 || !self.is_focused(window)
5047 || buffer.read(cx).is_empty())
5048 {
5049 self.discard_inline_completion(false, cx);
5050 return None;
5051 }
5052
5053 self.update_visible_inline_completion(window, cx);
5054 provider.refresh(
5055 self.project.clone(),
5056 buffer,
5057 cursor_buffer_position,
5058 debounce,
5059 cx,
5060 );
5061 Some(())
5062 }
5063
5064 fn show_edit_predictions_in_menu(&self) -> bool {
5065 match self.edit_prediction_settings {
5066 EditPredictionSettings::Disabled => false,
5067 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5068 }
5069 }
5070
5071 pub fn edit_predictions_enabled(&self) -> bool {
5072 match self.edit_prediction_settings {
5073 EditPredictionSettings::Disabled => false,
5074 EditPredictionSettings::Enabled { .. } => true,
5075 }
5076 }
5077
5078 fn edit_prediction_requires_modifier(&self) -> bool {
5079 match self.edit_prediction_settings {
5080 EditPredictionSettings::Disabled => false,
5081 EditPredictionSettings::Enabled {
5082 preview_requires_modifier,
5083 ..
5084 } => preview_requires_modifier,
5085 }
5086 }
5087
5088 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5089 if self.edit_prediction_provider.is_none() {
5090 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5091 } else {
5092 let selection = self.selections.newest_anchor();
5093 let cursor = selection.head();
5094
5095 if let Some((buffer, cursor_buffer_position)) =
5096 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5097 {
5098 self.edit_prediction_settings =
5099 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5100 }
5101 }
5102 }
5103
5104 fn edit_prediction_settings_at_position(
5105 &self,
5106 buffer: &Entity<Buffer>,
5107 buffer_position: language::Anchor,
5108 cx: &App,
5109 ) -> EditPredictionSettings {
5110 if self.mode != EditorMode::Full
5111 || !self.show_inline_completions_override.unwrap_or(true)
5112 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5113 {
5114 return EditPredictionSettings::Disabled;
5115 }
5116
5117 let buffer = buffer.read(cx);
5118
5119 let file = buffer.file();
5120
5121 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5122 return EditPredictionSettings::Disabled;
5123 };
5124
5125 let by_provider = matches!(
5126 self.menu_inline_completions_policy,
5127 MenuInlineCompletionsPolicy::ByProvider
5128 );
5129
5130 let show_in_menu = by_provider
5131 && self
5132 .edit_prediction_provider
5133 .as_ref()
5134 .map_or(false, |provider| {
5135 provider.provider.show_completions_in_menu()
5136 });
5137
5138 let preview_requires_modifier =
5139 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5140
5141 EditPredictionSettings::Enabled {
5142 show_in_menu,
5143 preview_requires_modifier,
5144 }
5145 }
5146
5147 fn should_show_edit_predictions(&self) -> bool {
5148 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5149 }
5150
5151 pub fn edit_prediction_preview_is_active(&self) -> bool {
5152 matches!(
5153 self.edit_prediction_preview,
5154 EditPredictionPreview::Active { .. }
5155 )
5156 }
5157
5158 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5159 let cursor = self.selections.newest_anchor().head();
5160 if let Some((buffer, cursor_position)) =
5161 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5162 {
5163 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5164 } else {
5165 false
5166 }
5167 }
5168
5169 fn edit_predictions_enabled_in_buffer(
5170 &self,
5171 buffer: &Entity<Buffer>,
5172 buffer_position: language::Anchor,
5173 cx: &App,
5174 ) -> bool {
5175 maybe!({
5176 let provider = self.edit_prediction_provider()?;
5177 if !provider.is_enabled(&buffer, buffer_position, cx) {
5178 return Some(false);
5179 }
5180 let buffer = buffer.read(cx);
5181 let Some(file) = buffer.file() else {
5182 return Some(true);
5183 };
5184 let settings = all_language_settings(Some(file), cx);
5185 Some(settings.edit_predictions_enabled_for_file(file, cx))
5186 })
5187 .unwrap_or(false)
5188 }
5189
5190 fn cycle_inline_completion(
5191 &mut self,
5192 direction: Direction,
5193 window: &mut Window,
5194 cx: &mut Context<Self>,
5195 ) -> Option<()> {
5196 let provider = self.edit_prediction_provider()?;
5197 let cursor = self.selections.newest_anchor().head();
5198 let (buffer, cursor_buffer_position) =
5199 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5200 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5201 return None;
5202 }
5203
5204 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5205 self.update_visible_inline_completion(window, cx);
5206
5207 Some(())
5208 }
5209
5210 pub fn show_inline_completion(
5211 &mut self,
5212 _: &ShowEditPrediction,
5213 window: &mut Window,
5214 cx: &mut Context<Self>,
5215 ) {
5216 if !self.has_active_inline_completion() {
5217 self.refresh_inline_completion(false, true, window, cx);
5218 return;
5219 }
5220
5221 self.update_visible_inline_completion(window, cx);
5222 }
5223
5224 pub fn display_cursor_names(
5225 &mut self,
5226 _: &DisplayCursorNames,
5227 window: &mut Window,
5228 cx: &mut Context<Self>,
5229 ) {
5230 self.show_cursor_names(window, cx);
5231 }
5232
5233 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5234 self.show_cursor_names = true;
5235 cx.notify();
5236 cx.spawn_in(window, |this, mut cx| async move {
5237 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5238 this.update(&mut cx, |this, cx| {
5239 this.show_cursor_names = false;
5240 cx.notify()
5241 })
5242 .ok()
5243 })
5244 .detach();
5245 }
5246
5247 pub fn next_edit_prediction(
5248 &mut self,
5249 _: &NextEditPrediction,
5250 window: &mut Window,
5251 cx: &mut Context<Self>,
5252 ) {
5253 if self.has_active_inline_completion() {
5254 self.cycle_inline_completion(Direction::Next, window, cx);
5255 } else {
5256 let is_copilot_disabled = self
5257 .refresh_inline_completion(false, true, window, cx)
5258 .is_none();
5259 if is_copilot_disabled {
5260 cx.propagate();
5261 }
5262 }
5263 }
5264
5265 pub fn previous_edit_prediction(
5266 &mut self,
5267 _: &PreviousEditPrediction,
5268 window: &mut Window,
5269 cx: &mut Context<Self>,
5270 ) {
5271 if self.has_active_inline_completion() {
5272 self.cycle_inline_completion(Direction::Prev, window, cx);
5273 } else {
5274 let is_copilot_disabled = self
5275 .refresh_inline_completion(false, true, window, cx)
5276 .is_none();
5277 if is_copilot_disabled {
5278 cx.propagate();
5279 }
5280 }
5281 }
5282
5283 pub fn accept_edit_prediction(
5284 &mut self,
5285 _: &AcceptEditPrediction,
5286 window: &mut Window,
5287 cx: &mut Context<Self>,
5288 ) {
5289 if self.show_edit_predictions_in_menu() {
5290 self.hide_context_menu(window, cx);
5291 }
5292
5293 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5294 return;
5295 };
5296
5297 self.report_inline_completion_event(
5298 active_inline_completion.completion_id.clone(),
5299 true,
5300 cx,
5301 );
5302
5303 match &active_inline_completion.completion {
5304 InlineCompletion::Move { target, .. } => {
5305 let target = *target;
5306
5307 if let Some(position_map) = &self.last_position_map {
5308 if position_map
5309 .visible_row_range
5310 .contains(&target.to_display_point(&position_map.snapshot).row())
5311 || !self.edit_prediction_requires_modifier()
5312 {
5313 self.unfold_ranges(&[target..target], true, false, cx);
5314 // Note that this is also done in vim's handler of the Tab action.
5315 self.change_selections(
5316 Some(Autoscroll::newest()),
5317 window,
5318 cx,
5319 |selections| {
5320 selections.select_anchor_ranges([target..target]);
5321 },
5322 );
5323 self.clear_row_highlights::<EditPredictionPreview>();
5324
5325 self.edit_prediction_preview
5326 .set_previous_scroll_position(None);
5327 } else {
5328 self.edit_prediction_preview
5329 .set_previous_scroll_position(Some(
5330 position_map.snapshot.scroll_anchor,
5331 ));
5332
5333 self.highlight_rows::<EditPredictionPreview>(
5334 target..target,
5335 cx.theme().colors().editor_highlighted_line_background,
5336 true,
5337 cx,
5338 );
5339 self.request_autoscroll(Autoscroll::fit(), cx);
5340 }
5341 }
5342 }
5343 InlineCompletion::Edit { edits, .. } => {
5344 if let Some(provider) = self.edit_prediction_provider() {
5345 provider.accept(cx);
5346 }
5347
5348 let snapshot = self.buffer.read(cx).snapshot(cx);
5349 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5350
5351 self.buffer.update(cx, |buffer, cx| {
5352 buffer.edit(edits.iter().cloned(), None, cx)
5353 });
5354
5355 self.change_selections(None, window, cx, |s| {
5356 s.select_anchor_ranges([last_edit_end..last_edit_end])
5357 });
5358
5359 self.update_visible_inline_completion(window, cx);
5360 if self.active_inline_completion.is_none() {
5361 self.refresh_inline_completion(true, true, window, cx);
5362 }
5363
5364 cx.notify();
5365 }
5366 }
5367
5368 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5369 }
5370
5371 pub fn accept_partial_inline_completion(
5372 &mut self,
5373 _: &AcceptPartialEditPrediction,
5374 window: &mut Window,
5375 cx: &mut Context<Self>,
5376 ) {
5377 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5378 return;
5379 };
5380 if self.selections.count() != 1 {
5381 return;
5382 }
5383
5384 self.report_inline_completion_event(
5385 active_inline_completion.completion_id.clone(),
5386 true,
5387 cx,
5388 );
5389
5390 match &active_inline_completion.completion {
5391 InlineCompletion::Move { target, .. } => {
5392 let target = *target;
5393 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5394 selections.select_anchor_ranges([target..target]);
5395 });
5396 }
5397 InlineCompletion::Edit { edits, .. } => {
5398 // Find an insertion that starts at the cursor position.
5399 let snapshot = self.buffer.read(cx).snapshot(cx);
5400 let cursor_offset = self.selections.newest::<usize>(cx).head();
5401 let insertion = edits.iter().find_map(|(range, text)| {
5402 let range = range.to_offset(&snapshot);
5403 if range.is_empty() && range.start == cursor_offset {
5404 Some(text)
5405 } else {
5406 None
5407 }
5408 });
5409
5410 if let Some(text) = insertion {
5411 let mut partial_completion = text
5412 .chars()
5413 .by_ref()
5414 .take_while(|c| c.is_alphabetic())
5415 .collect::<String>();
5416 if partial_completion.is_empty() {
5417 partial_completion = text
5418 .chars()
5419 .by_ref()
5420 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5421 .collect::<String>();
5422 }
5423
5424 cx.emit(EditorEvent::InputHandled {
5425 utf16_range_to_replace: None,
5426 text: partial_completion.clone().into(),
5427 });
5428
5429 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5430
5431 self.refresh_inline_completion(true, true, window, cx);
5432 cx.notify();
5433 } else {
5434 self.accept_edit_prediction(&Default::default(), window, cx);
5435 }
5436 }
5437 }
5438 }
5439
5440 fn discard_inline_completion(
5441 &mut self,
5442 should_report_inline_completion_event: bool,
5443 cx: &mut Context<Self>,
5444 ) -> bool {
5445 if should_report_inline_completion_event {
5446 let completion_id = self
5447 .active_inline_completion
5448 .as_ref()
5449 .and_then(|active_completion| active_completion.completion_id.clone());
5450
5451 self.report_inline_completion_event(completion_id, false, cx);
5452 }
5453
5454 if let Some(provider) = self.edit_prediction_provider() {
5455 provider.discard(cx);
5456 }
5457
5458 self.take_active_inline_completion(cx)
5459 }
5460
5461 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5462 let Some(provider) = self.edit_prediction_provider() else {
5463 return;
5464 };
5465
5466 let Some((_, buffer, _)) = self
5467 .buffer
5468 .read(cx)
5469 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5470 else {
5471 return;
5472 };
5473
5474 let extension = buffer
5475 .read(cx)
5476 .file()
5477 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5478
5479 let event_type = match accepted {
5480 true => "Edit Prediction Accepted",
5481 false => "Edit Prediction Discarded",
5482 };
5483 telemetry::event!(
5484 event_type,
5485 provider = provider.name(),
5486 prediction_id = id,
5487 suggestion_accepted = accepted,
5488 file_extension = extension,
5489 );
5490 }
5491
5492 pub fn has_active_inline_completion(&self) -> bool {
5493 self.active_inline_completion.is_some()
5494 }
5495
5496 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5497 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5498 return false;
5499 };
5500
5501 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5502 self.clear_highlights::<InlineCompletionHighlight>(cx);
5503 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5504 true
5505 }
5506
5507 /// Returns true when we're displaying the edit prediction popover below the cursor
5508 /// like we are not previewing and the LSP autocomplete menu is visible
5509 /// or we are in `when_holding_modifier` mode.
5510 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5511 if self.edit_prediction_preview_is_active()
5512 || !self.show_edit_predictions_in_menu()
5513 || !self.edit_predictions_enabled()
5514 {
5515 return false;
5516 }
5517
5518 if self.has_visible_completions_menu() {
5519 return true;
5520 }
5521
5522 has_completion && self.edit_prediction_requires_modifier()
5523 }
5524
5525 fn handle_modifiers_changed(
5526 &mut self,
5527 modifiers: Modifiers,
5528 position_map: &PositionMap,
5529 window: &mut Window,
5530 cx: &mut Context<Self>,
5531 ) {
5532 if self.show_edit_predictions_in_menu() {
5533 self.update_edit_prediction_preview(&modifiers, window, cx);
5534 }
5535
5536 self.update_selection_mode(&modifiers, position_map, window, cx);
5537
5538 let mouse_position = window.mouse_position();
5539 if !position_map.text_hitbox.is_hovered(window) {
5540 return;
5541 }
5542
5543 self.update_hovered_link(
5544 position_map.point_for_position(mouse_position),
5545 &position_map.snapshot,
5546 modifiers,
5547 window,
5548 cx,
5549 )
5550 }
5551
5552 fn update_selection_mode(
5553 &mut self,
5554 modifiers: &Modifiers,
5555 position_map: &PositionMap,
5556 window: &mut Window,
5557 cx: &mut Context<Self>,
5558 ) {
5559 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5560 return;
5561 }
5562
5563 let mouse_position = window.mouse_position();
5564 let point_for_position = position_map.point_for_position(mouse_position);
5565 let position = point_for_position.previous_valid;
5566
5567 self.select(
5568 SelectPhase::BeginColumnar {
5569 position,
5570 reset: false,
5571 goal_column: point_for_position.exact_unclipped.column(),
5572 },
5573 window,
5574 cx,
5575 );
5576 }
5577
5578 fn update_edit_prediction_preview(
5579 &mut self,
5580 modifiers: &Modifiers,
5581 window: &mut Window,
5582 cx: &mut Context<Self>,
5583 ) {
5584 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5585 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5586 return;
5587 };
5588
5589 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5590 if matches!(
5591 self.edit_prediction_preview,
5592 EditPredictionPreview::Inactive { .. }
5593 ) {
5594 self.edit_prediction_preview = EditPredictionPreview::Active {
5595 previous_scroll_position: None,
5596 since: Instant::now(),
5597 };
5598
5599 self.update_visible_inline_completion(window, cx);
5600 cx.notify();
5601 }
5602 } else if let EditPredictionPreview::Active {
5603 previous_scroll_position,
5604 since,
5605 } = self.edit_prediction_preview
5606 {
5607 if let (Some(previous_scroll_position), Some(position_map)) =
5608 (previous_scroll_position, self.last_position_map.as_ref())
5609 {
5610 self.set_scroll_position(
5611 previous_scroll_position
5612 .scroll_position(&position_map.snapshot.display_snapshot),
5613 window,
5614 cx,
5615 );
5616 }
5617
5618 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5619 released_too_fast: since.elapsed() < Duration::from_millis(200),
5620 };
5621 self.clear_row_highlights::<EditPredictionPreview>();
5622 self.update_visible_inline_completion(window, cx);
5623 cx.notify();
5624 }
5625 }
5626
5627 fn update_visible_inline_completion(
5628 &mut self,
5629 _window: &mut Window,
5630 cx: &mut Context<Self>,
5631 ) -> Option<()> {
5632 let selection = self.selections.newest_anchor();
5633 let cursor = selection.head();
5634 let multibuffer = self.buffer.read(cx).snapshot(cx);
5635 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5636 let excerpt_id = cursor.excerpt_id;
5637
5638 let show_in_menu = self.show_edit_predictions_in_menu();
5639 let completions_menu_has_precedence = !show_in_menu
5640 && (self.context_menu.borrow().is_some()
5641 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5642
5643 if completions_menu_has_precedence
5644 || !offset_selection.is_empty()
5645 || self
5646 .active_inline_completion
5647 .as_ref()
5648 .map_or(false, |completion| {
5649 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5650 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5651 !invalidation_range.contains(&offset_selection.head())
5652 })
5653 {
5654 self.discard_inline_completion(false, cx);
5655 return None;
5656 }
5657
5658 self.take_active_inline_completion(cx);
5659 let Some(provider) = self.edit_prediction_provider() else {
5660 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5661 return None;
5662 };
5663
5664 let (buffer, cursor_buffer_position) =
5665 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5666
5667 self.edit_prediction_settings =
5668 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5669
5670 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5671
5672 if self.edit_prediction_indent_conflict {
5673 let cursor_point = cursor.to_point(&multibuffer);
5674
5675 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5676
5677 if let Some((_, indent)) = indents.iter().next() {
5678 if indent.len == cursor_point.column {
5679 self.edit_prediction_indent_conflict = false;
5680 }
5681 }
5682 }
5683
5684 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5685 let edits = inline_completion
5686 .edits
5687 .into_iter()
5688 .flat_map(|(range, new_text)| {
5689 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5690 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5691 Some((start..end, new_text))
5692 })
5693 .collect::<Vec<_>>();
5694 if edits.is_empty() {
5695 return None;
5696 }
5697
5698 let first_edit_start = edits.first().unwrap().0.start;
5699 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5700 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5701
5702 let last_edit_end = edits.last().unwrap().0.end;
5703 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5704 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5705
5706 let cursor_row = cursor.to_point(&multibuffer).row;
5707
5708 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5709
5710 let mut inlay_ids = Vec::new();
5711 let invalidation_row_range;
5712 let move_invalidation_row_range = if cursor_row < edit_start_row {
5713 Some(cursor_row..edit_end_row)
5714 } else if cursor_row > edit_end_row {
5715 Some(edit_start_row..cursor_row)
5716 } else {
5717 None
5718 };
5719 let is_move =
5720 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5721 let completion = if is_move {
5722 invalidation_row_range =
5723 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5724 let target = first_edit_start;
5725 InlineCompletion::Move { target, snapshot }
5726 } else {
5727 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5728 && !self.inline_completions_hidden_for_vim_mode;
5729
5730 if show_completions_in_buffer {
5731 if edits
5732 .iter()
5733 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5734 {
5735 let mut inlays = Vec::new();
5736 for (range, new_text) in &edits {
5737 let inlay = Inlay::inline_completion(
5738 post_inc(&mut self.next_inlay_id),
5739 range.start,
5740 new_text.as_str(),
5741 );
5742 inlay_ids.push(inlay.id);
5743 inlays.push(inlay);
5744 }
5745
5746 self.splice_inlays(&[], inlays, cx);
5747 } else {
5748 let background_color = cx.theme().status().deleted_background;
5749 self.highlight_text::<InlineCompletionHighlight>(
5750 edits.iter().map(|(range, _)| range.clone()).collect(),
5751 HighlightStyle {
5752 background_color: Some(background_color),
5753 ..Default::default()
5754 },
5755 cx,
5756 );
5757 }
5758 }
5759
5760 invalidation_row_range = edit_start_row..edit_end_row;
5761
5762 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5763 if provider.show_tab_accept_marker() {
5764 EditDisplayMode::TabAccept
5765 } else {
5766 EditDisplayMode::Inline
5767 }
5768 } else {
5769 EditDisplayMode::DiffPopover
5770 };
5771
5772 InlineCompletion::Edit {
5773 edits,
5774 edit_preview: inline_completion.edit_preview,
5775 display_mode,
5776 snapshot,
5777 }
5778 };
5779
5780 let invalidation_range = multibuffer
5781 .anchor_before(Point::new(invalidation_row_range.start, 0))
5782 ..multibuffer.anchor_after(Point::new(
5783 invalidation_row_range.end,
5784 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5785 ));
5786
5787 self.stale_inline_completion_in_menu = None;
5788 self.active_inline_completion = Some(InlineCompletionState {
5789 inlay_ids,
5790 completion,
5791 completion_id: inline_completion.id,
5792 invalidation_range,
5793 });
5794
5795 cx.notify();
5796
5797 Some(())
5798 }
5799
5800 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5801 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5802 }
5803
5804 fn render_code_actions_indicator(
5805 &self,
5806 _style: &EditorStyle,
5807 row: DisplayRow,
5808 is_active: bool,
5809 cx: &mut Context<Self>,
5810 ) -> Option<IconButton> {
5811 if self.available_code_actions.is_some() {
5812 Some(
5813 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5814 .shape(ui::IconButtonShape::Square)
5815 .icon_size(IconSize::XSmall)
5816 .icon_color(Color::Muted)
5817 .toggle_state(is_active)
5818 .tooltip({
5819 let focus_handle = self.focus_handle.clone();
5820 move |window, cx| {
5821 Tooltip::for_action_in(
5822 "Toggle Code Actions",
5823 &ToggleCodeActions {
5824 deployed_from_indicator: None,
5825 },
5826 &focus_handle,
5827 window,
5828 cx,
5829 )
5830 }
5831 })
5832 .on_click(cx.listener(move |editor, _e, window, cx| {
5833 window.focus(&editor.focus_handle(cx));
5834 editor.toggle_code_actions(
5835 &ToggleCodeActions {
5836 deployed_from_indicator: Some(row),
5837 },
5838 window,
5839 cx,
5840 );
5841 })),
5842 )
5843 } else {
5844 None
5845 }
5846 }
5847
5848 fn clear_tasks(&mut self) {
5849 self.tasks.clear()
5850 }
5851
5852 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5853 if self.tasks.insert(key, value).is_some() {
5854 // This case should hopefully be rare, but just in case...
5855 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5856 }
5857 }
5858
5859 fn build_tasks_context(
5860 project: &Entity<Project>,
5861 buffer: &Entity<Buffer>,
5862 buffer_row: u32,
5863 tasks: &Arc<RunnableTasks>,
5864 cx: &mut Context<Self>,
5865 ) -> Task<Option<task::TaskContext>> {
5866 let position = Point::new(buffer_row, tasks.column);
5867 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5868 let location = Location {
5869 buffer: buffer.clone(),
5870 range: range_start..range_start,
5871 };
5872 // Fill in the environmental variables from the tree-sitter captures
5873 let mut captured_task_variables = TaskVariables::default();
5874 for (capture_name, value) in tasks.extra_variables.clone() {
5875 captured_task_variables.insert(
5876 task::VariableName::Custom(capture_name.into()),
5877 value.clone(),
5878 );
5879 }
5880 project.update(cx, |project, cx| {
5881 project.task_store().update(cx, |task_store, cx| {
5882 task_store.task_context_for_location(captured_task_variables, location, cx)
5883 })
5884 })
5885 }
5886
5887 pub fn spawn_nearest_task(
5888 &mut self,
5889 action: &SpawnNearestTask,
5890 window: &mut Window,
5891 cx: &mut Context<Self>,
5892 ) {
5893 let Some((workspace, _)) = self.workspace.clone() else {
5894 return;
5895 };
5896 let Some(project) = self.project.clone() else {
5897 return;
5898 };
5899
5900 // Try to find a closest, enclosing node using tree-sitter that has a
5901 // task
5902 let Some((buffer, buffer_row, tasks)) = self
5903 .find_enclosing_node_task(cx)
5904 // Or find the task that's closest in row-distance.
5905 .or_else(|| self.find_closest_task(cx))
5906 else {
5907 return;
5908 };
5909
5910 let reveal_strategy = action.reveal;
5911 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5912 cx.spawn_in(window, |_, mut cx| async move {
5913 let context = task_context.await?;
5914 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5915
5916 let resolved = resolved_task.resolved.as_mut()?;
5917 resolved.reveal = reveal_strategy;
5918
5919 workspace
5920 .update(&mut cx, |workspace, cx| {
5921 workspace::tasks::schedule_resolved_task(
5922 workspace,
5923 task_source_kind,
5924 resolved_task,
5925 false,
5926 cx,
5927 );
5928 })
5929 .ok()
5930 })
5931 .detach();
5932 }
5933
5934 fn find_closest_task(
5935 &mut self,
5936 cx: &mut Context<Self>,
5937 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5938 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5939
5940 let ((buffer_id, row), tasks) = self
5941 .tasks
5942 .iter()
5943 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5944
5945 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5946 let tasks = Arc::new(tasks.to_owned());
5947 Some((buffer, *row, tasks))
5948 }
5949
5950 fn find_enclosing_node_task(
5951 &mut self,
5952 cx: &mut Context<Self>,
5953 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5954 let snapshot = self.buffer.read(cx).snapshot(cx);
5955 let offset = self.selections.newest::<usize>(cx).head();
5956 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5957 let buffer_id = excerpt.buffer().remote_id();
5958
5959 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5960 let mut cursor = layer.node().walk();
5961
5962 while cursor.goto_first_child_for_byte(offset).is_some() {
5963 if cursor.node().end_byte() == offset {
5964 cursor.goto_next_sibling();
5965 }
5966 }
5967
5968 // Ascend to the smallest ancestor that contains the range and has a task.
5969 loop {
5970 let node = cursor.node();
5971 let node_range = node.byte_range();
5972 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5973
5974 // Check if this node contains our offset
5975 if node_range.start <= offset && node_range.end >= offset {
5976 // If it contains offset, check for task
5977 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5978 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5979 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5980 }
5981 }
5982
5983 if !cursor.goto_parent() {
5984 break;
5985 }
5986 }
5987 None
5988 }
5989
5990 fn render_run_indicator(
5991 &self,
5992 _style: &EditorStyle,
5993 is_active: bool,
5994 row: DisplayRow,
5995 cx: &mut Context<Self>,
5996 ) -> IconButton {
5997 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5998 .shape(ui::IconButtonShape::Square)
5999 .icon_size(IconSize::XSmall)
6000 .icon_color(Color::Muted)
6001 .toggle_state(is_active)
6002 .on_click(cx.listener(move |editor, _e, window, cx| {
6003 window.focus(&editor.focus_handle(cx));
6004 editor.toggle_code_actions(
6005 &ToggleCodeActions {
6006 deployed_from_indicator: Some(row),
6007 },
6008 window,
6009 cx,
6010 );
6011 }))
6012 }
6013
6014 pub fn context_menu_visible(&self) -> bool {
6015 !self.edit_prediction_preview_is_active()
6016 && self
6017 .context_menu
6018 .borrow()
6019 .as_ref()
6020 .map_or(false, |menu| menu.visible())
6021 }
6022
6023 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6024 self.context_menu
6025 .borrow()
6026 .as_ref()
6027 .map(|menu| menu.origin())
6028 }
6029
6030 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6031 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6032
6033 fn render_edit_prediction_popover(
6034 &mut self,
6035 text_bounds: &Bounds<Pixels>,
6036 content_origin: gpui::Point<Pixels>,
6037 editor_snapshot: &EditorSnapshot,
6038 visible_row_range: Range<DisplayRow>,
6039 scroll_top: f32,
6040 scroll_bottom: f32,
6041 line_layouts: &[LineWithInvisibles],
6042 line_height: Pixels,
6043 scroll_pixel_position: gpui::Point<Pixels>,
6044 newest_selection_head: Option<DisplayPoint>,
6045 editor_width: Pixels,
6046 style: &EditorStyle,
6047 window: &mut Window,
6048 cx: &mut App,
6049 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6050 let active_inline_completion = self.active_inline_completion.as_ref()?;
6051
6052 if self.edit_prediction_visible_in_cursor_popover(true) {
6053 return None;
6054 }
6055
6056 match &active_inline_completion.completion {
6057 InlineCompletion::Move { target, .. } => {
6058 let target_display_point = target.to_display_point(editor_snapshot);
6059
6060 if self.edit_prediction_requires_modifier() {
6061 if !self.edit_prediction_preview_is_active() {
6062 return None;
6063 }
6064
6065 self.render_edit_prediction_modifier_jump_popover(
6066 text_bounds,
6067 content_origin,
6068 visible_row_range,
6069 line_layouts,
6070 line_height,
6071 scroll_pixel_position,
6072 newest_selection_head,
6073 target_display_point,
6074 window,
6075 cx,
6076 )
6077 } else {
6078 self.render_edit_prediction_eager_jump_popover(
6079 text_bounds,
6080 content_origin,
6081 editor_snapshot,
6082 visible_row_range,
6083 scroll_top,
6084 scroll_bottom,
6085 line_height,
6086 scroll_pixel_position,
6087 target_display_point,
6088 editor_width,
6089 window,
6090 cx,
6091 )
6092 }
6093 }
6094 InlineCompletion::Edit {
6095 display_mode: EditDisplayMode::Inline,
6096 ..
6097 } => None,
6098 InlineCompletion::Edit {
6099 display_mode: EditDisplayMode::TabAccept,
6100 edits,
6101 ..
6102 } => {
6103 let range = &edits.first()?.0;
6104 let target_display_point = range.end.to_display_point(editor_snapshot);
6105
6106 self.render_edit_prediction_end_of_line_popover(
6107 "Accept",
6108 editor_snapshot,
6109 visible_row_range,
6110 target_display_point,
6111 line_height,
6112 scroll_pixel_position,
6113 content_origin,
6114 editor_width,
6115 window,
6116 cx,
6117 )
6118 }
6119 InlineCompletion::Edit {
6120 edits,
6121 edit_preview,
6122 display_mode: EditDisplayMode::DiffPopover,
6123 snapshot,
6124 } => self.render_edit_prediction_diff_popover(
6125 text_bounds,
6126 content_origin,
6127 editor_snapshot,
6128 visible_row_range,
6129 line_layouts,
6130 line_height,
6131 scroll_pixel_position,
6132 newest_selection_head,
6133 editor_width,
6134 style,
6135 edits,
6136 edit_preview,
6137 snapshot,
6138 window,
6139 cx,
6140 ),
6141 }
6142 }
6143
6144 fn render_edit_prediction_modifier_jump_popover(
6145 &mut self,
6146 text_bounds: &Bounds<Pixels>,
6147 content_origin: gpui::Point<Pixels>,
6148 visible_row_range: Range<DisplayRow>,
6149 line_layouts: &[LineWithInvisibles],
6150 line_height: Pixels,
6151 scroll_pixel_position: gpui::Point<Pixels>,
6152 newest_selection_head: Option<DisplayPoint>,
6153 target_display_point: DisplayPoint,
6154 window: &mut Window,
6155 cx: &mut App,
6156 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6157 let scrolled_content_origin =
6158 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6159
6160 const SCROLL_PADDING_Y: Pixels = px(12.);
6161
6162 if target_display_point.row() < visible_row_range.start {
6163 return self.render_edit_prediction_scroll_popover(
6164 |_| SCROLL_PADDING_Y,
6165 IconName::ArrowUp,
6166 visible_row_range,
6167 line_layouts,
6168 newest_selection_head,
6169 scrolled_content_origin,
6170 window,
6171 cx,
6172 );
6173 } else if target_display_point.row() >= visible_row_range.end {
6174 return self.render_edit_prediction_scroll_popover(
6175 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6176 IconName::ArrowDown,
6177 visible_row_range,
6178 line_layouts,
6179 newest_selection_head,
6180 scrolled_content_origin,
6181 window,
6182 cx,
6183 );
6184 }
6185
6186 const POLE_WIDTH: Pixels = px(2.);
6187
6188 let line_layout =
6189 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6190 let target_column = target_display_point.column() as usize;
6191
6192 let target_x = line_layout.x_for_index(target_column);
6193 let target_y =
6194 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6195
6196 let flag_on_right = target_x < text_bounds.size.width / 2.;
6197
6198 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6199 border_color.l += 0.001;
6200
6201 let mut element = v_flex()
6202 .items_end()
6203 .when(flag_on_right, |el| el.items_start())
6204 .child(if flag_on_right {
6205 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6206 .rounded_bl(px(0.))
6207 .rounded_tl(px(0.))
6208 .border_l_2()
6209 .border_color(border_color)
6210 } else {
6211 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6212 .rounded_br(px(0.))
6213 .rounded_tr(px(0.))
6214 .border_r_2()
6215 .border_color(border_color)
6216 })
6217 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6218 .into_any();
6219
6220 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6221
6222 let mut origin = scrolled_content_origin + point(target_x, target_y)
6223 - point(
6224 if flag_on_right {
6225 POLE_WIDTH
6226 } else {
6227 size.width - POLE_WIDTH
6228 },
6229 size.height - line_height,
6230 );
6231
6232 origin.x = origin.x.max(content_origin.x);
6233
6234 element.prepaint_at(origin, window, cx);
6235
6236 Some((element, origin))
6237 }
6238
6239 fn render_edit_prediction_scroll_popover(
6240 &mut self,
6241 to_y: impl Fn(Size<Pixels>) -> Pixels,
6242 scroll_icon: IconName,
6243 visible_row_range: Range<DisplayRow>,
6244 line_layouts: &[LineWithInvisibles],
6245 newest_selection_head: Option<DisplayPoint>,
6246 scrolled_content_origin: gpui::Point<Pixels>,
6247 window: &mut Window,
6248 cx: &mut App,
6249 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6250 let mut element = self
6251 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6252 .into_any();
6253
6254 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6255
6256 let cursor = newest_selection_head?;
6257 let cursor_row_layout =
6258 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6259 let cursor_column = cursor.column() as usize;
6260
6261 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6262
6263 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6264
6265 element.prepaint_at(origin, window, cx);
6266 Some((element, origin))
6267 }
6268
6269 fn render_edit_prediction_eager_jump_popover(
6270 &mut self,
6271 text_bounds: &Bounds<Pixels>,
6272 content_origin: gpui::Point<Pixels>,
6273 editor_snapshot: &EditorSnapshot,
6274 visible_row_range: Range<DisplayRow>,
6275 scroll_top: f32,
6276 scroll_bottom: f32,
6277 line_height: Pixels,
6278 scroll_pixel_position: gpui::Point<Pixels>,
6279 target_display_point: DisplayPoint,
6280 editor_width: Pixels,
6281 window: &mut Window,
6282 cx: &mut App,
6283 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6284 if target_display_point.row().as_f32() < scroll_top {
6285 let mut element = self
6286 .render_edit_prediction_line_popover(
6287 "Jump to Edit",
6288 Some(IconName::ArrowUp),
6289 window,
6290 cx,
6291 )?
6292 .into_any();
6293
6294 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6295 let offset = point(
6296 (text_bounds.size.width - size.width) / 2.,
6297 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6298 );
6299
6300 let origin = text_bounds.origin + offset;
6301 element.prepaint_at(origin, window, cx);
6302 Some((element, origin))
6303 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6304 let mut element = self
6305 .render_edit_prediction_line_popover(
6306 "Jump to Edit",
6307 Some(IconName::ArrowDown),
6308 window,
6309 cx,
6310 )?
6311 .into_any();
6312
6313 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6314 let offset = point(
6315 (text_bounds.size.width - size.width) / 2.,
6316 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6317 );
6318
6319 let origin = text_bounds.origin + offset;
6320 element.prepaint_at(origin, window, cx);
6321 Some((element, origin))
6322 } else {
6323 self.render_edit_prediction_end_of_line_popover(
6324 "Jump to Edit",
6325 editor_snapshot,
6326 visible_row_range,
6327 target_display_point,
6328 line_height,
6329 scroll_pixel_position,
6330 content_origin,
6331 editor_width,
6332 window,
6333 cx,
6334 )
6335 }
6336 }
6337
6338 fn render_edit_prediction_end_of_line_popover(
6339 self: &mut Editor,
6340 label: &'static str,
6341 editor_snapshot: &EditorSnapshot,
6342 visible_row_range: Range<DisplayRow>,
6343 target_display_point: DisplayPoint,
6344 line_height: Pixels,
6345 scroll_pixel_position: gpui::Point<Pixels>,
6346 content_origin: gpui::Point<Pixels>,
6347 editor_width: Pixels,
6348 window: &mut Window,
6349 cx: &mut App,
6350 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6351 let target_line_end = DisplayPoint::new(
6352 target_display_point.row(),
6353 editor_snapshot.line_len(target_display_point.row()),
6354 );
6355
6356 let mut element = self
6357 .render_edit_prediction_line_popover(label, None, window, cx)?
6358 .into_any();
6359
6360 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6361
6362 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6363
6364 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6365 let mut origin = start_point
6366 + line_origin
6367 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6368 origin.x = origin.x.max(content_origin.x);
6369
6370 let max_x = content_origin.x + editor_width - size.width;
6371
6372 if origin.x > max_x {
6373 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6374
6375 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6376 origin.y += offset;
6377 IconName::ArrowUp
6378 } else {
6379 origin.y -= offset;
6380 IconName::ArrowDown
6381 };
6382
6383 element = self
6384 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6385 .into_any();
6386
6387 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6388
6389 origin.x = content_origin.x + editor_width - size.width - px(2.);
6390 }
6391
6392 element.prepaint_at(origin, window, cx);
6393 Some((element, origin))
6394 }
6395
6396 fn render_edit_prediction_diff_popover(
6397 self: &Editor,
6398 text_bounds: &Bounds<Pixels>,
6399 content_origin: gpui::Point<Pixels>,
6400 editor_snapshot: &EditorSnapshot,
6401 visible_row_range: Range<DisplayRow>,
6402 line_layouts: &[LineWithInvisibles],
6403 line_height: Pixels,
6404 scroll_pixel_position: gpui::Point<Pixels>,
6405 newest_selection_head: Option<DisplayPoint>,
6406 editor_width: Pixels,
6407 style: &EditorStyle,
6408 edits: &Vec<(Range<Anchor>, String)>,
6409 edit_preview: &Option<language::EditPreview>,
6410 snapshot: &language::BufferSnapshot,
6411 window: &mut Window,
6412 cx: &mut App,
6413 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6414 let edit_start = edits
6415 .first()
6416 .unwrap()
6417 .0
6418 .start
6419 .to_display_point(editor_snapshot);
6420 let edit_end = edits
6421 .last()
6422 .unwrap()
6423 .0
6424 .end
6425 .to_display_point(editor_snapshot);
6426
6427 let is_visible = visible_row_range.contains(&edit_start.row())
6428 || visible_row_range.contains(&edit_end.row());
6429 if !is_visible {
6430 return None;
6431 }
6432
6433 let highlighted_edits =
6434 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6435
6436 let styled_text = highlighted_edits.to_styled_text(&style.text);
6437 let line_count = highlighted_edits.text.lines().count();
6438
6439 const BORDER_WIDTH: Pixels = px(1.);
6440
6441 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6442 let has_keybind = keybind.is_some();
6443
6444 let mut element = h_flex()
6445 .items_start()
6446 .child(
6447 h_flex()
6448 .bg(cx.theme().colors().editor_background)
6449 .border(BORDER_WIDTH)
6450 .shadow_sm()
6451 .border_color(cx.theme().colors().border)
6452 .rounded_l_lg()
6453 .when(line_count > 1, |el| el.rounded_br_lg())
6454 .pr_1()
6455 .child(styled_text),
6456 )
6457 .child(
6458 h_flex()
6459 .h(line_height + BORDER_WIDTH * px(2.))
6460 .px_1p5()
6461 .gap_1()
6462 // Workaround: For some reason, there's a gap if we don't do this
6463 .ml(-BORDER_WIDTH)
6464 .shadow(smallvec![gpui::BoxShadow {
6465 color: gpui::black().opacity(0.05),
6466 offset: point(px(1.), px(1.)),
6467 blur_radius: px(2.),
6468 spread_radius: px(0.),
6469 }])
6470 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6471 .border(BORDER_WIDTH)
6472 .border_color(cx.theme().colors().border)
6473 .rounded_r_lg()
6474 .id("edit_prediction_diff_popover_keybind")
6475 .when(!has_keybind, |el| {
6476 let status_colors = cx.theme().status();
6477
6478 el.bg(status_colors.error_background)
6479 .border_color(status_colors.error.opacity(0.6))
6480 .child(Icon::new(IconName::Info).color(Color::Error))
6481 .cursor_default()
6482 .hoverable_tooltip(move |_window, cx| {
6483 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6484 })
6485 })
6486 .children(keybind),
6487 )
6488 .into_any();
6489
6490 let longest_row =
6491 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6492 let longest_line_width = if visible_row_range.contains(&longest_row) {
6493 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6494 } else {
6495 layout_line(
6496 longest_row,
6497 editor_snapshot,
6498 style,
6499 editor_width,
6500 |_| false,
6501 window,
6502 cx,
6503 )
6504 .width
6505 };
6506
6507 let viewport_bounds =
6508 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6509 right: -EditorElement::SCROLLBAR_WIDTH,
6510 ..Default::default()
6511 });
6512
6513 let x_after_longest =
6514 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6515 - scroll_pixel_position.x;
6516
6517 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6518
6519 // Fully visible if it can be displayed within the window (allow overlapping other
6520 // panes). However, this is only allowed if the popover starts within text_bounds.
6521 let can_position_to_the_right = x_after_longest < text_bounds.right()
6522 && x_after_longest + element_bounds.width < viewport_bounds.right();
6523
6524 let mut origin = if can_position_to_the_right {
6525 point(
6526 x_after_longest,
6527 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6528 - scroll_pixel_position.y,
6529 )
6530 } else {
6531 let cursor_row = newest_selection_head.map(|head| head.row());
6532 let above_edit = edit_start
6533 .row()
6534 .0
6535 .checked_sub(line_count as u32)
6536 .map(DisplayRow);
6537 let below_edit = Some(edit_end.row() + 1);
6538 let above_cursor =
6539 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6540 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6541
6542 // Place the edit popover adjacent to the edit if there is a location
6543 // available that is onscreen and does not obscure the cursor. Otherwise,
6544 // place it adjacent to the cursor.
6545 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6546 .into_iter()
6547 .flatten()
6548 .find(|&start_row| {
6549 let end_row = start_row + line_count as u32;
6550 visible_row_range.contains(&start_row)
6551 && visible_row_range.contains(&end_row)
6552 && cursor_row.map_or(true, |cursor_row| {
6553 !((start_row..end_row).contains(&cursor_row))
6554 })
6555 })?;
6556
6557 content_origin
6558 + point(
6559 -scroll_pixel_position.x,
6560 row_target.as_f32() * line_height - scroll_pixel_position.y,
6561 )
6562 };
6563
6564 origin.x -= BORDER_WIDTH;
6565
6566 window.defer_draw(element, origin, 1);
6567
6568 // Do not return an element, since it will already be drawn due to defer_draw.
6569 None
6570 }
6571
6572 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6573 px(30.)
6574 }
6575
6576 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6577 if self.read_only(cx) {
6578 cx.theme().players().read_only()
6579 } else {
6580 self.style.as_ref().unwrap().local_player
6581 }
6582 }
6583
6584 fn render_edit_prediction_accept_keybind(
6585 &self,
6586 window: &mut Window,
6587 cx: &App,
6588 ) -> Option<AnyElement> {
6589 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6590 let accept_keystroke = accept_binding.keystroke()?;
6591
6592 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6593
6594 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6595 Color::Accent
6596 } else {
6597 Color::Muted
6598 };
6599
6600 h_flex()
6601 .px_0p5()
6602 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6603 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6604 .text_size(TextSize::XSmall.rems(cx))
6605 .child(h_flex().children(ui::render_modifiers(
6606 &accept_keystroke.modifiers,
6607 PlatformStyle::platform(),
6608 Some(modifiers_color),
6609 Some(IconSize::XSmall.rems().into()),
6610 true,
6611 )))
6612 .when(is_platform_style_mac, |parent| {
6613 parent.child(accept_keystroke.key.clone())
6614 })
6615 .when(!is_platform_style_mac, |parent| {
6616 parent.child(
6617 Key::new(
6618 util::capitalize(&accept_keystroke.key),
6619 Some(Color::Default),
6620 )
6621 .size(Some(IconSize::XSmall.rems().into())),
6622 )
6623 })
6624 .into_any()
6625 .into()
6626 }
6627
6628 fn render_edit_prediction_line_popover(
6629 &self,
6630 label: impl Into<SharedString>,
6631 icon: Option<IconName>,
6632 window: &mut Window,
6633 cx: &App,
6634 ) -> Option<Stateful<Div>> {
6635 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6636
6637 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6638 let has_keybind = keybind.is_some();
6639
6640 let result = h_flex()
6641 .id("ep-line-popover")
6642 .py_0p5()
6643 .pl_1()
6644 .pr(padding_right)
6645 .gap_1()
6646 .rounded_md()
6647 .border_1()
6648 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6649 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6650 .shadow_sm()
6651 .when(!has_keybind, |el| {
6652 let status_colors = cx.theme().status();
6653
6654 el.bg(status_colors.error_background)
6655 .border_color(status_colors.error.opacity(0.6))
6656 .pl_2()
6657 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
6658 .cursor_default()
6659 .hoverable_tooltip(move |_window, cx| {
6660 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6661 })
6662 })
6663 .children(keybind)
6664 .child(
6665 Label::new(label)
6666 .size(LabelSize::Small)
6667 .when(!has_keybind, |el| {
6668 el.color(cx.theme().status().error.into()).strikethrough()
6669 }),
6670 )
6671 .when(!has_keybind, |el| {
6672 el.child(
6673 h_flex().ml_1().child(
6674 Icon::new(IconName::Info)
6675 .size(IconSize::Small)
6676 .color(cx.theme().status().error.into()),
6677 ),
6678 )
6679 })
6680 .when_some(icon, |element, icon| {
6681 element.child(
6682 div()
6683 .mt(px(1.5))
6684 .child(Icon::new(icon).size(IconSize::Small)),
6685 )
6686 });
6687
6688 Some(result)
6689 }
6690
6691 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6692 let accent_color = cx.theme().colors().text_accent;
6693 let editor_bg_color = cx.theme().colors().editor_background;
6694 editor_bg_color.blend(accent_color.opacity(0.1))
6695 }
6696
6697 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6698 let accent_color = cx.theme().colors().text_accent;
6699 let editor_bg_color = cx.theme().colors().editor_background;
6700 editor_bg_color.blend(accent_color.opacity(0.6))
6701 }
6702
6703 fn render_edit_prediction_cursor_popover(
6704 &self,
6705 min_width: Pixels,
6706 max_width: Pixels,
6707 cursor_point: Point,
6708 style: &EditorStyle,
6709 accept_keystroke: Option<&gpui::Keystroke>,
6710 _window: &Window,
6711 cx: &mut Context<Editor>,
6712 ) -> Option<AnyElement> {
6713 let provider = self.edit_prediction_provider.as_ref()?;
6714
6715 if provider.provider.needs_terms_acceptance(cx) {
6716 return Some(
6717 h_flex()
6718 .min_w(min_width)
6719 .flex_1()
6720 .px_2()
6721 .py_1()
6722 .gap_3()
6723 .elevation_2(cx)
6724 .hover(|style| style.bg(cx.theme().colors().element_hover))
6725 .id("accept-terms")
6726 .cursor_pointer()
6727 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6728 .on_click(cx.listener(|this, _event, window, cx| {
6729 cx.stop_propagation();
6730 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6731 window.dispatch_action(
6732 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6733 cx,
6734 );
6735 }))
6736 .child(
6737 h_flex()
6738 .flex_1()
6739 .gap_2()
6740 .child(Icon::new(IconName::ZedPredict))
6741 .child(Label::new("Accept Terms of Service"))
6742 .child(div().w_full())
6743 .child(
6744 Icon::new(IconName::ArrowUpRight)
6745 .color(Color::Muted)
6746 .size(IconSize::Small),
6747 )
6748 .into_any_element(),
6749 )
6750 .into_any(),
6751 );
6752 }
6753
6754 let is_refreshing = provider.provider.is_refreshing(cx);
6755
6756 fn pending_completion_container() -> Div {
6757 h_flex()
6758 .h_full()
6759 .flex_1()
6760 .gap_2()
6761 .child(Icon::new(IconName::ZedPredict))
6762 }
6763
6764 let completion = match &self.active_inline_completion {
6765 Some(prediction) => {
6766 if !self.has_visible_completions_menu() {
6767 const RADIUS: Pixels = px(6.);
6768 const BORDER_WIDTH: Pixels = px(1.);
6769
6770 return Some(
6771 h_flex()
6772 .elevation_2(cx)
6773 .border(BORDER_WIDTH)
6774 .border_color(cx.theme().colors().border)
6775 .when(accept_keystroke.is_none(), |el| {
6776 el.border_color(cx.theme().status().error)
6777 })
6778 .rounded(RADIUS)
6779 .rounded_tl(px(0.))
6780 .overflow_hidden()
6781 .child(div().px_1p5().child(match &prediction.completion {
6782 InlineCompletion::Move { target, snapshot } => {
6783 use text::ToPoint as _;
6784 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6785 {
6786 Icon::new(IconName::ZedPredictDown)
6787 } else {
6788 Icon::new(IconName::ZedPredictUp)
6789 }
6790 }
6791 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6792 }))
6793 .child(
6794 h_flex()
6795 .gap_1()
6796 .py_1()
6797 .px_2()
6798 .rounded_r(RADIUS - BORDER_WIDTH)
6799 .border_l_1()
6800 .border_color(cx.theme().colors().border)
6801 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6802 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6803 el.child(
6804 Label::new("Hold")
6805 .size(LabelSize::Small)
6806 .when(accept_keystroke.is_none(), |el| {
6807 el.strikethrough()
6808 })
6809 .line_height_style(LineHeightStyle::UiLabel),
6810 )
6811 })
6812 .id("edit_prediction_cursor_popover_keybind")
6813 .when(accept_keystroke.is_none(), |el| {
6814 let status_colors = cx.theme().status();
6815
6816 el.bg(status_colors.error_background)
6817 .border_color(status_colors.error.opacity(0.6))
6818 .child(Icon::new(IconName::Info).color(Color::Error))
6819 .cursor_default()
6820 .hoverable_tooltip(move |_window, cx| {
6821 cx.new(|_| MissingEditPredictionKeybindingTooltip)
6822 .into()
6823 })
6824 })
6825 .when_some(
6826 accept_keystroke.as_ref(),
6827 |el, accept_keystroke| {
6828 el.child(h_flex().children(ui::render_modifiers(
6829 &accept_keystroke.modifiers,
6830 PlatformStyle::platform(),
6831 Some(Color::Default),
6832 Some(IconSize::XSmall.rems().into()),
6833 false,
6834 )))
6835 },
6836 ),
6837 )
6838 .into_any(),
6839 );
6840 }
6841
6842 self.render_edit_prediction_cursor_popover_preview(
6843 prediction,
6844 cursor_point,
6845 style,
6846 cx,
6847 )?
6848 }
6849
6850 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6851 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6852 stale_completion,
6853 cursor_point,
6854 style,
6855 cx,
6856 )?,
6857
6858 None => {
6859 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6860 }
6861 },
6862
6863 None => pending_completion_container().child(Label::new("No Prediction")),
6864 };
6865
6866 let completion = if is_refreshing {
6867 completion
6868 .with_animation(
6869 "loading-completion",
6870 Animation::new(Duration::from_secs(2))
6871 .repeat()
6872 .with_easing(pulsating_between(0.4, 0.8)),
6873 |label, delta| label.opacity(delta),
6874 )
6875 .into_any_element()
6876 } else {
6877 completion.into_any_element()
6878 };
6879
6880 let has_completion = self.active_inline_completion.is_some();
6881
6882 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6883 Some(
6884 h_flex()
6885 .min_w(min_width)
6886 .max_w(max_width)
6887 .flex_1()
6888 .elevation_2(cx)
6889 .border_color(cx.theme().colors().border)
6890 .child(
6891 div()
6892 .flex_1()
6893 .py_1()
6894 .px_2()
6895 .overflow_hidden()
6896 .child(completion),
6897 )
6898 .when_some(accept_keystroke, |el, accept_keystroke| {
6899 if !accept_keystroke.modifiers.modified() {
6900 return el;
6901 }
6902
6903 el.child(
6904 h_flex()
6905 .h_full()
6906 .border_l_1()
6907 .rounded_r_lg()
6908 .border_color(cx.theme().colors().border)
6909 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6910 .gap_1()
6911 .py_1()
6912 .px_2()
6913 .child(
6914 h_flex()
6915 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6916 .when(is_platform_style_mac, |parent| parent.gap_1())
6917 .child(h_flex().children(ui::render_modifiers(
6918 &accept_keystroke.modifiers,
6919 PlatformStyle::platform(),
6920 Some(if !has_completion {
6921 Color::Muted
6922 } else {
6923 Color::Default
6924 }),
6925 None,
6926 false,
6927 ))),
6928 )
6929 .child(Label::new("Preview").into_any_element())
6930 .opacity(if has_completion { 1.0 } else { 0.4 }),
6931 )
6932 })
6933 .into_any(),
6934 )
6935 }
6936
6937 fn render_edit_prediction_cursor_popover_preview(
6938 &self,
6939 completion: &InlineCompletionState,
6940 cursor_point: Point,
6941 style: &EditorStyle,
6942 cx: &mut Context<Editor>,
6943 ) -> Option<Div> {
6944 use text::ToPoint as _;
6945
6946 fn render_relative_row_jump(
6947 prefix: impl Into<String>,
6948 current_row: u32,
6949 target_row: u32,
6950 ) -> Div {
6951 let (row_diff, arrow) = if target_row < current_row {
6952 (current_row - target_row, IconName::ArrowUp)
6953 } else {
6954 (target_row - current_row, IconName::ArrowDown)
6955 };
6956
6957 h_flex()
6958 .child(
6959 Label::new(format!("{}{}", prefix.into(), row_diff))
6960 .color(Color::Muted)
6961 .size(LabelSize::Small),
6962 )
6963 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6964 }
6965
6966 match &completion.completion {
6967 InlineCompletion::Move {
6968 target, snapshot, ..
6969 } => Some(
6970 h_flex()
6971 .px_2()
6972 .gap_2()
6973 .flex_1()
6974 .child(
6975 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6976 Icon::new(IconName::ZedPredictDown)
6977 } else {
6978 Icon::new(IconName::ZedPredictUp)
6979 },
6980 )
6981 .child(Label::new("Jump to Edit")),
6982 ),
6983
6984 InlineCompletion::Edit {
6985 edits,
6986 edit_preview,
6987 snapshot,
6988 display_mode: _,
6989 } => {
6990 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6991
6992 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6993 &snapshot,
6994 &edits,
6995 edit_preview.as_ref()?,
6996 true,
6997 cx,
6998 )
6999 .first_line_preview();
7000
7001 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7002 .with_default_highlights(&style.text, highlighted_edits.highlights);
7003
7004 let preview = h_flex()
7005 .gap_1()
7006 .min_w_16()
7007 .child(styled_text)
7008 .when(has_more_lines, |parent| parent.child("…"));
7009
7010 let left = if first_edit_row != cursor_point.row {
7011 render_relative_row_jump("", cursor_point.row, first_edit_row)
7012 .into_any_element()
7013 } else {
7014 Icon::new(IconName::ZedPredict).into_any_element()
7015 };
7016
7017 Some(
7018 h_flex()
7019 .h_full()
7020 .flex_1()
7021 .gap_2()
7022 .pr_1()
7023 .overflow_x_hidden()
7024 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7025 .child(left)
7026 .child(preview),
7027 )
7028 }
7029 }
7030 }
7031
7032 fn render_context_menu(
7033 &self,
7034 style: &EditorStyle,
7035 max_height_in_lines: u32,
7036 y_flipped: bool,
7037 window: &mut Window,
7038 cx: &mut Context<Editor>,
7039 ) -> Option<AnyElement> {
7040 let menu = self.context_menu.borrow();
7041 let menu = menu.as_ref()?;
7042 if !menu.visible() {
7043 return None;
7044 };
7045 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7046 }
7047
7048 fn render_context_menu_aside(
7049 &mut self,
7050 max_size: Size<Pixels>,
7051 window: &mut Window,
7052 cx: &mut Context<Editor>,
7053 ) -> Option<AnyElement> {
7054 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7055 if menu.visible() {
7056 menu.render_aside(self, max_size, window, cx)
7057 } else {
7058 None
7059 }
7060 })
7061 }
7062
7063 fn hide_context_menu(
7064 &mut self,
7065 window: &mut Window,
7066 cx: &mut Context<Self>,
7067 ) -> Option<CodeContextMenu> {
7068 cx.notify();
7069 self.completion_tasks.clear();
7070 let context_menu = self.context_menu.borrow_mut().take();
7071 self.stale_inline_completion_in_menu.take();
7072 self.update_visible_inline_completion(window, cx);
7073 context_menu
7074 }
7075
7076 fn show_snippet_choices(
7077 &mut self,
7078 choices: &Vec<String>,
7079 selection: Range<Anchor>,
7080 cx: &mut Context<Self>,
7081 ) {
7082 if selection.start.buffer_id.is_none() {
7083 return;
7084 }
7085 let buffer_id = selection.start.buffer_id.unwrap();
7086 let buffer = self.buffer().read(cx).buffer(buffer_id);
7087 let id = post_inc(&mut self.next_completion_id);
7088
7089 if let Some(buffer) = buffer {
7090 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7091 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7092 ));
7093 }
7094 }
7095
7096 pub fn insert_snippet(
7097 &mut self,
7098 insertion_ranges: &[Range<usize>],
7099 snippet: Snippet,
7100 window: &mut Window,
7101 cx: &mut Context<Self>,
7102 ) -> Result<()> {
7103 struct Tabstop<T> {
7104 is_end_tabstop: bool,
7105 ranges: Vec<Range<T>>,
7106 choices: Option<Vec<String>>,
7107 }
7108
7109 let tabstops = self.buffer.update(cx, |buffer, cx| {
7110 let snippet_text: Arc<str> = snippet.text.clone().into();
7111 buffer.edit(
7112 insertion_ranges
7113 .iter()
7114 .cloned()
7115 .map(|range| (range, snippet_text.clone())),
7116 Some(AutoindentMode::EachLine),
7117 cx,
7118 );
7119
7120 let snapshot = &*buffer.read(cx);
7121 let snippet = &snippet;
7122 snippet
7123 .tabstops
7124 .iter()
7125 .map(|tabstop| {
7126 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7127 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7128 });
7129 let mut tabstop_ranges = tabstop
7130 .ranges
7131 .iter()
7132 .flat_map(|tabstop_range| {
7133 let mut delta = 0_isize;
7134 insertion_ranges.iter().map(move |insertion_range| {
7135 let insertion_start = insertion_range.start as isize + delta;
7136 delta +=
7137 snippet.text.len() as isize - insertion_range.len() as isize;
7138
7139 let start = ((insertion_start + tabstop_range.start) as usize)
7140 .min(snapshot.len());
7141 let end = ((insertion_start + tabstop_range.end) as usize)
7142 .min(snapshot.len());
7143 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7144 })
7145 })
7146 .collect::<Vec<_>>();
7147 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7148
7149 Tabstop {
7150 is_end_tabstop,
7151 ranges: tabstop_ranges,
7152 choices: tabstop.choices.clone(),
7153 }
7154 })
7155 .collect::<Vec<_>>()
7156 });
7157 if let Some(tabstop) = tabstops.first() {
7158 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7159 s.select_ranges(tabstop.ranges.iter().cloned());
7160 });
7161
7162 if let Some(choices) = &tabstop.choices {
7163 if let Some(selection) = tabstop.ranges.first() {
7164 self.show_snippet_choices(choices, selection.clone(), cx)
7165 }
7166 }
7167
7168 // If we're already at the last tabstop and it's at the end of the snippet,
7169 // we're done, we don't need to keep the state around.
7170 if !tabstop.is_end_tabstop {
7171 let choices = tabstops
7172 .iter()
7173 .map(|tabstop| tabstop.choices.clone())
7174 .collect();
7175
7176 let ranges = tabstops
7177 .into_iter()
7178 .map(|tabstop| tabstop.ranges)
7179 .collect::<Vec<_>>();
7180
7181 self.snippet_stack.push(SnippetState {
7182 active_index: 0,
7183 ranges,
7184 choices,
7185 });
7186 }
7187
7188 // Check whether the just-entered snippet ends with an auto-closable bracket.
7189 if self.autoclose_regions.is_empty() {
7190 let snapshot = self.buffer.read(cx).snapshot(cx);
7191 for selection in &mut self.selections.all::<Point>(cx) {
7192 let selection_head = selection.head();
7193 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7194 continue;
7195 };
7196
7197 let mut bracket_pair = None;
7198 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7199 let prev_chars = snapshot
7200 .reversed_chars_at(selection_head)
7201 .collect::<String>();
7202 for (pair, enabled) in scope.brackets() {
7203 if enabled
7204 && pair.close
7205 && prev_chars.starts_with(pair.start.as_str())
7206 && next_chars.starts_with(pair.end.as_str())
7207 {
7208 bracket_pair = Some(pair.clone());
7209 break;
7210 }
7211 }
7212 if let Some(pair) = bracket_pair {
7213 let start = snapshot.anchor_after(selection_head);
7214 let end = snapshot.anchor_after(selection_head);
7215 self.autoclose_regions.push(AutocloseRegion {
7216 selection_id: selection.id,
7217 range: start..end,
7218 pair,
7219 });
7220 }
7221 }
7222 }
7223 }
7224 Ok(())
7225 }
7226
7227 pub fn move_to_next_snippet_tabstop(
7228 &mut self,
7229 window: &mut Window,
7230 cx: &mut Context<Self>,
7231 ) -> bool {
7232 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7233 }
7234
7235 pub fn move_to_prev_snippet_tabstop(
7236 &mut self,
7237 window: &mut Window,
7238 cx: &mut Context<Self>,
7239 ) -> bool {
7240 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7241 }
7242
7243 pub fn move_to_snippet_tabstop(
7244 &mut self,
7245 bias: Bias,
7246 window: &mut Window,
7247 cx: &mut Context<Self>,
7248 ) -> bool {
7249 if let Some(mut snippet) = self.snippet_stack.pop() {
7250 match bias {
7251 Bias::Left => {
7252 if snippet.active_index > 0 {
7253 snippet.active_index -= 1;
7254 } else {
7255 self.snippet_stack.push(snippet);
7256 return false;
7257 }
7258 }
7259 Bias::Right => {
7260 if snippet.active_index + 1 < snippet.ranges.len() {
7261 snippet.active_index += 1;
7262 } else {
7263 self.snippet_stack.push(snippet);
7264 return false;
7265 }
7266 }
7267 }
7268 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7269 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7270 s.select_anchor_ranges(current_ranges.iter().cloned())
7271 });
7272
7273 if let Some(choices) = &snippet.choices[snippet.active_index] {
7274 if let Some(selection) = current_ranges.first() {
7275 self.show_snippet_choices(&choices, selection.clone(), cx);
7276 }
7277 }
7278
7279 // If snippet state is not at the last tabstop, push it back on the stack
7280 if snippet.active_index + 1 < snippet.ranges.len() {
7281 self.snippet_stack.push(snippet);
7282 }
7283 return true;
7284 }
7285 }
7286
7287 false
7288 }
7289
7290 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7291 self.transact(window, cx, |this, window, cx| {
7292 this.select_all(&SelectAll, window, cx);
7293 this.insert("", window, cx);
7294 });
7295 }
7296
7297 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7298 self.transact(window, cx, |this, window, cx| {
7299 this.select_autoclose_pair(window, cx);
7300 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7301 if !this.linked_edit_ranges.is_empty() {
7302 let selections = this.selections.all::<MultiBufferPoint>(cx);
7303 let snapshot = this.buffer.read(cx).snapshot(cx);
7304
7305 for selection in selections.iter() {
7306 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7307 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7308 if selection_start.buffer_id != selection_end.buffer_id {
7309 continue;
7310 }
7311 if let Some(ranges) =
7312 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7313 {
7314 for (buffer, entries) in ranges {
7315 linked_ranges.entry(buffer).or_default().extend(entries);
7316 }
7317 }
7318 }
7319 }
7320
7321 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7322 if !this.selections.line_mode {
7323 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7324 for selection in &mut selections {
7325 if selection.is_empty() {
7326 let old_head = selection.head();
7327 let mut new_head =
7328 movement::left(&display_map, old_head.to_display_point(&display_map))
7329 .to_point(&display_map);
7330 if let Some((buffer, line_buffer_range)) = display_map
7331 .buffer_snapshot
7332 .buffer_line_for_row(MultiBufferRow(old_head.row))
7333 {
7334 let indent_size =
7335 buffer.indent_size_for_line(line_buffer_range.start.row);
7336 let indent_len = match indent_size.kind {
7337 IndentKind::Space => {
7338 buffer.settings_at(line_buffer_range.start, cx).tab_size
7339 }
7340 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7341 };
7342 if old_head.column <= indent_size.len && old_head.column > 0 {
7343 let indent_len = indent_len.get();
7344 new_head = cmp::min(
7345 new_head,
7346 MultiBufferPoint::new(
7347 old_head.row,
7348 ((old_head.column - 1) / indent_len) * indent_len,
7349 ),
7350 );
7351 }
7352 }
7353
7354 selection.set_head(new_head, SelectionGoal::None);
7355 }
7356 }
7357 }
7358
7359 this.signature_help_state.set_backspace_pressed(true);
7360 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7361 s.select(selections)
7362 });
7363 this.insert("", window, cx);
7364 let empty_str: Arc<str> = Arc::from("");
7365 for (buffer, edits) in linked_ranges {
7366 let snapshot = buffer.read(cx).snapshot();
7367 use text::ToPoint as TP;
7368
7369 let edits = edits
7370 .into_iter()
7371 .map(|range| {
7372 let end_point = TP::to_point(&range.end, &snapshot);
7373 let mut start_point = TP::to_point(&range.start, &snapshot);
7374
7375 if end_point == start_point {
7376 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7377 .saturating_sub(1);
7378 start_point =
7379 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7380 };
7381
7382 (start_point..end_point, empty_str.clone())
7383 })
7384 .sorted_by_key(|(range, _)| range.start)
7385 .collect::<Vec<_>>();
7386 buffer.update(cx, |this, cx| {
7387 this.edit(edits, None, cx);
7388 })
7389 }
7390 this.refresh_inline_completion(true, false, window, cx);
7391 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7392 });
7393 }
7394
7395 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7396 self.transact(window, cx, |this, window, cx| {
7397 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7398 let line_mode = s.line_mode;
7399 s.move_with(|map, selection| {
7400 if selection.is_empty() && !line_mode {
7401 let cursor = movement::right(map, selection.head());
7402 selection.end = cursor;
7403 selection.reversed = true;
7404 selection.goal = SelectionGoal::None;
7405 }
7406 })
7407 });
7408 this.insert("", window, cx);
7409 this.refresh_inline_completion(true, false, window, cx);
7410 });
7411 }
7412
7413 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7414 if self.move_to_prev_snippet_tabstop(window, cx) {
7415 return;
7416 }
7417
7418 self.outdent(&Outdent, window, cx);
7419 }
7420
7421 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7422 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7423 return;
7424 }
7425
7426 let mut selections = self.selections.all_adjusted(cx);
7427 let buffer = self.buffer.read(cx);
7428 let snapshot = buffer.snapshot(cx);
7429 let rows_iter = selections.iter().map(|s| s.head().row);
7430 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7431
7432 let mut edits = Vec::new();
7433 let mut prev_edited_row = 0;
7434 let mut row_delta = 0;
7435 for selection in &mut selections {
7436 if selection.start.row != prev_edited_row {
7437 row_delta = 0;
7438 }
7439 prev_edited_row = selection.end.row;
7440
7441 // If the selection is non-empty, then increase the indentation of the selected lines.
7442 if !selection.is_empty() {
7443 row_delta =
7444 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7445 continue;
7446 }
7447
7448 // If the selection is empty and the cursor is in the leading whitespace before the
7449 // suggested indentation, then auto-indent the line.
7450 let cursor = selection.head();
7451 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7452 if let Some(suggested_indent) =
7453 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7454 {
7455 if cursor.column < suggested_indent.len
7456 && cursor.column <= current_indent.len
7457 && current_indent.len <= suggested_indent.len
7458 {
7459 selection.start = Point::new(cursor.row, suggested_indent.len);
7460 selection.end = selection.start;
7461 if row_delta == 0 {
7462 edits.extend(Buffer::edit_for_indent_size_adjustment(
7463 cursor.row,
7464 current_indent,
7465 suggested_indent,
7466 ));
7467 row_delta = suggested_indent.len - current_indent.len;
7468 }
7469 continue;
7470 }
7471 }
7472
7473 // Otherwise, insert a hard or soft tab.
7474 let settings = buffer.language_settings_at(cursor, cx);
7475 let tab_size = if settings.hard_tabs {
7476 IndentSize::tab()
7477 } else {
7478 let tab_size = settings.tab_size.get();
7479 let char_column = snapshot
7480 .text_for_range(Point::new(cursor.row, 0)..cursor)
7481 .flat_map(str::chars)
7482 .count()
7483 + row_delta as usize;
7484 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7485 IndentSize::spaces(chars_to_next_tab_stop)
7486 };
7487 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7488 selection.end = selection.start;
7489 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7490 row_delta += tab_size.len;
7491 }
7492
7493 self.transact(window, cx, |this, window, cx| {
7494 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7495 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7496 s.select(selections)
7497 });
7498 this.refresh_inline_completion(true, false, window, cx);
7499 });
7500 }
7501
7502 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7503 if self.read_only(cx) {
7504 return;
7505 }
7506 let mut selections = self.selections.all::<Point>(cx);
7507 let mut prev_edited_row = 0;
7508 let mut row_delta = 0;
7509 let mut edits = Vec::new();
7510 let buffer = self.buffer.read(cx);
7511 let snapshot = buffer.snapshot(cx);
7512 for selection in &mut selections {
7513 if selection.start.row != prev_edited_row {
7514 row_delta = 0;
7515 }
7516 prev_edited_row = selection.end.row;
7517
7518 row_delta =
7519 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7520 }
7521
7522 self.transact(window, cx, |this, window, cx| {
7523 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7524 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7525 s.select(selections)
7526 });
7527 });
7528 }
7529
7530 fn indent_selection(
7531 buffer: &MultiBuffer,
7532 snapshot: &MultiBufferSnapshot,
7533 selection: &mut Selection<Point>,
7534 edits: &mut Vec<(Range<Point>, String)>,
7535 delta_for_start_row: u32,
7536 cx: &App,
7537 ) -> u32 {
7538 let settings = buffer.language_settings_at(selection.start, cx);
7539 let tab_size = settings.tab_size.get();
7540 let indent_kind = if settings.hard_tabs {
7541 IndentKind::Tab
7542 } else {
7543 IndentKind::Space
7544 };
7545 let mut start_row = selection.start.row;
7546 let mut end_row = selection.end.row + 1;
7547
7548 // If a selection ends at the beginning of a line, don't indent
7549 // that last line.
7550 if selection.end.column == 0 && selection.end.row > selection.start.row {
7551 end_row -= 1;
7552 }
7553
7554 // Avoid re-indenting a row that has already been indented by a
7555 // previous selection, but still update this selection's column
7556 // to reflect that indentation.
7557 if delta_for_start_row > 0 {
7558 start_row += 1;
7559 selection.start.column += delta_for_start_row;
7560 if selection.end.row == selection.start.row {
7561 selection.end.column += delta_for_start_row;
7562 }
7563 }
7564
7565 let mut delta_for_end_row = 0;
7566 let has_multiple_rows = start_row + 1 != end_row;
7567 for row in start_row..end_row {
7568 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7569 let indent_delta = match (current_indent.kind, indent_kind) {
7570 (IndentKind::Space, IndentKind::Space) => {
7571 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7572 IndentSize::spaces(columns_to_next_tab_stop)
7573 }
7574 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7575 (_, IndentKind::Tab) => IndentSize::tab(),
7576 };
7577
7578 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7579 0
7580 } else {
7581 selection.start.column
7582 };
7583 let row_start = Point::new(row, start);
7584 edits.push((
7585 row_start..row_start,
7586 indent_delta.chars().collect::<String>(),
7587 ));
7588
7589 // Update this selection's endpoints to reflect the indentation.
7590 if row == selection.start.row {
7591 selection.start.column += indent_delta.len;
7592 }
7593 if row == selection.end.row {
7594 selection.end.column += indent_delta.len;
7595 delta_for_end_row = indent_delta.len;
7596 }
7597 }
7598
7599 if selection.start.row == selection.end.row {
7600 delta_for_start_row + delta_for_end_row
7601 } else {
7602 delta_for_end_row
7603 }
7604 }
7605
7606 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7607 if self.read_only(cx) {
7608 return;
7609 }
7610 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7611 let selections = self.selections.all::<Point>(cx);
7612 let mut deletion_ranges = Vec::new();
7613 let mut last_outdent = None;
7614 {
7615 let buffer = self.buffer.read(cx);
7616 let snapshot = buffer.snapshot(cx);
7617 for selection in &selections {
7618 let settings = buffer.language_settings_at(selection.start, cx);
7619 let tab_size = settings.tab_size.get();
7620 let mut rows = selection.spanned_rows(false, &display_map);
7621
7622 // Avoid re-outdenting a row that has already been outdented by a
7623 // previous selection.
7624 if let Some(last_row) = last_outdent {
7625 if last_row == rows.start {
7626 rows.start = rows.start.next_row();
7627 }
7628 }
7629 let has_multiple_rows = rows.len() > 1;
7630 for row in rows.iter_rows() {
7631 let indent_size = snapshot.indent_size_for_line(row);
7632 if indent_size.len > 0 {
7633 let deletion_len = match indent_size.kind {
7634 IndentKind::Space => {
7635 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7636 if columns_to_prev_tab_stop == 0 {
7637 tab_size
7638 } else {
7639 columns_to_prev_tab_stop
7640 }
7641 }
7642 IndentKind::Tab => 1,
7643 };
7644 let start = if has_multiple_rows
7645 || deletion_len > selection.start.column
7646 || indent_size.len < selection.start.column
7647 {
7648 0
7649 } else {
7650 selection.start.column - deletion_len
7651 };
7652 deletion_ranges.push(
7653 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7654 );
7655 last_outdent = Some(row);
7656 }
7657 }
7658 }
7659 }
7660
7661 self.transact(window, cx, |this, window, cx| {
7662 this.buffer.update(cx, |buffer, cx| {
7663 let empty_str: Arc<str> = Arc::default();
7664 buffer.edit(
7665 deletion_ranges
7666 .into_iter()
7667 .map(|range| (range, empty_str.clone())),
7668 None,
7669 cx,
7670 );
7671 });
7672 let selections = this.selections.all::<usize>(cx);
7673 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7674 s.select(selections)
7675 });
7676 });
7677 }
7678
7679 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7680 if self.read_only(cx) {
7681 return;
7682 }
7683 let selections = self
7684 .selections
7685 .all::<usize>(cx)
7686 .into_iter()
7687 .map(|s| s.range());
7688
7689 self.transact(window, cx, |this, window, cx| {
7690 this.buffer.update(cx, |buffer, cx| {
7691 buffer.autoindent_ranges(selections, cx);
7692 });
7693 let selections = this.selections.all::<usize>(cx);
7694 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7695 s.select(selections)
7696 });
7697 });
7698 }
7699
7700 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7701 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7702 let selections = self.selections.all::<Point>(cx);
7703
7704 let mut new_cursors = Vec::new();
7705 let mut edit_ranges = Vec::new();
7706 let mut selections = selections.iter().peekable();
7707 while let Some(selection) = selections.next() {
7708 let mut rows = selection.spanned_rows(false, &display_map);
7709 let goal_display_column = selection.head().to_display_point(&display_map).column();
7710
7711 // Accumulate contiguous regions of rows that we want to delete.
7712 while let Some(next_selection) = selections.peek() {
7713 let next_rows = next_selection.spanned_rows(false, &display_map);
7714 if next_rows.start <= rows.end {
7715 rows.end = next_rows.end;
7716 selections.next().unwrap();
7717 } else {
7718 break;
7719 }
7720 }
7721
7722 let buffer = &display_map.buffer_snapshot;
7723 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7724 let edit_end;
7725 let cursor_buffer_row;
7726 if buffer.max_point().row >= rows.end.0 {
7727 // If there's a line after the range, delete the \n from the end of the row range
7728 // and position the cursor on the next line.
7729 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7730 cursor_buffer_row = rows.end;
7731 } else {
7732 // If there isn't a line after the range, delete the \n from the line before the
7733 // start of the row range and position the cursor there.
7734 edit_start = edit_start.saturating_sub(1);
7735 edit_end = buffer.len();
7736 cursor_buffer_row = rows.start.previous_row();
7737 }
7738
7739 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7740 *cursor.column_mut() =
7741 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7742
7743 new_cursors.push((
7744 selection.id,
7745 buffer.anchor_after(cursor.to_point(&display_map)),
7746 ));
7747 edit_ranges.push(edit_start..edit_end);
7748 }
7749
7750 self.transact(window, cx, |this, window, cx| {
7751 let buffer = this.buffer.update(cx, |buffer, cx| {
7752 let empty_str: Arc<str> = Arc::default();
7753 buffer.edit(
7754 edit_ranges
7755 .into_iter()
7756 .map(|range| (range, empty_str.clone())),
7757 None,
7758 cx,
7759 );
7760 buffer.snapshot(cx)
7761 });
7762 let new_selections = new_cursors
7763 .into_iter()
7764 .map(|(id, cursor)| {
7765 let cursor = cursor.to_point(&buffer);
7766 Selection {
7767 id,
7768 start: cursor,
7769 end: cursor,
7770 reversed: false,
7771 goal: SelectionGoal::None,
7772 }
7773 })
7774 .collect();
7775
7776 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7777 s.select(new_selections);
7778 });
7779 });
7780 }
7781
7782 pub fn join_lines_impl(
7783 &mut self,
7784 insert_whitespace: bool,
7785 window: &mut Window,
7786 cx: &mut Context<Self>,
7787 ) {
7788 if self.read_only(cx) {
7789 return;
7790 }
7791 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7792 for selection in self.selections.all::<Point>(cx) {
7793 let start = MultiBufferRow(selection.start.row);
7794 // Treat single line selections as if they include the next line. Otherwise this action
7795 // would do nothing for single line selections individual cursors.
7796 let end = if selection.start.row == selection.end.row {
7797 MultiBufferRow(selection.start.row + 1)
7798 } else {
7799 MultiBufferRow(selection.end.row)
7800 };
7801
7802 if let Some(last_row_range) = row_ranges.last_mut() {
7803 if start <= last_row_range.end {
7804 last_row_range.end = end;
7805 continue;
7806 }
7807 }
7808 row_ranges.push(start..end);
7809 }
7810
7811 let snapshot = self.buffer.read(cx).snapshot(cx);
7812 let mut cursor_positions = Vec::new();
7813 for row_range in &row_ranges {
7814 let anchor = snapshot.anchor_before(Point::new(
7815 row_range.end.previous_row().0,
7816 snapshot.line_len(row_range.end.previous_row()),
7817 ));
7818 cursor_positions.push(anchor..anchor);
7819 }
7820
7821 self.transact(window, cx, |this, window, cx| {
7822 for row_range in row_ranges.into_iter().rev() {
7823 for row in row_range.iter_rows().rev() {
7824 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7825 let next_line_row = row.next_row();
7826 let indent = snapshot.indent_size_for_line(next_line_row);
7827 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7828
7829 let replace =
7830 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7831 " "
7832 } else {
7833 ""
7834 };
7835
7836 this.buffer.update(cx, |buffer, cx| {
7837 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7838 });
7839 }
7840 }
7841
7842 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7843 s.select_anchor_ranges(cursor_positions)
7844 });
7845 });
7846 }
7847
7848 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7849 self.join_lines_impl(true, window, cx);
7850 }
7851
7852 pub fn sort_lines_case_sensitive(
7853 &mut self,
7854 _: &SortLinesCaseSensitive,
7855 window: &mut Window,
7856 cx: &mut Context<Self>,
7857 ) {
7858 self.manipulate_lines(window, cx, |lines| lines.sort())
7859 }
7860
7861 pub fn sort_lines_case_insensitive(
7862 &mut self,
7863 _: &SortLinesCaseInsensitive,
7864 window: &mut Window,
7865 cx: &mut Context<Self>,
7866 ) {
7867 self.manipulate_lines(window, cx, |lines| {
7868 lines.sort_by_key(|line| line.to_lowercase())
7869 })
7870 }
7871
7872 pub fn unique_lines_case_insensitive(
7873 &mut self,
7874 _: &UniqueLinesCaseInsensitive,
7875 window: &mut Window,
7876 cx: &mut Context<Self>,
7877 ) {
7878 self.manipulate_lines(window, cx, |lines| {
7879 let mut seen = HashSet::default();
7880 lines.retain(|line| seen.insert(line.to_lowercase()));
7881 })
7882 }
7883
7884 pub fn unique_lines_case_sensitive(
7885 &mut self,
7886 _: &UniqueLinesCaseSensitive,
7887 window: &mut Window,
7888 cx: &mut Context<Self>,
7889 ) {
7890 self.manipulate_lines(window, cx, |lines| {
7891 let mut seen = HashSet::default();
7892 lines.retain(|line| seen.insert(*line));
7893 })
7894 }
7895
7896 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7897 let Some(project) = self.project.clone() else {
7898 return;
7899 };
7900 self.reload(project, window, cx)
7901 .detach_and_notify_err(window, cx);
7902 }
7903
7904 pub fn restore_file(
7905 &mut self,
7906 _: &::git::RestoreFile,
7907 window: &mut Window,
7908 cx: &mut Context<Self>,
7909 ) {
7910 let mut buffer_ids = HashSet::default();
7911 let snapshot = self.buffer().read(cx).snapshot(cx);
7912 for selection in self.selections.all::<usize>(cx) {
7913 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7914 }
7915
7916 let buffer = self.buffer().read(cx);
7917 let ranges = buffer_ids
7918 .into_iter()
7919 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7920 .collect::<Vec<_>>();
7921
7922 self.restore_hunks_in_ranges(ranges, window, cx);
7923 }
7924
7925 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7926 let selections = self
7927 .selections
7928 .all(cx)
7929 .into_iter()
7930 .map(|s| s.range())
7931 .collect();
7932 self.restore_hunks_in_ranges(selections, window, cx);
7933 }
7934
7935 fn restore_hunks_in_ranges(
7936 &mut self,
7937 ranges: Vec<Range<Point>>,
7938 window: &mut Window,
7939 cx: &mut Context<Editor>,
7940 ) {
7941 let mut revert_changes = HashMap::default();
7942 let chunk_by = self
7943 .snapshot(window, cx)
7944 .hunks_for_ranges(ranges)
7945 .into_iter()
7946 .chunk_by(|hunk| hunk.buffer_id);
7947 for (buffer_id, hunks) in &chunk_by {
7948 let hunks = hunks.collect::<Vec<_>>();
7949 for hunk in &hunks {
7950 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7951 }
7952 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7953 }
7954 drop(chunk_by);
7955 if !revert_changes.is_empty() {
7956 self.transact(window, cx, |editor, window, cx| {
7957 editor.restore(revert_changes, window, cx);
7958 });
7959 }
7960 }
7961
7962 pub fn open_active_item_in_terminal(
7963 &mut self,
7964 _: &OpenInTerminal,
7965 window: &mut Window,
7966 cx: &mut Context<Self>,
7967 ) {
7968 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7969 let project_path = buffer.read(cx).project_path(cx)?;
7970 let project = self.project.as_ref()?.read(cx);
7971 let entry = project.entry_for_path(&project_path, cx)?;
7972 let parent = match &entry.canonical_path {
7973 Some(canonical_path) => canonical_path.to_path_buf(),
7974 None => project.absolute_path(&project_path, cx)?,
7975 }
7976 .parent()?
7977 .to_path_buf();
7978 Some(parent)
7979 }) {
7980 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7981 }
7982 }
7983
7984 pub fn prepare_restore_change(
7985 &self,
7986 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7987 hunk: &MultiBufferDiffHunk,
7988 cx: &mut App,
7989 ) -> Option<()> {
7990 if hunk.is_created_file() {
7991 return None;
7992 }
7993 let buffer = self.buffer.read(cx);
7994 let diff = buffer.diff_for(hunk.buffer_id)?;
7995 let buffer = buffer.buffer(hunk.buffer_id)?;
7996 let buffer = buffer.read(cx);
7997 let original_text = diff
7998 .read(cx)
7999 .base_text()
8000 .as_rope()
8001 .slice(hunk.diff_base_byte_range.clone());
8002 let buffer_snapshot = buffer.snapshot();
8003 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8004 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8005 probe
8006 .0
8007 .start
8008 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8009 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8010 }) {
8011 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8012 Some(())
8013 } else {
8014 None
8015 }
8016 }
8017
8018 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8019 self.manipulate_lines(window, cx, |lines| lines.reverse())
8020 }
8021
8022 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8023 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8024 }
8025
8026 fn manipulate_lines<Fn>(
8027 &mut self,
8028 window: &mut Window,
8029 cx: &mut Context<Self>,
8030 mut callback: Fn,
8031 ) where
8032 Fn: FnMut(&mut Vec<&str>),
8033 {
8034 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8035 let buffer = self.buffer.read(cx).snapshot(cx);
8036
8037 let mut edits = Vec::new();
8038
8039 let selections = self.selections.all::<Point>(cx);
8040 let mut selections = selections.iter().peekable();
8041 let mut contiguous_row_selections = Vec::new();
8042 let mut new_selections = Vec::new();
8043 let mut added_lines = 0;
8044 let mut removed_lines = 0;
8045
8046 while let Some(selection) = selections.next() {
8047 let (start_row, end_row) = consume_contiguous_rows(
8048 &mut contiguous_row_selections,
8049 selection,
8050 &display_map,
8051 &mut selections,
8052 );
8053
8054 let start_point = Point::new(start_row.0, 0);
8055 let end_point = Point::new(
8056 end_row.previous_row().0,
8057 buffer.line_len(end_row.previous_row()),
8058 );
8059 let text = buffer
8060 .text_for_range(start_point..end_point)
8061 .collect::<String>();
8062
8063 let mut lines = text.split('\n').collect_vec();
8064
8065 let lines_before = lines.len();
8066 callback(&mut lines);
8067 let lines_after = lines.len();
8068
8069 edits.push((start_point..end_point, lines.join("\n")));
8070
8071 // Selections must change based on added and removed line count
8072 let start_row =
8073 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8074 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8075 new_selections.push(Selection {
8076 id: selection.id,
8077 start: start_row,
8078 end: end_row,
8079 goal: SelectionGoal::None,
8080 reversed: selection.reversed,
8081 });
8082
8083 if lines_after > lines_before {
8084 added_lines += lines_after - lines_before;
8085 } else if lines_before > lines_after {
8086 removed_lines += lines_before - lines_after;
8087 }
8088 }
8089
8090 self.transact(window, cx, |this, window, cx| {
8091 let buffer = this.buffer.update(cx, |buffer, cx| {
8092 buffer.edit(edits, None, cx);
8093 buffer.snapshot(cx)
8094 });
8095
8096 // Recalculate offsets on newly edited buffer
8097 let new_selections = new_selections
8098 .iter()
8099 .map(|s| {
8100 let start_point = Point::new(s.start.0, 0);
8101 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8102 Selection {
8103 id: s.id,
8104 start: buffer.point_to_offset(start_point),
8105 end: buffer.point_to_offset(end_point),
8106 goal: s.goal,
8107 reversed: s.reversed,
8108 }
8109 })
8110 .collect();
8111
8112 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8113 s.select(new_selections);
8114 });
8115
8116 this.request_autoscroll(Autoscroll::fit(), cx);
8117 });
8118 }
8119
8120 pub fn convert_to_upper_case(
8121 &mut self,
8122 _: &ConvertToUpperCase,
8123 window: &mut Window,
8124 cx: &mut Context<Self>,
8125 ) {
8126 self.manipulate_text(window, cx, |text| text.to_uppercase())
8127 }
8128
8129 pub fn convert_to_lower_case(
8130 &mut self,
8131 _: &ConvertToLowerCase,
8132 window: &mut Window,
8133 cx: &mut Context<Self>,
8134 ) {
8135 self.manipulate_text(window, cx, |text| text.to_lowercase())
8136 }
8137
8138 pub fn convert_to_title_case(
8139 &mut self,
8140 _: &ConvertToTitleCase,
8141 window: &mut Window,
8142 cx: &mut Context<Self>,
8143 ) {
8144 self.manipulate_text(window, cx, |text| {
8145 text.split('\n')
8146 .map(|line| line.to_case(Case::Title))
8147 .join("\n")
8148 })
8149 }
8150
8151 pub fn convert_to_snake_case(
8152 &mut self,
8153 _: &ConvertToSnakeCase,
8154 window: &mut Window,
8155 cx: &mut Context<Self>,
8156 ) {
8157 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8158 }
8159
8160 pub fn convert_to_kebab_case(
8161 &mut self,
8162 _: &ConvertToKebabCase,
8163 window: &mut Window,
8164 cx: &mut Context<Self>,
8165 ) {
8166 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8167 }
8168
8169 pub fn convert_to_upper_camel_case(
8170 &mut self,
8171 _: &ConvertToUpperCamelCase,
8172 window: &mut Window,
8173 cx: &mut Context<Self>,
8174 ) {
8175 self.manipulate_text(window, cx, |text| {
8176 text.split('\n')
8177 .map(|line| line.to_case(Case::UpperCamel))
8178 .join("\n")
8179 })
8180 }
8181
8182 pub fn convert_to_lower_camel_case(
8183 &mut self,
8184 _: &ConvertToLowerCamelCase,
8185 window: &mut Window,
8186 cx: &mut Context<Self>,
8187 ) {
8188 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8189 }
8190
8191 pub fn convert_to_opposite_case(
8192 &mut self,
8193 _: &ConvertToOppositeCase,
8194 window: &mut Window,
8195 cx: &mut Context<Self>,
8196 ) {
8197 self.manipulate_text(window, cx, |text| {
8198 text.chars()
8199 .fold(String::with_capacity(text.len()), |mut t, c| {
8200 if c.is_uppercase() {
8201 t.extend(c.to_lowercase());
8202 } else {
8203 t.extend(c.to_uppercase());
8204 }
8205 t
8206 })
8207 })
8208 }
8209
8210 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8211 where
8212 Fn: FnMut(&str) -> String,
8213 {
8214 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8215 let buffer = self.buffer.read(cx).snapshot(cx);
8216
8217 let mut new_selections = Vec::new();
8218 let mut edits = Vec::new();
8219 let mut selection_adjustment = 0i32;
8220
8221 for selection in self.selections.all::<usize>(cx) {
8222 let selection_is_empty = selection.is_empty();
8223
8224 let (start, end) = if selection_is_empty {
8225 let word_range = movement::surrounding_word(
8226 &display_map,
8227 selection.start.to_display_point(&display_map),
8228 );
8229 let start = word_range.start.to_offset(&display_map, Bias::Left);
8230 let end = word_range.end.to_offset(&display_map, Bias::Left);
8231 (start, end)
8232 } else {
8233 (selection.start, selection.end)
8234 };
8235
8236 let text = buffer.text_for_range(start..end).collect::<String>();
8237 let old_length = text.len() as i32;
8238 let text = callback(&text);
8239
8240 new_selections.push(Selection {
8241 start: (start as i32 - selection_adjustment) as usize,
8242 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8243 goal: SelectionGoal::None,
8244 ..selection
8245 });
8246
8247 selection_adjustment += old_length - text.len() as i32;
8248
8249 edits.push((start..end, text));
8250 }
8251
8252 self.transact(window, cx, |this, window, cx| {
8253 this.buffer.update(cx, |buffer, cx| {
8254 buffer.edit(edits, None, cx);
8255 });
8256
8257 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8258 s.select(new_selections);
8259 });
8260
8261 this.request_autoscroll(Autoscroll::fit(), cx);
8262 });
8263 }
8264
8265 pub fn duplicate(
8266 &mut self,
8267 upwards: bool,
8268 whole_lines: bool,
8269 window: &mut Window,
8270 cx: &mut Context<Self>,
8271 ) {
8272 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8273 let buffer = &display_map.buffer_snapshot;
8274 let selections = self.selections.all::<Point>(cx);
8275
8276 let mut edits = Vec::new();
8277 let mut selections_iter = selections.iter().peekable();
8278 while let Some(selection) = selections_iter.next() {
8279 let mut rows = selection.spanned_rows(false, &display_map);
8280 // duplicate line-wise
8281 if whole_lines || selection.start == selection.end {
8282 // Avoid duplicating the same lines twice.
8283 while let Some(next_selection) = selections_iter.peek() {
8284 let next_rows = next_selection.spanned_rows(false, &display_map);
8285 if next_rows.start < rows.end {
8286 rows.end = next_rows.end;
8287 selections_iter.next().unwrap();
8288 } else {
8289 break;
8290 }
8291 }
8292
8293 // Copy the text from the selected row region and splice it either at the start
8294 // or end of the region.
8295 let start = Point::new(rows.start.0, 0);
8296 let end = Point::new(
8297 rows.end.previous_row().0,
8298 buffer.line_len(rows.end.previous_row()),
8299 );
8300 let text = buffer
8301 .text_for_range(start..end)
8302 .chain(Some("\n"))
8303 .collect::<String>();
8304 let insert_location = if upwards {
8305 Point::new(rows.end.0, 0)
8306 } else {
8307 start
8308 };
8309 edits.push((insert_location..insert_location, text));
8310 } else {
8311 // duplicate character-wise
8312 let start = selection.start;
8313 let end = selection.end;
8314 let text = buffer.text_for_range(start..end).collect::<String>();
8315 edits.push((selection.end..selection.end, text));
8316 }
8317 }
8318
8319 self.transact(window, cx, |this, _, cx| {
8320 this.buffer.update(cx, |buffer, cx| {
8321 buffer.edit(edits, None, cx);
8322 });
8323
8324 this.request_autoscroll(Autoscroll::fit(), cx);
8325 });
8326 }
8327
8328 pub fn duplicate_line_up(
8329 &mut self,
8330 _: &DuplicateLineUp,
8331 window: &mut Window,
8332 cx: &mut Context<Self>,
8333 ) {
8334 self.duplicate(true, true, window, cx);
8335 }
8336
8337 pub fn duplicate_line_down(
8338 &mut self,
8339 _: &DuplicateLineDown,
8340 window: &mut Window,
8341 cx: &mut Context<Self>,
8342 ) {
8343 self.duplicate(false, true, window, cx);
8344 }
8345
8346 pub fn duplicate_selection(
8347 &mut self,
8348 _: &DuplicateSelection,
8349 window: &mut Window,
8350 cx: &mut Context<Self>,
8351 ) {
8352 self.duplicate(false, false, window, cx);
8353 }
8354
8355 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8356 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8357 let buffer = self.buffer.read(cx).snapshot(cx);
8358
8359 let mut edits = Vec::new();
8360 let mut unfold_ranges = Vec::new();
8361 let mut refold_creases = Vec::new();
8362
8363 let selections = self.selections.all::<Point>(cx);
8364 let mut selections = selections.iter().peekable();
8365 let mut contiguous_row_selections = Vec::new();
8366 let mut new_selections = Vec::new();
8367
8368 while let Some(selection) = selections.next() {
8369 // Find all the selections that span a contiguous row range
8370 let (start_row, end_row) = consume_contiguous_rows(
8371 &mut contiguous_row_selections,
8372 selection,
8373 &display_map,
8374 &mut selections,
8375 );
8376
8377 // Move the text spanned by the row range to be before the line preceding the row range
8378 if start_row.0 > 0 {
8379 let range_to_move = Point::new(
8380 start_row.previous_row().0,
8381 buffer.line_len(start_row.previous_row()),
8382 )
8383 ..Point::new(
8384 end_row.previous_row().0,
8385 buffer.line_len(end_row.previous_row()),
8386 );
8387 let insertion_point = display_map
8388 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8389 .0;
8390
8391 // Don't move lines across excerpts
8392 if buffer
8393 .excerpt_containing(insertion_point..range_to_move.end)
8394 .is_some()
8395 {
8396 let text = buffer
8397 .text_for_range(range_to_move.clone())
8398 .flat_map(|s| s.chars())
8399 .skip(1)
8400 .chain(['\n'])
8401 .collect::<String>();
8402
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 = range_to_move.start.row - insertion_point.row + 1;
8412
8413 // Move selections up
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 up
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 move_line_down(
8456 &mut self,
8457 _: &MoveLineDown,
8458 window: &mut Window,
8459 cx: &mut Context<Self>,
8460 ) {
8461 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8462 let buffer = self.buffer.read(cx).snapshot(cx);
8463
8464 let mut edits = Vec::new();
8465 let mut unfold_ranges = Vec::new();
8466 let mut refold_creases = Vec::new();
8467
8468 let selections = self.selections.all::<Point>(cx);
8469 let mut selections = selections.iter().peekable();
8470 let mut contiguous_row_selections = Vec::new();
8471 let mut new_selections = Vec::new();
8472
8473 while let Some(selection) = selections.next() {
8474 // Find all the selections that span a contiguous row range
8475 let (start_row, end_row) = consume_contiguous_rows(
8476 &mut contiguous_row_selections,
8477 selection,
8478 &display_map,
8479 &mut selections,
8480 );
8481
8482 // Move the text spanned by the row range to be after the last line of the row range
8483 if end_row.0 <= buffer.max_point().row {
8484 let range_to_move =
8485 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8486 let insertion_point = display_map
8487 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8488 .0;
8489
8490 // Don't move lines across excerpt boundaries
8491 if buffer
8492 .excerpt_containing(range_to_move.start..insertion_point)
8493 .is_some()
8494 {
8495 let mut text = String::from("\n");
8496 text.extend(buffer.text_for_range(range_to_move.clone()));
8497 text.pop(); // Drop trailing newline
8498 edits.push((
8499 buffer.anchor_after(range_to_move.start)
8500 ..buffer.anchor_before(range_to_move.end),
8501 String::new(),
8502 ));
8503 let insertion_anchor = buffer.anchor_after(insertion_point);
8504 edits.push((insertion_anchor..insertion_anchor, text));
8505
8506 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8507
8508 // Move selections down
8509 new_selections.extend(contiguous_row_selections.drain(..).map(
8510 |mut selection| {
8511 selection.start.row += row_delta;
8512 selection.end.row += row_delta;
8513 selection
8514 },
8515 ));
8516
8517 // Move folds down
8518 unfold_ranges.push(range_to_move.clone());
8519 for fold in display_map.folds_in_range(
8520 buffer.anchor_before(range_to_move.start)
8521 ..buffer.anchor_after(range_to_move.end),
8522 ) {
8523 let mut start = fold.range.start.to_point(&buffer);
8524 let mut end = fold.range.end.to_point(&buffer);
8525 start.row += row_delta;
8526 end.row += row_delta;
8527 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8528 }
8529 }
8530 }
8531
8532 // If we didn't move line(s), preserve the existing selections
8533 new_selections.append(&mut contiguous_row_selections);
8534 }
8535
8536 self.transact(window, cx, |this, window, cx| {
8537 this.unfold_ranges(&unfold_ranges, true, true, cx);
8538 this.buffer.update(cx, |buffer, cx| {
8539 for (range, text) in edits {
8540 buffer.edit([(range, text)], None, cx);
8541 }
8542 });
8543 this.fold_creases(refold_creases, true, window, cx);
8544 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8545 s.select(new_selections)
8546 });
8547 });
8548 }
8549
8550 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8551 let text_layout_details = &self.text_layout_details(window);
8552 self.transact(window, cx, |this, window, cx| {
8553 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8554 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8555 let line_mode = s.line_mode;
8556 s.move_with(|display_map, selection| {
8557 if !selection.is_empty() || line_mode {
8558 return;
8559 }
8560
8561 let mut head = selection.head();
8562 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8563 if head.column() == display_map.line_len(head.row()) {
8564 transpose_offset = display_map
8565 .buffer_snapshot
8566 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8567 }
8568
8569 if transpose_offset == 0 {
8570 return;
8571 }
8572
8573 *head.column_mut() += 1;
8574 head = display_map.clip_point(head, Bias::Right);
8575 let goal = SelectionGoal::HorizontalPosition(
8576 display_map
8577 .x_for_display_point(head, text_layout_details)
8578 .into(),
8579 );
8580 selection.collapse_to(head, goal);
8581
8582 let transpose_start = display_map
8583 .buffer_snapshot
8584 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8585 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8586 let transpose_end = display_map
8587 .buffer_snapshot
8588 .clip_offset(transpose_offset + 1, Bias::Right);
8589 if let Some(ch) =
8590 display_map.buffer_snapshot.chars_at(transpose_start).next()
8591 {
8592 edits.push((transpose_start..transpose_offset, String::new()));
8593 edits.push((transpose_end..transpose_end, ch.to_string()));
8594 }
8595 }
8596 });
8597 edits
8598 });
8599 this.buffer
8600 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8601 let selections = this.selections.all::<usize>(cx);
8602 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8603 s.select(selections);
8604 });
8605 });
8606 }
8607
8608 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8609 self.rewrap_impl(false, cx)
8610 }
8611
8612 pub fn rewrap_impl(&mut self, override_language_settings: bool, cx: &mut Context<Self>) {
8613 let buffer = self.buffer.read(cx).snapshot(cx);
8614 let selections = self.selections.all::<Point>(cx);
8615 let mut selections = selections.iter().peekable();
8616
8617 let mut edits = Vec::new();
8618 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8619
8620 while let Some(selection) = selections.next() {
8621 let mut start_row = selection.start.row;
8622 let mut end_row = selection.end.row;
8623
8624 // Skip selections that overlap with a range that has already been rewrapped.
8625 let selection_range = start_row..end_row;
8626 if rewrapped_row_ranges
8627 .iter()
8628 .any(|range| range.overlaps(&selection_range))
8629 {
8630 continue;
8631 }
8632
8633 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
8634
8635 // Since not all lines in the selection may be at the same indent
8636 // level, choose the indent size that is the most common between all
8637 // of the lines.
8638 //
8639 // If there is a tie, we use the deepest indent.
8640 let (indent_size, indent_end) = {
8641 let mut indent_size_occurrences = HashMap::default();
8642 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8643
8644 for row in start_row..=end_row {
8645 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8646 rows_by_indent_size.entry(indent).or_default().push(row);
8647 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8648 }
8649
8650 let indent_size = indent_size_occurrences
8651 .into_iter()
8652 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8653 .map(|(indent, _)| indent)
8654 .unwrap_or_default();
8655 let row = rows_by_indent_size[&indent_size][0];
8656 let indent_end = Point::new(row, indent_size.len);
8657
8658 (indent_size, indent_end)
8659 };
8660
8661 let mut line_prefix = indent_size.chars().collect::<String>();
8662
8663 let mut inside_comment = false;
8664 if let Some(comment_prefix) =
8665 buffer
8666 .language_scope_at(selection.head())
8667 .and_then(|language| {
8668 language
8669 .line_comment_prefixes()
8670 .iter()
8671 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8672 .cloned()
8673 })
8674 {
8675 line_prefix.push_str(&comment_prefix);
8676 inside_comment = true;
8677 }
8678
8679 let language_settings = buffer.language_settings_at(selection.head(), cx);
8680 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8681 RewrapBehavior::InComments => inside_comment,
8682 RewrapBehavior::InSelections => !selection.is_empty(),
8683 RewrapBehavior::Anywhere => true,
8684 };
8685
8686 let should_rewrap = override_language_settings
8687 || allow_rewrap_based_on_language
8688 || self.hard_wrap.is_some();
8689 if !should_rewrap {
8690 continue;
8691 }
8692
8693 if selection.is_empty() {
8694 'expand_upwards: while start_row > 0 {
8695 let prev_row = start_row - 1;
8696 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8697 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8698 {
8699 start_row = prev_row;
8700 } else {
8701 break 'expand_upwards;
8702 }
8703 }
8704
8705 'expand_downwards: while end_row < buffer.max_point().row {
8706 let next_row = end_row + 1;
8707 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8708 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8709 {
8710 end_row = next_row;
8711 } else {
8712 break 'expand_downwards;
8713 }
8714 }
8715 }
8716
8717 let start = Point::new(start_row, 0);
8718 let start_offset = start.to_offset(&buffer);
8719 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8720 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8721 let Some(lines_without_prefixes) = selection_text
8722 .lines()
8723 .map(|line| {
8724 line.strip_prefix(&line_prefix)
8725 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8726 .ok_or_else(|| {
8727 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8728 })
8729 })
8730 .collect::<Result<Vec<_>, _>>()
8731 .log_err()
8732 else {
8733 continue;
8734 };
8735
8736 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
8737 buffer
8738 .language_settings_at(Point::new(start_row, 0), cx)
8739 .preferred_line_length as usize
8740 });
8741 let wrapped_text = wrap_with_prefix(
8742 line_prefix,
8743 lines_without_prefixes.join(" "),
8744 wrap_column,
8745 tab_size,
8746 );
8747
8748 // TODO: should always use char-based diff while still supporting cursor behavior that
8749 // matches vim.
8750 let mut diff_options = DiffOptions::default();
8751 if override_language_settings {
8752 diff_options.max_word_diff_len = 0;
8753 diff_options.max_word_diff_line_count = 0;
8754 } else {
8755 diff_options.max_word_diff_len = usize::MAX;
8756 diff_options.max_word_diff_line_count = usize::MAX;
8757 }
8758
8759 for (old_range, new_text) in
8760 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8761 {
8762 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8763 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8764 edits.push((edit_start..edit_end, new_text));
8765 }
8766
8767 rewrapped_row_ranges.push(start_row..=end_row);
8768 }
8769
8770 self.buffer
8771 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8772 }
8773
8774 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8775 let mut text = String::new();
8776 let buffer = self.buffer.read(cx).snapshot(cx);
8777 let mut selections = self.selections.all::<Point>(cx);
8778 let mut clipboard_selections = Vec::with_capacity(selections.len());
8779 {
8780 let max_point = buffer.max_point();
8781 let mut is_first = true;
8782 for selection in &mut selections {
8783 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8784 if is_entire_line {
8785 selection.start = Point::new(selection.start.row, 0);
8786 if !selection.is_empty() && selection.end.column == 0 {
8787 selection.end = cmp::min(max_point, selection.end);
8788 } else {
8789 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8790 }
8791 selection.goal = SelectionGoal::None;
8792 }
8793 if is_first {
8794 is_first = false;
8795 } else {
8796 text += "\n";
8797 }
8798 let mut len = 0;
8799 for chunk in buffer.text_for_range(selection.start..selection.end) {
8800 text.push_str(chunk);
8801 len += chunk.len();
8802 }
8803 clipboard_selections.push(ClipboardSelection {
8804 len,
8805 is_entire_line,
8806 first_line_indent: buffer
8807 .indent_size_for_line(MultiBufferRow(selection.start.row))
8808 .len,
8809 });
8810 }
8811 }
8812
8813 self.transact(window, cx, |this, window, cx| {
8814 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8815 s.select(selections);
8816 });
8817 this.insert("", window, cx);
8818 });
8819 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8820 }
8821
8822 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8823 let item = self.cut_common(window, cx);
8824 cx.write_to_clipboard(item);
8825 }
8826
8827 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8828 self.change_selections(None, window, cx, |s| {
8829 s.move_with(|snapshot, sel| {
8830 if sel.is_empty() {
8831 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8832 }
8833 });
8834 });
8835 let item = self.cut_common(window, cx);
8836 cx.set_global(KillRing(item))
8837 }
8838
8839 pub fn kill_ring_yank(
8840 &mut self,
8841 _: &KillRingYank,
8842 window: &mut Window,
8843 cx: &mut Context<Self>,
8844 ) {
8845 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8846 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8847 (kill_ring.text().to_string(), kill_ring.metadata_json())
8848 } else {
8849 return;
8850 }
8851 } else {
8852 return;
8853 };
8854 self.do_paste(&text, metadata, false, window, cx);
8855 }
8856
8857 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8858 let selections = self.selections.all::<Point>(cx);
8859 let buffer = self.buffer.read(cx).read(cx);
8860 let mut text = String::new();
8861
8862 let mut clipboard_selections = Vec::with_capacity(selections.len());
8863 {
8864 let max_point = buffer.max_point();
8865 let mut is_first = true;
8866 for selection in selections.iter() {
8867 let mut start = selection.start;
8868 let mut end = selection.end;
8869 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8870 if is_entire_line {
8871 start = Point::new(start.row, 0);
8872 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8873 }
8874 if is_first {
8875 is_first = false;
8876 } else {
8877 text += "\n";
8878 }
8879 let mut len = 0;
8880 for chunk in buffer.text_for_range(start..end) {
8881 text.push_str(chunk);
8882 len += chunk.len();
8883 }
8884 clipboard_selections.push(ClipboardSelection {
8885 len,
8886 is_entire_line,
8887 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8888 });
8889 }
8890 }
8891
8892 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8893 text,
8894 clipboard_selections,
8895 ));
8896 }
8897
8898 pub fn do_paste(
8899 &mut self,
8900 text: &String,
8901 clipboard_selections: Option<Vec<ClipboardSelection>>,
8902 handle_entire_lines: bool,
8903 window: &mut Window,
8904 cx: &mut Context<Self>,
8905 ) {
8906 if self.read_only(cx) {
8907 return;
8908 }
8909
8910 let clipboard_text = Cow::Borrowed(text);
8911
8912 self.transact(window, cx, |this, window, cx| {
8913 if let Some(mut clipboard_selections) = clipboard_selections {
8914 let old_selections = this.selections.all::<usize>(cx);
8915 let all_selections_were_entire_line =
8916 clipboard_selections.iter().all(|s| s.is_entire_line);
8917 let first_selection_indent_column =
8918 clipboard_selections.first().map(|s| s.first_line_indent);
8919 if clipboard_selections.len() != old_selections.len() {
8920 clipboard_selections.drain(..);
8921 }
8922 let cursor_offset = this.selections.last::<usize>(cx).head();
8923 let mut auto_indent_on_paste = true;
8924
8925 this.buffer.update(cx, |buffer, cx| {
8926 let snapshot = buffer.read(cx);
8927 auto_indent_on_paste = snapshot
8928 .language_settings_at(cursor_offset, cx)
8929 .auto_indent_on_paste;
8930
8931 let mut start_offset = 0;
8932 let mut edits = Vec::new();
8933 let mut original_indent_columns = Vec::new();
8934 for (ix, selection) in old_selections.iter().enumerate() {
8935 let to_insert;
8936 let entire_line;
8937 let original_indent_column;
8938 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8939 let end_offset = start_offset + clipboard_selection.len;
8940 to_insert = &clipboard_text[start_offset..end_offset];
8941 entire_line = clipboard_selection.is_entire_line;
8942 start_offset = end_offset + 1;
8943 original_indent_column = Some(clipboard_selection.first_line_indent);
8944 } else {
8945 to_insert = clipboard_text.as_str();
8946 entire_line = all_selections_were_entire_line;
8947 original_indent_column = first_selection_indent_column
8948 }
8949
8950 // If the corresponding selection was empty when this slice of the
8951 // clipboard text was written, then the entire line containing the
8952 // selection was copied. If this selection is also currently empty,
8953 // then paste the line before the current line of the buffer.
8954 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8955 let column = selection.start.to_point(&snapshot).column as usize;
8956 let line_start = selection.start - column;
8957 line_start..line_start
8958 } else {
8959 selection.range()
8960 };
8961
8962 edits.push((range, to_insert));
8963 original_indent_columns.push(original_indent_column);
8964 }
8965 drop(snapshot);
8966
8967 buffer.edit(
8968 edits,
8969 if auto_indent_on_paste {
8970 Some(AutoindentMode::Block {
8971 original_indent_columns,
8972 })
8973 } else {
8974 None
8975 },
8976 cx,
8977 );
8978 });
8979
8980 let selections = this.selections.all::<usize>(cx);
8981 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8982 s.select(selections)
8983 });
8984 } else {
8985 this.insert(&clipboard_text, window, cx);
8986 }
8987 });
8988 }
8989
8990 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8991 if let Some(item) = cx.read_from_clipboard() {
8992 let entries = item.entries();
8993
8994 match entries.first() {
8995 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8996 // of all the pasted entries.
8997 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8998 .do_paste(
8999 clipboard_string.text(),
9000 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9001 true,
9002 window,
9003 cx,
9004 ),
9005 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9006 }
9007 }
9008 }
9009
9010 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9011 if self.read_only(cx) {
9012 return;
9013 }
9014
9015 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9016 if let Some((selections, _)) =
9017 self.selection_history.transaction(transaction_id).cloned()
9018 {
9019 self.change_selections(None, window, cx, |s| {
9020 s.select_anchors(selections.to_vec());
9021 });
9022 } else {
9023 log::error!(
9024 "No entry in selection_history found for undo. \
9025 This may correspond to a bug where undo does not update the selection. \
9026 If this is occurring, please add details to \
9027 https://github.com/zed-industries/zed/issues/22692"
9028 );
9029 }
9030 self.request_autoscroll(Autoscroll::fit(), cx);
9031 self.unmark_text(window, cx);
9032 self.refresh_inline_completion(true, false, window, cx);
9033 cx.emit(EditorEvent::Edited { transaction_id });
9034 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9035 }
9036 }
9037
9038 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9039 if self.read_only(cx) {
9040 return;
9041 }
9042
9043 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9044 if let Some((_, Some(selections))) =
9045 self.selection_history.transaction(transaction_id).cloned()
9046 {
9047 self.change_selections(None, window, cx, |s| {
9048 s.select_anchors(selections.to_vec());
9049 });
9050 } else {
9051 log::error!(
9052 "No entry in selection_history found for redo. \
9053 This may correspond to a bug where undo does not update the selection. \
9054 If this is occurring, please add details to \
9055 https://github.com/zed-industries/zed/issues/22692"
9056 );
9057 }
9058 self.request_autoscroll(Autoscroll::fit(), cx);
9059 self.unmark_text(window, cx);
9060 self.refresh_inline_completion(true, false, window, cx);
9061 cx.emit(EditorEvent::Edited { transaction_id });
9062 }
9063 }
9064
9065 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9066 self.buffer
9067 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9068 }
9069
9070 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9071 self.buffer
9072 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9073 }
9074
9075 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9076 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9077 let line_mode = s.line_mode;
9078 s.move_with(|map, selection| {
9079 let cursor = if selection.is_empty() && !line_mode {
9080 movement::left(map, selection.start)
9081 } else {
9082 selection.start
9083 };
9084 selection.collapse_to(cursor, SelectionGoal::None);
9085 });
9086 })
9087 }
9088
9089 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9090 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9091 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9092 })
9093 }
9094
9095 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9096 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9097 let line_mode = s.line_mode;
9098 s.move_with(|map, selection| {
9099 let cursor = if selection.is_empty() && !line_mode {
9100 movement::right(map, selection.end)
9101 } else {
9102 selection.end
9103 };
9104 selection.collapse_to(cursor, SelectionGoal::None)
9105 });
9106 })
9107 }
9108
9109 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9110 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9111 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9112 })
9113 }
9114
9115 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9116 if self.take_rename(true, window, cx).is_some() {
9117 return;
9118 }
9119
9120 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9121 cx.propagate();
9122 return;
9123 }
9124
9125 let text_layout_details = &self.text_layout_details(window);
9126 let selection_count = self.selections.count();
9127 let first_selection = self.selections.first_anchor();
9128
9129 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9130 let line_mode = s.line_mode;
9131 s.move_with(|map, selection| {
9132 if !selection.is_empty() && !line_mode {
9133 selection.goal = SelectionGoal::None;
9134 }
9135 let (cursor, goal) = movement::up(
9136 map,
9137 selection.start,
9138 selection.goal,
9139 false,
9140 text_layout_details,
9141 );
9142 selection.collapse_to(cursor, goal);
9143 });
9144 });
9145
9146 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9147 {
9148 cx.propagate();
9149 }
9150 }
9151
9152 pub fn move_up_by_lines(
9153 &mut self,
9154 action: &MoveUpByLines,
9155 window: &mut Window,
9156 cx: &mut Context<Self>,
9157 ) {
9158 if self.take_rename(true, window, cx).is_some() {
9159 return;
9160 }
9161
9162 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9163 cx.propagate();
9164 return;
9165 }
9166
9167 let text_layout_details = &self.text_layout_details(window);
9168
9169 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9170 let line_mode = s.line_mode;
9171 s.move_with(|map, selection| {
9172 if !selection.is_empty() && !line_mode {
9173 selection.goal = SelectionGoal::None;
9174 }
9175 let (cursor, goal) = movement::up_by_rows(
9176 map,
9177 selection.start,
9178 action.lines,
9179 selection.goal,
9180 false,
9181 text_layout_details,
9182 );
9183 selection.collapse_to(cursor, goal);
9184 });
9185 })
9186 }
9187
9188 pub fn move_down_by_lines(
9189 &mut self,
9190 action: &MoveDownByLines,
9191 window: &mut Window,
9192 cx: &mut Context<Self>,
9193 ) {
9194 if self.take_rename(true, window, cx).is_some() {
9195 return;
9196 }
9197
9198 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9199 cx.propagate();
9200 return;
9201 }
9202
9203 let text_layout_details = &self.text_layout_details(window);
9204
9205 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9206 let line_mode = s.line_mode;
9207 s.move_with(|map, selection| {
9208 if !selection.is_empty() && !line_mode {
9209 selection.goal = SelectionGoal::None;
9210 }
9211 let (cursor, goal) = movement::down_by_rows(
9212 map,
9213 selection.start,
9214 action.lines,
9215 selection.goal,
9216 false,
9217 text_layout_details,
9218 );
9219 selection.collapse_to(cursor, goal);
9220 });
9221 })
9222 }
9223
9224 pub fn select_down_by_lines(
9225 &mut self,
9226 action: &SelectDownByLines,
9227 window: &mut Window,
9228 cx: &mut Context<Self>,
9229 ) {
9230 let text_layout_details = &self.text_layout_details(window);
9231 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9232 s.move_heads_with(|map, head, goal| {
9233 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9234 })
9235 })
9236 }
9237
9238 pub fn select_up_by_lines(
9239 &mut self,
9240 action: &SelectUpByLines,
9241 window: &mut Window,
9242 cx: &mut Context<Self>,
9243 ) {
9244 let text_layout_details = &self.text_layout_details(window);
9245 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9246 s.move_heads_with(|map, head, goal| {
9247 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9248 })
9249 })
9250 }
9251
9252 pub fn select_page_up(
9253 &mut self,
9254 _: &SelectPageUp,
9255 window: &mut Window,
9256 cx: &mut Context<Self>,
9257 ) {
9258 let Some(row_count) = self.visible_row_count() else {
9259 return;
9260 };
9261
9262 let text_layout_details = &self.text_layout_details(window);
9263
9264 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9265 s.move_heads_with(|map, head, goal| {
9266 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9267 })
9268 })
9269 }
9270
9271 pub fn move_page_up(
9272 &mut self,
9273 action: &MovePageUp,
9274 window: &mut Window,
9275 cx: &mut Context<Self>,
9276 ) {
9277 if self.take_rename(true, window, cx).is_some() {
9278 return;
9279 }
9280
9281 if self
9282 .context_menu
9283 .borrow_mut()
9284 .as_mut()
9285 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9286 .unwrap_or(false)
9287 {
9288 return;
9289 }
9290
9291 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9292 cx.propagate();
9293 return;
9294 }
9295
9296 let Some(row_count) = self.visible_row_count() else {
9297 return;
9298 };
9299
9300 let autoscroll = if action.center_cursor {
9301 Autoscroll::center()
9302 } else {
9303 Autoscroll::fit()
9304 };
9305
9306 let text_layout_details = &self.text_layout_details(window);
9307
9308 self.change_selections(Some(autoscroll), window, cx, |s| {
9309 let line_mode = s.line_mode;
9310 s.move_with(|map, selection| {
9311 if !selection.is_empty() && !line_mode {
9312 selection.goal = SelectionGoal::None;
9313 }
9314 let (cursor, goal) = movement::up_by_rows(
9315 map,
9316 selection.end,
9317 row_count,
9318 selection.goal,
9319 false,
9320 text_layout_details,
9321 );
9322 selection.collapse_to(cursor, goal);
9323 });
9324 });
9325 }
9326
9327 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9328 let text_layout_details = &self.text_layout_details(window);
9329 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9330 s.move_heads_with(|map, head, goal| {
9331 movement::up(map, head, goal, false, text_layout_details)
9332 })
9333 })
9334 }
9335
9336 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9337 self.take_rename(true, window, cx);
9338
9339 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9340 cx.propagate();
9341 return;
9342 }
9343
9344 let text_layout_details = &self.text_layout_details(window);
9345 let selection_count = self.selections.count();
9346 let first_selection = self.selections.first_anchor();
9347
9348 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9349 let line_mode = s.line_mode;
9350 s.move_with(|map, selection| {
9351 if !selection.is_empty() && !line_mode {
9352 selection.goal = SelectionGoal::None;
9353 }
9354 let (cursor, goal) = movement::down(
9355 map,
9356 selection.end,
9357 selection.goal,
9358 false,
9359 text_layout_details,
9360 );
9361 selection.collapse_to(cursor, goal);
9362 });
9363 });
9364
9365 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9366 {
9367 cx.propagate();
9368 }
9369 }
9370
9371 pub fn select_page_down(
9372 &mut self,
9373 _: &SelectPageDown,
9374 window: &mut Window,
9375 cx: &mut Context<Self>,
9376 ) {
9377 let Some(row_count) = self.visible_row_count() else {
9378 return;
9379 };
9380
9381 let text_layout_details = &self.text_layout_details(window);
9382
9383 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9384 s.move_heads_with(|map, head, goal| {
9385 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9386 })
9387 })
9388 }
9389
9390 pub fn move_page_down(
9391 &mut self,
9392 action: &MovePageDown,
9393 window: &mut Window,
9394 cx: &mut Context<Self>,
9395 ) {
9396 if self.take_rename(true, window, cx).is_some() {
9397 return;
9398 }
9399
9400 if self
9401 .context_menu
9402 .borrow_mut()
9403 .as_mut()
9404 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9405 .unwrap_or(false)
9406 {
9407 return;
9408 }
9409
9410 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9411 cx.propagate();
9412 return;
9413 }
9414
9415 let Some(row_count) = self.visible_row_count() else {
9416 return;
9417 };
9418
9419 let autoscroll = if action.center_cursor {
9420 Autoscroll::center()
9421 } else {
9422 Autoscroll::fit()
9423 };
9424
9425 let text_layout_details = &self.text_layout_details(window);
9426 self.change_selections(Some(autoscroll), window, cx, |s| {
9427 let line_mode = s.line_mode;
9428 s.move_with(|map, selection| {
9429 if !selection.is_empty() && !line_mode {
9430 selection.goal = SelectionGoal::None;
9431 }
9432 let (cursor, goal) = movement::down_by_rows(
9433 map,
9434 selection.end,
9435 row_count,
9436 selection.goal,
9437 false,
9438 text_layout_details,
9439 );
9440 selection.collapse_to(cursor, goal);
9441 });
9442 });
9443 }
9444
9445 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9446 let text_layout_details = &self.text_layout_details(window);
9447 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9448 s.move_heads_with(|map, head, goal| {
9449 movement::down(map, head, goal, false, text_layout_details)
9450 })
9451 });
9452 }
9453
9454 pub fn context_menu_first(
9455 &mut self,
9456 _: &ContextMenuFirst,
9457 _window: &mut Window,
9458 cx: &mut Context<Self>,
9459 ) {
9460 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9461 context_menu.select_first(self.completion_provider.as_deref(), cx);
9462 }
9463 }
9464
9465 pub fn context_menu_prev(
9466 &mut self,
9467 _: &ContextMenuPrevious,
9468 _window: &mut Window,
9469 cx: &mut Context<Self>,
9470 ) {
9471 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9472 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9473 }
9474 }
9475
9476 pub fn context_menu_next(
9477 &mut self,
9478 _: &ContextMenuNext,
9479 _window: &mut Window,
9480 cx: &mut Context<Self>,
9481 ) {
9482 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9483 context_menu.select_next(self.completion_provider.as_deref(), cx);
9484 }
9485 }
9486
9487 pub fn context_menu_last(
9488 &mut self,
9489 _: &ContextMenuLast,
9490 _window: &mut Window,
9491 cx: &mut Context<Self>,
9492 ) {
9493 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9494 context_menu.select_last(self.completion_provider.as_deref(), cx);
9495 }
9496 }
9497
9498 pub fn move_to_previous_word_start(
9499 &mut self,
9500 _: &MoveToPreviousWordStart,
9501 window: &mut Window,
9502 cx: &mut Context<Self>,
9503 ) {
9504 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9505 s.move_cursors_with(|map, head, _| {
9506 (
9507 movement::previous_word_start(map, head),
9508 SelectionGoal::None,
9509 )
9510 });
9511 })
9512 }
9513
9514 pub fn move_to_previous_subword_start(
9515 &mut self,
9516 _: &MoveToPreviousSubwordStart,
9517 window: &mut Window,
9518 cx: &mut Context<Self>,
9519 ) {
9520 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9521 s.move_cursors_with(|map, head, _| {
9522 (
9523 movement::previous_subword_start(map, head),
9524 SelectionGoal::None,
9525 )
9526 });
9527 })
9528 }
9529
9530 pub fn select_to_previous_word_start(
9531 &mut self,
9532 _: &SelectToPreviousWordStart,
9533 window: &mut Window,
9534 cx: &mut Context<Self>,
9535 ) {
9536 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9537 s.move_heads_with(|map, head, _| {
9538 (
9539 movement::previous_word_start(map, head),
9540 SelectionGoal::None,
9541 )
9542 });
9543 })
9544 }
9545
9546 pub fn select_to_previous_subword_start(
9547 &mut self,
9548 _: &SelectToPreviousSubwordStart,
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 (
9555 movement::previous_subword_start(map, head),
9556 SelectionGoal::None,
9557 )
9558 });
9559 })
9560 }
9561
9562 pub fn delete_to_previous_word_start(
9563 &mut self,
9564 action: &DeleteToPreviousWordStart,
9565 window: &mut Window,
9566 cx: &mut Context<Self>,
9567 ) {
9568 self.transact(window, cx, |this, window, cx| {
9569 this.select_autoclose_pair(window, cx);
9570 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9571 let line_mode = s.line_mode;
9572 s.move_with(|map, selection| {
9573 if selection.is_empty() && !line_mode {
9574 let cursor = if action.ignore_newlines {
9575 movement::previous_word_start(map, selection.head())
9576 } else {
9577 movement::previous_word_start_or_newline(map, selection.head())
9578 };
9579 selection.set_head(cursor, SelectionGoal::None);
9580 }
9581 });
9582 });
9583 this.insert("", window, cx);
9584 });
9585 }
9586
9587 pub fn delete_to_previous_subword_start(
9588 &mut self,
9589 _: &DeleteToPreviousSubwordStart,
9590 window: &mut Window,
9591 cx: &mut Context<Self>,
9592 ) {
9593 self.transact(window, cx, |this, window, cx| {
9594 this.select_autoclose_pair(window, cx);
9595 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9596 let line_mode = s.line_mode;
9597 s.move_with(|map, selection| {
9598 if selection.is_empty() && !line_mode {
9599 let cursor = movement::previous_subword_start(map, selection.head());
9600 selection.set_head(cursor, SelectionGoal::None);
9601 }
9602 });
9603 });
9604 this.insert("", window, cx);
9605 });
9606 }
9607
9608 pub fn move_to_next_word_end(
9609 &mut self,
9610 _: &MoveToNextWordEnd,
9611 window: &mut Window,
9612 cx: &mut Context<Self>,
9613 ) {
9614 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9615 s.move_cursors_with(|map, head, _| {
9616 (movement::next_word_end(map, head), SelectionGoal::None)
9617 });
9618 })
9619 }
9620
9621 pub fn move_to_next_subword_end(
9622 &mut self,
9623 _: &MoveToNextSubwordEnd,
9624 window: &mut Window,
9625 cx: &mut Context<Self>,
9626 ) {
9627 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9628 s.move_cursors_with(|map, head, _| {
9629 (movement::next_subword_end(map, head), SelectionGoal::None)
9630 });
9631 })
9632 }
9633
9634 pub fn select_to_next_word_end(
9635 &mut self,
9636 _: &SelectToNextWordEnd,
9637 window: &mut Window,
9638 cx: &mut Context<Self>,
9639 ) {
9640 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9641 s.move_heads_with(|map, head, _| {
9642 (movement::next_word_end(map, head), SelectionGoal::None)
9643 });
9644 })
9645 }
9646
9647 pub fn select_to_next_subword_end(
9648 &mut self,
9649 _: &SelectToNextSubwordEnd,
9650 window: &mut Window,
9651 cx: &mut Context<Self>,
9652 ) {
9653 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9654 s.move_heads_with(|map, head, _| {
9655 (movement::next_subword_end(map, head), SelectionGoal::None)
9656 });
9657 })
9658 }
9659
9660 pub fn delete_to_next_word_end(
9661 &mut self,
9662 action: &DeleteToNextWordEnd,
9663 window: &mut Window,
9664 cx: &mut Context<Self>,
9665 ) {
9666 self.transact(window, cx, |this, window, cx| {
9667 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9668 let line_mode = s.line_mode;
9669 s.move_with(|map, selection| {
9670 if selection.is_empty() && !line_mode {
9671 let cursor = if action.ignore_newlines {
9672 movement::next_word_end(map, selection.head())
9673 } else {
9674 movement::next_word_end_or_newline(map, selection.head())
9675 };
9676 selection.set_head(cursor, SelectionGoal::None);
9677 }
9678 });
9679 });
9680 this.insert("", window, cx);
9681 });
9682 }
9683
9684 pub fn delete_to_next_subword_end(
9685 &mut self,
9686 _: &DeleteToNextSubwordEnd,
9687 window: &mut Window,
9688 cx: &mut Context<Self>,
9689 ) {
9690 self.transact(window, cx, |this, window, cx| {
9691 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9692 s.move_with(|map, selection| {
9693 if selection.is_empty() {
9694 let cursor = movement::next_subword_end(map, selection.head());
9695 selection.set_head(cursor, SelectionGoal::None);
9696 }
9697 });
9698 });
9699 this.insert("", window, cx);
9700 });
9701 }
9702
9703 pub fn move_to_beginning_of_line(
9704 &mut self,
9705 action: &MoveToBeginningOfLine,
9706 window: &mut Window,
9707 cx: &mut Context<Self>,
9708 ) {
9709 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9710 s.move_cursors_with(|map, head, _| {
9711 (
9712 movement::indented_line_beginning(
9713 map,
9714 head,
9715 action.stop_at_soft_wraps,
9716 action.stop_at_indent,
9717 ),
9718 SelectionGoal::None,
9719 )
9720 });
9721 })
9722 }
9723
9724 pub fn select_to_beginning_of_line(
9725 &mut self,
9726 action: &SelectToBeginningOfLine,
9727 window: &mut Window,
9728 cx: &mut Context<Self>,
9729 ) {
9730 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9731 s.move_heads_with(|map, head, _| {
9732 (
9733 movement::indented_line_beginning(
9734 map,
9735 head,
9736 action.stop_at_soft_wraps,
9737 action.stop_at_indent,
9738 ),
9739 SelectionGoal::None,
9740 )
9741 });
9742 });
9743 }
9744
9745 pub fn delete_to_beginning_of_line(
9746 &mut self,
9747 action: &DeleteToBeginningOfLine,
9748 window: &mut Window,
9749 cx: &mut Context<Self>,
9750 ) {
9751 self.transact(window, cx, |this, window, cx| {
9752 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9753 s.move_with(|_, selection| {
9754 selection.reversed = true;
9755 });
9756 });
9757
9758 this.select_to_beginning_of_line(
9759 &SelectToBeginningOfLine {
9760 stop_at_soft_wraps: false,
9761 stop_at_indent: action.stop_at_indent,
9762 },
9763 window,
9764 cx,
9765 );
9766 this.backspace(&Backspace, window, cx);
9767 });
9768 }
9769
9770 pub fn move_to_end_of_line(
9771 &mut self,
9772 action: &MoveToEndOfLine,
9773 window: &mut Window,
9774 cx: &mut Context<Self>,
9775 ) {
9776 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9777 s.move_cursors_with(|map, head, _| {
9778 (
9779 movement::line_end(map, head, action.stop_at_soft_wraps),
9780 SelectionGoal::None,
9781 )
9782 });
9783 })
9784 }
9785
9786 pub fn select_to_end_of_line(
9787 &mut self,
9788 action: &SelectToEndOfLine,
9789 window: &mut Window,
9790 cx: &mut Context<Self>,
9791 ) {
9792 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9793 s.move_heads_with(|map, head, _| {
9794 (
9795 movement::line_end(map, head, action.stop_at_soft_wraps),
9796 SelectionGoal::None,
9797 )
9798 });
9799 })
9800 }
9801
9802 pub fn delete_to_end_of_line(
9803 &mut self,
9804 _: &DeleteToEndOfLine,
9805 window: &mut Window,
9806 cx: &mut Context<Self>,
9807 ) {
9808 self.transact(window, cx, |this, window, cx| {
9809 this.select_to_end_of_line(
9810 &SelectToEndOfLine {
9811 stop_at_soft_wraps: false,
9812 },
9813 window,
9814 cx,
9815 );
9816 this.delete(&Delete, window, cx);
9817 });
9818 }
9819
9820 pub fn cut_to_end_of_line(
9821 &mut self,
9822 _: &CutToEndOfLine,
9823 window: &mut Window,
9824 cx: &mut Context<Self>,
9825 ) {
9826 self.transact(window, cx, |this, window, cx| {
9827 this.select_to_end_of_line(
9828 &SelectToEndOfLine {
9829 stop_at_soft_wraps: false,
9830 },
9831 window,
9832 cx,
9833 );
9834 this.cut(&Cut, window, cx);
9835 });
9836 }
9837
9838 pub fn move_to_start_of_paragraph(
9839 &mut self,
9840 _: &MoveToStartOfParagraph,
9841 window: &mut Window,
9842 cx: &mut Context<Self>,
9843 ) {
9844 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9845 cx.propagate();
9846 return;
9847 }
9848
9849 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9850 s.move_with(|map, selection| {
9851 selection.collapse_to(
9852 movement::start_of_paragraph(map, selection.head(), 1),
9853 SelectionGoal::None,
9854 )
9855 });
9856 })
9857 }
9858
9859 pub fn move_to_end_of_paragraph(
9860 &mut self,
9861 _: &MoveToEndOfParagraph,
9862 window: &mut Window,
9863 cx: &mut Context<Self>,
9864 ) {
9865 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9866 cx.propagate();
9867 return;
9868 }
9869
9870 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9871 s.move_with(|map, selection| {
9872 selection.collapse_to(
9873 movement::end_of_paragraph(map, selection.head(), 1),
9874 SelectionGoal::None,
9875 )
9876 });
9877 })
9878 }
9879
9880 pub fn select_to_start_of_paragraph(
9881 &mut self,
9882 _: &SelectToStartOfParagraph,
9883 window: &mut Window,
9884 cx: &mut Context<Self>,
9885 ) {
9886 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9887 cx.propagate();
9888 return;
9889 }
9890
9891 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9892 s.move_heads_with(|map, head, _| {
9893 (
9894 movement::start_of_paragraph(map, head, 1),
9895 SelectionGoal::None,
9896 )
9897 });
9898 })
9899 }
9900
9901 pub fn select_to_end_of_paragraph(
9902 &mut self,
9903 _: &SelectToEndOfParagraph,
9904 window: &mut Window,
9905 cx: &mut Context<Self>,
9906 ) {
9907 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9908 cx.propagate();
9909 return;
9910 }
9911
9912 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9913 s.move_heads_with(|map, head, _| {
9914 (
9915 movement::end_of_paragraph(map, head, 1),
9916 SelectionGoal::None,
9917 )
9918 });
9919 })
9920 }
9921
9922 pub fn move_to_start_of_excerpt(
9923 &mut self,
9924 _: &MoveToStartOfExcerpt,
9925 window: &mut Window,
9926 cx: &mut Context<Self>,
9927 ) {
9928 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9929 cx.propagate();
9930 return;
9931 }
9932
9933 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9934 s.move_with(|map, selection| {
9935 selection.collapse_to(
9936 movement::start_of_excerpt(
9937 map,
9938 selection.head(),
9939 workspace::searchable::Direction::Prev,
9940 ),
9941 SelectionGoal::None,
9942 )
9943 });
9944 })
9945 }
9946
9947 pub fn move_to_start_of_next_excerpt(
9948 &mut self,
9949 _: &MoveToStartOfNextExcerpt,
9950 window: &mut Window,
9951 cx: &mut Context<Self>,
9952 ) {
9953 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9954 cx.propagate();
9955 return;
9956 }
9957
9958 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9959 s.move_with(|map, selection| {
9960 selection.collapse_to(
9961 movement::start_of_excerpt(
9962 map,
9963 selection.head(),
9964 workspace::searchable::Direction::Next,
9965 ),
9966 SelectionGoal::None,
9967 )
9968 });
9969 })
9970 }
9971
9972 pub fn move_to_end_of_excerpt(
9973 &mut self,
9974 _: &MoveToEndOfExcerpt,
9975 window: &mut Window,
9976 cx: &mut Context<Self>,
9977 ) {
9978 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9979 cx.propagate();
9980 return;
9981 }
9982
9983 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9984 s.move_with(|map, selection| {
9985 selection.collapse_to(
9986 movement::end_of_excerpt(
9987 map,
9988 selection.head(),
9989 workspace::searchable::Direction::Next,
9990 ),
9991 SelectionGoal::None,
9992 )
9993 });
9994 })
9995 }
9996
9997 pub fn move_to_end_of_previous_excerpt(
9998 &mut self,
9999 _: &MoveToEndOfPreviousExcerpt,
10000 window: &mut Window,
10001 cx: &mut Context<Self>,
10002 ) {
10003 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10004 cx.propagate();
10005 return;
10006 }
10007
10008 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10009 s.move_with(|map, selection| {
10010 selection.collapse_to(
10011 movement::end_of_excerpt(
10012 map,
10013 selection.head(),
10014 workspace::searchable::Direction::Prev,
10015 ),
10016 SelectionGoal::None,
10017 )
10018 });
10019 })
10020 }
10021
10022 pub fn select_to_start_of_excerpt(
10023 &mut self,
10024 _: &SelectToStartOfExcerpt,
10025 window: &mut Window,
10026 cx: &mut Context<Self>,
10027 ) {
10028 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10029 cx.propagate();
10030 return;
10031 }
10032
10033 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10034 s.move_heads_with(|map, head, _| {
10035 (
10036 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10037 SelectionGoal::None,
10038 )
10039 });
10040 })
10041 }
10042
10043 pub fn select_to_start_of_next_excerpt(
10044 &mut self,
10045 _: &SelectToStartOfNextExcerpt,
10046 window: &mut Window,
10047 cx: &mut Context<Self>,
10048 ) {
10049 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10050 cx.propagate();
10051 return;
10052 }
10053
10054 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10055 s.move_heads_with(|map, head, _| {
10056 (
10057 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10058 SelectionGoal::None,
10059 )
10060 });
10061 })
10062 }
10063
10064 pub fn select_to_end_of_excerpt(
10065 &mut self,
10066 _: &SelectToEndOfExcerpt,
10067 window: &mut Window,
10068 cx: &mut Context<Self>,
10069 ) {
10070 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10071 cx.propagate();
10072 return;
10073 }
10074
10075 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10076 s.move_heads_with(|map, head, _| {
10077 (
10078 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10079 SelectionGoal::None,
10080 )
10081 });
10082 })
10083 }
10084
10085 pub fn select_to_end_of_previous_excerpt(
10086 &mut self,
10087 _: &SelectToEndOfPreviousExcerpt,
10088 window: &mut Window,
10089 cx: &mut Context<Self>,
10090 ) {
10091 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10092 cx.propagate();
10093 return;
10094 }
10095
10096 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10097 s.move_heads_with(|map, head, _| {
10098 (
10099 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10100 SelectionGoal::None,
10101 )
10102 });
10103 })
10104 }
10105
10106 pub fn move_to_beginning(
10107 &mut self,
10108 _: &MoveToBeginning,
10109 window: &mut Window,
10110 cx: &mut Context<Self>,
10111 ) {
10112 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10113 cx.propagate();
10114 return;
10115 }
10116
10117 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10118 s.select_ranges(vec![0..0]);
10119 });
10120 }
10121
10122 pub fn select_to_beginning(
10123 &mut self,
10124 _: &SelectToBeginning,
10125 window: &mut Window,
10126 cx: &mut Context<Self>,
10127 ) {
10128 let mut selection = self.selections.last::<Point>(cx);
10129 selection.set_head(Point::zero(), SelectionGoal::None);
10130
10131 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10132 s.select(vec![selection]);
10133 });
10134 }
10135
10136 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10137 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10138 cx.propagate();
10139 return;
10140 }
10141
10142 let cursor = self.buffer.read(cx).read(cx).len();
10143 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10144 s.select_ranges(vec![cursor..cursor])
10145 });
10146 }
10147
10148 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10149 self.nav_history = nav_history;
10150 }
10151
10152 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10153 self.nav_history.as_ref()
10154 }
10155
10156 fn push_to_nav_history(
10157 &mut self,
10158 cursor_anchor: Anchor,
10159 new_position: Option<Point>,
10160 cx: &mut Context<Self>,
10161 ) {
10162 if let Some(nav_history) = self.nav_history.as_mut() {
10163 let buffer = self.buffer.read(cx).read(cx);
10164 let cursor_position = cursor_anchor.to_point(&buffer);
10165 let scroll_state = self.scroll_manager.anchor();
10166 let scroll_top_row = scroll_state.top_row(&buffer);
10167 drop(buffer);
10168
10169 if let Some(new_position) = new_position {
10170 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10171 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10172 return;
10173 }
10174 }
10175
10176 nav_history.push(
10177 Some(NavigationData {
10178 cursor_anchor,
10179 cursor_position,
10180 scroll_anchor: scroll_state,
10181 scroll_top_row,
10182 }),
10183 cx,
10184 );
10185 }
10186 }
10187
10188 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10189 let buffer = self.buffer.read(cx).snapshot(cx);
10190 let mut selection = self.selections.first::<usize>(cx);
10191 selection.set_head(buffer.len(), SelectionGoal::None);
10192 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10193 s.select(vec![selection]);
10194 });
10195 }
10196
10197 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10198 let end = self.buffer.read(cx).read(cx).len();
10199 self.change_selections(None, window, cx, |s| {
10200 s.select_ranges(vec![0..end]);
10201 });
10202 }
10203
10204 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10205 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10206 let mut selections = self.selections.all::<Point>(cx);
10207 let max_point = display_map.buffer_snapshot.max_point();
10208 for selection in &mut selections {
10209 let rows = selection.spanned_rows(true, &display_map);
10210 selection.start = Point::new(rows.start.0, 0);
10211 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10212 selection.reversed = false;
10213 }
10214 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10215 s.select(selections);
10216 });
10217 }
10218
10219 pub fn split_selection_into_lines(
10220 &mut self,
10221 _: &SplitSelectionIntoLines,
10222 window: &mut Window,
10223 cx: &mut Context<Self>,
10224 ) {
10225 let selections = self
10226 .selections
10227 .all::<Point>(cx)
10228 .into_iter()
10229 .map(|selection| selection.start..selection.end)
10230 .collect::<Vec<_>>();
10231 self.unfold_ranges(&selections, true, true, cx);
10232
10233 let mut new_selection_ranges = Vec::new();
10234 {
10235 let buffer = self.buffer.read(cx).read(cx);
10236 for selection in selections {
10237 for row in selection.start.row..selection.end.row {
10238 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10239 new_selection_ranges.push(cursor..cursor);
10240 }
10241
10242 let is_multiline_selection = selection.start.row != selection.end.row;
10243 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10244 // so this action feels more ergonomic when paired with other selection operations
10245 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10246 if !should_skip_last {
10247 new_selection_ranges.push(selection.end..selection.end);
10248 }
10249 }
10250 }
10251 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10252 s.select_ranges(new_selection_ranges);
10253 });
10254 }
10255
10256 pub fn add_selection_above(
10257 &mut self,
10258 _: &AddSelectionAbove,
10259 window: &mut Window,
10260 cx: &mut Context<Self>,
10261 ) {
10262 self.add_selection(true, window, cx);
10263 }
10264
10265 pub fn add_selection_below(
10266 &mut self,
10267 _: &AddSelectionBelow,
10268 window: &mut Window,
10269 cx: &mut Context<Self>,
10270 ) {
10271 self.add_selection(false, window, cx);
10272 }
10273
10274 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10276 let mut selections = self.selections.all::<Point>(cx);
10277 let text_layout_details = self.text_layout_details(window);
10278 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10279 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10280 let range = oldest_selection.display_range(&display_map).sorted();
10281
10282 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10283 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10284 let positions = start_x.min(end_x)..start_x.max(end_x);
10285
10286 selections.clear();
10287 let mut stack = Vec::new();
10288 for row in range.start.row().0..=range.end.row().0 {
10289 if let Some(selection) = self.selections.build_columnar_selection(
10290 &display_map,
10291 DisplayRow(row),
10292 &positions,
10293 oldest_selection.reversed,
10294 &text_layout_details,
10295 ) {
10296 stack.push(selection.id);
10297 selections.push(selection);
10298 }
10299 }
10300
10301 if above {
10302 stack.reverse();
10303 }
10304
10305 AddSelectionsState { above, stack }
10306 });
10307
10308 let last_added_selection = *state.stack.last().unwrap();
10309 let mut new_selections = Vec::new();
10310 if above == state.above {
10311 let end_row = if above {
10312 DisplayRow(0)
10313 } else {
10314 display_map.max_point().row()
10315 };
10316
10317 'outer: for selection in selections {
10318 if selection.id == last_added_selection {
10319 let range = selection.display_range(&display_map).sorted();
10320 debug_assert_eq!(range.start.row(), range.end.row());
10321 let mut row = range.start.row();
10322 let positions =
10323 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10324 px(start)..px(end)
10325 } else {
10326 let start_x =
10327 display_map.x_for_display_point(range.start, &text_layout_details);
10328 let end_x =
10329 display_map.x_for_display_point(range.end, &text_layout_details);
10330 start_x.min(end_x)..start_x.max(end_x)
10331 };
10332
10333 while row != end_row {
10334 if above {
10335 row.0 -= 1;
10336 } else {
10337 row.0 += 1;
10338 }
10339
10340 if let Some(new_selection) = self.selections.build_columnar_selection(
10341 &display_map,
10342 row,
10343 &positions,
10344 selection.reversed,
10345 &text_layout_details,
10346 ) {
10347 state.stack.push(new_selection.id);
10348 if above {
10349 new_selections.push(new_selection);
10350 new_selections.push(selection);
10351 } else {
10352 new_selections.push(selection);
10353 new_selections.push(new_selection);
10354 }
10355
10356 continue 'outer;
10357 }
10358 }
10359 }
10360
10361 new_selections.push(selection);
10362 }
10363 } else {
10364 new_selections = selections;
10365 new_selections.retain(|s| s.id != last_added_selection);
10366 state.stack.pop();
10367 }
10368
10369 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10370 s.select(new_selections);
10371 });
10372 if state.stack.len() > 1 {
10373 self.add_selections_state = Some(state);
10374 }
10375 }
10376
10377 pub fn select_next_match_internal(
10378 &mut self,
10379 display_map: &DisplaySnapshot,
10380 replace_newest: bool,
10381 autoscroll: Option<Autoscroll>,
10382 window: &mut Window,
10383 cx: &mut Context<Self>,
10384 ) -> Result<()> {
10385 fn select_next_match_ranges(
10386 this: &mut Editor,
10387 range: Range<usize>,
10388 replace_newest: bool,
10389 auto_scroll: Option<Autoscroll>,
10390 window: &mut Window,
10391 cx: &mut Context<Editor>,
10392 ) {
10393 this.unfold_ranges(&[range.clone()], false, true, cx);
10394 this.change_selections(auto_scroll, window, cx, |s| {
10395 if replace_newest {
10396 s.delete(s.newest_anchor().id);
10397 }
10398 s.insert_range(range.clone());
10399 });
10400 }
10401
10402 let buffer = &display_map.buffer_snapshot;
10403 let mut selections = self.selections.all::<usize>(cx);
10404 if let Some(mut select_next_state) = self.select_next_state.take() {
10405 let query = &select_next_state.query;
10406 if !select_next_state.done {
10407 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10408 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10409 let mut next_selected_range = None;
10410
10411 let bytes_after_last_selection =
10412 buffer.bytes_in_range(last_selection.end..buffer.len());
10413 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10414 let query_matches = query
10415 .stream_find_iter(bytes_after_last_selection)
10416 .map(|result| (last_selection.end, result))
10417 .chain(
10418 query
10419 .stream_find_iter(bytes_before_first_selection)
10420 .map(|result| (0, result)),
10421 );
10422
10423 for (start_offset, query_match) in query_matches {
10424 let query_match = query_match.unwrap(); // can only fail due to I/O
10425 let offset_range =
10426 start_offset + query_match.start()..start_offset + query_match.end();
10427 let display_range = offset_range.start.to_display_point(display_map)
10428 ..offset_range.end.to_display_point(display_map);
10429
10430 if !select_next_state.wordwise
10431 || (!movement::is_inside_word(display_map, display_range.start)
10432 && !movement::is_inside_word(display_map, display_range.end))
10433 {
10434 // TODO: This is n^2, because we might check all the selections
10435 if !selections
10436 .iter()
10437 .any(|selection| selection.range().overlaps(&offset_range))
10438 {
10439 next_selected_range = Some(offset_range);
10440 break;
10441 }
10442 }
10443 }
10444
10445 if let Some(next_selected_range) = next_selected_range {
10446 select_next_match_ranges(
10447 self,
10448 next_selected_range,
10449 replace_newest,
10450 autoscroll,
10451 window,
10452 cx,
10453 );
10454 } else {
10455 select_next_state.done = true;
10456 }
10457 }
10458
10459 self.select_next_state = Some(select_next_state);
10460 } else {
10461 let mut only_carets = true;
10462 let mut same_text_selected = true;
10463 let mut selected_text = None;
10464
10465 let mut selections_iter = selections.iter().peekable();
10466 while let Some(selection) = selections_iter.next() {
10467 if selection.start != selection.end {
10468 only_carets = false;
10469 }
10470
10471 if same_text_selected {
10472 if selected_text.is_none() {
10473 selected_text =
10474 Some(buffer.text_for_range(selection.range()).collect::<String>());
10475 }
10476
10477 if let Some(next_selection) = selections_iter.peek() {
10478 if next_selection.range().len() == selection.range().len() {
10479 let next_selected_text = buffer
10480 .text_for_range(next_selection.range())
10481 .collect::<String>();
10482 if Some(next_selected_text) != selected_text {
10483 same_text_selected = false;
10484 selected_text = None;
10485 }
10486 } else {
10487 same_text_selected = false;
10488 selected_text = None;
10489 }
10490 }
10491 }
10492 }
10493
10494 if only_carets {
10495 for selection in &mut selections {
10496 let word_range = movement::surrounding_word(
10497 display_map,
10498 selection.start.to_display_point(display_map),
10499 );
10500 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10501 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10502 selection.goal = SelectionGoal::None;
10503 selection.reversed = false;
10504 select_next_match_ranges(
10505 self,
10506 selection.start..selection.end,
10507 replace_newest,
10508 autoscroll,
10509 window,
10510 cx,
10511 );
10512 }
10513
10514 if selections.len() == 1 {
10515 let selection = selections
10516 .last()
10517 .expect("ensured that there's only one selection");
10518 let query = buffer
10519 .text_for_range(selection.start..selection.end)
10520 .collect::<String>();
10521 let is_empty = query.is_empty();
10522 let select_state = SelectNextState {
10523 query: AhoCorasick::new(&[query])?,
10524 wordwise: true,
10525 done: is_empty,
10526 };
10527 self.select_next_state = Some(select_state);
10528 } else {
10529 self.select_next_state = None;
10530 }
10531 } else if let Some(selected_text) = selected_text {
10532 self.select_next_state = Some(SelectNextState {
10533 query: AhoCorasick::new(&[selected_text])?,
10534 wordwise: false,
10535 done: false,
10536 });
10537 self.select_next_match_internal(
10538 display_map,
10539 replace_newest,
10540 autoscroll,
10541 window,
10542 cx,
10543 )?;
10544 }
10545 }
10546 Ok(())
10547 }
10548
10549 pub fn select_all_matches(
10550 &mut self,
10551 _action: &SelectAllMatches,
10552 window: &mut Window,
10553 cx: &mut Context<Self>,
10554 ) -> Result<()> {
10555 self.push_to_selection_history();
10556 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10557
10558 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10559 let Some(select_next_state) = self.select_next_state.as_mut() else {
10560 return Ok(());
10561 };
10562 if select_next_state.done {
10563 return Ok(());
10564 }
10565
10566 let mut new_selections = self.selections.all::<usize>(cx);
10567
10568 let buffer = &display_map.buffer_snapshot;
10569 let query_matches = select_next_state
10570 .query
10571 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10572
10573 for query_match in query_matches {
10574 let query_match = query_match.unwrap(); // can only fail due to I/O
10575 let offset_range = query_match.start()..query_match.end();
10576 let display_range = offset_range.start.to_display_point(&display_map)
10577 ..offset_range.end.to_display_point(&display_map);
10578
10579 if !select_next_state.wordwise
10580 || (!movement::is_inside_word(&display_map, display_range.start)
10581 && !movement::is_inside_word(&display_map, display_range.end))
10582 {
10583 self.selections.change_with(cx, |selections| {
10584 new_selections.push(Selection {
10585 id: selections.new_selection_id(),
10586 start: offset_range.start,
10587 end: offset_range.end,
10588 reversed: false,
10589 goal: SelectionGoal::None,
10590 });
10591 });
10592 }
10593 }
10594
10595 new_selections.sort_by_key(|selection| selection.start);
10596 let mut ix = 0;
10597 while ix + 1 < new_selections.len() {
10598 let current_selection = &new_selections[ix];
10599 let next_selection = &new_selections[ix + 1];
10600 if current_selection.range().overlaps(&next_selection.range()) {
10601 if current_selection.id < next_selection.id {
10602 new_selections.remove(ix + 1);
10603 } else {
10604 new_selections.remove(ix);
10605 }
10606 } else {
10607 ix += 1;
10608 }
10609 }
10610
10611 let reversed = self.selections.oldest::<usize>(cx).reversed;
10612
10613 for selection in new_selections.iter_mut() {
10614 selection.reversed = reversed;
10615 }
10616
10617 select_next_state.done = true;
10618 self.unfold_ranges(
10619 &new_selections
10620 .iter()
10621 .map(|selection| selection.range())
10622 .collect::<Vec<_>>(),
10623 false,
10624 false,
10625 cx,
10626 );
10627 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10628 selections.select(new_selections)
10629 });
10630
10631 Ok(())
10632 }
10633
10634 pub fn select_next(
10635 &mut self,
10636 action: &SelectNext,
10637 window: &mut Window,
10638 cx: &mut Context<Self>,
10639 ) -> Result<()> {
10640 self.push_to_selection_history();
10641 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10642 self.select_next_match_internal(
10643 &display_map,
10644 action.replace_newest,
10645 Some(Autoscroll::newest()),
10646 window,
10647 cx,
10648 )?;
10649 Ok(())
10650 }
10651
10652 pub fn select_previous(
10653 &mut self,
10654 action: &SelectPrevious,
10655 window: &mut Window,
10656 cx: &mut Context<Self>,
10657 ) -> Result<()> {
10658 self.push_to_selection_history();
10659 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10660 let buffer = &display_map.buffer_snapshot;
10661 let mut selections = self.selections.all::<usize>(cx);
10662 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10663 let query = &select_prev_state.query;
10664 if !select_prev_state.done {
10665 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10666 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10667 let mut next_selected_range = None;
10668 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10669 let bytes_before_last_selection =
10670 buffer.reversed_bytes_in_range(0..last_selection.start);
10671 let bytes_after_first_selection =
10672 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10673 let query_matches = query
10674 .stream_find_iter(bytes_before_last_selection)
10675 .map(|result| (last_selection.start, result))
10676 .chain(
10677 query
10678 .stream_find_iter(bytes_after_first_selection)
10679 .map(|result| (buffer.len(), result)),
10680 );
10681 for (end_offset, query_match) in query_matches {
10682 let query_match = query_match.unwrap(); // can only fail due to I/O
10683 let offset_range =
10684 end_offset - query_match.end()..end_offset - query_match.start();
10685 let display_range = offset_range.start.to_display_point(&display_map)
10686 ..offset_range.end.to_display_point(&display_map);
10687
10688 if !select_prev_state.wordwise
10689 || (!movement::is_inside_word(&display_map, display_range.start)
10690 && !movement::is_inside_word(&display_map, display_range.end))
10691 {
10692 next_selected_range = Some(offset_range);
10693 break;
10694 }
10695 }
10696
10697 if let Some(next_selected_range) = next_selected_range {
10698 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10699 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10700 if action.replace_newest {
10701 s.delete(s.newest_anchor().id);
10702 }
10703 s.insert_range(next_selected_range);
10704 });
10705 } else {
10706 select_prev_state.done = true;
10707 }
10708 }
10709
10710 self.select_prev_state = Some(select_prev_state);
10711 } else {
10712 let mut only_carets = true;
10713 let mut same_text_selected = true;
10714 let mut selected_text = None;
10715
10716 let mut selections_iter = selections.iter().peekable();
10717 while let Some(selection) = selections_iter.next() {
10718 if selection.start != selection.end {
10719 only_carets = false;
10720 }
10721
10722 if same_text_selected {
10723 if selected_text.is_none() {
10724 selected_text =
10725 Some(buffer.text_for_range(selection.range()).collect::<String>());
10726 }
10727
10728 if let Some(next_selection) = selections_iter.peek() {
10729 if next_selection.range().len() == selection.range().len() {
10730 let next_selected_text = buffer
10731 .text_for_range(next_selection.range())
10732 .collect::<String>();
10733 if Some(next_selected_text) != selected_text {
10734 same_text_selected = false;
10735 selected_text = None;
10736 }
10737 } else {
10738 same_text_selected = false;
10739 selected_text = None;
10740 }
10741 }
10742 }
10743 }
10744
10745 if only_carets {
10746 for selection in &mut selections {
10747 let word_range = movement::surrounding_word(
10748 &display_map,
10749 selection.start.to_display_point(&display_map),
10750 );
10751 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10752 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10753 selection.goal = SelectionGoal::None;
10754 selection.reversed = false;
10755 }
10756 if selections.len() == 1 {
10757 let selection = selections
10758 .last()
10759 .expect("ensured that there's only one selection");
10760 let query = buffer
10761 .text_for_range(selection.start..selection.end)
10762 .collect::<String>();
10763 let is_empty = query.is_empty();
10764 let select_state = SelectNextState {
10765 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10766 wordwise: true,
10767 done: is_empty,
10768 };
10769 self.select_prev_state = Some(select_state);
10770 } else {
10771 self.select_prev_state = None;
10772 }
10773
10774 self.unfold_ranges(
10775 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10776 false,
10777 true,
10778 cx,
10779 );
10780 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10781 s.select(selections);
10782 });
10783 } else if let Some(selected_text) = selected_text {
10784 self.select_prev_state = Some(SelectNextState {
10785 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10786 wordwise: false,
10787 done: false,
10788 });
10789 self.select_previous(action, window, cx)?;
10790 }
10791 }
10792 Ok(())
10793 }
10794
10795 pub fn toggle_comments(
10796 &mut self,
10797 action: &ToggleComments,
10798 window: &mut Window,
10799 cx: &mut Context<Self>,
10800 ) {
10801 if self.read_only(cx) {
10802 return;
10803 }
10804 let text_layout_details = &self.text_layout_details(window);
10805 self.transact(window, cx, |this, window, cx| {
10806 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10807 let mut edits = Vec::new();
10808 let mut selection_edit_ranges = Vec::new();
10809 let mut last_toggled_row = None;
10810 let snapshot = this.buffer.read(cx).read(cx);
10811 let empty_str: Arc<str> = Arc::default();
10812 let mut suffixes_inserted = Vec::new();
10813 let ignore_indent = action.ignore_indent;
10814
10815 fn comment_prefix_range(
10816 snapshot: &MultiBufferSnapshot,
10817 row: MultiBufferRow,
10818 comment_prefix: &str,
10819 comment_prefix_whitespace: &str,
10820 ignore_indent: bool,
10821 ) -> Range<Point> {
10822 let indent_size = if ignore_indent {
10823 0
10824 } else {
10825 snapshot.indent_size_for_line(row).len
10826 };
10827
10828 let start = Point::new(row.0, indent_size);
10829
10830 let mut line_bytes = snapshot
10831 .bytes_in_range(start..snapshot.max_point())
10832 .flatten()
10833 .copied();
10834
10835 // If this line currently begins with the line comment prefix, then record
10836 // the range containing the prefix.
10837 if line_bytes
10838 .by_ref()
10839 .take(comment_prefix.len())
10840 .eq(comment_prefix.bytes())
10841 {
10842 // Include any whitespace that matches the comment prefix.
10843 let matching_whitespace_len = line_bytes
10844 .zip(comment_prefix_whitespace.bytes())
10845 .take_while(|(a, b)| a == b)
10846 .count() as u32;
10847 let end = Point::new(
10848 start.row,
10849 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10850 );
10851 start..end
10852 } else {
10853 start..start
10854 }
10855 }
10856
10857 fn comment_suffix_range(
10858 snapshot: &MultiBufferSnapshot,
10859 row: MultiBufferRow,
10860 comment_suffix: &str,
10861 comment_suffix_has_leading_space: bool,
10862 ) -> Range<Point> {
10863 let end = Point::new(row.0, snapshot.line_len(row));
10864 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10865
10866 let mut line_end_bytes = snapshot
10867 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10868 .flatten()
10869 .copied();
10870
10871 let leading_space_len = if suffix_start_column > 0
10872 && line_end_bytes.next() == Some(b' ')
10873 && comment_suffix_has_leading_space
10874 {
10875 1
10876 } else {
10877 0
10878 };
10879
10880 // If this line currently begins with the line comment prefix, then record
10881 // the range containing the prefix.
10882 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10883 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10884 start..end
10885 } else {
10886 end..end
10887 }
10888 }
10889
10890 // TODO: Handle selections that cross excerpts
10891 for selection in &mut selections {
10892 let start_column = snapshot
10893 .indent_size_for_line(MultiBufferRow(selection.start.row))
10894 .len;
10895 let language = if let Some(language) =
10896 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10897 {
10898 language
10899 } else {
10900 continue;
10901 };
10902
10903 selection_edit_ranges.clear();
10904
10905 // If multiple selections contain a given row, avoid processing that
10906 // row more than once.
10907 let mut start_row = MultiBufferRow(selection.start.row);
10908 if last_toggled_row == Some(start_row) {
10909 start_row = start_row.next_row();
10910 }
10911 let end_row =
10912 if selection.end.row > selection.start.row && selection.end.column == 0 {
10913 MultiBufferRow(selection.end.row - 1)
10914 } else {
10915 MultiBufferRow(selection.end.row)
10916 };
10917 last_toggled_row = Some(end_row);
10918
10919 if start_row > end_row {
10920 continue;
10921 }
10922
10923 // If the language has line comments, toggle those.
10924 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10925
10926 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10927 if ignore_indent {
10928 full_comment_prefixes = full_comment_prefixes
10929 .into_iter()
10930 .map(|s| Arc::from(s.trim_end()))
10931 .collect();
10932 }
10933
10934 if !full_comment_prefixes.is_empty() {
10935 let first_prefix = full_comment_prefixes
10936 .first()
10937 .expect("prefixes is non-empty");
10938 let prefix_trimmed_lengths = full_comment_prefixes
10939 .iter()
10940 .map(|p| p.trim_end_matches(' ').len())
10941 .collect::<SmallVec<[usize; 4]>>();
10942
10943 let mut all_selection_lines_are_comments = true;
10944
10945 for row in start_row.0..=end_row.0 {
10946 let row = MultiBufferRow(row);
10947 if start_row < end_row && snapshot.is_line_blank(row) {
10948 continue;
10949 }
10950
10951 let prefix_range = full_comment_prefixes
10952 .iter()
10953 .zip(prefix_trimmed_lengths.iter().copied())
10954 .map(|(prefix, trimmed_prefix_len)| {
10955 comment_prefix_range(
10956 snapshot.deref(),
10957 row,
10958 &prefix[..trimmed_prefix_len],
10959 &prefix[trimmed_prefix_len..],
10960 ignore_indent,
10961 )
10962 })
10963 .max_by_key(|range| range.end.column - range.start.column)
10964 .expect("prefixes is non-empty");
10965
10966 if prefix_range.is_empty() {
10967 all_selection_lines_are_comments = false;
10968 }
10969
10970 selection_edit_ranges.push(prefix_range);
10971 }
10972
10973 if all_selection_lines_are_comments {
10974 edits.extend(
10975 selection_edit_ranges
10976 .iter()
10977 .cloned()
10978 .map(|range| (range, empty_str.clone())),
10979 );
10980 } else {
10981 let min_column = selection_edit_ranges
10982 .iter()
10983 .map(|range| range.start.column)
10984 .min()
10985 .unwrap_or(0);
10986 edits.extend(selection_edit_ranges.iter().map(|range| {
10987 let position = Point::new(range.start.row, min_column);
10988 (position..position, first_prefix.clone())
10989 }));
10990 }
10991 } else if let Some((full_comment_prefix, comment_suffix)) =
10992 language.block_comment_delimiters()
10993 {
10994 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10995 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10996 let prefix_range = comment_prefix_range(
10997 snapshot.deref(),
10998 start_row,
10999 comment_prefix,
11000 comment_prefix_whitespace,
11001 ignore_indent,
11002 );
11003 let suffix_range = comment_suffix_range(
11004 snapshot.deref(),
11005 end_row,
11006 comment_suffix.trim_start_matches(' '),
11007 comment_suffix.starts_with(' '),
11008 );
11009
11010 if prefix_range.is_empty() || suffix_range.is_empty() {
11011 edits.push((
11012 prefix_range.start..prefix_range.start,
11013 full_comment_prefix.clone(),
11014 ));
11015 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11016 suffixes_inserted.push((end_row, comment_suffix.len()));
11017 } else {
11018 edits.push((prefix_range, empty_str.clone()));
11019 edits.push((suffix_range, empty_str.clone()));
11020 }
11021 } else {
11022 continue;
11023 }
11024 }
11025
11026 drop(snapshot);
11027 this.buffer.update(cx, |buffer, cx| {
11028 buffer.edit(edits, None, cx);
11029 });
11030
11031 // Adjust selections so that they end before any comment suffixes that
11032 // were inserted.
11033 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11034 let mut selections = this.selections.all::<Point>(cx);
11035 let snapshot = this.buffer.read(cx).read(cx);
11036 for selection in &mut selections {
11037 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11038 match row.cmp(&MultiBufferRow(selection.end.row)) {
11039 Ordering::Less => {
11040 suffixes_inserted.next();
11041 continue;
11042 }
11043 Ordering::Greater => break,
11044 Ordering::Equal => {
11045 if selection.end.column == snapshot.line_len(row) {
11046 if selection.is_empty() {
11047 selection.start.column -= suffix_len as u32;
11048 }
11049 selection.end.column -= suffix_len as u32;
11050 }
11051 break;
11052 }
11053 }
11054 }
11055 }
11056
11057 drop(snapshot);
11058 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11059 s.select(selections)
11060 });
11061
11062 let selections = this.selections.all::<Point>(cx);
11063 let selections_on_single_row = selections.windows(2).all(|selections| {
11064 selections[0].start.row == selections[1].start.row
11065 && selections[0].end.row == selections[1].end.row
11066 && selections[0].start.row == selections[0].end.row
11067 });
11068 let selections_selecting = selections
11069 .iter()
11070 .any(|selection| selection.start != selection.end);
11071 let advance_downwards = action.advance_downwards
11072 && selections_on_single_row
11073 && !selections_selecting
11074 && !matches!(this.mode, EditorMode::SingleLine { .. });
11075
11076 if advance_downwards {
11077 let snapshot = this.buffer.read(cx).snapshot(cx);
11078
11079 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11080 s.move_cursors_with(|display_snapshot, display_point, _| {
11081 let mut point = display_point.to_point(display_snapshot);
11082 point.row += 1;
11083 point = snapshot.clip_point(point, Bias::Left);
11084 let display_point = point.to_display_point(display_snapshot);
11085 let goal = SelectionGoal::HorizontalPosition(
11086 display_snapshot
11087 .x_for_display_point(display_point, text_layout_details)
11088 .into(),
11089 );
11090 (display_point, goal)
11091 })
11092 });
11093 }
11094 });
11095 }
11096
11097 pub fn select_enclosing_symbol(
11098 &mut self,
11099 _: &SelectEnclosingSymbol,
11100 window: &mut Window,
11101 cx: &mut Context<Self>,
11102 ) {
11103 let buffer = self.buffer.read(cx).snapshot(cx);
11104 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11105
11106 fn update_selection(
11107 selection: &Selection<usize>,
11108 buffer_snap: &MultiBufferSnapshot,
11109 ) -> Option<Selection<usize>> {
11110 let cursor = selection.head();
11111 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11112 for symbol in symbols.iter().rev() {
11113 let start = symbol.range.start.to_offset(buffer_snap);
11114 let end = symbol.range.end.to_offset(buffer_snap);
11115 let new_range = start..end;
11116 if start < selection.start || end > selection.end {
11117 return Some(Selection {
11118 id: selection.id,
11119 start: new_range.start,
11120 end: new_range.end,
11121 goal: SelectionGoal::None,
11122 reversed: selection.reversed,
11123 });
11124 }
11125 }
11126 None
11127 }
11128
11129 let mut selected_larger_symbol = false;
11130 let new_selections = old_selections
11131 .iter()
11132 .map(|selection| match update_selection(selection, &buffer) {
11133 Some(new_selection) => {
11134 if new_selection.range() != selection.range() {
11135 selected_larger_symbol = true;
11136 }
11137 new_selection
11138 }
11139 None => selection.clone(),
11140 })
11141 .collect::<Vec<_>>();
11142
11143 if selected_larger_symbol {
11144 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11145 s.select(new_selections);
11146 });
11147 }
11148 }
11149
11150 pub fn select_larger_syntax_node(
11151 &mut self,
11152 _: &SelectLargerSyntaxNode,
11153 window: &mut Window,
11154 cx: &mut Context<Self>,
11155 ) {
11156 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11157 let buffer = self.buffer.read(cx).snapshot(cx);
11158 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11159
11160 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11161 let mut selected_larger_node = false;
11162 let new_selections = old_selections
11163 .iter()
11164 .map(|selection| {
11165 let old_range = selection.start..selection.end;
11166 let mut new_range = old_range.clone();
11167 let mut new_node = None;
11168 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11169 {
11170 new_node = Some(node);
11171 new_range = match containing_range {
11172 MultiOrSingleBufferOffsetRange::Single(_) => break,
11173 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11174 };
11175 if !display_map.intersects_fold(new_range.start)
11176 && !display_map.intersects_fold(new_range.end)
11177 {
11178 break;
11179 }
11180 }
11181
11182 if let Some(node) = new_node {
11183 // Log the ancestor, to support using this action as a way to explore TreeSitter
11184 // nodes. Parent and grandparent are also logged because this operation will not
11185 // visit nodes that have the same range as their parent.
11186 log::info!("Node: {node:?}");
11187 let parent = node.parent();
11188 log::info!("Parent: {parent:?}");
11189 let grandparent = parent.and_then(|x| x.parent());
11190 log::info!("Grandparent: {grandparent:?}");
11191 }
11192
11193 selected_larger_node |= new_range != old_range;
11194 Selection {
11195 id: selection.id,
11196 start: new_range.start,
11197 end: new_range.end,
11198 goal: SelectionGoal::None,
11199 reversed: selection.reversed,
11200 }
11201 })
11202 .collect::<Vec<_>>();
11203
11204 if selected_larger_node {
11205 stack.push(old_selections);
11206 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11207 s.select(new_selections);
11208 });
11209 }
11210 self.select_larger_syntax_node_stack = stack;
11211 }
11212
11213 pub fn select_smaller_syntax_node(
11214 &mut self,
11215 _: &SelectSmallerSyntaxNode,
11216 window: &mut Window,
11217 cx: &mut Context<Self>,
11218 ) {
11219 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11220 if let Some(selections) = stack.pop() {
11221 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11222 s.select(selections.to_vec());
11223 });
11224 }
11225 self.select_larger_syntax_node_stack = stack;
11226 }
11227
11228 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11229 if !EditorSettings::get_global(cx).gutter.runnables {
11230 self.clear_tasks();
11231 return Task::ready(());
11232 }
11233 let project = self.project.as_ref().map(Entity::downgrade);
11234 cx.spawn_in(window, |this, mut cx| async move {
11235 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11236 let Some(project) = project.and_then(|p| p.upgrade()) else {
11237 return;
11238 };
11239 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11240 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11241 }) else {
11242 return;
11243 };
11244
11245 let hide_runnables = project
11246 .update(&mut cx, |project, cx| {
11247 // Do not display any test indicators in non-dev server remote projects.
11248 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11249 })
11250 .unwrap_or(true);
11251 if hide_runnables {
11252 return;
11253 }
11254 let new_rows =
11255 cx.background_spawn({
11256 let snapshot = display_snapshot.clone();
11257 async move {
11258 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11259 }
11260 })
11261 .await;
11262
11263 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11264 this.update(&mut cx, |this, _| {
11265 this.clear_tasks();
11266 for (key, value) in rows {
11267 this.insert_tasks(key, value);
11268 }
11269 })
11270 .ok();
11271 })
11272 }
11273 fn fetch_runnable_ranges(
11274 snapshot: &DisplaySnapshot,
11275 range: Range<Anchor>,
11276 ) -> Vec<language::RunnableRange> {
11277 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11278 }
11279
11280 fn runnable_rows(
11281 project: Entity<Project>,
11282 snapshot: DisplaySnapshot,
11283 runnable_ranges: Vec<RunnableRange>,
11284 mut cx: AsyncWindowContext,
11285 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11286 runnable_ranges
11287 .into_iter()
11288 .filter_map(|mut runnable| {
11289 let tasks = cx
11290 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11291 .ok()?;
11292 if tasks.is_empty() {
11293 return None;
11294 }
11295
11296 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11297
11298 let row = snapshot
11299 .buffer_snapshot
11300 .buffer_line_for_row(MultiBufferRow(point.row))?
11301 .1
11302 .start
11303 .row;
11304
11305 let context_range =
11306 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11307 Some((
11308 (runnable.buffer_id, row),
11309 RunnableTasks {
11310 templates: tasks,
11311 offset: snapshot
11312 .buffer_snapshot
11313 .anchor_before(runnable.run_range.start),
11314 context_range,
11315 column: point.column,
11316 extra_variables: runnable.extra_captures,
11317 },
11318 ))
11319 })
11320 .collect()
11321 }
11322
11323 fn templates_with_tags(
11324 project: &Entity<Project>,
11325 runnable: &mut Runnable,
11326 cx: &mut App,
11327 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11328 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11329 let (worktree_id, file) = project
11330 .buffer_for_id(runnable.buffer, cx)
11331 .and_then(|buffer| buffer.read(cx).file())
11332 .map(|file| (file.worktree_id(cx), file.clone()))
11333 .unzip();
11334
11335 (
11336 project.task_store().read(cx).task_inventory().cloned(),
11337 worktree_id,
11338 file,
11339 )
11340 });
11341
11342 let tags = mem::take(&mut runnable.tags);
11343 let mut tags: Vec<_> = tags
11344 .into_iter()
11345 .flat_map(|tag| {
11346 let tag = tag.0.clone();
11347 inventory
11348 .as_ref()
11349 .into_iter()
11350 .flat_map(|inventory| {
11351 inventory.read(cx).list_tasks(
11352 file.clone(),
11353 Some(runnable.language.clone()),
11354 worktree_id,
11355 cx,
11356 )
11357 })
11358 .filter(move |(_, template)| {
11359 template.tags.iter().any(|source_tag| source_tag == &tag)
11360 })
11361 })
11362 .sorted_by_key(|(kind, _)| kind.to_owned())
11363 .collect();
11364 if let Some((leading_tag_source, _)) = tags.first() {
11365 // Strongest source wins; if we have worktree tag binding, prefer that to
11366 // global and language bindings;
11367 // if we have a global binding, prefer that to language binding.
11368 let first_mismatch = tags
11369 .iter()
11370 .position(|(tag_source, _)| tag_source != leading_tag_source);
11371 if let Some(index) = first_mismatch {
11372 tags.truncate(index);
11373 }
11374 }
11375
11376 tags
11377 }
11378
11379 pub fn move_to_enclosing_bracket(
11380 &mut self,
11381 _: &MoveToEnclosingBracket,
11382 window: &mut Window,
11383 cx: &mut Context<Self>,
11384 ) {
11385 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11386 s.move_offsets_with(|snapshot, selection| {
11387 let Some(enclosing_bracket_ranges) =
11388 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11389 else {
11390 return;
11391 };
11392
11393 let mut best_length = usize::MAX;
11394 let mut best_inside = false;
11395 let mut best_in_bracket_range = false;
11396 let mut best_destination = None;
11397 for (open, close) in enclosing_bracket_ranges {
11398 let close = close.to_inclusive();
11399 let length = close.end() - open.start;
11400 let inside = selection.start >= open.end && selection.end <= *close.start();
11401 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11402 || close.contains(&selection.head());
11403
11404 // If best is next to a bracket and current isn't, skip
11405 if !in_bracket_range && best_in_bracket_range {
11406 continue;
11407 }
11408
11409 // Prefer smaller lengths unless best is inside and current isn't
11410 if length > best_length && (best_inside || !inside) {
11411 continue;
11412 }
11413
11414 best_length = length;
11415 best_inside = inside;
11416 best_in_bracket_range = in_bracket_range;
11417 best_destination = Some(
11418 if close.contains(&selection.start) && close.contains(&selection.end) {
11419 if inside {
11420 open.end
11421 } else {
11422 open.start
11423 }
11424 } else if inside {
11425 *close.start()
11426 } else {
11427 *close.end()
11428 },
11429 );
11430 }
11431
11432 if let Some(destination) = best_destination {
11433 selection.collapse_to(destination, SelectionGoal::None);
11434 }
11435 })
11436 });
11437 }
11438
11439 pub fn undo_selection(
11440 &mut self,
11441 _: &UndoSelection,
11442 window: &mut Window,
11443 cx: &mut Context<Self>,
11444 ) {
11445 self.end_selection(window, cx);
11446 self.selection_history.mode = SelectionHistoryMode::Undoing;
11447 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11448 self.change_selections(None, window, cx, |s| {
11449 s.select_anchors(entry.selections.to_vec())
11450 });
11451 self.select_next_state = entry.select_next_state;
11452 self.select_prev_state = entry.select_prev_state;
11453 self.add_selections_state = entry.add_selections_state;
11454 self.request_autoscroll(Autoscroll::newest(), cx);
11455 }
11456 self.selection_history.mode = SelectionHistoryMode::Normal;
11457 }
11458
11459 pub fn redo_selection(
11460 &mut self,
11461 _: &RedoSelection,
11462 window: &mut Window,
11463 cx: &mut Context<Self>,
11464 ) {
11465 self.end_selection(window, cx);
11466 self.selection_history.mode = SelectionHistoryMode::Redoing;
11467 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11468 self.change_selections(None, window, cx, |s| {
11469 s.select_anchors(entry.selections.to_vec())
11470 });
11471 self.select_next_state = entry.select_next_state;
11472 self.select_prev_state = entry.select_prev_state;
11473 self.add_selections_state = entry.add_selections_state;
11474 self.request_autoscroll(Autoscroll::newest(), cx);
11475 }
11476 self.selection_history.mode = SelectionHistoryMode::Normal;
11477 }
11478
11479 pub fn expand_excerpts(
11480 &mut self,
11481 action: &ExpandExcerpts,
11482 _: &mut Window,
11483 cx: &mut Context<Self>,
11484 ) {
11485 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11486 }
11487
11488 pub fn expand_excerpts_down(
11489 &mut self,
11490 action: &ExpandExcerptsDown,
11491 _: &mut Window,
11492 cx: &mut Context<Self>,
11493 ) {
11494 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11495 }
11496
11497 pub fn expand_excerpts_up(
11498 &mut self,
11499 action: &ExpandExcerptsUp,
11500 _: &mut Window,
11501 cx: &mut Context<Self>,
11502 ) {
11503 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11504 }
11505
11506 pub fn expand_excerpts_for_direction(
11507 &mut self,
11508 lines: u32,
11509 direction: ExpandExcerptDirection,
11510
11511 cx: &mut Context<Self>,
11512 ) {
11513 let selections = self.selections.disjoint_anchors();
11514
11515 let lines = if lines == 0 {
11516 EditorSettings::get_global(cx).expand_excerpt_lines
11517 } else {
11518 lines
11519 };
11520
11521 self.buffer.update(cx, |buffer, cx| {
11522 let snapshot = buffer.snapshot(cx);
11523 let mut excerpt_ids = selections
11524 .iter()
11525 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11526 .collect::<Vec<_>>();
11527 excerpt_ids.sort();
11528 excerpt_ids.dedup();
11529 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11530 })
11531 }
11532
11533 pub fn expand_excerpt(
11534 &mut self,
11535 excerpt: ExcerptId,
11536 direction: ExpandExcerptDirection,
11537 cx: &mut Context<Self>,
11538 ) {
11539 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11540 self.buffer.update(cx, |buffer, cx| {
11541 buffer.expand_excerpts([excerpt], lines, direction, cx)
11542 })
11543 }
11544
11545 pub fn go_to_singleton_buffer_point(
11546 &mut self,
11547 point: Point,
11548 window: &mut Window,
11549 cx: &mut Context<Self>,
11550 ) {
11551 self.go_to_singleton_buffer_range(point..point, window, cx);
11552 }
11553
11554 pub fn go_to_singleton_buffer_range(
11555 &mut self,
11556 range: Range<Point>,
11557 window: &mut Window,
11558 cx: &mut Context<Self>,
11559 ) {
11560 let multibuffer = self.buffer().read(cx);
11561 let Some(buffer) = multibuffer.as_singleton() else {
11562 return;
11563 };
11564 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11565 return;
11566 };
11567 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11568 return;
11569 };
11570 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11571 s.select_anchor_ranges([start..end])
11572 });
11573 }
11574
11575 fn go_to_diagnostic(
11576 &mut self,
11577 _: &GoToDiagnostic,
11578 window: &mut Window,
11579 cx: &mut Context<Self>,
11580 ) {
11581 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11582 }
11583
11584 fn go_to_prev_diagnostic(
11585 &mut self,
11586 _: &GoToPreviousDiagnostic,
11587 window: &mut Window,
11588 cx: &mut Context<Self>,
11589 ) {
11590 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11591 }
11592
11593 pub fn go_to_diagnostic_impl(
11594 &mut self,
11595 direction: Direction,
11596 window: &mut Window,
11597 cx: &mut Context<Self>,
11598 ) {
11599 let buffer = self.buffer.read(cx).snapshot(cx);
11600 let selection = self.selections.newest::<usize>(cx);
11601
11602 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11603 if direction == Direction::Next {
11604 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11605 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11606 return;
11607 };
11608 self.activate_diagnostics(
11609 buffer_id,
11610 popover.local_diagnostic.diagnostic.group_id,
11611 window,
11612 cx,
11613 );
11614 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11615 let primary_range_start = active_diagnostics.primary_range.start;
11616 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11617 let mut new_selection = s.newest_anchor().clone();
11618 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11619 s.select_anchors(vec![new_selection.clone()]);
11620 });
11621 self.refresh_inline_completion(false, true, window, cx);
11622 }
11623 return;
11624 }
11625 }
11626
11627 let active_group_id = self
11628 .active_diagnostics
11629 .as_ref()
11630 .map(|active_group| active_group.group_id);
11631 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11632 active_diagnostics
11633 .primary_range
11634 .to_offset(&buffer)
11635 .to_inclusive()
11636 });
11637 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11638 if active_primary_range.contains(&selection.head()) {
11639 *active_primary_range.start()
11640 } else {
11641 selection.head()
11642 }
11643 } else {
11644 selection.head()
11645 };
11646
11647 let snapshot = self.snapshot(window, cx);
11648 let primary_diagnostics_before = buffer
11649 .diagnostics_in_range::<usize>(0..search_start)
11650 .filter(|entry| entry.diagnostic.is_primary)
11651 .filter(|entry| entry.range.start != entry.range.end)
11652 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11653 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11654 .collect::<Vec<_>>();
11655 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11656 primary_diagnostics_before
11657 .iter()
11658 .position(|entry| entry.diagnostic.group_id == active_group_id)
11659 });
11660
11661 let primary_diagnostics_after = buffer
11662 .diagnostics_in_range::<usize>(search_start..buffer.len())
11663 .filter(|entry| entry.diagnostic.is_primary)
11664 .filter(|entry| entry.range.start != entry.range.end)
11665 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11666 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11667 .collect::<Vec<_>>();
11668 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11669 primary_diagnostics_after
11670 .iter()
11671 .enumerate()
11672 .rev()
11673 .find_map(|(i, entry)| {
11674 if entry.diagnostic.group_id == active_group_id {
11675 Some(i)
11676 } else {
11677 None
11678 }
11679 })
11680 });
11681
11682 let next_primary_diagnostic = match direction {
11683 Direction::Prev => primary_diagnostics_before
11684 .iter()
11685 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11686 .rev()
11687 .next(),
11688 Direction::Next => primary_diagnostics_after
11689 .iter()
11690 .skip(
11691 last_same_group_diagnostic_after
11692 .map(|index| index + 1)
11693 .unwrap_or(0),
11694 )
11695 .next(),
11696 };
11697
11698 // Cycle around to the start of the buffer, potentially moving back to the start of
11699 // the currently active diagnostic.
11700 let cycle_around = || match direction {
11701 Direction::Prev => primary_diagnostics_after
11702 .iter()
11703 .rev()
11704 .chain(primary_diagnostics_before.iter().rev())
11705 .next(),
11706 Direction::Next => primary_diagnostics_before
11707 .iter()
11708 .chain(primary_diagnostics_after.iter())
11709 .next(),
11710 };
11711
11712 if let Some((primary_range, group_id)) = next_primary_diagnostic
11713 .or_else(cycle_around)
11714 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11715 {
11716 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11717 return;
11718 };
11719 self.activate_diagnostics(buffer_id, group_id, window, cx);
11720 if self.active_diagnostics.is_some() {
11721 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11722 s.select(vec![Selection {
11723 id: selection.id,
11724 start: primary_range.start,
11725 end: primary_range.start,
11726 reversed: false,
11727 goal: SelectionGoal::None,
11728 }]);
11729 });
11730 self.refresh_inline_completion(false, true, window, cx);
11731 }
11732 }
11733 }
11734
11735 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11736 let snapshot = self.snapshot(window, cx);
11737 let selection = self.selections.newest::<Point>(cx);
11738 self.go_to_hunk_before_or_after_position(
11739 &snapshot,
11740 selection.head(),
11741 Direction::Next,
11742 window,
11743 cx,
11744 );
11745 }
11746
11747 fn go_to_hunk_before_or_after_position(
11748 &mut self,
11749 snapshot: &EditorSnapshot,
11750 position: Point,
11751 direction: Direction,
11752 window: &mut Window,
11753 cx: &mut Context<Editor>,
11754 ) {
11755 let row = if direction == Direction::Next {
11756 self.hunk_after_position(snapshot, position)
11757 .map(|hunk| hunk.row_range.start)
11758 } else {
11759 self.hunk_before_position(snapshot, position)
11760 };
11761
11762 if let Some(row) = row {
11763 let destination = Point::new(row.0, 0);
11764 let autoscroll = Autoscroll::center();
11765
11766 self.unfold_ranges(&[destination..destination], false, false, cx);
11767 self.change_selections(Some(autoscroll), window, cx, |s| {
11768 s.select_ranges([destination..destination]);
11769 });
11770 }
11771 }
11772
11773 fn hunk_after_position(
11774 &mut self,
11775 snapshot: &EditorSnapshot,
11776 position: Point,
11777 ) -> Option<MultiBufferDiffHunk> {
11778 snapshot
11779 .buffer_snapshot
11780 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11781 .find(|hunk| hunk.row_range.start.0 > position.row)
11782 .or_else(|| {
11783 snapshot
11784 .buffer_snapshot
11785 .diff_hunks_in_range(Point::zero()..position)
11786 .find(|hunk| hunk.row_range.end.0 < position.row)
11787 })
11788 }
11789
11790 fn go_to_prev_hunk(
11791 &mut self,
11792 _: &GoToPreviousHunk,
11793 window: &mut Window,
11794 cx: &mut Context<Self>,
11795 ) {
11796 let snapshot = self.snapshot(window, cx);
11797 let selection = self.selections.newest::<Point>(cx);
11798 self.go_to_hunk_before_or_after_position(
11799 &snapshot,
11800 selection.head(),
11801 Direction::Prev,
11802 window,
11803 cx,
11804 );
11805 }
11806
11807 fn hunk_before_position(
11808 &mut self,
11809 snapshot: &EditorSnapshot,
11810 position: Point,
11811 ) -> Option<MultiBufferRow> {
11812 snapshot
11813 .buffer_snapshot
11814 .diff_hunk_before(position)
11815 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11816 }
11817
11818 pub fn go_to_definition(
11819 &mut self,
11820 _: &GoToDefinition,
11821 window: &mut Window,
11822 cx: &mut Context<Self>,
11823 ) -> Task<Result<Navigated>> {
11824 let definition =
11825 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11826 cx.spawn_in(window, |editor, mut cx| async move {
11827 if definition.await? == Navigated::Yes {
11828 return Ok(Navigated::Yes);
11829 }
11830 match editor.update_in(&mut cx, |editor, window, cx| {
11831 editor.find_all_references(&FindAllReferences, window, cx)
11832 })? {
11833 Some(references) => references.await,
11834 None => Ok(Navigated::No),
11835 }
11836 })
11837 }
11838
11839 pub fn go_to_declaration(
11840 &mut self,
11841 _: &GoToDeclaration,
11842 window: &mut Window,
11843 cx: &mut Context<Self>,
11844 ) -> Task<Result<Navigated>> {
11845 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11846 }
11847
11848 pub fn go_to_declaration_split(
11849 &mut self,
11850 _: &GoToDeclaration,
11851 window: &mut Window,
11852 cx: &mut Context<Self>,
11853 ) -> Task<Result<Navigated>> {
11854 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11855 }
11856
11857 pub fn go_to_implementation(
11858 &mut self,
11859 _: &GoToImplementation,
11860 window: &mut Window,
11861 cx: &mut Context<Self>,
11862 ) -> Task<Result<Navigated>> {
11863 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11864 }
11865
11866 pub fn go_to_implementation_split(
11867 &mut self,
11868 _: &GoToImplementationSplit,
11869 window: &mut Window,
11870 cx: &mut Context<Self>,
11871 ) -> Task<Result<Navigated>> {
11872 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11873 }
11874
11875 pub fn go_to_type_definition(
11876 &mut self,
11877 _: &GoToTypeDefinition,
11878 window: &mut Window,
11879 cx: &mut Context<Self>,
11880 ) -> Task<Result<Navigated>> {
11881 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11882 }
11883
11884 pub fn go_to_definition_split(
11885 &mut self,
11886 _: &GoToDefinitionSplit,
11887 window: &mut Window,
11888 cx: &mut Context<Self>,
11889 ) -> Task<Result<Navigated>> {
11890 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11891 }
11892
11893 pub fn go_to_type_definition_split(
11894 &mut self,
11895 _: &GoToTypeDefinitionSplit,
11896 window: &mut Window,
11897 cx: &mut Context<Self>,
11898 ) -> Task<Result<Navigated>> {
11899 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11900 }
11901
11902 fn go_to_definition_of_kind(
11903 &mut self,
11904 kind: GotoDefinitionKind,
11905 split: bool,
11906 window: &mut Window,
11907 cx: &mut Context<Self>,
11908 ) -> Task<Result<Navigated>> {
11909 let Some(provider) = self.semantics_provider.clone() else {
11910 return Task::ready(Ok(Navigated::No));
11911 };
11912 let head = self.selections.newest::<usize>(cx).head();
11913 let buffer = self.buffer.read(cx);
11914 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11915 text_anchor
11916 } else {
11917 return Task::ready(Ok(Navigated::No));
11918 };
11919
11920 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11921 return Task::ready(Ok(Navigated::No));
11922 };
11923
11924 cx.spawn_in(window, |editor, mut cx| async move {
11925 let definitions = definitions.await?;
11926 let navigated = editor
11927 .update_in(&mut cx, |editor, window, cx| {
11928 editor.navigate_to_hover_links(
11929 Some(kind),
11930 definitions
11931 .into_iter()
11932 .filter(|location| {
11933 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11934 })
11935 .map(HoverLink::Text)
11936 .collect::<Vec<_>>(),
11937 split,
11938 window,
11939 cx,
11940 )
11941 })?
11942 .await?;
11943 anyhow::Ok(navigated)
11944 })
11945 }
11946
11947 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11948 let selection = self.selections.newest_anchor();
11949 let head = selection.head();
11950 let tail = selection.tail();
11951
11952 let Some((buffer, start_position)) =
11953 self.buffer.read(cx).text_anchor_for_position(head, cx)
11954 else {
11955 return;
11956 };
11957
11958 let end_position = if head != tail {
11959 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11960 return;
11961 };
11962 Some(pos)
11963 } else {
11964 None
11965 };
11966
11967 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11968 let url = if let Some(end_pos) = end_position {
11969 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11970 } else {
11971 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11972 };
11973
11974 if let Some(url) = url {
11975 editor.update(&mut cx, |_, cx| {
11976 cx.open_url(&url);
11977 })
11978 } else {
11979 Ok(())
11980 }
11981 });
11982
11983 url_finder.detach();
11984 }
11985
11986 pub fn open_selected_filename(
11987 &mut self,
11988 _: &OpenSelectedFilename,
11989 window: &mut Window,
11990 cx: &mut Context<Self>,
11991 ) {
11992 let Some(workspace) = self.workspace() else {
11993 return;
11994 };
11995
11996 let position = self.selections.newest_anchor().head();
11997
11998 let Some((buffer, buffer_position)) =
11999 self.buffer.read(cx).text_anchor_for_position(position, cx)
12000 else {
12001 return;
12002 };
12003
12004 let project = self.project.clone();
12005
12006 cx.spawn_in(window, |_, mut cx| async move {
12007 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
12008
12009 if let Some((_, path)) = result {
12010 workspace
12011 .update_in(&mut cx, |workspace, window, cx| {
12012 workspace.open_resolved_path(path, window, cx)
12013 })?
12014 .await?;
12015 }
12016 anyhow::Ok(())
12017 })
12018 .detach();
12019 }
12020
12021 pub(crate) fn navigate_to_hover_links(
12022 &mut self,
12023 kind: Option<GotoDefinitionKind>,
12024 mut definitions: Vec<HoverLink>,
12025 split: bool,
12026 window: &mut Window,
12027 cx: &mut Context<Editor>,
12028 ) -> Task<Result<Navigated>> {
12029 // If there is one definition, just open it directly
12030 if definitions.len() == 1 {
12031 let definition = definitions.pop().unwrap();
12032
12033 enum TargetTaskResult {
12034 Location(Option<Location>),
12035 AlreadyNavigated,
12036 }
12037
12038 let target_task = match definition {
12039 HoverLink::Text(link) => {
12040 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12041 }
12042 HoverLink::InlayHint(lsp_location, server_id) => {
12043 let computation =
12044 self.compute_target_location(lsp_location, server_id, window, cx);
12045 cx.background_spawn(async move {
12046 let location = computation.await?;
12047 Ok(TargetTaskResult::Location(location))
12048 })
12049 }
12050 HoverLink::Url(url) => {
12051 cx.open_url(&url);
12052 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12053 }
12054 HoverLink::File(path) => {
12055 if let Some(workspace) = self.workspace() {
12056 cx.spawn_in(window, |_, mut cx| async move {
12057 workspace
12058 .update_in(&mut cx, |workspace, window, cx| {
12059 workspace.open_resolved_path(path, window, cx)
12060 })?
12061 .await
12062 .map(|_| TargetTaskResult::AlreadyNavigated)
12063 })
12064 } else {
12065 Task::ready(Ok(TargetTaskResult::Location(None)))
12066 }
12067 }
12068 };
12069 cx.spawn_in(window, |editor, mut cx| async move {
12070 let target = match target_task.await.context("target resolution task")? {
12071 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12072 TargetTaskResult::Location(None) => return Ok(Navigated::No),
12073 TargetTaskResult::Location(Some(target)) => target,
12074 };
12075
12076 editor.update_in(&mut cx, |editor, window, cx| {
12077 let Some(workspace) = editor.workspace() else {
12078 return Navigated::No;
12079 };
12080 let pane = workspace.read(cx).active_pane().clone();
12081
12082 let range = target.range.to_point(target.buffer.read(cx));
12083 let range = editor.range_for_match(&range);
12084 let range = collapse_multiline_range(range);
12085
12086 if !split
12087 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12088 {
12089 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12090 } else {
12091 window.defer(cx, move |window, cx| {
12092 let target_editor: Entity<Self> =
12093 workspace.update(cx, |workspace, cx| {
12094 let pane = if split {
12095 workspace.adjacent_pane(window, cx)
12096 } else {
12097 workspace.active_pane().clone()
12098 };
12099
12100 workspace.open_project_item(
12101 pane,
12102 target.buffer.clone(),
12103 true,
12104 true,
12105 window,
12106 cx,
12107 )
12108 });
12109 target_editor.update(cx, |target_editor, cx| {
12110 // When selecting a definition in a different buffer, disable the nav history
12111 // to avoid creating a history entry at the previous cursor location.
12112 pane.update(cx, |pane, _| pane.disable_history());
12113 target_editor.go_to_singleton_buffer_range(range, window, cx);
12114 pane.update(cx, |pane, _| pane.enable_history());
12115 });
12116 });
12117 }
12118 Navigated::Yes
12119 })
12120 })
12121 } else if !definitions.is_empty() {
12122 cx.spawn_in(window, |editor, mut cx| async move {
12123 let (title, location_tasks, workspace) = editor
12124 .update_in(&mut cx, |editor, window, cx| {
12125 let tab_kind = match kind {
12126 Some(GotoDefinitionKind::Implementation) => "Implementations",
12127 _ => "Definitions",
12128 };
12129 let title = definitions
12130 .iter()
12131 .find_map(|definition| match definition {
12132 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12133 let buffer = origin.buffer.read(cx);
12134 format!(
12135 "{} for {}",
12136 tab_kind,
12137 buffer
12138 .text_for_range(origin.range.clone())
12139 .collect::<String>()
12140 )
12141 }),
12142 HoverLink::InlayHint(_, _) => None,
12143 HoverLink::Url(_) => None,
12144 HoverLink::File(_) => None,
12145 })
12146 .unwrap_or(tab_kind.to_string());
12147 let location_tasks = definitions
12148 .into_iter()
12149 .map(|definition| match definition {
12150 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12151 HoverLink::InlayHint(lsp_location, server_id) => editor
12152 .compute_target_location(lsp_location, server_id, window, cx),
12153 HoverLink::Url(_) => Task::ready(Ok(None)),
12154 HoverLink::File(_) => Task::ready(Ok(None)),
12155 })
12156 .collect::<Vec<_>>();
12157 (title, location_tasks, editor.workspace().clone())
12158 })
12159 .context("location tasks preparation")?;
12160
12161 let locations = future::join_all(location_tasks)
12162 .await
12163 .into_iter()
12164 .filter_map(|location| location.transpose())
12165 .collect::<Result<_>>()
12166 .context("location tasks")?;
12167
12168 let Some(workspace) = workspace else {
12169 return Ok(Navigated::No);
12170 };
12171 let opened = workspace
12172 .update_in(&mut cx, |workspace, window, cx| {
12173 Self::open_locations_in_multibuffer(
12174 workspace,
12175 locations,
12176 title,
12177 split,
12178 MultibufferSelectionMode::First,
12179 window,
12180 cx,
12181 )
12182 })
12183 .ok();
12184
12185 anyhow::Ok(Navigated::from_bool(opened.is_some()))
12186 })
12187 } else {
12188 Task::ready(Ok(Navigated::No))
12189 }
12190 }
12191
12192 fn compute_target_location(
12193 &self,
12194 lsp_location: lsp::Location,
12195 server_id: LanguageServerId,
12196 window: &mut Window,
12197 cx: &mut Context<Self>,
12198 ) -> Task<anyhow::Result<Option<Location>>> {
12199 let Some(project) = self.project.clone() else {
12200 return Task::ready(Ok(None));
12201 };
12202
12203 cx.spawn_in(window, move |editor, mut cx| async move {
12204 let location_task = editor.update(&mut cx, |_, cx| {
12205 project.update(cx, |project, cx| {
12206 let language_server_name = project
12207 .language_server_statuses(cx)
12208 .find(|(id, _)| server_id == *id)
12209 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12210 language_server_name.map(|language_server_name| {
12211 project.open_local_buffer_via_lsp(
12212 lsp_location.uri.clone(),
12213 server_id,
12214 language_server_name,
12215 cx,
12216 )
12217 })
12218 })
12219 })?;
12220 let location = match location_task {
12221 Some(task) => Some({
12222 let target_buffer_handle = task.await.context("open local buffer")?;
12223 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12224 let target_start = target_buffer
12225 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12226 let target_end = target_buffer
12227 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12228 target_buffer.anchor_after(target_start)
12229 ..target_buffer.anchor_before(target_end)
12230 })?;
12231 Location {
12232 buffer: target_buffer_handle,
12233 range,
12234 }
12235 }),
12236 None => None,
12237 };
12238 Ok(location)
12239 })
12240 }
12241
12242 pub fn find_all_references(
12243 &mut self,
12244 _: &FindAllReferences,
12245 window: &mut Window,
12246 cx: &mut Context<Self>,
12247 ) -> Option<Task<Result<Navigated>>> {
12248 let selection = self.selections.newest::<usize>(cx);
12249 let multi_buffer = self.buffer.read(cx);
12250 let head = selection.head();
12251
12252 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12253 let head_anchor = multi_buffer_snapshot.anchor_at(
12254 head,
12255 if head < selection.tail() {
12256 Bias::Right
12257 } else {
12258 Bias::Left
12259 },
12260 );
12261
12262 match self
12263 .find_all_references_task_sources
12264 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12265 {
12266 Ok(_) => {
12267 log::info!(
12268 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12269 );
12270 return None;
12271 }
12272 Err(i) => {
12273 self.find_all_references_task_sources.insert(i, head_anchor);
12274 }
12275 }
12276
12277 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12278 let workspace = self.workspace()?;
12279 let project = workspace.read(cx).project().clone();
12280 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12281 Some(cx.spawn_in(window, |editor, mut cx| async move {
12282 let _cleanup = defer({
12283 let mut cx = cx.clone();
12284 move || {
12285 let _ = editor.update(&mut cx, |editor, _| {
12286 if let Ok(i) =
12287 editor
12288 .find_all_references_task_sources
12289 .binary_search_by(|anchor| {
12290 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12291 })
12292 {
12293 editor.find_all_references_task_sources.remove(i);
12294 }
12295 });
12296 }
12297 });
12298
12299 let locations = references.await?;
12300 if locations.is_empty() {
12301 return anyhow::Ok(Navigated::No);
12302 }
12303
12304 workspace.update_in(&mut cx, |workspace, window, cx| {
12305 let title = locations
12306 .first()
12307 .as_ref()
12308 .map(|location| {
12309 let buffer = location.buffer.read(cx);
12310 format!(
12311 "References to `{}`",
12312 buffer
12313 .text_for_range(location.range.clone())
12314 .collect::<String>()
12315 )
12316 })
12317 .unwrap();
12318 Self::open_locations_in_multibuffer(
12319 workspace,
12320 locations,
12321 title,
12322 false,
12323 MultibufferSelectionMode::First,
12324 window,
12325 cx,
12326 );
12327 Navigated::Yes
12328 })
12329 }))
12330 }
12331
12332 /// Opens a multibuffer with the given project locations in it
12333 pub fn open_locations_in_multibuffer(
12334 workspace: &mut Workspace,
12335 mut locations: Vec<Location>,
12336 title: String,
12337 split: bool,
12338 multibuffer_selection_mode: MultibufferSelectionMode,
12339 window: &mut Window,
12340 cx: &mut Context<Workspace>,
12341 ) {
12342 // If there are multiple definitions, open them in a multibuffer
12343 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12344 let mut locations = locations.into_iter().peekable();
12345 let mut ranges = Vec::new();
12346 let capability = workspace.project().read(cx).capability();
12347
12348 let excerpt_buffer = cx.new(|cx| {
12349 let mut multibuffer = MultiBuffer::new(capability);
12350 while let Some(location) = locations.next() {
12351 let buffer = location.buffer.read(cx);
12352 let mut ranges_for_buffer = Vec::new();
12353 let range = location.range.to_offset(buffer);
12354 ranges_for_buffer.push(range.clone());
12355
12356 while let Some(next_location) = locations.peek() {
12357 if next_location.buffer == location.buffer {
12358 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12359 locations.next();
12360 } else {
12361 break;
12362 }
12363 }
12364
12365 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12366 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12367 location.buffer.clone(),
12368 ranges_for_buffer,
12369 DEFAULT_MULTIBUFFER_CONTEXT,
12370 cx,
12371 ))
12372 }
12373
12374 multibuffer.with_title(title)
12375 });
12376
12377 let editor = cx.new(|cx| {
12378 Editor::for_multibuffer(
12379 excerpt_buffer,
12380 Some(workspace.project().clone()),
12381 true,
12382 window,
12383 cx,
12384 )
12385 });
12386 editor.update(cx, |editor, cx| {
12387 match multibuffer_selection_mode {
12388 MultibufferSelectionMode::First => {
12389 if let Some(first_range) = ranges.first() {
12390 editor.change_selections(None, window, cx, |selections| {
12391 selections.clear_disjoint();
12392 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12393 });
12394 }
12395 editor.highlight_background::<Self>(
12396 &ranges,
12397 |theme| theme.editor_highlighted_line_background,
12398 cx,
12399 );
12400 }
12401 MultibufferSelectionMode::All => {
12402 editor.change_selections(None, window, cx, |selections| {
12403 selections.clear_disjoint();
12404 selections.select_anchor_ranges(ranges);
12405 });
12406 }
12407 }
12408 editor.register_buffers_with_language_servers(cx);
12409 });
12410
12411 let item = Box::new(editor);
12412 let item_id = item.item_id();
12413
12414 if split {
12415 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12416 } else {
12417 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12418 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12419 pane.close_current_preview_item(window, cx)
12420 } else {
12421 None
12422 }
12423 });
12424 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12425 }
12426 workspace.active_pane().update(cx, |pane, cx| {
12427 pane.set_preview_item_id(Some(item_id), cx);
12428 });
12429 }
12430
12431 pub fn rename(
12432 &mut self,
12433 _: &Rename,
12434 window: &mut Window,
12435 cx: &mut Context<Self>,
12436 ) -> Option<Task<Result<()>>> {
12437 use language::ToOffset as _;
12438
12439 let provider = self.semantics_provider.clone()?;
12440 let selection = self.selections.newest_anchor().clone();
12441 let (cursor_buffer, cursor_buffer_position) = self
12442 .buffer
12443 .read(cx)
12444 .text_anchor_for_position(selection.head(), cx)?;
12445 let (tail_buffer, cursor_buffer_position_end) = self
12446 .buffer
12447 .read(cx)
12448 .text_anchor_for_position(selection.tail(), cx)?;
12449 if tail_buffer != cursor_buffer {
12450 return None;
12451 }
12452
12453 let snapshot = cursor_buffer.read(cx).snapshot();
12454 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12455 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12456 let prepare_rename = provider
12457 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12458 .unwrap_or_else(|| Task::ready(Ok(None)));
12459 drop(snapshot);
12460
12461 Some(cx.spawn_in(window, |this, mut cx| async move {
12462 let rename_range = if let Some(range) = prepare_rename.await? {
12463 Some(range)
12464 } else {
12465 this.update(&mut cx, |this, cx| {
12466 let buffer = this.buffer.read(cx).snapshot(cx);
12467 let mut buffer_highlights = this
12468 .document_highlights_for_position(selection.head(), &buffer)
12469 .filter(|highlight| {
12470 highlight.start.excerpt_id == selection.head().excerpt_id
12471 && highlight.end.excerpt_id == selection.head().excerpt_id
12472 });
12473 buffer_highlights
12474 .next()
12475 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12476 })?
12477 };
12478 if let Some(rename_range) = rename_range {
12479 this.update_in(&mut cx, |this, window, cx| {
12480 let snapshot = cursor_buffer.read(cx).snapshot();
12481 let rename_buffer_range = rename_range.to_offset(&snapshot);
12482 let cursor_offset_in_rename_range =
12483 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12484 let cursor_offset_in_rename_range_end =
12485 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12486
12487 this.take_rename(false, window, cx);
12488 let buffer = this.buffer.read(cx).read(cx);
12489 let cursor_offset = selection.head().to_offset(&buffer);
12490 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12491 let rename_end = rename_start + rename_buffer_range.len();
12492 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12493 let mut old_highlight_id = None;
12494 let old_name: Arc<str> = buffer
12495 .chunks(rename_start..rename_end, true)
12496 .map(|chunk| {
12497 if old_highlight_id.is_none() {
12498 old_highlight_id = chunk.syntax_highlight_id;
12499 }
12500 chunk.text
12501 })
12502 .collect::<String>()
12503 .into();
12504
12505 drop(buffer);
12506
12507 // Position the selection in the rename editor so that it matches the current selection.
12508 this.show_local_selections = false;
12509 let rename_editor = cx.new(|cx| {
12510 let mut editor = Editor::single_line(window, cx);
12511 editor.buffer.update(cx, |buffer, cx| {
12512 buffer.edit([(0..0, old_name.clone())], None, cx)
12513 });
12514 let rename_selection_range = match cursor_offset_in_rename_range
12515 .cmp(&cursor_offset_in_rename_range_end)
12516 {
12517 Ordering::Equal => {
12518 editor.select_all(&SelectAll, window, cx);
12519 return editor;
12520 }
12521 Ordering::Less => {
12522 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12523 }
12524 Ordering::Greater => {
12525 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12526 }
12527 };
12528 if rename_selection_range.end > old_name.len() {
12529 editor.select_all(&SelectAll, window, cx);
12530 } else {
12531 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12532 s.select_ranges([rename_selection_range]);
12533 });
12534 }
12535 editor
12536 });
12537 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12538 if e == &EditorEvent::Focused {
12539 cx.emit(EditorEvent::FocusedIn)
12540 }
12541 })
12542 .detach();
12543
12544 let write_highlights =
12545 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12546 let read_highlights =
12547 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12548 let ranges = write_highlights
12549 .iter()
12550 .flat_map(|(_, ranges)| ranges.iter())
12551 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12552 .cloned()
12553 .collect();
12554
12555 this.highlight_text::<Rename>(
12556 ranges,
12557 HighlightStyle {
12558 fade_out: Some(0.6),
12559 ..Default::default()
12560 },
12561 cx,
12562 );
12563 let rename_focus_handle = rename_editor.focus_handle(cx);
12564 window.focus(&rename_focus_handle);
12565 let block_id = this.insert_blocks(
12566 [BlockProperties {
12567 style: BlockStyle::Flex,
12568 placement: BlockPlacement::Below(range.start),
12569 height: 1,
12570 render: Arc::new({
12571 let rename_editor = rename_editor.clone();
12572 move |cx: &mut BlockContext| {
12573 let mut text_style = cx.editor_style.text.clone();
12574 if let Some(highlight_style) = old_highlight_id
12575 .and_then(|h| h.style(&cx.editor_style.syntax))
12576 {
12577 text_style = text_style.highlight(highlight_style);
12578 }
12579 div()
12580 .block_mouse_down()
12581 .pl(cx.anchor_x)
12582 .child(EditorElement::new(
12583 &rename_editor,
12584 EditorStyle {
12585 background: cx.theme().system().transparent,
12586 local_player: cx.editor_style.local_player,
12587 text: text_style,
12588 scrollbar_width: cx.editor_style.scrollbar_width,
12589 syntax: cx.editor_style.syntax.clone(),
12590 status: cx.editor_style.status.clone(),
12591 inlay_hints_style: HighlightStyle {
12592 font_weight: Some(FontWeight::BOLD),
12593 ..make_inlay_hints_style(cx.app)
12594 },
12595 inline_completion_styles: make_suggestion_styles(
12596 cx.app,
12597 ),
12598 ..EditorStyle::default()
12599 },
12600 ))
12601 .into_any_element()
12602 }
12603 }),
12604 priority: 0,
12605 }],
12606 Some(Autoscroll::fit()),
12607 cx,
12608 )[0];
12609 this.pending_rename = Some(RenameState {
12610 range,
12611 old_name,
12612 editor: rename_editor,
12613 block_id,
12614 });
12615 })?;
12616 }
12617
12618 Ok(())
12619 }))
12620 }
12621
12622 pub fn confirm_rename(
12623 &mut self,
12624 _: &ConfirmRename,
12625 window: &mut Window,
12626 cx: &mut Context<Self>,
12627 ) -> Option<Task<Result<()>>> {
12628 let rename = self.take_rename(false, window, cx)?;
12629 let workspace = self.workspace()?.downgrade();
12630 let (buffer, start) = self
12631 .buffer
12632 .read(cx)
12633 .text_anchor_for_position(rename.range.start, cx)?;
12634 let (end_buffer, _) = self
12635 .buffer
12636 .read(cx)
12637 .text_anchor_for_position(rename.range.end, cx)?;
12638 if buffer != end_buffer {
12639 return None;
12640 }
12641
12642 let old_name = rename.old_name;
12643 let new_name = rename.editor.read(cx).text(cx);
12644
12645 let rename = self.semantics_provider.as_ref()?.perform_rename(
12646 &buffer,
12647 start,
12648 new_name.clone(),
12649 cx,
12650 )?;
12651
12652 Some(cx.spawn_in(window, |editor, mut cx| async move {
12653 let project_transaction = rename.await?;
12654 Self::open_project_transaction(
12655 &editor,
12656 workspace,
12657 project_transaction,
12658 format!("Rename: {} → {}", old_name, new_name),
12659 cx.clone(),
12660 )
12661 .await?;
12662
12663 editor.update(&mut cx, |editor, cx| {
12664 editor.refresh_document_highlights(cx);
12665 })?;
12666 Ok(())
12667 }))
12668 }
12669
12670 fn take_rename(
12671 &mut self,
12672 moving_cursor: bool,
12673 window: &mut Window,
12674 cx: &mut Context<Self>,
12675 ) -> Option<RenameState> {
12676 let rename = self.pending_rename.take()?;
12677 if rename.editor.focus_handle(cx).is_focused(window) {
12678 window.focus(&self.focus_handle);
12679 }
12680
12681 self.remove_blocks(
12682 [rename.block_id].into_iter().collect(),
12683 Some(Autoscroll::fit()),
12684 cx,
12685 );
12686 self.clear_highlights::<Rename>(cx);
12687 self.show_local_selections = true;
12688
12689 if moving_cursor {
12690 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12691 editor.selections.newest::<usize>(cx).head()
12692 });
12693
12694 // Update the selection to match the position of the selection inside
12695 // the rename editor.
12696 let snapshot = self.buffer.read(cx).read(cx);
12697 let rename_range = rename.range.to_offset(&snapshot);
12698 let cursor_in_editor = snapshot
12699 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12700 .min(rename_range.end);
12701 drop(snapshot);
12702
12703 self.change_selections(None, window, cx, |s| {
12704 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12705 });
12706 } else {
12707 self.refresh_document_highlights(cx);
12708 }
12709
12710 Some(rename)
12711 }
12712
12713 pub fn pending_rename(&self) -> Option<&RenameState> {
12714 self.pending_rename.as_ref()
12715 }
12716
12717 fn format(
12718 &mut self,
12719 _: &Format,
12720 window: &mut Window,
12721 cx: &mut Context<Self>,
12722 ) -> Option<Task<Result<()>>> {
12723 let project = match &self.project {
12724 Some(project) => project.clone(),
12725 None => return None,
12726 };
12727
12728 Some(self.perform_format(
12729 project,
12730 FormatTrigger::Manual,
12731 FormatTarget::Buffers,
12732 window,
12733 cx,
12734 ))
12735 }
12736
12737 fn format_selections(
12738 &mut self,
12739 _: &FormatSelections,
12740 window: &mut Window,
12741 cx: &mut Context<Self>,
12742 ) -> Option<Task<Result<()>>> {
12743 let project = match &self.project {
12744 Some(project) => project.clone(),
12745 None => return None,
12746 };
12747
12748 let ranges = self
12749 .selections
12750 .all_adjusted(cx)
12751 .into_iter()
12752 .map(|selection| selection.range())
12753 .collect_vec();
12754
12755 Some(self.perform_format(
12756 project,
12757 FormatTrigger::Manual,
12758 FormatTarget::Ranges(ranges),
12759 window,
12760 cx,
12761 ))
12762 }
12763
12764 fn perform_format(
12765 &mut self,
12766 project: Entity<Project>,
12767 trigger: FormatTrigger,
12768 target: FormatTarget,
12769 window: &mut Window,
12770 cx: &mut Context<Self>,
12771 ) -> Task<Result<()>> {
12772 let buffer = self.buffer.clone();
12773 let (buffers, target) = match target {
12774 FormatTarget::Buffers => {
12775 let mut buffers = buffer.read(cx).all_buffers();
12776 if trigger == FormatTrigger::Save {
12777 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12778 }
12779 (buffers, LspFormatTarget::Buffers)
12780 }
12781 FormatTarget::Ranges(selection_ranges) => {
12782 let multi_buffer = buffer.read(cx);
12783 let snapshot = multi_buffer.read(cx);
12784 let mut buffers = HashSet::default();
12785 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12786 BTreeMap::new();
12787 for selection_range in selection_ranges {
12788 for (buffer, buffer_range, _) in
12789 snapshot.range_to_buffer_ranges(selection_range)
12790 {
12791 let buffer_id = buffer.remote_id();
12792 let start = buffer.anchor_before(buffer_range.start);
12793 let end = buffer.anchor_after(buffer_range.end);
12794 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12795 buffer_id_to_ranges
12796 .entry(buffer_id)
12797 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12798 .or_insert_with(|| vec![start..end]);
12799 }
12800 }
12801 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12802 }
12803 };
12804
12805 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12806 let format = project.update(cx, |project, cx| {
12807 project.format(buffers, target, true, trigger, cx)
12808 });
12809
12810 cx.spawn_in(window, |_, mut cx| async move {
12811 let transaction = futures::select_biased! {
12812 () = timeout => {
12813 log::warn!("timed out waiting for formatting");
12814 None
12815 }
12816 transaction = format.log_err().fuse() => transaction,
12817 };
12818
12819 buffer
12820 .update(&mut cx, |buffer, cx| {
12821 if let Some(transaction) = transaction {
12822 if !buffer.is_singleton() {
12823 buffer.push_transaction(&transaction.0, cx);
12824 }
12825 }
12826 cx.notify();
12827 })
12828 .ok();
12829
12830 Ok(())
12831 })
12832 }
12833
12834 fn organize_imports(
12835 &mut self,
12836 _: &OrganizeImports,
12837 window: &mut Window,
12838 cx: &mut Context<Self>,
12839 ) -> Option<Task<Result<()>>> {
12840 let project = match &self.project {
12841 Some(project) => project.clone(),
12842 None => return None,
12843 };
12844 Some(self.perform_code_action_kind(
12845 project,
12846 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12847 window,
12848 cx,
12849 ))
12850 }
12851
12852 fn perform_code_action_kind(
12853 &mut self,
12854 project: Entity<Project>,
12855 kind: CodeActionKind,
12856 window: &mut Window,
12857 cx: &mut Context<Self>,
12858 ) -> Task<Result<()>> {
12859 let buffer = self.buffer.clone();
12860 let buffers = buffer.read(cx).all_buffers();
12861 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12862 let apply_action = project.update(cx, |project, cx| {
12863 project.apply_code_action_kind(buffers, kind, true, cx)
12864 });
12865 cx.spawn_in(window, |_, mut cx| async move {
12866 let transaction = futures::select_biased! {
12867 () = timeout => {
12868 log::warn!("timed out waiting for executing code action");
12869 None
12870 }
12871 transaction = apply_action.log_err().fuse() => transaction,
12872 };
12873 buffer
12874 .update(&mut cx, |buffer, cx| {
12875 // check if we need this
12876 if let Some(transaction) = transaction {
12877 if !buffer.is_singleton() {
12878 buffer.push_transaction(&transaction.0, cx);
12879 }
12880 }
12881 cx.notify();
12882 })
12883 .ok();
12884 Ok(())
12885 })
12886 }
12887
12888 fn restart_language_server(
12889 &mut self,
12890 _: &RestartLanguageServer,
12891 _: &mut Window,
12892 cx: &mut Context<Self>,
12893 ) {
12894 if let Some(project) = self.project.clone() {
12895 self.buffer.update(cx, |multi_buffer, cx| {
12896 project.update(cx, |project, cx| {
12897 project.restart_language_servers_for_buffers(
12898 multi_buffer.all_buffers().into_iter().collect(),
12899 cx,
12900 );
12901 });
12902 })
12903 }
12904 }
12905
12906 fn cancel_language_server_work(
12907 workspace: &mut Workspace,
12908 _: &actions::CancelLanguageServerWork,
12909 _: &mut Window,
12910 cx: &mut Context<Workspace>,
12911 ) {
12912 let project = workspace.project();
12913 let buffers = workspace
12914 .active_item(cx)
12915 .and_then(|item| item.act_as::<Editor>(cx))
12916 .map_or(HashSet::default(), |editor| {
12917 editor.read(cx).buffer.read(cx).all_buffers()
12918 });
12919 project.update(cx, |project, cx| {
12920 project.cancel_language_server_work_for_buffers(buffers, cx);
12921 });
12922 }
12923
12924 fn show_character_palette(
12925 &mut self,
12926 _: &ShowCharacterPalette,
12927 window: &mut Window,
12928 _: &mut Context<Self>,
12929 ) {
12930 window.show_character_palette();
12931 }
12932
12933 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12934 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12935 let buffer = self.buffer.read(cx).snapshot(cx);
12936 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12937 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12938 let is_valid = buffer
12939 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12940 .any(|entry| {
12941 entry.diagnostic.is_primary
12942 && !entry.range.is_empty()
12943 && entry.range.start == primary_range_start
12944 && entry.diagnostic.message == active_diagnostics.primary_message
12945 });
12946
12947 if is_valid != active_diagnostics.is_valid {
12948 active_diagnostics.is_valid = is_valid;
12949 if is_valid {
12950 let mut new_styles = HashMap::default();
12951 for (block_id, diagnostic) in &active_diagnostics.blocks {
12952 new_styles.insert(
12953 *block_id,
12954 diagnostic_block_renderer(diagnostic.clone(), None, true),
12955 );
12956 }
12957 self.display_map.update(cx, |display_map, _cx| {
12958 display_map.replace_blocks(new_styles);
12959 });
12960 } else {
12961 self.dismiss_diagnostics(cx);
12962 }
12963 }
12964 }
12965 }
12966
12967 fn activate_diagnostics(
12968 &mut self,
12969 buffer_id: BufferId,
12970 group_id: usize,
12971 window: &mut Window,
12972 cx: &mut Context<Self>,
12973 ) {
12974 self.dismiss_diagnostics(cx);
12975 let snapshot = self.snapshot(window, cx);
12976 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12977 let buffer = self.buffer.read(cx).snapshot(cx);
12978
12979 let mut primary_range = None;
12980 let mut primary_message = None;
12981 let diagnostic_group = buffer
12982 .diagnostic_group(buffer_id, group_id)
12983 .filter_map(|entry| {
12984 let start = entry.range.start;
12985 let end = entry.range.end;
12986 if snapshot.is_line_folded(MultiBufferRow(start.row))
12987 && (start.row == end.row
12988 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12989 {
12990 return None;
12991 }
12992 if entry.diagnostic.is_primary {
12993 primary_range = Some(entry.range.clone());
12994 primary_message = Some(entry.diagnostic.message.clone());
12995 }
12996 Some(entry)
12997 })
12998 .collect::<Vec<_>>();
12999 let primary_range = primary_range?;
13000 let primary_message = primary_message?;
13001
13002 let blocks = display_map
13003 .insert_blocks(
13004 diagnostic_group.iter().map(|entry| {
13005 let diagnostic = entry.diagnostic.clone();
13006 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13007 BlockProperties {
13008 style: BlockStyle::Fixed,
13009 placement: BlockPlacement::Below(
13010 buffer.anchor_after(entry.range.start),
13011 ),
13012 height: message_height,
13013 render: diagnostic_block_renderer(diagnostic, None, true),
13014 priority: 0,
13015 }
13016 }),
13017 cx,
13018 )
13019 .into_iter()
13020 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13021 .collect();
13022
13023 Some(ActiveDiagnosticGroup {
13024 primary_range: buffer.anchor_before(primary_range.start)
13025 ..buffer.anchor_after(primary_range.end),
13026 primary_message,
13027 group_id,
13028 blocks,
13029 is_valid: true,
13030 })
13031 });
13032 }
13033
13034 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13035 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13036 self.display_map.update(cx, |display_map, cx| {
13037 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13038 });
13039 cx.notify();
13040 }
13041 }
13042
13043 /// Disable inline diagnostics rendering for this editor.
13044 pub fn disable_inline_diagnostics(&mut self) {
13045 self.inline_diagnostics_enabled = false;
13046 self.inline_diagnostics_update = Task::ready(());
13047 self.inline_diagnostics.clear();
13048 }
13049
13050 pub fn inline_diagnostics_enabled(&self) -> bool {
13051 self.inline_diagnostics_enabled
13052 }
13053
13054 pub fn show_inline_diagnostics(&self) -> bool {
13055 self.show_inline_diagnostics
13056 }
13057
13058 pub fn toggle_inline_diagnostics(
13059 &mut self,
13060 _: &ToggleInlineDiagnostics,
13061 window: &mut Window,
13062 cx: &mut Context<'_, Editor>,
13063 ) {
13064 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13065 self.refresh_inline_diagnostics(false, window, cx);
13066 }
13067
13068 fn refresh_inline_diagnostics(
13069 &mut self,
13070 debounce: bool,
13071 window: &mut Window,
13072 cx: &mut Context<Self>,
13073 ) {
13074 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13075 self.inline_diagnostics_update = Task::ready(());
13076 self.inline_diagnostics.clear();
13077 return;
13078 }
13079
13080 let debounce_ms = ProjectSettings::get_global(cx)
13081 .diagnostics
13082 .inline
13083 .update_debounce_ms;
13084 let debounce = if debounce && debounce_ms > 0 {
13085 Some(Duration::from_millis(debounce_ms))
13086 } else {
13087 None
13088 };
13089 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
13090 if let Some(debounce) = debounce {
13091 cx.background_executor().timer(debounce).await;
13092 }
13093 let Some(snapshot) = editor
13094 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13095 .ok()
13096 else {
13097 return;
13098 };
13099
13100 let new_inline_diagnostics = cx
13101 .background_spawn(async move {
13102 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13103 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13104 let message = diagnostic_entry
13105 .diagnostic
13106 .message
13107 .split_once('\n')
13108 .map(|(line, _)| line)
13109 .map(SharedString::new)
13110 .unwrap_or_else(|| {
13111 SharedString::from(diagnostic_entry.diagnostic.message)
13112 });
13113 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13114 let (Ok(i) | Err(i)) = inline_diagnostics
13115 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13116 inline_diagnostics.insert(
13117 i,
13118 (
13119 start_anchor,
13120 InlineDiagnostic {
13121 message,
13122 group_id: diagnostic_entry.diagnostic.group_id,
13123 start: diagnostic_entry.range.start.to_point(&snapshot),
13124 is_primary: diagnostic_entry.diagnostic.is_primary,
13125 severity: diagnostic_entry.diagnostic.severity,
13126 },
13127 ),
13128 );
13129 }
13130 inline_diagnostics
13131 })
13132 .await;
13133
13134 editor
13135 .update(&mut cx, |editor, cx| {
13136 editor.inline_diagnostics = new_inline_diagnostics;
13137 cx.notify();
13138 })
13139 .ok();
13140 });
13141 }
13142
13143 pub fn set_selections_from_remote(
13144 &mut self,
13145 selections: Vec<Selection<Anchor>>,
13146 pending_selection: Option<Selection<Anchor>>,
13147 window: &mut Window,
13148 cx: &mut Context<Self>,
13149 ) {
13150 let old_cursor_position = self.selections.newest_anchor().head();
13151 self.selections.change_with(cx, |s| {
13152 s.select_anchors(selections);
13153 if let Some(pending_selection) = pending_selection {
13154 s.set_pending(pending_selection, SelectMode::Character);
13155 } else {
13156 s.clear_pending();
13157 }
13158 });
13159 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13160 }
13161
13162 fn push_to_selection_history(&mut self) {
13163 self.selection_history.push(SelectionHistoryEntry {
13164 selections: self.selections.disjoint_anchors(),
13165 select_next_state: self.select_next_state.clone(),
13166 select_prev_state: self.select_prev_state.clone(),
13167 add_selections_state: self.add_selections_state.clone(),
13168 });
13169 }
13170
13171 pub fn transact(
13172 &mut self,
13173 window: &mut Window,
13174 cx: &mut Context<Self>,
13175 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13176 ) -> Option<TransactionId> {
13177 self.start_transaction_at(Instant::now(), window, cx);
13178 update(self, window, cx);
13179 self.end_transaction_at(Instant::now(), cx)
13180 }
13181
13182 pub fn start_transaction_at(
13183 &mut self,
13184 now: Instant,
13185 window: &mut Window,
13186 cx: &mut Context<Self>,
13187 ) {
13188 self.end_selection(window, cx);
13189 if let Some(tx_id) = self
13190 .buffer
13191 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13192 {
13193 self.selection_history
13194 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13195 cx.emit(EditorEvent::TransactionBegun {
13196 transaction_id: tx_id,
13197 })
13198 }
13199 }
13200
13201 pub fn end_transaction_at(
13202 &mut self,
13203 now: Instant,
13204 cx: &mut Context<Self>,
13205 ) -> Option<TransactionId> {
13206 if let Some(transaction_id) = self
13207 .buffer
13208 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13209 {
13210 if let Some((_, end_selections)) =
13211 self.selection_history.transaction_mut(transaction_id)
13212 {
13213 *end_selections = Some(self.selections.disjoint_anchors());
13214 } else {
13215 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13216 }
13217
13218 cx.emit(EditorEvent::Edited { transaction_id });
13219 Some(transaction_id)
13220 } else {
13221 None
13222 }
13223 }
13224
13225 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13226 if self.selection_mark_mode {
13227 self.change_selections(None, window, cx, |s| {
13228 s.move_with(|_, sel| {
13229 sel.collapse_to(sel.head(), SelectionGoal::None);
13230 });
13231 })
13232 }
13233 self.selection_mark_mode = true;
13234 cx.notify();
13235 }
13236
13237 pub fn swap_selection_ends(
13238 &mut self,
13239 _: &actions::SwapSelectionEnds,
13240 window: &mut Window,
13241 cx: &mut Context<Self>,
13242 ) {
13243 self.change_selections(None, window, cx, |s| {
13244 s.move_with(|_, sel| {
13245 if sel.start != sel.end {
13246 sel.reversed = !sel.reversed
13247 }
13248 });
13249 });
13250 self.request_autoscroll(Autoscroll::newest(), cx);
13251 cx.notify();
13252 }
13253
13254 pub fn toggle_fold(
13255 &mut self,
13256 _: &actions::ToggleFold,
13257 window: &mut Window,
13258 cx: &mut Context<Self>,
13259 ) {
13260 if self.is_singleton(cx) {
13261 let selection = self.selections.newest::<Point>(cx);
13262
13263 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13264 let range = if selection.is_empty() {
13265 let point = selection.head().to_display_point(&display_map);
13266 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13267 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13268 .to_point(&display_map);
13269 start..end
13270 } else {
13271 selection.range()
13272 };
13273 if display_map.folds_in_range(range).next().is_some() {
13274 self.unfold_lines(&Default::default(), window, cx)
13275 } else {
13276 self.fold(&Default::default(), window, cx)
13277 }
13278 } else {
13279 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13280 let buffer_ids: HashSet<_> = self
13281 .selections
13282 .disjoint_anchor_ranges()
13283 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13284 .collect();
13285
13286 let should_unfold = buffer_ids
13287 .iter()
13288 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13289
13290 for buffer_id in buffer_ids {
13291 if should_unfold {
13292 self.unfold_buffer(buffer_id, cx);
13293 } else {
13294 self.fold_buffer(buffer_id, cx);
13295 }
13296 }
13297 }
13298 }
13299
13300 pub fn toggle_fold_recursive(
13301 &mut self,
13302 _: &actions::ToggleFoldRecursive,
13303 window: &mut Window,
13304 cx: &mut Context<Self>,
13305 ) {
13306 let selection = self.selections.newest::<Point>(cx);
13307
13308 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13309 let range = if selection.is_empty() {
13310 let point = selection.head().to_display_point(&display_map);
13311 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13312 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13313 .to_point(&display_map);
13314 start..end
13315 } else {
13316 selection.range()
13317 };
13318 if display_map.folds_in_range(range).next().is_some() {
13319 self.unfold_recursive(&Default::default(), window, cx)
13320 } else {
13321 self.fold_recursive(&Default::default(), window, cx)
13322 }
13323 }
13324
13325 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13326 if self.is_singleton(cx) {
13327 let mut to_fold = Vec::new();
13328 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13329 let selections = self.selections.all_adjusted(cx);
13330
13331 for selection in selections {
13332 let range = selection.range().sorted();
13333 let buffer_start_row = range.start.row;
13334
13335 if range.start.row != range.end.row {
13336 let mut found = false;
13337 let mut row = range.start.row;
13338 while row <= range.end.row {
13339 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13340 {
13341 found = true;
13342 row = crease.range().end.row + 1;
13343 to_fold.push(crease);
13344 } else {
13345 row += 1
13346 }
13347 }
13348 if found {
13349 continue;
13350 }
13351 }
13352
13353 for row in (0..=range.start.row).rev() {
13354 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13355 if crease.range().end.row >= buffer_start_row {
13356 to_fold.push(crease);
13357 if row <= range.start.row {
13358 break;
13359 }
13360 }
13361 }
13362 }
13363 }
13364
13365 self.fold_creases(to_fold, true, window, cx);
13366 } else {
13367 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13368 let buffer_ids = self
13369 .selections
13370 .disjoint_anchor_ranges()
13371 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13372 .collect::<HashSet<_>>();
13373 for buffer_id in buffer_ids {
13374 self.fold_buffer(buffer_id, cx);
13375 }
13376 }
13377 }
13378
13379 fn fold_at_level(
13380 &mut self,
13381 fold_at: &FoldAtLevel,
13382 window: &mut Window,
13383 cx: &mut Context<Self>,
13384 ) {
13385 if !self.buffer.read(cx).is_singleton() {
13386 return;
13387 }
13388
13389 let fold_at_level = fold_at.0;
13390 let snapshot = self.buffer.read(cx).snapshot(cx);
13391 let mut to_fold = Vec::new();
13392 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13393
13394 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13395 while start_row < end_row {
13396 match self
13397 .snapshot(window, cx)
13398 .crease_for_buffer_row(MultiBufferRow(start_row))
13399 {
13400 Some(crease) => {
13401 let nested_start_row = crease.range().start.row + 1;
13402 let nested_end_row = crease.range().end.row;
13403
13404 if current_level < fold_at_level {
13405 stack.push((nested_start_row, nested_end_row, current_level + 1));
13406 } else if current_level == fold_at_level {
13407 to_fold.push(crease);
13408 }
13409
13410 start_row = nested_end_row + 1;
13411 }
13412 None => start_row += 1,
13413 }
13414 }
13415 }
13416
13417 self.fold_creases(to_fold, true, window, cx);
13418 }
13419
13420 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13421 if self.buffer.read(cx).is_singleton() {
13422 let mut fold_ranges = Vec::new();
13423 let snapshot = self.buffer.read(cx).snapshot(cx);
13424
13425 for row in 0..snapshot.max_row().0 {
13426 if let Some(foldable_range) = self
13427 .snapshot(window, cx)
13428 .crease_for_buffer_row(MultiBufferRow(row))
13429 {
13430 fold_ranges.push(foldable_range);
13431 }
13432 }
13433
13434 self.fold_creases(fold_ranges, true, window, cx);
13435 } else {
13436 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13437 editor
13438 .update_in(&mut cx, |editor, _, cx| {
13439 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13440 editor.fold_buffer(buffer_id, cx);
13441 }
13442 })
13443 .ok();
13444 });
13445 }
13446 }
13447
13448 pub fn fold_function_bodies(
13449 &mut self,
13450 _: &actions::FoldFunctionBodies,
13451 window: &mut Window,
13452 cx: &mut Context<Self>,
13453 ) {
13454 let snapshot = self.buffer.read(cx).snapshot(cx);
13455
13456 let ranges = snapshot
13457 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13458 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13459 .collect::<Vec<_>>();
13460
13461 let creases = ranges
13462 .into_iter()
13463 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13464 .collect();
13465
13466 self.fold_creases(creases, true, window, cx);
13467 }
13468
13469 pub fn fold_recursive(
13470 &mut self,
13471 _: &actions::FoldRecursive,
13472 window: &mut Window,
13473 cx: &mut Context<Self>,
13474 ) {
13475 let mut to_fold = Vec::new();
13476 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13477 let selections = self.selections.all_adjusted(cx);
13478
13479 for selection in selections {
13480 let range = selection.range().sorted();
13481 let buffer_start_row = range.start.row;
13482
13483 if range.start.row != range.end.row {
13484 let mut found = false;
13485 for row in range.start.row..=range.end.row {
13486 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13487 found = true;
13488 to_fold.push(crease);
13489 }
13490 }
13491 if found {
13492 continue;
13493 }
13494 }
13495
13496 for row in (0..=range.start.row).rev() {
13497 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13498 if crease.range().end.row >= buffer_start_row {
13499 to_fold.push(crease);
13500 } else {
13501 break;
13502 }
13503 }
13504 }
13505 }
13506
13507 self.fold_creases(to_fold, true, window, cx);
13508 }
13509
13510 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13511 let buffer_row = fold_at.buffer_row;
13512 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13513
13514 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13515 let autoscroll = self
13516 .selections
13517 .all::<Point>(cx)
13518 .iter()
13519 .any(|selection| crease.range().overlaps(&selection.range()));
13520
13521 self.fold_creases(vec![crease], autoscroll, window, cx);
13522 }
13523 }
13524
13525 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13526 if self.is_singleton(cx) {
13527 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13528 let buffer = &display_map.buffer_snapshot;
13529 let selections = self.selections.all::<Point>(cx);
13530 let ranges = selections
13531 .iter()
13532 .map(|s| {
13533 let range = s.display_range(&display_map).sorted();
13534 let mut start = range.start.to_point(&display_map);
13535 let mut end = range.end.to_point(&display_map);
13536 start.column = 0;
13537 end.column = buffer.line_len(MultiBufferRow(end.row));
13538 start..end
13539 })
13540 .collect::<Vec<_>>();
13541
13542 self.unfold_ranges(&ranges, true, true, cx);
13543 } else {
13544 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13545 let buffer_ids = self
13546 .selections
13547 .disjoint_anchor_ranges()
13548 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13549 .collect::<HashSet<_>>();
13550 for buffer_id in buffer_ids {
13551 self.unfold_buffer(buffer_id, cx);
13552 }
13553 }
13554 }
13555
13556 pub fn unfold_recursive(
13557 &mut self,
13558 _: &UnfoldRecursive,
13559 _window: &mut Window,
13560 cx: &mut Context<Self>,
13561 ) {
13562 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13563 let selections = self.selections.all::<Point>(cx);
13564 let ranges = selections
13565 .iter()
13566 .map(|s| {
13567 let mut range = s.display_range(&display_map).sorted();
13568 *range.start.column_mut() = 0;
13569 *range.end.column_mut() = display_map.line_len(range.end.row());
13570 let start = range.start.to_point(&display_map);
13571 let end = range.end.to_point(&display_map);
13572 start..end
13573 })
13574 .collect::<Vec<_>>();
13575
13576 self.unfold_ranges(&ranges, true, true, cx);
13577 }
13578
13579 pub fn unfold_at(
13580 &mut self,
13581 unfold_at: &UnfoldAt,
13582 _window: &mut Window,
13583 cx: &mut Context<Self>,
13584 ) {
13585 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13586
13587 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13588 ..Point::new(
13589 unfold_at.buffer_row.0,
13590 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13591 );
13592
13593 let autoscroll = self
13594 .selections
13595 .all::<Point>(cx)
13596 .iter()
13597 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13598
13599 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13600 }
13601
13602 pub fn unfold_all(
13603 &mut self,
13604 _: &actions::UnfoldAll,
13605 _window: &mut Window,
13606 cx: &mut Context<Self>,
13607 ) {
13608 if self.buffer.read(cx).is_singleton() {
13609 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13610 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13611 } else {
13612 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13613 editor
13614 .update(&mut cx, |editor, cx| {
13615 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13616 editor.unfold_buffer(buffer_id, cx);
13617 }
13618 })
13619 .ok();
13620 });
13621 }
13622 }
13623
13624 pub fn fold_selected_ranges(
13625 &mut self,
13626 _: &FoldSelectedRanges,
13627 window: &mut Window,
13628 cx: &mut Context<Self>,
13629 ) {
13630 let selections = self.selections.all::<Point>(cx);
13631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13632 let line_mode = self.selections.line_mode;
13633 let ranges = selections
13634 .into_iter()
13635 .map(|s| {
13636 if line_mode {
13637 let start = Point::new(s.start.row, 0);
13638 let end = Point::new(
13639 s.end.row,
13640 display_map
13641 .buffer_snapshot
13642 .line_len(MultiBufferRow(s.end.row)),
13643 );
13644 Crease::simple(start..end, display_map.fold_placeholder.clone())
13645 } else {
13646 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13647 }
13648 })
13649 .collect::<Vec<_>>();
13650 self.fold_creases(ranges, true, window, cx);
13651 }
13652
13653 pub fn fold_ranges<T: ToOffset + Clone>(
13654 &mut self,
13655 ranges: Vec<Range<T>>,
13656 auto_scroll: bool,
13657 window: &mut Window,
13658 cx: &mut Context<Self>,
13659 ) {
13660 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13661 let ranges = ranges
13662 .into_iter()
13663 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13664 .collect::<Vec<_>>();
13665 self.fold_creases(ranges, auto_scroll, window, cx);
13666 }
13667
13668 pub fn fold_creases<T: ToOffset + Clone>(
13669 &mut self,
13670 creases: Vec<Crease<T>>,
13671 auto_scroll: bool,
13672 window: &mut Window,
13673 cx: &mut Context<Self>,
13674 ) {
13675 if creases.is_empty() {
13676 return;
13677 }
13678
13679 let mut buffers_affected = HashSet::default();
13680 let multi_buffer = self.buffer().read(cx);
13681 for crease in &creases {
13682 if let Some((_, buffer, _)) =
13683 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13684 {
13685 buffers_affected.insert(buffer.read(cx).remote_id());
13686 };
13687 }
13688
13689 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13690
13691 if auto_scroll {
13692 self.request_autoscroll(Autoscroll::fit(), cx);
13693 }
13694
13695 cx.notify();
13696
13697 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13698 // Clear diagnostics block when folding a range that contains it.
13699 let snapshot = self.snapshot(window, cx);
13700 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13701 drop(snapshot);
13702 self.active_diagnostics = Some(active_diagnostics);
13703 self.dismiss_diagnostics(cx);
13704 } else {
13705 self.active_diagnostics = Some(active_diagnostics);
13706 }
13707 }
13708
13709 self.scrollbar_marker_state.dirty = true;
13710 }
13711
13712 /// Removes any folds whose ranges intersect any of the given ranges.
13713 pub fn unfold_ranges<T: ToOffset + Clone>(
13714 &mut self,
13715 ranges: &[Range<T>],
13716 inclusive: bool,
13717 auto_scroll: bool,
13718 cx: &mut Context<Self>,
13719 ) {
13720 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13721 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13722 });
13723 }
13724
13725 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13726 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13727 return;
13728 }
13729 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13730 self.display_map.update(cx, |display_map, cx| {
13731 display_map.fold_buffers([buffer_id], cx)
13732 });
13733 cx.emit(EditorEvent::BufferFoldToggled {
13734 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13735 folded: true,
13736 });
13737 cx.notify();
13738 }
13739
13740 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13741 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13742 return;
13743 }
13744 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13745 self.display_map.update(cx, |display_map, cx| {
13746 display_map.unfold_buffers([buffer_id], cx);
13747 });
13748 cx.emit(EditorEvent::BufferFoldToggled {
13749 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13750 folded: false,
13751 });
13752 cx.notify();
13753 }
13754
13755 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13756 self.display_map.read(cx).is_buffer_folded(buffer)
13757 }
13758
13759 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13760 self.display_map.read(cx).folded_buffers()
13761 }
13762
13763 /// Removes any folds with the given ranges.
13764 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13765 &mut self,
13766 ranges: &[Range<T>],
13767 type_id: TypeId,
13768 auto_scroll: bool,
13769 cx: &mut Context<Self>,
13770 ) {
13771 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13772 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13773 });
13774 }
13775
13776 fn remove_folds_with<T: ToOffset + Clone>(
13777 &mut self,
13778 ranges: &[Range<T>],
13779 auto_scroll: bool,
13780 cx: &mut Context<Self>,
13781 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13782 ) {
13783 if ranges.is_empty() {
13784 return;
13785 }
13786
13787 let mut buffers_affected = HashSet::default();
13788 let multi_buffer = self.buffer().read(cx);
13789 for range in ranges {
13790 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13791 buffers_affected.insert(buffer.read(cx).remote_id());
13792 };
13793 }
13794
13795 self.display_map.update(cx, update);
13796
13797 if auto_scroll {
13798 self.request_autoscroll(Autoscroll::fit(), cx);
13799 }
13800
13801 cx.notify();
13802 self.scrollbar_marker_state.dirty = true;
13803 self.active_indent_guides_state.dirty = true;
13804 }
13805
13806 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13807 self.display_map.read(cx).fold_placeholder.clone()
13808 }
13809
13810 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13811 self.buffer.update(cx, |buffer, cx| {
13812 buffer.set_all_diff_hunks_expanded(cx);
13813 });
13814 }
13815
13816 pub fn expand_all_diff_hunks(
13817 &mut self,
13818 _: &ExpandAllDiffHunks,
13819 _window: &mut Window,
13820 cx: &mut Context<Self>,
13821 ) {
13822 self.buffer.update(cx, |buffer, cx| {
13823 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13824 });
13825 }
13826
13827 pub fn toggle_selected_diff_hunks(
13828 &mut self,
13829 _: &ToggleSelectedDiffHunks,
13830 _window: &mut Window,
13831 cx: &mut Context<Self>,
13832 ) {
13833 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13834 self.toggle_diff_hunks_in_ranges(ranges, cx);
13835 }
13836
13837 pub fn diff_hunks_in_ranges<'a>(
13838 &'a self,
13839 ranges: &'a [Range<Anchor>],
13840 buffer: &'a MultiBufferSnapshot,
13841 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13842 ranges.iter().flat_map(move |range| {
13843 let end_excerpt_id = range.end.excerpt_id;
13844 let range = range.to_point(buffer);
13845 let mut peek_end = range.end;
13846 if range.end.row < buffer.max_row().0 {
13847 peek_end = Point::new(range.end.row + 1, 0);
13848 }
13849 buffer
13850 .diff_hunks_in_range(range.start..peek_end)
13851 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13852 })
13853 }
13854
13855 pub fn has_stageable_diff_hunks_in_ranges(
13856 &self,
13857 ranges: &[Range<Anchor>],
13858 snapshot: &MultiBufferSnapshot,
13859 ) -> bool {
13860 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13861 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13862 }
13863
13864 pub fn toggle_staged_selected_diff_hunks(
13865 &mut self,
13866 _: &::git::ToggleStaged,
13867 _: &mut Window,
13868 cx: &mut Context<Self>,
13869 ) {
13870 let snapshot = self.buffer.read(cx).snapshot(cx);
13871 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13872 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13873 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13874 }
13875
13876 pub fn stage_and_next(
13877 &mut self,
13878 _: &::git::StageAndNext,
13879 window: &mut Window,
13880 cx: &mut Context<Self>,
13881 ) {
13882 self.do_stage_or_unstage_and_next(true, window, cx);
13883 }
13884
13885 pub fn unstage_and_next(
13886 &mut self,
13887 _: &::git::UnstageAndNext,
13888 window: &mut Window,
13889 cx: &mut Context<Self>,
13890 ) {
13891 self.do_stage_or_unstage_and_next(false, window, cx);
13892 }
13893
13894 pub fn stage_or_unstage_diff_hunks(
13895 &mut self,
13896 stage: bool,
13897 ranges: Vec<Range<Anchor>>,
13898 cx: &mut Context<Self>,
13899 ) {
13900 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13901 cx.spawn(|this, mut cx| async move {
13902 task.await?;
13903 this.update(&mut cx, |this, cx| {
13904 let snapshot = this.buffer.read(cx).snapshot(cx);
13905 let chunk_by = this
13906 .diff_hunks_in_ranges(&ranges, &snapshot)
13907 .chunk_by(|hunk| hunk.buffer_id);
13908 for (buffer_id, hunks) in &chunk_by {
13909 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13910 }
13911 })
13912 })
13913 .detach_and_log_err(cx);
13914 }
13915
13916 fn save_buffers_for_ranges_if_needed(
13917 &mut self,
13918 ranges: &[Range<Anchor>],
13919 cx: &mut Context<'_, Editor>,
13920 ) -> Task<Result<()>> {
13921 let multibuffer = self.buffer.read(cx);
13922 let snapshot = multibuffer.read(cx);
13923 let buffer_ids: HashSet<_> = ranges
13924 .iter()
13925 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13926 .collect();
13927 drop(snapshot);
13928
13929 let mut buffers = HashSet::default();
13930 for buffer_id in buffer_ids {
13931 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13932 let buffer = buffer_entity.read(cx);
13933 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13934 {
13935 buffers.insert(buffer_entity);
13936 }
13937 }
13938 }
13939
13940 if let Some(project) = &self.project {
13941 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13942 } else {
13943 Task::ready(Ok(()))
13944 }
13945 }
13946
13947 fn do_stage_or_unstage_and_next(
13948 &mut self,
13949 stage: bool,
13950 window: &mut Window,
13951 cx: &mut Context<Self>,
13952 ) {
13953 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13954
13955 if ranges.iter().any(|range| range.start != range.end) {
13956 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13957 return;
13958 }
13959
13960 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13961 let snapshot = self.snapshot(window, cx);
13962 let position = self.selections.newest::<Point>(cx).head();
13963 let mut row = snapshot
13964 .buffer_snapshot
13965 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13966 .find(|hunk| hunk.row_range.start.0 > position.row)
13967 .map(|hunk| hunk.row_range.start);
13968
13969 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
13970 // Outside of the project diff editor, wrap around to the beginning.
13971 if !all_diff_hunks_expanded {
13972 row = row.or_else(|| {
13973 snapshot
13974 .buffer_snapshot
13975 .diff_hunks_in_range(Point::zero()..position)
13976 .find(|hunk| hunk.row_range.end.0 < position.row)
13977 .map(|hunk| hunk.row_range.start)
13978 });
13979 }
13980
13981 if let Some(row) = row {
13982 let destination = Point::new(row.0, 0);
13983 let autoscroll = Autoscroll::center();
13984
13985 self.unfold_ranges(&[destination..destination], false, false, cx);
13986 self.change_selections(Some(autoscroll), window, cx, |s| {
13987 s.select_ranges([destination..destination]);
13988 });
13989 } else if all_diff_hunks_expanded {
13990 window.dispatch_action(::git::ExpandCommitEditor.boxed_clone(), cx);
13991 }
13992 }
13993
13994 fn do_stage_or_unstage(
13995 &self,
13996 stage: bool,
13997 buffer_id: BufferId,
13998 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13999 cx: &mut App,
14000 ) -> Option<()> {
14001 let project = self.project.as_ref()?;
14002 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14003 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14004 let buffer_snapshot = buffer.read(cx).snapshot();
14005 let file_exists = buffer_snapshot
14006 .file()
14007 .is_some_and(|file| file.disk_state().exists());
14008 diff.update(cx, |diff, cx| {
14009 diff.stage_or_unstage_hunks(
14010 stage,
14011 &hunks
14012 .map(|hunk| buffer_diff::DiffHunk {
14013 buffer_range: hunk.buffer_range,
14014 diff_base_byte_range: hunk.diff_base_byte_range,
14015 secondary_status: hunk.secondary_status,
14016 range: Point::zero()..Point::zero(), // unused
14017 })
14018 .collect::<Vec<_>>(),
14019 &buffer_snapshot,
14020 file_exists,
14021 cx,
14022 )
14023 });
14024 None
14025 }
14026
14027 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14028 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14029 self.buffer
14030 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14031 }
14032
14033 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14034 self.buffer.update(cx, |buffer, cx| {
14035 let ranges = vec![Anchor::min()..Anchor::max()];
14036 if !buffer.all_diff_hunks_expanded()
14037 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14038 {
14039 buffer.collapse_diff_hunks(ranges, cx);
14040 true
14041 } else {
14042 false
14043 }
14044 })
14045 }
14046
14047 fn toggle_diff_hunks_in_ranges(
14048 &mut self,
14049 ranges: Vec<Range<Anchor>>,
14050 cx: &mut Context<'_, Editor>,
14051 ) {
14052 self.buffer.update(cx, |buffer, cx| {
14053 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14054 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14055 })
14056 }
14057
14058 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14059 self.buffer.update(cx, |buffer, cx| {
14060 let snapshot = buffer.snapshot(cx);
14061 let excerpt_id = range.end.excerpt_id;
14062 let point_range = range.to_point(&snapshot);
14063 let expand = !buffer.single_hunk_is_expanded(range, cx);
14064 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14065 })
14066 }
14067
14068 pub(crate) fn apply_all_diff_hunks(
14069 &mut self,
14070 _: &ApplyAllDiffHunks,
14071 window: &mut Window,
14072 cx: &mut Context<Self>,
14073 ) {
14074 let buffers = self.buffer.read(cx).all_buffers();
14075 for branch_buffer in buffers {
14076 branch_buffer.update(cx, |branch_buffer, cx| {
14077 branch_buffer.merge_into_base(Vec::new(), cx);
14078 });
14079 }
14080
14081 if let Some(project) = self.project.clone() {
14082 self.save(true, project, window, cx).detach_and_log_err(cx);
14083 }
14084 }
14085
14086 pub(crate) fn apply_selected_diff_hunks(
14087 &mut self,
14088 _: &ApplyDiffHunk,
14089 window: &mut Window,
14090 cx: &mut Context<Self>,
14091 ) {
14092 let snapshot = self.snapshot(window, cx);
14093 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14094 let mut ranges_by_buffer = HashMap::default();
14095 self.transact(window, cx, |editor, _window, cx| {
14096 for hunk in hunks {
14097 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14098 ranges_by_buffer
14099 .entry(buffer.clone())
14100 .or_insert_with(Vec::new)
14101 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14102 }
14103 }
14104
14105 for (buffer, ranges) in ranges_by_buffer {
14106 buffer.update(cx, |buffer, cx| {
14107 buffer.merge_into_base(ranges, cx);
14108 });
14109 }
14110 });
14111
14112 if let Some(project) = self.project.clone() {
14113 self.save(true, project, window, cx).detach_and_log_err(cx);
14114 }
14115 }
14116
14117 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14118 if hovered != self.gutter_hovered {
14119 self.gutter_hovered = hovered;
14120 cx.notify();
14121 }
14122 }
14123
14124 pub fn insert_blocks(
14125 &mut self,
14126 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14127 autoscroll: Option<Autoscroll>,
14128 cx: &mut Context<Self>,
14129 ) -> Vec<CustomBlockId> {
14130 let blocks = self
14131 .display_map
14132 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14133 if let Some(autoscroll) = autoscroll {
14134 self.request_autoscroll(autoscroll, cx);
14135 }
14136 cx.notify();
14137 blocks
14138 }
14139
14140 pub fn resize_blocks(
14141 &mut self,
14142 heights: HashMap<CustomBlockId, u32>,
14143 autoscroll: Option<Autoscroll>,
14144 cx: &mut Context<Self>,
14145 ) {
14146 self.display_map
14147 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14148 if let Some(autoscroll) = autoscroll {
14149 self.request_autoscroll(autoscroll, cx);
14150 }
14151 cx.notify();
14152 }
14153
14154 pub fn replace_blocks(
14155 &mut self,
14156 renderers: HashMap<CustomBlockId, RenderBlock>,
14157 autoscroll: Option<Autoscroll>,
14158 cx: &mut Context<Self>,
14159 ) {
14160 self.display_map
14161 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14162 if let Some(autoscroll) = autoscroll {
14163 self.request_autoscroll(autoscroll, cx);
14164 }
14165 cx.notify();
14166 }
14167
14168 pub fn remove_blocks(
14169 &mut self,
14170 block_ids: HashSet<CustomBlockId>,
14171 autoscroll: Option<Autoscroll>,
14172 cx: &mut Context<Self>,
14173 ) {
14174 self.display_map.update(cx, |display_map, cx| {
14175 display_map.remove_blocks(block_ids, cx)
14176 });
14177 if let Some(autoscroll) = autoscroll {
14178 self.request_autoscroll(autoscroll, cx);
14179 }
14180 cx.notify();
14181 }
14182
14183 pub fn row_for_block(
14184 &self,
14185 block_id: CustomBlockId,
14186 cx: &mut Context<Self>,
14187 ) -> Option<DisplayRow> {
14188 self.display_map
14189 .update(cx, |map, cx| map.row_for_block(block_id, cx))
14190 }
14191
14192 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14193 self.focused_block = Some(focused_block);
14194 }
14195
14196 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14197 self.focused_block.take()
14198 }
14199
14200 pub fn insert_creases(
14201 &mut self,
14202 creases: impl IntoIterator<Item = Crease<Anchor>>,
14203 cx: &mut Context<Self>,
14204 ) -> Vec<CreaseId> {
14205 self.display_map
14206 .update(cx, |map, cx| map.insert_creases(creases, cx))
14207 }
14208
14209 pub fn remove_creases(
14210 &mut self,
14211 ids: impl IntoIterator<Item = CreaseId>,
14212 cx: &mut Context<Self>,
14213 ) {
14214 self.display_map
14215 .update(cx, |map, cx| map.remove_creases(ids, cx));
14216 }
14217
14218 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14219 self.display_map
14220 .update(cx, |map, cx| map.snapshot(cx))
14221 .longest_row()
14222 }
14223
14224 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14225 self.display_map
14226 .update(cx, |map, cx| map.snapshot(cx))
14227 .max_point()
14228 }
14229
14230 pub fn text(&self, cx: &App) -> String {
14231 self.buffer.read(cx).read(cx).text()
14232 }
14233
14234 pub fn is_empty(&self, cx: &App) -> bool {
14235 self.buffer.read(cx).read(cx).is_empty()
14236 }
14237
14238 pub fn text_option(&self, cx: &App) -> Option<String> {
14239 let text = self.text(cx);
14240 let text = text.trim();
14241
14242 if text.is_empty() {
14243 return None;
14244 }
14245
14246 Some(text.to_string())
14247 }
14248
14249 pub fn set_text(
14250 &mut self,
14251 text: impl Into<Arc<str>>,
14252 window: &mut Window,
14253 cx: &mut Context<Self>,
14254 ) {
14255 self.transact(window, cx, |this, _, cx| {
14256 this.buffer
14257 .read(cx)
14258 .as_singleton()
14259 .expect("you can only call set_text on editors for singleton buffers")
14260 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14261 });
14262 }
14263
14264 pub fn display_text(&self, cx: &mut App) -> String {
14265 self.display_map
14266 .update(cx, |map, cx| map.snapshot(cx))
14267 .text()
14268 }
14269
14270 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14271 let mut wrap_guides = smallvec::smallvec![];
14272
14273 if self.show_wrap_guides == Some(false) {
14274 return wrap_guides;
14275 }
14276
14277 let settings = self.buffer.read(cx).language_settings(cx);
14278 if settings.show_wrap_guides {
14279 match self.soft_wrap_mode(cx) {
14280 SoftWrap::Column(soft_wrap) => {
14281 wrap_guides.push((soft_wrap as usize, true));
14282 }
14283 SoftWrap::Bounded(soft_wrap) => {
14284 wrap_guides.push((soft_wrap as usize, true));
14285 }
14286 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14287 }
14288 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14289 }
14290
14291 wrap_guides
14292 }
14293
14294 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14295 let settings = self.buffer.read(cx).language_settings(cx);
14296 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14297 match mode {
14298 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14299 SoftWrap::None
14300 }
14301 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14302 language_settings::SoftWrap::PreferredLineLength => {
14303 SoftWrap::Column(settings.preferred_line_length)
14304 }
14305 language_settings::SoftWrap::Bounded => {
14306 SoftWrap::Bounded(settings.preferred_line_length)
14307 }
14308 }
14309 }
14310
14311 pub fn set_soft_wrap_mode(
14312 &mut self,
14313 mode: language_settings::SoftWrap,
14314
14315 cx: &mut Context<Self>,
14316 ) {
14317 self.soft_wrap_mode_override = Some(mode);
14318 cx.notify();
14319 }
14320
14321 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14322 self.hard_wrap = hard_wrap;
14323 cx.notify();
14324 }
14325
14326 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14327 self.text_style_refinement = Some(style);
14328 }
14329
14330 /// called by the Element so we know what style we were most recently rendered with.
14331 pub(crate) fn set_style(
14332 &mut self,
14333 style: EditorStyle,
14334 window: &mut Window,
14335 cx: &mut Context<Self>,
14336 ) {
14337 let rem_size = window.rem_size();
14338 self.display_map.update(cx, |map, cx| {
14339 map.set_font(
14340 style.text.font(),
14341 style.text.font_size.to_pixels(rem_size),
14342 cx,
14343 )
14344 });
14345 self.style = Some(style);
14346 }
14347
14348 pub fn style(&self) -> Option<&EditorStyle> {
14349 self.style.as_ref()
14350 }
14351
14352 // Called by the element. This method is not designed to be called outside of the editor
14353 // element's layout code because it does not notify when rewrapping is computed synchronously.
14354 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14355 self.display_map
14356 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14357 }
14358
14359 pub fn set_soft_wrap(&mut self) {
14360 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14361 }
14362
14363 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14364 if self.soft_wrap_mode_override.is_some() {
14365 self.soft_wrap_mode_override.take();
14366 } else {
14367 let soft_wrap = match self.soft_wrap_mode(cx) {
14368 SoftWrap::GitDiff => return,
14369 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14370 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14371 language_settings::SoftWrap::None
14372 }
14373 };
14374 self.soft_wrap_mode_override = Some(soft_wrap);
14375 }
14376 cx.notify();
14377 }
14378
14379 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14380 let Some(workspace) = self.workspace() else {
14381 return;
14382 };
14383 let fs = workspace.read(cx).app_state().fs.clone();
14384 let current_show = TabBarSettings::get_global(cx).show;
14385 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14386 setting.show = Some(!current_show);
14387 });
14388 }
14389
14390 pub fn toggle_indent_guides(
14391 &mut self,
14392 _: &ToggleIndentGuides,
14393 _: &mut Window,
14394 cx: &mut Context<Self>,
14395 ) {
14396 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14397 self.buffer
14398 .read(cx)
14399 .language_settings(cx)
14400 .indent_guides
14401 .enabled
14402 });
14403 self.show_indent_guides = Some(!currently_enabled);
14404 cx.notify();
14405 }
14406
14407 fn should_show_indent_guides(&self) -> Option<bool> {
14408 self.show_indent_guides
14409 }
14410
14411 pub fn toggle_line_numbers(
14412 &mut self,
14413 _: &ToggleLineNumbers,
14414 _: &mut Window,
14415 cx: &mut Context<Self>,
14416 ) {
14417 let mut editor_settings = EditorSettings::get_global(cx).clone();
14418 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14419 EditorSettings::override_global(editor_settings, cx);
14420 }
14421
14422 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
14423 if let Some(show_line_numbers) = self.show_line_numbers {
14424 return show_line_numbers;
14425 }
14426 EditorSettings::get_global(cx).gutter.line_numbers
14427 }
14428
14429 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14430 self.use_relative_line_numbers
14431 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14432 }
14433
14434 pub fn toggle_relative_line_numbers(
14435 &mut self,
14436 _: &ToggleRelativeLineNumbers,
14437 _: &mut Window,
14438 cx: &mut Context<Self>,
14439 ) {
14440 let is_relative = self.should_use_relative_line_numbers(cx);
14441 self.set_relative_line_number(Some(!is_relative), cx)
14442 }
14443
14444 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14445 self.use_relative_line_numbers = is_relative;
14446 cx.notify();
14447 }
14448
14449 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14450 self.show_gutter = show_gutter;
14451 cx.notify();
14452 }
14453
14454 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14455 self.show_scrollbars = show_scrollbars;
14456 cx.notify();
14457 }
14458
14459 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14460 self.show_line_numbers = Some(show_line_numbers);
14461 cx.notify();
14462 }
14463
14464 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14465 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14466 cx.notify();
14467 }
14468
14469 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14470 self.show_code_actions = Some(show_code_actions);
14471 cx.notify();
14472 }
14473
14474 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14475 self.show_runnables = Some(show_runnables);
14476 cx.notify();
14477 }
14478
14479 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14480 if self.display_map.read(cx).masked != masked {
14481 self.display_map.update(cx, |map, _| map.masked = masked);
14482 }
14483 cx.notify()
14484 }
14485
14486 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14487 self.show_wrap_guides = Some(show_wrap_guides);
14488 cx.notify();
14489 }
14490
14491 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14492 self.show_indent_guides = Some(show_indent_guides);
14493 cx.notify();
14494 }
14495
14496 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14497 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14498 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14499 if let Some(dir) = file.abs_path(cx).parent() {
14500 return Some(dir.to_owned());
14501 }
14502 }
14503
14504 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14505 return Some(project_path.path.to_path_buf());
14506 }
14507 }
14508
14509 None
14510 }
14511
14512 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14513 self.active_excerpt(cx)?
14514 .1
14515 .read(cx)
14516 .file()
14517 .and_then(|f| f.as_local())
14518 }
14519
14520 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14521 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14522 let buffer = buffer.read(cx);
14523 if let Some(project_path) = buffer.project_path(cx) {
14524 let project = self.project.as_ref()?.read(cx);
14525 project.absolute_path(&project_path, cx)
14526 } else {
14527 buffer
14528 .file()
14529 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14530 }
14531 })
14532 }
14533
14534 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14535 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14536 let project_path = buffer.read(cx).project_path(cx)?;
14537 let project = self.project.as_ref()?.read(cx);
14538 let entry = project.entry_for_path(&project_path, cx)?;
14539 let path = entry.path.to_path_buf();
14540 Some(path)
14541 })
14542 }
14543
14544 pub fn reveal_in_finder(
14545 &mut self,
14546 _: &RevealInFileManager,
14547 _window: &mut Window,
14548 cx: &mut Context<Self>,
14549 ) {
14550 if let Some(target) = self.target_file(cx) {
14551 cx.reveal_path(&target.abs_path(cx));
14552 }
14553 }
14554
14555 pub fn copy_path(
14556 &mut self,
14557 _: &zed_actions::workspace::CopyPath,
14558 _window: &mut Window,
14559 cx: &mut Context<Self>,
14560 ) {
14561 if let Some(path) = self.target_file_abs_path(cx) {
14562 if let Some(path) = path.to_str() {
14563 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14564 }
14565 }
14566 }
14567
14568 pub fn copy_relative_path(
14569 &mut self,
14570 _: &zed_actions::workspace::CopyRelativePath,
14571 _window: &mut Window,
14572 cx: &mut Context<Self>,
14573 ) {
14574 if let Some(path) = self.target_file_path(cx) {
14575 if let Some(path) = path.to_str() {
14576 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14577 }
14578 }
14579 }
14580
14581 pub fn copy_file_name_without_extension(
14582 &mut self,
14583 _: &CopyFileNameWithoutExtension,
14584 _: &mut Window,
14585 cx: &mut Context<Self>,
14586 ) {
14587 if let Some(file) = self.target_file(cx) {
14588 if let Some(file_stem) = file.path().file_stem() {
14589 if let Some(name) = file_stem.to_str() {
14590 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14591 }
14592 }
14593 }
14594 }
14595
14596 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14597 if let Some(file) = self.target_file(cx) {
14598 if let Some(file_name) = file.path().file_name() {
14599 if let Some(name) = file_name.to_str() {
14600 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14601 }
14602 }
14603 }
14604 }
14605
14606 pub fn toggle_git_blame(
14607 &mut self,
14608 _: &ToggleGitBlame,
14609 window: &mut Window,
14610 cx: &mut Context<Self>,
14611 ) {
14612 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14613
14614 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14615 self.start_git_blame(true, window, cx);
14616 }
14617
14618 cx.notify();
14619 }
14620
14621 pub fn toggle_git_blame_inline(
14622 &mut self,
14623 _: &ToggleGitBlameInline,
14624 window: &mut Window,
14625 cx: &mut Context<Self>,
14626 ) {
14627 self.toggle_git_blame_inline_internal(true, window, cx);
14628 cx.notify();
14629 }
14630
14631 pub fn git_blame_inline_enabled(&self) -> bool {
14632 self.git_blame_inline_enabled
14633 }
14634
14635 pub fn toggle_selection_menu(
14636 &mut self,
14637 _: &ToggleSelectionMenu,
14638 _: &mut Window,
14639 cx: &mut Context<Self>,
14640 ) {
14641 self.show_selection_menu = self
14642 .show_selection_menu
14643 .map(|show_selections_menu| !show_selections_menu)
14644 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14645
14646 cx.notify();
14647 }
14648
14649 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14650 self.show_selection_menu
14651 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14652 }
14653
14654 fn start_git_blame(
14655 &mut self,
14656 user_triggered: bool,
14657 window: &mut Window,
14658 cx: &mut Context<Self>,
14659 ) {
14660 if let Some(project) = self.project.as_ref() {
14661 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14662 return;
14663 };
14664
14665 if buffer.read(cx).file().is_none() {
14666 return;
14667 }
14668
14669 let focused = self.focus_handle(cx).contains_focused(window, cx);
14670
14671 let project = project.clone();
14672 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14673 self.blame_subscription =
14674 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14675 self.blame = Some(blame);
14676 }
14677 }
14678
14679 fn toggle_git_blame_inline_internal(
14680 &mut self,
14681 user_triggered: bool,
14682 window: &mut Window,
14683 cx: &mut Context<Self>,
14684 ) {
14685 if self.git_blame_inline_enabled {
14686 self.git_blame_inline_enabled = false;
14687 self.show_git_blame_inline = false;
14688 self.show_git_blame_inline_delay_task.take();
14689 } else {
14690 self.git_blame_inline_enabled = true;
14691 self.start_git_blame_inline(user_triggered, window, cx);
14692 }
14693
14694 cx.notify();
14695 }
14696
14697 fn start_git_blame_inline(
14698 &mut self,
14699 user_triggered: bool,
14700 window: &mut Window,
14701 cx: &mut Context<Self>,
14702 ) {
14703 self.start_git_blame(user_triggered, window, cx);
14704
14705 if ProjectSettings::get_global(cx)
14706 .git
14707 .inline_blame_delay()
14708 .is_some()
14709 {
14710 self.start_inline_blame_timer(window, cx);
14711 } else {
14712 self.show_git_blame_inline = true
14713 }
14714 }
14715
14716 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14717 self.blame.as_ref()
14718 }
14719
14720 pub fn show_git_blame_gutter(&self) -> bool {
14721 self.show_git_blame_gutter
14722 }
14723
14724 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14725 self.show_git_blame_gutter && self.has_blame_entries(cx)
14726 }
14727
14728 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14729 self.show_git_blame_inline
14730 && (self.focus_handle.is_focused(window)
14731 || self
14732 .git_blame_inline_tooltip
14733 .as_ref()
14734 .and_then(|t| t.upgrade())
14735 .is_some())
14736 && !self.newest_selection_head_on_empty_line(cx)
14737 && self.has_blame_entries(cx)
14738 }
14739
14740 fn has_blame_entries(&self, cx: &App) -> bool {
14741 self.blame()
14742 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14743 }
14744
14745 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14746 let cursor_anchor = self.selections.newest_anchor().head();
14747
14748 let snapshot = self.buffer.read(cx).snapshot(cx);
14749 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14750
14751 snapshot.line_len(buffer_row) == 0
14752 }
14753
14754 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14755 let buffer_and_selection = maybe!({
14756 let selection = self.selections.newest::<Point>(cx);
14757 let selection_range = selection.range();
14758
14759 let multi_buffer = self.buffer().read(cx);
14760 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14761 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14762
14763 let (buffer, range, _) = if selection.reversed {
14764 buffer_ranges.first()
14765 } else {
14766 buffer_ranges.last()
14767 }?;
14768
14769 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14770 ..text::ToPoint::to_point(&range.end, &buffer).row;
14771 Some((
14772 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14773 selection,
14774 ))
14775 });
14776
14777 let Some((buffer, selection)) = buffer_and_selection else {
14778 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14779 };
14780
14781 let Some(project) = self.project.as_ref() else {
14782 return Task::ready(Err(anyhow!("editor does not have project")));
14783 };
14784
14785 project.update(cx, |project, cx| {
14786 project.get_permalink_to_line(&buffer, selection, cx)
14787 })
14788 }
14789
14790 pub fn copy_permalink_to_line(
14791 &mut self,
14792 _: &CopyPermalinkToLine,
14793 window: &mut Window,
14794 cx: &mut Context<Self>,
14795 ) {
14796 let permalink_task = self.get_permalink_to_line(cx);
14797 let workspace = self.workspace();
14798
14799 cx.spawn_in(window, |_, mut cx| async move {
14800 match permalink_task.await {
14801 Ok(permalink) => {
14802 cx.update(|_, cx| {
14803 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14804 })
14805 .ok();
14806 }
14807 Err(err) => {
14808 let message = format!("Failed to copy permalink: {err}");
14809
14810 Err::<(), anyhow::Error>(err).log_err();
14811
14812 if let Some(workspace) = workspace {
14813 workspace
14814 .update_in(&mut cx, |workspace, _, cx| {
14815 struct CopyPermalinkToLine;
14816
14817 workspace.show_toast(
14818 Toast::new(
14819 NotificationId::unique::<CopyPermalinkToLine>(),
14820 message,
14821 ),
14822 cx,
14823 )
14824 })
14825 .ok();
14826 }
14827 }
14828 }
14829 })
14830 .detach();
14831 }
14832
14833 pub fn copy_file_location(
14834 &mut self,
14835 _: &CopyFileLocation,
14836 _: &mut Window,
14837 cx: &mut Context<Self>,
14838 ) {
14839 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14840 if let Some(file) = self.target_file(cx) {
14841 if let Some(path) = file.path().to_str() {
14842 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14843 }
14844 }
14845 }
14846
14847 pub fn open_permalink_to_line(
14848 &mut self,
14849 _: &OpenPermalinkToLine,
14850 window: &mut Window,
14851 cx: &mut Context<Self>,
14852 ) {
14853 let permalink_task = self.get_permalink_to_line(cx);
14854 let workspace = self.workspace();
14855
14856 cx.spawn_in(window, |_, mut cx| async move {
14857 match permalink_task.await {
14858 Ok(permalink) => {
14859 cx.update(|_, cx| {
14860 cx.open_url(permalink.as_ref());
14861 })
14862 .ok();
14863 }
14864 Err(err) => {
14865 let message = format!("Failed to open permalink: {err}");
14866
14867 Err::<(), anyhow::Error>(err).log_err();
14868
14869 if let Some(workspace) = workspace {
14870 workspace
14871 .update(&mut cx, |workspace, cx| {
14872 struct OpenPermalinkToLine;
14873
14874 workspace.show_toast(
14875 Toast::new(
14876 NotificationId::unique::<OpenPermalinkToLine>(),
14877 message,
14878 ),
14879 cx,
14880 )
14881 })
14882 .ok();
14883 }
14884 }
14885 }
14886 })
14887 .detach();
14888 }
14889
14890 pub fn insert_uuid_v4(
14891 &mut self,
14892 _: &InsertUuidV4,
14893 window: &mut Window,
14894 cx: &mut Context<Self>,
14895 ) {
14896 self.insert_uuid(UuidVersion::V4, window, cx);
14897 }
14898
14899 pub fn insert_uuid_v7(
14900 &mut self,
14901 _: &InsertUuidV7,
14902 window: &mut Window,
14903 cx: &mut Context<Self>,
14904 ) {
14905 self.insert_uuid(UuidVersion::V7, window, cx);
14906 }
14907
14908 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14909 self.transact(window, cx, |this, window, cx| {
14910 let edits = this
14911 .selections
14912 .all::<Point>(cx)
14913 .into_iter()
14914 .map(|selection| {
14915 let uuid = match version {
14916 UuidVersion::V4 => uuid::Uuid::new_v4(),
14917 UuidVersion::V7 => uuid::Uuid::now_v7(),
14918 };
14919
14920 (selection.range(), uuid.to_string())
14921 });
14922 this.edit(edits, cx);
14923 this.refresh_inline_completion(true, false, window, cx);
14924 });
14925 }
14926
14927 pub fn open_selections_in_multibuffer(
14928 &mut self,
14929 _: &OpenSelectionsInMultibuffer,
14930 window: &mut Window,
14931 cx: &mut Context<Self>,
14932 ) {
14933 let multibuffer = self.buffer.read(cx);
14934
14935 let Some(buffer) = multibuffer.as_singleton() else {
14936 return;
14937 };
14938
14939 let Some(workspace) = self.workspace() else {
14940 return;
14941 };
14942
14943 let locations = self
14944 .selections
14945 .disjoint_anchors()
14946 .iter()
14947 .map(|range| Location {
14948 buffer: buffer.clone(),
14949 range: range.start.text_anchor..range.end.text_anchor,
14950 })
14951 .collect::<Vec<_>>();
14952
14953 let title = multibuffer.title(cx).to_string();
14954
14955 cx.spawn_in(window, |_, mut cx| async move {
14956 workspace.update_in(&mut cx, |workspace, window, cx| {
14957 Self::open_locations_in_multibuffer(
14958 workspace,
14959 locations,
14960 format!("Selections for '{title}'"),
14961 false,
14962 MultibufferSelectionMode::All,
14963 window,
14964 cx,
14965 );
14966 })
14967 })
14968 .detach();
14969 }
14970
14971 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14972 /// last highlight added will be used.
14973 ///
14974 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14975 pub fn highlight_rows<T: 'static>(
14976 &mut self,
14977 range: Range<Anchor>,
14978 color: Hsla,
14979 should_autoscroll: bool,
14980 cx: &mut Context<Self>,
14981 ) {
14982 let snapshot = self.buffer().read(cx).snapshot(cx);
14983 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14984 let ix = row_highlights.binary_search_by(|highlight| {
14985 Ordering::Equal
14986 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14987 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14988 });
14989
14990 if let Err(mut ix) = ix {
14991 let index = post_inc(&mut self.highlight_order);
14992
14993 // If this range intersects with the preceding highlight, then merge it with
14994 // the preceding highlight. Otherwise insert a new highlight.
14995 let mut merged = false;
14996 if ix > 0 {
14997 let prev_highlight = &mut row_highlights[ix - 1];
14998 if prev_highlight
14999 .range
15000 .end
15001 .cmp(&range.start, &snapshot)
15002 .is_ge()
15003 {
15004 ix -= 1;
15005 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15006 prev_highlight.range.end = range.end;
15007 }
15008 merged = true;
15009 prev_highlight.index = index;
15010 prev_highlight.color = color;
15011 prev_highlight.should_autoscroll = should_autoscroll;
15012 }
15013 }
15014
15015 if !merged {
15016 row_highlights.insert(
15017 ix,
15018 RowHighlight {
15019 range: range.clone(),
15020 index,
15021 color,
15022 should_autoscroll,
15023 },
15024 );
15025 }
15026
15027 // If any of the following highlights intersect with this one, merge them.
15028 while let Some(next_highlight) = row_highlights.get(ix + 1) {
15029 let highlight = &row_highlights[ix];
15030 if next_highlight
15031 .range
15032 .start
15033 .cmp(&highlight.range.end, &snapshot)
15034 .is_le()
15035 {
15036 if next_highlight
15037 .range
15038 .end
15039 .cmp(&highlight.range.end, &snapshot)
15040 .is_gt()
15041 {
15042 row_highlights[ix].range.end = next_highlight.range.end;
15043 }
15044 row_highlights.remove(ix + 1);
15045 } else {
15046 break;
15047 }
15048 }
15049 }
15050 }
15051
15052 /// Remove any highlighted row ranges of the given type that intersect the
15053 /// given ranges.
15054 pub fn remove_highlighted_rows<T: 'static>(
15055 &mut self,
15056 ranges_to_remove: Vec<Range<Anchor>>,
15057 cx: &mut Context<Self>,
15058 ) {
15059 let snapshot = self.buffer().read(cx).snapshot(cx);
15060 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15061 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15062 row_highlights.retain(|highlight| {
15063 while let Some(range_to_remove) = ranges_to_remove.peek() {
15064 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15065 Ordering::Less | Ordering::Equal => {
15066 ranges_to_remove.next();
15067 }
15068 Ordering::Greater => {
15069 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15070 Ordering::Less | Ordering::Equal => {
15071 return false;
15072 }
15073 Ordering::Greater => break,
15074 }
15075 }
15076 }
15077 }
15078
15079 true
15080 })
15081 }
15082
15083 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15084 pub fn clear_row_highlights<T: 'static>(&mut self) {
15085 self.highlighted_rows.remove(&TypeId::of::<T>());
15086 }
15087
15088 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15089 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15090 self.highlighted_rows
15091 .get(&TypeId::of::<T>())
15092 .map_or(&[] as &[_], |vec| vec.as_slice())
15093 .iter()
15094 .map(|highlight| (highlight.range.clone(), highlight.color))
15095 }
15096
15097 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15098 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15099 /// Allows to ignore certain kinds of highlights.
15100 pub fn highlighted_display_rows(
15101 &self,
15102 window: &mut Window,
15103 cx: &mut App,
15104 ) -> BTreeMap<DisplayRow, LineHighlight> {
15105 let snapshot = self.snapshot(window, cx);
15106 let mut used_highlight_orders = HashMap::default();
15107 self.highlighted_rows
15108 .iter()
15109 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15110 .fold(
15111 BTreeMap::<DisplayRow, LineHighlight>::new(),
15112 |mut unique_rows, highlight| {
15113 let start = highlight.range.start.to_display_point(&snapshot);
15114 let end = highlight.range.end.to_display_point(&snapshot);
15115 let start_row = start.row().0;
15116 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15117 && end.column() == 0
15118 {
15119 end.row().0.saturating_sub(1)
15120 } else {
15121 end.row().0
15122 };
15123 for row in start_row..=end_row {
15124 let used_index =
15125 used_highlight_orders.entry(row).or_insert(highlight.index);
15126 if highlight.index >= *used_index {
15127 *used_index = highlight.index;
15128 unique_rows.insert(DisplayRow(row), highlight.color.into());
15129 }
15130 }
15131 unique_rows
15132 },
15133 )
15134 }
15135
15136 pub fn highlighted_display_row_for_autoscroll(
15137 &self,
15138 snapshot: &DisplaySnapshot,
15139 ) -> Option<DisplayRow> {
15140 self.highlighted_rows
15141 .values()
15142 .flat_map(|highlighted_rows| highlighted_rows.iter())
15143 .filter_map(|highlight| {
15144 if highlight.should_autoscroll {
15145 Some(highlight.range.start.to_display_point(snapshot).row())
15146 } else {
15147 None
15148 }
15149 })
15150 .min()
15151 }
15152
15153 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15154 self.highlight_background::<SearchWithinRange>(
15155 ranges,
15156 |colors| colors.editor_document_highlight_read_background,
15157 cx,
15158 )
15159 }
15160
15161 pub fn set_breadcrumb_header(&mut self, new_header: String) {
15162 self.breadcrumb_header = Some(new_header);
15163 }
15164
15165 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15166 self.clear_background_highlights::<SearchWithinRange>(cx);
15167 }
15168
15169 pub fn highlight_background<T: 'static>(
15170 &mut self,
15171 ranges: &[Range<Anchor>],
15172 color_fetcher: fn(&ThemeColors) -> Hsla,
15173 cx: &mut Context<Self>,
15174 ) {
15175 self.background_highlights
15176 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15177 self.scrollbar_marker_state.dirty = true;
15178 cx.notify();
15179 }
15180
15181 pub fn clear_background_highlights<T: 'static>(
15182 &mut self,
15183 cx: &mut Context<Self>,
15184 ) -> Option<BackgroundHighlight> {
15185 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15186 if !text_highlights.1.is_empty() {
15187 self.scrollbar_marker_state.dirty = true;
15188 cx.notify();
15189 }
15190 Some(text_highlights)
15191 }
15192
15193 pub fn highlight_gutter<T: 'static>(
15194 &mut self,
15195 ranges: &[Range<Anchor>],
15196 color_fetcher: fn(&App) -> Hsla,
15197 cx: &mut Context<Self>,
15198 ) {
15199 self.gutter_highlights
15200 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15201 cx.notify();
15202 }
15203
15204 pub fn clear_gutter_highlights<T: 'static>(
15205 &mut self,
15206 cx: &mut Context<Self>,
15207 ) -> Option<GutterHighlight> {
15208 cx.notify();
15209 self.gutter_highlights.remove(&TypeId::of::<T>())
15210 }
15211
15212 #[cfg(feature = "test-support")]
15213 pub fn all_text_background_highlights(
15214 &self,
15215 window: &mut Window,
15216 cx: &mut Context<Self>,
15217 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15218 let snapshot = self.snapshot(window, cx);
15219 let buffer = &snapshot.buffer_snapshot;
15220 let start = buffer.anchor_before(0);
15221 let end = buffer.anchor_after(buffer.len());
15222 let theme = cx.theme().colors();
15223 self.background_highlights_in_range(start..end, &snapshot, theme)
15224 }
15225
15226 #[cfg(feature = "test-support")]
15227 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15228 let snapshot = self.buffer().read(cx).snapshot(cx);
15229
15230 let highlights = self
15231 .background_highlights
15232 .get(&TypeId::of::<items::BufferSearchHighlights>());
15233
15234 if let Some((_color, ranges)) = highlights {
15235 ranges
15236 .iter()
15237 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15238 .collect_vec()
15239 } else {
15240 vec![]
15241 }
15242 }
15243
15244 fn document_highlights_for_position<'a>(
15245 &'a self,
15246 position: Anchor,
15247 buffer: &'a MultiBufferSnapshot,
15248 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15249 let read_highlights = self
15250 .background_highlights
15251 .get(&TypeId::of::<DocumentHighlightRead>())
15252 .map(|h| &h.1);
15253 let write_highlights = self
15254 .background_highlights
15255 .get(&TypeId::of::<DocumentHighlightWrite>())
15256 .map(|h| &h.1);
15257 let left_position = position.bias_left(buffer);
15258 let right_position = position.bias_right(buffer);
15259 read_highlights
15260 .into_iter()
15261 .chain(write_highlights)
15262 .flat_map(move |ranges| {
15263 let start_ix = match ranges.binary_search_by(|probe| {
15264 let cmp = probe.end.cmp(&left_position, buffer);
15265 if cmp.is_ge() {
15266 Ordering::Greater
15267 } else {
15268 Ordering::Less
15269 }
15270 }) {
15271 Ok(i) | Err(i) => i,
15272 };
15273
15274 ranges[start_ix..]
15275 .iter()
15276 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15277 })
15278 }
15279
15280 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15281 self.background_highlights
15282 .get(&TypeId::of::<T>())
15283 .map_or(false, |(_, highlights)| !highlights.is_empty())
15284 }
15285
15286 pub fn background_highlights_in_range(
15287 &self,
15288 search_range: Range<Anchor>,
15289 display_snapshot: &DisplaySnapshot,
15290 theme: &ThemeColors,
15291 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15292 let mut results = Vec::new();
15293 for (color_fetcher, ranges) in self.background_highlights.values() {
15294 let color = color_fetcher(theme);
15295 let start_ix = match ranges.binary_search_by(|probe| {
15296 let cmp = probe
15297 .end
15298 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15299 if cmp.is_gt() {
15300 Ordering::Greater
15301 } else {
15302 Ordering::Less
15303 }
15304 }) {
15305 Ok(i) | Err(i) => i,
15306 };
15307 for range in &ranges[start_ix..] {
15308 if range
15309 .start
15310 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15311 .is_ge()
15312 {
15313 break;
15314 }
15315
15316 let start = range.start.to_display_point(display_snapshot);
15317 let end = range.end.to_display_point(display_snapshot);
15318 results.push((start..end, color))
15319 }
15320 }
15321 results
15322 }
15323
15324 pub fn background_highlight_row_ranges<T: 'static>(
15325 &self,
15326 search_range: Range<Anchor>,
15327 display_snapshot: &DisplaySnapshot,
15328 count: usize,
15329 ) -> Vec<RangeInclusive<DisplayPoint>> {
15330 let mut results = Vec::new();
15331 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15332 return vec![];
15333 };
15334
15335 let start_ix = match ranges.binary_search_by(|probe| {
15336 let cmp = probe
15337 .end
15338 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15339 if cmp.is_gt() {
15340 Ordering::Greater
15341 } else {
15342 Ordering::Less
15343 }
15344 }) {
15345 Ok(i) | Err(i) => i,
15346 };
15347 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15348 if let (Some(start_display), Some(end_display)) = (start, end) {
15349 results.push(
15350 start_display.to_display_point(display_snapshot)
15351 ..=end_display.to_display_point(display_snapshot),
15352 );
15353 }
15354 };
15355 let mut start_row: Option<Point> = None;
15356 let mut end_row: Option<Point> = None;
15357 if ranges.len() > count {
15358 return Vec::new();
15359 }
15360 for range in &ranges[start_ix..] {
15361 if range
15362 .start
15363 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15364 .is_ge()
15365 {
15366 break;
15367 }
15368 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15369 if let Some(current_row) = &end_row {
15370 if end.row == current_row.row {
15371 continue;
15372 }
15373 }
15374 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15375 if start_row.is_none() {
15376 assert_eq!(end_row, None);
15377 start_row = Some(start);
15378 end_row = Some(end);
15379 continue;
15380 }
15381 if let Some(current_end) = end_row.as_mut() {
15382 if start.row > current_end.row + 1 {
15383 push_region(start_row, end_row);
15384 start_row = Some(start);
15385 end_row = Some(end);
15386 } else {
15387 // Merge two hunks.
15388 *current_end = end;
15389 }
15390 } else {
15391 unreachable!();
15392 }
15393 }
15394 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15395 push_region(start_row, end_row);
15396 results
15397 }
15398
15399 pub fn gutter_highlights_in_range(
15400 &self,
15401 search_range: Range<Anchor>,
15402 display_snapshot: &DisplaySnapshot,
15403 cx: &App,
15404 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15405 let mut results = Vec::new();
15406 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15407 let color = color_fetcher(cx);
15408 let start_ix = match ranges.binary_search_by(|probe| {
15409 let cmp = probe
15410 .end
15411 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15412 if cmp.is_gt() {
15413 Ordering::Greater
15414 } else {
15415 Ordering::Less
15416 }
15417 }) {
15418 Ok(i) | Err(i) => i,
15419 };
15420 for range in &ranges[start_ix..] {
15421 if range
15422 .start
15423 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15424 .is_ge()
15425 {
15426 break;
15427 }
15428
15429 let start = range.start.to_display_point(display_snapshot);
15430 let end = range.end.to_display_point(display_snapshot);
15431 results.push((start..end, color))
15432 }
15433 }
15434 results
15435 }
15436
15437 /// Get the text ranges corresponding to the redaction query
15438 pub fn redacted_ranges(
15439 &self,
15440 search_range: Range<Anchor>,
15441 display_snapshot: &DisplaySnapshot,
15442 cx: &App,
15443 ) -> Vec<Range<DisplayPoint>> {
15444 display_snapshot
15445 .buffer_snapshot
15446 .redacted_ranges(search_range, |file| {
15447 if let Some(file) = file {
15448 file.is_private()
15449 && EditorSettings::get(
15450 Some(SettingsLocation {
15451 worktree_id: file.worktree_id(cx),
15452 path: file.path().as_ref(),
15453 }),
15454 cx,
15455 )
15456 .redact_private_values
15457 } else {
15458 false
15459 }
15460 })
15461 .map(|range| {
15462 range.start.to_display_point(display_snapshot)
15463 ..range.end.to_display_point(display_snapshot)
15464 })
15465 .collect()
15466 }
15467
15468 pub fn highlight_text<T: 'static>(
15469 &mut self,
15470 ranges: Vec<Range<Anchor>>,
15471 style: HighlightStyle,
15472 cx: &mut Context<Self>,
15473 ) {
15474 self.display_map.update(cx, |map, _| {
15475 map.highlight_text(TypeId::of::<T>(), ranges, style)
15476 });
15477 cx.notify();
15478 }
15479
15480 pub(crate) fn highlight_inlays<T: 'static>(
15481 &mut self,
15482 highlights: Vec<InlayHighlight>,
15483 style: HighlightStyle,
15484 cx: &mut Context<Self>,
15485 ) {
15486 self.display_map.update(cx, |map, _| {
15487 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15488 });
15489 cx.notify();
15490 }
15491
15492 pub fn text_highlights<'a, T: 'static>(
15493 &'a self,
15494 cx: &'a App,
15495 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15496 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15497 }
15498
15499 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15500 let cleared = self
15501 .display_map
15502 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15503 if cleared {
15504 cx.notify();
15505 }
15506 }
15507
15508 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15509 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15510 && self.focus_handle.is_focused(window)
15511 }
15512
15513 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15514 self.show_cursor_when_unfocused = is_enabled;
15515 cx.notify();
15516 }
15517
15518 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15519 cx.notify();
15520 }
15521
15522 fn on_buffer_event(
15523 &mut self,
15524 multibuffer: &Entity<MultiBuffer>,
15525 event: &multi_buffer::Event,
15526 window: &mut Window,
15527 cx: &mut Context<Self>,
15528 ) {
15529 match event {
15530 multi_buffer::Event::Edited {
15531 singleton_buffer_edited,
15532 edited_buffer: buffer_edited,
15533 } => {
15534 self.scrollbar_marker_state.dirty = true;
15535 self.active_indent_guides_state.dirty = true;
15536 self.refresh_active_diagnostics(cx);
15537 self.refresh_code_actions(window, cx);
15538 if self.has_active_inline_completion() {
15539 self.update_visible_inline_completion(window, cx);
15540 }
15541 if let Some(buffer) = buffer_edited {
15542 let buffer_id = buffer.read(cx).remote_id();
15543 if !self.registered_buffers.contains_key(&buffer_id) {
15544 if let Some(project) = self.project.as_ref() {
15545 project.update(cx, |project, cx| {
15546 self.registered_buffers.insert(
15547 buffer_id,
15548 project.register_buffer_with_language_servers(&buffer, cx),
15549 );
15550 })
15551 }
15552 }
15553 }
15554 cx.emit(EditorEvent::BufferEdited);
15555 cx.emit(SearchEvent::MatchesInvalidated);
15556 if *singleton_buffer_edited {
15557 if let Some(project) = &self.project {
15558 #[allow(clippy::mutable_key_type)]
15559 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15560 multibuffer
15561 .all_buffers()
15562 .into_iter()
15563 .filter_map(|buffer| {
15564 buffer.update(cx, |buffer, cx| {
15565 let language = buffer.language()?;
15566 let should_discard = project.update(cx, |project, cx| {
15567 project.is_local()
15568 && !project.has_language_servers_for(buffer, cx)
15569 });
15570 should_discard.not().then_some(language.clone())
15571 })
15572 })
15573 .collect::<HashSet<_>>()
15574 });
15575 if !languages_affected.is_empty() {
15576 self.refresh_inlay_hints(
15577 InlayHintRefreshReason::BufferEdited(languages_affected),
15578 cx,
15579 );
15580 }
15581 }
15582 }
15583
15584 let Some(project) = &self.project else { return };
15585 let (telemetry, is_via_ssh) = {
15586 let project = project.read(cx);
15587 let telemetry = project.client().telemetry().clone();
15588 let is_via_ssh = project.is_via_ssh();
15589 (telemetry, is_via_ssh)
15590 };
15591 refresh_linked_ranges(self, window, cx);
15592 telemetry.log_edit_event("editor", is_via_ssh);
15593 }
15594 multi_buffer::Event::ExcerptsAdded {
15595 buffer,
15596 predecessor,
15597 excerpts,
15598 } => {
15599 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15600 let buffer_id = buffer.read(cx).remote_id();
15601 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15602 if let Some(project) = &self.project {
15603 get_uncommitted_diff_for_buffer(
15604 project,
15605 [buffer.clone()],
15606 self.buffer.clone(),
15607 cx,
15608 )
15609 .detach();
15610 }
15611 }
15612 cx.emit(EditorEvent::ExcerptsAdded {
15613 buffer: buffer.clone(),
15614 predecessor: *predecessor,
15615 excerpts: excerpts.clone(),
15616 });
15617 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15618 }
15619 multi_buffer::Event::ExcerptsRemoved { ids } => {
15620 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15621 let buffer = self.buffer.read(cx);
15622 self.registered_buffers
15623 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15624 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15625 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15626 }
15627 multi_buffer::Event::ExcerptsEdited {
15628 excerpt_ids,
15629 buffer_ids,
15630 } => {
15631 self.display_map.update(cx, |map, cx| {
15632 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15633 });
15634 cx.emit(EditorEvent::ExcerptsEdited {
15635 ids: excerpt_ids.clone(),
15636 })
15637 }
15638 multi_buffer::Event::ExcerptsExpanded { ids } => {
15639 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15640 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15641 }
15642 multi_buffer::Event::Reparsed(buffer_id) => {
15643 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15644 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15645
15646 cx.emit(EditorEvent::Reparsed(*buffer_id));
15647 }
15648 multi_buffer::Event::DiffHunksToggled => {
15649 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15650 }
15651 multi_buffer::Event::LanguageChanged(buffer_id) => {
15652 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15653 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15654 cx.emit(EditorEvent::Reparsed(*buffer_id));
15655 cx.notify();
15656 }
15657 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15658 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15659 multi_buffer::Event::FileHandleChanged
15660 | multi_buffer::Event::Reloaded
15661 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15662 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15663 multi_buffer::Event::DiagnosticsUpdated => {
15664 self.refresh_active_diagnostics(cx);
15665 self.refresh_inline_diagnostics(true, window, cx);
15666 self.scrollbar_marker_state.dirty = true;
15667 cx.notify();
15668 }
15669 _ => {}
15670 };
15671 }
15672
15673 fn on_display_map_changed(
15674 &mut self,
15675 _: Entity<DisplayMap>,
15676 _: &mut Window,
15677 cx: &mut Context<Self>,
15678 ) {
15679 cx.notify();
15680 }
15681
15682 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15683 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15684 self.update_edit_prediction_settings(cx);
15685 self.refresh_inline_completion(true, false, window, cx);
15686 self.refresh_inlay_hints(
15687 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15688 self.selections.newest_anchor().head(),
15689 &self.buffer.read(cx).snapshot(cx),
15690 cx,
15691 )),
15692 cx,
15693 );
15694
15695 let old_cursor_shape = self.cursor_shape;
15696
15697 {
15698 let editor_settings = EditorSettings::get_global(cx);
15699 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15700 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15701 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15702 }
15703
15704 if old_cursor_shape != self.cursor_shape {
15705 cx.emit(EditorEvent::CursorShapeChanged);
15706 }
15707
15708 let project_settings = ProjectSettings::get_global(cx);
15709 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15710
15711 if self.mode == EditorMode::Full {
15712 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15713 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15714 if self.show_inline_diagnostics != show_inline_diagnostics {
15715 self.show_inline_diagnostics = show_inline_diagnostics;
15716 self.refresh_inline_diagnostics(false, window, cx);
15717 }
15718
15719 if self.git_blame_inline_enabled != inline_blame_enabled {
15720 self.toggle_git_blame_inline_internal(false, window, cx);
15721 }
15722 }
15723
15724 cx.notify();
15725 }
15726
15727 pub fn set_searchable(&mut self, searchable: bool) {
15728 self.searchable = searchable;
15729 }
15730
15731 pub fn searchable(&self) -> bool {
15732 self.searchable
15733 }
15734
15735 fn open_proposed_changes_editor(
15736 &mut self,
15737 _: &OpenProposedChangesEditor,
15738 window: &mut Window,
15739 cx: &mut Context<Self>,
15740 ) {
15741 let Some(workspace) = self.workspace() else {
15742 cx.propagate();
15743 return;
15744 };
15745
15746 let selections = self.selections.all::<usize>(cx);
15747 let multi_buffer = self.buffer.read(cx);
15748 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15749 let mut new_selections_by_buffer = HashMap::default();
15750 for selection in selections {
15751 for (buffer, range, _) in
15752 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15753 {
15754 let mut range = range.to_point(buffer);
15755 range.start.column = 0;
15756 range.end.column = buffer.line_len(range.end.row);
15757 new_selections_by_buffer
15758 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15759 .or_insert(Vec::new())
15760 .push(range)
15761 }
15762 }
15763
15764 let proposed_changes_buffers = new_selections_by_buffer
15765 .into_iter()
15766 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15767 .collect::<Vec<_>>();
15768 let proposed_changes_editor = cx.new(|cx| {
15769 ProposedChangesEditor::new(
15770 "Proposed changes",
15771 proposed_changes_buffers,
15772 self.project.clone(),
15773 window,
15774 cx,
15775 )
15776 });
15777
15778 window.defer(cx, move |window, cx| {
15779 workspace.update(cx, |workspace, cx| {
15780 workspace.active_pane().update(cx, |pane, cx| {
15781 pane.add_item(
15782 Box::new(proposed_changes_editor),
15783 true,
15784 true,
15785 None,
15786 window,
15787 cx,
15788 );
15789 });
15790 });
15791 });
15792 }
15793
15794 pub fn open_excerpts_in_split(
15795 &mut self,
15796 _: &OpenExcerptsSplit,
15797 window: &mut Window,
15798 cx: &mut Context<Self>,
15799 ) {
15800 self.open_excerpts_common(None, true, window, cx)
15801 }
15802
15803 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15804 self.open_excerpts_common(None, false, window, cx)
15805 }
15806
15807 fn open_excerpts_common(
15808 &mut self,
15809 jump_data: Option<JumpData>,
15810 split: bool,
15811 window: &mut Window,
15812 cx: &mut Context<Self>,
15813 ) {
15814 let Some(workspace) = self.workspace() else {
15815 cx.propagate();
15816 return;
15817 };
15818
15819 if self.buffer.read(cx).is_singleton() {
15820 cx.propagate();
15821 return;
15822 }
15823
15824 let mut new_selections_by_buffer = HashMap::default();
15825 match &jump_data {
15826 Some(JumpData::MultiBufferPoint {
15827 excerpt_id,
15828 position,
15829 anchor,
15830 line_offset_from_top,
15831 }) => {
15832 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15833 if let Some(buffer) = multi_buffer_snapshot
15834 .buffer_id_for_excerpt(*excerpt_id)
15835 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15836 {
15837 let buffer_snapshot = buffer.read(cx).snapshot();
15838 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15839 language::ToPoint::to_point(anchor, &buffer_snapshot)
15840 } else {
15841 buffer_snapshot.clip_point(*position, Bias::Left)
15842 };
15843 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15844 new_selections_by_buffer.insert(
15845 buffer,
15846 (
15847 vec![jump_to_offset..jump_to_offset],
15848 Some(*line_offset_from_top),
15849 ),
15850 );
15851 }
15852 }
15853 Some(JumpData::MultiBufferRow {
15854 row,
15855 line_offset_from_top,
15856 }) => {
15857 let point = MultiBufferPoint::new(row.0, 0);
15858 if let Some((buffer, buffer_point, _)) =
15859 self.buffer.read(cx).point_to_buffer_point(point, cx)
15860 {
15861 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15862 new_selections_by_buffer
15863 .entry(buffer)
15864 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15865 .0
15866 .push(buffer_offset..buffer_offset)
15867 }
15868 }
15869 None => {
15870 let selections = self.selections.all::<usize>(cx);
15871 let multi_buffer = self.buffer.read(cx);
15872 for selection in selections {
15873 for (snapshot, range, _, anchor) in multi_buffer
15874 .snapshot(cx)
15875 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15876 {
15877 if let Some(anchor) = anchor {
15878 // selection is in a deleted hunk
15879 let Some(buffer_id) = anchor.buffer_id else {
15880 continue;
15881 };
15882 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15883 continue;
15884 };
15885 let offset = text::ToOffset::to_offset(
15886 &anchor.text_anchor,
15887 &buffer_handle.read(cx).snapshot(),
15888 );
15889 let range = offset..offset;
15890 new_selections_by_buffer
15891 .entry(buffer_handle)
15892 .or_insert((Vec::new(), None))
15893 .0
15894 .push(range)
15895 } else {
15896 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15897 else {
15898 continue;
15899 };
15900 new_selections_by_buffer
15901 .entry(buffer_handle)
15902 .or_insert((Vec::new(), None))
15903 .0
15904 .push(range)
15905 }
15906 }
15907 }
15908 }
15909 }
15910
15911 if new_selections_by_buffer.is_empty() {
15912 return;
15913 }
15914
15915 // We defer the pane interaction because we ourselves are a workspace item
15916 // and activating a new item causes the pane to call a method on us reentrantly,
15917 // which panics if we're on the stack.
15918 window.defer(cx, move |window, cx| {
15919 workspace.update(cx, |workspace, cx| {
15920 let pane = if split {
15921 workspace.adjacent_pane(window, cx)
15922 } else {
15923 workspace.active_pane().clone()
15924 };
15925
15926 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15927 let editor = buffer
15928 .read(cx)
15929 .file()
15930 .is_none()
15931 .then(|| {
15932 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15933 // so `workspace.open_project_item` will never find them, always opening a new editor.
15934 // Instead, we try to activate the existing editor in the pane first.
15935 let (editor, pane_item_index) =
15936 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15937 let editor = item.downcast::<Editor>()?;
15938 let singleton_buffer =
15939 editor.read(cx).buffer().read(cx).as_singleton()?;
15940 if singleton_buffer == buffer {
15941 Some((editor, i))
15942 } else {
15943 None
15944 }
15945 })?;
15946 pane.update(cx, |pane, cx| {
15947 pane.activate_item(pane_item_index, true, true, window, cx)
15948 });
15949 Some(editor)
15950 })
15951 .flatten()
15952 .unwrap_or_else(|| {
15953 workspace.open_project_item::<Self>(
15954 pane.clone(),
15955 buffer,
15956 true,
15957 true,
15958 window,
15959 cx,
15960 )
15961 });
15962
15963 editor.update(cx, |editor, cx| {
15964 let autoscroll = match scroll_offset {
15965 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15966 None => Autoscroll::newest(),
15967 };
15968 let nav_history = editor.nav_history.take();
15969 editor.change_selections(Some(autoscroll), window, cx, |s| {
15970 s.select_ranges(ranges);
15971 });
15972 editor.nav_history = nav_history;
15973 });
15974 }
15975 })
15976 });
15977 }
15978
15979 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15980 let snapshot = self.buffer.read(cx).read(cx);
15981 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15982 Some(
15983 ranges
15984 .iter()
15985 .map(move |range| {
15986 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15987 })
15988 .collect(),
15989 )
15990 }
15991
15992 fn selection_replacement_ranges(
15993 &self,
15994 range: Range<OffsetUtf16>,
15995 cx: &mut App,
15996 ) -> Vec<Range<OffsetUtf16>> {
15997 let selections = self.selections.all::<OffsetUtf16>(cx);
15998 let newest_selection = selections
15999 .iter()
16000 .max_by_key(|selection| selection.id)
16001 .unwrap();
16002 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16003 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16004 let snapshot = self.buffer.read(cx).read(cx);
16005 selections
16006 .into_iter()
16007 .map(|mut selection| {
16008 selection.start.0 =
16009 (selection.start.0 as isize).saturating_add(start_delta) as usize;
16010 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16011 snapshot.clip_offset_utf16(selection.start, Bias::Left)
16012 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16013 })
16014 .collect()
16015 }
16016
16017 fn report_editor_event(
16018 &self,
16019 event_type: &'static str,
16020 file_extension: Option<String>,
16021 cx: &App,
16022 ) {
16023 if cfg!(any(test, feature = "test-support")) {
16024 return;
16025 }
16026
16027 let Some(project) = &self.project else { return };
16028
16029 // If None, we are in a file without an extension
16030 let file = self
16031 .buffer
16032 .read(cx)
16033 .as_singleton()
16034 .and_then(|b| b.read(cx).file());
16035 let file_extension = file_extension.or(file
16036 .as_ref()
16037 .and_then(|file| Path::new(file.file_name(cx)).extension())
16038 .and_then(|e| e.to_str())
16039 .map(|a| a.to_string()));
16040
16041 let vim_mode = cx
16042 .global::<SettingsStore>()
16043 .raw_user_settings()
16044 .get("vim_mode")
16045 == Some(&serde_json::Value::Bool(true));
16046
16047 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16048 let copilot_enabled = edit_predictions_provider
16049 == language::language_settings::EditPredictionProvider::Copilot;
16050 let copilot_enabled_for_language = self
16051 .buffer
16052 .read(cx)
16053 .language_settings(cx)
16054 .show_edit_predictions;
16055
16056 let project = project.read(cx);
16057 telemetry::event!(
16058 event_type,
16059 file_extension,
16060 vim_mode,
16061 copilot_enabled,
16062 copilot_enabled_for_language,
16063 edit_predictions_provider,
16064 is_via_ssh = project.is_via_ssh(),
16065 );
16066 }
16067
16068 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16069 /// with each line being an array of {text, highlight} objects.
16070 fn copy_highlight_json(
16071 &mut self,
16072 _: &CopyHighlightJson,
16073 window: &mut Window,
16074 cx: &mut Context<Self>,
16075 ) {
16076 #[derive(Serialize)]
16077 struct Chunk<'a> {
16078 text: String,
16079 highlight: Option<&'a str>,
16080 }
16081
16082 let snapshot = self.buffer.read(cx).snapshot(cx);
16083 let range = self
16084 .selected_text_range(false, window, cx)
16085 .and_then(|selection| {
16086 if selection.range.is_empty() {
16087 None
16088 } else {
16089 Some(selection.range)
16090 }
16091 })
16092 .unwrap_or_else(|| 0..snapshot.len());
16093
16094 let chunks = snapshot.chunks(range, true);
16095 let mut lines = Vec::new();
16096 let mut line: VecDeque<Chunk> = VecDeque::new();
16097
16098 let Some(style) = self.style.as_ref() else {
16099 return;
16100 };
16101
16102 for chunk in chunks {
16103 let highlight = chunk
16104 .syntax_highlight_id
16105 .and_then(|id| id.name(&style.syntax));
16106 let mut chunk_lines = chunk.text.split('\n').peekable();
16107 while let Some(text) = chunk_lines.next() {
16108 let mut merged_with_last_token = false;
16109 if let Some(last_token) = line.back_mut() {
16110 if last_token.highlight == highlight {
16111 last_token.text.push_str(text);
16112 merged_with_last_token = true;
16113 }
16114 }
16115
16116 if !merged_with_last_token {
16117 line.push_back(Chunk {
16118 text: text.into(),
16119 highlight,
16120 });
16121 }
16122
16123 if chunk_lines.peek().is_some() {
16124 if line.len() > 1 && line.front().unwrap().text.is_empty() {
16125 line.pop_front();
16126 }
16127 if line.len() > 1 && line.back().unwrap().text.is_empty() {
16128 line.pop_back();
16129 }
16130
16131 lines.push(mem::take(&mut line));
16132 }
16133 }
16134 }
16135
16136 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16137 return;
16138 };
16139 cx.write_to_clipboard(ClipboardItem::new_string(lines));
16140 }
16141
16142 pub fn open_context_menu(
16143 &mut self,
16144 _: &OpenContextMenu,
16145 window: &mut Window,
16146 cx: &mut Context<Self>,
16147 ) {
16148 self.request_autoscroll(Autoscroll::newest(), cx);
16149 let position = self.selections.newest_display(cx).start;
16150 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16151 }
16152
16153 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16154 &self.inlay_hint_cache
16155 }
16156
16157 pub fn replay_insert_event(
16158 &mut self,
16159 text: &str,
16160 relative_utf16_range: Option<Range<isize>>,
16161 window: &mut Window,
16162 cx: &mut Context<Self>,
16163 ) {
16164 if !self.input_enabled {
16165 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16166 return;
16167 }
16168 if let Some(relative_utf16_range) = relative_utf16_range {
16169 let selections = self.selections.all::<OffsetUtf16>(cx);
16170 self.change_selections(None, window, cx, |s| {
16171 let new_ranges = selections.into_iter().map(|range| {
16172 let start = OffsetUtf16(
16173 range
16174 .head()
16175 .0
16176 .saturating_add_signed(relative_utf16_range.start),
16177 );
16178 let end = OffsetUtf16(
16179 range
16180 .head()
16181 .0
16182 .saturating_add_signed(relative_utf16_range.end),
16183 );
16184 start..end
16185 });
16186 s.select_ranges(new_ranges);
16187 });
16188 }
16189
16190 self.handle_input(text, window, cx);
16191 }
16192
16193 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16194 let Some(provider) = self.semantics_provider.as_ref() else {
16195 return false;
16196 };
16197
16198 let mut supports = false;
16199 self.buffer().update(cx, |this, cx| {
16200 this.for_each_buffer(|buffer| {
16201 supports |= provider.supports_inlay_hints(buffer, cx);
16202 });
16203 });
16204
16205 supports
16206 }
16207
16208 pub fn is_focused(&self, window: &Window) -> bool {
16209 self.focus_handle.is_focused(window)
16210 }
16211
16212 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16213 cx.emit(EditorEvent::Focused);
16214
16215 if let Some(descendant) = self
16216 .last_focused_descendant
16217 .take()
16218 .and_then(|descendant| descendant.upgrade())
16219 {
16220 window.focus(&descendant);
16221 } else {
16222 if let Some(blame) = self.blame.as_ref() {
16223 blame.update(cx, GitBlame::focus)
16224 }
16225
16226 self.blink_manager.update(cx, BlinkManager::enable);
16227 self.show_cursor_names(window, cx);
16228 self.buffer.update(cx, |buffer, cx| {
16229 buffer.finalize_last_transaction(cx);
16230 if self.leader_peer_id.is_none() {
16231 buffer.set_active_selections(
16232 &self.selections.disjoint_anchors(),
16233 self.selections.line_mode,
16234 self.cursor_shape,
16235 cx,
16236 );
16237 }
16238 });
16239 }
16240 }
16241
16242 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16243 cx.emit(EditorEvent::FocusedIn)
16244 }
16245
16246 fn handle_focus_out(
16247 &mut self,
16248 event: FocusOutEvent,
16249 _window: &mut Window,
16250 cx: &mut Context<Self>,
16251 ) {
16252 if event.blurred != self.focus_handle {
16253 self.last_focused_descendant = Some(event.blurred);
16254 }
16255 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16256 }
16257
16258 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16259 self.blink_manager.update(cx, BlinkManager::disable);
16260 self.buffer
16261 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16262
16263 if let Some(blame) = self.blame.as_ref() {
16264 blame.update(cx, GitBlame::blur)
16265 }
16266 if !self.hover_state.focused(window, cx) {
16267 hide_hover(self, cx);
16268 }
16269 if !self
16270 .context_menu
16271 .borrow()
16272 .as_ref()
16273 .is_some_and(|context_menu| context_menu.focused(window, cx))
16274 {
16275 self.hide_context_menu(window, cx);
16276 }
16277 self.discard_inline_completion(false, cx);
16278 cx.emit(EditorEvent::Blurred);
16279 cx.notify();
16280 }
16281
16282 pub fn register_action<A: Action>(
16283 &mut self,
16284 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16285 ) -> Subscription {
16286 let id = self.next_editor_action_id.post_inc();
16287 let listener = Arc::new(listener);
16288 self.editor_actions.borrow_mut().insert(
16289 id,
16290 Box::new(move |window, _| {
16291 let listener = listener.clone();
16292 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16293 let action = action.downcast_ref().unwrap();
16294 if phase == DispatchPhase::Bubble {
16295 listener(action, window, cx)
16296 }
16297 })
16298 }),
16299 );
16300
16301 let editor_actions = self.editor_actions.clone();
16302 Subscription::new(move || {
16303 editor_actions.borrow_mut().remove(&id);
16304 })
16305 }
16306
16307 pub fn file_header_size(&self) -> u32 {
16308 FILE_HEADER_HEIGHT
16309 }
16310
16311 pub fn restore(
16312 &mut self,
16313 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16314 window: &mut Window,
16315 cx: &mut Context<Self>,
16316 ) {
16317 let workspace = self.workspace();
16318 let project = self.project.as_ref();
16319 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16320 let mut tasks = Vec::new();
16321 for (buffer_id, changes) in revert_changes {
16322 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16323 buffer.update(cx, |buffer, cx| {
16324 buffer.edit(
16325 changes
16326 .into_iter()
16327 .map(|(range, text)| (range, text.to_string())),
16328 None,
16329 cx,
16330 );
16331 });
16332
16333 if let Some(project) =
16334 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16335 {
16336 project.update(cx, |project, cx| {
16337 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16338 })
16339 }
16340 }
16341 }
16342 tasks
16343 });
16344 cx.spawn_in(window, |_, mut cx| async move {
16345 for (buffer, task) in save_tasks {
16346 let result = task.await;
16347 if result.is_err() {
16348 let Some(path) = buffer
16349 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16350 .ok()
16351 else {
16352 continue;
16353 };
16354 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16355 let Some(task) = cx
16356 .update_window_entity(&workspace, |workspace, window, cx| {
16357 workspace
16358 .open_path_preview(path, None, false, false, false, window, cx)
16359 })
16360 .ok()
16361 else {
16362 continue;
16363 };
16364 task.await.log_err();
16365 }
16366 }
16367 }
16368 })
16369 .detach();
16370 self.change_selections(None, window, cx, |selections| selections.refresh());
16371 }
16372
16373 pub fn to_pixel_point(
16374 &self,
16375 source: multi_buffer::Anchor,
16376 editor_snapshot: &EditorSnapshot,
16377 window: &mut Window,
16378 ) -> Option<gpui::Point<Pixels>> {
16379 let source_point = source.to_display_point(editor_snapshot);
16380 self.display_to_pixel_point(source_point, editor_snapshot, window)
16381 }
16382
16383 pub fn display_to_pixel_point(
16384 &self,
16385 source: DisplayPoint,
16386 editor_snapshot: &EditorSnapshot,
16387 window: &mut Window,
16388 ) -> Option<gpui::Point<Pixels>> {
16389 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16390 let text_layout_details = self.text_layout_details(window);
16391 let scroll_top = text_layout_details
16392 .scroll_anchor
16393 .scroll_position(editor_snapshot)
16394 .y;
16395
16396 if source.row().as_f32() < scroll_top.floor() {
16397 return None;
16398 }
16399 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16400 let source_y = line_height * (source.row().as_f32() - scroll_top);
16401 Some(gpui::Point::new(source_x, source_y))
16402 }
16403
16404 pub fn has_visible_completions_menu(&self) -> bool {
16405 !self.edit_prediction_preview_is_active()
16406 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16407 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16408 })
16409 }
16410
16411 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16412 self.addons
16413 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16414 }
16415
16416 pub fn unregister_addon<T: Addon>(&mut self) {
16417 self.addons.remove(&std::any::TypeId::of::<T>());
16418 }
16419
16420 pub fn addon<T: Addon>(&self) -> Option<&T> {
16421 let type_id = std::any::TypeId::of::<T>();
16422 self.addons
16423 .get(&type_id)
16424 .and_then(|item| item.to_any().downcast_ref::<T>())
16425 }
16426
16427 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16428 let text_layout_details = self.text_layout_details(window);
16429 let style = &text_layout_details.editor_style;
16430 let font_id = window.text_system().resolve_font(&style.text.font());
16431 let font_size = style.text.font_size.to_pixels(window.rem_size());
16432 let line_height = style.text.line_height_in_pixels(window.rem_size());
16433 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16434
16435 gpui::Size::new(em_width, line_height)
16436 }
16437
16438 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16439 self.load_diff_task.clone()
16440 }
16441
16442 fn read_selections_from_db(
16443 &mut self,
16444 item_id: u64,
16445 workspace_id: WorkspaceId,
16446 window: &mut Window,
16447 cx: &mut Context<Editor>,
16448 ) {
16449 if !self.is_singleton(cx)
16450 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16451 {
16452 return;
16453 }
16454 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16455 return;
16456 };
16457 if selections.is_empty() {
16458 return;
16459 }
16460
16461 let snapshot = self.buffer.read(cx).snapshot(cx);
16462 self.change_selections(None, window, cx, |s| {
16463 s.select_ranges(selections.into_iter().map(|(start, end)| {
16464 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16465 }));
16466 });
16467 }
16468}
16469
16470fn insert_extra_newline_brackets(
16471 buffer: &MultiBufferSnapshot,
16472 range: Range<usize>,
16473 language: &language::LanguageScope,
16474) -> bool {
16475 let leading_whitespace_len = buffer
16476 .reversed_chars_at(range.start)
16477 .take_while(|c| c.is_whitespace() && *c != '\n')
16478 .map(|c| c.len_utf8())
16479 .sum::<usize>();
16480 let trailing_whitespace_len = buffer
16481 .chars_at(range.end)
16482 .take_while(|c| c.is_whitespace() && *c != '\n')
16483 .map(|c| c.len_utf8())
16484 .sum::<usize>();
16485 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16486
16487 language.brackets().any(|(pair, enabled)| {
16488 let pair_start = pair.start.trim_end();
16489 let pair_end = pair.end.trim_start();
16490
16491 enabled
16492 && pair.newline
16493 && buffer.contains_str_at(range.end, pair_end)
16494 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16495 })
16496}
16497
16498fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16499 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16500 [(buffer, range, _)] => (*buffer, range.clone()),
16501 _ => return false,
16502 };
16503 let pair = {
16504 let mut result: Option<BracketMatch> = None;
16505
16506 for pair in buffer
16507 .all_bracket_ranges(range.clone())
16508 .filter(move |pair| {
16509 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16510 })
16511 {
16512 let len = pair.close_range.end - pair.open_range.start;
16513
16514 if let Some(existing) = &result {
16515 let existing_len = existing.close_range.end - existing.open_range.start;
16516 if len > existing_len {
16517 continue;
16518 }
16519 }
16520
16521 result = Some(pair);
16522 }
16523
16524 result
16525 };
16526 let Some(pair) = pair else {
16527 return false;
16528 };
16529 pair.newline_only
16530 && buffer
16531 .chars_for_range(pair.open_range.end..range.start)
16532 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16533 .all(|c| c.is_whitespace() && c != '\n')
16534}
16535
16536fn get_uncommitted_diff_for_buffer(
16537 project: &Entity<Project>,
16538 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16539 buffer: Entity<MultiBuffer>,
16540 cx: &mut App,
16541) -> Task<()> {
16542 let mut tasks = Vec::new();
16543 project.update(cx, |project, cx| {
16544 for buffer in buffers {
16545 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16546 }
16547 });
16548 cx.spawn(|mut cx| async move {
16549 let diffs = future::join_all(tasks).await;
16550 buffer
16551 .update(&mut cx, |buffer, cx| {
16552 for diff in diffs.into_iter().flatten() {
16553 buffer.add_diff(diff, cx);
16554 }
16555 })
16556 .ok();
16557 })
16558}
16559
16560fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16561 let tab_size = tab_size.get() as usize;
16562 let mut width = offset;
16563
16564 for ch in text.chars() {
16565 width += if ch == '\t' {
16566 tab_size - (width % tab_size)
16567 } else {
16568 1
16569 };
16570 }
16571
16572 width - offset
16573}
16574
16575#[cfg(test)]
16576mod tests {
16577 use super::*;
16578
16579 #[test]
16580 fn test_string_size_with_expanded_tabs() {
16581 let nz = |val| NonZeroU32::new(val).unwrap();
16582 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16583 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16584 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16585 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16586 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16587 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16588 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16589 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16590 }
16591}
16592
16593/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16594struct WordBreakingTokenizer<'a> {
16595 input: &'a str,
16596}
16597
16598impl<'a> WordBreakingTokenizer<'a> {
16599 fn new(input: &'a str) -> Self {
16600 Self { input }
16601 }
16602}
16603
16604fn is_char_ideographic(ch: char) -> bool {
16605 use unicode_script::Script::*;
16606 use unicode_script::UnicodeScript;
16607 matches!(ch.script(), Han | Tangut | Yi)
16608}
16609
16610fn is_grapheme_ideographic(text: &str) -> bool {
16611 text.chars().any(is_char_ideographic)
16612}
16613
16614fn is_grapheme_whitespace(text: &str) -> bool {
16615 text.chars().any(|x| x.is_whitespace())
16616}
16617
16618fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16619 text.chars().next().map_or(false, |ch| {
16620 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16621 })
16622}
16623
16624#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16625struct WordBreakToken<'a> {
16626 token: &'a str,
16627 grapheme_len: usize,
16628 is_whitespace: bool,
16629}
16630
16631impl<'a> Iterator for WordBreakingTokenizer<'a> {
16632 /// Yields a span, the count of graphemes in the token, and whether it was
16633 /// whitespace. Note that it also breaks at word boundaries.
16634 type Item = WordBreakToken<'a>;
16635
16636 fn next(&mut self) -> Option<Self::Item> {
16637 use unicode_segmentation::UnicodeSegmentation;
16638 if self.input.is_empty() {
16639 return None;
16640 }
16641
16642 let mut iter = self.input.graphemes(true).peekable();
16643 let mut offset = 0;
16644 let mut graphemes = 0;
16645 if let Some(first_grapheme) = iter.next() {
16646 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16647 offset += first_grapheme.len();
16648 graphemes += 1;
16649 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16650 if let Some(grapheme) = iter.peek().copied() {
16651 if should_stay_with_preceding_ideograph(grapheme) {
16652 offset += grapheme.len();
16653 graphemes += 1;
16654 }
16655 }
16656 } else {
16657 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16658 let mut next_word_bound = words.peek().copied();
16659 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16660 next_word_bound = words.next();
16661 }
16662 while let Some(grapheme) = iter.peek().copied() {
16663 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16664 break;
16665 };
16666 if is_grapheme_whitespace(grapheme) != is_whitespace {
16667 break;
16668 };
16669 offset += grapheme.len();
16670 graphemes += 1;
16671 iter.next();
16672 }
16673 }
16674 let token = &self.input[..offset];
16675 self.input = &self.input[offset..];
16676 if is_whitespace {
16677 Some(WordBreakToken {
16678 token: " ",
16679 grapheme_len: 1,
16680 is_whitespace: true,
16681 })
16682 } else {
16683 Some(WordBreakToken {
16684 token,
16685 grapheme_len: graphemes,
16686 is_whitespace: false,
16687 })
16688 }
16689 } else {
16690 None
16691 }
16692 }
16693}
16694
16695#[test]
16696fn test_word_breaking_tokenizer() {
16697 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16698 ("", &[]),
16699 (" ", &[(" ", 1, true)]),
16700 ("Ʒ", &[("Ʒ", 1, false)]),
16701 ("Ǽ", &[("Ǽ", 1, false)]),
16702 ("⋑", &[("⋑", 1, false)]),
16703 ("⋑⋑", &[("⋑⋑", 2, false)]),
16704 (
16705 "原理,进而",
16706 &[
16707 ("原", 1, false),
16708 ("理,", 2, false),
16709 ("进", 1, false),
16710 ("而", 1, false),
16711 ],
16712 ),
16713 (
16714 "hello world",
16715 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16716 ),
16717 (
16718 "hello, world",
16719 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16720 ),
16721 (
16722 " hello world",
16723 &[
16724 (" ", 1, true),
16725 ("hello", 5, false),
16726 (" ", 1, true),
16727 ("world", 5, false),
16728 ],
16729 ),
16730 (
16731 "这是什么 \n 钢笔",
16732 &[
16733 ("这", 1, false),
16734 ("是", 1, false),
16735 ("什", 1, false),
16736 ("么", 1, false),
16737 (" ", 1, true),
16738 ("钢", 1, false),
16739 ("笔", 1, false),
16740 ],
16741 ),
16742 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16743 ];
16744
16745 for (input, result) in tests {
16746 assert_eq!(
16747 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16748 result
16749 .iter()
16750 .copied()
16751 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16752 token,
16753 grapheme_len,
16754 is_whitespace,
16755 })
16756 .collect::<Vec<_>>()
16757 );
16758 }
16759}
16760
16761fn wrap_with_prefix(
16762 line_prefix: String,
16763 unwrapped_text: String,
16764 wrap_column: usize,
16765 tab_size: NonZeroU32,
16766) -> String {
16767 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16768 let mut wrapped_text = String::new();
16769 let mut current_line = line_prefix.clone();
16770
16771 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16772 let mut current_line_len = line_prefix_len;
16773 for WordBreakToken {
16774 token,
16775 grapheme_len,
16776 is_whitespace,
16777 } in tokenizer
16778 {
16779 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16780 wrapped_text.push_str(current_line.trim_end());
16781 wrapped_text.push('\n');
16782 current_line.truncate(line_prefix.len());
16783 current_line_len = line_prefix_len;
16784 if !is_whitespace {
16785 current_line.push_str(token);
16786 current_line_len += grapheme_len;
16787 }
16788 } else if !is_whitespace {
16789 current_line.push_str(token);
16790 current_line_len += grapheme_len;
16791 } else if current_line_len != line_prefix_len {
16792 current_line.push(' ');
16793 current_line_len += 1;
16794 }
16795 }
16796
16797 if !current_line.is_empty() {
16798 wrapped_text.push_str(¤t_line);
16799 }
16800 wrapped_text
16801}
16802
16803#[test]
16804fn test_wrap_with_prefix() {
16805 assert_eq!(
16806 wrap_with_prefix(
16807 "# ".to_string(),
16808 "abcdefg".to_string(),
16809 4,
16810 NonZeroU32::new(4).unwrap()
16811 ),
16812 "# abcdefg"
16813 );
16814 assert_eq!(
16815 wrap_with_prefix(
16816 "".to_string(),
16817 "\thello world".to_string(),
16818 8,
16819 NonZeroU32::new(4).unwrap()
16820 ),
16821 "hello\nworld"
16822 );
16823 assert_eq!(
16824 wrap_with_prefix(
16825 "// ".to_string(),
16826 "xx \nyy zz aa bb cc".to_string(),
16827 12,
16828 NonZeroU32::new(4).unwrap()
16829 ),
16830 "// xx yy zz\n// aa bb cc"
16831 );
16832 assert_eq!(
16833 wrap_with_prefix(
16834 String::new(),
16835 "这是什么 \n 钢笔".to_string(),
16836 3,
16837 NonZeroU32::new(4).unwrap()
16838 ),
16839 "这是什\n么 钢\n笔"
16840 );
16841}
16842
16843pub trait CollaborationHub {
16844 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16845 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16846 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16847}
16848
16849impl CollaborationHub for Entity<Project> {
16850 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16851 self.read(cx).collaborators()
16852 }
16853
16854 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16855 self.read(cx).user_store().read(cx).participant_indices()
16856 }
16857
16858 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16859 let this = self.read(cx);
16860 let user_ids = this.collaborators().values().map(|c| c.user_id);
16861 this.user_store().read_with(cx, |user_store, cx| {
16862 user_store.participant_names(user_ids, cx)
16863 })
16864 }
16865}
16866
16867pub trait SemanticsProvider {
16868 fn hover(
16869 &self,
16870 buffer: &Entity<Buffer>,
16871 position: text::Anchor,
16872 cx: &mut App,
16873 ) -> Option<Task<Vec<project::Hover>>>;
16874
16875 fn inlay_hints(
16876 &self,
16877 buffer_handle: Entity<Buffer>,
16878 range: Range<text::Anchor>,
16879 cx: &mut App,
16880 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16881
16882 fn resolve_inlay_hint(
16883 &self,
16884 hint: InlayHint,
16885 buffer_handle: Entity<Buffer>,
16886 server_id: LanguageServerId,
16887 cx: &mut App,
16888 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16889
16890 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16891
16892 fn document_highlights(
16893 &self,
16894 buffer: &Entity<Buffer>,
16895 position: text::Anchor,
16896 cx: &mut App,
16897 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16898
16899 fn definitions(
16900 &self,
16901 buffer: &Entity<Buffer>,
16902 position: text::Anchor,
16903 kind: GotoDefinitionKind,
16904 cx: &mut App,
16905 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16906
16907 fn range_for_rename(
16908 &self,
16909 buffer: &Entity<Buffer>,
16910 position: text::Anchor,
16911 cx: &mut App,
16912 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16913
16914 fn perform_rename(
16915 &self,
16916 buffer: &Entity<Buffer>,
16917 position: text::Anchor,
16918 new_name: String,
16919 cx: &mut App,
16920 ) -> Option<Task<Result<ProjectTransaction>>>;
16921}
16922
16923pub trait CompletionProvider {
16924 fn completions(
16925 &self,
16926 buffer: &Entity<Buffer>,
16927 buffer_position: text::Anchor,
16928 trigger: CompletionContext,
16929 window: &mut Window,
16930 cx: &mut Context<Editor>,
16931 ) -> Task<Result<Vec<Completion>>>;
16932
16933 fn resolve_completions(
16934 &self,
16935 buffer: Entity<Buffer>,
16936 completion_indices: Vec<usize>,
16937 completions: Rc<RefCell<Box<[Completion]>>>,
16938 cx: &mut Context<Editor>,
16939 ) -> Task<Result<bool>>;
16940
16941 fn apply_additional_edits_for_completion(
16942 &self,
16943 _buffer: Entity<Buffer>,
16944 _completions: Rc<RefCell<Box<[Completion]>>>,
16945 _completion_index: usize,
16946 _push_to_history: bool,
16947 _cx: &mut Context<Editor>,
16948 ) -> Task<Result<Option<language::Transaction>>> {
16949 Task::ready(Ok(None))
16950 }
16951
16952 fn is_completion_trigger(
16953 &self,
16954 buffer: &Entity<Buffer>,
16955 position: language::Anchor,
16956 text: &str,
16957 trigger_in_words: bool,
16958 cx: &mut Context<Editor>,
16959 ) -> bool;
16960
16961 fn sort_completions(&self) -> bool {
16962 true
16963 }
16964}
16965
16966pub trait CodeActionProvider {
16967 fn id(&self) -> Arc<str>;
16968
16969 fn code_actions(
16970 &self,
16971 buffer: &Entity<Buffer>,
16972 range: Range<text::Anchor>,
16973 window: &mut Window,
16974 cx: &mut App,
16975 ) -> Task<Result<Vec<CodeAction>>>;
16976
16977 fn apply_code_action(
16978 &self,
16979 buffer_handle: Entity<Buffer>,
16980 action: CodeAction,
16981 excerpt_id: ExcerptId,
16982 push_to_history: bool,
16983 window: &mut Window,
16984 cx: &mut App,
16985 ) -> Task<Result<ProjectTransaction>>;
16986}
16987
16988impl CodeActionProvider for Entity<Project> {
16989 fn id(&self) -> Arc<str> {
16990 "project".into()
16991 }
16992
16993 fn code_actions(
16994 &self,
16995 buffer: &Entity<Buffer>,
16996 range: Range<text::Anchor>,
16997 _window: &mut Window,
16998 cx: &mut App,
16999 ) -> Task<Result<Vec<CodeAction>>> {
17000 self.update(cx, |project, cx| {
17001 project.code_actions(buffer, range, None, cx)
17002 })
17003 }
17004
17005 fn apply_code_action(
17006 &self,
17007 buffer_handle: Entity<Buffer>,
17008 action: CodeAction,
17009 _excerpt_id: ExcerptId,
17010 push_to_history: bool,
17011 _window: &mut Window,
17012 cx: &mut App,
17013 ) -> Task<Result<ProjectTransaction>> {
17014 self.update(cx, |project, cx| {
17015 project.apply_code_action(buffer_handle, action, push_to_history, cx)
17016 })
17017 }
17018}
17019
17020fn snippet_completions(
17021 project: &Project,
17022 buffer: &Entity<Buffer>,
17023 buffer_position: text::Anchor,
17024 cx: &mut App,
17025) -> Task<Result<Vec<Completion>>> {
17026 let language = buffer.read(cx).language_at(buffer_position);
17027 let language_name = language.as_ref().map(|language| language.lsp_id());
17028 let snippet_store = project.snippets().read(cx);
17029 let snippets = snippet_store.snippets_for(language_name, cx);
17030
17031 if snippets.is_empty() {
17032 return Task::ready(Ok(vec![]));
17033 }
17034 let snapshot = buffer.read(cx).text_snapshot();
17035 let chars: String = snapshot
17036 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17037 .collect();
17038
17039 let scope = language.map(|language| language.default_scope());
17040 let executor = cx.background_executor().clone();
17041
17042 cx.background_spawn(async move {
17043 let classifier = CharClassifier::new(scope).for_completion(true);
17044 let mut last_word = chars
17045 .chars()
17046 .take_while(|c| classifier.is_word(*c))
17047 .collect::<String>();
17048 last_word = last_word.chars().rev().collect();
17049
17050 if last_word.is_empty() {
17051 return Ok(vec![]);
17052 }
17053
17054 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17055 let to_lsp = |point: &text::Anchor| {
17056 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
17057 point_to_lsp(end)
17058 };
17059 let lsp_end = to_lsp(&buffer_position);
17060
17061 let candidates = snippets
17062 .iter()
17063 .enumerate()
17064 .flat_map(|(ix, snippet)| {
17065 snippet
17066 .prefix
17067 .iter()
17068 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
17069 })
17070 .collect::<Vec<StringMatchCandidate>>();
17071
17072 let mut matches = fuzzy::match_strings(
17073 &candidates,
17074 &last_word,
17075 last_word.chars().any(|c| c.is_uppercase()),
17076 100,
17077 &Default::default(),
17078 executor,
17079 )
17080 .await;
17081
17082 // Remove all candidates where the query's start does not match the start of any word in the candidate
17083 if let Some(query_start) = last_word.chars().next() {
17084 matches.retain(|string_match| {
17085 split_words(&string_match.string).any(|word| {
17086 // Check that the first codepoint of the word as lowercase matches the first
17087 // codepoint of the query as lowercase
17088 word.chars()
17089 .flat_map(|codepoint| codepoint.to_lowercase())
17090 .zip(query_start.to_lowercase())
17091 .all(|(word_cp, query_cp)| word_cp == query_cp)
17092 })
17093 });
17094 }
17095
17096 let matched_strings = matches
17097 .into_iter()
17098 .map(|m| m.string)
17099 .collect::<HashSet<_>>();
17100
17101 let result: Vec<Completion> = snippets
17102 .into_iter()
17103 .filter_map(|snippet| {
17104 let matching_prefix = snippet
17105 .prefix
17106 .iter()
17107 .find(|prefix| matched_strings.contains(*prefix))?;
17108 let start = as_offset - last_word.len();
17109 let start = snapshot.anchor_before(start);
17110 let range = start..buffer_position;
17111 let lsp_start = to_lsp(&start);
17112 let lsp_range = lsp::Range {
17113 start: lsp_start,
17114 end: lsp_end,
17115 };
17116 Some(Completion {
17117 old_range: range,
17118 new_text: snippet.body.clone(),
17119 source: CompletionSource::Lsp {
17120 server_id: LanguageServerId(usize::MAX),
17121 resolved: true,
17122 lsp_completion: Box::new(lsp::CompletionItem {
17123 label: snippet.prefix.first().unwrap().clone(),
17124 kind: Some(CompletionItemKind::SNIPPET),
17125 label_details: snippet.description.as_ref().map(|description| {
17126 lsp::CompletionItemLabelDetails {
17127 detail: Some(description.clone()),
17128 description: None,
17129 }
17130 }),
17131 insert_text_format: Some(InsertTextFormat::SNIPPET),
17132 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17133 lsp::InsertReplaceEdit {
17134 new_text: snippet.body.clone(),
17135 insert: lsp_range,
17136 replace: lsp_range,
17137 },
17138 )),
17139 filter_text: Some(snippet.body.clone()),
17140 sort_text: Some(char::MAX.to_string()),
17141 ..lsp::CompletionItem::default()
17142 }),
17143 lsp_defaults: None,
17144 },
17145 label: CodeLabel {
17146 text: matching_prefix.clone(),
17147 runs: Vec::new(),
17148 filter_range: 0..matching_prefix.len(),
17149 },
17150 documentation: snippet
17151 .description
17152 .clone()
17153 .map(|description| CompletionDocumentation::SingleLine(description.into())),
17154 confirm: None,
17155 })
17156 })
17157 .collect();
17158
17159 Ok(result)
17160 })
17161}
17162
17163impl CompletionProvider for Entity<Project> {
17164 fn completions(
17165 &self,
17166 buffer: &Entity<Buffer>,
17167 buffer_position: text::Anchor,
17168 options: CompletionContext,
17169 _window: &mut Window,
17170 cx: &mut Context<Editor>,
17171 ) -> Task<Result<Vec<Completion>>> {
17172 self.update(cx, |project, cx| {
17173 let snippets = snippet_completions(project, buffer, buffer_position, cx);
17174 let project_completions = project.completions(buffer, buffer_position, options, cx);
17175 cx.background_spawn(async move {
17176 let mut completions = project_completions.await?;
17177 let snippets_completions = snippets.await?;
17178 completions.extend(snippets_completions);
17179 Ok(completions)
17180 })
17181 })
17182 }
17183
17184 fn resolve_completions(
17185 &self,
17186 buffer: Entity<Buffer>,
17187 completion_indices: Vec<usize>,
17188 completions: Rc<RefCell<Box<[Completion]>>>,
17189 cx: &mut Context<Editor>,
17190 ) -> Task<Result<bool>> {
17191 self.update(cx, |project, cx| {
17192 project.lsp_store().update(cx, |lsp_store, cx| {
17193 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17194 })
17195 })
17196 }
17197
17198 fn apply_additional_edits_for_completion(
17199 &self,
17200 buffer: Entity<Buffer>,
17201 completions: Rc<RefCell<Box<[Completion]>>>,
17202 completion_index: usize,
17203 push_to_history: bool,
17204 cx: &mut Context<Editor>,
17205 ) -> Task<Result<Option<language::Transaction>>> {
17206 self.update(cx, |project, cx| {
17207 project.lsp_store().update(cx, |lsp_store, cx| {
17208 lsp_store.apply_additional_edits_for_completion(
17209 buffer,
17210 completions,
17211 completion_index,
17212 push_to_history,
17213 cx,
17214 )
17215 })
17216 })
17217 }
17218
17219 fn is_completion_trigger(
17220 &self,
17221 buffer: &Entity<Buffer>,
17222 position: language::Anchor,
17223 text: &str,
17224 trigger_in_words: bool,
17225 cx: &mut Context<Editor>,
17226 ) -> bool {
17227 let mut chars = text.chars();
17228 let char = if let Some(char) = chars.next() {
17229 char
17230 } else {
17231 return false;
17232 };
17233 if chars.next().is_some() {
17234 return false;
17235 }
17236
17237 let buffer = buffer.read(cx);
17238 let snapshot = buffer.snapshot();
17239 if !snapshot.settings_at(position, cx).show_completions_on_input {
17240 return false;
17241 }
17242 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17243 if trigger_in_words && classifier.is_word(char) {
17244 return true;
17245 }
17246
17247 buffer.completion_triggers().contains(text)
17248 }
17249}
17250
17251impl SemanticsProvider for Entity<Project> {
17252 fn hover(
17253 &self,
17254 buffer: &Entity<Buffer>,
17255 position: text::Anchor,
17256 cx: &mut App,
17257 ) -> Option<Task<Vec<project::Hover>>> {
17258 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17259 }
17260
17261 fn document_highlights(
17262 &self,
17263 buffer: &Entity<Buffer>,
17264 position: text::Anchor,
17265 cx: &mut App,
17266 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17267 Some(self.update(cx, |project, cx| {
17268 project.document_highlights(buffer, position, cx)
17269 }))
17270 }
17271
17272 fn definitions(
17273 &self,
17274 buffer: &Entity<Buffer>,
17275 position: text::Anchor,
17276 kind: GotoDefinitionKind,
17277 cx: &mut App,
17278 ) -> Option<Task<Result<Vec<LocationLink>>>> {
17279 Some(self.update(cx, |project, cx| match kind {
17280 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17281 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17282 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17283 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17284 }))
17285 }
17286
17287 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17288 // TODO: make this work for remote projects
17289 self.update(cx, |this, cx| {
17290 buffer.update(cx, |buffer, cx| {
17291 this.any_language_server_supports_inlay_hints(buffer, cx)
17292 })
17293 })
17294 }
17295
17296 fn inlay_hints(
17297 &self,
17298 buffer_handle: Entity<Buffer>,
17299 range: Range<text::Anchor>,
17300 cx: &mut App,
17301 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17302 Some(self.update(cx, |project, cx| {
17303 project.inlay_hints(buffer_handle, range, cx)
17304 }))
17305 }
17306
17307 fn resolve_inlay_hint(
17308 &self,
17309 hint: InlayHint,
17310 buffer_handle: Entity<Buffer>,
17311 server_id: LanguageServerId,
17312 cx: &mut App,
17313 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17314 Some(self.update(cx, |project, cx| {
17315 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17316 }))
17317 }
17318
17319 fn range_for_rename(
17320 &self,
17321 buffer: &Entity<Buffer>,
17322 position: text::Anchor,
17323 cx: &mut App,
17324 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17325 Some(self.update(cx, |project, cx| {
17326 let buffer = buffer.clone();
17327 let task = project.prepare_rename(buffer.clone(), position, cx);
17328 cx.spawn(|_, mut cx| async move {
17329 Ok(match task.await? {
17330 PrepareRenameResponse::Success(range) => Some(range),
17331 PrepareRenameResponse::InvalidPosition => None,
17332 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17333 // Fallback on using TreeSitter info to determine identifier range
17334 buffer.update(&mut cx, |buffer, _| {
17335 let snapshot = buffer.snapshot();
17336 let (range, kind) = snapshot.surrounding_word(position);
17337 if kind != Some(CharKind::Word) {
17338 return None;
17339 }
17340 Some(
17341 snapshot.anchor_before(range.start)
17342 ..snapshot.anchor_after(range.end),
17343 )
17344 })?
17345 }
17346 })
17347 })
17348 }))
17349 }
17350
17351 fn perform_rename(
17352 &self,
17353 buffer: &Entity<Buffer>,
17354 position: text::Anchor,
17355 new_name: String,
17356 cx: &mut App,
17357 ) -> Option<Task<Result<ProjectTransaction>>> {
17358 Some(self.update(cx, |project, cx| {
17359 project.perform_rename(buffer.clone(), position, new_name, cx)
17360 }))
17361 }
17362}
17363
17364fn inlay_hint_settings(
17365 location: Anchor,
17366 snapshot: &MultiBufferSnapshot,
17367 cx: &mut Context<Editor>,
17368) -> InlayHintSettings {
17369 let file = snapshot.file_at(location);
17370 let language = snapshot.language_at(location).map(|l| l.name());
17371 language_settings(language, file, cx).inlay_hints
17372}
17373
17374fn consume_contiguous_rows(
17375 contiguous_row_selections: &mut Vec<Selection<Point>>,
17376 selection: &Selection<Point>,
17377 display_map: &DisplaySnapshot,
17378 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17379) -> (MultiBufferRow, MultiBufferRow) {
17380 contiguous_row_selections.push(selection.clone());
17381 let start_row = MultiBufferRow(selection.start.row);
17382 let mut end_row = ending_row(selection, display_map);
17383
17384 while let Some(next_selection) = selections.peek() {
17385 if next_selection.start.row <= end_row.0 {
17386 end_row = ending_row(next_selection, display_map);
17387 contiguous_row_selections.push(selections.next().unwrap().clone());
17388 } else {
17389 break;
17390 }
17391 }
17392 (start_row, end_row)
17393}
17394
17395fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17396 if next_selection.end.column > 0 || next_selection.is_empty() {
17397 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17398 } else {
17399 MultiBufferRow(next_selection.end.row)
17400 }
17401}
17402
17403impl EditorSnapshot {
17404 pub fn remote_selections_in_range<'a>(
17405 &'a self,
17406 range: &'a Range<Anchor>,
17407 collaboration_hub: &dyn CollaborationHub,
17408 cx: &'a App,
17409 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17410 let participant_names = collaboration_hub.user_names(cx);
17411 let participant_indices = collaboration_hub.user_participant_indices(cx);
17412 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17413 let collaborators_by_replica_id = collaborators_by_peer_id
17414 .iter()
17415 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17416 .collect::<HashMap<_, _>>();
17417 self.buffer_snapshot
17418 .selections_in_range(range, false)
17419 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17420 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17421 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17422 let user_name = participant_names.get(&collaborator.user_id).cloned();
17423 Some(RemoteSelection {
17424 replica_id,
17425 selection,
17426 cursor_shape,
17427 line_mode,
17428 participant_index,
17429 peer_id: collaborator.peer_id,
17430 user_name,
17431 })
17432 })
17433 }
17434
17435 pub fn hunks_for_ranges(
17436 &self,
17437 ranges: impl IntoIterator<Item = Range<Point>>,
17438 ) -> Vec<MultiBufferDiffHunk> {
17439 let mut hunks = Vec::new();
17440 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17441 HashMap::default();
17442 for query_range in ranges {
17443 let query_rows =
17444 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17445 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17446 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17447 ) {
17448 // Include deleted hunks that are adjacent to the query range, because
17449 // otherwise they would be missed.
17450 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17451 if hunk.status().is_deleted() {
17452 intersects_range |= hunk.row_range.start == query_rows.end;
17453 intersects_range |= hunk.row_range.end == query_rows.start;
17454 }
17455 if intersects_range {
17456 if !processed_buffer_rows
17457 .entry(hunk.buffer_id)
17458 .or_default()
17459 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17460 {
17461 continue;
17462 }
17463 hunks.push(hunk);
17464 }
17465 }
17466 }
17467
17468 hunks
17469 }
17470
17471 fn display_diff_hunks_for_rows<'a>(
17472 &'a self,
17473 display_rows: Range<DisplayRow>,
17474 folded_buffers: &'a HashSet<BufferId>,
17475 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17476 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17477 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17478
17479 self.buffer_snapshot
17480 .diff_hunks_in_range(buffer_start..buffer_end)
17481 .filter_map(|hunk| {
17482 if folded_buffers.contains(&hunk.buffer_id) {
17483 return None;
17484 }
17485
17486 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17487 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17488
17489 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17490 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17491
17492 let display_hunk = if hunk_display_start.column() != 0 {
17493 DisplayDiffHunk::Folded {
17494 display_row: hunk_display_start.row(),
17495 }
17496 } else {
17497 let mut end_row = hunk_display_end.row();
17498 if hunk_display_end.column() > 0 {
17499 end_row.0 += 1;
17500 }
17501 let is_created_file = hunk.is_created_file();
17502 DisplayDiffHunk::Unfolded {
17503 status: hunk.status(),
17504 diff_base_byte_range: hunk.diff_base_byte_range,
17505 display_row_range: hunk_display_start.row()..end_row,
17506 multi_buffer_range: Anchor::range_in_buffer(
17507 hunk.excerpt_id,
17508 hunk.buffer_id,
17509 hunk.buffer_range,
17510 ),
17511 is_created_file,
17512 }
17513 };
17514
17515 Some(display_hunk)
17516 })
17517 }
17518
17519 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17520 self.display_snapshot.buffer_snapshot.language_at(position)
17521 }
17522
17523 pub fn is_focused(&self) -> bool {
17524 self.is_focused
17525 }
17526
17527 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17528 self.placeholder_text.as_ref()
17529 }
17530
17531 pub fn scroll_position(&self) -> gpui::Point<f32> {
17532 self.scroll_anchor.scroll_position(&self.display_snapshot)
17533 }
17534
17535 fn gutter_dimensions(
17536 &self,
17537 font_id: FontId,
17538 font_size: Pixels,
17539 max_line_number_width: Pixels,
17540 cx: &App,
17541 ) -> Option<GutterDimensions> {
17542 if !self.show_gutter {
17543 return None;
17544 }
17545
17546 let descent = cx.text_system().descent(font_id, font_size);
17547 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17548 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17549
17550 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17551 matches!(
17552 ProjectSettings::get_global(cx).git.git_gutter,
17553 Some(GitGutterSetting::TrackedFiles)
17554 )
17555 });
17556 let gutter_settings = EditorSettings::get_global(cx).gutter;
17557 let show_line_numbers = self
17558 .show_line_numbers
17559 .unwrap_or(gutter_settings.line_numbers);
17560 let line_gutter_width = if show_line_numbers {
17561 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17562 let min_width_for_number_on_gutter = em_advance * 4.0;
17563 max_line_number_width.max(min_width_for_number_on_gutter)
17564 } else {
17565 0.0.into()
17566 };
17567
17568 let show_code_actions = self
17569 .show_code_actions
17570 .unwrap_or(gutter_settings.code_actions);
17571
17572 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17573
17574 let git_blame_entries_width =
17575 self.git_blame_gutter_max_author_length
17576 .map(|max_author_length| {
17577 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17578
17579 /// The number of characters to dedicate to gaps and margins.
17580 const SPACING_WIDTH: usize = 4;
17581
17582 let max_char_count = max_author_length
17583 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17584 + ::git::SHORT_SHA_LENGTH
17585 + MAX_RELATIVE_TIMESTAMP.len()
17586 + SPACING_WIDTH;
17587
17588 em_advance * max_char_count
17589 });
17590
17591 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17592 left_padding += if show_code_actions || show_runnables {
17593 em_width * 3.0
17594 } else if show_git_gutter && show_line_numbers {
17595 em_width * 2.0
17596 } else if show_git_gutter || show_line_numbers {
17597 em_width
17598 } else {
17599 px(0.)
17600 };
17601
17602 let right_padding = if gutter_settings.folds && show_line_numbers {
17603 em_width * 4.0
17604 } else if gutter_settings.folds {
17605 em_width * 3.0
17606 } else if show_line_numbers {
17607 em_width
17608 } else {
17609 px(0.)
17610 };
17611
17612 Some(GutterDimensions {
17613 left_padding,
17614 right_padding,
17615 width: line_gutter_width + left_padding + right_padding,
17616 margin: -descent,
17617 git_blame_entries_width,
17618 })
17619 }
17620
17621 pub fn render_crease_toggle(
17622 &self,
17623 buffer_row: MultiBufferRow,
17624 row_contains_cursor: bool,
17625 editor: Entity<Editor>,
17626 window: &mut Window,
17627 cx: &mut App,
17628 ) -> Option<AnyElement> {
17629 let folded = self.is_line_folded(buffer_row);
17630 let mut is_foldable = false;
17631
17632 if let Some(crease) = self
17633 .crease_snapshot
17634 .query_row(buffer_row, &self.buffer_snapshot)
17635 {
17636 is_foldable = true;
17637 match crease {
17638 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17639 if let Some(render_toggle) = render_toggle {
17640 let toggle_callback =
17641 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17642 if folded {
17643 editor.update(cx, |editor, cx| {
17644 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17645 });
17646 } else {
17647 editor.update(cx, |editor, cx| {
17648 editor.unfold_at(
17649 &crate::UnfoldAt { buffer_row },
17650 window,
17651 cx,
17652 )
17653 });
17654 }
17655 });
17656 return Some((render_toggle)(
17657 buffer_row,
17658 folded,
17659 toggle_callback,
17660 window,
17661 cx,
17662 ));
17663 }
17664 }
17665 }
17666 }
17667
17668 is_foldable |= self.starts_indent(buffer_row);
17669
17670 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17671 Some(
17672 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17673 .toggle_state(folded)
17674 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17675 if folded {
17676 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17677 } else {
17678 this.fold_at(&FoldAt { buffer_row }, window, cx);
17679 }
17680 }))
17681 .into_any_element(),
17682 )
17683 } else {
17684 None
17685 }
17686 }
17687
17688 pub fn render_crease_trailer(
17689 &self,
17690 buffer_row: MultiBufferRow,
17691 window: &mut Window,
17692 cx: &mut App,
17693 ) -> Option<AnyElement> {
17694 let folded = self.is_line_folded(buffer_row);
17695 if let Crease::Inline { render_trailer, .. } = self
17696 .crease_snapshot
17697 .query_row(buffer_row, &self.buffer_snapshot)?
17698 {
17699 let render_trailer = render_trailer.as_ref()?;
17700 Some(render_trailer(buffer_row, folded, window, cx))
17701 } else {
17702 None
17703 }
17704 }
17705}
17706
17707impl Deref for EditorSnapshot {
17708 type Target = DisplaySnapshot;
17709
17710 fn deref(&self) -> &Self::Target {
17711 &self.display_snapshot
17712 }
17713}
17714
17715#[derive(Clone, Debug, PartialEq, Eq)]
17716pub enum EditorEvent {
17717 InputIgnored {
17718 text: Arc<str>,
17719 },
17720 InputHandled {
17721 utf16_range_to_replace: Option<Range<isize>>,
17722 text: Arc<str>,
17723 },
17724 ExcerptsAdded {
17725 buffer: Entity<Buffer>,
17726 predecessor: ExcerptId,
17727 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17728 },
17729 ExcerptsRemoved {
17730 ids: Vec<ExcerptId>,
17731 },
17732 BufferFoldToggled {
17733 ids: Vec<ExcerptId>,
17734 folded: bool,
17735 },
17736 ExcerptsEdited {
17737 ids: Vec<ExcerptId>,
17738 },
17739 ExcerptsExpanded {
17740 ids: Vec<ExcerptId>,
17741 },
17742 BufferEdited,
17743 Edited {
17744 transaction_id: clock::Lamport,
17745 },
17746 Reparsed(BufferId),
17747 Focused,
17748 FocusedIn,
17749 Blurred,
17750 DirtyChanged,
17751 Saved,
17752 TitleChanged,
17753 DiffBaseChanged,
17754 SelectionsChanged {
17755 local: bool,
17756 },
17757 ScrollPositionChanged {
17758 local: bool,
17759 autoscroll: bool,
17760 },
17761 Closed,
17762 TransactionUndone {
17763 transaction_id: clock::Lamport,
17764 },
17765 TransactionBegun {
17766 transaction_id: clock::Lamport,
17767 },
17768 Reloaded,
17769 CursorShapeChanged,
17770}
17771
17772impl EventEmitter<EditorEvent> for Editor {}
17773
17774impl Focusable for Editor {
17775 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17776 self.focus_handle.clone()
17777 }
17778}
17779
17780impl Render for Editor {
17781 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17782 let settings = ThemeSettings::get_global(cx);
17783
17784 let mut text_style = match self.mode {
17785 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17786 color: cx.theme().colors().editor_foreground,
17787 font_family: settings.ui_font.family.clone(),
17788 font_features: settings.ui_font.features.clone(),
17789 font_fallbacks: settings.ui_font.fallbacks.clone(),
17790 font_size: rems(0.875).into(),
17791 font_weight: settings.ui_font.weight,
17792 line_height: relative(settings.buffer_line_height.value()),
17793 ..Default::default()
17794 },
17795 EditorMode::Full => TextStyle {
17796 color: cx.theme().colors().editor_foreground,
17797 font_family: settings.buffer_font.family.clone(),
17798 font_features: settings.buffer_font.features.clone(),
17799 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17800 font_size: settings.buffer_font_size(cx).into(),
17801 font_weight: settings.buffer_font.weight,
17802 line_height: relative(settings.buffer_line_height.value()),
17803 ..Default::default()
17804 },
17805 };
17806 if let Some(text_style_refinement) = &self.text_style_refinement {
17807 text_style.refine(text_style_refinement)
17808 }
17809
17810 let background = match self.mode {
17811 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17812 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17813 EditorMode::Full => cx.theme().colors().editor_background,
17814 };
17815
17816 EditorElement::new(
17817 &cx.entity(),
17818 EditorStyle {
17819 background,
17820 local_player: cx.theme().players().local(),
17821 text: text_style,
17822 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17823 syntax: cx.theme().syntax().clone(),
17824 status: cx.theme().status().clone(),
17825 inlay_hints_style: make_inlay_hints_style(cx),
17826 inline_completion_styles: make_suggestion_styles(cx),
17827 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17828 },
17829 )
17830 }
17831}
17832
17833impl EntityInputHandler for Editor {
17834 fn text_for_range(
17835 &mut self,
17836 range_utf16: Range<usize>,
17837 adjusted_range: &mut Option<Range<usize>>,
17838 _: &mut Window,
17839 cx: &mut Context<Self>,
17840 ) -> Option<String> {
17841 let snapshot = self.buffer.read(cx).read(cx);
17842 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17843 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17844 if (start.0..end.0) != range_utf16 {
17845 adjusted_range.replace(start.0..end.0);
17846 }
17847 Some(snapshot.text_for_range(start..end).collect())
17848 }
17849
17850 fn selected_text_range(
17851 &mut self,
17852 ignore_disabled_input: bool,
17853 _: &mut Window,
17854 cx: &mut Context<Self>,
17855 ) -> Option<UTF16Selection> {
17856 // Prevent the IME menu from appearing when holding down an alphabetic key
17857 // while input is disabled.
17858 if !ignore_disabled_input && !self.input_enabled {
17859 return None;
17860 }
17861
17862 let selection = self.selections.newest::<OffsetUtf16>(cx);
17863 let range = selection.range();
17864
17865 Some(UTF16Selection {
17866 range: range.start.0..range.end.0,
17867 reversed: selection.reversed,
17868 })
17869 }
17870
17871 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17872 let snapshot = self.buffer.read(cx).read(cx);
17873 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17874 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17875 }
17876
17877 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17878 self.clear_highlights::<InputComposition>(cx);
17879 self.ime_transaction.take();
17880 }
17881
17882 fn replace_text_in_range(
17883 &mut self,
17884 range_utf16: Option<Range<usize>>,
17885 text: &str,
17886 window: &mut Window,
17887 cx: &mut Context<Self>,
17888 ) {
17889 if !self.input_enabled {
17890 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17891 return;
17892 }
17893
17894 self.transact(window, cx, |this, window, cx| {
17895 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17896 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17897 Some(this.selection_replacement_ranges(range_utf16, cx))
17898 } else {
17899 this.marked_text_ranges(cx)
17900 };
17901
17902 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17903 let newest_selection_id = this.selections.newest_anchor().id;
17904 this.selections
17905 .all::<OffsetUtf16>(cx)
17906 .iter()
17907 .zip(ranges_to_replace.iter())
17908 .find_map(|(selection, range)| {
17909 if selection.id == newest_selection_id {
17910 Some(
17911 (range.start.0 as isize - selection.head().0 as isize)
17912 ..(range.end.0 as isize - selection.head().0 as isize),
17913 )
17914 } else {
17915 None
17916 }
17917 })
17918 });
17919
17920 cx.emit(EditorEvent::InputHandled {
17921 utf16_range_to_replace: range_to_replace,
17922 text: text.into(),
17923 });
17924
17925 if let Some(new_selected_ranges) = new_selected_ranges {
17926 this.change_selections(None, window, cx, |selections| {
17927 selections.select_ranges(new_selected_ranges)
17928 });
17929 this.backspace(&Default::default(), window, cx);
17930 }
17931
17932 this.handle_input(text, window, cx);
17933 });
17934
17935 if let Some(transaction) = self.ime_transaction {
17936 self.buffer.update(cx, |buffer, cx| {
17937 buffer.group_until_transaction(transaction, cx);
17938 });
17939 }
17940
17941 self.unmark_text(window, cx);
17942 }
17943
17944 fn replace_and_mark_text_in_range(
17945 &mut self,
17946 range_utf16: Option<Range<usize>>,
17947 text: &str,
17948 new_selected_range_utf16: Option<Range<usize>>,
17949 window: &mut Window,
17950 cx: &mut Context<Self>,
17951 ) {
17952 if !self.input_enabled {
17953 return;
17954 }
17955
17956 let transaction = self.transact(window, cx, |this, window, cx| {
17957 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17958 let snapshot = this.buffer.read(cx).read(cx);
17959 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17960 for marked_range in &mut marked_ranges {
17961 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17962 marked_range.start.0 += relative_range_utf16.start;
17963 marked_range.start =
17964 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17965 marked_range.end =
17966 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17967 }
17968 }
17969 Some(marked_ranges)
17970 } else if let Some(range_utf16) = range_utf16 {
17971 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17972 Some(this.selection_replacement_ranges(range_utf16, cx))
17973 } else {
17974 None
17975 };
17976
17977 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17978 let newest_selection_id = this.selections.newest_anchor().id;
17979 this.selections
17980 .all::<OffsetUtf16>(cx)
17981 .iter()
17982 .zip(ranges_to_replace.iter())
17983 .find_map(|(selection, range)| {
17984 if selection.id == newest_selection_id {
17985 Some(
17986 (range.start.0 as isize - selection.head().0 as isize)
17987 ..(range.end.0 as isize - selection.head().0 as isize),
17988 )
17989 } else {
17990 None
17991 }
17992 })
17993 });
17994
17995 cx.emit(EditorEvent::InputHandled {
17996 utf16_range_to_replace: range_to_replace,
17997 text: text.into(),
17998 });
17999
18000 if let Some(ranges) = ranges_to_replace {
18001 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18002 }
18003
18004 let marked_ranges = {
18005 let snapshot = this.buffer.read(cx).read(cx);
18006 this.selections
18007 .disjoint_anchors()
18008 .iter()
18009 .map(|selection| {
18010 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18011 })
18012 .collect::<Vec<_>>()
18013 };
18014
18015 if text.is_empty() {
18016 this.unmark_text(window, cx);
18017 } else {
18018 this.highlight_text::<InputComposition>(
18019 marked_ranges.clone(),
18020 HighlightStyle {
18021 underline: Some(UnderlineStyle {
18022 thickness: px(1.),
18023 color: None,
18024 wavy: false,
18025 }),
18026 ..Default::default()
18027 },
18028 cx,
18029 );
18030 }
18031
18032 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18033 let use_autoclose = this.use_autoclose;
18034 let use_auto_surround = this.use_auto_surround;
18035 this.set_use_autoclose(false);
18036 this.set_use_auto_surround(false);
18037 this.handle_input(text, window, cx);
18038 this.set_use_autoclose(use_autoclose);
18039 this.set_use_auto_surround(use_auto_surround);
18040
18041 if let Some(new_selected_range) = new_selected_range_utf16 {
18042 let snapshot = this.buffer.read(cx).read(cx);
18043 let new_selected_ranges = marked_ranges
18044 .into_iter()
18045 .map(|marked_range| {
18046 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
18047 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
18048 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
18049 snapshot.clip_offset_utf16(new_start, Bias::Left)
18050 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
18051 })
18052 .collect::<Vec<_>>();
18053
18054 drop(snapshot);
18055 this.change_selections(None, window, cx, |selections| {
18056 selections.select_ranges(new_selected_ranges)
18057 });
18058 }
18059 });
18060
18061 self.ime_transaction = self.ime_transaction.or(transaction);
18062 if let Some(transaction) = self.ime_transaction {
18063 self.buffer.update(cx, |buffer, cx| {
18064 buffer.group_until_transaction(transaction, cx);
18065 });
18066 }
18067
18068 if self.text_highlights::<InputComposition>(cx).is_none() {
18069 self.ime_transaction.take();
18070 }
18071 }
18072
18073 fn bounds_for_range(
18074 &mut self,
18075 range_utf16: Range<usize>,
18076 element_bounds: gpui::Bounds<Pixels>,
18077 window: &mut Window,
18078 cx: &mut Context<Self>,
18079 ) -> Option<gpui::Bounds<Pixels>> {
18080 let text_layout_details = self.text_layout_details(window);
18081 let gpui::Size {
18082 width: em_width,
18083 height: line_height,
18084 } = self.character_size(window);
18085
18086 let snapshot = self.snapshot(window, cx);
18087 let scroll_position = snapshot.scroll_position();
18088 let scroll_left = scroll_position.x * em_width;
18089
18090 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
18091 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
18092 + self.gutter_dimensions.width
18093 + self.gutter_dimensions.margin;
18094 let y = line_height * (start.row().as_f32() - scroll_position.y);
18095
18096 Some(Bounds {
18097 origin: element_bounds.origin + point(x, y),
18098 size: size(em_width, line_height),
18099 })
18100 }
18101
18102 fn character_index_for_point(
18103 &mut self,
18104 point: gpui::Point<Pixels>,
18105 _window: &mut Window,
18106 _cx: &mut Context<Self>,
18107 ) -> Option<usize> {
18108 let position_map = self.last_position_map.as_ref()?;
18109 if !position_map.text_hitbox.contains(&point) {
18110 return None;
18111 }
18112 let display_point = position_map.point_for_position(point).previous_valid;
18113 let anchor = position_map
18114 .snapshot
18115 .display_point_to_anchor(display_point, Bias::Left);
18116 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18117 Some(utf16_offset.0)
18118 }
18119}
18120
18121trait SelectionExt {
18122 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18123 fn spanned_rows(
18124 &self,
18125 include_end_if_at_line_start: bool,
18126 map: &DisplaySnapshot,
18127 ) -> Range<MultiBufferRow>;
18128}
18129
18130impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18131 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18132 let start = self
18133 .start
18134 .to_point(&map.buffer_snapshot)
18135 .to_display_point(map);
18136 let end = self
18137 .end
18138 .to_point(&map.buffer_snapshot)
18139 .to_display_point(map);
18140 if self.reversed {
18141 end..start
18142 } else {
18143 start..end
18144 }
18145 }
18146
18147 fn spanned_rows(
18148 &self,
18149 include_end_if_at_line_start: bool,
18150 map: &DisplaySnapshot,
18151 ) -> Range<MultiBufferRow> {
18152 let start = self.start.to_point(&map.buffer_snapshot);
18153 let mut end = self.end.to_point(&map.buffer_snapshot);
18154 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18155 end.row -= 1;
18156 }
18157
18158 let buffer_start = map.prev_line_boundary(start).0;
18159 let buffer_end = map.next_line_boundary(end).0;
18160 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18161 }
18162}
18163
18164impl<T: InvalidationRegion> InvalidationStack<T> {
18165 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18166 where
18167 S: Clone + ToOffset,
18168 {
18169 while let Some(region) = self.last() {
18170 let all_selections_inside_invalidation_ranges =
18171 if selections.len() == region.ranges().len() {
18172 selections
18173 .iter()
18174 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18175 .all(|(selection, invalidation_range)| {
18176 let head = selection.head().to_offset(buffer);
18177 invalidation_range.start <= head && invalidation_range.end >= head
18178 })
18179 } else {
18180 false
18181 };
18182
18183 if all_selections_inside_invalidation_ranges {
18184 break;
18185 } else {
18186 self.pop();
18187 }
18188 }
18189 }
18190}
18191
18192impl<T> Default for InvalidationStack<T> {
18193 fn default() -> Self {
18194 Self(Default::default())
18195 }
18196}
18197
18198impl<T> Deref for InvalidationStack<T> {
18199 type Target = Vec<T>;
18200
18201 fn deref(&self) -> &Self::Target {
18202 &self.0
18203 }
18204}
18205
18206impl<T> DerefMut for InvalidationStack<T> {
18207 fn deref_mut(&mut self) -> &mut Self::Target {
18208 &mut self.0
18209 }
18210}
18211
18212impl InvalidationRegion for SnippetState {
18213 fn ranges(&self) -> &[Range<Anchor>] {
18214 &self.ranges[self.active_index]
18215 }
18216}
18217
18218pub fn diagnostic_block_renderer(
18219 diagnostic: Diagnostic,
18220 max_message_rows: Option<u8>,
18221 allow_closing: bool,
18222) -> RenderBlock {
18223 let (text_without_backticks, code_ranges) =
18224 highlight_diagnostic_message(&diagnostic, max_message_rows);
18225
18226 Arc::new(move |cx: &mut BlockContext| {
18227 let group_id: SharedString = cx.block_id.to_string().into();
18228
18229 let mut text_style = cx.window.text_style().clone();
18230 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18231 let theme_settings = ThemeSettings::get_global(cx);
18232 text_style.font_family = theme_settings.buffer_font.family.clone();
18233 text_style.font_style = theme_settings.buffer_font.style;
18234 text_style.font_features = theme_settings.buffer_font.features.clone();
18235 text_style.font_weight = theme_settings.buffer_font.weight;
18236
18237 let multi_line_diagnostic = diagnostic.message.contains('\n');
18238
18239 let buttons = |diagnostic: &Diagnostic| {
18240 if multi_line_diagnostic {
18241 v_flex()
18242 } else {
18243 h_flex()
18244 }
18245 .when(allow_closing, |div| {
18246 div.children(diagnostic.is_primary.then(|| {
18247 IconButton::new("close-block", IconName::XCircle)
18248 .icon_color(Color::Muted)
18249 .size(ButtonSize::Compact)
18250 .style(ButtonStyle::Transparent)
18251 .visible_on_hover(group_id.clone())
18252 .on_click(move |_click, window, cx| {
18253 window.dispatch_action(Box::new(Cancel), cx)
18254 })
18255 .tooltip(|window, cx| {
18256 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18257 })
18258 }))
18259 })
18260 .child(
18261 IconButton::new("copy-block", IconName::Copy)
18262 .icon_color(Color::Muted)
18263 .size(ButtonSize::Compact)
18264 .style(ButtonStyle::Transparent)
18265 .visible_on_hover(group_id.clone())
18266 .on_click({
18267 let message = diagnostic.message.clone();
18268 move |_click, _, cx| {
18269 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18270 }
18271 })
18272 .tooltip(Tooltip::text("Copy diagnostic message")),
18273 )
18274 };
18275
18276 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18277 AvailableSpace::min_size(),
18278 cx.window,
18279 cx.app,
18280 );
18281
18282 h_flex()
18283 .id(cx.block_id)
18284 .group(group_id.clone())
18285 .relative()
18286 .size_full()
18287 .block_mouse_down()
18288 .pl(cx.gutter_dimensions.width)
18289 .w(cx.max_width - cx.gutter_dimensions.full_width())
18290 .child(
18291 div()
18292 .flex()
18293 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18294 .flex_shrink(),
18295 )
18296 .child(buttons(&diagnostic))
18297 .child(div().flex().flex_shrink_0().child(
18298 StyledText::new(text_without_backticks.clone()).with_default_highlights(
18299 &text_style,
18300 code_ranges.iter().map(|range| {
18301 (
18302 range.clone(),
18303 HighlightStyle {
18304 font_weight: Some(FontWeight::BOLD),
18305 ..Default::default()
18306 },
18307 )
18308 }),
18309 ),
18310 ))
18311 .into_any_element()
18312 })
18313}
18314
18315fn inline_completion_edit_text(
18316 current_snapshot: &BufferSnapshot,
18317 edits: &[(Range<Anchor>, String)],
18318 edit_preview: &EditPreview,
18319 include_deletions: bool,
18320 cx: &App,
18321) -> HighlightedText {
18322 let edits = edits
18323 .iter()
18324 .map(|(anchor, text)| {
18325 (
18326 anchor.start.text_anchor..anchor.end.text_anchor,
18327 text.clone(),
18328 )
18329 })
18330 .collect::<Vec<_>>();
18331
18332 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18333}
18334
18335pub fn highlight_diagnostic_message(
18336 diagnostic: &Diagnostic,
18337 mut max_message_rows: Option<u8>,
18338) -> (SharedString, Vec<Range<usize>>) {
18339 let mut text_without_backticks = String::new();
18340 let mut code_ranges = Vec::new();
18341
18342 if let Some(source) = &diagnostic.source {
18343 text_without_backticks.push_str(source);
18344 code_ranges.push(0..source.len());
18345 text_without_backticks.push_str(": ");
18346 }
18347
18348 let mut prev_offset = 0;
18349 let mut in_code_block = false;
18350 let has_row_limit = max_message_rows.is_some();
18351 let mut newline_indices = diagnostic
18352 .message
18353 .match_indices('\n')
18354 .filter(|_| has_row_limit)
18355 .map(|(ix, _)| ix)
18356 .fuse()
18357 .peekable();
18358
18359 for (quote_ix, _) in diagnostic
18360 .message
18361 .match_indices('`')
18362 .chain([(diagnostic.message.len(), "")])
18363 {
18364 let mut first_newline_ix = None;
18365 let mut last_newline_ix = None;
18366 while let Some(newline_ix) = newline_indices.peek() {
18367 if *newline_ix < quote_ix {
18368 if first_newline_ix.is_none() {
18369 first_newline_ix = Some(*newline_ix);
18370 }
18371 last_newline_ix = Some(*newline_ix);
18372
18373 if let Some(rows_left) = &mut max_message_rows {
18374 if *rows_left == 0 {
18375 break;
18376 } else {
18377 *rows_left -= 1;
18378 }
18379 }
18380 let _ = newline_indices.next();
18381 } else {
18382 break;
18383 }
18384 }
18385 let prev_len = text_without_backticks.len();
18386 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18387 text_without_backticks.push_str(new_text);
18388 if in_code_block {
18389 code_ranges.push(prev_len..text_without_backticks.len());
18390 }
18391 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18392 in_code_block = !in_code_block;
18393 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18394 text_without_backticks.push_str("...");
18395 break;
18396 }
18397 }
18398
18399 (text_without_backticks.into(), code_ranges)
18400}
18401
18402fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18403 match severity {
18404 DiagnosticSeverity::ERROR => colors.error,
18405 DiagnosticSeverity::WARNING => colors.warning,
18406 DiagnosticSeverity::INFORMATION => colors.info,
18407 DiagnosticSeverity::HINT => colors.info,
18408 _ => colors.ignored,
18409 }
18410}
18411
18412pub fn styled_runs_for_code_label<'a>(
18413 label: &'a CodeLabel,
18414 syntax_theme: &'a theme::SyntaxTheme,
18415) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18416 let fade_out = HighlightStyle {
18417 fade_out: Some(0.35),
18418 ..Default::default()
18419 };
18420
18421 let mut prev_end = label.filter_range.end;
18422 label
18423 .runs
18424 .iter()
18425 .enumerate()
18426 .flat_map(move |(ix, (range, highlight_id))| {
18427 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18428 style
18429 } else {
18430 return Default::default();
18431 };
18432 let mut muted_style = style;
18433 muted_style.highlight(fade_out);
18434
18435 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18436 if range.start >= label.filter_range.end {
18437 if range.start > prev_end {
18438 runs.push((prev_end..range.start, fade_out));
18439 }
18440 runs.push((range.clone(), muted_style));
18441 } else if range.end <= label.filter_range.end {
18442 runs.push((range.clone(), style));
18443 } else {
18444 runs.push((range.start..label.filter_range.end, style));
18445 runs.push((label.filter_range.end..range.end, muted_style));
18446 }
18447 prev_end = cmp::max(prev_end, range.end);
18448
18449 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18450 runs.push((prev_end..label.text.len(), fade_out));
18451 }
18452
18453 runs
18454 })
18455}
18456
18457pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18458 let mut prev_index = 0;
18459 let mut prev_codepoint: Option<char> = None;
18460 text.char_indices()
18461 .chain([(text.len(), '\0')])
18462 .filter_map(move |(index, codepoint)| {
18463 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18464 let is_boundary = index == text.len()
18465 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18466 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18467 if is_boundary {
18468 let chunk = &text[prev_index..index];
18469 prev_index = index;
18470 Some(chunk)
18471 } else {
18472 None
18473 }
18474 })
18475}
18476
18477pub trait RangeToAnchorExt: Sized {
18478 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18479
18480 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18481 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18482 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18483 }
18484}
18485
18486impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18487 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18488 let start_offset = self.start.to_offset(snapshot);
18489 let end_offset = self.end.to_offset(snapshot);
18490 if start_offset == end_offset {
18491 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18492 } else {
18493 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18494 }
18495 }
18496}
18497
18498pub trait RowExt {
18499 fn as_f32(&self) -> f32;
18500
18501 fn next_row(&self) -> Self;
18502
18503 fn previous_row(&self) -> Self;
18504
18505 fn minus(&self, other: Self) -> u32;
18506}
18507
18508impl RowExt for DisplayRow {
18509 fn as_f32(&self) -> f32 {
18510 self.0 as f32
18511 }
18512
18513 fn next_row(&self) -> Self {
18514 Self(self.0 + 1)
18515 }
18516
18517 fn previous_row(&self) -> Self {
18518 Self(self.0.saturating_sub(1))
18519 }
18520
18521 fn minus(&self, other: Self) -> u32 {
18522 self.0 - other.0
18523 }
18524}
18525
18526impl RowExt for MultiBufferRow {
18527 fn as_f32(&self) -> f32 {
18528 self.0 as f32
18529 }
18530
18531 fn next_row(&self) -> Self {
18532 Self(self.0 + 1)
18533 }
18534
18535 fn previous_row(&self) -> Self {
18536 Self(self.0.saturating_sub(1))
18537 }
18538
18539 fn minus(&self, other: Self) -> u32 {
18540 self.0 - other.0
18541 }
18542}
18543
18544trait RowRangeExt {
18545 type Row;
18546
18547 fn len(&self) -> usize;
18548
18549 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18550}
18551
18552impl RowRangeExt for Range<MultiBufferRow> {
18553 type Row = MultiBufferRow;
18554
18555 fn len(&self) -> usize {
18556 (self.end.0 - self.start.0) as usize
18557 }
18558
18559 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18560 (self.start.0..self.end.0).map(MultiBufferRow)
18561 }
18562}
18563
18564impl RowRangeExt for Range<DisplayRow> {
18565 type Row = DisplayRow;
18566
18567 fn len(&self) -> usize {
18568 (self.end.0 - self.start.0) as usize
18569 }
18570
18571 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18572 (self.start.0..self.end.0).map(DisplayRow)
18573 }
18574}
18575
18576/// If select range has more than one line, we
18577/// just point the cursor to range.start.
18578fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18579 if range.start.row == range.end.row {
18580 range
18581 } else {
18582 range.start..range.start
18583 }
18584}
18585pub struct KillRing(ClipboardItem);
18586impl Global for KillRing {}
18587
18588const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18589
18590fn all_edits_insertions_or_deletions(
18591 edits: &Vec<(Range<Anchor>, String)>,
18592 snapshot: &MultiBufferSnapshot,
18593) -> bool {
18594 let mut all_insertions = true;
18595 let mut all_deletions = true;
18596
18597 for (range, new_text) in edits.iter() {
18598 let range_is_empty = range.to_offset(&snapshot).is_empty();
18599 let text_is_empty = new_text.is_empty();
18600
18601 if range_is_empty != text_is_empty {
18602 if range_is_empty {
18603 all_deletions = false;
18604 } else {
18605 all_insertions = false;
18606 }
18607 } else {
18608 return false;
18609 }
18610
18611 if !all_insertions && !all_deletions {
18612 return false;
18613 }
18614 }
18615 all_insertions || all_deletions
18616}
18617
18618struct MissingEditPredictionKeybindingTooltip;
18619
18620impl Render for MissingEditPredictionKeybindingTooltip {
18621 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18622 ui::tooltip_container(window, cx, |container, _, cx| {
18623 container
18624 .flex_shrink_0()
18625 .max_w_80()
18626 .min_h(rems_from_px(124.))
18627 .justify_between()
18628 .child(
18629 v_flex()
18630 .flex_1()
18631 .text_ui_sm(cx)
18632 .child(Label::new("Conflict with Accept Keybinding"))
18633 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18634 )
18635 .child(
18636 h_flex()
18637 .pb_1()
18638 .gap_1()
18639 .items_end()
18640 .w_full()
18641 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18642 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18643 }))
18644 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18645 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18646 })),
18647 )
18648 })
18649 }
18650}
18651
18652#[derive(Debug, Clone, Copy, PartialEq)]
18653pub struct LineHighlight {
18654 pub background: Background,
18655 pub border: Option<gpui::Hsla>,
18656}
18657
18658impl From<Hsla> for LineHighlight {
18659 fn from(hsla: Hsla) -> Self {
18660 Self {
18661 background: hsla.into(),
18662 border: None,
18663 }
18664 }
18665}
18666
18667impl From<Background> for LineHighlight {
18668 fn from(background: Background) -> Self {
18669 Self {
18670 background,
18671 border: None,
18672 }
18673 }
18674}