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 let mut words = words.await;
4108 if let Some(word_to_exclude) = &word_to_exclude {
4109 words.remove(word_to_exclude);
4110 }
4111 for lsp_completion in &completions {
4112 words.remove(&lsp_completion.new_text);
4113 }
4114 completions.extend(words.into_iter().map(|(word, word_range)| {
4115 Completion {
4116 old_range: old_range.clone(),
4117 new_text: word.clone(),
4118 label: CodeLabel::plain(word, None),
4119 documentation: None,
4120 source: CompletionSource::BufferWord {
4121 word_range,
4122 resolved: false,
4123 },
4124 confirm: None,
4125 }
4126 }));
4127 }
4128 WordsCompletionMode::Fallback => {
4129 if completions.is_empty() {
4130 completions.extend(
4131 words
4132 .await
4133 .into_iter()
4134 .filter(|(word, _)| word_to_exclude.as_ref() != Some(word))
4135 .map(|(word, word_range)| Completion {
4136 old_range: old_range.clone(),
4137 new_text: word.clone(),
4138 label: CodeLabel::plain(word, None),
4139 documentation: None,
4140 source: CompletionSource::BufferWord {
4141 word_range,
4142 resolved: false,
4143 },
4144 confirm: None,
4145 }),
4146 );
4147 }
4148 }
4149 WordsCompletionMode::Disabled => {}
4150 }
4151
4152 let menu = if completions.is_empty() {
4153 None
4154 } else {
4155 let mut menu = CompletionsMenu::new(
4156 id,
4157 sort_completions,
4158 show_completion_documentation,
4159 position,
4160 buffer.clone(),
4161 completions.into(),
4162 );
4163
4164 menu.filter(query.as_deref(), cx.background_executor().clone())
4165 .await;
4166
4167 menu.visible().then_some(menu)
4168 };
4169
4170 editor.update_in(&mut cx, |editor, window, cx| {
4171 match editor.context_menu.borrow().as_ref() {
4172 None => {}
4173 Some(CodeContextMenu::Completions(prev_menu)) => {
4174 if prev_menu.id > id {
4175 return;
4176 }
4177 }
4178 _ => return,
4179 }
4180
4181 if editor.focus_handle.is_focused(window) && menu.is_some() {
4182 let mut menu = menu.unwrap();
4183 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4184
4185 *editor.context_menu.borrow_mut() =
4186 Some(CodeContextMenu::Completions(menu));
4187
4188 if editor.show_edit_predictions_in_menu() {
4189 editor.update_visible_inline_completion(window, cx);
4190 } else {
4191 editor.discard_inline_completion(false, cx);
4192 }
4193
4194 cx.notify();
4195 } else if editor.completion_tasks.len() <= 1 {
4196 // If there are no more completion tasks and the last menu was
4197 // empty, we should hide it.
4198 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4199 // If it was already hidden and we don't show inline
4200 // completions in the menu, we should also show the
4201 // inline-completion when available.
4202 if was_hidden && editor.show_edit_predictions_in_menu() {
4203 editor.update_visible_inline_completion(window, cx);
4204 }
4205 }
4206 })?;
4207
4208 Ok::<_, anyhow::Error>(())
4209 }
4210 .log_err()
4211 });
4212
4213 self.completion_tasks.push((id, task));
4214 }
4215
4216 pub fn confirm_completion(
4217 &mut self,
4218 action: &ConfirmCompletion,
4219 window: &mut Window,
4220 cx: &mut Context<Self>,
4221 ) -> Option<Task<Result<()>>> {
4222 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4223 }
4224
4225 pub fn compose_completion(
4226 &mut self,
4227 action: &ComposeCompletion,
4228 window: &mut Window,
4229 cx: &mut Context<Self>,
4230 ) -> Option<Task<Result<()>>> {
4231 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4232 }
4233
4234 fn do_completion(
4235 &mut self,
4236 item_ix: Option<usize>,
4237 intent: CompletionIntent,
4238 window: &mut Window,
4239 cx: &mut Context<Editor>,
4240 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4241 use language::ToOffset as _;
4242
4243 let completions_menu =
4244 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4245 menu
4246 } else {
4247 return None;
4248 };
4249
4250 let entries = completions_menu.entries.borrow();
4251 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4252 if self.show_edit_predictions_in_menu() {
4253 self.discard_inline_completion(true, cx);
4254 }
4255 let candidate_id = mat.candidate_id;
4256 drop(entries);
4257
4258 let buffer_handle = completions_menu.buffer;
4259 let completion = completions_menu
4260 .completions
4261 .borrow()
4262 .get(candidate_id)?
4263 .clone();
4264 cx.stop_propagation();
4265
4266 let snippet;
4267 let text;
4268
4269 if completion.is_snippet() {
4270 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4271 text = snippet.as_ref().unwrap().text.clone();
4272 } else {
4273 snippet = None;
4274 text = completion.new_text.clone();
4275 };
4276 let selections = self.selections.all::<usize>(cx);
4277 let buffer = buffer_handle.read(cx);
4278 let old_range = completion.old_range.to_offset(buffer);
4279 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4280
4281 let newest_selection = self.selections.newest_anchor();
4282 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4283 return None;
4284 }
4285
4286 let lookbehind = newest_selection
4287 .start
4288 .text_anchor
4289 .to_offset(buffer)
4290 .saturating_sub(old_range.start);
4291 let lookahead = old_range
4292 .end
4293 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4294 let mut common_prefix_len = old_text
4295 .bytes()
4296 .zip(text.bytes())
4297 .take_while(|(a, b)| a == b)
4298 .count();
4299
4300 let snapshot = self.buffer.read(cx).snapshot(cx);
4301 let mut range_to_replace: Option<Range<isize>> = None;
4302 let mut ranges = Vec::new();
4303 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4304 for selection in &selections {
4305 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4306 let start = selection.start.saturating_sub(lookbehind);
4307 let end = selection.end + lookahead;
4308 if selection.id == newest_selection.id {
4309 range_to_replace = Some(
4310 ((start + common_prefix_len) as isize - selection.start as isize)
4311 ..(end as isize - selection.start as isize),
4312 );
4313 }
4314 ranges.push(start + common_prefix_len..end);
4315 } else {
4316 common_prefix_len = 0;
4317 ranges.clear();
4318 ranges.extend(selections.iter().map(|s| {
4319 if s.id == newest_selection.id {
4320 range_to_replace = Some(
4321 old_range.start.to_offset_utf16(&snapshot).0 as isize
4322 - selection.start as isize
4323 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4324 - selection.start as isize,
4325 );
4326 old_range.clone()
4327 } else {
4328 s.start..s.end
4329 }
4330 }));
4331 break;
4332 }
4333 if !self.linked_edit_ranges.is_empty() {
4334 let start_anchor = snapshot.anchor_before(selection.head());
4335 let end_anchor = snapshot.anchor_after(selection.tail());
4336 if let Some(ranges) = self
4337 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4338 {
4339 for (buffer, edits) in ranges {
4340 linked_edits.entry(buffer.clone()).or_default().extend(
4341 edits
4342 .into_iter()
4343 .map(|range| (range, text[common_prefix_len..].to_owned())),
4344 );
4345 }
4346 }
4347 }
4348 }
4349 let text = &text[common_prefix_len..];
4350
4351 cx.emit(EditorEvent::InputHandled {
4352 utf16_range_to_replace: range_to_replace,
4353 text: text.into(),
4354 });
4355
4356 self.transact(window, cx, |this, window, cx| {
4357 if let Some(mut snippet) = snippet {
4358 snippet.text = text.to_string();
4359 for tabstop in snippet
4360 .tabstops
4361 .iter_mut()
4362 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4363 {
4364 tabstop.start -= common_prefix_len as isize;
4365 tabstop.end -= common_prefix_len as isize;
4366 }
4367
4368 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4369 } else {
4370 this.buffer.update(cx, |buffer, cx| {
4371 buffer.edit(
4372 ranges.iter().map(|range| (range.clone(), text)),
4373 this.autoindent_mode.clone(),
4374 cx,
4375 );
4376 });
4377 }
4378 for (buffer, edits) in linked_edits {
4379 buffer.update(cx, |buffer, cx| {
4380 let snapshot = buffer.snapshot();
4381 let edits = edits
4382 .into_iter()
4383 .map(|(range, text)| {
4384 use text::ToPoint as TP;
4385 let end_point = TP::to_point(&range.end, &snapshot);
4386 let start_point = TP::to_point(&range.start, &snapshot);
4387 (start_point..end_point, text)
4388 })
4389 .sorted_by_key(|(range, _)| range.start)
4390 .collect::<Vec<_>>();
4391 buffer.edit(edits, None, cx);
4392 })
4393 }
4394
4395 this.refresh_inline_completion(true, false, window, cx);
4396 });
4397
4398 let show_new_completions_on_confirm = completion
4399 .confirm
4400 .as_ref()
4401 .map_or(false, |confirm| confirm(intent, window, cx));
4402 if show_new_completions_on_confirm {
4403 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4404 }
4405
4406 let provider = self.completion_provider.as_ref()?;
4407 drop(completion);
4408 let apply_edits = provider.apply_additional_edits_for_completion(
4409 buffer_handle,
4410 completions_menu.completions.clone(),
4411 candidate_id,
4412 true,
4413 cx,
4414 );
4415
4416 let editor_settings = EditorSettings::get_global(cx);
4417 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4418 // After the code completion is finished, users often want to know what signatures are needed.
4419 // so we should automatically call signature_help
4420 self.show_signature_help(&ShowSignatureHelp, window, cx);
4421 }
4422
4423 Some(cx.foreground_executor().spawn(async move {
4424 apply_edits.await?;
4425 Ok(())
4426 }))
4427 }
4428
4429 pub fn toggle_code_actions(
4430 &mut self,
4431 action: &ToggleCodeActions,
4432 window: &mut Window,
4433 cx: &mut Context<Self>,
4434 ) {
4435 let mut context_menu = self.context_menu.borrow_mut();
4436 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4437 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4438 // Toggle if we're selecting the same one
4439 *context_menu = None;
4440 cx.notify();
4441 return;
4442 } else {
4443 // Otherwise, clear it and start a new one
4444 *context_menu = None;
4445 cx.notify();
4446 }
4447 }
4448 drop(context_menu);
4449 let snapshot = self.snapshot(window, cx);
4450 let deployed_from_indicator = action.deployed_from_indicator;
4451 let mut task = self.code_actions_task.take();
4452 let action = action.clone();
4453 cx.spawn_in(window, |editor, mut cx| async move {
4454 while let Some(prev_task) = task {
4455 prev_task.await.log_err();
4456 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4457 }
4458
4459 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4460 if editor.focus_handle.is_focused(window) {
4461 let multibuffer_point = action
4462 .deployed_from_indicator
4463 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4464 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4465 let (buffer, buffer_row) = snapshot
4466 .buffer_snapshot
4467 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4468 .and_then(|(buffer_snapshot, range)| {
4469 editor
4470 .buffer
4471 .read(cx)
4472 .buffer(buffer_snapshot.remote_id())
4473 .map(|buffer| (buffer, range.start.row))
4474 })?;
4475 let (_, code_actions) = editor
4476 .available_code_actions
4477 .clone()
4478 .and_then(|(location, code_actions)| {
4479 let snapshot = location.buffer.read(cx).snapshot();
4480 let point_range = location.range.to_point(&snapshot);
4481 let point_range = point_range.start.row..=point_range.end.row;
4482 if point_range.contains(&buffer_row) {
4483 Some((location, code_actions))
4484 } else {
4485 None
4486 }
4487 })
4488 .unzip();
4489 let buffer_id = buffer.read(cx).remote_id();
4490 let tasks = editor
4491 .tasks
4492 .get(&(buffer_id, buffer_row))
4493 .map(|t| Arc::new(t.to_owned()));
4494 if tasks.is_none() && code_actions.is_none() {
4495 return None;
4496 }
4497
4498 editor.completion_tasks.clear();
4499 editor.discard_inline_completion(false, cx);
4500 let task_context =
4501 tasks
4502 .as_ref()
4503 .zip(editor.project.clone())
4504 .map(|(tasks, project)| {
4505 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4506 });
4507
4508 Some(cx.spawn_in(window, |editor, mut cx| async move {
4509 let task_context = match task_context {
4510 Some(task_context) => task_context.await,
4511 None => None,
4512 };
4513 let resolved_tasks =
4514 tasks.zip(task_context).map(|(tasks, task_context)| {
4515 Rc::new(ResolvedTasks {
4516 templates: tasks.resolve(&task_context).collect(),
4517 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4518 multibuffer_point.row,
4519 tasks.column,
4520 )),
4521 })
4522 });
4523 let spawn_straight_away = resolved_tasks
4524 .as_ref()
4525 .map_or(false, |tasks| tasks.templates.len() == 1)
4526 && code_actions
4527 .as_ref()
4528 .map_or(true, |actions| actions.is_empty());
4529 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4530 *editor.context_menu.borrow_mut() =
4531 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4532 buffer,
4533 actions: CodeActionContents {
4534 tasks: resolved_tasks,
4535 actions: code_actions,
4536 },
4537 selected_item: Default::default(),
4538 scroll_handle: UniformListScrollHandle::default(),
4539 deployed_from_indicator,
4540 }));
4541 if spawn_straight_away {
4542 if let Some(task) = editor.confirm_code_action(
4543 &ConfirmCodeAction { item_ix: Some(0) },
4544 window,
4545 cx,
4546 ) {
4547 cx.notify();
4548 return task;
4549 }
4550 }
4551 cx.notify();
4552 Task::ready(Ok(()))
4553 }) {
4554 task.await
4555 } else {
4556 Ok(())
4557 }
4558 }))
4559 } else {
4560 Some(Task::ready(Ok(())))
4561 }
4562 })?;
4563 if let Some(task) = spawned_test_task {
4564 task.await?;
4565 }
4566
4567 Ok::<_, anyhow::Error>(())
4568 })
4569 .detach_and_log_err(cx);
4570 }
4571
4572 pub fn confirm_code_action(
4573 &mut self,
4574 action: &ConfirmCodeAction,
4575 window: &mut Window,
4576 cx: &mut Context<Self>,
4577 ) -> Option<Task<Result<()>>> {
4578 let actions_menu =
4579 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4580 menu
4581 } else {
4582 return None;
4583 };
4584 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4585 let action = actions_menu.actions.get(action_ix)?;
4586 let title = action.label();
4587 let buffer = actions_menu.buffer;
4588 let workspace = self.workspace()?;
4589
4590 match action {
4591 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4592 workspace.update(cx, |workspace, cx| {
4593 workspace::tasks::schedule_resolved_task(
4594 workspace,
4595 task_source_kind,
4596 resolved_task,
4597 false,
4598 cx,
4599 );
4600
4601 Some(Task::ready(Ok(())))
4602 })
4603 }
4604 CodeActionsItem::CodeAction {
4605 excerpt_id,
4606 action,
4607 provider,
4608 } => {
4609 let apply_code_action =
4610 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4611 let workspace = workspace.downgrade();
4612 Some(cx.spawn_in(window, |editor, cx| async move {
4613 let project_transaction = apply_code_action.await?;
4614 Self::open_project_transaction(
4615 &editor,
4616 workspace,
4617 project_transaction,
4618 title,
4619 cx,
4620 )
4621 .await
4622 }))
4623 }
4624 }
4625 }
4626
4627 pub async fn open_project_transaction(
4628 this: &WeakEntity<Editor>,
4629 workspace: WeakEntity<Workspace>,
4630 transaction: ProjectTransaction,
4631 title: String,
4632 mut cx: AsyncWindowContext,
4633 ) -> Result<()> {
4634 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4635 cx.update(|_, cx| {
4636 entries.sort_unstable_by_key(|(buffer, _)| {
4637 buffer.read(cx).file().map(|f| f.path().clone())
4638 });
4639 })?;
4640
4641 // If the project transaction's edits are all contained within this editor, then
4642 // avoid opening a new editor to display them.
4643
4644 if let Some((buffer, transaction)) = entries.first() {
4645 if entries.len() == 1 {
4646 let excerpt = this.update(&mut cx, |editor, cx| {
4647 editor
4648 .buffer()
4649 .read(cx)
4650 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4651 })?;
4652 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4653 if excerpted_buffer == *buffer {
4654 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4655 let excerpt_range = excerpt_range.to_offset(buffer);
4656 buffer
4657 .edited_ranges_for_transaction::<usize>(transaction)
4658 .all(|range| {
4659 excerpt_range.start <= range.start
4660 && excerpt_range.end >= range.end
4661 })
4662 })?;
4663
4664 if all_edits_within_excerpt {
4665 return Ok(());
4666 }
4667 }
4668 }
4669 }
4670 } else {
4671 return Ok(());
4672 }
4673
4674 let mut ranges_to_highlight = Vec::new();
4675 let excerpt_buffer = cx.new(|cx| {
4676 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4677 for (buffer_handle, transaction) in &entries {
4678 let buffer = buffer_handle.read(cx);
4679 ranges_to_highlight.extend(
4680 multibuffer.push_excerpts_with_context_lines(
4681 buffer_handle.clone(),
4682 buffer
4683 .edited_ranges_for_transaction::<usize>(transaction)
4684 .collect(),
4685 DEFAULT_MULTIBUFFER_CONTEXT,
4686 cx,
4687 ),
4688 );
4689 }
4690 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4691 multibuffer
4692 })?;
4693
4694 workspace.update_in(&mut cx, |workspace, window, cx| {
4695 let project = workspace.project().clone();
4696 let editor = cx
4697 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4698 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4699 editor.update(cx, |editor, cx| {
4700 editor.highlight_background::<Self>(
4701 &ranges_to_highlight,
4702 |theme| theme.editor_highlighted_line_background,
4703 cx,
4704 );
4705 });
4706 })?;
4707
4708 Ok(())
4709 }
4710
4711 pub fn clear_code_action_providers(&mut self) {
4712 self.code_action_providers.clear();
4713 self.available_code_actions.take();
4714 }
4715
4716 pub fn add_code_action_provider(
4717 &mut self,
4718 provider: Rc<dyn CodeActionProvider>,
4719 window: &mut Window,
4720 cx: &mut Context<Self>,
4721 ) {
4722 if self
4723 .code_action_providers
4724 .iter()
4725 .any(|existing_provider| existing_provider.id() == provider.id())
4726 {
4727 return;
4728 }
4729
4730 self.code_action_providers.push(provider);
4731 self.refresh_code_actions(window, cx);
4732 }
4733
4734 pub fn remove_code_action_provider(
4735 &mut self,
4736 id: Arc<str>,
4737 window: &mut Window,
4738 cx: &mut Context<Self>,
4739 ) {
4740 self.code_action_providers
4741 .retain(|provider| provider.id() != id);
4742 self.refresh_code_actions(window, cx);
4743 }
4744
4745 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4746 let buffer = self.buffer.read(cx);
4747 let newest_selection = self.selections.newest_anchor().clone();
4748 if newest_selection.head().diff_base_anchor.is_some() {
4749 return None;
4750 }
4751 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4752 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4753 if start_buffer != end_buffer {
4754 return None;
4755 }
4756
4757 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4758 cx.background_executor()
4759 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4760 .await;
4761
4762 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4763 let providers = this.code_action_providers.clone();
4764 let tasks = this
4765 .code_action_providers
4766 .iter()
4767 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4768 .collect::<Vec<_>>();
4769 (providers, tasks)
4770 })?;
4771
4772 let mut actions = Vec::new();
4773 for (provider, provider_actions) in
4774 providers.into_iter().zip(future::join_all(tasks).await)
4775 {
4776 if let Some(provider_actions) = provider_actions.log_err() {
4777 actions.extend(provider_actions.into_iter().map(|action| {
4778 AvailableCodeAction {
4779 excerpt_id: newest_selection.start.excerpt_id,
4780 action,
4781 provider: provider.clone(),
4782 }
4783 }));
4784 }
4785 }
4786
4787 this.update(&mut cx, |this, cx| {
4788 this.available_code_actions = if actions.is_empty() {
4789 None
4790 } else {
4791 Some((
4792 Location {
4793 buffer: start_buffer,
4794 range: start..end,
4795 },
4796 actions.into(),
4797 ))
4798 };
4799 cx.notify();
4800 })
4801 }));
4802 None
4803 }
4804
4805 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4806 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4807 self.show_git_blame_inline = false;
4808
4809 self.show_git_blame_inline_delay_task =
4810 Some(cx.spawn_in(window, |this, mut cx| async move {
4811 cx.background_executor().timer(delay).await;
4812
4813 this.update(&mut cx, |this, cx| {
4814 this.show_git_blame_inline = true;
4815 cx.notify();
4816 })
4817 .log_err();
4818 }));
4819 }
4820 }
4821
4822 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4823 if self.pending_rename.is_some() {
4824 return None;
4825 }
4826
4827 let provider = self.semantics_provider.clone()?;
4828 let buffer = self.buffer.read(cx);
4829 let newest_selection = self.selections.newest_anchor().clone();
4830 let cursor_position = newest_selection.head();
4831 let (cursor_buffer, cursor_buffer_position) =
4832 buffer.text_anchor_for_position(cursor_position, cx)?;
4833 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4834 if cursor_buffer != tail_buffer {
4835 return None;
4836 }
4837 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4838 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4839 cx.background_executor()
4840 .timer(Duration::from_millis(debounce))
4841 .await;
4842
4843 let highlights = if let Some(highlights) = cx
4844 .update(|cx| {
4845 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4846 })
4847 .ok()
4848 .flatten()
4849 {
4850 highlights.await.log_err()
4851 } else {
4852 None
4853 };
4854
4855 if let Some(highlights) = highlights {
4856 this.update(&mut cx, |this, cx| {
4857 if this.pending_rename.is_some() {
4858 return;
4859 }
4860
4861 let buffer_id = cursor_position.buffer_id;
4862 let buffer = this.buffer.read(cx);
4863 if !buffer
4864 .text_anchor_for_position(cursor_position, cx)
4865 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4866 {
4867 return;
4868 }
4869
4870 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4871 let mut write_ranges = Vec::new();
4872 let mut read_ranges = Vec::new();
4873 for highlight in highlights {
4874 for (excerpt_id, excerpt_range) in
4875 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4876 {
4877 let start = highlight
4878 .range
4879 .start
4880 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4881 let end = highlight
4882 .range
4883 .end
4884 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4885 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4886 continue;
4887 }
4888
4889 let range = Anchor {
4890 buffer_id,
4891 excerpt_id,
4892 text_anchor: start,
4893 diff_base_anchor: None,
4894 }..Anchor {
4895 buffer_id,
4896 excerpt_id,
4897 text_anchor: end,
4898 diff_base_anchor: None,
4899 };
4900 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4901 write_ranges.push(range);
4902 } else {
4903 read_ranges.push(range);
4904 }
4905 }
4906 }
4907
4908 this.highlight_background::<DocumentHighlightRead>(
4909 &read_ranges,
4910 |theme| theme.editor_document_highlight_read_background,
4911 cx,
4912 );
4913 this.highlight_background::<DocumentHighlightWrite>(
4914 &write_ranges,
4915 |theme| theme.editor_document_highlight_write_background,
4916 cx,
4917 );
4918 cx.notify();
4919 })
4920 .log_err();
4921 }
4922 }));
4923 None
4924 }
4925
4926 pub fn refresh_selected_text_highlights(
4927 &mut self,
4928 window: &mut Window,
4929 cx: &mut Context<Editor>,
4930 ) {
4931 self.selection_highlight_task.take();
4932 if !EditorSettings::get_global(cx).selection_highlight {
4933 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4934 return;
4935 }
4936 if self.selections.count() != 1 || self.selections.line_mode {
4937 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4938 return;
4939 }
4940 let selection = self.selections.newest::<Point>(cx);
4941 if selection.is_empty() || selection.start.row != selection.end.row {
4942 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4943 return;
4944 }
4945 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4946 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4947 cx.background_executor()
4948 .timer(Duration::from_millis(debounce))
4949 .await;
4950 let Some(Some(matches_task)) = editor
4951 .update_in(&mut cx, |editor, _, cx| {
4952 if editor.selections.count() != 1 || editor.selections.line_mode {
4953 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4954 return None;
4955 }
4956 let selection = editor.selections.newest::<Point>(cx);
4957 if selection.is_empty() || selection.start.row != selection.end.row {
4958 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4959 return None;
4960 }
4961 let buffer = editor.buffer().read(cx).snapshot(cx);
4962 let query = buffer.text_for_range(selection.range()).collect::<String>();
4963 if query.trim().is_empty() {
4964 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4965 return None;
4966 }
4967 Some(cx.background_spawn(async move {
4968 let mut ranges = Vec::new();
4969 let selection_anchors = selection.range().to_anchors(&buffer);
4970 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4971 for (search_buffer, search_range, excerpt_id) in
4972 buffer.range_to_buffer_ranges(range)
4973 {
4974 ranges.extend(
4975 project::search::SearchQuery::text(
4976 query.clone(),
4977 false,
4978 false,
4979 false,
4980 Default::default(),
4981 Default::default(),
4982 None,
4983 )
4984 .unwrap()
4985 .search(search_buffer, Some(search_range.clone()))
4986 .await
4987 .into_iter()
4988 .filter_map(
4989 |match_range| {
4990 let start = search_buffer.anchor_after(
4991 search_range.start + match_range.start,
4992 );
4993 let end = search_buffer.anchor_before(
4994 search_range.start + match_range.end,
4995 );
4996 let range = Anchor::range_in_buffer(
4997 excerpt_id,
4998 search_buffer.remote_id(),
4999 start..end,
5000 );
5001 (range != selection_anchors).then_some(range)
5002 },
5003 ),
5004 );
5005 }
5006 }
5007 ranges
5008 }))
5009 })
5010 .log_err()
5011 else {
5012 return;
5013 };
5014 let matches = matches_task.await;
5015 editor
5016 .update_in(&mut cx, |editor, _, cx| {
5017 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5018 if !matches.is_empty() {
5019 editor.highlight_background::<SelectedTextHighlight>(
5020 &matches,
5021 |theme| theme.editor_document_highlight_bracket_background,
5022 cx,
5023 )
5024 }
5025 })
5026 .log_err();
5027 }));
5028 }
5029
5030 pub fn refresh_inline_completion(
5031 &mut self,
5032 debounce: bool,
5033 user_requested: bool,
5034 window: &mut Window,
5035 cx: &mut Context<Self>,
5036 ) -> Option<()> {
5037 let provider = self.edit_prediction_provider()?;
5038 let cursor = self.selections.newest_anchor().head();
5039 let (buffer, cursor_buffer_position) =
5040 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5041
5042 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5043 self.discard_inline_completion(false, cx);
5044 return None;
5045 }
5046
5047 if !user_requested
5048 && (!self.should_show_edit_predictions()
5049 || !self.is_focused(window)
5050 || buffer.read(cx).is_empty())
5051 {
5052 self.discard_inline_completion(false, cx);
5053 return None;
5054 }
5055
5056 self.update_visible_inline_completion(window, cx);
5057 provider.refresh(
5058 self.project.clone(),
5059 buffer,
5060 cursor_buffer_position,
5061 debounce,
5062 cx,
5063 );
5064 Some(())
5065 }
5066
5067 fn show_edit_predictions_in_menu(&self) -> bool {
5068 match self.edit_prediction_settings {
5069 EditPredictionSettings::Disabled => false,
5070 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5071 }
5072 }
5073
5074 pub fn edit_predictions_enabled(&self) -> bool {
5075 match self.edit_prediction_settings {
5076 EditPredictionSettings::Disabled => false,
5077 EditPredictionSettings::Enabled { .. } => true,
5078 }
5079 }
5080
5081 fn edit_prediction_requires_modifier(&self) -> bool {
5082 match self.edit_prediction_settings {
5083 EditPredictionSettings::Disabled => false,
5084 EditPredictionSettings::Enabled {
5085 preview_requires_modifier,
5086 ..
5087 } => preview_requires_modifier,
5088 }
5089 }
5090
5091 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5092 if self.edit_prediction_provider.is_none() {
5093 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5094 } else {
5095 let selection = self.selections.newest_anchor();
5096 let cursor = selection.head();
5097
5098 if let Some((buffer, cursor_buffer_position)) =
5099 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5100 {
5101 self.edit_prediction_settings =
5102 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5103 }
5104 }
5105 }
5106
5107 fn edit_prediction_settings_at_position(
5108 &self,
5109 buffer: &Entity<Buffer>,
5110 buffer_position: language::Anchor,
5111 cx: &App,
5112 ) -> EditPredictionSettings {
5113 if self.mode != EditorMode::Full
5114 || !self.show_inline_completions_override.unwrap_or(true)
5115 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5116 {
5117 return EditPredictionSettings::Disabled;
5118 }
5119
5120 let buffer = buffer.read(cx);
5121
5122 let file = buffer.file();
5123
5124 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5125 return EditPredictionSettings::Disabled;
5126 };
5127
5128 let by_provider = matches!(
5129 self.menu_inline_completions_policy,
5130 MenuInlineCompletionsPolicy::ByProvider
5131 );
5132
5133 let show_in_menu = by_provider
5134 && self
5135 .edit_prediction_provider
5136 .as_ref()
5137 .map_or(false, |provider| {
5138 provider.provider.show_completions_in_menu()
5139 });
5140
5141 let preview_requires_modifier =
5142 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5143
5144 EditPredictionSettings::Enabled {
5145 show_in_menu,
5146 preview_requires_modifier,
5147 }
5148 }
5149
5150 fn should_show_edit_predictions(&self) -> bool {
5151 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5152 }
5153
5154 pub fn edit_prediction_preview_is_active(&self) -> bool {
5155 matches!(
5156 self.edit_prediction_preview,
5157 EditPredictionPreview::Active { .. }
5158 )
5159 }
5160
5161 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5162 let cursor = self.selections.newest_anchor().head();
5163 if let Some((buffer, cursor_position)) =
5164 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5165 {
5166 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5167 } else {
5168 false
5169 }
5170 }
5171
5172 fn edit_predictions_enabled_in_buffer(
5173 &self,
5174 buffer: &Entity<Buffer>,
5175 buffer_position: language::Anchor,
5176 cx: &App,
5177 ) -> bool {
5178 maybe!({
5179 let provider = self.edit_prediction_provider()?;
5180 if !provider.is_enabled(&buffer, buffer_position, cx) {
5181 return Some(false);
5182 }
5183 let buffer = buffer.read(cx);
5184 let Some(file) = buffer.file() else {
5185 return Some(true);
5186 };
5187 let settings = all_language_settings(Some(file), cx);
5188 Some(settings.edit_predictions_enabled_for_file(file, cx))
5189 })
5190 .unwrap_or(false)
5191 }
5192
5193 fn cycle_inline_completion(
5194 &mut self,
5195 direction: Direction,
5196 window: &mut Window,
5197 cx: &mut Context<Self>,
5198 ) -> Option<()> {
5199 let provider = self.edit_prediction_provider()?;
5200 let cursor = self.selections.newest_anchor().head();
5201 let (buffer, cursor_buffer_position) =
5202 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5203 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5204 return None;
5205 }
5206
5207 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5208 self.update_visible_inline_completion(window, cx);
5209
5210 Some(())
5211 }
5212
5213 pub fn show_inline_completion(
5214 &mut self,
5215 _: &ShowEditPrediction,
5216 window: &mut Window,
5217 cx: &mut Context<Self>,
5218 ) {
5219 if !self.has_active_inline_completion() {
5220 self.refresh_inline_completion(false, true, window, cx);
5221 return;
5222 }
5223
5224 self.update_visible_inline_completion(window, cx);
5225 }
5226
5227 pub fn display_cursor_names(
5228 &mut self,
5229 _: &DisplayCursorNames,
5230 window: &mut Window,
5231 cx: &mut Context<Self>,
5232 ) {
5233 self.show_cursor_names(window, cx);
5234 }
5235
5236 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5237 self.show_cursor_names = true;
5238 cx.notify();
5239 cx.spawn_in(window, |this, mut cx| async move {
5240 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5241 this.update(&mut cx, |this, cx| {
5242 this.show_cursor_names = false;
5243 cx.notify()
5244 })
5245 .ok()
5246 })
5247 .detach();
5248 }
5249
5250 pub fn next_edit_prediction(
5251 &mut self,
5252 _: &NextEditPrediction,
5253 window: &mut Window,
5254 cx: &mut Context<Self>,
5255 ) {
5256 if self.has_active_inline_completion() {
5257 self.cycle_inline_completion(Direction::Next, window, cx);
5258 } else {
5259 let is_copilot_disabled = self
5260 .refresh_inline_completion(false, true, window, cx)
5261 .is_none();
5262 if is_copilot_disabled {
5263 cx.propagate();
5264 }
5265 }
5266 }
5267
5268 pub fn previous_edit_prediction(
5269 &mut self,
5270 _: &PreviousEditPrediction,
5271 window: &mut Window,
5272 cx: &mut Context<Self>,
5273 ) {
5274 if self.has_active_inline_completion() {
5275 self.cycle_inline_completion(Direction::Prev, window, cx);
5276 } else {
5277 let is_copilot_disabled = self
5278 .refresh_inline_completion(false, true, window, cx)
5279 .is_none();
5280 if is_copilot_disabled {
5281 cx.propagate();
5282 }
5283 }
5284 }
5285
5286 pub fn accept_edit_prediction(
5287 &mut self,
5288 _: &AcceptEditPrediction,
5289 window: &mut Window,
5290 cx: &mut Context<Self>,
5291 ) {
5292 if self.show_edit_predictions_in_menu() {
5293 self.hide_context_menu(window, cx);
5294 }
5295
5296 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5297 return;
5298 };
5299
5300 self.report_inline_completion_event(
5301 active_inline_completion.completion_id.clone(),
5302 true,
5303 cx,
5304 );
5305
5306 match &active_inline_completion.completion {
5307 InlineCompletion::Move { target, .. } => {
5308 let target = *target;
5309
5310 if let Some(position_map) = &self.last_position_map {
5311 if position_map
5312 .visible_row_range
5313 .contains(&target.to_display_point(&position_map.snapshot).row())
5314 || !self.edit_prediction_requires_modifier()
5315 {
5316 self.unfold_ranges(&[target..target], true, false, cx);
5317 // Note that this is also done in vim's handler of the Tab action.
5318 self.change_selections(
5319 Some(Autoscroll::newest()),
5320 window,
5321 cx,
5322 |selections| {
5323 selections.select_anchor_ranges([target..target]);
5324 },
5325 );
5326 self.clear_row_highlights::<EditPredictionPreview>();
5327
5328 self.edit_prediction_preview
5329 .set_previous_scroll_position(None);
5330 } else {
5331 self.edit_prediction_preview
5332 .set_previous_scroll_position(Some(
5333 position_map.snapshot.scroll_anchor,
5334 ));
5335
5336 self.highlight_rows::<EditPredictionPreview>(
5337 target..target,
5338 cx.theme().colors().editor_highlighted_line_background,
5339 true,
5340 cx,
5341 );
5342 self.request_autoscroll(Autoscroll::fit(), cx);
5343 }
5344 }
5345 }
5346 InlineCompletion::Edit { edits, .. } => {
5347 if let Some(provider) = self.edit_prediction_provider() {
5348 provider.accept(cx);
5349 }
5350
5351 let snapshot = self.buffer.read(cx).snapshot(cx);
5352 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5353
5354 self.buffer.update(cx, |buffer, cx| {
5355 buffer.edit(edits.iter().cloned(), None, cx)
5356 });
5357
5358 self.change_selections(None, window, cx, |s| {
5359 s.select_anchor_ranges([last_edit_end..last_edit_end])
5360 });
5361
5362 self.update_visible_inline_completion(window, cx);
5363 if self.active_inline_completion.is_none() {
5364 self.refresh_inline_completion(true, true, window, cx);
5365 }
5366
5367 cx.notify();
5368 }
5369 }
5370
5371 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5372 }
5373
5374 pub fn accept_partial_inline_completion(
5375 &mut self,
5376 _: &AcceptPartialEditPrediction,
5377 window: &mut Window,
5378 cx: &mut Context<Self>,
5379 ) {
5380 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5381 return;
5382 };
5383 if self.selections.count() != 1 {
5384 return;
5385 }
5386
5387 self.report_inline_completion_event(
5388 active_inline_completion.completion_id.clone(),
5389 true,
5390 cx,
5391 );
5392
5393 match &active_inline_completion.completion {
5394 InlineCompletion::Move { target, .. } => {
5395 let target = *target;
5396 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5397 selections.select_anchor_ranges([target..target]);
5398 });
5399 }
5400 InlineCompletion::Edit { edits, .. } => {
5401 // Find an insertion that starts at the cursor position.
5402 let snapshot = self.buffer.read(cx).snapshot(cx);
5403 let cursor_offset = self.selections.newest::<usize>(cx).head();
5404 let insertion = edits.iter().find_map(|(range, text)| {
5405 let range = range.to_offset(&snapshot);
5406 if range.is_empty() && range.start == cursor_offset {
5407 Some(text)
5408 } else {
5409 None
5410 }
5411 });
5412
5413 if let Some(text) = insertion {
5414 let mut partial_completion = text
5415 .chars()
5416 .by_ref()
5417 .take_while(|c| c.is_alphabetic())
5418 .collect::<String>();
5419 if partial_completion.is_empty() {
5420 partial_completion = text
5421 .chars()
5422 .by_ref()
5423 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5424 .collect::<String>();
5425 }
5426
5427 cx.emit(EditorEvent::InputHandled {
5428 utf16_range_to_replace: None,
5429 text: partial_completion.clone().into(),
5430 });
5431
5432 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5433
5434 self.refresh_inline_completion(true, true, window, cx);
5435 cx.notify();
5436 } else {
5437 self.accept_edit_prediction(&Default::default(), window, cx);
5438 }
5439 }
5440 }
5441 }
5442
5443 fn discard_inline_completion(
5444 &mut self,
5445 should_report_inline_completion_event: bool,
5446 cx: &mut Context<Self>,
5447 ) -> bool {
5448 if should_report_inline_completion_event {
5449 let completion_id = self
5450 .active_inline_completion
5451 .as_ref()
5452 .and_then(|active_completion| active_completion.completion_id.clone());
5453
5454 self.report_inline_completion_event(completion_id, false, cx);
5455 }
5456
5457 if let Some(provider) = self.edit_prediction_provider() {
5458 provider.discard(cx);
5459 }
5460
5461 self.take_active_inline_completion(cx)
5462 }
5463
5464 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5465 let Some(provider) = self.edit_prediction_provider() else {
5466 return;
5467 };
5468
5469 let Some((_, buffer, _)) = self
5470 .buffer
5471 .read(cx)
5472 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5473 else {
5474 return;
5475 };
5476
5477 let extension = buffer
5478 .read(cx)
5479 .file()
5480 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5481
5482 let event_type = match accepted {
5483 true => "Edit Prediction Accepted",
5484 false => "Edit Prediction Discarded",
5485 };
5486 telemetry::event!(
5487 event_type,
5488 provider = provider.name(),
5489 prediction_id = id,
5490 suggestion_accepted = accepted,
5491 file_extension = extension,
5492 );
5493 }
5494
5495 pub fn has_active_inline_completion(&self) -> bool {
5496 self.active_inline_completion.is_some()
5497 }
5498
5499 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5500 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5501 return false;
5502 };
5503
5504 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5505 self.clear_highlights::<InlineCompletionHighlight>(cx);
5506 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5507 true
5508 }
5509
5510 /// Returns true when we're displaying the edit prediction popover below the cursor
5511 /// like we are not previewing and the LSP autocomplete menu is visible
5512 /// or we are in `when_holding_modifier` mode.
5513 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5514 if self.edit_prediction_preview_is_active()
5515 || !self.show_edit_predictions_in_menu()
5516 || !self.edit_predictions_enabled()
5517 {
5518 return false;
5519 }
5520
5521 if self.has_visible_completions_menu() {
5522 return true;
5523 }
5524
5525 has_completion && self.edit_prediction_requires_modifier()
5526 }
5527
5528 fn handle_modifiers_changed(
5529 &mut self,
5530 modifiers: Modifiers,
5531 position_map: &PositionMap,
5532 window: &mut Window,
5533 cx: &mut Context<Self>,
5534 ) {
5535 if self.show_edit_predictions_in_menu() {
5536 self.update_edit_prediction_preview(&modifiers, window, cx);
5537 }
5538
5539 self.update_selection_mode(&modifiers, position_map, window, cx);
5540
5541 let mouse_position = window.mouse_position();
5542 if !position_map.text_hitbox.is_hovered(window) {
5543 return;
5544 }
5545
5546 self.update_hovered_link(
5547 position_map.point_for_position(mouse_position),
5548 &position_map.snapshot,
5549 modifiers,
5550 window,
5551 cx,
5552 )
5553 }
5554
5555 fn update_selection_mode(
5556 &mut self,
5557 modifiers: &Modifiers,
5558 position_map: &PositionMap,
5559 window: &mut Window,
5560 cx: &mut Context<Self>,
5561 ) {
5562 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5563 return;
5564 }
5565
5566 let mouse_position = window.mouse_position();
5567 let point_for_position = position_map.point_for_position(mouse_position);
5568 let position = point_for_position.previous_valid;
5569
5570 self.select(
5571 SelectPhase::BeginColumnar {
5572 position,
5573 reset: false,
5574 goal_column: point_for_position.exact_unclipped.column(),
5575 },
5576 window,
5577 cx,
5578 );
5579 }
5580
5581 fn update_edit_prediction_preview(
5582 &mut self,
5583 modifiers: &Modifiers,
5584 window: &mut Window,
5585 cx: &mut Context<Self>,
5586 ) {
5587 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5588 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5589 return;
5590 };
5591
5592 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5593 if matches!(
5594 self.edit_prediction_preview,
5595 EditPredictionPreview::Inactive { .. }
5596 ) {
5597 self.edit_prediction_preview = EditPredictionPreview::Active {
5598 previous_scroll_position: None,
5599 since: Instant::now(),
5600 };
5601
5602 self.update_visible_inline_completion(window, cx);
5603 cx.notify();
5604 }
5605 } else if let EditPredictionPreview::Active {
5606 previous_scroll_position,
5607 since,
5608 } = self.edit_prediction_preview
5609 {
5610 if let (Some(previous_scroll_position), Some(position_map)) =
5611 (previous_scroll_position, self.last_position_map.as_ref())
5612 {
5613 self.set_scroll_position(
5614 previous_scroll_position
5615 .scroll_position(&position_map.snapshot.display_snapshot),
5616 window,
5617 cx,
5618 );
5619 }
5620
5621 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5622 released_too_fast: since.elapsed() < Duration::from_millis(200),
5623 };
5624 self.clear_row_highlights::<EditPredictionPreview>();
5625 self.update_visible_inline_completion(window, cx);
5626 cx.notify();
5627 }
5628 }
5629
5630 fn update_visible_inline_completion(
5631 &mut self,
5632 _window: &mut Window,
5633 cx: &mut Context<Self>,
5634 ) -> Option<()> {
5635 let selection = self.selections.newest_anchor();
5636 let cursor = selection.head();
5637 let multibuffer = self.buffer.read(cx).snapshot(cx);
5638 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5639 let excerpt_id = cursor.excerpt_id;
5640
5641 let show_in_menu = self.show_edit_predictions_in_menu();
5642 let completions_menu_has_precedence = !show_in_menu
5643 && (self.context_menu.borrow().is_some()
5644 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5645
5646 if completions_menu_has_precedence
5647 || !offset_selection.is_empty()
5648 || self
5649 .active_inline_completion
5650 .as_ref()
5651 .map_or(false, |completion| {
5652 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5653 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5654 !invalidation_range.contains(&offset_selection.head())
5655 })
5656 {
5657 self.discard_inline_completion(false, cx);
5658 return None;
5659 }
5660
5661 self.take_active_inline_completion(cx);
5662 let Some(provider) = self.edit_prediction_provider() else {
5663 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5664 return None;
5665 };
5666
5667 let (buffer, cursor_buffer_position) =
5668 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5669
5670 self.edit_prediction_settings =
5671 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5672
5673 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5674
5675 if self.edit_prediction_indent_conflict {
5676 let cursor_point = cursor.to_point(&multibuffer);
5677
5678 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5679
5680 if let Some((_, indent)) = indents.iter().next() {
5681 if indent.len == cursor_point.column {
5682 self.edit_prediction_indent_conflict = false;
5683 }
5684 }
5685 }
5686
5687 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5688 let edits = inline_completion
5689 .edits
5690 .into_iter()
5691 .flat_map(|(range, new_text)| {
5692 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5693 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5694 Some((start..end, new_text))
5695 })
5696 .collect::<Vec<_>>();
5697 if edits.is_empty() {
5698 return None;
5699 }
5700
5701 let first_edit_start = edits.first().unwrap().0.start;
5702 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5703 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5704
5705 let last_edit_end = edits.last().unwrap().0.end;
5706 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5707 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5708
5709 let cursor_row = cursor.to_point(&multibuffer).row;
5710
5711 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5712
5713 let mut inlay_ids = Vec::new();
5714 let invalidation_row_range;
5715 let move_invalidation_row_range = if cursor_row < edit_start_row {
5716 Some(cursor_row..edit_end_row)
5717 } else if cursor_row > edit_end_row {
5718 Some(edit_start_row..cursor_row)
5719 } else {
5720 None
5721 };
5722 let is_move =
5723 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5724 let completion = if is_move {
5725 invalidation_row_range =
5726 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5727 let target = first_edit_start;
5728 InlineCompletion::Move { target, snapshot }
5729 } else {
5730 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5731 && !self.inline_completions_hidden_for_vim_mode;
5732
5733 if show_completions_in_buffer {
5734 if edits
5735 .iter()
5736 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5737 {
5738 let mut inlays = Vec::new();
5739 for (range, new_text) in &edits {
5740 let inlay = Inlay::inline_completion(
5741 post_inc(&mut self.next_inlay_id),
5742 range.start,
5743 new_text.as_str(),
5744 );
5745 inlay_ids.push(inlay.id);
5746 inlays.push(inlay);
5747 }
5748
5749 self.splice_inlays(&[], inlays, cx);
5750 } else {
5751 let background_color = cx.theme().status().deleted_background;
5752 self.highlight_text::<InlineCompletionHighlight>(
5753 edits.iter().map(|(range, _)| range.clone()).collect(),
5754 HighlightStyle {
5755 background_color: Some(background_color),
5756 ..Default::default()
5757 },
5758 cx,
5759 );
5760 }
5761 }
5762
5763 invalidation_row_range = edit_start_row..edit_end_row;
5764
5765 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5766 if provider.show_tab_accept_marker() {
5767 EditDisplayMode::TabAccept
5768 } else {
5769 EditDisplayMode::Inline
5770 }
5771 } else {
5772 EditDisplayMode::DiffPopover
5773 };
5774
5775 InlineCompletion::Edit {
5776 edits,
5777 edit_preview: inline_completion.edit_preview,
5778 display_mode,
5779 snapshot,
5780 }
5781 };
5782
5783 let invalidation_range = multibuffer
5784 .anchor_before(Point::new(invalidation_row_range.start, 0))
5785 ..multibuffer.anchor_after(Point::new(
5786 invalidation_row_range.end,
5787 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5788 ));
5789
5790 self.stale_inline_completion_in_menu = None;
5791 self.active_inline_completion = Some(InlineCompletionState {
5792 inlay_ids,
5793 completion,
5794 completion_id: inline_completion.id,
5795 invalidation_range,
5796 });
5797
5798 cx.notify();
5799
5800 Some(())
5801 }
5802
5803 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5804 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5805 }
5806
5807 fn render_code_actions_indicator(
5808 &self,
5809 _style: &EditorStyle,
5810 row: DisplayRow,
5811 is_active: bool,
5812 cx: &mut Context<Self>,
5813 ) -> Option<IconButton> {
5814 if self.available_code_actions.is_some() {
5815 Some(
5816 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5817 .shape(ui::IconButtonShape::Square)
5818 .icon_size(IconSize::XSmall)
5819 .icon_color(Color::Muted)
5820 .toggle_state(is_active)
5821 .tooltip({
5822 let focus_handle = self.focus_handle.clone();
5823 move |window, cx| {
5824 Tooltip::for_action_in(
5825 "Toggle Code Actions",
5826 &ToggleCodeActions {
5827 deployed_from_indicator: None,
5828 },
5829 &focus_handle,
5830 window,
5831 cx,
5832 )
5833 }
5834 })
5835 .on_click(cx.listener(move |editor, _e, window, cx| {
5836 window.focus(&editor.focus_handle(cx));
5837 editor.toggle_code_actions(
5838 &ToggleCodeActions {
5839 deployed_from_indicator: Some(row),
5840 },
5841 window,
5842 cx,
5843 );
5844 })),
5845 )
5846 } else {
5847 None
5848 }
5849 }
5850
5851 fn clear_tasks(&mut self) {
5852 self.tasks.clear()
5853 }
5854
5855 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5856 if self.tasks.insert(key, value).is_some() {
5857 // This case should hopefully be rare, but just in case...
5858 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5859 }
5860 }
5861
5862 fn build_tasks_context(
5863 project: &Entity<Project>,
5864 buffer: &Entity<Buffer>,
5865 buffer_row: u32,
5866 tasks: &Arc<RunnableTasks>,
5867 cx: &mut Context<Self>,
5868 ) -> Task<Option<task::TaskContext>> {
5869 let position = Point::new(buffer_row, tasks.column);
5870 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5871 let location = Location {
5872 buffer: buffer.clone(),
5873 range: range_start..range_start,
5874 };
5875 // Fill in the environmental variables from the tree-sitter captures
5876 let mut captured_task_variables = TaskVariables::default();
5877 for (capture_name, value) in tasks.extra_variables.clone() {
5878 captured_task_variables.insert(
5879 task::VariableName::Custom(capture_name.into()),
5880 value.clone(),
5881 );
5882 }
5883 project.update(cx, |project, cx| {
5884 project.task_store().update(cx, |task_store, cx| {
5885 task_store.task_context_for_location(captured_task_variables, location, cx)
5886 })
5887 })
5888 }
5889
5890 pub fn spawn_nearest_task(
5891 &mut self,
5892 action: &SpawnNearestTask,
5893 window: &mut Window,
5894 cx: &mut Context<Self>,
5895 ) {
5896 let Some((workspace, _)) = self.workspace.clone() else {
5897 return;
5898 };
5899 let Some(project) = self.project.clone() else {
5900 return;
5901 };
5902
5903 // Try to find a closest, enclosing node using tree-sitter that has a
5904 // task
5905 let Some((buffer, buffer_row, tasks)) = self
5906 .find_enclosing_node_task(cx)
5907 // Or find the task that's closest in row-distance.
5908 .or_else(|| self.find_closest_task(cx))
5909 else {
5910 return;
5911 };
5912
5913 let reveal_strategy = action.reveal;
5914 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5915 cx.spawn_in(window, |_, mut cx| async move {
5916 let context = task_context.await?;
5917 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5918
5919 let resolved = resolved_task.resolved.as_mut()?;
5920 resolved.reveal = reveal_strategy;
5921
5922 workspace
5923 .update(&mut cx, |workspace, cx| {
5924 workspace::tasks::schedule_resolved_task(
5925 workspace,
5926 task_source_kind,
5927 resolved_task,
5928 false,
5929 cx,
5930 );
5931 })
5932 .ok()
5933 })
5934 .detach();
5935 }
5936
5937 fn find_closest_task(
5938 &mut self,
5939 cx: &mut Context<Self>,
5940 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5941 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5942
5943 let ((buffer_id, row), tasks) = self
5944 .tasks
5945 .iter()
5946 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5947
5948 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5949 let tasks = Arc::new(tasks.to_owned());
5950 Some((buffer, *row, tasks))
5951 }
5952
5953 fn find_enclosing_node_task(
5954 &mut self,
5955 cx: &mut Context<Self>,
5956 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5957 let snapshot = self.buffer.read(cx).snapshot(cx);
5958 let offset = self.selections.newest::<usize>(cx).head();
5959 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5960 let buffer_id = excerpt.buffer().remote_id();
5961
5962 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5963 let mut cursor = layer.node().walk();
5964
5965 while cursor.goto_first_child_for_byte(offset).is_some() {
5966 if cursor.node().end_byte() == offset {
5967 cursor.goto_next_sibling();
5968 }
5969 }
5970
5971 // Ascend to the smallest ancestor that contains the range and has a task.
5972 loop {
5973 let node = cursor.node();
5974 let node_range = node.byte_range();
5975 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5976
5977 // Check if this node contains our offset
5978 if node_range.start <= offset && node_range.end >= offset {
5979 // If it contains offset, check for task
5980 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5981 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5982 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5983 }
5984 }
5985
5986 if !cursor.goto_parent() {
5987 break;
5988 }
5989 }
5990 None
5991 }
5992
5993 fn render_run_indicator(
5994 &self,
5995 _style: &EditorStyle,
5996 is_active: bool,
5997 row: DisplayRow,
5998 cx: &mut Context<Self>,
5999 ) -> IconButton {
6000 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6001 .shape(ui::IconButtonShape::Square)
6002 .icon_size(IconSize::XSmall)
6003 .icon_color(Color::Muted)
6004 .toggle_state(is_active)
6005 .on_click(cx.listener(move |editor, _e, window, cx| {
6006 window.focus(&editor.focus_handle(cx));
6007 editor.toggle_code_actions(
6008 &ToggleCodeActions {
6009 deployed_from_indicator: Some(row),
6010 },
6011 window,
6012 cx,
6013 );
6014 }))
6015 }
6016
6017 pub fn context_menu_visible(&self) -> bool {
6018 !self.edit_prediction_preview_is_active()
6019 && self
6020 .context_menu
6021 .borrow()
6022 .as_ref()
6023 .map_or(false, |menu| menu.visible())
6024 }
6025
6026 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6027 self.context_menu
6028 .borrow()
6029 .as_ref()
6030 .map(|menu| menu.origin())
6031 }
6032
6033 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6034 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6035
6036 fn render_edit_prediction_popover(
6037 &mut self,
6038 text_bounds: &Bounds<Pixels>,
6039 content_origin: gpui::Point<Pixels>,
6040 editor_snapshot: &EditorSnapshot,
6041 visible_row_range: Range<DisplayRow>,
6042 scroll_top: f32,
6043 scroll_bottom: f32,
6044 line_layouts: &[LineWithInvisibles],
6045 line_height: Pixels,
6046 scroll_pixel_position: gpui::Point<Pixels>,
6047 newest_selection_head: Option<DisplayPoint>,
6048 editor_width: Pixels,
6049 style: &EditorStyle,
6050 window: &mut Window,
6051 cx: &mut App,
6052 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6053 let active_inline_completion = self.active_inline_completion.as_ref()?;
6054
6055 if self.edit_prediction_visible_in_cursor_popover(true) {
6056 return None;
6057 }
6058
6059 match &active_inline_completion.completion {
6060 InlineCompletion::Move { target, .. } => {
6061 let target_display_point = target.to_display_point(editor_snapshot);
6062
6063 if self.edit_prediction_requires_modifier() {
6064 if !self.edit_prediction_preview_is_active() {
6065 return None;
6066 }
6067
6068 self.render_edit_prediction_modifier_jump_popover(
6069 text_bounds,
6070 content_origin,
6071 visible_row_range,
6072 line_layouts,
6073 line_height,
6074 scroll_pixel_position,
6075 newest_selection_head,
6076 target_display_point,
6077 window,
6078 cx,
6079 )
6080 } else {
6081 self.render_edit_prediction_eager_jump_popover(
6082 text_bounds,
6083 content_origin,
6084 editor_snapshot,
6085 visible_row_range,
6086 scroll_top,
6087 scroll_bottom,
6088 line_height,
6089 scroll_pixel_position,
6090 target_display_point,
6091 editor_width,
6092 window,
6093 cx,
6094 )
6095 }
6096 }
6097 InlineCompletion::Edit {
6098 display_mode: EditDisplayMode::Inline,
6099 ..
6100 } => None,
6101 InlineCompletion::Edit {
6102 display_mode: EditDisplayMode::TabAccept,
6103 edits,
6104 ..
6105 } => {
6106 let range = &edits.first()?.0;
6107 let target_display_point = range.end.to_display_point(editor_snapshot);
6108
6109 self.render_edit_prediction_end_of_line_popover(
6110 "Accept",
6111 editor_snapshot,
6112 visible_row_range,
6113 target_display_point,
6114 line_height,
6115 scroll_pixel_position,
6116 content_origin,
6117 editor_width,
6118 window,
6119 cx,
6120 )
6121 }
6122 InlineCompletion::Edit {
6123 edits,
6124 edit_preview,
6125 display_mode: EditDisplayMode::DiffPopover,
6126 snapshot,
6127 } => self.render_edit_prediction_diff_popover(
6128 text_bounds,
6129 content_origin,
6130 editor_snapshot,
6131 visible_row_range,
6132 line_layouts,
6133 line_height,
6134 scroll_pixel_position,
6135 newest_selection_head,
6136 editor_width,
6137 style,
6138 edits,
6139 edit_preview,
6140 snapshot,
6141 window,
6142 cx,
6143 ),
6144 }
6145 }
6146
6147 fn render_edit_prediction_modifier_jump_popover(
6148 &mut self,
6149 text_bounds: &Bounds<Pixels>,
6150 content_origin: gpui::Point<Pixels>,
6151 visible_row_range: Range<DisplayRow>,
6152 line_layouts: &[LineWithInvisibles],
6153 line_height: Pixels,
6154 scroll_pixel_position: gpui::Point<Pixels>,
6155 newest_selection_head: Option<DisplayPoint>,
6156 target_display_point: DisplayPoint,
6157 window: &mut Window,
6158 cx: &mut App,
6159 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6160 let scrolled_content_origin =
6161 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6162
6163 const SCROLL_PADDING_Y: Pixels = px(12.);
6164
6165 if target_display_point.row() < visible_row_range.start {
6166 return self.render_edit_prediction_scroll_popover(
6167 |_| SCROLL_PADDING_Y,
6168 IconName::ArrowUp,
6169 visible_row_range,
6170 line_layouts,
6171 newest_selection_head,
6172 scrolled_content_origin,
6173 window,
6174 cx,
6175 );
6176 } else if target_display_point.row() >= visible_row_range.end {
6177 return self.render_edit_prediction_scroll_popover(
6178 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6179 IconName::ArrowDown,
6180 visible_row_range,
6181 line_layouts,
6182 newest_selection_head,
6183 scrolled_content_origin,
6184 window,
6185 cx,
6186 );
6187 }
6188
6189 const POLE_WIDTH: Pixels = px(2.);
6190
6191 let line_layout =
6192 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6193 let target_column = target_display_point.column() as usize;
6194
6195 let target_x = line_layout.x_for_index(target_column);
6196 let target_y =
6197 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6198
6199 let flag_on_right = target_x < text_bounds.size.width / 2.;
6200
6201 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6202 border_color.l += 0.001;
6203
6204 let mut element = v_flex()
6205 .items_end()
6206 .when(flag_on_right, |el| el.items_start())
6207 .child(if flag_on_right {
6208 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6209 .rounded_bl(px(0.))
6210 .rounded_tl(px(0.))
6211 .border_l_2()
6212 .border_color(border_color)
6213 } else {
6214 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6215 .rounded_br(px(0.))
6216 .rounded_tr(px(0.))
6217 .border_r_2()
6218 .border_color(border_color)
6219 })
6220 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6221 .into_any();
6222
6223 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6224
6225 let mut origin = scrolled_content_origin + point(target_x, target_y)
6226 - point(
6227 if flag_on_right {
6228 POLE_WIDTH
6229 } else {
6230 size.width - POLE_WIDTH
6231 },
6232 size.height - line_height,
6233 );
6234
6235 origin.x = origin.x.max(content_origin.x);
6236
6237 element.prepaint_at(origin, window, cx);
6238
6239 Some((element, origin))
6240 }
6241
6242 fn render_edit_prediction_scroll_popover(
6243 &mut self,
6244 to_y: impl Fn(Size<Pixels>) -> Pixels,
6245 scroll_icon: IconName,
6246 visible_row_range: Range<DisplayRow>,
6247 line_layouts: &[LineWithInvisibles],
6248 newest_selection_head: Option<DisplayPoint>,
6249 scrolled_content_origin: gpui::Point<Pixels>,
6250 window: &mut Window,
6251 cx: &mut App,
6252 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6253 let mut element = self
6254 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6255 .into_any();
6256
6257 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6258
6259 let cursor = newest_selection_head?;
6260 let cursor_row_layout =
6261 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6262 let cursor_column = cursor.column() as usize;
6263
6264 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6265
6266 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6267
6268 element.prepaint_at(origin, window, cx);
6269 Some((element, origin))
6270 }
6271
6272 fn render_edit_prediction_eager_jump_popover(
6273 &mut self,
6274 text_bounds: &Bounds<Pixels>,
6275 content_origin: gpui::Point<Pixels>,
6276 editor_snapshot: &EditorSnapshot,
6277 visible_row_range: Range<DisplayRow>,
6278 scroll_top: f32,
6279 scroll_bottom: f32,
6280 line_height: Pixels,
6281 scroll_pixel_position: gpui::Point<Pixels>,
6282 target_display_point: DisplayPoint,
6283 editor_width: Pixels,
6284 window: &mut Window,
6285 cx: &mut App,
6286 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6287 if target_display_point.row().as_f32() < scroll_top {
6288 let mut element = self
6289 .render_edit_prediction_line_popover(
6290 "Jump to Edit",
6291 Some(IconName::ArrowUp),
6292 window,
6293 cx,
6294 )?
6295 .into_any();
6296
6297 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6298 let offset = point(
6299 (text_bounds.size.width - size.width) / 2.,
6300 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6301 );
6302
6303 let origin = text_bounds.origin + offset;
6304 element.prepaint_at(origin, window, cx);
6305 Some((element, origin))
6306 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6307 let mut element = self
6308 .render_edit_prediction_line_popover(
6309 "Jump to Edit",
6310 Some(IconName::ArrowDown),
6311 window,
6312 cx,
6313 )?
6314 .into_any();
6315
6316 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6317 let offset = point(
6318 (text_bounds.size.width - size.width) / 2.,
6319 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6320 );
6321
6322 let origin = text_bounds.origin + offset;
6323 element.prepaint_at(origin, window, cx);
6324 Some((element, origin))
6325 } else {
6326 self.render_edit_prediction_end_of_line_popover(
6327 "Jump to Edit",
6328 editor_snapshot,
6329 visible_row_range,
6330 target_display_point,
6331 line_height,
6332 scroll_pixel_position,
6333 content_origin,
6334 editor_width,
6335 window,
6336 cx,
6337 )
6338 }
6339 }
6340
6341 fn render_edit_prediction_end_of_line_popover(
6342 self: &mut Editor,
6343 label: &'static str,
6344 editor_snapshot: &EditorSnapshot,
6345 visible_row_range: Range<DisplayRow>,
6346 target_display_point: DisplayPoint,
6347 line_height: Pixels,
6348 scroll_pixel_position: gpui::Point<Pixels>,
6349 content_origin: gpui::Point<Pixels>,
6350 editor_width: Pixels,
6351 window: &mut Window,
6352 cx: &mut App,
6353 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6354 let target_line_end = DisplayPoint::new(
6355 target_display_point.row(),
6356 editor_snapshot.line_len(target_display_point.row()),
6357 );
6358
6359 let mut element = self
6360 .render_edit_prediction_line_popover(label, None, window, cx)?
6361 .into_any();
6362
6363 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6364
6365 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6366
6367 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6368 let mut origin = start_point
6369 + line_origin
6370 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6371 origin.x = origin.x.max(content_origin.x);
6372
6373 let max_x = content_origin.x + editor_width - size.width;
6374
6375 if origin.x > max_x {
6376 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6377
6378 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6379 origin.y += offset;
6380 IconName::ArrowUp
6381 } else {
6382 origin.y -= offset;
6383 IconName::ArrowDown
6384 };
6385
6386 element = self
6387 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6388 .into_any();
6389
6390 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6391
6392 origin.x = content_origin.x + editor_width - size.width - px(2.);
6393 }
6394
6395 element.prepaint_at(origin, window, cx);
6396 Some((element, origin))
6397 }
6398
6399 fn render_edit_prediction_diff_popover(
6400 self: &Editor,
6401 text_bounds: &Bounds<Pixels>,
6402 content_origin: gpui::Point<Pixels>,
6403 editor_snapshot: &EditorSnapshot,
6404 visible_row_range: Range<DisplayRow>,
6405 line_layouts: &[LineWithInvisibles],
6406 line_height: Pixels,
6407 scroll_pixel_position: gpui::Point<Pixels>,
6408 newest_selection_head: Option<DisplayPoint>,
6409 editor_width: Pixels,
6410 style: &EditorStyle,
6411 edits: &Vec<(Range<Anchor>, String)>,
6412 edit_preview: &Option<language::EditPreview>,
6413 snapshot: &language::BufferSnapshot,
6414 window: &mut Window,
6415 cx: &mut App,
6416 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6417 let edit_start = edits
6418 .first()
6419 .unwrap()
6420 .0
6421 .start
6422 .to_display_point(editor_snapshot);
6423 let edit_end = edits
6424 .last()
6425 .unwrap()
6426 .0
6427 .end
6428 .to_display_point(editor_snapshot);
6429
6430 let is_visible = visible_row_range.contains(&edit_start.row())
6431 || visible_row_range.contains(&edit_end.row());
6432 if !is_visible {
6433 return None;
6434 }
6435
6436 let highlighted_edits =
6437 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6438
6439 let styled_text = highlighted_edits.to_styled_text(&style.text);
6440 let line_count = highlighted_edits.text.lines().count();
6441
6442 const BORDER_WIDTH: Pixels = px(1.);
6443
6444 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6445 let has_keybind = keybind.is_some();
6446
6447 let mut element = h_flex()
6448 .items_start()
6449 .child(
6450 h_flex()
6451 .bg(cx.theme().colors().editor_background)
6452 .border(BORDER_WIDTH)
6453 .shadow_sm()
6454 .border_color(cx.theme().colors().border)
6455 .rounded_l_lg()
6456 .when(line_count > 1, |el| el.rounded_br_lg())
6457 .pr_1()
6458 .child(styled_text),
6459 )
6460 .child(
6461 h_flex()
6462 .h(line_height + BORDER_WIDTH * px(2.))
6463 .px_1p5()
6464 .gap_1()
6465 // Workaround: For some reason, there's a gap if we don't do this
6466 .ml(-BORDER_WIDTH)
6467 .shadow(smallvec![gpui::BoxShadow {
6468 color: gpui::black().opacity(0.05),
6469 offset: point(px(1.), px(1.)),
6470 blur_radius: px(2.),
6471 spread_radius: px(0.),
6472 }])
6473 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6474 .border(BORDER_WIDTH)
6475 .border_color(cx.theme().colors().border)
6476 .rounded_r_lg()
6477 .id("edit_prediction_diff_popover_keybind")
6478 .when(!has_keybind, |el| {
6479 let status_colors = cx.theme().status();
6480
6481 el.bg(status_colors.error_background)
6482 .border_color(status_colors.error.opacity(0.6))
6483 .child(Icon::new(IconName::Info).color(Color::Error))
6484 .cursor_default()
6485 .hoverable_tooltip(move |_window, cx| {
6486 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6487 })
6488 })
6489 .children(keybind),
6490 )
6491 .into_any();
6492
6493 let longest_row =
6494 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6495 let longest_line_width = if visible_row_range.contains(&longest_row) {
6496 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6497 } else {
6498 layout_line(
6499 longest_row,
6500 editor_snapshot,
6501 style,
6502 editor_width,
6503 |_| false,
6504 window,
6505 cx,
6506 )
6507 .width
6508 };
6509
6510 let viewport_bounds =
6511 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6512 right: -EditorElement::SCROLLBAR_WIDTH,
6513 ..Default::default()
6514 });
6515
6516 let x_after_longest =
6517 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6518 - scroll_pixel_position.x;
6519
6520 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6521
6522 // Fully visible if it can be displayed within the window (allow overlapping other
6523 // panes). However, this is only allowed if the popover starts within text_bounds.
6524 let can_position_to_the_right = x_after_longest < text_bounds.right()
6525 && x_after_longest + element_bounds.width < viewport_bounds.right();
6526
6527 let mut origin = if can_position_to_the_right {
6528 point(
6529 x_after_longest,
6530 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6531 - scroll_pixel_position.y,
6532 )
6533 } else {
6534 let cursor_row = newest_selection_head.map(|head| head.row());
6535 let above_edit = edit_start
6536 .row()
6537 .0
6538 .checked_sub(line_count as u32)
6539 .map(DisplayRow);
6540 let below_edit = Some(edit_end.row() + 1);
6541 let above_cursor =
6542 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6543 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6544
6545 // Place the edit popover adjacent to the edit if there is a location
6546 // available that is onscreen and does not obscure the cursor. Otherwise,
6547 // place it adjacent to the cursor.
6548 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6549 .into_iter()
6550 .flatten()
6551 .find(|&start_row| {
6552 let end_row = start_row + line_count as u32;
6553 visible_row_range.contains(&start_row)
6554 && visible_row_range.contains(&end_row)
6555 && cursor_row.map_or(true, |cursor_row| {
6556 !((start_row..end_row).contains(&cursor_row))
6557 })
6558 })?;
6559
6560 content_origin
6561 + point(
6562 -scroll_pixel_position.x,
6563 row_target.as_f32() * line_height - scroll_pixel_position.y,
6564 )
6565 };
6566
6567 origin.x -= BORDER_WIDTH;
6568
6569 window.defer_draw(element, origin, 1);
6570
6571 // Do not return an element, since it will already be drawn due to defer_draw.
6572 None
6573 }
6574
6575 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6576 px(30.)
6577 }
6578
6579 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6580 if self.read_only(cx) {
6581 cx.theme().players().read_only()
6582 } else {
6583 self.style.as_ref().unwrap().local_player
6584 }
6585 }
6586
6587 fn render_edit_prediction_accept_keybind(
6588 &self,
6589 window: &mut Window,
6590 cx: &App,
6591 ) -> Option<AnyElement> {
6592 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6593 let accept_keystroke = accept_binding.keystroke()?;
6594
6595 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6596
6597 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6598 Color::Accent
6599 } else {
6600 Color::Muted
6601 };
6602
6603 h_flex()
6604 .px_0p5()
6605 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6606 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6607 .text_size(TextSize::XSmall.rems(cx))
6608 .child(h_flex().children(ui::render_modifiers(
6609 &accept_keystroke.modifiers,
6610 PlatformStyle::platform(),
6611 Some(modifiers_color),
6612 Some(IconSize::XSmall.rems().into()),
6613 true,
6614 )))
6615 .when(is_platform_style_mac, |parent| {
6616 parent.child(accept_keystroke.key.clone())
6617 })
6618 .when(!is_platform_style_mac, |parent| {
6619 parent.child(
6620 Key::new(
6621 util::capitalize(&accept_keystroke.key),
6622 Some(Color::Default),
6623 )
6624 .size(Some(IconSize::XSmall.rems().into())),
6625 )
6626 })
6627 .into_any()
6628 .into()
6629 }
6630
6631 fn render_edit_prediction_line_popover(
6632 &self,
6633 label: impl Into<SharedString>,
6634 icon: Option<IconName>,
6635 window: &mut Window,
6636 cx: &App,
6637 ) -> Option<Stateful<Div>> {
6638 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6639
6640 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6641 let has_keybind = keybind.is_some();
6642
6643 let result = h_flex()
6644 .id("ep-line-popover")
6645 .py_0p5()
6646 .pl_1()
6647 .pr(padding_right)
6648 .gap_1()
6649 .rounded_md()
6650 .border_1()
6651 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6652 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6653 .shadow_sm()
6654 .when(!has_keybind, |el| {
6655 let status_colors = cx.theme().status();
6656
6657 el.bg(status_colors.error_background)
6658 .border_color(status_colors.error.opacity(0.6))
6659 .pl_2()
6660 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
6661 .cursor_default()
6662 .hoverable_tooltip(move |_window, cx| {
6663 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6664 })
6665 })
6666 .children(keybind)
6667 .child(
6668 Label::new(label)
6669 .size(LabelSize::Small)
6670 .when(!has_keybind, |el| {
6671 el.color(cx.theme().status().error.into()).strikethrough()
6672 }),
6673 )
6674 .when(!has_keybind, |el| {
6675 el.child(
6676 h_flex().ml_1().child(
6677 Icon::new(IconName::Info)
6678 .size(IconSize::Small)
6679 .color(cx.theme().status().error.into()),
6680 ),
6681 )
6682 })
6683 .when_some(icon, |element, icon| {
6684 element.child(
6685 div()
6686 .mt(px(1.5))
6687 .child(Icon::new(icon).size(IconSize::Small)),
6688 )
6689 });
6690
6691 Some(result)
6692 }
6693
6694 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6695 let accent_color = cx.theme().colors().text_accent;
6696 let editor_bg_color = cx.theme().colors().editor_background;
6697 editor_bg_color.blend(accent_color.opacity(0.1))
6698 }
6699
6700 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6701 let accent_color = cx.theme().colors().text_accent;
6702 let editor_bg_color = cx.theme().colors().editor_background;
6703 editor_bg_color.blend(accent_color.opacity(0.6))
6704 }
6705
6706 fn render_edit_prediction_cursor_popover(
6707 &self,
6708 min_width: Pixels,
6709 max_width: Pixels,
6710 cursor_point: Point,
6711 style: &EditorStyle,
6712 accept_keystroke: Option<&gpui::Keystroke>,
6713 _window: &Window,
6714 cx: &mut Context<Editor>,
6715 ) -> Option<AnyElement> {
6716 let provider = self.edit_prediction_provider.as_ref()?;
6717
6718 if provider.provider.needs_terms_acceptance(cx) {
6719 return Some(
6720 h_flex()
6721 .min_w(min_width)
6722 .flex_1()
6723 .px_2()
6724 .py_1()
6725 .gap_3()
6726 .elevation_2(cx)
6727 .hover(|style| style.bg(cx.theme().colors().element_hover))
6728 .id("accept-terms")
6729 .cursor_pointer()
6730 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6731 .on_click(cx.listener(|this, _event, window, cx| {
6732 cx.stop_propagation();
6733 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6734 window.dispatch_action(
6735 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6736 cx,
6737 );
6738 }))
6739 .child(
6740 h_flex()
6741 .flex_1()
6742 .gap_2()
6743 .child(Icon::new(IconName::ZedPredict))
6744 .child(Label::new("Accept Terms of Service"))
6745 .child(div().w_full())
6746 .child(
6747 Icon::new(IconName::ArrowUpRight)
6748 .color(Color::Muted)
6749 .size(IconSize::Small),
6750 )
6751 .into_any_element(),
6752 )
6753 .into_any(),
6754 );
6755 }
6756
6757 let is_refreshing = provider.provider.is_refreshing(cx);
6758
6759 fn pending_completion_container() -> Div {
6760 h_flex()
6761 .h_full()
6762 .flex_1()
6763 .gap_2()
6764 .child(Icon::new(IconName::ZedPredict))
6765 }
6766
6767 let completion = match &self.active_inline_completion {
6768 Some(prediction) => {
6769 if !self.has_visible_completions_menu() {
6770 const RADIUS: Pixels = px(6.);
6771 const BORDER_WIDTH: Pixels = px(1.);
6772
6773 return Some(
6774 h_flex()
6775 .elevation_2(cx)
6776 .border(BORDER_WIDTH)
6777 .border_color(cx.theme().colors().border)
6778 .when(accept_keystroke.is_none(), |el| {
6779 el.border_color(cx.theme().status().error)
6780 })
6781 .rounded(RADIUS)
6782 .rounded_tl(px(0.))
6783 .overflow_hidden()
6784 .child(div().px_1p5().child(match &prediction.completion {
6785 InlineCompletion::Move { target, snapshot } => {
6786 use text::ToPoint as _;
6787 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6788 {
6789 Icon::new(IconName::ZedPredictDown)
6790 } else {
6791 Icon::new(IconName::ZedPredictUp)
6792 }
6793 }
6794 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6795 }))
6796 .child(
6797 h_flex()
6798 .gap_1()
6799 .py_1()
6800 .px_2()
6801 .rounded_r(RADIUS - BORDER_WIDTH)
6802 .border_l_1()
6803 .border_color(cx.theme().colors().border)
6804 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6805 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6806 el.child(
6807 Label::new("Hold")
6808 .size(LabelSize::Small)
6809 .when(accept_keystroke.is_none(), |el| {
6810 el.strikethrough()
6811 })
6812 .line_height_style(LineHeightStyle::UiLabel),
6813 )
6814 })
6815 .id("edit_prediction_cursor_popover_keybind")
6816 .when(accept_keystroke.is_none(), |el| {
6817 let status_colors = cx.theme().status();
6818
6819 el.bg(status_colors.error_background)
6820 .border_color(status_colors.error.opacity(0.6))
6821 .child(Icon::new(IconName::Info).color(Color::Error))
6822 .cursor_default()
6823 .hoverable_tooltip(move |_window, cx| {
6824 cx.new(|_| MissingEditPredictionKeybindingTooltip)
6825 .into()
6826 })
6827 })
6828 .when_some(
6829 accept_keystroke.as_ref(),
6830 |el, accept_keystroke| {
6831 el.child(h_flex().children(ui::render_modifiers(
6832 &accept_keystroke.modifiers,
6833 PlatformStyle::platform(),
6834 Some(Color::Default),
6835 Some(IconSize::XSmall.rems().into()),
6836 false,
6837 )))
6838 },
6839 ),
6840 )
6841 .into_any(),
6842 );
6843 }
6844
6845 self.render_edit_prediction_cursor_popover_preview(
6846 prediction,
6847 cursor_point,
6848 style,
6849 cx,
6850 )?
6851 }
6852
6853 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6854 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6855 stale_completion,
6856 cursor_point,
6857 style,
6858 cx,
6859 )?,
6860
6861 None => {
6862 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6863 }
6864 },
6865
6866 None => pending_completion_container().child(Label::new("No Prediction")),
6867 };
6868
6869 let completion = if is_refreshing {
6870 completion
6871 .with_animation(
6872 "loading-completion",
6873 Animation::new(Duration::from_secs(2))
6874 .repeat()
6875 .with_easing(pulsating_between(0.4, 0.8)),
6876 |label, delta| label.opacity(delta),
6877 )
6878 .into_any_element()
6879 } else {
6880 completion.into_any_element()
6881 };
6882
6883 let has_completion = self.active_inline_completion.is_some();
6884
6885 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6886 Some(
6887 h_flex()
6888 .min_w(min_width)
6889 .max_w(max_width)
6890 .flex_1()
6891 .elevation_2(cx)
6892 .border_color(cx.theme().colors().border)
6893 .child(
6894 div()
6895 .flex_1()
6896 .py_1()
6897 .px_2()
6898 .overflow_hidden()
6899 .child(completion),
6900 )
6901 .when_some(accept_keystroke, |el, accept_keystroke| {
6902 if !accept_keystroke.modifiers.modified() {
6903 return el;
6904 }
6905
6906 el.child(
6907 h_flex()
6908 .h_full()
6909 .border_l_1()
6910 .rounded_r_lg()
6911 .border_color(cx.theme().colors().border)
6912 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6913 .gap_1()
6914 .py_1()
6915 .px_2()
6916 .child(
6917 h_flex()
6918 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6919 .when(is_platform_style_mac, |parent| parent.gap_1())
6920 .child(h_flex().children(ui::render_modifiers(
6921 &accept_keystroke.modifiers,
6922 PlatformStyle::platform(),
6923 Some(if !has_completion {
6924 Color::Muted
6925 } else {
6926 Color::Default
6927 }),
6928 None,
6929 false,
6930 ))),
6931 )
6932 .child(Label::new("Preview").into_any_element())
6933 .opacity(if has_completion { 1.0 } else { 0.4 }),
6934 )
6935 })
6936 .into_any(),
6937 )
6938 }
6939
6940 fn render_edit_prediction_cursor_popover_preview(
6941 &self,
6942 completion: &InlineCompletionState,
6943 cursor_point: Point,
6944 style: &EditorStyle,
6945 cx: &mut Context<Editor>,
6946 ) -> Option<Div> {
6947 use text::ToPoint as _;
6948
6949 fn render_relative_row_jump(
6950 prefix: impl Into<String>,
6951 current_row: u32,
6952 target_row: u32,
6953 ) -> Div {
6954 let (row_diff, arrow) = if target_row < current_row {
6955 (current_row - target_row, IconName::ArrowUp)
6956 } else {
6957 (target_row - current_row, IconName::ArrowDown)
6958 };
6959
6960 h_flex()
6961 .child(
6962 Label::new(format!("{}{}", prefix.into(), row_diff))
6963 .color(Color::Muted)
6964 .size(LabelSize::Small),
6965 )
6966 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6967 }
6968
6969 match &completion.completion {
6970 InlineCompletion::Move {
6971 target, snapshot, ..
6972 } => Some(
6973 h_flex()
6974 .px_2()
6975 .gap_2()
6976 .flex_1()
6977 .child(
6978 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6979 Icon::new(IconName::ZedPredictDown)
6980 } else {
6981 Icon::new(IconName::ZedPredictUp)
6982 },
6983 )
6984 .child(Label::new("Jump to Edit")),
6985 ),
6986
6987 InlineCompletion::Edit {
6988 edits,
6989 edit_preview,
6990 snapshot,
6991 display_mode: _,
6992 } => {
6993 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6994
6995 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6996 &snapshot,
6997 &edits,
6998 edit_preview.as_ref()?,
6999 true,
7000 cx,
7001 )
7002 .first_line_preview();
7003
7004 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7005 .with_default_highlights(&style.text, highlighted_edits.highlights);
7006
7007 let preview = h_flex()
7008 .gap_1()
7009 .min_w_16()
7010 .child(styled_text)
7011 .when(has_more_lines, |parent| parent.child("…"));
7012
7013 let left = if first_edit_row != cursor_point.row {
7014 render_relative_row_jump("", cursor_point.row, first_edit_row)
7015 .into_any_element()
7016 } else {
7017 Icon::new(IconName::ZedPredict).into_any_element()
7018 };
7019
7020 Some(
7021 h_flex()
7022 .h_full()
7023 .flex_1()
7024 .gap_2()
7025 .pr_1()
7026 .overflow_x_hidden()
7027 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7028 .child(left)
7029 .child(preview),
7030 )
7031 }
7032 }
7033 }
7034
7035 fn render_context_menu(
7036 &self,
7037 style: &EditorStyle,
7038 max_height_in_lines: u32,
7039 y_flipped: bool,
7040 window: &mut Window,
7041 cx: &mut Context<Editor>,
7042 ) -> Option<AnyElement> {
7043 let menu = self.context_menu.borrow();
7044 let menu = menu.as_ref()?;
7045 if !menu.visible() {
7046 return None;
7047 };
7048 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7049 }
7050
7051 fn render_context_menu_aside(
7052 &mut self,
7053 max_size: Size<Pixels>,
7054 window: &mut Window,
7055 cx: &mut Context<Editor>,
7056 ) -> Option<AnyElement> {
7057 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7058 if menu.visible() {
7059 menu.render_aside(self, max_size, window, cx)
7060 } else {
7061 None
7062 }
7063 })
7064 }
7065
7066 fn hide_context_menu(
7067 &mut self,
7068 window: &mut Window,
7069 cx: &mut Context<Self>,
7070 ) -> Option<CodeContextMenu> {
7071 cx.notify();
7072 self.completion_tasks.clear();
7073 let context_menu = self.context_menu.borrow_mut().take();
7074 self.stale_inline_completion_in_menu.take();
7075 self.update_visible_inline_completion(window, cx);
7076 context_menu
7077 }
7078
7079 fn show_snippet_choices(
7080 &mut self,
7081 choices: &Vec<String>,
7082 selection: Range<Anchor>,
7083 cx: &mut Context<Self>,
7084 ) {
7085 if selection.start.buffer_id.is_none() {
7086 return;
7087 }
7088 let buffer_id = selection.start.buffer_id.unwrap();
7089 let buffer = self.buffer().read(cx).buffer(buffer_id);
7090 let id = post_inc(&mut self.next_completion_id);
7091
7092 if let Some(buffer) = buffer {
7093 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7094 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7095 ));
7096 }
7097 }
7098
7099 pub fn insert_snippet(
7100 &mut self,
7101 insertion_ranges: &[Range<usize>],
7102 snippet: Snippet,
7103 window: &mut Window,
7104 cx: &mut Context<Self>,
7105 ) -> Result<()> {
7106 struct Tabstop<T> {
7107 is_end_tabstop: bool,
7108 ranges: Vec<Range<T>>,
7109 choices: Option<Vec<String>>,
7110 }
7111
7112 let tabstops = self.buffer.update(cx, |buffer, cx| {
7113 let snippet_text: Arc<str> = snippet.text.clone().into();
7114 buffer.edit(
7115 insertion_ranges
7116 .iter()
7117 .cloned()
7118 .map(|range| (range, snippet_text.clone())),
7119 Some(AutoindentMode::EachLine),
7120 cx,
7121 );
7122
7123 let snapshot = &*buffer.read(cx);
7124 let snippet = &snippet;
7125 snippet
7126 .tabstops
7127 .iter()
7128 .map(|tabstop| {
7129 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7130 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7131 });
7132 let mut tabstop_ranges = tabstop
7133 .ranges
7134 .iter()
7135 .flat_map(|tabstop_range| {
7136 let mut delta = 0_isize;
7137 insertion_ranges.iter().map(move |insertion_range| {
7138 let insertion_start = insertion_range.start as isize + delta;
7139 delta +=
7140 snippet.text.len() as isize - insertion_range.len() as isize;
7141
7142 let start = ((insertion_start + tabstop_range.start) as usize)
7143 .min(snapshot.len());
7144 let end = ((insertion_start + tabstop_range.end) as usize)
7145 .min(snapshot.len());
7146 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7147 })
7148 })
7149 .collect::<Vec<_>>();
7150 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7151
7152 Tabstop {
7153 is_end_tabstop,
7154 ranges: tabstop_ranges,
7155 choices: tabstop.choices.clone(),
7156 }
7157 })
7158 .collect::<Vec<_>>()
7159 });
7160 if let Some(tabstop) = tabstops.first() {
7161 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7162 s.select_ranges(tabstop.ranges.iter().cloned());
7163 });
7164
7165 if let Some(choices) = &tabstop.choices {
7166 if let Some(selection) = tabstop.ranges.first() {
7167 self.show_snippet_choices(choices, selection.clone(), cx)
7168 }
7169 }
7170
7171 // If we're already at the last tabstop and it's at the end of the snippet,
7172 // we're done, we don't need to keep the state around.
7173 if !tabstop.is_end_tabstop {
7174 let choices = tabstops
7175 .iter()
7176 .map(|tabstop| tabstop.choices.clone())
7177 .collect();
7178
7179 let ranges = tabstops
7180 .into_iter()
7181 .map(|tabstop| tabstop.ranges)
7182 .collect::<Vec<_>>();
7183
7184 self.snippet_stack.push(SnippetState {
7185 active_index: 0,
7186 ranges,
7187 choices,
7188 });
7189 }
7190
7191 // Check whether the just-entered snippet ends with an auto-closable bracket.
7192 if self.autoclose_regions.is_empty() {
7193 let snapshot = self.buffer.read(cx).snapshot(cx);
7194 for selection in &mut self.selections.all::<Point>(cx) {
7195 let selection_head = selection.head();
7196 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7197 continue;
7198 };
7199
7200 let mut bracket_pair = None;
7201 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7202 let prev_chars = snapshot
7203 .reversed_chars_at(selection_head)
7204 .collect::<String>();
7205 for (pair, enabled) in scope.brackets() {
7206 if enabled
7207 && pair.close
7208 && prev_chars.starts_with(pair.start.as_str())
7209 && next_chars.starts_with(pair.end.as_str())
7210 {
7211 bracket_pair = Some(pair.clone());
7212 break;
7213 }
7214 }
7215 if let Some(pair) = bracket_pair {
7216 let start = snapshot.anchor_after(selection_head);
7217 let end = snapshot.anchor_after(selection_head);
7218 self.autoclose_regions.push(AutocloseRegion {
7219 selection_id: selection.id,
7220 range: start..end,
7221 pair,
7222 });
7223 }
7224 }
7225 }
7226 }
7227 Ok(())
7228 }
7229
7230 pub fn move_to_next_snippet_tabstop(
7231 &mut self,
7232 window: &mut Window,
7233 cx: &mut Context<Self>,
7234 ) -> bool {
7235 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7236 }
7237
7238 pub fn move_to_prev_snippet_tabstop(
7239 &mut self,
7240 window: &mut Window,
7241 cx: &mut Context<Self>,
7242 ) -> bool {
7243 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7244 }
7245
7246 pub fn move_to_snippet_tabstop(
7247 &mut self,
7248 bias: Bias,
7249 window: &mut Window,
7250 cx: &mut Context<Self>,
7251 ) -> bool {
7252 if let Some(mut snippet) = self.snippet_stack.pop() {
7253 match bias {
7254 Bias::Left => {
7255 if snippet.active_index > 0 {
7256 snippet.active_index -= 1;
7257 } else {
7258 self.snippet_stack.push(snippet);
7259 return false;
7260 }
7261 }
7262 Bias::Right => {
7263 if snippet.active_index + 1 < snippet.ranges.len() {
7264 snippet.active_index += 1;
7265 } else {
7266 self.snippet_stack.push(snippet);
7267 return false;
7268 }
7269 }
7270 }
7271 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7272 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7273 s.select_anchor_ranges(current_ranges.iter().cloned())
7274 });
7275
7276 if let Some(choices) = &snippet.choices[snippet.active_index] {
7277 if let Some(selection) = current_ranges.first() {
7278 self.show_snippet_choices(&choices, selection.clone(), cx);
7279 }
7280 }
7281
7282 // If snippet state is not at the last tabstop, push it back on the stack
7283 if snippet.active_index + 1 < snippet.ranges.len() {
7284 self.snippet_stack.push(snippet);
7285 }
7286 return true;
7287 }
7288 }
7289
7290 false
7291 }
7292
7293 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7294 self.transact(window, cx, |this, window, cx| {
7295 this.select_all(&SelectAll, window, cx);
7296 this.insert("", window, cx);
7297 });
7298 }
7299
7300 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7301 self.transact(window, cx, |this, window, cx| {
7302 this.select_autoclose_pair(window, cx);
7303 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7304 if !this.linked_edit_ranges.is_empty() {
7305 let selections = this.selections.all::<MultiBufferPoint>(cx);
7306 let snapshot = this.buffer.read(cx).snapshot(cx);
7307
7308 for selection in selections.iter() {
7309 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7310 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7311 if selection_start.buffer_id != selection_end.buffer_id {
7312 continue;
7313 }
7314 if let Some(ranges) =
7315 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7316 {
7317 for (buffer, entries) in ranges {
7318 linked_ranges.entry(buffer).or_default().extend(entries);
7319 }
7320 }
7321 }
7322 }
7323
7324 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7325 if !this.selections.line_mode {
7326 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7327 for selection in &mut selections {
7328 if selection.is_empty() {
7329 let old_head = selection.head();
7330 let mut new_head =
7331 movement::left(&display_map, old_head.to_display_point(&display_map))
7332 .to_point(&display_map);
7333 if let Some((buffer, line_buffer_range)) = display_map
7334 .buffer_snapshot
7335 .buffer_line_for_row(MultiBufferRow(old_head.row))
7336 {
7337 let indent_size =
7338 buffer.indent_size_for_line(line_buffer_range.start.row);
7339 let indent_len = match indent_size.kind {
7340 IndentKind::Space => {
7341 buffer.settings_at(line_buffer_range.start, cx).tab_size
7342 }
7343 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7344 };
7345 if old_head.column <= indent_size.len && old_head.column > 0 {
7346 let indent_len = indent_len.get();
7347 new_head = cmp::min(
7348 new_head,
7349 MultiBufferPoint::new(
7350 old_head.row,
7351 ((old_head.column - 1) / indent_len) * indent_len,
7352 ),
7353 );
7354 }
7355 }
7356
7357 selection.set_head(new_head, SelectionGoal::None);
7358 }
7359 }
7360 }
7361
7362 this.signature_help_state.set_backspace_pressed(true);
7363 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7364 s.select(selections)
7365 });
7366 this.insert("", window, cx);
7367 let empty_str: Arc<str> = Arc::from("");
7368 for (buffer, edits) in linked_ranges {
7369 let snapshot = buffer.read(cx).snapshot();
7370 use text::ToPoint as TP;
7371
7372 let edits = edits
7373 .into_iter()
7374 .map(|range| {
7375 let end_point = TP::to_point(&range.end, &snapshot);
7376 let mut start_point = TP::to_point(&range.start, &snapshot);
7377
7378 if end_point == start_point {
7379 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7380 .saturating_sub(1);
7381 start_point =
7382 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7383 };
7384
7385 (start_point..end_point, empty_str.clone())
7386 })
7387 .sorted_by_key(|(range, _)| range.start)
7388 .collect::<Vec<_>>();
7389 buffer.update(cx, |this, cx| {
7390 this.edit(edits, None, cx);
7391 })
7392 }
7393 this.refresh_inline_completion(true, false, window, cx);
7394 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7395 });
7396 }
7397
7398 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7399 self.transact(window, cx, |this, window, cx| {
7400 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7401 let line_mode = s.line_mode;
7402 s.move_with(|map, selection| {
7403 if selection.is_empty() && !line_mode {
7404 let cursor = movement::right(map, selection.head());
7405 selection.end = cursor;
7406 selection.reversed = true;
7407 selection.goal = SelectionGoal::None;
7408 }
7409 })
7410 });
7411 this.insert("", window, cx);
7412 this.refresh_inline_completion(true, false, window, cx);
7413 });
7414 }
7415
7416 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7417 if self.move_to_prev_snippet_tabstop(window, cx) {
7418 return;
7419 }
7420
7421 self.outdent(&Outdent, window, cx);
7422 }
7423
7424 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7425 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7426 return;
7427 }
7428
7429 let mut selections = self.selections.all_adjusted(cx);
7430 let buffer = self.buffer.read(cx);
7431 let snapshot = buffer.snapshot(cx);
7432 let rows_iter = selections.iter().map(|s| s.head().row);
7433 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7434
7435 let mut edits = Vec::new();
7436 let mut prev_edited_row = 0;
7437 let mut row_delta = 0;
7438 for selection in &mut selections {
7439 if selection.start.row != prev_edited_row {
7440 row_delta = 0;
7441 }
7442 prev_edited_row = selection.end.row;
7443
7444 // If the selection is non-empty, then increase the indentation of the selected lines.
7445 if !selection.is_empty() {
7446 row_delta =
7447 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7448 continue;
7449 }
7450
7451 // If the selection is empty and the cursor is in the leading whitespace before the
7452 // suggested indentation, then auto-indent the line.
7453 let cursor = selection.head();
7454 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7455 if let Some(suggested_indent) =
7456 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7457 {
7458 if cursor.column < suggested_indent.len
7459 && cursor.column <= current_indent.len
7460 && current_indent.len <= suggested_indent.len
7461 {
7462 selection.start = Point::new(cursor.row, suggested_indent.len);
7463 selection.end = selection.start;
7464 if row_delta == 0 {
7465 edits.extend(Buffer::edit_for_indent_size_adjustment(
7466 cursor.row,
7467 current_indent,
7468 suggested_indent,
7469 ));
7470 row_delta = suggested_indent.len - current_indent.len;
7471 }
7472 continue;
7473 }
7474 }
7475
7476 // Otherwise, insert a hard or soft tab.
7477 let settings = buffer.language_settings_at(cursor, cx);
7478 let tab_size = if settings.hard_tabs {
7479 IndentSize::tab()
7480 } else {
7481 let tab_size = settings.tab_size.get();
7482 let char_column = snapshot
7483 .text_for_range(Point::new(cursor.row, 0)..cursor)
7484 .flat_map(str::chars)
7485 .count()
7486 + row_delta as usize;
7487 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7488 IndentSize::spaces(chars_to_next_tab_stop)
7489 };
7490 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7491 selection.end = selection.start;
7492 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7493 row_delta += tab_size.len;
7494 }
7495
7496 self.transact(window, cx, |this, window, cx| {
7497 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7498 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7499 s.select(selections)
7500 });
7501 this.refresh_inline_completion(true, false, window, cx);
7502 });
7503 }
7504
7505 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7506 if self.read_only(cx) {
7507 return;
7508 }
7509 let mut selections = self.selections.all::<Point>(cx);
7510 let mut prev_edited_row = 0;
7511 let mut row_delta = 0;
7512 let mut edits = Vec::new();
7513 let buffer = self.buffer.read(cx);
7514 let snapshot = buffer.snapshot(cx);
7515 for selection in &mut selections {
7516 if selection.start.row != prev_edited_row {
7517 row_delta = 0;
7518 }
7519 prev_edited_row = selection.end.row;
7520
7521 row_delta =
7522 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7523 }
7524
7525 self.transact(window, cx, |this, window, cx| {
7526 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7527 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7528 s.select(selections)
7529 });
7530 });
7531 }
7532
7533 fn indent_selection(
7534 buffer: &MultiBuffer,
7535 snapshot: &MultiBufferSnapshot,
7536 selection: &mut Selection<Point>,
7537 edits: &mut Vec<(Range<Point>, String)>,
7538 delta_for_start_row: u32,
7539 cx: &App,
7540 ) -> u32 {
7541 let settings = buffer.language_settings_at(selection.start, cx);
7542 let tab_size = settings.tab_size.get();
7543 let indent_kind = if settings.hard_tabs {
7544 IndentKind::Tab
7545 } else {
7546 IndentKind::Space
7547 };
7548 let mut start_row = selection.start.row;
7549 let mut end_row = selection.end.row + 1;
7550
7551 // If a selection ends at the beginning of a line, don't indent
7552 // that last line.
7553 if selection.end.column == 0 && selection.end.row > selection.start.row {
7554 end_row -= 1;
7555 }
7556
7557 // Avoid re-indenting a row that has already been indented by a
7558 // previous selection, but still update this selection's column
7559 // to reflect that indentation.
7560 if delta_for_start_row > 0 {
7561 start_row += 1;
7562 selection.start.column += delta_for_start_row;
7563 if selection.end.row == selection.start.row {
7564 selection.end.column += delta_for_start_row;
7565 }
7566 }
7567
7568 let mut delta_for_end_row = 0;
7569 let has_multiple_rows = start_row + 1 != end_row;
7570 for row in start_row..end_row {
7571 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7572 let indent_delta = match (current_indent.kind, indent_kind) {
7573 (IndentKind::Space, IndentKind::Space) => {
7574 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7575 IndentSize::spaces(columns_to_next_tab_stop)
7576 }
7577 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7578 (_, IndentKind::Tab) => IndentSize::tab(),
7579 };
7580
7581 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7582 0
7583 } else {
7584 selection.start.column
7585 };
7586 let row_start = Point::new(row, start);
7587 edits.push((
7588 row_start..row_start,
7589 indent_delta.chars().collect::<String>(),
7590 ));
7591
7592 // Update this selection's endpoints to reflect the indentation.
7593 if row == selection.start.row {
7594 selection.start.column += indent_delta.len;
7595 }
7596 if row == selection.end.row {
7597 selection.end.column += indent_delta.len;
7598 delta_for_end_row = indent_delta.len;
7599 }
7600 }
7601
7602 if selection.start.row == selection.end.row {
7603 delta_for_start_row + delta_for_end_row
7604 } else {
7605 delta_for_end_row
7606 }
7607 }
7608
7609 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7610 if self.read_only(cx) {
7611 return;
7612 }
7613 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7614 let selections = self.selections.all::<Point>(cx);
7615 let mut deletion_ranges = Vec::new();
7616 let mut last_outdent = None;
7617 {
7618 let buffer = self.buffer.read(cx);
7619 let snapshot = buffer.snapshot(cx);
7620 for selection in &selections {
7621 let settings = buffer.language_settings_at(selection.start, cx);
7622 let tab_size = settings.tab_size.get();
7623 let mut rows = selection.spanned_rows(false, &display_map);
7624
7625 // Avoid re-outdenting a row that has already been outdented by a
7626 // previous selection.
7627 if let Some(last_row) = last_outdent {
7628 if last_row == rows.start {
7629 rows.start = rows.start.next_row();
7630 }
7631 }
7632 let has_multiple_rows = rows.len() > 1;
7633 for row in rows.iter_rows() {
7634 let indent_size = snapshot.indent_size_for_line(row);
7635 if indent_size.len > 0 {
7636 let deletion_len = match indent_size.kind {
7637 IndentKind::Space => {
7638 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7639 if columns_to_prev_tab_stop == 0 {
7640 tab_size
7641 } else {
7642 columns_to_prev_tab_stop
7643 }
7644 }
7645 IndentKind::Tab => 1,
7646 };
7647 let start = if has_multiple_rows
7648 || deletion_len > selection.start.column
7649 || indent_size.len < selection.start.column
7650 {
7651 0
7652 } else {
7653 selection.start.column - deletion_len
7654 };
7655 deletion_ranges.push(
7656 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7657 );
7658 last_outdent = Some(row);
7659 }
7660 }
7661 }
7662 }
7663
7664 self.transact(window, cx, |this, window, cx| {
7665 this.buffer.update(cx, |buffer, cx| {
7666 let empty_str: Arc<str> = Arc::default();
7667 buffer.edit(
7668 deletion_ranges
7669 .into_iter()
7670 .map(|range| (range, empty_str.clone())),
7671 None,
7672 cx,
7673 );
7674 });
7675 let selections = this.selections.all::<usize>(cx);
7676 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7677 s.select(selections)
7678 });
7679 });
7680 }
7681
7682 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7683 if self.read_only(cx) {
7684 return;
7685 }
7686 let selections = self
7687 .selections
7688 .all::<usize>(cx)
7689 .into_iter()
7690 .map(|s| s.range());
7691
7692 self.transact(window, cx, |this, window, cx| {
7693 this.buffer.update(cx, |buffer, cx| {
7694 buffer.autoindent_ranges(selections, cx);
7695 });
7696 let selections = this.selections.all::<usize>(cx);
7697 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7698 s.select(selections)
7699 });
7700 });
7701 }
7702
7703 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7704 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7705 let selections = self.selections.all::<Point>(cx);
7706
7707 let mut new_cursors = Vec::new();
7708 let mut edit_ranges = Vec::new();
7709 let mut selections = selections.iter().peekable();
7710 while let Some(selection) = selections.next() {
7711 let mut rows = selection.spanned_rows(false, &display_map);
7712 let goal_display_column = selection.head().to_display_point(&display_map).column();
7713
7714 // Accumulate contiguous regions of rows that we want to delete.
7715 while let Some(next_selection) = selections.peek() {
7716 let next_rows = next_selection.spanned_rows(false, &display_map);
7717 if next_rows.start <= rows.end {
7718 rows.end = next_rows.end;
7719 selections.next().unwrap();
7720 } else {
7721 break;
7722 }
7723 }
7724
7725 let buffer = &display_map.buffer_snapshot;
7726 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7727 let edit_end;
7728 let cursor_buffer_row;
7729 if buffer.max_point().row >= rows.end.0 {
7730 // If there's a line after the range, delete the \n from the end of the row range
7731 // and position the cursor on the next line.
7732 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7733 cursor_buffer_row = rows.end;
7734 } else {
7735 // If there isn't a line after the range, delete the \n from the line before the
7736 // start of the row range and position the cursor there.
7737 edit_start = edit_start.saturating_sub(1);
7738 edit_end = buffer.len();
7739 cursor_buffer_row = rows.start.previous_row();
7740 }
7741
7742 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7743 *cursor.column_mut() =
7744 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7745
7746 new_cursors.push((
7747 selection.id,
7748 buffer.anchor_after(cursor.to_point(&display_map)),
7749 ));
7750 edit_ranges.push(edit_start..edit_end);
7751 }
7752
7753 self.transact(window, cx, |this, window, cx| {
7754 let buffer = this.buffer.update(cx, |buffer, cx| {
7755 let empty_str: Arc<str> = Arc::default();
7756 buffer.edit(
7757 edit_ranges
7758 .into_iter()
7759 .map(|range| (range, empty_str.clone())),
7760 None,
7761 cx,
7762 );
7763 buffer.snapshot(cx)
7764 });
7765 let new_selections = new_cursors
7766 .into_iter()
7767 .map(|(id, cursor)| {
7768 let cursor = cursor.to_point(&buffer);
7769 Selection {
7770 id,
7771 start: cursor,
7772 end: cursor,
7773 reversed: false,
7774 goal: SelectionGoal::None,
7775 }
7776 })
7777 .collect();
7778
7779 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7780 s.select(new_selections);
7781 });
7782 });
7783 }
7784
7785 pub fn join_lines_impl(
7786 &mut self,
7787 insert_whitespace: bool,
7788 window: &mut Window,
7789 cx: &mut Context<Self>,
7790 ) {
7791 if self.read_only(cx) {
7792 return;
7793 }
7794 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7795 for selection in self.selections.all::<Point>(cx) {
7796 let start = MultiBufferRow(selection.start.row);
7797 // Treat single line selections as if they include the next line. Otherwise this action
7798 // would do nothing for single line selections individual cursors.
7799 let end = if selection.start.row == selection.end.row {
7800 MultiBufferRow(selection.start.row + 1)
7801 } else {
7802 MultiBufferRow(selection.end.row)
7803 };
7804
7805 if let Some(last_row_range) = row_ranges.last_mut() {
7806 if start <= last_row_range.end {
7807 last_row_range.end = end;
7808 continue;
7809 }
7810 }
7811 row_ranges.push(start..end);
7812 }
7813
7814 let snapshot = self.buffer.read(cx).snapshot(cx);
7815 let mut cursor_positions = Vec::new();
7816 for row_range in &row_ranges {
7817 let anchor = snapshot.anchor_before(Point::new(
7818 row_range.end.previous_row().0,
7819 snapshot.line_len(row_range.end.previous_row()),
7820 ));
7821 cursor_positions.push(anchor..anchor);
7822 }
7823
7824 self.transact(window, cx, |this, window, cx| {
7825 for row_range in row_ranges.into_iter().rev() {
7826 for row in row_range.iter_rows().rev() {
7827 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7828 let next_line_row = row.next_row();
7829 let indent = snapshot.indent_size_for_line(next_line_row);
7830 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7831
7832 let replace =
7833 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7834 " "
7835 } else {
7836 ""
7837 };
7838
7839 this.buffer.update(cx, |buffer, cx| {
7840 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7841 });
7842 }
7843 }
7844
7845 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7846 s.select_anchor_ranges(cursor_positions)
7847 });
7848 });
7849 }
7850
7851 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7852 self.join_lines_impl(true, window, cx);
7853 }
7854
7855 pub fn sort_lines_case_sensitive(
7856 &mut self,
7857 _: &SortLinesCaseSensitive,
7858 window: &mut Window,
7859 cx: &mut Context<Self>,
7860 ) {
7861 self.manipulate_lines(window, cx, |lines| lines.sort())
7862 }
7863
7864 pub fn sort_lines_case_insensitive(
7865 &mut self,
7866 _: &SortLinesCaseInsensitive,
7867 window: &mut Window,
7868 cx: &mut Context<Self>,
7869 ) {
7870 self.manipulate_lines(window, cx, |lines| {
7871 lines.sort_by_key(|line| line.to_lowercase())
7872 })
7873 }
7874
7875 pub fn unique_lines_case_insensitive(
7876 &mut self,
7877 _: &UniqueLinesCaseInsensitive,
7878 window: &mut Window,
7879 cx: &mut Context<Self>,
7880 ) {
7881 self.manipulate_lines(window, cx, |lines| {
7882 let mut seen = HashSet::default();
7883 lines.retain(|line| seen.insert(line.to_lowercase()));
7884 })
7885 }
7886
7887 pub fn unique_lines_case_sensitive(
7888 &mut self,
7889 _: &UniqueLinesCaseSensitive,
7890 window: &mut Window,
7891 cx: &mut Context<Self>,
7892 ) {
7893 self.manipulate_lines(window, cx, |lines| {
7894 let mut seen = HashSet::default();
7895 lines.retain(|line| seen.insert(*line));
7896 })
7897 }
7898
7899 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7900 let Some(project) = self.project.clone() else {
7901 return;
7902 };
7903 self.reload(project, window, cx)
7904 .detach_and_notify_err(window, cx);
7905 }
7906
7907 pub fn restore_file(
7908 &mut self,
7909 _: &::git::RestoreFile,
7910 window: &mut Window,
7911 cx: &mut Context<Self>,
7912 ) {
7913 let mut buffer_ids = HashSet::default();
7914 let snapshot = self.buffer().read(cx).snapshot(cx);
7915 for selection in self.selections.all::<usize>(cx) {
7916 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7917 }
7918
7919 let buffer = self.buffer().read(cx);
7920 let ranges = buffer_ids
7921 .into_iter()
7922 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7923 .collect::<Vec<_>>();
7924
7925 self.restore_hunks_in_ranges(ranges, window, cx);
7926 }
7927
7928 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7929 let selections = self
7930 .selections
7931 .all(cx)
7932 .into_iter()
7933 .map(|s| s.range())
7934 .collect();
7935 self.restore_hunks_in_ranges(selections, window, cx);
7936 }
7937
7938 fn restore_hunks_in_ranges(
7939 &mut self,
7940 ranges: Vec<Range<Point>>,
7941 window: &mut Window,
7942 cx: &mut Context<Editor>,
7943 ) {
7944 let mut revert_changes = HashMap::default();
7945 let chunk_by = self
7946 .snapshot(window, cx)
7947 .hunks_for_ranges(ranges)
7948 .into_iter()
7949 .chunk_by(|hunk| hunk.buffer_id);
7950 for (buffer_id, hunks) in &chunk_by {
7951 let hunks = hunks.collect::<Vec<_>>();
7952 for hunk in &hunks {
7953 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7954 }
7955 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7956 }
7957 drop(chunk_by);
7958 if !revert_changes.is_empty() {
7959 self.transact(window, cx, |editor, window, cx| {
7960 editor.restore(revert_changes, window, cx);
7961 });
7962 }
7963 }
7964
7965 pub fn open_active_item_in_terminal(
7966 &mut self,
7967 _: &OpenInTerminal,
7968 window: &mut Window,
7969 cx: &mut Context<Self>,
7970 ) {
7971 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7972 let project_path = buffer.read(cx).project_path(cx)?;
7973 let project = self.project.as_ref()?.read(cx);
7974 let entry = project.entry_for_path(&project_path, cx)?;
7975 let parent = match &entry.canonical_path {
7976 Some(canonical_path) => canonical_path.to_path_buf(),
7977 None => project.absolute_path(&project_path, cx)?,
7978 }
7979 .parent()?
7980 .to_path_buf();
7981 Some(parent)
7982 }) {
7983 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7984 }
7985 }
7986
7987 pub fn prepare_restore_change(
7988 &self,
7989 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7990 hunk: &MultiBufferDiffHunk,
7991 cx: &mut App,
7992 ) -> Option<()> {
7993 if hunk.is_created_file() {
7994 return None;
7995 }
7996 let buffer = self.buffer.read(cx);
7997 let diff = buffer.diff_for(hunk.buffer_id)?;
7998 let buffer = buffer.buffer(hunk.buffer_id)?;
7999 let buffer = buffer.read(cx);
8000 let original_text = diff
8001 .read(cx)
8002 .base_text()
8003 .as_rope()
8004 .slice(hunk.diff_base_byte_range.clone());
8005 let buffer_snapshot = buffer.snapshot();
8006 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8007 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8008 probe
8009 .0
8010 .start
8011 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8012 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8013 }) {
8014 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8015 Some(())
8016 } else {
8017 None
8018 }
8019 }
8020
8021 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8022 self.manipulate_lines(window, cx, |lines| lines.reverse())
8023 }
8024
8025 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8026 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8027 }
8028
8029 fn manipulate_lines<Fn>(
8030 &mut self,
8031 window: &mut Window,
8032 cx: &mut Context<Self>,
8033 mut callback: Fn,
8034 ) where
8035 Fn: FnMut(&mut Vec<&str>),
8036 {
8037 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8038 let buffer = self.buffer.read(cx).snapshot(cx);
8039
8040 let mut edits = Vec::new();
8041
8042 let selections = self.selections.all::<Point>(cx);
8043 let mut selections = selections.iter().peekable();
8044 let mut contiguous_row_selections = Vec::new();
8045 let mut new_selections = Vec::new();
8046 let mut added_lines = 0;
8047 let mut removed_lines = 0;
8048
8049 while let Some(selection) = selections.next() {
8050 let (start_row, end_row) = consume_contiguous_rows(
8051 &mut contiguous_row_selections,
8052 selection,
8053 &display_map,
8054 &mut selections,
8055 );
8056
8057 let start_point = Point::new(start_row.0, 0);
8058 let end_point = Point::new(
8059 end_row.previous_row().0,
8060 buffer.line_len(end_row.previous_row()),
8061 );
8062 let text = buffer
8063 .text_for_range(start_point..end_point)
8064 .collect::<String>();
8065
8066 let mut lines = text.split('\n').collect_vec();
8067
8068 let lines_before = lines.len();
8069 callback(&mut lines);
8070 let lines_after = lines.len();
8071
8072 edits.push((start_point..end_point, lines.join("\n")));
8073
8074 // Selections must change based on added and removed line count
8075 let start_row =
8076 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8077 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8078 new_selections.push(Selection {
8079 id: selection.id,
8080 start: start_row,
8081 end: end_row,
8082 goal: SelectionGoal::None,
8083 reversed: selection.reversed,
8084 });
8085
8086 if lines_after > lines_before {
8087 added_lines += lines_after - lines_before;
8088 } else if lines_before > lines_after {
8089 removed_lines += lines_before - lines_after;
8090 }
8091 }
8092
8093 self.transact(window, cx, |this, window, cx| {
8094 let buffer = this.buffer.update(cx, |buffer, cx| {
8095 buffer.edit(edits, None, cx);
8096 buffer.snapshot(cx)
8097 });
8098
8099 // Recalculate offsets on newly edited buffer
8100 let new_selections = new_selections
8101 .iter()
8102 .map(|s| {
8103 let start_point = Point::new(s.start.0, 0);
8104 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8105 Selection {
8106 id: s.id,
8107 start: buffer.point_to_offset(start_point),
8108 end: buffer.point_to_offset(end_point),
8109 goal: s.goal,
8110 reversed: s.reversed,
8111 }
8112 })
8113 .collect();
8114
8115 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8116 s.select(new_selections);
8117 });
8118
8119 this.request_autoscroll(Autoscroll::fit(), cx);
8120 });
8121 }
8122
8123 pub fn convert_to_upper_case(
8124 &mut self,
8125 _: &ConvertToUpperCase,
8126 window: &mut Window,
8127 cx: &mut Context<Self>,
8128 ) {
8129 self.manipulate_text(window, cx, |text| text.to_uppercase())
8130 }
8131
8132 pub fn convert_to_lower_case(
8133 &mut self,
8134 _: &ConvertToLowerCase,
8135 window: &mut Window,
8136 cx: &mut Context<Self>,
8137 ) {
8138 self.manipulate_text(window, cx, |text| text.to_lowercase())
8139 }
8140
8141 pub fn convert_to_title_case(
8142 &mut self,
8143 _: &ConvertToTitleCase,
8144 window: &mut Window,
8145 cx: &mut Context<Self>,
8146 ) {
8147 self.manipulate_text(window, cx, |text| {
8148 text.split('\n')
8149 .map(|line| line.to_case(Case::Title))
8150 .join("\n")
8151 })
8152 }
8153
8154 pub fn convert_to_snake_case(
8155 &mut self,
8156 _: &ConvertToSnakeCase,
8157 window: &mut Window,
8158 cx: &mut Context<Self>,
8159 ) {
8160 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8161 }
8162
8163 pub fn convert_to_kebab_case(
8164 &mut self,
8165 _: &ConvertToKebabCase,
8166 window: &mut Window,
8167 cx: &mut Context<Self>,
8168 ) {
8169 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8170 }
8171
8172 pub fn convert_to_upper_camel_case(
8173 &mut self,
8174 _: &ConvertToUpperCamelCase,
8175 window: &mut Window,
8176 cx: &mut Context<Self>,
8177 ) {
8178 self.manipulate_text(window, cx, |text| {
8179 text.split('\n')
8180 .map(|line| line.to_case(Case::UpperCamel))
8181 .join("\n")
8182 })
8183 }
8184
8185 pub fn convert_to_lower_camel_case(
8186 &mut self,
8187 _: &ConvertToLowerCamelCase,
8188 window: &mut Window,
8189 cx: &mut Context<Self>,
8190 ) {
8191 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8192 }
8193
8194 pub fn convert_to_opposite_case(
8195 &mut self,
8196 _: &ConvertToOppositeCase,
8197 window: &mut Window,
8198 cx: &mut Context<Self>,
8199 ) {
8200 self.manipulate_text(window, cx, |text| {
8201 text.chars()
8202 .fold(String::with_capacity(text.len()), |mut t, c| {
8203 if c.is_uppercase() {
8204 t.extend(c.to_lowercase());
8205 } else {
8206 t.extend(c.to_uppercase());
8207 }
8208 t
8209 })
8210 })
8211 }
8212
8213 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8214 where
8215 Fn: FnMut(&str) -> String,
8216 {
8217 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8218 let buffer = self.buffer.read(cx).snapshot(cx);
8219
8220 let mut new_selections = Vec::new();
8221 let mut edits = Vec::new();
8222 let mut selection_adjustment = 0i32;
8223
8224 for selection in self.selections.all::<usize>(cx) {
8225 let selection_is_empty = selection.is_empty();
8226
8227 let (start, end) = if selection_is_empty {
8228 let word_range = movement::surrounding_word(
8229 &display_map,
8230 selection.start.to_display_point(&display_map),
8231 );
8232 let start = word_range.start.to_offset(&display_map, Bias::Left);
8233 let end = word_range.end.to_offset(&display_map, Bias::Left);
8234 (start, end)
8235 } else {
8236 (selection.start, selection.end)
8237 };
8238
8239 let text = buffer.text_for_range(start..end).collect::<String>();
8240 let old_length = text.len() as i32;
8241 let text = callback(&text);
8242
8243 new_selections.push(Selection {
8244 start: (start as i32 - selection_adjustment) as usize,
8245 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8246 goal: SelectionGoal::None,
8247 ..selection
8248 });
8249
8250 selection_adjustment += old_length - text.len() as i32;
8251
8252 edits.push((start..end, text));
8253 }
8254
8255 self.transact(window, cx, |this, window, cx| {
8256 this.buffer.update(cx, |buffer, cx| {
8257 buffer.edit(edits, None, cx);
8258 });
8259
8260 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8261 s.select(new_selections);
8262 });
8263
8264 this.request_autoscroll(Autoscroll::fit(), cx);
8265 });
8266 }
8267
8268 pub fn duplicate(
8269 &mut self,
8270 upwards: bool,
8271 whole_lines: bool,
8272 window: &mut Window,
8273 cx: &mut Context<Self>,
8274 ) {
8275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8276 let buffer = &display_map.buffer_snapshot;
8277 let selections = self.selections.all::<Point>(cx);
8278
8279 let mut edits = Vec::new();
8280 let mut selections_iter = selections.iter().peekable();
8281 while let Some(selection) = selections_iter.next() {
8282 let mut rows = selection.spanned_rows(false, &display_map);
8283 // duplicate line-wise
8284 if whole_lines || selection.start == selection.end {
8285 // Avoid duplicating the same lines twice.
8286 while let Some(next_selection) = selections_iter.peek() {
8287 let next_rows = next_selection.spanned_rows(false, &display_map);
8288 if next_rows.start < rows.end {
8289 rows.end = next_rows.end;
8290 selections_iter.next().unwrap();
8291 } else {
8292 break;
8293 }
8294 }
8295
8296 // Copy the text from the selected row region and splice it either at the start
8297 // or end of the region.
8298 let start = Point::new(rows.start.0, 0);
8299 let end = Point::new(
8300 rows.end.previous_row().0,
8301 buffer.line_len(rows.end.previous_row()),
8302 );
8303 let text = buffer
8304 .text_for_range(start..end)
8305 .chain(Some("\n"))
8306 .collect::<String>();
8307 let insert_location = if upwards {
8308 Point::new(rows.end.0, 0)
8309 } else {
8310 start
8311 };
8312 edits.push((insert_location..insert_location, text));
8313 } else {
8314 // duplicate character-wise
8315 let start = selection.start;
8316 let end = selection.end;
8317 let text = buffer.text_for_range(start..end).collect::<String>();
8318 edits.push((selection.end..selection.end, text));
8319 }
8320 }
8321
8322 self.transact(window, cx, |this, _, cx| {
8323 this.buffer.update(cx, |buffer, cx| {
8324 buffer.edit(edits, None, cx);
8325 });
8326
8327 this.request_autoscroll(Autoscroll::fit(), cx);
8328 });
8329 }
8330
8331 pub fn duplicate_line_up(
8332 &mut self,
8333 _: &DuplicateLineUp,
8334 window: &mut Window,
8335 cx: &mut Context<Self>,
8336 ) {
8337 self.duplicate(true, true, window, cx);
8338 }
8339
8340 pub fn duplicate_line_down(
8341 &mut self,
8342 _: &DuplicateLineDown,
8343 window: &mut Window,
8344 cx: &mut Context<Self>,
8345 ) {
8346 self.duplicate(false, true, window, cx);
8347 }
8348
8349 pub fn duplicate_selection(
8350 &mut self,
8351 _: &DuplicateSelection,
8352 window: &mut Window,
8353 cx: &mut Context<Self>,
8354 ) {
8355 self.duplicate(false, false, window, cx);
8356 }
8357
8358 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8359 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8360 let buffer = self.buffer.read(cx).snapshot(cx);
8361
8362 let mut edits = Vec::new();
8363 let mut unfold_ranges = Vec::new();
8364 let mut refold_creases = Vec::new();
8365
8366 let selections = self.selections.all::<Point>(cx);
8367 let mut selections = selections.iter().peekable();
8368 let mut contiguous_row_selections = Vec::new();
8369 let mut new_selections = Vec::new();
8370
8371 while let Some(selection) = selections.next() {
8372 // Find all the selections that span a contiguous row range
8373 let (start_row, end_row) = consume_contiguous_rows(
8374 &mut contiguous_row_selections,
8375 selection,
8376 &display_map,
8377 &mut selections,
8378 );
8379
8380 // Move the text spanned by the row range to be before the line preceding the row range
8381 if start_row.0 > 0 {
8382 let range_to_move = Point::new(
8383 start_row.previous_row().0,
8384 buffer.line_len(start_row.previous_row()),
8385 )
8386 ..Point::new(
8387 end_row.previous_row().0,
8388 buffer.line_len(end_row.previous_row()),
8389 );
8390 let insertion_point = display_map
8391 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8392 .0;
8393
8394 // Don't move lines across excerpts
8395 if buffer
8396 .excerpt_containing(insertion_point..range_to_move.end)
8397 .is_some()
8398 {
8399 let text = buffer
8400 .text_for_range(range_to_move.clone())
8401 .flat_map(|s| s.chars())
8402 .skip(1)
8403 .chain(['\n'])
8404 .collect::<String>();
8405
8406 edits.push((
8407 buffer.anchor_after(range_to_move.start)
8408 ..buffer.anchor_before(range_to_move.end),
8409 String::new(),
8410 ));
8411 let insertion_anchor = buffer.anchor_after(insertion_point);
8412 edits.push((insertion_anchor..insertion_anchor, text));
8413
8414 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8415
8416 // Move selections up
8417 new_selections.extend(contiguous_row_selections.drain(..).map(
8418 |mut selection| {
8419 selection.start.row -= row_delta;
8420 selection.end.row -= row_delta;
8421 selection
8422 },
8423 ));
8424
8425 // Move folds up
8426 unfold_ranges.push(range_to_move.clone());
8427 for fold in display_map.folds_in_range(
8428 buffer.anchor_before(range_to_move.start)
8429 ..buffer.anchor_after(range_to_move.end),
8430 ) {
8431 let mut start = fold.range.start.to_point(&buffer);
8432 let mut end = fold.range.end.to_point(&buffer);
8433 start.row -= row_delta;
8434 end.row -= row_delta;
8435 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8436 }
8437 }
8438 }
8439
8440 // If we didn't move line(s), preserve the existing selections
8441 new_selections.append(&mut contiguous_row_selections);
8442 }
8443
8444 self.transact(window, cx, |this, window, cx| {
8445 this.unfold_ranges(&unfold_ranges, true, true, cx);
8446 this.buffer.update(cx, |buffer, cx| {
8447 for (range, text) in edits {
8448 buffer.edit([(range, text)], None, cx);
8449 }
8450 });
8451 this.fold_creases(refold_creases, true, window, cx);
8452 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8453 s.select(new_selections);
8454 })
8455 });
8456 }
8457
8458 pub fn move_line_down(
8459 &mut self,
8460 _: &MoveLineDown,
8461 window: &mut Window,
8462 cx: &mut Context<Self>,
8463 ) {
8464 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8465 let buffer = self.buffer.read(cx).snapshot(cx);
8466
8467 let mut edits = Vec::new();
8468 let mut unfold_ranges = Vec::new();
8469 let mut refold_creases = Vec::new();
8470
8471 let selections = self.selections.all::<Point>(cx);
8472 let mut selections = selections.iter().peekable();
8473 let mut contiguous_row_selections = Vec::new();
8474 let mut new_selections = Vec::new();
8475
8476 while let Some(selection) = selections.next() {
8477 // Find all the selections that span a contiguous row range
8478 let (start_row, end_row) = consume_contiguous_rows(
8479 &mut contiguous_row_selections,
8480 selection,
8481 &display_map,
8482 &mut selections,
8483 );
8484
8485 // Move the text spanned by the row range to be after the last line of the row range
8486 if end_row.0 <= buffer.max_point().row {
8487 let range_to_move =
8488 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8489 let insertion_point = display_map
8490 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8491 .0;
8492
8493 // Don't move lines across excerpt boundaries
8494 if buffer
8495 .excerpt_containing(range_to_move.start..insertion_point)
8496 .is_some()
8497 {
8498 let mut text = String::from("\n");
8499 text.extend(buffer.text_for_range(range_to_move.clone()));
8500 text.pop(); // Drop trailing newline
8501 edits.push((
8502 buffer.anchor_after(range_to_move.start)
8503 ..buffer.anchor_before(range_to_move.end),
8504 String::new(),
8505 ));
8506 let insertion_anchor = buffer.anchor_after(insertion_point);
8507 edits.push((insertion_anchor..insertion_anchor, text));
8508
8509 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8510
8511 // Move selections down
8512 new_selections.extend(contiguous_row_selections.drain(..).map(
8513 |mut selection| {
8514 selection.start.row += row_delta;
8515 selection.end.row += row_delta;
8516 selection
8517 },
8518 ));
8519
8520 // Move folds down
8521 unfold_ranges.push(range_to_move.clone());
8522 for fold in display_map.folds_in_range(
8523 buffer.anchor_before(range_to_move.start)
8524 ..buffer.anchor_after(range_to_move.end),
8525 ) {
8526 let mut start = fold.range.start.to_point(&buffer);
8527 let mut end = fold.range.end.to_point(&buffer);
8528 start.row += row_delta;
8529 end.row += row_delta;
8530 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8531 }
8532 }
8533 }
8534
8535 // If we didn't move line(s), preserve the existing selections
8536 new_selections.append(&mut contiguous_row_selections);
8537 }
8538
8539 self.transact(window, cx, |this, window, cx| {
8540 this.unfold_ranges(&unfold_ranges, true, true, cx);
8541 this.buffer.update(cx, |buffer, cx| {
8542 for (range, text) in edits {
8543 buffer.edit([(range, text)], None, cx);
8544 }
8545 });
8546 this.fold_creases(refold_creases, true, window, cx);
8547 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8548 s.select(new_selections)
8549 });
8550 });
8551 }
8552
8553 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8554 let text_layout_details = &self.text_layout_details(window);
8555 self.transact(window, cx, |this, window, cx| {
8556 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8557 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8558 let line_mode = s.line_mode;
8559 s.move_with(|display_map, selection| {
8560 if !selection.is_empty() || line_mode {
8561 return;
8562 }
8563
8564 let mut head = selection.head();
8565 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8566 if head.column() == display_map.line_len(head.row()) {
8567 transpose_offset = display_map
8568 .buffer_snapshot
8569 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8570 }
8571
8572 if transpose_offset == 0 {
8573 return;
8574 }
8575
8576 *head.column_mut() += 1;
8577 head = display_map.clip_point(head, Bias::Right);
8578 let goal = SelectionGoal::HorizontalPosition(
8579 display_map
8580 .x_for_display_point(head, text_layout_details)
8581 .into(),
8582 );
8583 selection.collapse_to(head, goal);
8584
8585 let transpose_start = display_map
8586 .buffer_snapshot
8587 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8588 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8589 let transpose_end = display_map
8590 .buffer_snapshot
8591 .clip_offset(transpose_offset + 1, Bias::Right);
8592 if let Some(ch) =
8593 display_map.buffer_snapshot.chars_at(transpose_start).next()
8594 {
8595 edits.push((transpose_start..transpose_offset, String::new()));
8596 edits.push((transpose_end..transpose_end, ch.to_string()));
8597 }
8598 }
8599 });
8600 edits
8601 });
8602 this.buffer
8603 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8604 let selections = this.selections.all::<usize>(cx);
8605 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8606 s.select(selections);
8607 });
8608 });
8609 }
8610
8611 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8612 self.rewrap_impl(false, cx)
8613 }
8614
8615 pub fn rewrap_impl(&mut self, override_language_settings: bool, cx: &mut Context<Self>) {
8616 let buffer = self.buffer.read(cx).snapshot(cx);
8617 let selections = self.selections.all::<Point>(cx);
8618 let mut selections = selections.iter().peekable();
8619
8620 let mut edits = Vec::new();
8621 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8622
8623 while let Some(selection) = selections.next() {
8624 let mut start_row = selection.start.row;
8625 let mut end_row = selection.end.row;
8626
8627 // Skip selections that overlap with a range that has already been rewrapped.
8628 let selection_range = start_row..end_row;
8629 if rewrapped_row_ranges
8630 .iter()
8631 .any(|range| range.overlaps(&selection_range))
8632 {
8633 continue;
8634 }
8635
8636 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
8637
8638 // Since not all lines in the selection may be at the same indent
8639 // level, choose the indent size that is the most common between all
8640 // of the lines.
8641 //
8642 // If there is a tie, we use the deepest indent.
8643 let (indent_size, indent_end) = {
8644 let mut indent_size_occurrences = HashMap::default();
8645 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8646
8647 for row in start_row..=end_row {
8648 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8649 rows_by_indent_size.entry(indent).or_default().push(row);
8650 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8651 }
8652
8653 let indent_size = indent_size_occurrences
8654 .into_iter()
8655 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8656 .map(|(indent, _)| indent)
8657 .unwrap_or_default();
8658 let row = rows_by_indent_size[&indent_size][0];
8659 let indent_end = Point::new(row, indent_size.len);
8660
8661 (indent_size, indent_end)
8662 };
8663
8664 let mut line_prefix = indent_size.chars().collect::<String>();
8665
8666 let mut inside_comment = false;
8667 if let Some(comment_prefix) =
8668 buffer
8669 .language_scope_at(selection.head())
8670 .and_then(|language| {
8671 language
8672 .line_comment_prefixes()
8673 .iter()
8674 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8675 .cloned()
8676 })
8677 {
8678 line_prefix.push_str(&comment_prefix);
8679 inside_comment = true;
8680 }
8681
8682 let language_settings = buffer.language_settings_at(selection.head(), cx);
8683 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8684 RewrapBehavior::InComments => inside_comment,
8685 RewrapBehavior::InSelections => !selection.is_empty(),
8686 RewrapBehavior::Anywhere => true,
8687 };
8688
8689 let should_rewrap = override_language_settings
8690 || allow_rewrap_based_on_language
8691 || self.hard_wrap.is_some();
8692 if !should_rewrap {
8693 continue;
8694 }
8695
8696 if selection.is_empty() {
8697 'expand_upwards: while start_row > 0 {
8698 let prev_row = start_row - 1;
8699 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8700 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8701 {
8702 start_row = prev_row;
8703 } else {
8704 break 'expand_upwards;
8705 }
8706 }
8707
8708 'expand_downwards: while end_row < buffer.max_point().row {
8709 let next_row = end_row + 1;
8710 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8711 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8712 {
8713 end_row = next_row;
8714 } else {
8715 break 'expand_downwards;
8716 }
8717 }
8718 }
8719
8720 let start = Point::new(start_row, 0);
8721 let start_offset = start.to_offset(&buffer);
8722 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8723 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8724 let Some(lines_without_prefixes) = selection_text
8725 .lines()
8726 .map(|line| {
8727 line.strip_prefix(&line_prefix)
8728 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8729 .ok_or_else(|| {
8730 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8731 })
8732 })
8733 .collect::<Result<Vec<_>, _>>()
8734 .log_err()
8735 else {
8736 continue;
8737 };
8738
8739 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
8740 buffer
8741 .language_settings_at(Point::new(start_row, 0), cx)
8742 .preferred_line_length as usize
8743 });
8744 let wrapped_text = wrap_with_prefix(
8745 line_prefix,
8746 lines_without_prefixes.join(" "),
8747 wrap_column,
8748 tab_size,
8749 );
8750
8751 // TODO: should always use char-based diff while still supporting cursor behavior that
8752 // matches vim.
8753 let mut diff_options = DiffOptions::default();
8754 if override_language_settings {
8755 diff_options.max_word_diff_len = 0;
8756 diff_options.max_word_diff_line_count = 0;
8757 } else {
8758 diff_options.max_word_diff_len = usize::MAX;
8759 diff_options.max_word_diff_line_count = usize::MAX;
8760 }
8761
8762 for (old_range, new_text) in
8763 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8764 {
8765 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8766 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8767 edits.push((edit_start..edit_end, new_text));
8768 }
8769
8770 rewrapped_row_ranges.push(start_row..=end_row);
8771 }
8772
8773 self.buffer
8774 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8775 }
8776
8777 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8778 let mut text = String::new();
8779 let buffer = self.buffer.read(cx).snapshot(cx);
8780 let mut selections = self.selections.all::<Point>(cx);
8781 let mut clipboard_selections = Vec::with_capacity(selections.len());
8782 {
8783 let max_point = buffer.max_point();
8784 let mut is_first = true;
8785 for selection in &mut selections {
8786 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8787 if is_entire_line {
8788 selection.start = Point::new(selection.start.row, 0);
8789 if !selection.is_empty() && selection.end.column == 0 {
8790 selection.end = cmp::min(max_point, selection.end);
8791 } else {
8792 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8793 }
8794 selection.goal = SelectionGoal::None;
8795 }
8796 if is_first {
8797 is_first = false;
8798 } else {
8799 text += "\n";
8800 }
8801 let mut len = 0;
8802 for chunk in buffer.text_for_range(selection.start..selection.end) {
8803 text.push_str(chunk);
8804 len += chunk.len();
8805 }
8806 clipboard_selections.push(ClipboardSelection {
8807 len,
8808 is_entire_line,
8809 first_line_indent: buffer
8810 .indent_size_for_line(MultiBufferRow(selection.start.row))
8811 .len,
8812 });
8813 }
8814 }
8815
8816 self.transact(window, cx, |this, window, cx| {
8817 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8818 s.select(selections);
8819 });
8820 this.insert("", window, cx);
8821 });
8822 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8823 }
8824
8825 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8826 let item = self.cut_common(window, cx);
8827 cx.write_to_clipboard(item);
8828 }
8829
8830 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8831 self.change_selections(None, window, cx, |s| {
8832 s.move_with(|snapshot, sel| {
8833 if sel.is_empty() {
8834 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8835 }
8836 });
8837 });
8838 let item = self.cut_common(window, cx);
8839 cx.set_global(KillRing(item))
8840 }
8841
8842 pub fn kill_ring_yank(
8843 &mut self,
8844 _: &KillRingYank,
8845 window: &mut Window,
8846 cx: &mut Context<Self>,
8847 ) {
8848 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8849 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8850 (kill_ring.text().to_string(), kill_ring.metadata_json())
8851 } else {
8852 return;
8853 }
8854 } else {
8855 return;
8856 };
8857 self.do_paste(&text, metadata, false, window, cx);
8858 }
8859
8860 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8861 let selections = self.selections.all::<Point>(cx);
8862 let buffer = self.buffer.read(cx).read(cx);
8863 let mut text = String::new();
8864
8865 let mut clipboard_selections = Vec::with_capacity(selections.len());
8866 {
8867 let max_point = buffer.max_point();
8868 let mut is_first = true;
8869 for selection in selections.iter() {
8870 let mut start = selection.start;
8871 let mut end = selection.end;
8872 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8873 if is_entire_line {
8874 start = Point::new(start.row, 0);
8875 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8876 }
8877 if is_first {
8878 is_first = false;
8879 } else {
8880 text += "\n";
8881 }
8882 let mut len = 0;
8883 for chunk in buffer.text_for_range(start..end) {
8884 text.push_str(chunk);
8885 len += chunk.len();
8886 }
8887 clipboard_selections.push(ClipboardSelection {
8888 len,
8889 is_entire_line,
8890 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8891 });
8892 }
8893 }
8894
8895 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8896 text,
8897 clipboard_selections,
8898 ));
8899 }
8900
8901 pub fn do_paste(
8902 &mut self,
8903 text: &String,
8904 clipboard_selections: Option<Vec<ClipboardSelection>>,
8905 handle_entire_lines: bool,
8906 window: &mut Window,
8907 cx: &mut Context<Self>,
8908 ) {
8909 if self.read_only(cx) {
8910 return;
8911 }
8912
8913 let clipboard_text = Cow::Borrowed(text);
8914
8915 self.transact(window, cx, |this, window, cx| {
8916 if let Some(mut clipboard_selections) = clipboard_selections {
8917 let old_selections = this.selections.all::<usize>(cx);
8918 let all_selections_were_entire_line =
8919 clipboard_selections.iter().all(|s| s.is_entire_line);
8920 let first_selection_indent_column =
8921 clipboard_selections.first().map(|s| s.first_line_indent);
8922 if clipboard_selections.len() != old_selections.len() {
8923 clipboard_selections.drain(..);
8924 }
8925 let cursor_offset = this.selections.last::<usize>(cx).head();
8926 let mut auto_indent_on_paste = true;
8927
8928 this.buffer.update(cx, |buffer, cx| {
8929 let snapshot = buffer.read(cx);
8930 auto_indent_on_paste = snapshot
8931 .language_settings_at(cursor_offset, cx)
8932 .auto_indent_on_paste;
8933
8934 let mut start_offset = 0;
8935 let mut edits = Vec::new();
8936 let mut original_indent_columns = Vec::new();
8937 for (ix, selection) in old_selections.iter().enumerate() {
8938 let to_insert;
8939 let entire_line;
8940 let original_indent_column;
8941 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8942 let end_offset = start_offset + clipboard_selection.len;
8943 to_insert = &clipboard_text[start_offset..end_offset];
8944 entire_line = clipboard_selection.is_entire_line;
8945 start_offset = end_offset + 1;
8946 original_indent_column = Some(clipboard_selection.first_line_indent);
8947 } else {
8948 to_insert = clipboard_text.as_str();
8949 entire_line = all_selections_were_entire_line;
8950 original_indent_column = first_selection_indent_column
8951 }
8952
8953 // If the corresponding selection was empty when this slice of the
8954 // clipboard text was written, then the entire line containing the
8955 // selection was copied. If this selection is also currently empty,
8956 // then paste the line before the current line of the buffer.
8957 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8958 let column = selection.start.to_point(&snapshot).column as usize;
8959 let line_start = selection.start - column;
8960 line_start..line_start
8961 } else {
8962 selection.range()
8963 };
8964
8965 edits.push((range, to_insert));
8966 original_indent_columns.push(original_indent_column);
8967 }
8968 drop(snapshot);
8969
8970 buffer.edit(
8971 edits,
8972 if auto_indent_on_paste {
8973 Some(AutoindentMode::Block {
8974 original_indent_columns,
8975 })
8976 } else {
8977 None
8978 },
8979 cx,
8980 );
8981 });
8982
8983 let selections = this.selections.all::<usize>(cx);
8984 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8985 s.select(selections)
8986 });
8987 } else {
8988 this.insert(&clipboard_text, window, cx);
8989 }
8990 });
8991 }
8992
8993 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8994 if let Some(item) = cx.read_from_clipboard() {
8995 let entries = item.entries();
8996
8997 match entries.first() {
8998 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8999 // of all the pasted entries.
9000 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
9001 .do_paste(
9002 clipboard_string.text(),
9003 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9004 true,
9005 window,
9006 cx,
9007 ),
9008 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9009 }
9010 }
9011 }
9012
9013 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9014 if self.read_only(cx) {
9015 return;
9016 }
9017
9018 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9019 if let Some((selections, _)) =
9020 self.selection_history.transaction(transaction_id).cloned()
9021 {
9022 self.change_selections(None, window, cx, |s| {
9023 s.select_anchors(selections.to_vec());
9024 });
9025 } else {
9026 log::error!(
9027 "No entry in selection_history found for undo. \
9028 This may correspond to a bug where undo does not update the selection. \
9029 If this is occurring, please add details to \
9030 https://github.com/zed-industries/zed/issues/22692"
9031 );
9032 }
9033 self.request_autoscroll(Autoscroll::fit(), cx);
9034 self.unmark_text(window, cx);
9035 self.refresh_inline_completion(true, false, window, cx);
9036 cx.emit(EditorEvent::Edited { transaction_id });
9037 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9038 }
9039 }
9040
9041 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9042 if self.read_only(cx) {
9043 return;
9044 }
9045
9046 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9047 if let Some((_, Some(selections))) =
9048 self.selection_history.transaction(transaction_id).cloned()
9049 {
9050 self.change_selections(None, window, cx, |s| {
9051 s.select_anchors(selections.to_vec());
9052 });
9053 } else {
9054 log::error!(
9055 "No entry in selection_history found for redo. \
9056 This may correspond to a bug where undo does not update the selection. \
9057 If this is occurring, please add details to \
9058 https://github.com/zed-industries/zed/issues/22692"
9059 );
9060 }
9061 self.request_autoscroll(Autoscroll::fit(), cx);
9062 self.unmark_text(window, cx);
9063 self.refresh_inline_completion(true, false, window, cx);
9064 cx.emit(EditorEvent::Edited { transaction_id });
9065 }
9066 }
9067
9068 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9069 self.buffer
9070 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9071 }
9072
9073 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9074 self.buffer
9075 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9076 }
9077
9078 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9079 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9080 let line_mode = s.line_mode;
9081 s.move_with(|map, selection| {
9082 let cursor = if selection.is_empty() && !line_mode {
9083 movement::left(map, selection.start)
9084 } else {
9085 selection.start
9086 };
9087 selection.collapse_to(cursor, SelectionGoal::None);
9088 });
9089 })
9090 }
9091
9092 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9093 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9094 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9095 })
9096 }
9097
9098 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9099 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9100 let line_mode = s.line_mode;
9101 s.move_with(|map, selection| {
9102 let cursor = if selection.is_empty() && !line_mode {
9103 movement::right(map, selection.end)
9104 } else {
9105 selection.end
9106 };
9107 selection.collapse_to(cursor, SelectionGoal::None)
9108 });
9109 })
9110 }
9111
9112 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9113 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9114 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9115 })
9116 }
9117
9118 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9119 if self.take_rename(true, window, cx).is_some() {
9120 return;
9121 }
9122
9123 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9124 cx.propagate();
9125 return;
9126 }
9127
9128 let text_layout_details = &self.text_layout_details(window);
9129 let selection_count = self.selections.count();
9130 let first_selection = self.selections.first_anchor();
9131
9132 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9133 let line_mode = s.line_mode;
9134 s.move_with(|map, selection| {
9135 if !selection.is_empty() && !line_mode {
9136 selection.goal = SelectionGoal::None;
9137 }
9138 let (cursor, goal) = movement::up(
9139 map,
9140 selection.start,
9141 selection.goal,
9142 false,
9143 text_layout_details,
9144 );
9145 selection.collapse_to(cursor, goal);
9146 });
9147 });
9148
9149 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9150 {
9151 cx.propagate();
9152 }
9153 }
9154
9155 pub fn move_up_by_lines(
9156 &mut self,
9157 action: &MoveUpByLines,
9158 window: &mut Window,
9159 cx: &mut Context<Self>,
9160 ) {
9161 if self.take_rename(true, window, cx).is_some() {
9162 return;
9163 }
9164
9165 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9166 cx.propagate();
9167 return;
9168 }
9169
9170 let text_layout_details = &self.text_layout_details(window);
9171
9172 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9173 let line_mode = s.line_mode;
9174 s.move_with(|map, selection| {
9175 if !selection.is_empty() && !line_mode {
9176 selection.goal = SelectionGoal::None;
9177 }
9178 let (cursor, goal) = movement::up_by_rows(
9179 map,
9180 selection.start,
9181 action.lines,
9182 selection.goal,
9183 false,
9184 text_layout_details,
9185 );
9186 selection.collapse_to(cursor, goal);
9187 });
9188 })
9189 }
9190
9191 pub fn move_down_by_lines(
9192 &mut self,
9193 action: &MoveDownByLines,
9194 window: &mut Window,
9195 cx: &mut Context<Self>,
9196 ) {
9197 if self.take_rename(true, window, cx).is_some() {
9198 return;
9199 }
9200
9201 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9202 cx.propagate();
9203 return;
9204 }
9205
9206 let text_layout_details = &self.text_layout_details(window);
9207
9208 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9209 let line_mode = s.line_mode;
9210 s.move_with(|map, selection| {
9211 if !selection.is_empty() && !line_mode {
9212 selection.goal = SelectionGoal::None;
9213 }
9214 let (cursor, goal) = movement::down_by_rows(
9215 map,
9216 selection.start,
9217 action.lines,
9218 selection.goal,
9219 false,
9220 text_layout_details,
9221 );
9222 selection.collapse_to(cursor, goal);
9223 });
9224 })
9225 }
9226
9227 pub fn select_down_by_lines(
9228 &mut self,
9229 action: &SelectDownByLines,
9230 window: &mut Window,
9231 cx: &mut Context<Self>,
9232 ) {
9233 let text_layout_details = &self.text_layout_details(window);
9234 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9235 s.move_heads_with(|map, head, goal| {
9236 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9237 })
9238 })
9239 }
9240
9241 pub fn select_up_by_lines(
9242 &mut self,
9243 action: &SelectUpByLines,
9244 window: &mut Window,
9245 cx: &mut Context<Self>,
9246 ) {
9247 let text_layout_details = &self.text_layout_details(window);
9248 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9249 s.move_heads_with(|map, head, goal| {
9250 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9251 })
9252 })
9253 }
9254
9255 pub fn select_page_up(
9256 &mut self,
9257 _: &SelectPageUp,
9258 window: &mut Window,
9259 cx: &mut Context<Self>,
9260 ) {
9261 let Some(row_count) = self.visible_row_count() else {
9262 return;
9263 };
9264
9265 let text_layout_details = &self.text_layout_details(window);
9266
9267 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9268 s.move_heads_with(|map, head, goal| {
9269 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9270 })
9271 })
9272 }
9273
9274 pub fn move_page_up(
9275 &mut self,
9276 action: &MovePageUp,
9277 window: &mut Window,
9278 cx: &mut Context<Self>,
9279 ) {
9280 if self.take_rename(true, window, cx).is_some() {
9281 return;
9282 }
9283
9284 if self
9285 .context_menu
9286 .borrow_mut()
9287 .as_mut()
9288 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9289 .unwrap_or(false)
9290 {
9291 return;
9292 }
9293
9294 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9295 cx.propagate();
9296 return;
9297 }
9298
9299 let Some(row_count) = self.visible_row_count() else {
9300 return;
9301 };
9302
9303 let autoscroll = if action.center_cursor {
9304 Autoscroll::center()
9305 } else {
9306 Autoscroll::fit()
9307 };
9308
9309 let text_layout_details = &self.text_layout_details(window);
9310
9311 self.change_selections(Some(autoscroll), window, cx, |s| {
9312 let line_mode = s.line_mode;
9313 s.move_with(|map, selection| {
9314 if !selection.is_empty() && !line_mode {
9315 selection.goal = SelectionGoal::None;
9316 }
9317 let (cursor, goal) = movement::up_by_rows(
9318 map,
9319 selection.end,
9320 row_count,
9321 selection.goal,
9322 false,
9323 text_layout_details,
9324 );
9325 selection.collapse_to(cursor, goal);
9326 });
9327 });
9328 }
9329
9330 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9331 let text_layout_details = &self.text_layout_details(window);
9332 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9333 s.move_heads_with(|map, head, goal| {
9334 movement::up(map, head, goal, false, text_layout_details)
9335 })
9336 })
9337 }
9338
9339 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9340 self.take_rename(true, window, cx);
9341
9342 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9343 cx.propagate();
9344 return;
9345 }
9346
9347 let text_layout_details = &self.text_layout_details(window);
9348 let selection_count = self.selections.count();
9349 let first_selection = self.selections.first_anchor();
9350
9351 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9352 let line_mode = s.line_mode;
9353 s.move_with(|map, selection| {
9354 if !selection.is_empty() && !line_mode {
9355 selection.goal = SelectionGoal::None;
9356 }
9357 let (cursor, goal) = movement::down(
9358 map,
9359 selection.end,
9360 selection.goal,
9361 false,
9362 text_layout_details,
9363 );
9364 selection.collapse_to(cursor, goal);
9365 });
9366 });
9367
9368 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9369 {
9370 cx.propagate();
9371 }
9372 }
9373
9374 pub fn select_page_down(
9375 &mut self,
9376 _: &SelectPageDown,
9377 window: &mut Window,
9378 cx: &mut Context<Self>,
9379 ) {
9380 let Some(row_count) = self.visible_row_count() else {
9381 return;
9382 };
9383
9384 let text_layout_details = &self.text_layout_details(window);
9385
9386 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9387 s.move_heads_with(|map, head, goal| {
9388 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9389 })
9390 })
9391 }
9392
9393 pub fn move_page_down(
9394 &mut self,
9395 action: &MovePageDown,
9396 window: &mut Window,
9397 cx: &mut Context<Self>,
9398 ) {
9399 if self.take_rename(true, window, cx).is_some() {
9400 return;
9401 }
9402
9403 if self
9404 .context_menu
9405 .borrow_mut()
9406 .as_mut()
9407 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9408 .unwrap_or(false)
9409 {
9410 return;
9411 }
9412
9413 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9414 cx.propagate();
9415 return;
9416 }
9417
9418 let Some(row_count) = self.visible_row_count() else {
9419 return;
9420 };
9421
9422 let autoscroll = if action.center_cursor {
9423 Autoscroll::center()
9424 } else {
9425 Autoscroll::fit()
9426 };
9427
9428 let text_layout_details = &self.text_layout_details(window);
9429 self.change_selections(Some(autoscroll), window, cx, |s| {
9430 let line_mode = s.line_mode;
9431 s.move_with(|map, selection| {
9432 if !selection.is_empty() && !line_mode {
9433 selection.goal = SelectionGoal::None;
9434 }
9435 let (cursor, goal) = movement::down_by_rows(
9436 map,
9437 selection.end,
9438 row_count,
9439 selection.goal,
9440 false,
9441 text_layout_details,
9442 );
9443 selection.collapse_to(cursor, goal);
9444 });
9445 });
9446 }
9447
9448 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9449 let text_layout_details = &self.text_layout_details(window);
9450 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9451 s.move_heads_with(|map, head, goal| {
9452 movement::down(map, head, goal, false, text_layout_details)
9453 })
9454 });
9455 }
9456
9457 pub fn context_menu_first(
9458 &mut self,
9459 _: &ContextMenuFirst,
9460 _window: &mut Window,
9461 cx: &mut Context<Self>,
9462 ) {
9463 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9464 context_menu.select_first(self.completion_provider.as_deref(), cx);
9465 }
9466 }
9467
9468 pub fn context_menu_prev(
9469 &mut self,
9470 _: &ContextMenuPrevious,
9471 _window: &mut Window,
9472 cx: &mut Context<Self>,
9473 ) {
9474 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9475 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9476 }
9477 }
9478
9479 pub fn context_menu_next(
9480 &mut self,
9481 _: &ContextMenuNext,
9482 _window: &mut Window,
9483 cx: &mut Context<Self>,
9484 ) {
9485 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9486 context_menu.select_next(self.completion_provider.as_deref(), cx);
9487 }
9488 }
9489
9490 pub fn context_menu_last(
9491 &mut self,
9492 _: &ContextMenuLast,
9493 _window: &mut Window,
9494 cx: &mut Context<Self>,
9495 ) {
9496 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9497 context_menu.select_last(self.completion_provider.as_deref(), cx);
9498 }
9499 }
9500
9501 pub fn move_to_previous_word_start(
9502 &mut self,
9503 _: &MoveToPreviousWordStart,
9504 window: &mut Window,
9505 cx: &mut Context<Self>,
9506 ) {
9507 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9508 s.move_cursors_with(|map, head, _| {
9509 (
9510 movement::previous_word_start(map, head),
9511 SelectionGoal::None,
9512 )
9513 });
9514 })
9515 }
9516
9517 pub fn move_to_previous_subword_start(
9518 &mut self,
9519 _: &MoveToPreviousSubwordStart,
9520 window: &mut Window,
9521 cx: &mut Context<Self>,
9522 ) {
9523 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9524 s.move_cursors_with(|map, head, _| {
9525 (
9526 movement::previous_subword_start(map, head),
9527 SelectionGoal::None,
9528 )
9529 });
9530 })
9531 }
9532
9533 pub fn select_to_previous_word_start(
9534 &mut self,
9535 _: &SelectToPreviousWordStart,
9536 window: &mut Window,
9537 cx: &mut Context<Self>,
9538 ) {
9539 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9540 s.move_heads_with(|map, head, _| {
9541 (
9542 movement::previous_word_start(map, head),
9543 SelectionGoal::None,
9544 )
9545 });
9546 })
9547 }
9548
9549 pub fn select_to_previous_subword_start(
9550 &mut self,
9551 _: &SelectToPreviousSubwordStart,
9552 window: &mut Window,
9553 cx: &mut Context<Self>,
9554 ) {
9555 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9556 s.move_heads_with(|map, head, _| {
9557 (
9558 movement::previous_subword_start(map, head),
9559 SelectionGoal::None,
9560 )
9561 });
9562 })
9563 }
9564
9565 pub fn delete_to_previous_word_start(
9566 &mut self,
9567 action: &DeleteToPreviousWordStart,
9568 window: &mut Window,
9569 cx: &mut Context<Self>,
9570 ) {
9571 self.transact(window, cx, |this, window, cx| {
9572 this.select_autoclose_pair(window, cx);
9573 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9574 let line_mode = s.line_mode;
9575 s.move_with(|map, selection| {
9576 if selection.is_empty() && !line_mode {
9577 let cursor = if action.ignore_newlines {
9578 movement::previous_word_start(map, selection.head())
9579 } else {
9580 movement::previous_word_start_or_newline(map, selection.head())
9581 };
9582 selection.set_head(cursor, SelectionGoal::None);
9583 }
9584 });
9585 });
9586 this.insert("", window, cx);
9587 });
9588 }
9589
9590 pub fn delete_to_previous_subword_start(
9591 &mut self,
9592 _: &DeleteToPreviousSubwordStart,
9593 window: &mut Window,
9594 cx: &mut Context<Self>,
9595 ) {
9596 self.transact(window, cx, |this, window, cx| {
9597 this.select_autoclose_pair(window, cx);
9598 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9599 let line_mode = s.line_mode;
9600 s.move_with(|map, selection| {
9601 if selection.is_empty() && !line_mode {
9602 let cursor = movement::previous_subword_start(map, selection.head());
9603 selection.set_head(cursor, SelectionGoal::None);
9604 }
9605 });
9606 });
9607 this.insert("", window, cx);
9608 });
9609 }
9610
9611 pub fn move_to_next_word_end(
9612 &mut self,
9613 _: &MoveToNextWordEnd,
9614 window: &mut Window,
9615 cx: &mut Context<Self>,
9616 ) {
9617 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9618 s.move_cursors_with(|map, head, _| {
9619 (movement::next_word_end(map, head), SelectionGoal::None)
9620 });
9621 })
9622 }
9623
9624 pub fn move_to_next_subword_end(
9625 &mut self,
9626 _: &MoveToNextSubwordEnd,
9627 window: &mut Window,
9628 cx: &mut Context<Self>,
9629 ) {
9630 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9631 s.move_cursors_with(|map, head, _| {
9632 (movement::next_subword_end(map, head), SelectionGoal::None)
9633 });
9634 })
9635 }
9636
9637 pub fn select_to_next_word_end(
9638 &mut self,
9639 _: &SelectToNextWordEnd,
9640 window: &mut Window,
9641 cx: &mut Context<Self>,
9642 ) {
9643 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9644 s.move_heads_with(|map, head, _| {
9645 (movement::next_word_end(map, head), SelectionGoal::None)
9646 });
9647 })
9648 }
9649
9650 pub fn select_to_next_subword_end(
9651 &mut self,
9652 _: &SelectToNextSubwordEnd,
9653 window: &mut Window,
9654 cx: &mut Context<Self>,
9655 ) {
9656 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9657 s.move_heads_with(|map, head, _| {
9658 (movement::next_subword_end(map, head), SelectionGoal::None)
9659 });
9660 })
9661 }
9662
9663 pub fn delete_to_next_word_end(
9664 &mut self,
9665 action: &DeleteToNextWordEnd,
9666 window: &mut Window,
9667 cx: &mut Context<Self>,
9668 ) {
9669 self.transact(window, cx, |this, window, cx| {
9670 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9671 let line_mode = s.line_mode;
9672 s.move_with(|map, selection| {
9673 if selection.is_empty() && !line_mode {
9674 let cursor = if action.ignore_newlines {
9675 movement::next_word_end(map, selection.head())
9676 } else {
9677 movement::next_word_end_or_newline(map, selection.head())
9678 };
9679 selection.set_head(cursor, SelectionGoal::None);
9680 }
9681 });
9682 });
9683 this.insert("", window, cx);
9684 });
9685 }
9686
9687 pub fn delete_to_next_subword_end(
9688 &mut self,
9689 _: &DeleteToNextSubwordEnd,
9690 window: &mut Window,
9691 cx: &mut Context<Self>,
9692 ) {
9693 self.transact(window, cx, |this, window, cx| {
9694 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9695 s.move_with(|map, selection| {
9696 if selection.is_empty() {
9697 let cursor = movement::next_subword_end(map, selection.head());
9698 selection.set_head(cursor, SelectionGoal::None);
9699 }
9700 });
9701 });
9702 this.insert("", window, cx);
9703 });
9704 }
9705
9706 pub fn move_to_beginning_of_line(
9707 &mut self,
9708 action: &MoveToBeginningOfLine,
9709 window: &mut Window,
9710 cx: &mut Context<Self>,
9711 ) {
9712 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9713 s.move_cursors_with(|map, head, _| {
9714 (
9715 movement::indented_line_beginning(
9716 map,
9717 head,
9718 action.stop_at_soft_wraps,
9719 action.stop_at_indent,
9720 ),
9721 SelectionGoal::None,
9722 )
9723 });
9724 })
9725 }
9726
9727 pub fn select_to_beginning_of_line(
9728 &mut self,
9729 action: &SelectToBeginningOfLine,
9730 window: &mut Window,
9731 cx: &mut Context<Self>,
9732 ) {
9733 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9734 s.move_heads_with(|map, head, _| {
9735 (
9736 movement::indented_line_beginning(
9737 map,
9738 head,
9739 action.stop_at_soft_wraps,
9740 action.stop_at_indent,
9741 ),
9742 SelectionGoal::None,
9743 )
9744 });
9745 });
9746 }
9747
9748 pub fn delete_to_beginning_of_line(
9749 &mut self,
9750 action: &DeleteToBeginningOfLine,
9751 window: &mut Window,
9752 cx: &mut Context<Self>,
9753 ) {
9754 self.transact(window, cx, |this, window, cx| {
9755 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9756 s.move_with(|_, selection| {
9757 selection.reversed = true;
9758 });
9759 });
9760
9761 this.select_to_beginning_of_line(
9762 &SelectToBeginningOfLine {
9763 stop_at_soft_wraps: false,
9764 stop_at_indent: action.stop_at_indent,
9765 },
9766 window,
9767 cx,
9768 );
9769 this.backspace(&Backspace, window, cx);
9770 });
9771 }
9772
9773 pub fn move_to_end_of_line(
9774 &mut self,
9775 action: &MoveToEndOfLine,
9776 window: &mut Window,
9777 cx: &mut Context<Self>,
9778 ) {
9779 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9780 s.move_cursors_with(|map, head, _| {
9781 (
9782 movement::line_end(map, head, action.stop_at_soft_wraps),
9783 SelectionGoal::None,
9784 )
9785 });
9786 })
9787 }
9788
9789 pub fn select_to_end_of_line(
9790 &mut self,
9791 action: &SelectToEndOfLine,
9792 window: &mut Window,
9793 cx: &mut Context<Self>,
9794 ) {
9795 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9796 s.move_heads_with(|map, head, _| {
9797 (
9798 movement::line_end(map, head, action.stop_at_soft_wraps),
9799 SelectionGoal::None,
9800 )
9801 });
9802 })
9803 }
9804
9805 pub fn delete_to_end_of_line(
9806 &mut self,
9807 _: &DeleteToEndOfLine,
9808 window: &mut Window,
9809 cx: &mut Context<Self>,
9810 ) {
9811 self.transact(window, cx, |this, window, cx| {
9812 this.select_to_end_of_line(
9813 &SelectToEndOfLine {
9814 stop_at_soft_wraps: false,
9815 },
9816 window,
9817 cx,
9818 );
9819 this.delete(&Delete, window, cx);
9820 });
9821 }
9822
9823 pub fn cut_to_end_of_line(
9824 &mut self,
9825 _: &CutToEndOfLine,
9826 window: &mut Window,
9827 cx: &mut Context<Self>,
9828 ) {
9829 self.transact(window, cx, |this, window, cx| {
9830 this.select_to_end_of_line(
9831 &SelectToEndOfLine {
9832 stop_at_soft_wraps: false,
9833 },
9834 window,
9835 cx,
9836 );
9837 this.cut(&Cut, window, cx);
9838 });
9839 }
9840
9841 pub fn move_to_start_of_paragraph(
9842 &mut self,
9843 _: &MoveToStartOfParagraph,
9844 window: &mut Window,
9845 cx: &mut Context<Self>,
9846 ) {
9847 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9848 cx.propagate();
9849 return;
9850 }
9851
9852 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9853 s.move_with(|map, selection| {
9854 selection.collapse_to(
9855 movement::start_of_paragraph(map, selection.head(), 1),
9856 SelectionGoal::None,
9857 )
9858 });
9859 })
9860 }
9861
9862 pub fn move_to_end_of_paragraph(
9863 &mut self,
9864 _: &MoveToEndOfParagraph,
9865 window: &mut Window,
9866 cx: &mut Context<Self>,
9867 ) {
9868 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9869 cx.propagate();
9870 return;
9871 }
9872
9873 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9874 s.move_with(|map, selection| {
9875 selection.collapse_to(
9876 movement::end_of_paragraph(map, selection.head(), 1),
9877 SelectionGoal::None,
9878 )
9879 });
9880 })
9881 }
9882
9883 pub fn select_to_start_of_paragraph(
9884 &mut self,
9885 _: &SelectToStartOfParagraph,
9886 window: &mut Window,
9887 cx: &mut Context<Self>,
9888 ) {
9889 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9890 cx.propagate();
9891 return;
9892 }
9893
9894 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9895 s.move_heads_with(|map, head, _| {
9896 (
9897 movement::start_of_paragraph(map, head, 1),
9898 SelectionGoal::None,
9899 )
9900 });
9901 })
9902 }
9903
9904 pub fn select_to_end_of_paragraph(
9905 &mut self,
9906 _: &SelectToEndOfParagraph,
9907 window: &mut Window,
9908 cx: &mut Context<Self>,
9909 ) {
9910 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9911 cx.propagate();
9912 return;
9913 }
9914
9915 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9916 s.move_heads_with(|map, head, _| {
9917 (
9918 movement::end_of_paragraph(map, head, 1),
9919 SelectionGoal::None,
9920 )
9921 });
9922 })
9923 }
9924
9925 pub fn move_to_start_of_excerpt(
9926 &mut self,
9927 _: &MoveToStartOfExcerpt,
9928 window: &mut Window,
9929 cx: &mut Context<Self>,
9930 ) {
9931 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9932 cx.propagate();
9933 return;
9934 }
9935
9936 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9937 s.move_with(|map, selection| {
9938 selection.collapse_to(
9939 movement::start_of_excerpt(
9940 map,
9941 selection.head(),
9942 workspace::searchable::Direction::Prev,
9943 ),
9944 SelectionGoal::None,
9945 )
9946 });
9947 })
9948 }
9949
9950 pub fn move_to_start_of_next_excerpt(
9951 &mut self,
9952 _: &MoveToStartOfNextExcerpt,
9953 window: &mut Window,
9954 cx: &mut Context<Self>,
9955 ) {
9956 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9957 cx.propagate();
9958 return;
9959 }
9960
9961 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9962 s.move_with(|map, selection| {
9963 selection.collapse_to(
9964 movement::start_of_excerpt(
9965 map,
9966 selection.head(),
9967 workspace::searchable::Direction::Next,
9968 ),
9969 SelectionGoal::None,
9970 )
9971 });
9972 })
9973 }
9974
9975 pub fn move_to_end_of_excerpt(
9976 &mut self,
9977 _: &MoveToEndOfExcerpt,
9978 window: &mut Window,
9979 cx: &mut Context<Self>,
9980 ) {
9981 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9982 cx.propagate();
9983 return;
9984 }
9985
9986 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9987 s.move_with(|map, selection| {
9988 selection.collapse_to(
9989 movement::end_of_excerpt(
9990 map,
9991 selection.head(),
9992 workspace::searchable::Direction::Next,
9993 ),
9994 SelectionGoal::None,
9995 )
9996 });
9997 })
9998 }
9999
10000 pub fn move_to_end_of_previous_excerpt(
10001 &mut self,
10002 _: &MoveToEndOfPreviousExcerpt,
10003 window: &mut Window,
10004 cx: &mut Context<Self>,
10005 ) {
10006 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10007 cx.propagate();
10008 return;
10009 }
10010
10011 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10012 s.move_with(|map, selection| {
10013 selection.collapse_to(
10014 movement::end_of_excerpt(
10015 map,
10016 selection.head(),
10017 workspace::searchable::Direction::Prev,
10018 ),
10019 SelectionGoal::None,
10020 )
10021 });
10022 })
10023 }
10024
10025 pub fn select_to_start_of_excerpt(
10026 &mut self,
10027 _: &SelectToStartOfExcerpt,
10028 window: &mut Window,
10029 cx: &mut Context<Self>,
10030 ) {
10031 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10032 cx.propagate();
10033 return;
10034 }
10035
10036 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10037 s.move_heads_with(|map, head, _| {
10038 (
10039 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10040 SelectionGoal::None,
10041 )
10042 });
10043 })
10044 }
10045
10046 pub fn select_to_start_of_next_excerpt(
10047 &mut self,
10048 _: &SelectToStartOfNextExcerpt,
10049 window: &mut Window,
10050 cx: &mut Context<Self>,
10051 ) {
10052 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10053 cx.propagate();
10054 return;
10055 }
10056
10057 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10058 s.move_heads_with(|map, head, _| {
10059 (
10060 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10061 SelectionGoal::None,
10062 )
10063 });
10064 })
10065 }
10066
10067 pub fn select_to_end_of_excerpt(
10068 &mut self,
10069 _: &SelectToEndOfExcerpt,
10070 window: &mut Window,
10071 cx: &mut Context<Self>,
10072 ) {
10073 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10074 cx.propagate();
10075 return;
10076 }
10077
10078 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10079 s.move_heads_with(|map, head, _| {
10080 (
10081 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10082 SelectionGoal::None,
10083 )
10084 });
10085 })
10086 }
10087
10088 pub fn select_to_end_of_previous_excerpt(
10089 &mut self,
10090 _: &SelectToEndOfPreviousExcerpt,
10091 window: &mut Window,
10092 cx: &mut Context<Self>,
10093 ) {
10094 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10095 cx.propagate();
10096 return;
10097 }
10098
10099 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10100 s.move_heads_with(|map, head, _| {
10101 (
10102 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10103 SelectionGoal::None,
10104 )
10105 });
10106 })
10107 }
10108
10109 pub fn move_to_beginning(
10110 &mut self,
10111 _: &MoveToBeginning,
10112 window: &mut Window,
10113 cx: &mut Context<Self>,
10114 ) {
10115 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10116 cx.propagate();
10117 return;
10118 }
10119
10120 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10121 s.select_ranges(vec![0..0]);
10122 });
10123 }
10124
10125 pub fn select_to_beginning(
10126 &mut self,
10127 _: &SelectToBeginning,
10128 window: &mut Window,
10129 cx: &mut Context<Self>,
10130 ) {
10131 let mut selection = self.selections.last::<Point>(cx);
10132 selection.set_head(Point::zero(), SelectionGoal::None);
10133
10134 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10135 s.select(vec![selection]);
10136 });
10137 }
10138
10139 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10140 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10141 cx.propagate();
10142 return;
10143 }
10144
10145 let cursor = self.buffer.read(cx).read(cx).len();
10146 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10147 s.select_ranges(vec![cursor..cursor])
10148 });
10149 }
10150
10151 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10152 self.nav_history = nav_history;
10153 }
10154
10155 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10156 self.nav_history.as_ref()
10157 }
10158
10159 fn push_to_nav_history(
10160 &mut self,
10161 cursor_anchor: Anchor,
10162 new_position: Option<Point>,
10163 cx: &mut Context<Self>,
10164 ) {
10165 if let Some(nav_history) = self.nav_history.as_mut() {
10166 let buffer = self.buffer.read(cx).read(cx);
10167 let cursor_position = cursor_anchor.to_point(&buffer);
10168 let scroll_state = self.scroll_manager.anchor();
10169 let scroll_top_row = scroll_state.top_row(&buffer);
10170 drop(buffer);
10171
10172 if let Some(new_position) = new_position {
10173 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10174 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10175 return;
10176 }
10177 }
10178
10179 nav_history.push(
10180 Some(NavigationData {
10181 cursor_anchor,
10182 cursor_position,
10183 scroll_anchor: scroll_state,
10184 scroll_top_row,
10185 }),
10186 cx,
10187 );
10188 }
10189 }
10190
10191 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10192 let buffer = self.buffer.read(cx).snapshot(cx);
10193 let mut selection = self.selections.first::<usize>(cx);
10194 selection.set_head(buffer.len(), SelectionGoal::None);
10195 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10196 s.select(vec![selection]);
10197 });
10198 }
10199
10200 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10201 let end = self.buffer.read(cx).read(cx).len();
10202 self.change_selections(None, window, cx, |s| {
10203 s.select_ranges(vec![0..end]);
10204 });
10205 }
10206
10207 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10208 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10209 let mut selections = self.selections.all::<Point>(cx);
10210 let max_point = display_map.buffer_snapshot.max_point();
10211 for selection in &mut selections {
10212 let rows = selection.spanned_rows(true, &display_map);
10213 selection.start = Point::new(rows.start.0, 0);
10214 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10215 selection.reversed = false;
10216 }
10217 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10218 s.select(selections);
10219 });
10220 }
10221
10222 pub fn split_selection_into_lines(
10223 &mut self,
10224 _: &SplitSelectionIntoLines,
10225 window: &mut Window,
10226 cx: &mut Context<Self>,
10227 ) {
10228 let selections = self
10229 .selections
10230 .all::<Point>(cx)
10231 .into_iter()
10232 .map(|selection| selection.start..selection.end)
10233 .collect::<Vec<_>>();
10234 self.unfold_ranges(&selections, true, true, cx);
10235
10236 let mut new_selection_ranges = Vec::new();
10237 {
10238 let buffer = self.buffer.read(cx).read(cx);
10239 for selection in selections {
10240 for row in selection.start.row..selection.end.row {
10241 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10242 new_selection_ranges.push(cursor..cursor);
10243 }
10244
10245 let is_multiline_selection = selection.start.row != selection.end.row;
10246 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10247 // so this action feels more ergonomic when paired with other selection operations
10248 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10249 if !should_skip_last {
10250 new_selection_ranges.push(selection.end..selection.end);
10251 }
10252 }
10253 }
10254 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10255 s.select_ranges(new_selection_ranges);
10256 });
10257 }
10258
10259 pub fn add_selection_above(
10260 &mut self,
10261 _: &AddSelectionAbove,
10262 window: &mut Window,
10263 cx: &mut Context<Self>,
10264 ) {
10265 self.add_selection(true, window, cx);
10266 }
10267
10268 pub fn add_selection_below(
10269 &mut self,
10270 _: &AddSelectionBelow,
10271 window: &mut Window,
10272 cx: &mut Context<Self>,
10273 ) {
10274 self.add_selection(false, window, cx);
10275 }
10276
10277 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10278 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10279 let mut selections = self.selections.all::<Point>(cx);
10280 let text_layout_details = self.text_layout_details(window);
10281 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10282 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10283 let range = oldest_selection.display_range(&display_map).sorted();
10284
10285 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10286 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10287 let positions = start_x.min(end_x)..start_x.max(end_x);
10288
10289 selections.clear();
10290 let mut stack = Vec::new();
10291 for row in range.start.row().0..=range.end.row().0 {
10292 if let Some(selection) = self.selections.build_columnar_selection(
10293 &display_map,
10294 DisplayRow(row),
10295 &positions,
10296 oldest_selection.reversed,
10297 &text_layout_details,
10298 ) {
10299 stack.push(selection.id);
10300 selections.push(selection);
10301 }
10302 }
10303
10304 if above {
10305 stack.reverse();
10306 }
10307
10308 AddSelectionsState { above, stack }
10309 });
10310
10311 let last_added_selection = *state.stack.last().unwrap();
10312 let mut new_selections = Vec::new();
10313 if above == state.above {
10314 let end_row = if above {
10315 DisplayRow(0)
10316 } else {
10317 display_map.max_point().row()
10318 };
10319
10320 'outer: for selection in selections {
10321 if selection.id == last_added_selection {
10322 let range = selection.display_range(&display_map).sorted();
10323 debug_assert_eq!(range.start.row(), range.end.row());
10324 let mut row = range.start.row();
10325 let positions =
10326 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10327 px(start)..px(end)
10328 } else {
10329 let start_x =
10330 display_map.x_for_display_point(range.start, &text_layout_details);
10331 let end_x =
10332 display_map.x_for_display_point(range.end, &text_layout_details);
10333 start_x.min(end_x)..start_x.max(end_x)
10334 };
10335
10336 while row != end_row {
10337 if above {
10338 row.0 -= 1;
10339 } else {
10340 row.0 += 1;
10341 }
10342
10343 if let Some(new_selection) = self.selections.build_columnar_selection(
10344 &display_map,
10345 row,
10346 &positions,
10347 selection.reversed,
10348 &text_layout_details,
10349 ) {
10350 state.stack.push(new_selection.id);
10351 if above {
10352 new_selections.push(new_selection);
10353 new_selections.push(selection);
10354 } else {
10355 new_selections.push(selection);
10356 new_selections.push(new_selection);
10357 }
10358
10359 continue 'outer;
10360 }
10361 }
10362 }
10363
10364 new_selections.push(selection);
10365 }
10366 } else {
10367 new_selections = selections;
10368 new_selections.retain(|s| s.id != last_added_selection);
10369 state.stack.pop();
10370 }
10371
10372 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10373 s.select(new_selections);
10374 });
10375 if state.stack.len() > 1 {
10376 self.add_selections_state = Some(state);
10377 }
10378 }
10379
10380 pub fn select_next_match_internal(
10381 &mut self,
10382 display_map: &DisplaySnapshot,
10383 replace_newest: bool,
10384 autoscroll: Option<Autoscroll>,
10385 window: &mut Window,
10386 cx: &mut Context<Self>,
10387 ) -> Result<()> {
10388 fn select_next_match_ranges(
10389 this: &mut Editor,
10390 range: Range<usize>,
10391 replace_newest: bool,
10392 auto_scroll: Option<Autoscroll>,
10393 window: &mut Window,
10394 cx: &mut Context<Editor>,
10395 ) {
10396 this.unfold_ranges(&[range.clone()], false, true, cx);
10397 this.change_selections(auto_scroll, window, cx, |s| {
10398 if replace_newest {
10399 s.delete(s.newest_anchor().id);
10400 }
10401 s.insert_range(range.clone());
10402 });
10403 }
10404
10405 let buffer = &display_map.buffer_snapshot;
10406 let mut selections = self.selections.all::<usize>(cx);
10407 if let Some(mut select_next_state) = self.select_next_state.take() {
10408 let query = &select_next_state.query;
10409 if !select_next_state.done {
10410 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10411 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10412 let mut next_selected_range = None;
10413
10414 let bytes_after_last_selection =
10415 buffer.bytes_in_range(last_selection.end..buffer.len());
10416 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10417 let query_matches = query
10418 .stream_find_iter(bytes_after_last_selection)
10419 .map(|result| (last_selection.end, result))
10420 .chain(
10421 query
10422 .stream_find_iter(bytes_before_first_selection)
10423 .map(|result| (0, result)),
10424 );
10425
10426 for (start_offset, query_match) in query_matches {
10427 let query_match = query_match.unwrap(); // can only fail due to I/O
10428 let offset_range =
10429 start_offset + query_match.start()..start_offset + query_match.end();
10430 let display_range = offset_range.start.to_display_point(display_map)
10431 ..offset_range.end.to_display_point(display_map);
10432
10433 if !select_next_state.wordwise
10434 || (!movement::is_inside_word(display_map, display_range.start)
10435 && !movement::is_inside_word(display_map, display_range.end))
10436 {
10437 // TODO: This is n^2, because we might check all the selections
10438 if !selections
10439 .iter()
10440 .any(|selection| selection.range().overlaps(&offset_range))
10441 {
10442 next_selected_range = Some(offset_range);
10443 break;
10444 }
10445 }
10446 }
10447
10448 if let Some(next_selected_range) = next_selected_range {
10449 select_next_match_ranges(
10450 self,
10451 next_selected_range,
10452 replace_newest,
10453 autoscroll,
10454 window,
10455 cx,
10456 );
10457 } else {
10458 select_next_state.done = true;
10459 }
10460 }
10461
10462 self.select_next_state = Some(select_next_state);
10463 } else {
10464 let mut only_carets = true;
10465 let mut same_text_selected = true;
10466 let mut selected_text = None;
10467
10468 let mut selections_iter = selections.iter().peekable();
10469 while let Some(selection) = selections_iter.next() {
10470 if selection.start != selection.end {
10471 only_carets = false;
10472 }
10473
10474 if same_text_selected {
10475 if selected_text.is_none() {
10476 selected_text =
10477 Some(buffer.text_for_range(selection.range()).collect::<String>());
10478 }
10479
10480 if let Some(next_selection) = selections_iter.peek() {
10481 if next_selection.range().len() == selection.range().len() {
10482 let next_selected_text = buffer
10483 .text_for_range(next_selection.range())
10484 .collect::<String>();
10485 if Some(next_selected_text) != selected_text {
10486 same_text_selected = false;
10487 selected_text = None;
10488 }
10489 } else {
10490 same_text_selected = false;
10491 selected_text = None;
10492 }
10493 }
10494 }
10495 }
10496
10497 if only_carets {
10498 for selection in &mut selections {
10499 let word_range = movement::surrounding_word(
10500 display_map,
10501 selection.start.to_display_point(display_map),
10502 );
10503 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10504 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10505 selection.goal = SelectionGoal::None;
10506 selection.reversed = false;
10507 select_next_match_ranges(
10508 self,
10509 selection.start..selection.end,
10510 replace_newest,
10511 autoscroll,
10512 window,
10513 cx,
10514 );
10515 }
10516
10517 if selections.len() == 1 {
10518 let selection = selections
10519 .last()
10520 .expect("ensured that there's only one selection");
10521 let query = buffer
10522 .text_for_range(selection.start..selection.end)
10523 .collect::<String>();
10524 let is_empty = query.is_empty();
10525 let select_state = SelectNextState {
10526 query: AhoCorasick::new(&[query])?,
10527 wordwise: true,
10528 done: is_empty,
10529 };
10530 self.select_next_state = Some(select_state);
10531 } else {
10532 self.select_next_state = None;
10533 }
10534 } else if let Some(selected_text) = selected_text {
10535 self.select_next_state = Some(SelectNextState {
10536 query: AhoCorasick::new(&[selected_text])?,
10537 wordwise: false,
10538 done: false,
10539 });
10540 self.select_next_match_internal(
10541 display_map,
10542 replace_newest,
10543 autoscroll,
10544 window,
10545 cx,
10546 )?;
10547 }
10548 }
10549 Ok(())
10550 }
10551
10552 pub fn select_all_matches(
10553 &mut self,
10554 _action: &SelectAllMatches,
10555 window: &mut Window,
10556 cx: &mut Context<Self>,
10557 ) -> Result<()> {
10558 self.push_to_selection_history();
10559 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10560
10561 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10562 let Some(select_next_state) = self.select_next_state.as_mut() else {
10563 return Ok(());
10564 };
10565 if select_next_state.done {
10566 return Ok(());
10567 }
10568
10569 let mut new_selections = self.selections.all::<usize>(cx);
10570
10571 let buffer = &display_map.buffer_snapshot;
10572 let query_matches = select_next_state
10573 .query
10574 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10575
10576 for query_match in query_matches {
10577 let query_match = query_match.unwrap(); // can only fail due to I/O
10578 let offset_range = query_match.start()..query_match.end();
10579 let display_range = offset_range.start.to_display_point(&display_map)
10580 ..offset_range.end.to_display_point(&display_map);
10581
10582 if !select_next_state.wordwise
10583 || (!movement::is_inside_word(&display_map, display_range.start)
10584 && !movement::is_inside_word(&display_map, display_range.end))
10585 {
10586 self.selections.change_with(cx, |selections| {
10587 new_selections.push(Selection {
10588 id: selections.new_selection_id(),
10589 start: offset_range.start,
10590 end: offset_range.end,
10591 reversed: false,
10592 goal: SelectionGoal::None,
10593 });
10594 });
10595 }
10596 }
10597
10598 new_selections.sort_by_key(|selection| selection.start);
10599 let mut ix = 0;
10600 while ix + 1 < new_selections.len() {
10601 let current_selection = &new_selections[ix];
10602 let next_selection = &new_selections[ix + 1];
10603 if current_selection.range().overlaps(&next_selection.range()) {
10604 if current_selection.id < next_selection.id {
10605 new_selections.remove(ix + 1);
10606 } else {
10607 new_selections.remove(ix);
10608 }
10609 } else {
10610 ix += 1;
10611 }
10612 }
10613
10614 let reversed = self.selections.oldest::<usize>(cx).reversed;
10615
10616 for selection in new_selections.iter_mut() {
10617 selection.reversed = reversed;
10618 }
10619
10620 select_next_state.done = true;
10621 self.unfold_ranges(
10622 &new_selections
10623 .iter()
10624 .map(|selection| selection.range())
10625 .collect::<Vec<_>>(),
10626 false,
10627 false,
10628 cx,
10629 );
10630 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10631 selections.select(new_selections)
10632 });
10633
10634 Ok(())
10635 }
10636
10637 pub fn select_next(
10638 &mut self,
10639 action: &SelectNext,
10640 window: &mut Window,
10641 cx: &mut Context<Self>,
10642 ) -> Result<()> {
10643 self.push_to_selection_history();
10644 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10645 self.select_next_match_internal(
10646 &display_map,
10647 action.replace_newest,
10648 Some(Autoscroll::newest()),
10649 window,
10650 cx,
10651 )?;
10652 Ok(())
10653 }
10654
10655 pub fn select_previous(
10656 &mut self,
10657 action: &SelectPrevious,
10658 window: &mut Window,
10659 cx: &mut Context<Self>,
10660 ) -> Result<()> {
10661 self.push_to_selection_history();
10662 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10663 let buffer = &display_map.buffer_snapshot;
10664 let mut selections = self.selections.all::<usize>(cx);
10665 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10666 let query = &select_prev_state.query;
10667 if !select_prev_state.done {
10668 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10669 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10670 let mut next_selected_range = None;
10671 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10672 let bytes_before_last_selection =
10673 buffer.reversed_bytes_in_range(0..last_selection.start);
10674 let bytes_after_first_selection =
10675 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10676 let query_matches = query
10677 .stream_find_iter(bytes_before_last_selection)
10678 .map(|result| (last_selection.start, result))
10679 .chain(
10680 query
10681 .stream_find_iter(bytes_after_first_selection)
10682 .map(|result| (buffer.len(), result)),
10683 );
10684 for (end_offset, query_match) in query_matches {
10685 let query_match = query_match.unwrap(); // can only fail due to I/O
10686 let offset_range =
10687 end_offset - query_match.end()..end_offset - query_match.start();
10688 let display_range = offset_range.start.to_display_point(&display_map)
10689 ..offset_range.end.to_display_point(&display_map);
10690
10691 if !select_prev_state.wordwise
10692 || (!movement::is_inside_word(&display_map, display_range.start)
10693 && !movement::is_inside_word(&display_map, display_range.end))
10694 {
10695 next_selected_range = Some(offset_range);
10696 break;
10697 }
10698 }
10699
10700 if let Some(next_selected_range) = next_selected_range {
10701 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10702 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10703 if action.replace_newest {
10704 s.delete(s.newest_anchor().id);
10705 }
10706 s.insert_range(next_selected_range);
10707 });
10708 } else {
10709 select_prev_state.done = true;
10710 }
10711 }
10712
10713 self.select_prev_state = Some(select_prev_state);
10714 } else {
10715 let mut only_carets = true;
10716 let mut same_text_selected = true;
10717 let mut selected_text = None;
10718
10719 let mut selections_iter = selections.iter().peekable();
10720 while let Some(selection) = selections_iter.next() {
10721 if selection.start != selection.end {
10722 only_carets = false;
10723 }
10724
10725 if same_text_selected {
10726 if selected_text.is_none() {
10727 selected_text =
10728 Some(buffer.text_for_range(selection.range()).collect::<String>());
10729 }
10730
10731 if let Some(next_selection) = selections_iter.peek() {
10732 if next_selection.range().len() == selection.range().len() {
10733 let next_selected_text = buffer
10734 .text_for_range(next_selection.range())
10735 .collect::<String>();
10736 if Some(next_selected_text) != selected_text {
10737 same_text_selected = false;
10738 selected_text = None;
10739 }
10740 } else {
10741 same_text_selected = false;
10742 selected_text = None;
10743 }
10744 }
10745 }
10746 }
10747
10748 if only_carets {
10749 for selection in &mut selections {
10750 let word_range = movement::surrounding_word(
10751 &display_map,
10752 selection.start.to_display_point(&display_map),
10753 );
10754 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10755 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10756 selection.goal = SelectionGoal::None;
10757 selection.reversed = false;
10758 }
10759 if selections.len() == 1 {
10760 let selection = selections
10761 .last()
10762 .expect("ensured that there's only one selection");
10763 let query = buffer
10764 .text_for_range(selection.start..selection.end)
10765 .collect::<String>();
10766 let is_empty = query.is_empty();
10767 let select_state = SelectNextState {
10768 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10769 wordwise: true,
10770 done: is_empty,
10771 };
10772 self.select_prev_state = Some(select_state);
10773 } else {
10774 self.select_prev_state = None;
10775 }
10776
10777 self.unfold_ranges(
10778 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10779 false,
10780 true,
10781 cx,
10782 );
10783 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10784 s.select(selections);
10785 });
10786 } else if let Some(selected_text) = selected_text {
10787 self.select_prev_state = Some(SelectNextState {
10788 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10789 wordwise: false,
10790 done: false,
10791 });
10792 self.select_previous(action, window, cx)?;
10793 }
10794 }
10795 Ok(())
10796 }
10797
10798 pub fn toggle_comments(
10799 &mut self,
10800 action: &ToggleComments,
10801 window: &mut Window,
10802 cx: &mut Context<Self>,
10803 ) {
10804 if self.read_only(cx) {
10805 return;
10806 }
10807 let text_layout_details = &self.text_layout_details(window);
10808 self.transact(window, cx, |this, window, cx| {
10809 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10810 let mut edits = Vec::new();
10811 let mut selection_edit_ranges = Vec::new();
10812 let mut last_toggled_row = None;
10813 let snapshot = this.buffer.read(cx).read(cx);
10814 let empty_str: Arc<str> = Arc::default();
10815 let mut suffixes_inserted = Vec::new();
10816 let ignore_indent = action.ignore_indent;
10817
10818 fn comment_prefix_range(
10819 snapshot: &MultiBufferSnapshot,
10820 row: MultiBufferRow,
10821 comment_prefix: &str,
10822 comment_prefix_whitespace: &str,
10823 ignore_indent: bool,
10824 ) -> Range<Point> {
10825 let indent_size = if ignore_indent {
10826 0
10827 } else {
10828 snapshot.indent_size_for_line(row).len
10829 };
10830
10831 let start = Point::new(row.0, indent_size);
10832
10833 let mut line_bytes = snapshot
10834 .bytes_in_range(start..snapshot.max_point())
10835 .flatten()
10836 .copied();
10837
10838 // If this line currently begins with the line comment prefix, then record
10839 // the range containing the prefix.
10840 if line_bytes
10841 .by_ref()
10842 .take(comment_prefix.len())
10843 .eq(comment_prefix.bytes())
10844 {
10845 // Include any whitespace that matches the comment prefix.
10846 let matching_whitespace_len = line_bytes
10847 .zip(comment_prefix_whitespace.bytes())
10848 .take_while(|(a, b)| a == b)
10849 .count() as u32;
10850 let end = Point::new(
10851 start.row,
10852 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10853 );
10854 start..end
10855 } else {
10856 start..start
10857 }
10858 }
10859
10860 fn comment_suffix_range(
10861 snapshot: &MultiBufferSnapshot,
10862 row: MultiBufferRow,
10863 comment_suffix: &str,
10864 comment_suffix_has_leading_space: bool,
10865 ) -> Range<Point> {
10866 let end = Point::new(row.0, snapshot.line_len(row));
10867 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10868
10869 let mut line_end_bytes = snapshot
10870 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10871 .flatten()
10872 .copied();
10873
10874 let leading_space_len = if suffix_start_column > 0
10875 && line_end_bytes.next() == Some(b' ')
10876 && comment_suffix_has_leading_space
10877 {
10878 1
10879 } else {
10880 0
10881 };
10882
10883 // If this line currently begins with the line comment prefix, then record
10884 // the range containing the prefix.
10885 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10886 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10887 start..end
10888 } else {
10889 end..end
10890 }
10891 }
10892
10893 // TODO: Handle selections that cross excerpts
10894 for selection in &mut selections {
10895 let start_column = snapshot
10896 .indent_size_for_line(MultiBufferRow(selection.start.row))
10897 .len;
10898 let language = if let Some(language) =
10899 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10900 {
10901 language
10902 } else {
10903 continue;
10904 };
10905
10906 selection_edit_ranges.clear();
10907
10908 // If multiple selections contain a given row, avoid processing that
10909 // row more than once.
10910 let mut start_row = MultiBufferRow(selection.start.row);
10911 if last_toggled_row == Some(start_row) {
10912 start_row = start_row.next_row();
10913 }
10914 let end_row =
10915 if selection.end.row > selection.start.row && selection.end.column == 0 {
10916 MultiBufferRow(selection.end.row - 1)
10917 } else {
10918 MultiBufferRow(selection.end.row)
10919 };
10920 last_toggled_row = Some(end_row);
10921
10922 if start_row > end_row {
10923 continue;
10924 }
10925
10926 // If the language has line comments, toggle those.
10927 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10928
10929 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10930 if ignore_indent {
10931 full_comment_prefixes = full_comment_prefixes
10932 .into_iter()
10933 .map(|s| Arc::from(s.trim_end()))
10934 .collect();
10935 }
10936
10937 if !full_comment_prefixes.is_empty() {
10938 let first_prefix = full_comment_prefixes
10939 .first()
10940 .expect("prefixes is non-empty");
10941 let prefix_trimmed_lengths = full_comment_prefixes
10942 .iter()
10943 .map(|p| p.trim_end_matches(' ').len())
10944 .collect::<SmallVec<[usize; 4]>>();
10945
10946 let mut all_selection_lines_are_comments = true;
10947
10948 for row in start_row.0..=end_row.0 {
10949 let row = MultiBufferRow(row);
10950 if start_row < end_row && snapshot.is_line_blank(row) {
10951 continue;
10952 }
10953
10954 let prefix_range = full_comment_prefixes
10955 .iter()
10956 .zip(prefix_trimmed_lengths.iter().copied())
10957 .map(|(prefix, trimmed_prefix_len)| {
10958 comment_prefix_range(
10959 snapshot.deref(),
10960 row,
10961 &prefix[..trimmed_prefix_len],
10962 &prefix[trimmed_prefix_len..],
10963 ignore_indent,
10964 )
10965 })
10966 .max_by_key(|range| range.end.column - range.start.column)
10967 .expect("prefixes is non-empty");
10968
10969 if prefix_range.is_empty() {
10970 all_selection_lines_are_comments = false;
10971 }
10972
10973 selection_edit_ranges.push(prefix_range);
10974 }
10975
10976 if all_selection_lines_are_comments {
10977 edits.extend(
10978 selection_edit_ranges
10979 .iter()
10980 .cloned()
10981 .map(|range| (range, empty_str.clone())),
10982 );
10983 } else {
10984 let min_column = selection_edit_ranges
10985 .iter()
10986 .map(|range| range.start.column)
10987 .min()
10988 .unwrap_or(0);
10989 edits.extend(selection_edit_ranges.iter().map(|range| {
10990 let position = Point::new(range.start.row, min_column);
10991 (position..position, first_prefix.clone())
10992 }));
10993 }
10994 } else if let Some((full_comment_prefix, comment_suffix)) =
10995 language.block_comment_delimiters()
10996 {
10997 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10998 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10999 let prefix_range = comment_prefix_range(
11000 snapshot.deref(),
11001 start_row,
11002 comment_prefix,
11003 comment_prefix_whitespace,
11004 ignore_indent,
11005 );
11006 let suffix_range = comment_suffix_range(
11007 snapshot.deref(),
11008 end_row,
11009 comment_suffix.trim_start_matches(' '),
11010 comment_suffix.starts_with(' '),
11011 );
11012
11013 if prefix_range.is_empty() || suffix_range.is_empty() {
11014 edits.push((
11015 prefix_range.start..prefix_range.start,
11016 full_comment_prefix.clone(),
11017 ));
11018 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11019 suffixes_inserted.push((end_row, comment_suffix.len()));
11020 } else {
11021 edits.push((prefix_range, empty_str.clone()));
11022 edits.push((suffix_range, empty_str.clone()));
11023 }
11024 } else {
11025 continue;
11026 }
11027 }
11028
11029 drop(snapshot);
11030 this.buffer.update(cx, |buffer, cx| {
11031 buffer.edit(edits, None, cx);
11032 });
11033
11034 // Adjust selections so that they end before any comment suffixes that
11035 // were inserted.
11036 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11037 let mut selections = this.selections.all::<Point>(cx);
11038 let snapshot = this.buffer.read(cx).read(cx);
11039 for selection in &mut selections {
11040 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11041 match row.cmp(&MultiBufferRow(selection.end.row)) {
11042 Ordering::Less => {
11043 suffixes_inserted.next();
11044 continue;
11045 }
11046 Ordering::Greater => break,
11047 Ordering::Equal => {
11048 if selection.end.column == snapshot.line_len(row) {
11049 if selection.is_empty() {
11050 selection.start.column -= suffix_len as u32;
11051 }
11052 selection.end.column -= suffix_len as u32;
11053 }
11054 break;
11055 }
11056 }
11057 }
11058 }
11059
11060 drop(snapshot);
11061 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11062 s.select(selections)
11063 });
11064
11065 let selections = this.selections.all::<Point>(cx);
11066 let selections_on_single_row = selections.windows(2).all(|selections| {
11067 selections[0].start.row == selections[1].start.row
11068 && selections[0].end.row == selections[1].end.row
11069 && selections[0].start.row == selections[0].end.row
11070 });
11071 let selections_selecting = selections
11072 .iter()
11073 .any(|selection| selection.start != selection.end);
11074 let advance_downwards = action.advance_downwards
11075 && selections_on_single_row
11076 && !selections_selecting
11077 && !matches!(this.mode, EditorMode::SingleLine { .. });
11078
11079 if advance_downwards {
11080 let snapshot = this.buffer.read(cx).snapshot(cx);
11081
11082 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11083 s.move_cursors_with(|display_snapshot, display_point, _| {
11084 let mut point = display_point.to_point(display_snapshot);
11085 point.row += 1;
11086 point = snapshot.clip_point(point, Bias::Left);
11087 let display_point = point.to_display_point(display_snapshot);
11088 let goal = SelectionGoal::HorizontalPosition(
11089 display_snapshot
11090 .x_for_display_point(display_point, text_layout_details)
11091 .into(),
11092 );
11093 (display_point, goal)
11094 })
11095 });
11096 }
11097 });
11098 }
11099
11100 pub fn select_enclosing_symbol(
11101 &mut self,
11102 _: &SelectEnclosingSymbol,
11103 window: &mut Window,
11104 cx: &mut Context<Self>,
11105 ) {
11106 let buffer = self.buffer.read(cx).snapshot(cx);
11107 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11108
11109 fn update_selection(
11110 selection: &Selection<usize>,
11111 buffer_snap: &MultiBufferSnapshot,
11112 ) -> Option<Selection<usize>> {
11113 let cursor = selection.head();
11114 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11115 for symbol in symbols.iter().rev() {
11116 let start = symbol.range.start.to_offset(buffer_snap);
11117 let end = symbol.range.end.to_offset(buffer_snap);
11118 let new_range = start..end;
11119 if start < selection.start || end > selection.end {
11120 return Some(Selection {
11121 id: selection.id,
11122 start: new_range.start,
11123 end: new_range.end,
11124 goal: SelectionGoal::None,
11125 reversed: selection.reversed,
11126 });
11127 }
11128 }
11129 None
11130 }
11131
11132 let mut selected_larger_symbol = false;
11133 let new_selections = old_selections
11134 .iter()
11135 .map(|selection| match update_selection(selection, &buffer) {
11136 Some(new_selection) => {
11137 if new_selection.range() != selection.range() {
11138 selected_larger_symbol = true;
11139 }
11140 new_selection
11141 }
11142 None => selection.clone(),
11143 })
11144 .collect::<Vec<_>>();
11145
11146 if selected_larger_symbol {
11147 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11148 s.select(new_selections);
11149 });
11150 }
11151 }
11152
11153 pub fn select_larger_syntax_node(
11154 &mut self,
11155 _: &SelectLargerSyntaxNode,
11156 window: &mut Window,
11157 cx: &mut Context<Self>,
11158 ) {
11159 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11160 let buffer = self.buffer.read(cx).snapshot(cx);
11161 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11162
11163 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11164 let mut selected_larger_node = false;
11165 let new_selections = old_selections
11166 .iter()
11167 .map(|selection| {
11168 let old_range = selection.start..selection.end;
11169 let mut new_range = old_range.clone();
11170 let mut new_node = None;
11171 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11172 {
11173 new_node = Some(node);
11174 new_range = match containing_range {
11175 MultiOrSingleBufferOffsetRange::Single(_) => break,
11176 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11177 };
11178 if !display_map.intersects_fold(new_range.start)
11179 && !display_map.intersects_fold(new_range.end)
11180 {
11181 break;
11182 }
11183 }
11184
11185 if let Some(node) = new_node {
11186 // Log the ancestor, to support using this action as a way to explore TreeSitter
11187 // nodes. Parent and grandparent are also logged because this operation will not
11188 // visit nodes that have the same range as their parent.
11189 log::info!("Node: {node:?}");
11190 let parent = node.parent();
11191 log::info!("Parent: {parent:?}");
11192 let grandparent = parent.and_then(|x| x.parent());
11193 log::info!("Grandparent: {grandparent:?}");
11194 }
11195
11196 selected_larger_node |= new_range != old_range;
11197 Selection {
11198 id: selection.id,
11199 start: new_range.start,
11200 end: new_range.end,
11201 goal: SelectionGoal::None,
11202 reversed: selection.reversed,
11203 }
11204 })
11205 .collect::<Vec<_>>();
11206
11207 if selected_larger_node {
11208 stack.push(old_selections);
11209 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11210 s.select(new_selections);
11211 });
11212 }
11213 self.select_larger_syntax_node_stack = stack;
11214 }
11215
11216 pub fn select_smaller_syntax_node(
11217 &mut self,
11218 _: &SelectSmallerSyntaxNode,
11219 window: &mut Window,
11220 cx: &mut Context<Self>,
11221 ) {
11222 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11223 if let Some(selections) = stack.pop() {
11224 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11225 s.select(selections.to_vec());
11226 });
11227 }
11228 self.select_larger_syntax_node_stack = stack;
11229 }
11230
11231 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11232 if !EditorSettings::get_global(cx).gutter.runnables {
11233 self.clear_tasks();
11234 return Task::ready(());
11235 }
11236 let project = self.project.as_ref().map(Entity::downgrade);
11237 cx.spawn_in(window, |this, mut cx| async move {
11238 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11239 let Some(project) = project.and_then(|p| p.upgrade()) else {
11240 return;
11241 };
11242 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11243 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11244 }) else {
11245 return;
11246 };
11247
11248 let hide_runnables = project
11249 .update(&mut cx, |project, cx| {
11250 // Do not display any test indicators in non-dev server remote projects.
11251 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11252 })
11253 .unwrap_or(true);
11254 if hide_runnables {
11255 return;
11256 }
11257 let new_rows =
11258 cx.background_spawn({
11259 let snapshot = display_snapshot.clone();
11260 async move {
11261 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11262 }
11263 })
11264 .await;
11265
11266 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11267 this.update(&mut cx, |this, _| {
11268 this.clear_tasks();
11269 for (key, value) in rows {
11270 this.insert_tasks(key, value);
11271 }
11272 })
11273 .ok();
11274 })
11275 }
11276 fn fetch_runnable_ranges(
11277 snapshot: &DisplaySnapshot,
11278 range: Range<Anchor>,
11279 ) -> Vec<language::RunnableRange> {
11280 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11281 }
11282
11283 fn runnable_rows(
11284 project: Entity<Project>,
11285 snapshot: DisplaySnapshot,
11286 runnable_ranges: Vec<RunnableRange>,
11287 mut cx: AsyncWindowContext,
11288 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11289 runnable_ranges
11290 .into_iter()
11291 .filter_map(|mut runnable| {
11292 let tasks = cx
11293 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11294 .ok()?;
11295 if tasks.is_empty() {
11296 return None;
11297 }
11298
11299 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11300
11301 let row = snapshot
11302 .buffer_snapshot
11303 .buffer_line_for_row(MultiBufferRow(point.row))?
11304 .1
11305 .start
11306 .row;
11307
11308 let context_range =
11309 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11310 Some((
11311 (runnable.buffer_id, row),
11312 RunnableTasks {
11313 templates: tasks,
11314 offset: snapshot
11315 .buffer_snapshot
11316 .anchor_before(runnable.run_range.start),
11317 context_range,
11318 column: point.column,
11319 extra_variables: runnable.extra_captures,
11320 },
11321 ))
11322 })
11323 .collect()
11324 }
11325
11326 fn templates_with_tags(
11327 project: &Entity<Project>,
11328 runnable: &mut Runnable,
11329 cx: &mut App,
11330 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11331 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11332 let (worktree_id, file) = project
11333 .buffer_for_id(runnable.buffer, cx)
11334 .and_then(|buffer| buffer.read(cx).file())
11335 .map(|file| (file.worktree_id(cx), file.clone()))
11336 .unzip();
11337
11338 (
11339 project.task_store().read(cx).task_inventory().cloned(),
11340 worktree_id,
11341 file,
11342 )
11343 });
11344
11345 let tags = mem::take(&mut runnable.tags);
11346 let mut tags: Vec<_> = tags
11347 .into_iter()
11348 .flat_map(|tag| {
11349 let tag = tag.0.clone();
11350 inventory
11351 .as_ref()
11352 .into_iter()
11353 .flat_map(|inventory| {
11354 inventory.read(cx).list_tasks(
11355 file.clone(),
11356 Some(runnable.language.clone()),
11357 worktree_id,
11358 cx,
11359 )
11360 })
11361 .filter(move |(_, template)| {
11362 template.tags.iter().any(|source_tag| source_tag == &tag)
11363 })
11364 })
11365 .sorted_by_key(|(kind, _)| kind.to_owned())
11366 .collect();
11367 if let Some((leading_tag_source, _)) = tags.first() {
11368 // Strongest source wins; if we have worktree tag binding, prefer that to
11369 // global and language bindings;
11370 // if we have a global binding, prefer that to language binding.
11371 let first_mismatch = tags
11372 .iter()
11373 .position(|(tag_source, _)| tag_source != leading_tag_source);
11374 if let Some(index) = first_mismatch {
11375 tags.truncate(index);
11376 }
11377 }
11378
11379 tags
11380 }
11381
11382 pub fn move_to_enclosing_bracket(
11383 &mut self,
11384 _: &MoveToEnclosingBracket,
11385 window: &mut Window,
11386 cx: &mut Context<Self>,
11387 ) {
11388 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11389 s.move_offsets_with(|snapshot, selection| {
11390 let Some(enclosing_bracket_ranges) =
11391 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11392 else {
11393 return;
11394 };
11395
11396 let mut best_length = usize::MAX;
11397 let mut best_inside = false;
11398 let mut best_in_bracket_range = false;
11399 let mut best_destination = None;
11400 for (open, close) in enclosing_bracket_ranges {
11401 let close = close.to_inclusive();
11402 let length = close.end() - open.start;
11403 let inside = selection.start >= open.end && selection.end <= *close.start();
11404 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11405 || close.contains(&selection.head());
11406
11407 // If best is next to a bracket and current isn't, skip
11408 if !in_bracket_range && best_in_bracket_range {
11409 continue;
11410 }
11411
11412 // Prefer smaller lengths unless best is inside and current isn't
11413 if length > best_length && (best_inside || !inside) {
11414 continue;
11415 }
11416
11417 best_length = length;
11418 best_inside = inside;
11419 best_in_bracket_range = in_bracket_range;
11420 best_destination = Some(
11421 if close.contains(&selection.start) && close.contains(&selection.end) {
11422 if inside {
11423 open.end
11424 } else {
11425 open.start
11426 }
11427 } else if inside {
11428 *close.start()
11429 } else {
11430 *close.end()
11431 },
11432 );
11433 }
11434
11435 if let Some(destination) = best_destination {
11436 selection.collapse_to(destination, SelectionGoal::None);
11437 }
11438 })
11439 });
11440 }
11441
11442 pub fn undo_selection(
11443 &mut self,
11444 _: &UndoSelection,
11445 window: &mut Window,
11446 cx: &mut Context<Self>,
11447 ) {
11448 self.end_selection(window, cx);
11449 self.selection_history.mode = SelectionHistoryMode::Undoing;
11450 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11451 self.change_selections(None, window, cx, |s| {
11452 s.select_anchors(entry.selections.to_vec())
11453 });
11454 self.select_next_state = entry.select_next_state;
11455 self.select_prev_state = entry.select_prev_state;
11456 self.add_selections_state = entry.add_selections_state;
11457 self.request_autoscroll(Autoscroll::newest(), cx);
11458 }
11459 self.selection_history.mode = SelectionHistoryMode::Normal;
11460 }
11461
11462 pub fn redo_selection(
11463 &mut self,
11464 _: &RedoSelection,
11465 window: &mut Window,
11466 cx: &mut Context<Self>,
11467 ) {
11468 self.end_selection(window, cx);
11469 self.selection_history.mode = SelectionHistoryMode::Redoing;
11470 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11471 self.change_selections(None, window, cx, |s| {
11472 s.select_anchors(entry.selections.to_vec())
11473 });
11474 self.select_next_state = entry.select_next_state;
11475 self.select_prev_state = entry.select_prev_state;
11476 self.add_selections_state = entry.add_selections_state;
11477 self.request_autoscroll(Autoscroll::newest(), cx);
11478 }
11479 self.selection_history.mode = SelectionHistoryMode::Normal;
11480 }
11481
11482 pub fn expand_excerpts(
11483 &mut self,
11484 action: &ExpandExcerpts,
11485 _: &mut Window,
11486 cx: &mut Context<Self>,
11487 ) {
11488 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11489 }
11490
11491 pub fn expand_excerpts_down(
11492 &mut self,
11493 action: &ExpandExcerptsDown,
11494 _: &mut Window,
11495 cx: &mut Context<Self>,
11496 ) {
11497 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11498 }
11499
11500 pub fn expand_excerpts_up(
11501 &mut self,
11502 action: &ExpandExcerptsUp,
11503 _: &mut Window,
11504 cx: &mut Context<Self>,
11505 ) {
11506 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11507 }
11508
11509 pub fn expand_excerpts_for_direction(
11510 &mut self,
11511 lines: u32,
11512 direction: ExpandExcerptDirection,
11513
11514 cx: &mut Context<Self>,
11515 ) {
11516 let selections = self.selections.disjoint_anchors();
11517
11518 let lines = if lines == 0 {
11519 EditorSettings::get_global(cx).expand_excerpt_lines
11520 } else {
11521 lines
11522 };
11523
11524 self.buffer.update(cx, |buffer, cx| {
11525 let snapshot = buffer.snapshot(cx);
11526 let mut excerpt_ids = selections
11527 .iter()
11528 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11529 .collect::<Vec<_>>();
11530 excerpt_ids.sort();
11531 excerpt_ids.dedup();
11532 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11533 })
11534 }
11535
11536 pub fn expand_excerpt(
11537 &mut self,
11538 excerpt: ExcerptId,
11539 direction: ExpandExcerptDirection,
11540 cx: &mut Context<Self>,
11541 ) {
11542 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11543 self.buffer.update(cx, |buffer, cx| {
11544 buffer.expand_excerpts([excerpt], lines, direction, cx)
11545 })
11546 }
11547
11548 pub fn go_to_singleton_buffer_point(
11549 &mut self,
11550 point: Point,
11551 window: &mut Window,
11552 cx: &mut Context<Self>,
11553 ) {
11554 self.go_to_singleton_buffer_range(point..point, window, cx);
11555 }
11556
11557 pub fn go_to_singleton_buffer_range(
11558 &mut self,
11559 range: Range<Point>,
11560 window: &mut Window,
11561 cx: &mut Context<Self>,
11562 ) {
11563 let multibuffer = self.buffer().read(cx);
11564 let Some(buffer) = multibuffer.as_singleton() else {
11565 return;
11566 };
11567 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11568 return;
11569 };
11570 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11571 return;
11572 };
11573 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11574 s.select_anchor_ranges([start..end])
11575 });
11576 }
11577
11578 fn go_to_diagnostic(
11579 &mut self,
11580 _: &GoToDiagnostic,
11581 window: &mut Window,
11582 cx: &mut Context<Self>,
11583 ) {
11584 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11585 }
11586
11587 fn go_to_prev_diagnostic(
11588 &mut self,
11589 _: &GoToPreviousDiagnostic,
11590 window: &mut Window,
11591 cx: &mut Context<Self>,
11592 ) {
11593 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11594 }
11595
11596 pub fn go_to_diagnostic_impl(
11597 &mut self,
11598 direction: Direction,
11599 window: &mut Window,
11600 cx: &mut Context<Self>,
11601 ) {
11602 let buffer = self.buffer.read(cx).snapshot(cx);
11603 let selection = self.selections.newest::<usize>(cx);
11604
11605 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11606 if direction == Direction::Next {
11607 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11608 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11609 return;
11610 };
11611 self.activate_diagnostics(
11612 buffer_id,
11613 popover.local_diagnostic.diagnostic.group_id,
11614 window,
11615 cx,
11616 );
11617 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11618 let primary_range_start = active_diagnostics.primary_range.start;
11619 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11620 let mut new_selection = s.newest_anchor().clone();
11621 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11622 s.select_anchors(vec![new_selection.clone()]);
11623 });
11624 self.refresh_inline_completion(false, true, window, cx);
11625 }
11626 return;
11627 }
11628 }
11629
11630 let active_group_id = self
11631 .active_diagnostics
11632 .as_ref()
11633 .map(|active_group| active_group.group_id);
11634 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11635 active_diagnostics
11636 .primary_range
11637 .to_offset(&buffer)
11638 .to_inclusive()
11639 });
11640 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11641 if active_primary_range.contains(&selection.head()) {
11642 *active_primary_range.start()
11643 } else {
11644 selection.head()
11645 }
11646 } else {
11647 selection.head()
11648 };
11649
11650 let snapshot = self.snapshot(window, cx);
11651 let primary_diagnostics_before = buffer
11652 .diagnostics_in_range::<usize>(0..search_start)
11653 .filter(|entry| entry.diagnostic.is_primary)
11654 .filter(|entry| entry.range.start != entry.range.end)
11655 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11656 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11657 .collect::<Vec<_>>();
11658 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11659 primary_diagnostics_before
11660 .iter()
11661 .position(|entry| entry.diagnostic.group_id == active_group_id)
11662 });
11663
11664 let primary_diagnostics_after = buffer
11665 .diagnostics_in_range::<usize>(search_start..buffer.len())
11666 .filter(|entry| entry.diagnostic.is_primary)
11667 .filter(|entry| entry.range.start != entry.range.end)
11668 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11669 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11670 .collect::<Vec<_>>();
11671 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11672 primary_diagnostics_after
11673 .iter()
11674 .enumerate()
11675 .rev()
11676 .find_map(|(i, entry)| {
11677 if entry.diagnostic.group_id == active_group_id {
11678 Some(i)
11679 } else {
11680 None
11681 }
11682 })
11683 });
11684
11685 let next_primary_diagnostic = match direction {
11686 Direction::Prev => primary_diagnostics_before
11687 .iter()
11688 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11689 .rev()
11690 .next(),
11691 Direction::Next => primary_diagnostics_after
11692 .iter()
11693 .skip(
11694 last_same_group_diagnostic_after
11695 .map(|index| index + 1)
11696 .unwrap_or(0),
11697 )
11698 .next(),
11699 };
11700
11701 // Cycle around to the start of the buffer, potentially moving back to the start of
11702 // the currently active diagnostic.
11703 let cycle_around = || match direction {
11704 Direction::Prev => primary_diagnostics_after
11705 .iter()
11706 .rev()
11707 .chain(primary_diagnostics_before.iter().rev())
11708 .next(),
11709 Direction::Next => primary_diagnostics_before
11710 .iter()
11711 .chain(primary_diagnostics_after.iter())
11712 .next(),
11713 };
11714
11715 if let Some((primary_range, group_id)) = next_primary_diagnostic
11716 .or_else(cycle_around)
11717 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11718 {
11719 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11720 return;
11721 };
11722 self.activate_diagnostics(buffer_id, group_id, window, cx);
11723 if self.active_diagnostics.is_some() {
11724 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11725 s.select(vec![Selection {
11726 id: selection.id,
11727 start: primary_range.start,
11728 end: primary_range.start,
11729 reversed: false,
11730 goal: SelectionGoal::None,
11731 }]);
11732 });
11733 self.refresh_inline_completion(false, true, window, cx);
11734 }
11735 }
11736 }
11737
11738 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11739 let snapshot = self.snapshot(window, cx);
11740 let selection = self.selections.newest::<Point>(cx);
11741 self.go_to_hunk_before_or_after_position(
11742 &snapshot,
11743 selection.head(),
11744 Direction::Next,
11745 window,
11746 cx,
11747 );
11748 }
11749
11750 fn go_to_hunk_before_or_after_position(
11751 &mut self,
11752 snapshot: &EditorSnapshot,
11753 position: Point,
11754 direction: Direction,
11755 window: &mut Window,
11756 cx: &mut Context<Editor>,
11757 ) {
11758 let row = if direction == Direction::Next {
11759 self.hunk_after_position(snapshot, position)
11760 .map(|hunk| hunk.row_range.start)
11761 } else {
11762 self.hunk_before_position(snapshot, position)
11763 };
11764
11765 if let Some(row) = row {
11766 let destination = Point::new(row.0, 0);
11767 let autoscroll = Autoscroll::center();
11768
11769 self.unfold_ranges(&[destination..destination], false, false, cx);
11770 self.change_selections(Some(autoscroll), window, cx, |s| {
11771 s.select_ranges([destination..destination]);
11772 });
11773 }
11774 }
11775
11776 fn hunk_after_position(
11777 &mut self,
11778 snapshot: &EditorSnapshot,
11779 position: Point,
11780 ) -> Option<MultiBufferDiffHunk> {
11781 snapshot
11782 .buffer_snapshot
11783 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11784 .find(|hunk| hunk.row_range.start.0 > position.row)
11785 .or_else(|| {
11786 snapshot
11787 .buffer_snapshot
11788 .diff_hunks_in_range(Point::zero()..position)
11789 .find(|hunk| hunk.row_range.end.0 < position.row)
11790 })
11791 }
11792
11793 fn go_to_prev_hunk(
11794 &mut self,
11795 _: &GoToPreviousHunk,
11796 window: &mut Window,
11797 cx: &mut Context<Self>,
11798 ) {
11799 let snapshot = self.snapshot(window, cx);
11800 let selection = self.selections.newest::<Point>(cx);
11801 self.go_to_hunk_before_or_after_position(
11802 &snapshot,
11803 selection.head(),
11804 Direction::Prev,
11805 window,
11806 cx,
11807 );
11808 }
11809
11810 fn hunk_before_position(
11811 &mut self,
11812 snapshot: &EditorSnapshot,
11813 position: Point,
11814 ) -> Option<MultiBufferRow> {
11815 snapshot
11816 .buffer_snapshot
11817 .diff_hunk_before(position)
11818 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11819 }
11820
11821 pub fn go_to_definition(
11822 &mut self,
11823 _: &GoToDefinition,
11824 window: &mut Window,
11825 cx: &mut Context<Self>,
11826 ) -> Task<Result<Navigated>> {
11827 let definition =
11828 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11829 cx.spawn_in(window, |editor, mut cx| async move {
11830 if definition.await? == Navigated::Yes {
11831 return Ok(Navigated::Yes);
11832 }
11833 match editor.update_in(&mut cx, |editor, window, cx| {
11834 editor.find_all_references(&FindAllReferences, window, cx)
11835 })? {
11836 Some(references) => references.await,
11837 None => Ok(Navigated::No),
11838 }
11839 })
11840 }
11841
11842 pub fn go_to_declaration(
11843 &mut self,
11844 _: &GoToDeclaration,
11845 window: &mut Window,
11846 cx: &mut Context<Self>,
11847 ) -> Task<Result<Navigated>> {
11848 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11849 }
11850
11851 pub fn go_to_declaration_split(
11852 &mut self,
11853 _: &GoToDeclaration,
11854 window: &mut Window,
11855 cx: &mut Context<Self>,
11856 ) -> Task<Result<Navigated>> {
11857 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11858 }
11859
11860 pub fn go_to_implementation(
11861 &mut self,
11862 _: &GoToImplementation,
11863 window: &mut Window,
11864 cx: &mut Context<Self>,
11865 ) -> Task<Result<Navigated>> {
11866 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11867 }
11868
11869 pub fn go_to_implementation_split(
11870 &mut self,
11871 _: &GoToImplementationSplit,
11872 window: &mut Window,
11873 cx: &mut Context<Self>,
11874 ) -> Task<Result<Navigated>> {
11875 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11876 }
11877
11878 pub fn go_to_type_definition(
11879 &mut self,
11880 _: &GoToTypeDefinition,
11881 window: &mut Window,
11882 cx: &mut Context<Self>,
11883 ) -> Task<Result<Navigated>> {
11884 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11885 }
11886
11887 pub fn go_to_definition_split(
11888 &mut self,
11889 _: &GoToDefinitionSplit,
11890 window: &mut Window,
11891 cx: &mut Context<Self>,
11892 ) -> Task<Result<Navigated>> {
11893 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11894 }
11895
11896 pub fn go_to_type_definition_split(
11897 &mut self,
11898 _: &GoToTypeDefinitionSplit,
11899 window: &mut Window,
11900 cx: &mut Context<Self>,
11901 ) -> Task<Result<Navigated>> {
11902 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11903 }
11904
11905 fn go_to_definition_of_kind(
11906 &mut self,
11907 kind: GotoDefinitionKind,
11908 split: bool,
11909 window: &mut Window,
11910 cx: &mut Context<Self>,
11911 ) -> Task<Result<Navigated>> {
11912 let Some(provider) = self.semantics_provider.clone() else {
11913 return Task::ready(Ok(Navigated::No));
11914 };
11915 let head = self.selections.newest::<usize>(cx).head();
11916 let buffer = self.buffer.read(cx);
11917 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11918 text_anchor
11919 } else {
11920 return Task::ready(Ok(Navigated::No));
11921 };
11922
11923 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11924 return Task::ready(Ok(Navigated::No));
11925 };
11926
11927 cx.spawn_in(window, |editor, mut cx| async move {
11928 let definitions = definitions.await?;
11929 let navigated = editor
11930 .update_in(&mut cx, |editor, window, cx| {
11931 editor.navigate_to_hover_links(
11932 Some(kind),
11933 definitions
11934 .into_iter()
11935 .filter(|location| {
11936 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11937 })
11938 .map(HoverLink::Text)
11939 .collect::<Vec<_>>(),
11940 split,
11941 window,
11942 cx,
11943 )
11944 })?
11945 .await?;
11946 anyhow::Ok(navigated)
11947 })
11948 }
11949
11950 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11951 let selection = self.selections.newest_anchor();
11952 let head = selection.head();
11953 let tail = selection.tail();
11954
11955 let Some((buffer, start_position)) =
11956 self.buffer.read(cx).text_anchor_for_position(head, cx)
11957 else {
11958 return;
11959 };
11960
11961 let end_position = if head != tail {
11962 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11963 return;
11964 };
11965 Some(pos)
11966 } else {
11967 None
11968 };
11969
11970 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11971 let url = if let Some(end_pos) = end_position {
11972 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11973 } else {
11974 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11975 };
11976
11977 if let Some(url) = url {
11978 editor.update(&mut cx, |_, cx| {
11979 cx.open_url(&url);
11980 })
11981 } else {
11982 Ok(())
11983 }
11984 });
11985
11986 url_finder.detach();
11987 }
11988
11989 pub fn open_selected_filename(
11990 &mut self,
11991 _: &OpenSelectedFilename,
11992 window: &mut Window,
11993 cx: &mut Context<Self>,
11994 ) {
11995 let Some(workspace) = self.workspace() else {
11996 return;
11997 };
11998
11999 let position = self.selections.newest_anchor().head();
12000
12001 let Some((buffer, buffer_position)) =
12002 self.buffer.read(cx).text_anchor_for_position(position, cx)
12003 else {
12004 return;
12005 };
12006
12007 let project = self.project.clone();
12008
12009 cx.spawn_in(window, |_, mut cx| async move {
12010 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
12011
12012 if let Some((_, path)) = result {
12013 workspace
12014 .update_in(&mut cx, |workspace, window, cx| {
12015 workspace.open_resolved_path(path, window, cx)
12016 })?
12017 .await?;
12018 }
12019 anyhow::Ok(())
12020 })
12021 .detach();
12022 }
12023
12024 pub(crate) fn navigate_to_hover_links(
12025 &mut self,
12026 kind: Option<GotoDefinitionKind>,
12027 mut definitions: Vec<HoverLink>,
12028 split: bool,
12029 window: &mut Window,
12030 cx: &mut Context<Editor>,
12031 ) -> Task<Result<Navigated>> {
12032 // If there is one definition, just open it directly
12033 if definitions.len() == 1 {
12034 let definition = definitions.pop().unwrap();
12035
12036 enum TargetTaskResult {
12037 Location(Option<Location>),
12038 AlreadyNavigated,
12039 }
12040
12041 let target_task = match definition {
12042 HoverLink::Text(link) => {
12043 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12044 }
12045 HoverLink::InlayHint(lsp_location, server_id) => {
12046 let computation =
12047 self.compute_target_location(lsp_location, server_id, window, cx);
12048 cx.background_spawn(async move {
12049 let location = computation.await?;
12050 Ok(TargetTaskResult::Location(location))
12051 })
12052 }
12053 HoverLink::Url(url) => {
12054 cx.open_url(&url);
12055 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12056 }
12057 HoverLink::File(path) => {
12058 if let Some(workspace) = self.workspace() {
12059 cx.spawn_in(window, |_, mut cx| async move {
12060 workspace
12061 .update_in(&mut cx, |workspace, window, cx| {
12062 workspace.open_resolved_path(path, window, cx)
12063 })?
12064 .await
12065 .map(|_| TargetTaskResult::AlreadyNavigated)
12066 })
12067 } else {
12068 Task::ready(Ok(TargetTaskResult::Location(None)))
12069 }
12070 }
12071 };
12072 cx.spawn_in(window, |editor, mut cx| async move {
12073 let target = match target_task.await.context("target resolution task")? {
12074 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12075 TargetTaskResult::Location(None) => return Ok(Navigated::No),
12076 TargetTaskResult::Location(Some(target)) => target,
12077 };
12078
12079 editor.update_in(&mut cx, |editor, window, cx| {
12080 let Some(workspace) = editor.workspace() else {
12081 return Navigated::No;
12082 };
12083 let pane = workspace.read(cx).active_pane().clone();
12084
12085 let range = target.range.to_point(target.buffer.read(cx));
12086 let range = editor.range_for_match(&range);
12087 let range = collapse_multiline_range(range);
12088
12089 if !split
12090 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12091 {
12092 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12093 } else {
12094 window.defer(cx, move |window, cx| {
12095 let target_editor: Entity<Self> =
12096 workspace.update(cx, |workspace, cx| {
12097 let pane = if split {
12098 workspace.adjacent_pane(window, cx)
12099 } else {
12100 workspace.active_pane().clone()
12101 };
12102
12103 workspace.open_project_item(
12104 pane,
12105 target.buffer.clone(),
12106 true,
12107 true,
12108 window,
12109 cx,
12110 )
12111 });
12112 target_editor.update(cx, |target_editor, cx| {
12113 // When selecting a definition in a different buffer, disable the nav history
12114 // to avoid creating a history entry at the previous cursor location.
12115 pane.update(cx, |pane, _| pane.disable_history());
12116 target_editor.go_to_singleton_buffer_range(range, window, cx);
12117 pane.update(cx, |pane, _| pane.enable_history());
12118 });
12119 });
12120 }
12121 Navigated::Yes
12122 })
12123 })
12124 } else if !definitions.is_empty() {
12125 cx.spawn_in(window, |editor, mut cx| async move {
12126 let (title, location_tasks, workspace) = editor
12127 .update_in(&mut cx, |editor, window, cx| {
12128 let tab_kind = match kind {
12129 Some(GotoDefinitionKind::Implementation) => "Implementations",
12130 _ => "Definitions",
12131 };
12132 let title = definitions
12133 .iter()
12134 .find_map(|definition| match definition {
12135 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12136 let buffer = origin.buffer.read(cx);
12137 format!(
12138 "{} for {}",
12139 tab_kind,
12140 buffer
12141 .text_for_range(origin.range.clone())
12142 .collect::<String>()
12143 )
12144 }),
12145 HoverLink::InlayHint(_, _) => None,
12146 HoverLink::Url(_) => None,
12147 HoverLink::File(_) => None,
12148 })
12149 .unwrap_or(tab_kind.to_string());
12150 let location_tasks = definitions
12151 .into_iter()
12152 .map(|definition| match definition {
12153 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12154 HoverLink::InlayHint(lsp_location, server_id) => editor
12155 .compute_target_location(lsp_location, server_id, window, cx),
12156 HoverLink::Url(_) => Task::ready(Ok(None)),
12157 HoverLink::File(_) => Task::ready(Ok(None)),
12158 })
12159 .collect::<Vec<_>>();
12160 (title, location_tasks, editor.workspace().clone())
12161 })
12162 .context("location tasks preparation")?;
12163
12164 let locations = future::join_all(location_tasks)
12165 .await
12166 .into_iter()
12167 .filter_map(|location| location.transpose())
12168 .collect::<Result<_>>()
12169 .context("location tasks")?;
12170
12171 let Some(workspace) = workspace else {
12172 return Ok(Navigated::No);
12173 };
12174 let opened = workspace
12175 .update_in(&mut cx, |workspace, window, cx| {
12176 Self::open_locations_in_multibuffer(
12177 workspace,
12178 locations,
12179 title,
12180 split,
12181 MultibufferSelectionMode::First,
12182 window,
12183 cx,
12184 )
12185 })
12186 .ok();
12187
12188 anyhow::Ok(Navigated::from_bool(opened.is_some()))
12189 })
12190 } else {
12191 Task::ready(Ok(Navigated::No))
12192 }
12193 }
12194
12195 fn compute_target_location(
12196 &self,
12197 lsp_location: lsp::Location,
12198 server_id: LanguageServerId,
12199 window: &mut Window,
12200 cx: &mut Context<Self>,
12201 ) -> Task<anyhow::Result<Option<Location>>> {
12202 let Some(project) = self.project.clone() else {
12203 return Task::ready(Ok(None));
12204 };
12205
12206 cx.spawn_in(window, move |editor, mut cx| async move {
12207 let location_task = editor.update(&mut cx, |_, cx| {
12208 project.update(cx, |project, cx| {
12209 let language_server_name = project
12210 .language_server_statuses(cx)
12211 .find(|(id, _)| server_id == *id)
12212 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12213 language_server_name.map(|language_server_name| {
12214 project.open_local_buffer_via_lsp(
12215 lsp_location.uri.clone(),
12216 server_id,
12217 language_server_name,
12218 cx,
12219 )
12220 })
12221 })
12222 })?;
12223 let location = match location_task {
12224 Some(task) => Some({
12225 let target_buffer_handle = task.await.context("open local buffer")?;
12226 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12227 let target_start = target_buffer
12228 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12229 let target_end = target_buffer
12230 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12231 target_buffer.anchor_after(target_start)
12232 ..target_buffer.anchor_before(target_end)
12233 })?;
12234 Location {
12235 buffer: target_buffer_handle,
12236 range,
12237 }
12238 }),
12239 None => None,
12240 };
12241 Ok(location)
12242 })
12243 }
12244
12245 pub fn find_all_references(
12246 &mut self,
12247 _: &FindAllReferences,
12248 window: &mut Window,
12249 cx: &mut Context<Self>,
12250 ) -> Option<Task<Result<Navigated>>> {
12251 let selection = self.selections.newest::<usize>(cx);
12252 let multi_buffer = self.buffer.read(cx);
12253 let head = selection.head();
12254
12255 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12256 let head_anchor = multi_buffer_snapshot.anchor_at(
12257 head,
12258 if head < selection.tail() {
12259 Bias::Right
12260 } else {
12261 Bias::Left
12262 },
12263 );
12264
12265 match self
12266 .find_all_references_task_sources
12267 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12268 {
12269 Ok(_) => {
12270 log::info!(
12271 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12272 );
12273 return None;
12274 }
12275 Err(i) => {
12276 self.find_all_references_task_sources.insert(i, head_anchor);
12277 }
12278 }
12279
12280 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12281 let workspace = self.workspace()?;
12282 let project = workspace.read(cx).project().clone();
12283 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12284 Some(cx.spawn_in(window, |editor, mut cx| async move {
12285 let _cleanup = defer({
12286 let mut cx = cx.clone();
12287 move || {
12288 let _ = editor.update(&mut cx, |editor, _| {
12289 if let Ok(i) =
12290 editor
12291 .find_all_references_task_sources
12292 .binary_search_by(|anchor| {
12293 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12294 })
12295 {
12296 editor.find_all_references_task_sources.remove(i);
12297 }
12298 });
12299 }
12300 });
12301
12302 let locations = references.await?;
12303 if locations.is_empty() {
12304 return anyhow::Ok(Navigated::No);
12305 }
12306
12307 workspace.update_in(&mut cx, |workspace, window, cx| {
12308 let title = locations
12309 .first()
12310 .as_ref()
12311 .map(|location| {
12312 let buffer = location.buffer.read(cx);
12313 format!(
12314 "References to `{}`",
12315 buffer
12316 .text_for_range(location.range.clone())
12317 .collect::<String>()
12318 )
12319 })
12320 .unwrap();
12321 Self::open_locations_in_multibuffer(
12322 workspace,
12323 locations,
12324 title,
12325 false,
12326 MultibufferSelectionMode::First,
12327 window,
12328 cx,
12329 );
12330 Navigated::Yes
12331 })
12332 }))
12333 }
12334
12335 /// Opens a multibuffer with the given project locations in it
12336 pub fn open_locations_in_multibuffer(
12337 workspace: &mut Workspace,
12338 mut locations: Vec<Location>,
12339 title: String,
12340 split: bool,
12341 multibuffer_selection_mode: MultibufferSelectionMode,
12342 window: &mut Window,
12343 cx: &mut Context<Workspace>,
12344 ) {
12345 // If there are multiple definitions, open them in a multibuffer
12346 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12347 let mut locations = locations.into_iter().peekable();
12348 let mut ranges = Vec::new();
12349 let capability = workspace.project().read(cx).capability();
12350
12351 let excerpt_buffer = cx.new(|cx| {
12352 let mut multibuffer = MultiBuffer::new(capability);
12353 while let Some(location) = locations.next() {
12354 let buffer = location.buffer.read(cx);
12355 let mut ranges_for_buffer = Vec::new();
12356 let range = location.range.to_offset(buffer);
12357 ranges_for_buffer.push(range.clone());
12358
12359 while let Some(next_location) = locations.peek() {
12360 if next_location.buffer == location.buffer {
12361 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12362 locations.next();
12363 } else {
12364 break;
12365 }
12366 }
12367
12368 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12369 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12370 location.buffer.clone(),
12371 ranges_for_buffer,
12372 DEFAULT_MULTIBUFFER_CONTEXT,
12373 cx,
12374 ))
12375 }
12376
12377 multibuffer.with_title(title)
12378 });
12379
12380 let editor = cx.new(|cx| {
12381 Editor::for_multibuffer(
12382 excerpt_buffer,
12383 Some(workspace.project().clone()),
12384 true,
12385 window,
12386 cx,
12387 )
12388 });
12389 editor.update(cx, |editor, cx| {
12390 match multibuffer_selection_mode {
12391 MultibufferSelectionMode::First => {
12392 if let Some(first_range) = ranges.first() {
12393 editor.change_selections(None, window, cx, |selections| {
12394 selections.clear_disjoint();
12395 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12396 });
12397 }
12398 editor.highlight_background::<Self>(
12399 &ranges,
12400 |theme| theme.editor_highlighted_line_background,
12401 cx,
12402 );
12403 }
12404 MultibufferSelectionMode::All => {
12405 editor.change_selections(None, window, cx, |selections| {
12406 selections.clear_disjoint();
12407 selections.select_anchor_ranges(ranges);
12408 });
12409 }
12410 }
12411 editor.register_buffers_with_language_servers(cx);
12412 });
12413
12414 let item = Box::new(editor);
12415 let item_id = item.item_id();
12416
12417 if split {
12418 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12419 } else {
12420 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12421 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12422 pane.close_current_preview_item(window, cx)
12423 } else {
12424 None
12425 }
12426 });
12427 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12428 }
12429 workspace.active_pane().update(cx, |pane, cx| {
12430 pane.set_preview_item_id(Some(item_id), cx);
12431 });
12432 }
12433
12434 pub fn rename(
12435 &mut self,
12436 _: &Rename,
12437 window: &mut Window,
12438 cx: &mut Context<Self>,
12439 ) -> Option<Task<Result<()>>> {
12440 use language::ToOffset as _;
12441
12442 let provider = self.semantics_provider.clone()?;
12443 let selection = self.selections.newest_anchor().clone();
12444 let (cursor_buffer, cursor_buffer_position) = self
12445 .buffer
12446 .read(cx)
12447 .text_anchor_for_position(selection.head(), cx)?;
12448 let (tail_buffer, cursor_buffer_position_end) = self
12449 .buffer
12450 .read(cx)
12451 .text_anchor_for_position(selection.tail(), cx)?;
12452 if tail_buffer != cursor_buffer {
12453 return None;
12454 }
12455
12456 let snapshot = cursor_buffer.read(cx).snapshot();
12457 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12458 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12459 let prepare_rename = provider
12460 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12461 .unwrap_or_else(|| Task::ready(Ok(None)));
12462 drop(snapshot);
12463
12464 Some(cx.spawn_in(window, |this, mut cx| async move {
12465 let rename_range = if let Some(range) = prepare_rename.await? {
12466 Some(range)
12467 } else {
12468 this.update(&mut cx, |this, cx| {
12469 let buffer = this.buffer.read(cx).snapshot(cx);
12470 let mut buffer_highlights = this
12471 .document_highlights_for_position(selection.head(), &buffer)
12472 .filter(|highlight| {
12473 highlight.start.excerpt_id == selection.head().excerpt_id
12474 && highlight.end.excerpt_id == selection.head().excerpt_id
12475 });
12476 buffer_highlights
12477 .next()
12478 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12479 })?
12480 };
12481 if let Some(rename_range) = rename_range {
12482 this.update_in(&mut cx, |this, window, cx| {
12483 let snapshot = cursor_buffer.read(cx).snapshot();
12484 let rename_buffer_range = rename_range.to_offset(&snapshot);
12485 let cursor_offset_in_rename_range =
12486 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12487 let cursor_offset_in_rename_range_end =
12488 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12489
12490 this.take_rename(false, window, cx);
12491 let buffer = this.buffer.read(cx).read(cx);
12492 let cursor_offset = selection.head().to_offset(&buffer);
12493 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12494 let rename_end = rename_start + rename_buffer_range.len();
12495 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12496 let mut old_highlight_id = None;
12497 let old_name: Arc<str> = buffer
12498 .chunks(rename_start..rename_end, true)
12499 .map(|chunk| {
12500 if old_highlight_id.is_none() {
12501 old_highlight_id = chunk.syntax_highlight_id;
12502 }
12503 chunk.text
12504 })
12505 .collect::<String>()
12506 .into();
12507
12508 drop(buffer);
12509
12510 // Position the selection in the rename editor so that it matches the current selection.
12511 this.show_local_selections = false;
12512 let rename_editor = cx.new(|cx| {
12513 let mut editor = Editor::single_line(window, cx);
12514 editor.buffer.update(cx, |buffer, cx| {
12515 buffer.edit([(0..0, old_name.clone())], None, cx)
12516 });
12517 let rename_selection_range = match cursor_offset_in_rename_range
12518 .cmp(&cursor_offset_in_rename_range_end)
12519 {
12520 Ordering::Equal => {
12521 editor.select_all(&SelectAll, window, cx);
12522 return editor;
12523 }
12524 Ordering::Less => {
12525 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12526 }
12527 Ordering::Greater => {
12528 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12529 }
12530 };
12531 if rename_selection_range.end > old_name.len() {
12532 editor.select_all(&SelectAll, window, cx);
12533 } else {
12534 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12535 s.select_ranges([rename_selection_range]);
12536 });
12537 }
12538 editor
12539 });
12540 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12541 if e == &EditorEvent::Focused {
12542 cx.emit(EditorEvent::FocusedIn)
12543 }
12544 })
12545 .detach();
12546
12547 let write_highlights =
12548 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12549 let read_highlights =
12550 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12551 let ranges = write_highlights
12552 .iter()
12553 .flat_map(|(_, ranges)| ranges.iter())
12554 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12555 .cloned()
12556 .collect();
12557
12558 this.highlight_text::<Rename>(
12559 ranges,
12560 HighlightStyle {
12561 fade_out: Some(0.6),
12562 ..Default::default()
12563 },
12564 cx,
12565 );
12566 let rename_focus_handle = rename_editor.focus_handle(cx);
12567 window.focus(&rename_focus_handle);
12568 let block_id = this.insert_blocks(
12569 [BlockProperties {
12570 style: BlockStyle::Flex,
12571 placement: BlockPlacement::Below(range.start),
12572 height: 1,
12573 render: Arc::new({
12574 let rename_editor = rename_editor.clone();
12575 move |cx: &mut BlockContext| {
12576 let mut text_style = cx.editor_style.text.clone();
12577 if let Some(highlight_style) = old_highlight_id
12578 .and_then(|h| h.style(&cx.editor_style.syntax))
12579 {
12580 text_style = text_style.highlight(highlight_style);
12581 }
12582 div()
12583 .block_mouse_down()
12584 .pl(cx.anchor_x)
12585 .child(EditorElement::new(
12586 &rename_editor,
12587 EditorStyle {
12588 background: cx.theme().system().transparent,
12589 local_player: cx.editor_style.local_player,
12590 text: text_style,
12591 scrollbar_width: cx.editor_style.scrollbar_width,
12592 syntax: cx.editor_style.syntax.clone(),
12593 status: cx.editor_style.status.clone(),
12594 inlay_hints_style: HighlightStyle {
12595 font_weight: Some(FontWeight::BOLD),
12596 ..make_inlay_hints_style(cx.app)
12597 },
12598 inline_completion_styles: make_suggestion_styles(
12599 cx.app,
12600 ),
12601 ..EditorStyle::default()
12602 },
12603 ))
12604 .into_any_element()
12605 }
12606 }),
12607 priority: 0,
12608 }],
12609 Some(Autoscroll::fit()),
12610 cx,
12611 )[0];
12612 this.pending_rename = Some(RenameState {
12613 range,
12614 old_name,
12615 editor: rename_editor,
12616 block_id,
12617 });
12618 })?;
12619 }
12620
12621 Ok(())
12622 }))
12623 }
12624
12625 pub fn confirm_rename(
12626 &mut self,
12627 _: &ConfirmRename,
12628 window: &mut Window,
12629 cx: &mut Context<Self>,
12630 ) -> Option<Task<Result<()>>> {
12631 let rename = self.take_rename(false, window, cx)?;
12632 let workspace = self.workspace()?.downgrade();
12633 let (buffer, start) = self
12634 .buffer
12635 .read(cx)
12636 .text_anchor_for_position(rename.range.start, cx)?;
12637 let (end_buffer, _) = self
12638 .buffer
12639 .read(cx)
12640 .text_anchor_for_position(rename.range.end, cx)?;
12641 if buffer != end_buffer {
12642 return None;
12643 }
12644
12645 let old_name = rename.old_name;
12646 let new_name = rename.editor.read(cx).text(cx);
12647
12648 let rename = self.semantics_provider.as_ref()?.perform_rename(
12649 &buffer,
12650 start,
12651 new_name.clone(),
12652 cx,
12653 )?;
12654
12655 Some(cx.spawn_in(window, |editor, mut cx| async move {
12656 let project_transaction = rename.await?;
12657 Self::open_project_transaction(
12658 &editor,
12659 workspace,
12660 project_transaction,
12661 format!("Rename: {} → {}", old_name, new_name),
12662 cx.clone(),
12663 )
12664 .await?;
12665
12666 editor.update(&mut cx, |editor, cx| {
12667 editor.refresh_document_highlights(cx);
12668 })?;
12669 Ok(())
12670 }))
12671 }
12672
12673 fn take_rename(
12674 &mut self,
12675 moving_cursor: bool,
12676 window: &mut Window,
12677 cx: &mut Context<Self>,
12678 ) -> Option<RenameState> {
12679 let rename = self.pending_rename.take()?;
12680 if rename.editor.focus_handle(cx).is_focused(window) {
12681 window.focus(&self.focus_handle);
12682 }
12683
12684 self.remove_blocks(
12685 [rename.block_id].into_iter().collect(),
12686 Some(Autoscroll::fit()),
12687 cx,
12688 );
12689 self.clear_highlights::<Rename>(cx);
12690 self.show_local_selections = true;
12691
12692 if moving_cursor {
12693 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12694 editor.selections.newest::<usize>(cx).head()
12695 });
12696
12697 // Update the selection to match the position of the selection inside
12698 // the rename editor.
12699 let snapshot = self.buffer.read(cx).read(cx);
12700 let rename_range = rename.range.to_offset(&snapshot);
12701 let cursor_in_editor = snapshot
12702 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12703 .min(rename_range.end);
12704 drop(snapshot);
12705
12706 self.change_selections(None, window, cx, |s| {
12707 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12708 });
12709 } else {
12710 self.refresh_document_highlights(cx);
12711 }
12712
12713 Some(rename)
12714 }
12715
12716 pub fn pending_rename(&self) -> Option<&RenameState> {
12717 self.pending_rename.as_ref()
12718 }
12719
12720 fn format(
12721 &mut self,
12722 _: &Format,
12723 window: &mut Window,
12724 cx: &mut Context<Self>,
12725 ) -> Option<Task<Result<()>>> {
12726 let project = match &self.project {
12727 Some(project) => project.clone(),
12728 None => return None,
12729 };
12730
12731 Some(self.perform_format(
12732 project,
12733 FormatTrigger::Manual,
12734 FormatTarget::Buffers,
12735 window,
12736 cx,
12737 ))
12738 }
12739
12740 fn format_selections(
12741 &mut self,
12742 _: &FormatSelections,
12743 window: &mut Window,
12744 cx: &mut Context<Self>,
12745 ) -> Option<Task<Result<()>>> {
12746 let project = match &self.project {
12747 Some(project) => project.clone(),
12748 None => return None,
12749 };
12750
12751 let ranges = self
12752 .selections
12753 .all_adjusted(cx)
12754 .into_iter()
12755 .map(|selection| selection.range())
12756 .collect_vec();
12757
12758 Some(self.perform_format(
12759 project,
12760 FormatTrigger::Manual,
12761 FormatTarget::Ranges(ranges),
12762 window,
12763 cx,
12764 ))
12765 }
12766
12767 fn perform_format(
12768 &mut self,
12769 project: Entity<Project>,
12770 trigger: FormatTrigger,
12771 target: FormatTarget,
12772 window: &mut Window,
12773 cx: &mut Context<Self>,
12774 ) -> Task<Result<()>> {
12775 let buffer = self.buffer.clone();
12776 let (buffers, target) = match target {
12777 FormatTarget::Buffers => {
12778 let mut buffers = buffer.read(cx).all_buffers();
12779 if trigger == FormatTrigger::Save {
12780 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12781 }
12782 (buffers, LspFormatTarget::Buffers)
12783 }
12784 FormatTarget::Ranges(selection_ranges) => {
12785 let multi_buffer = buffer.read(cx);
12786 let snapshot = multi_buffer.read(cx);
12787 let mut buffers = HashSet::default();
12788 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12789 BTreeMap::new();
12790 for selection_range in selection_ranges {
12791 for (buffer, buffer_range, _) in
12792 snapshot.range_to_buffer_ranges(selection_range)
12793 {
12794 let buffer_id = buffer.remote_id();
12795 let start = buffer.anchor_before(buffer_range.start);
12796 let end = buffer.anchor_after(buffer_range.end);
12797 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12798 buffer_id_to_ranges
12799 .entry(buffer_id)
12800 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12801 .or_insert_with(|| vec![start..end]);
12802 }
12803 }
12804 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12805 }
12806 };
12807
12808 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12809 let format = project.update(cx, |project, cx| {
12810 project.format(buffers, target, true, trigger, cx)
12811 });
12812
12813 cx.spawn_in(window, |_, mut cx| async move {
12814 let transaction = futures::select_biased! {
12815 () = timeout => {
12816 log::warn!("timed out waiting for formatting");
12817 None
12818 }
12819 transaction = format.log_err().fuse() => transaction,
12820 };
12821
12822 buffer
12823 .update(&mut cx, |buffer, cx| {
12824 if let Some(transaction) = transaction {
12825 if !buffer.is_singleton() {
12826 buffer.push_transaction(&transaction.0, cx);
12827 }
12828 }
12829 cx.notify();
12830 })
12831 .ok();
12832
12833 Ok(())
12834 })
12835 }
12836
12837 fn organize_imports(
12838 &mut self,
12839 _: &OrganizeImports,
12840 window: &mut Window,
12841 cx: &mut Context<Self>,
12842 ) -> Option<Task<Result<()>>> {
12843 let project = match &self.project {
12844 Some(project) => project.clone(),
12845 None => return None,
12846 };
12847 Some(self.perform_code_action_kind(
12848 project,
12849 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12850 window,
12851 cx,
12852 ))
12853 }
12854
12855 fn perform_code_action_kind(
12856 &mut self,
12857 project: Entity<Project>,
12858 kind: CodeActionKind,
12859 window: &mut Window,
12860 cx: &mut Context<Self>,
12861 ) -> Task<Result<()>> {
12862 let buffer = self.buffer.clone();
12863 let buffers = buffer.read(cx).all_buffers();
12864 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12865 let apply_action = project.update(cx, |project, cx| {
12866 project.apply_code_action_kind(buffers, kind, true, cx)
12867 });
12868 cx.spawn_in(window, |_, mut cx| async move {
12869 let transaction = futures::select_biased! {
12870 () = timeout => {
12871 log::warn!("timed out waiting for executing code action");
12872 None
12873 }
12874 transaction = apply_action.log_err().fuse() => transaction,
12875 };
12876 buffer
12877 .update(&mut cx, |buffer, cx| {
12878 // check if we need this
12879 if let Some(transaction) = transaction {
12880 if !buffer.is_singleton() {
12881 buffer.push_transaction(&transaction.0, cx);
12882 }
12883 }
12884 cx.notify();
12885 })
12886 .ok();
12887 Ok(())
12888 })
12889 }
12890
12891 fn restart_language_server(
12892 &mut self,
12893 _: &RestartLanguageServer,
12894 _: &mut Window,
12895 cx: &mut Context<Self>,
12896 ) {
12897 if let Some(project) = self.project.clone() {
12898 self.buffer.update(cx, |multi_buffer, cx| {
12899 project.update(cx, |project, cx| {
12900 project.restart_language_servers_for_buffers(
12901 multi_buffer.all_buffers().into_iter().collect(),
12902 cx,
12903 );
12904 });
12905 })
12906 }
12907 }
12908
12909 fn cancel_language_server_work(
12910 workspace: &mut Workspace,
12911 _: &actions::CancelLanguageServerWork,
12912 _: &mut Window,
12913 cx: &mut Context<Workspace>,
12914 ) {
12915 let project = workspace.project();
12916 let buffers = workspace
12917 .active_item(cx)
12918 .and_then(|item| item.act_as::<Editor>(cx))
12919 .map_or(HashSet::default(), |editor| {
12920 editor.read(cx).buffer.read(cx).all_buffers()
12921 });
12922 project.update(cx, |project, cx| {
12923 project.cancel_language_server_work_for_buffers(buffers, cx);
12924 });
12925 }
12926
12927 fn show_character_palette(
12928 &mut self,
12929 _: &ShowCharacterPalette,
12930 window: &mut Window,
12931 _: &mut Context<Self>,
12932 ) {
12933 window.show_character_palette();
12934 }
12935
12936 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12937 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12938 let buffer = self.buffer.read(cx).snapshot(cx);
12939 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12940 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12941 let is_valid = buffer
12942 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12943 .any(|entry| {
12944 entry.diagnostic.is_primary
12945 && !entry.range.is_empty()
12946 && entry.range.start == primary_range_start
12947 && entry.diagnostic.message == active_diagnostics.primary_message
12948 });
12949
12950 if is_valid != active_diagnostics.is_valid {
12951 active_diagnostics.is_valid = is_valid;
12952 if is_valid {
12953 let mut new_styles = HashMap::default();
12954 for (block_id, diagnostic) in &active_diagnostics.blocks {
12955 new_styles.insert(
12956 *block_id,
12957 diagnostic_block_renderer(diagnostic.clone(), None, true),
12958 );
12959 }
12960 self.display_map.update(cx, |display_map, _cx| {
12961 display_map.replace_blocks(new_styles);
12962 });
12963 } else {
12964 self.dismiss_diagnostics(cx);
12965 }
12966 }
12967 }
12968 }
12969
12970 fn activate_diagnostics(
12971 &mut self,
12972 buffer_id: BufferId,
12973 group_id: usize,
12974 window: &mut Window,
12975 cx: &mut Context<Self>,
12976 ) {
12977 self.dismiss_diagnostics(cx);
12978 let snapshot = self.snapshot(window, cx);
12979 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12980 let buffer = self.buffer.read(cx).snapshot(cx);
12981
12982 let mut primary_range = None;
12983 let mut primary_message = None;
12984 let diagnostic_group = buffer
12985 .diagnostic_group(buffer_id, group_id)
12986 .filter_map(|entry| {
12987 let start = entry.range.start;
12988 let end = entry.range.end;
12989 if snapshot.is_line_folded(MultiBufferRow(start.row))
12990 && (start.row == end.row
12991 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12992 {
12993 return None;
12994 }
12995 if entry.diagnostic.is_primary {
12996 primary_range = Some(entry.range.clone());
12997 primary_message = Some(entry.diagnostic.message.clone());
12998 }
12999 Some(entry)
13000 })
13001 .collect::<Vec<_>>();
13002 let primary_range = primary_range?;
13003 let primary_message = primary_message?;
13004
13005 let blocks = display_map
13006 .insert_blocks(
13007 diagnostic_group.iter().map(|entry| {
13008 let diagnostic = entry.diagnostic.clone();
13009 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13010 BlockProperties {
13011 style: BlockStyle::Fixed,
13012 placement: BlockPlacement::Below(
13013 buffer.anchor_after(entry.range.start),
13014 ),
13015 height: message_height,
13016 render: diagnostic_block_renderer(diagnostic, None, true),
13017 priority: 0,
13018 }
13019 }),
13020 cx,
13021 )
13022 .into_iter()
13023 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13024 .collect();
13025
13026 Some(ActiveDiagnosticGroup {
13027 primary_range: buffer.anchor_before(primary_range.start)
13028 ..buffer.anchor_after(primary_range.end),
13029 primary_message,
13030 group_id,
13031 blocks,
13032 is_valid: true,
13033 })
13034 });
13035 }
13036
13037 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13038 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13039 self.display_map.update(cx, |display_map, cx| {
13040 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13041 });
13042 cx.notify();
13043 }
13044 }
13045
13046 /// Disable inline diagnostics rendering for this editor.
13047 pub fn disable_inline_diagnostics(&mut self) {
13048 self.inline_diagnostics_enabled = false;
13049 self.inline_diagnostics_update = Task::ready(());
13050 self.inline_diagnostics.clear();
13051 }
13052
13053 pub fn inline_diagnostics_enabled(&self) -> bool {
13054 self.inline_diagnostics_enabled
13055 }
13056
13057 pub fn show_inline_diagnostics(&self) -> bool {
13058 self.show_inline_diagnostics
13059 }
13060
13061 pub fn toggle_inline_diagnostics(
13062 &mut self,
13063 _: &ToggleInlineDiagnostics,
13064 window: &mut Window,
13065 cx: &mut Context<'_, Editor>,
13066 ) {
13067 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13068 self.refresh_inline_diagnostics(false, window, cx);
13069 }
13070
13071 fn refresh_inline_diagnostics(
13072 &mut self,
13073 debounce: bool,
13074 window: &mut Window,
13075 cx: &mut Context<Self>,
13076 ) {
13077 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13078 self.inline_diagnostics_update = Task::ready(());
13079 self.inline_diagnostics.clear();
13080 return;
13081 }
13082
13083 let debounce_ms = ProjectSettings::get_global(cx)
13084 .diagnostics
13085 .inline
13086 .update_debounce_ms;
13087 let debounce = if debounce && debounce_ms > 0 {
13088 Some(Duration::from_millis(debounce_ms))
13089 } else {
13090 None
13091 };
13092 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
13093 if let Some(debounce) = debounce {
13094 cx.background_executor().timer(debounce).await;
13095 }
13096 let Some(snapshot) = editor
13097 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13098 .ok()
13099 else {
13100 return;
13101 };
13102
13103 let new_inline_diagnostics = cx
13104 .background_spawn(async move {
13105 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13106 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13107 let message = diagnostic_entry
13108 .diagnostic
13109 .message
13110 .split_once('\n')
13111 .map(|(line, _)| line)
13112 .map(SharedString::new)
13113 .unwrap_or_else(|| {
13114 SharedString::from(diagnostic_entry.diagnostic.message)
13115 });
13116 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13117 let (Ok(i) | Err(i)) = inline_diagnostics
13118 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13119 inline_diagnostics.insert(
13120 i,
13121 (
13122 start_anchor,
13123 InlineDiagnostic {
13124 message,
13125 group_id: diagnostic_entry.diagnostic.group_id,
13126 start: diagnostic_entry.range.start.to_point(&snapshot),
13127 is_primary: diagnostic_entry.diagnostic.is_primary,
13128 severity: diagnostic_entry.diagnostic.severity,
13129 },
13130 ),
13131 );
13132 }
13133 inline_diagnostics
13134 })
13135 .await;
13136
13137 editor
13138 .update(&mut cx, |editor, cx| {
13139 editor.inline_diagnostics = new_inline_diagnostics;
13140 cx.notify();
13141 })
13142 .ok();
13143 });
13144 }
13145
13146 pub fn set_selections_from_remote(
13147 &mut self,
13148 selections: Vec<Selection<Anchor>>,
13149 pending_selection: Option<Selection<Anchor>>,
13150 window: &mut Window,
13151 cx: &mut Context<Self>,
13152 ) {
13153 let old_cursor_position = self.selections.newest_anchor().head();
13154 self.selections.change_with(cx, |s| {
13155 s.select_anchors(selections);
13156 if let Some(pending_selection) = pending_selection {
13157 s.set_pending(pending_selection, SelectMode::Character);
13158 } else {
13159 s.clear_pending();
13160 }
13161 });
13162 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13163 }
13164
13165 fn push_to_selection_history(&mut self) {
13166 self.selection_history.push(SelectionHistoryEntry {
13167 selections: self.selections.disjoint_anchors(),
13168 select_next_state: self.select_next_state.clone(),
13169 select_prev_state: self.select_prev_state.clone(),
13170 add_selections_state: self.add_selections_state.clone(),
13171 });
13172 }
13173
13174 pub fn transact(
13175 &mut self,
13176 window: &mut Window,
13177 cx: &mut Context<Self>,
13178 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13179 ) -> Option<TransactionId> {
13180 self.start_transaction_at(Instant::now(), window, cx);
13181 update(self, window, cx);
13182 self.end_transaction_at(Instant::now(), cx)
13183 }
13184
13185 pub fn start_transaction_at(
13186 &mut self,
13187 now: Instant,
13188 window: &mut Window,
13189 cx: &mut Context<Self>,
13190 ) {
13191 self.end_selection(window, cx);
13192 if let Some(tx_id) = self
13193 .buffer
13194 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13195 {
13196 self.selection_history
13197 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13198 cx.emit(EditorEvent::TransactionBegun {
13199 transaction_id: tx_id,
13200 })
13201 }
13202 }
13203
13204 pub fn end_transaction_at(
13205 &mut self,
13206 now: Instant,
13207 cx: &mut Context<Self>,
13208 ) -> Option<TransactionId> {
13209 if let Some(transaction_id) = self
13210 .buffer
13211 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13212 {
13213 if let Some((_, end_selections)) =
13214 self.selection_history.transaction_mut(transaction_id)
13215 {
13216 *end_selections = Some(self.selections.disjoint_anchors());
13217 } else {
13218 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13219 }
13220
13221 cx.emit(EditorEvent::Edited { transaction_id });
13222 Some(transaction_id)
13223 } else {
13224 None
13225 }
13226 }
13227
13228 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13229 if self.selection_mark_mode {
13230 self.change_selections(None, window, cx, |s| {
13231 s.move_with(|_, sel| {
13232 sel.collapse_to(sel.head(), SelectionGoal::None);
13233 });
13234 })
13235 }
13236 self.selection_mark_mode = true;
13237 cx.notify();
13238 }
13239
13240 pub fn swap_selection_ends(
13241 &mut self,
13242 _: &actions::SwapSelectionEnds,
13243 window: &mut Window,
13244 cx: &mut Context<Self>,
13245 ) {
13246 self.change_selections(None, window, cx, |s| {
13247 s.move_with(|_, sel| {
13248 if sel.start != sel.end {
13249 sel.reversed = !sel.reversed
13250 }
13251 });
13252 });
13253 self.request_autoscroll(Autoscroll::newest(), cx);
13254 cx.notify();
13255 }
13256
13257 pub fn toggle_fold(
13258 &mut self,
13259 _: &actions::ToggleFold,
13260 window: &mut Window,
13261 cx: &mut Context<Self>,
13262 ) {
13263 if self.is_singleton(cx) {
13264 let selection = self.selections.newest::<Point>(cx);
13265
13266 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13267 let range = if selection.is_empty() {
13268 let point = selection.head().to_display_point(&display_map);
13269 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13270 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13271 .to_point(&display_map);
13272 start..end
13273 } else {
13274 selection.range()
13275 };
13276 if display_map.folds_in_range(range).next().is_some() {
13277 self.unfold_lines(&Default::default(), window, cx)
13278 } else {
13279 self.fold(&Default::default(), window, cx)
13280 }
13281 } else {
13282 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13283 let buffer_ids: HashSet<_> = self
13284 .selections
13285 .disjoint_anchor_ranges()
13286 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13287 .collect();
13288
13289 let should_unfold = buffer_ids
13290 .iter()
13291 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13292
13293 for buffer_id in buffer_ids {
13294 if should_unfold {
13295 self.unfold_buffer(buffer_id, cx);
13296 } else {
13297 self.fold_buffer(buffer_id, cx);
13298 }
13299 }
13300 }
13301 }
13302
13303 pub fn toggle_fold_recursive(
13304 &mut self,
13305 _: &actions::ToggleFoldRecursive,
13306 window: &mut Window,
13307 cx: &mut Context<Self>,
13308 ) {
13309 let selection = self.selections.newest::<Point>(cx);
13310
13311 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13312 let range = if selection.is_empty() {
13313 let point = selection.head().to_display_point(&display_map);
13314 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13315 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13316 .to_point(&display_map);
13317 start..end
13318 } else {
13319 selection.range()
13320 };
13321 if display_map.folds_in_range(range).next().is_some() {
13322 self.unfold_recursive(&Default::default(), window, cx)
13323 } else {
13324 self.fold_recursive(&Default::default(), window, cx)
13325 }
13326 }
13327
13328 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13329 if self.is_singleton(cx) {
13330 let mut to_fold = Vec::new();
13331 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13332 let selections = self.selections.all_adjusted(cx);
13333
13334 for selection in selections {
13335 let range = selection.range().sorted();
13336 let buffer_start_row = range.start.row;
13337
13338 if range.start.row != range.end.row {
13339 let mut found = false;
13340 let mut row = range.start.row;
13341 while row <= range.end.row {
13342 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13343 {
13344 found = true;
13345 row = crease.range().end.row + 1;
13346 to_fold.push(crease);
13347 } else {
13348 row += 1
13349 }
13350 }
13351 if found {
13352 continue;
13353 }
13354 }
13355
13356 for row in (0..=range.start.row).rev() {
13357 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13358 if crease.range().end.row >= buffer_start_row {
13359 to_fold.push(crease);
13360 if row <= range.start.row {
13361 break;
13362 }
13363 }
13364 }
13365 }
13366 }
13367
13368 self.fold_creases(to_fold, true, window, cx);
13369 } else {
13370 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13371 let buffer_ids = self
13372 .selections
13373 .disjoint_anchor_ranges()
13374 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13375 .collect::<HashSet<_>>();
13376 for buffer_id in buffer_ids {
13377 self.fold_buffer(buffer_id, cx);
13378 }
13379 }
13380 }
13381
13382 fn fold_at_level(
13383 &mut self,
13384 fold_at: &FoldAtLevel,
13385 window: &mut Window,
13386 cx: &mut Context<Self>,
13387 ) {
13388 if !self.buffer.read(cx).is_singleton() {
13389 return;
13390 }
13391
13392 let fold_at_level = fold_at.0;
13393 let snapshot = self.buffer.read(cx).snapshot(cx);
13394 let mut to_fold = Vec::new();
13395 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13396
13397 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13398 while start_row < end_row {
13399 match self
13400 .snapshot(window, cx)
13401 .crease_for_buffer_row(MultiBufferRow(start_row))
13402 {
13403 Some(crease) => {
13404 let nested_start_row = crease.range().start.row + 1;
13405 let nested_end_row = crease.range().end.row;
13406
13407 if current_level < fold_at_level {
13408 stack.push((nested_start_row, nested_end_row, current_level + 1));
13409 } else if current_level == fold_at_level {
13410 to_fold.push(crease);
13411 }
13412
13413 start_row = nested_end_row + 1;
13414 }
13415 None => start_row += 1,
13416 }
13417 }
13418 }
13419
13420 self.fold_creases(to_fold, true, window, cx);
13421 }
13422
13423 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13424 if self.buffer.read(cx).is_singleton() {
13425 let mut fold_ranges = Vec::new();
13426 let snapshot = self.buffer.read(cx).snapshot(cx);
13427
13428 for row in 0..snapshot.max_row().0 {
13429 if let Some(foldable_range) = self
13430 .snapshot(window, cx)
13431 .crease_for_buffer_row(MultiBufferRow(row))
13432 {
13433 fold_ranges.push(foldable_range);
13434 }
13435 }
13436
13437 self.fold_creases(fold_ranges, true, window, cx);
13438 } else {
13439 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13440 editor
13441 .update_in(&mut cx, |editor, _, cx| {
13442 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13443 editor.fold_buffer(buffer_id, cx);
13444 }
13445 })
13446 .ok();
13447 });
13448 }
13449 }
13450
13451 pub fn fold_function_bodies(
13452 &mut self,
13453 _: &actions::FoldFunctionBodies,
13454 window: &mut Window,
13455 cx: &mut Context<Self>,
13456 ) {
13457 let snapshot = self.buffer.read(cx).snapshot(cx);
13458
13459 let ranges = snapshot
13460 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13461 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13462 .collect::<Vec<_>>();
13463
13464 let creases = ranges
13465 .into_iter()
13466 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13467 .collect();
13468
13469 self.fold_creases(creases, true, window, cx);
13470 }
13471
13472 pub fn fold_recursive(
13473 &mut self,
13474 _: &actions::FoldRecursive,
13475 window: &mut Window,
13476 cx: &mut Context<Self>,
13477 ) {
13478 let mut to_fold = Vec::new();
13479 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13480 let selections = self.selections.all_adjusted(cx);
13481
13482 for selection in selections {
13483 let range = selection.range().sorted();
13484 let buffer_start_row = range.start.row;
13485
13486 if range.start.row != range.end.row {
13487 let mut found = false;
13488 for row in range.start.row..=range.end.row {
13489 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13490 found = true;
13491 to_fold.push(crease);
13492 }
13493 }
13494 if found {
13495 continue;
13496 }
13497 }
13498
13499 for row in (0..=range.start.row).rev() {
13500 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13501 if crease.range().end.row >= buffer_start_row {
13502 to_fold.push(crease);
13503 } else {
13504 break;
13505 }
13506 }
13507 }
13508 }
13509
13510 self.fold_creases(to_fold, true, window, cx);
13511 }
13512
13513 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13514 let buffer_row = fold_at.buffer_row;
13515 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13516
13517 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13518 let autoscroll = self
13519 .selections
13520 .all::<Point>(cx)
13521 .iter()
13522 .any(|selection| crease.range().overlaps(&selection.range()));
13523
13524 self.fold_creases(vec![crease], autoscroll, window, cx);
13525 }
13526 }
13527
13528 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13529 if self.is_singleton(cx) {
13530 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13531 let buffer = &display_map.buffer_snapshot;
13532 let selections = self.selections.all::<Point>(cx);
13533 let ranges = selections
13534 .iter()
13535 .map(|s| {
13536 let range = s.display_range(&display_map).sorted();
13537 let mut start = range.start.to_point(&display_map);
13538 let mut end = range.end.to_point(&display_map);
13539 start.column = 0;
13540 end.column = buffer.line_len(MultiBufferRow(end.row));
13541 start..end
13542 })
13543 .collect::<Vec<_>>();
13544
13545 self.unfold_ranges(&ranges, true, true, cx);
13546 } else {
13547 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13548 let buffer_ids = self
13549 .selections
13550 .disjoint_anchor_ranges()
13551 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13552 .collect::<HashSet<_>>();
13553 for buffer_id in buffer_ids {
13554 self.unfold_buffer(buffer_id, cx);
13555 }
13556 }
13557 }
13558
13559 pub fn unfold_recursive(
13560 &mut self,
13561 _: &UnfoldRecursive,
13562 _window: &mut Window,
13563 cx: &mut Context<Self>,
13564 ) {
13565 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13566 let selections = self.selections.all::<Point>(cx);
13567 let ranges = selections
13568 .iter()
13569 .map(|s| {
13570 let mut range = s.display_range(&display_map).sorted();
13571 *range.start.column_mut() = 0;
13572 *range.end.column_mut() = display_map.line_len(range.end.row());
13573 let start = range.start.to_point(&display_map);
13574 let end = range.end.to_point(&display_map);
13575 start..end
13576 })
13577 .collect::<Vec<_>>();
13578
13579 self.unfold_ranges(&ranges, true, true, cx);
13580 }
13581
13582 pub fn unfold_at(
13583 &mut self,
13584 unfold_at: &UnfoldAt,
13585 _window: &mut Window,
13586 cx: &mut Context<Self>,
13587 ) {
13588 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13589
13590 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13591 ..Point::new(
13592 unfold_at.buffer_row.0,
13593 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13594 );
13595
13596 let autoscroll = self
13597 .selections
13598 .all::<Point>(cx)
13599 .iter()
13600 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13601
13602 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13603 }
13604
13605 pub fn unfold_all(
13606 &mut self,
13607 _: &actions::UnfoldAll,
13608 _window: &mut Window,
13609 cx: &mut Context<Self>,
13610 ) {
13611 if self.buffer.read(cx).is_singleton() {
13612 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13613 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13614 } else {
13615 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13616 editor
13617 .update(&mut cx, |editor, cx| {
13618 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13619 editor.unfold_buffer(buffer_id, cx);
13620 }
13621 })
13622 .ok();
13623 });
13624 }
13625 }
13626
13627 pub fn fold_selected_ranges(
13628 &mut self,
13629 _: &FoldSelectedRanges,
13630 window: &mut Window,
13631 cx: &mut Context<Self>,
13632 ) {
13633 let selections = self.selections.all::<Point>(cx);
13634 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13635 let line_mode = self.selections.line_mode;
13636 let ranges = selections
13637 .into_iter()
13638 .map(|s| {
13639 if line_mode {
13640 let start = Point::new(s.start.row, 0);
13641 let end = Point::new(
13642 s.end.row,
13643 display_map
13644 .buffer_snapshot
13645 .line_len(MultiBufferRow(s.end.row)),
13646 );
13647 Crease::simple(start..end, display_map.fold_placeholder.clone())
13648 } else {
13649 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13650 }
13651 })
13652 .collect::<Vec<_>>();
13653 self.fold_creases(ranges, true, window, cx);
13654 }
13655
13656 pub fn fold_ranges<T: ToOffset + Clone>(
13657 &mut self,
13658 ranges: Vec<Range<T>>,
13659 auto_scroll: bool,
13660 window: &mut Window,
13661 cx: &mut Context<Self>,
13662 ) {
13663 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13664 let ranges = ranges
13665 .into_iter()
13666 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13667 .collect::<Vec<_>>();
13668 self.fold_creases(ranges, auto_scroll, window, cx);
13669 }
13670
13671 pub fn fold_creases<T: ToOffset + Clone>(
13672 &mut self,
13673 creases: Vec<Crease<T>>,
13674 auto_scroll: bool,
13675 window: &mut Window,
13676 cx: &mut Context<Self>,
13677 ) {
13678 if creases.is_empty() {
13679 return;
13680 }
13681
13682 let mut buffers_affected = HashSet::default();
13683 let multi_buffer = self.buffer().read(cx);
13684 for crease in &creases {
13685 if let Some((_, buffer, _)) =
13686 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13687 {
13688 buffers_affected.insert(buffer.read(cx).remote_id());
13689 };
13690 }
13691
13692 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13693
13694 if auto_scroll {
13695 self.request_autoscroll(Autoscroll::fit(), cx);
13696 }
13697
13698 cx.notify();
13699
13700 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13701 // Clear diagnostics block when folding a range that contains it.
13702 let snapshot = self.snapshot(window, cx);
13703 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13704 drop(snapshot);
13705 self.active_diagnostics = Some(active_diagnostics);
13706 self.dismiss_diagnostics(cx);
13707 } else {
13708 self.active_diagnostics = Some(active_diagnostics);
13709 }
13710 }
13711
13712 self.scrollbar_marker_state.dirty = true;
13713 }
13714
13715 /// Removes any folds whose ranges intersect any of the given ranges.
13716 pub fn unfold_ranges<T: ToOffset + Clone>(
13717 &mut self,
13718 ranges: &[Range<T>],
13719 inclusive: bool,
13720 auto_scroll: bool,
13721 cx: &mut Context<Self>,
13722 ) {
13723 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13724 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13725 });
13726 }
13727
13728 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13729 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13730 return;
13731 }
13732 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13733 self.display_map.update(cx, |display_map, cx| {
13734 display_map.fold_buffers([buffer_id], cx)
13735 });
13736 cx.emit(EditorEvent::BufferFoldToggled {
13737 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13738 folded: true,
13739 });
13740 cx.notify();
13741 }
13742
13743 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13744 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13745 return;
13746 }
13747 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13748 self.display_map.update(cx, |display_map, cx| {
13749 display_map.unfold_buffers([buffer_id], cx);
13750 });
13751 cx.emit(EditorEvent::BufferFoldToggled {
13752 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13753 folded: false,
13754 });
13755 cx.notify();
13756 }
13757
13758 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13759 self.display_map.read(cx).is_buffer_folded(buffer)
13760 }
13761
13762 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13763 self.display_map.read(cx).folded_buffers()
13764 }
13765
13766 /// Removes any folds with the given ranges.
13767 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13768 &mut self,
13769 ranges: &[Range<T>],
13770 type_id: TypeId,
13771 auto_scroll: bool,
13772 cx: &mut Context<Self>,
13773 ) {
13774 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13775 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13776 });
13777 }
13778
13779 fn remove_folds_with<T: ToOffset + Clone>(
13780 &mut self,
13781 ranges: &[Range<T>],
13782 auto_scroll: bool,
13783 cx: &mut Context<Self>,
13784 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13785 ) {
13786 if ranges.is_empty() {
13787 return;
13788 }
13789
13790 let mut buffers_affected = HashSet::default();
13791 let multi_buffer = self.buffer().read(cx);
13792 for range in ranges {
13793 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13794 buffers_affected.insert(buffer.read(cx).remote_id());
13795 };
13796 }
13797
13798 self.display_map.update(cx, update);
13799
13800 if auto_scroll {
13801 self.request_autoscroll(Autoscroll::fit(), cx);
13802 }
13803
13804 cx.notify();
13805 self.scrollbar_marker_state.dirty = true;
13806 self.active_indent_guides_state.dirty = true;
13807 }
13808
13809 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13810 self.display_map.read(cx).fold_placeholder.clone()
13811 }
13812
13813 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13814 self.buffer.update(cx, |buffer, cx| {
13815 buffer.set_all_diff_hunks_expanded(cx);
13816 });
13817 }
13818
13819 pub fn expand_all_diff_hunks(
13820 &mut self,
13821 _: &ExpandAllDiffHunks,
13822 _window: &mut Window,
13823 cx: &mut Context<Self>,
13824 ) {
13825 self.buffer.update(cx, |buffer, cx| {
13826 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13827 });
13828 }
13829
13830 pub fn toggle_selected_diff_hunks(
13831 &mut self,
13832 _: &ToggleSelectedDiffHunks,
13833 _window: &mut Window,
13834 cx: &mut Context<Self>,
13835 ) {
13836 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13837 self.toggle_diff_hunks_in_ranges(ranges, cx);
13838 }
13839
13840 pub fn diff_hunks_in_ranges<'a>(
13841 &'a self,
13842 ranges: &'a [Range<Anchor>],
13843 buffer: &'a MultiBufferSnapshot,
13844 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13845 ranges.iter().flat_map(move |range| {
13846 let end_excerpt_id = range.end.excerpt_id;
13847 let range = range.to_point(buffer);
13848 let mut peek_end = range.end;
13849 if range.end.row < buffer.max_row().0 {
13850 peek_end = Point::new(range.end.row + 1, 0);
13851 }
13852 buffer
13853 .diff_hunks_in_range(range.start..peek_end)
13854 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13855 })
13856 }
13857
13858 pub fn has_stageable_diff_hunks_in_ranges(
13859 &self,
13860 ranges: &[Range<Anchor>],
13861 snapshot: &MultiBufferSnapshot,
13862 ) -> bool {
13863 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13864 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13865 }
13866
13867 pub fn toggle_staged_selected_diff_hunks(
13868 &mut self,
13869 _: &::git::ToggleStaged,
13870 _: &mut Window,
13871 cx: &mut Context<Self>,
13872 ) {
13873 let snapshot = self.buffer.read(cx).snapshot(cx);
13874 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13875 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13876 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13877 }
13878
13879 pub fn stage_and_next(
13880 &mut self,
13881 _: &::git::StageAndNext,
13882 window: &mut Window,
13883 cx: &mut Context<Self>,
13884 ) {
13885 self.do_stage_or_unstage_and_next(true, window, cx);
13886 }
13887
13888 pub fn unstage_and_next(
13889 &mut self,
13890 _: &::git::UnstageAndNext,
13891 window: &mut Window,
13892 cx: &mut Context<Self>,
13893 ) {
13894 self.do_stage_or_unstage_and_next(false, window, cx);
13895 }
13896
13897 pub fn stage_or_unstage_diff_hunks(
13898 &mut self,
13899 stage: bool,
13900 ranges: Vec<Range<Anchor>>,
13901 cx: &mut Context<Self>,
13902 ) {
13903 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13904 cx.spawn(|this, mut cx| async move {
13905 task.await?;
13906 this.update(&mut cx, |this, cx| {
13907 let snapshot = this.buffer.read(cx).snapshot(cx);
13908 let chunk_by = this
13909 .diff_hunks_in_ranges(&ranges, &snapshot)
13910 .chunk_by(|hunk| hunk.buffer_id);
13911 for (buffer_id, hunks) in &chunk_by {
13912 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13913 }
13914 })
13915 })
13916 .detach_and_log_err(cx);
13917 }
13918
13919 fn save_buffers_for_ranges_if_needed(
13920 &mut self,
13921 ranges: &[Range<Anchor>],
13922 cx: &mut Context<'_, Editor>,
13923 ) -> Task<Result<()>> {
13924 let multibuffer = self.buffer.read(cx);
13925 let snapshot = multibuffer.read(cx);
13926 let buffer_ids: HashSet<_> = ranges
13927 .iter()
13928 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13929 .collect();
13930 drop(snapshot);
13931
13932 let mut buffers = HashSet::default();
13933 for buffer_id in buffer_ids {
13934 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13935 let buffer = buffer_entity.read(cx);
13936 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13937 {
13938 buffers.insert(buffer_entity);
13939 }
13940 }
13941 }
13942
13943 if let Some(project) = &self.project {
13944 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13945 } else {
13946 Task::ready(Ok(()))
13947 }
13948 }
13949
13950 fn do_stage_or_unstage_and_next(
13951 &mut self,
13952 stage: bool,
13953 window: &mut Window,
13954 cx: &mut Context<Self>,
13955 ) {
13956 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13957
13958 if ranges.iter().any(|range| range.start != range.end) {
13959 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13960 return;
13961 }
13962
13963 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13964 let snapshot = self.snapshot(window, cx);
13965 let position = self.selections.newest::<Point>(cx).head();
13966 let mut row = snapshot
13967 .buffer_snapshot
13968 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13969 .find(|hunk| hunk.row_range.start.0 > position.row)
13970 .map(|hunk| hunk.row_range.start);
13971
13972 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
13973 // Outside of the project diff editor, wrap around to the beginning.
13974 if !all_diff_hunks_expanded {
13975 row = row.or_else(|| {
13976 snapshot
13977 .buffer_snapshot
13978 .diff_hunks_in_range(Point::zero()..position)
13979 .find(|hunk| hunk.row_range.end.0 < position.row)
13980 .map(|hunk| hunk.row_range.start)
13981 });
13982 }
13983
13984 if let Some(row) = row {
13985 let destination = Point::new(row.0, 0);
13986 let autoscroll = Autoscroll::center();
13987
13988 self.unfold_ranges(&[destination..destination], false, false, cx);
13989 self.change_selections(Some(autoscroll), window, cx, |s| {
13990 s.select_ranges([destination..destination]);
13991 });
13992 } else if all_diff_hunks_expanded {
13993 window.dispatch_action(::git::ExpandCommitEditor.boxed_clone(), cx);
13994 }
13995 }
13996
13997 fn do_stage_or_unstage(
13998 &self,
13999 stage: bool,
14000 buffer_id: BufferId,
14001 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14002 cx: &mut App,
14003 ) -> Option<()> {
14004 let project = self.project.as_ref()?;
14005 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14006 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14007 let buffer_snapshot = buffer.read(cx).snapshot();
14008 let file_exists = buffer_snapshot
14009 .file()
14010 .is_some_and(|file| file.disk_state().exists());
14011 diff.update(cx, |diff, cx| {
14012 diff.stage_or_unstage_hunks(
14013 stage,
14014 &hunks
14015 .map(|hunk| buffer_diff::DiffHunk {
14016 buffer_range: hunk.buffer_range,
14017 diff_base_byte_range: hunk.diff_base_byte_range,
14018 secondary_status: hunk.secondary_status,
14019 range: Point::zero()..Point::zero(), // unused
14020 })
14021 .collect::<Vec<_>>(),
14022 &buffer_snapshot,
14023 file_exists,
14024 cx,
14025 )
14026 });
14027 None
14028 }
14029
14030 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14031 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14032 self.buffer
14033 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14034 }
14035
14036 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14037 self.buffer.update(cx, |buffer, cx| {
14038 let ranges = vec![Anchor::min()..Anchor::max()];
14039 if !buffer.all_diff_hunks_expanded()
14040 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14041 {
14042 buffer.collapse_diff_hunks(ranges, cx);
14043 true
14044 } else {
14045 false
14046 }
14047 })
14048 }
14049
14050 fn toggle_diff_hunks_in_ranges(
14051 &mut self,
14052 ranges: Vec<Range<Anchor>>,
14053 cx: &mut Context<'_, Editor>,
14054 ) {
14055 self.buffer.update(cx, |buffer, cx| {
14056 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14057 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14058 })
14059 }
14060
14061 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14062 self.buffer.update(cx, |buffer, cx| {
14063 let snapshot = buffer.snapshot(cx);
14064 let excerpt_id = range.end.excerpt_id;
14065 let point_range = range.to_point(&snapshot);
14066 let expand = !buffer.single_hunk_is_expanded(range, cx);
14067 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14068 })
14069 }
14070
14071 pub(crate) fn apply_all_diff_hunks(
14072 &mut self,
14073 _: &ApplyAllDiffHunks,
14074 window: &mut Window,
14075 cx: &mut Context<Self>,
14076 ) {
14077 let buffers = self.buffer.read(cx).all_buffers();
14078 for branch_buffer in buffers {
14079 branch_buffer.update(cx, |branch_buffer, cx| {
14080 branch_buffer.merge_into_base(Vec::new(), cx);
14081 });
14082 }
14083
14084 if let Some(project) = self.project.clone() {
14085 self.save(true, project, window, cx).detach_and_log_err(cx);
14086 }
14087 }
14088
14089 pub(crate) fn apply_selected_diff_hunks(
14090 &mut self,
14091 _: &ApplyDiffHunk,
14092 window: &mut Window,
14093 cx: &mut Context<Self>,
14094 ) {
14095 let snapshot = self.snapshot(window, cx);
14096 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14097 let mut ranges_by_buffer = HashMap::default();
14098 self.transact(window, cx, |editor, _window, cx| {
14099 for hunk in hunks {
14100 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14101 ranges_by_buffer
14102 .entry(buffer.clone())
14103 .or_insert_with(Vec::new)
14104 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14105 }
14106 }
14107
14108 for (buffer, ranges) in ranges_by_buffer {
14109 buffer.update(cx, |buffer, cx| {
14110 buffer.merge_into_base(ranges, cx);
14111 });
14112 }
14113 });
14114
14115 if let Some(project) = self.project.clone() {
14116 self.save(true, project, window, cx).detach_and_log_err(cx);
14117 }
14118 }
14119
14120 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14121 if hovered != self.gutter_hovered {
14122 self.gutter_hovered = hovered;
14123 cx.notify();
14124 }
14125 }
14126
14127 pub fn insert_blocks(
14128 &mut self,
14129 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14130 autoscroll: Option<Autoscroll>,
14131 cx: &mut Context<Self>,
14132 ) -> Vec<CustomBlockId> {
14133 let blocks = self
14134 .display_map
14135 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14136 if let Some(autoscroll) = autoscroll {
14137 self.request_autoscroll(autoscroll, cx);
14138 }
14139 cx.notify();
14140 blocks
14141 }
14142
14143 pub fn resize_blocks(
14144 &mut self,
14145 heights: HashMap<CustomBlockId, u32>,
14146 autoscroll: Option<Autoscroll>,
14147 cx: &mut Context<Self>,
14148 ) {
14149 self.display_map
14150 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14151 if let Some(autoscroll) = autoscroll {
14152 self.request_autoscroll(autoscroll, cx);
14153 }
14154 cx.notify();
14155 }
14156
14157 pub fn replace_blocks(
14158 &mut self,
14159 renderers: HashMap<CustomBlockId, RenderBlock>,
14160 autoscroll: Option<Autoscroll>,
14161 cx: &mut Context<Self>,
14162 ) {
14163 self.display_map
14164 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14165 if let Some(autoscroll) = autoscroll {
14166 self.request_autoscroll(autoscroll, cx);
14167 }
14168 cx.notify();
14169 }
14170
14171 pub fn remove_blocks(
14172 &mut self,
14173 block_ids: HashSet<CustomBlockId>,
14174 autoscroll: Option<Autoscroll>,
14175 cx: &mut Context<Self>,
14176 ) {
14177 self.display_map.update(cx, |display_map, cx| {
14178 display_map.remove_blocks(block_ids, cx)
14179 });
14180 if let Some(autoscroll) = autoscroll {
14181 self.request_autoscroll(autoscroll, cx);
14182 }
14183 cx.notify();
14184 }
14185
14186 pub fn row_for_block(
14187 &self,
14188 block_id: CustomBlockId,
14189 cx: &mut Context<Self>,
14190 ) -> Option<DisplayRow> {
14191 self.display_map
14192 .update(cx, |map, cx| map.row_for_block(block_id, cx))
14193 }
14194
14195 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14196 self.focused_block = Some(focused_block);
14197 }
14198
14199 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14200 self.focused_block.take()
14201 }
14202
14203 pub fn insert_creases(
14204 &mut self,
14205 creases: impl IntoIterator<Item = Crease<Anchor>>,
14206 cx: &mut Context<Self>,
14207 ) -> Vec<CreaseId> {
14208 self.display_map
14209 .update(cx, |map, cx| map.insert_creases(creases, cx))
14210 }
14211
14212 pub fn remove_creases(
14213 &mut self,
14214 ids: impl IntoIterator<Item = CreaseId>,
14215 cx: &mut Context<Self>,
14216 ) {
14217 self.display_map
14218 .update(cx, |map, cx| map.remove_creases(ids, cx));
14219 }
14220
14221 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14222 self.display_map
14223 .update(cx, |map, cx| map.snapshot(cx))
14224 .longest_row()
14225 }
14226
14227 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14228 self.display_map
14229 .update(cx, |map, cx| map.snapshot(cx))
14230 .max_point()
14231 }
14232
14233 pub fn text(&self, cx: &App) -> String {
14234 self.buffer.read(cx).read(cx).text()
14235 }
14236
14237 pub fn is_empty(&self, cx: &App) -> bool {
14238 self.buffer.read(cx).read(cx).is_empty()
14239 }
14240
14241 pub fn text_option(&self, cx: &App) -> Option<String> {
14242 let text = self.text(cx);
14243 let text = text.trim();
14244
14245 if text.is_empty() {
14246 return None;
14247 }
14248
14249 Some(text.to_string())
14250 }
14251
14252 pub fn set_text(
14253 &mut self,
14254 text: impl Into<Arc<str>>,
14255 window: &mut Window,
14256 cx: &mut Context<Self>,
14257 ) {
14258 self.transact(window, cx, |this, _, cx| {
14259 this.buffer
14260 .read(cx)
14261 .as_singleton()
14262 .expect("you can only call set_text on editors for singleton buffers")
14263 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14264 });
14265 }
14266
14267 pub fn display_text(&self, cx: &mut App) -> String {
14268 self.display_map
14269 .update(cx, |map, cx| map.snapshot(cx))
14270 .text()
14271 }
14272
14273 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14274 let mut wrap_guides = smallvec::smallvec![];
14275
14276 if self.show_wrap_guides == Some(false) {
14277 return wrap_guides;
14278 }
14279
14280 let settings = self.buffer.read(cx).language_settings(cx);
14281 if settings.show_wrap_guides {
14282 match self.soft_wrap_mode(cx) {
14283 SoftWrap::Column(soft_wrap) => {
14284 wrap_guides.push((soft_wrap as usize, true));
14285 }
14286 SoftWrap::Bounded(soft_wrap) => {
14287 wrap_guides.push((soft_wrap as usize, true));
14288 }
14289 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14290 }
14291 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14292 }
14293
14294 wrap_guides
14295 }
14296
14297 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14298 let settings = self.buffer.read(cx).language_settings(cx);
14299 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14300 match mode {
14301 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14302 SoftWrap::None
14303 }
14304 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14305 language_settings::SoftWrap::PreferredLineLength => {
14306 SoftWrap::Column(settings.preferred_line_length)
14307 }
14308 language_settings::SoftWrap::Bounded => {
14309 SoftWrap::Bounded(settings.preferred_line_length)
14310 }
14311 }
14312 }
14313
14314 pub fn set_soft_wrap_mode(
14315 &mut self,
14316 mode: language_settings::SoftWrap,
14317
14318 cx: &mut Context<Self>,
14319 ) {
14320 self.soft_wrap_mode_override = Some(mode);
14321 cx.notify();
14322 }
14323
14324 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14325 self.hard_wrap = hard_wrap;
14326 cx.notify();
14327 }
14328
14329 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14330 self.text_style_refinement = Some(style);
14331 }
14332
14333 /// called by the Element so we know what style we were most recently rendered with.
14334 pub(crate) fn set_style(
14335 &mut self,
14336 style: EditorStyle,
14337 window: &mut Window,
14338 cx: &mut Context<Self>,
14339 ) {
14340 let rem_size = window.rem_size();
14341 self.display_map.update(cx, |map, cx| {
14342 map.set_font(
14343 style.text.font(),
14344 style.text.font_size.to_pixels(rem_size),
14345 cx,
14346 )
14347 });
14348 self.style = Some(style);
14349 }
14350
14351 pub fn style(&self) -> Option<&EditorStyle> {
14352 self.style.as_ref()
14353 }
14354
14355 // Called by the element. This method is not designed to be called outside of the editor
14356 // element's layout code because it does not notify when rewrapping is computed synchronously.
14357 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14358 self.display_map
14359 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14360 }
14361
14362 pub fn set_soft_wrap(&mut self) {
14363 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14364 }
14365
14366 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14367 if self.soft_wrap_mode_override.is_some() {
14368 self.soft_wrap_mode_override.take();
14369 } else {
14370 let soft_wrap = match self.soft_wrap_mode(cx) {
14371 SoftWrap::GitDiff => return,
14372 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14373 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14374 language_settings::SoftWrap::None
14375 }
14376 };
14377 self.soft_wrap_mode_override = Some(soft_wrap);
14378 }
14379 cx.notify();
14380 }
14381
14382 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14383 let Some(workspace) = self.workspace() else {
14384 return;
14385 };
14386 let fs = workspace.read(cx).app_state().fs.clone();
14387 let current_show = TabBarSettings::get_global(cx).show;
14388 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14389 setting.show = Some(!current_show);
14390 });
14391 }
14392
14393 pub fn toggle_indent_guides(
14394 &mut self,
14395 _: &ToggleIndentGuides,
14396 _: &mut Window,
14397 cx: &mut Context<Self>,
14398 ) {
14399 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14400 self.buffer
14401 .read(cx)
14402 .language_settings(cx)
14403 .indent_guides
14404 .enabled
14405 });
14406 self.show_indent_guides = Some(!currently_enabled);
14407 cx.notify();
14408 }
14409
14410 fn should_show_indent_guides(&self) -> Option<bool> {
14411 self.show_indent_guides
14412 }
14413
14414 pub fn toggle_line_numbers(
14415 &mut self,
14416 _: &ToggleLineNumbers,
14417 _: &mut Window,
14418 cx: &mut Context<Self>,
14419 ) {
14420 let mut editor_settings = EditorSettings::get_global(cx).clone();
14421 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14422 EditorSettings::override_global(editor_settings, cx);
14423 }
14424
14425 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
14426 if let Some(show_line_numbers) = self.show_line_numbers {
14427 return show_line_numbers;
14428 }
14429 EditorSettings::get_global(cx).gutter.line_numbers
14430 }
14431
14432 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14433 self.use_relative_line_numbers
14434 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14435 }
14436
14437 pub fn toggle_relative_line_numbers(
14438 &mut self,
14439 _: &ToggleRelativeLineNumbers,
14440 _: &mut Window,
14441 cx: &mut Context<Self>,
14442 ) {
14443 let is_relative = self.should_use_relative_line_numbers(cx);
14444 self.set_relative_line_number(Some(!is_relative), cx)
14445 }
14446
14447 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14448 self.use_relative_line_numbers = is_relative;
14449 cx.notify();
14450 }
14451
14452 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14453 self.show_gutter = show_gutter;
14454 cx.notify();
14455 }
14456
14457 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14458 self.show_scrollbars = show_scrollbars;
14459 cx.notify();
14460 }
14461
14462 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14463 self.show_line_numbers = Some(show_line_numbers);
14464 cx.notify();
14465 }
14466
14467 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14468 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14469 cx.notify();
14470 }
14471
14472 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14473 self.show_code_actions = Some(show_code_actions);
14474 cx.notify();
14475 }
14476
14477 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14478 self.show_runnables = Some(show_runnables);
14479 cx.notify();
14480 }
14481
14482 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14483 if self.display_map.read(cx).masked != masked {
14484 self.display_map.update(cx, |map, _| map.masked = masked);
14485 }
14486 cx.notify()
14487 }
14488
14489 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14490 self.show_wrap_guides = Some(show_wrap_guides);
14491 cx.notify();
14492 }
14493
14494 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14495 self.show_indent_guides = Some(show_indent_guides);
14496 cx.notify();
14497 }
14498
14499 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14500 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14501 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14502 if let Some(dir) = file.abs_path(cx).parent() {
14503 return Some(dir.to_owned());
14504 }
14505 }
14506
14507 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14508 return Some(project_path.path.to_path_buf());
14509 }
14510 }
14511
14512 None
14513 }
14514
14515 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14516 self.active_excerpt(cx)?
14517 .1
14518 .read(cx)
14519 .file()
14520 .and_then(|f| f.as_local())
14521 }
14522
14523 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14524 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14525 let buffer = buffer.read(cx);
14526 if let Some(project_path) = buffer.project_path(cx) {
14527 let project = self.project.as_ref()?.read(cx);
14528 project.absolute_path(&project_path, cx)
14529 } else {
14530 buffer
14531 .file()
14532 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14533 }
14534 })
14535 }
14536
14537 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14538 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14539 let project_path = buffer.read(cx).project_path(cx)?;
14540 let project = self.project.as_ref()?.read(cx);
14541 let entry = project.entry_for_path(&project_path, cx)?;
14542 let path = entry.path.to_path_buf();
14543 Some(path)
14544 })
14545 }
14546
14547 pub fn reveal_in_finder(
14548 &mut self,
14549 _: &RevealInFileManager,
14550 _window: &mut Window,
14551 cx: &mut Context<Self>,
14552 ) {
14553 if let Some(target) = self.target_file(cx) {
14554 cx.reveal_path(&target.abs_path(cx));
14555 }
14556 }
14557
14558 pub fn copy_path(
14559 &mut self,
14560 _: &zed_actions::workspace::CopyPath,
14561 _window: &mut Window,
14562 cx: &mut Context<Self>,
14563 ) {
14564 if let Some(path) = self.target_file_abs_path(cx) {
14565 if let Some(path) = path.to_str() {
14566 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14567 }
14568 }
14569 }
14570
14571 pub fn copy_relative_path(
14572 &mut self,
14573 _: &zed_actions::workspace::CopyRelativePath,
14574 _window: &mut Window,
14575 cx: &mut Context<Self>,
14576 ) {
14577 if let Some(path) = self.target_file_path(cx) {
14578 if let Some(path) = path.to_str() {
14579 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14580 }
14581 }
14582 }
14583
14584 pub fn copy_file_name_without_extension(
14585 &mut self,
14586 _: &CopyFileNameWithoutExtension,
14587 _: &mut Window,
14588 cx: &mut Context<Self>,
14589 ) {
14590 if let Some(file) = self.target_file(cx) {
14591 if let Some(file_stem) = file.path().file_stem() {
14592 if let Some(name) = file_stem.to_str() {
14593 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14594 }
14595 }
14596 }
14597 }
14598
14599 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14600 if let Some(file) = self.target_file(cx) {
14601 if let Some(file_name) = file.path().file_name() {
14602 if let Some(name) = file_name.to_str() {
14603 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14604 }
14605 }
14606 }
14607 }
14608
14609 pub fn toggle_git_blame(
14610 &mut self,
14611 _: &::git::Blame,
14612 window: &mut Window,
14613 cx: &mut Context<Self>,
14614 ) {
14615 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14616
14617 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14618 self.start_git_blame(true, window, cx);
14619 }
14620
14621 cx.notify();
14622 }
14623
14624 pub fn toggle_git_blame_inline(
14625 &mut self,
14626 _: &ToggleGitBlameInline,
14627 window: &mut Window,
14628 cx: &mut Context<Self>,
14629 ) {
14630 self.toggle_git_blame_inline_internal(true, window, cx);
14631 cx.notify();
14632 }
14633
14634 pub fn git_blame_inline_enabled(&self) -> bool {
14635 self.git_blame_inline_enabled
14636 }
14637
14638 pub fn toggle_selection_menu(
14639 &mut self,
14640 _: &ToggleSelectionMenu,
14641 _: &mut Window,
14642 cx: &mut Context<Self>,
14643 ) {
14644 self.show_selection_menu = self
14645 .show_selection_menu
14646 .map(|show_selections_menu| !show_selections_menu)
14647 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14648
14649 cx.notify();
14650 }
14651
14652 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14653 self.show_selection_menu
14654 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14655 }
14656
14657 fn start_git_blame(
14658 &mut self,
14659 user_triggered: bool,
14660 window: &mut Window,
14661 cx: &mut Context<Self>,
14662 ) {
14663 if let Some(project) = self.project.as_ref() {
14664 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14665 return;
14666 };
14667
14668 if buffer.read(cx).file().is_none() {
14669 return;
14670 }
14671
14672 let focused = self.focus_handle(cx).contains_focused(window, cx);
14673
14674 let project = project.clone();
14675 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14676 self.blame_subscription =
14677 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14678 self.blame = Some(blame);
14679 }
14680 }
14681
14682 fn toggle_git_blame_inline_internal(
14683 &mut self,
14684 user_triggered: bool,
14685 window: &mut Window,
14686 cx: &mut Context<Self>,
14687 ) {
14688 if self.git_blame_inline_enabled {
14689 self.git_blame_inline_enabled = false;
14690 self.show_git_blame_inline = false;
14691 self.show_git_blame_inline_delay_task.take();
14692 } else {
14693 self.git_blame_inline_enabled = true;
14694 self.start_git_blame_inline(user_triggered, window, cx);
14695 }
14696
14697 cx.notify();
14698 }
14699
14700 fn start_git_blame_inline(
14701 &mut self,
14702 user_triggered: bool,
14703 window: &mut Window,
14704 cx: &mut Context<Self>,
14705 ) {
14706 self.start_git_blame(user_triggered, window, cx);
14707
14708 if ProjectSettings::get_global(cx)
14709 .git
14710 .inline_blame_delay()
14711 .is_some()
14712 {
14713 self.start_inline_blame_timer(window, cx);
14714 } else {
14715 self.show_git_blame_inline = true
14716 }
14717 }
14718
14719 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14720 self.blame.as_ref()
14721 }
14722
14723 pub fn show_git_blame_gutter(&self) -> bool {
14724 self.show_git_blame_gutter
14725 }
14726
14727 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14728 self.show_git_blame_gutter && self.has_blame_entries(cx)
14729 }
14730
14731 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14732 self.show_git_blame_inline
14733 && (self.focus_handle.is_focused(window)
14734 || self
14735 .git_blame_inline_tooltip
14736 .as_ref()
14737 .and_then(|t| t.upgrade())
14738 .is_some())
14739 && !self.newest_selection_head_on_empty_line(cx)
14740 && self.has_blame_entries(cx)
14741 }
14742
14743 fn has_blame_entries(&self, cx: &App) -> bool {
14744 self.blame()
14745 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14746 }
14747
14748 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14749 let cursor_anchor = self.selections.newest_anchor().head();
14750
14751 let snapshot = self.buffer.read(cx).snapshot(cx);
14752 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14753
14754 snapshot.line_len(buffer_row) == 0
14755 }
14756
14757 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14758 let buffer_and_selection = maybe!({
14759 let selection = self.selections.newest::<Point>(cx);
14760 let selection_range = selection.range();
14761
14762 let multi_buffer = self.buffer().read(cx);
14763 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14764 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14765
14766 let (buffer, range, _) = if selection.reversed {
14767 buffer_ranges.first()
14768 } else {
14769 buffer_ranges.last()
14770 }?;
14771
14772 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14773 ..text::ToPoint::to_point(&range.end, &buffer).row;
14774 Some((
14775 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14776 selection,
14777 ))
14778 });
14779
14780 let Some((buffer, selection)) = buffer_and_selection else {
14781 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14782 };
14783
14784 let Some(project) = self.project.as_ref() else {
14785 return Task::ready(Err(anyhow!("editor does not have project")));
14786 };
14787
14788 project.update(cx, |project, cx| {
14789 project.get_permalink_to_line(&buffer, selection, cx)
14790 })
14791 }
14792
14793 pub fn copy_permalink_to_line(
14794 &mut self,
14795 _: &CopyPermalinkToLine,
14796 window: &mut Window,
14797 cx: &mut Context<Self>,
14798 ) {
14799 let permalink_task = self.get_permalink_to_line(cx);
14800 let workspace = self.workspace();
14801
14802 cx.spawn_in(window, |_, mut cx| async move {
14803 match permalink_task.await {
14804 Ok(permalink) => {
14805 cx.update(|_, cx| {
14806 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14807 })
14808 .ok();
14809 }
14810 Err(err) => {
14811 let message = format!("Failed to copy permalink: {err}");
14812
14813 Err::<(), anyhow::Error>(err).log_err();
14814
14815 if let Some(workspace) = workspace {
14816 workspace
14817 .update_in(&mut cx, |workspace, _, cx| {
14818 struct CopyPermalinkToLine;
14819
14820 workspace.show_toast(
14821 Toast::new(
14822 NotificationId::unique::<CopyPermalinkToLine>(),
14823 message,
14824 ),
14825 cx,
14826 )
14827 })
14828 .ok();
14829 }
14830 }
14831 }
14832 })
14833 .detach();
14834 }
14835
14836 pub fn copy_file_location(
14837 &mut self,
14838 _: &CopyFileLocation,
14839 _: &mut Window,
14840 cx: &mut Context<Self>,
14841 ) {
14842 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14843 if let Some(file) = self.target_file(cx) {
14844 if let Some(path) = file.path().to_str() {
14845 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14846 }
14847 }
14848 }
14849
14850 pub fn open_permalink_to_line(
14851 &mut self,
14852 _: &OpenPermalinkToLine,
14853 window: &mut Window,
14854 cx: &mut Context<Self>,
14855 ) {
14856 let permalink_task = self.get_permalink_to_line(cx);
14857 let workspace = self.workspace();
14858
14859 cx.spawn_in(window, |_, mut cx| async move {
14860 match permalink_task.await {
14861 Ok(permalink) => {
14862 cx.update(|_, cx| {
14863 cx.open_url(permalink.as_ref());
14864 })
14865 .ok();
14866 }
14867 Err(err) => {
14868 let message = format!("Failed to open permalink: {err}");
14869
14870 Err::<(), anyhow::Error>(err).log_err();
14871
14872 if let Some(workspace) = workspace {
14873 workspace
14874 .update(&mut cx, |workspace, cx| {
14875 struct OpenPermalinkToLine;
14876
14877 workspace.show_toast(
14878 Toast::new(
14879 NotificationId::unique::<OpenPermalinkToLine>(),
14880 message,
14881 ),
14882 cx,
14883 )
14884 })
14885 .ok();
14886 }
14887 }
14888 }
14889 })
14890 .detach();
14891 }
14892
14893 pub fn insert_uuid_v4(
14894 &mut self,
14895 _: &InsertUuidV4,
14896 window: &mut Window,
14897 cx: &mut Context<Self>,
14898 ) {
14899 self.insert_uuid(UuidVersion::V4, window, cx);
14900 }
14901
14902 pub fn insert_uuid_v7(
14903 &mut self,
14904 _: &InsertUuidV7,
14905 window: &mut Window,
14906 cx: &mut Context<Self>,
14907 ) {
14908 self.insert_uuid(UuidVersion::V7, window, cx);
14909 }
14910
14911 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14912 self.transact(window, cx, |this, window, cx| {
14913 let edits = this
14914 .selections
14915 .all::<Point>(cx)
14916 .into_iter()
14917 .map(|selection| {
14918 let uuid = match version {
14919 UuidVersion::V4 => uuid::Uuid::new_v4(),
14920 UuidVersion::V7 => uuid::Uuid::now_v7(),
14921 };
14922
14923 (selection.range(), uuid.to_string())
14924 });
14925 this.edit(edits, cx);
14926 this.refresh_inline_completion(true, false, window, cx);
14927 });
14928 }
14929
14930 pub fn open_selections_in_multibuffer(
14931 &mut self,
14932 _: &OpenSelectionsInMultibuffer,
14933 window: &mut Window,
14934 cx: &mut Context<Self>,
14935 ) {
14936 let multibuffer = self.buffer.read(cx);
14937
14938 let Some(buffer) = multibuffer.as_singleton() else {
14939 return;
14940 };
14941
14942 let Some(workspace) = self.workspace() else {
14943 return;
14944 };
14945
14946 let locations = self
14947 .selections
14948 .disjoint_anchors()
14949 .iter()
14950 .map(|range| Location {
14951 buffer: buffer.clone(),
14952 range: range.start.text_anchor..range.end.text_anchor,
14953 })
14954 .collect::<Vec<_>>();
14955
14956 let title = multibuffer.title(cx).to_string();
14957
14958 cx.spawn_in(window, |_, mut cx| async move {
14959 workspace.update_in(&mut cx, |workspace, window, cx| {
14960 Self::open_locations_in_multibuffer(
14961 workspace,
14962 locations,
14963 format!("Selections for '{title}'"),
14964 false,
14965 MultibufferSelectionMode::All,
14966 window,
14967 cx,
14968 );
14969 })
14970 })
14971 .detach();
14972 }
14973
14974 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14975 /// last highlight added will be used.
14976 ///
14977 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14978 pub fn highlight_rows<T: 'static>(
14979 &mut self,
14980 range: Range<Anchor>,
14981 color: Hsla,
14982 should_autoscroll: bool,
14983 cx: &mut Context<Self>,
14984 ) {
14985 let snapshot = self.buffer().read(cx).snapshot(cx);
14986 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14987 let ix = row_highlights.binary_search_by(|highlight| {
14988 Ordering::Equal
14989 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14990 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14991 });
14992
14993 if let Err(mut ix) = ix {
14994 let index = post_inc(&mut self.highlight_order);
14995
14996 // If this range intersects with the preceding highlight, then merge it with
14997 // the preceding highlight. Otherwise insert a new highlight.
14998 let mut merged = false;
14999 if ix > 0 {
15000 let prev_highlight = &mut row_highlights[ix - 1];
15001 if prev_highlight
15002 .range
15003 .end
15004 .cmp(&range.start, &snapshot)
15005 .is_ge()
15006 {
15007 ix -= 1;
15008 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15009 prev_highlight.range.end = range.end;
15010 }
15011 merged = true;
15012 prev_highlight.index = index;
15013 prev_highlight.color = color;
15014 prev_highlight.should_autoscroll = should_autoscroll;
15015 }
15016 }
15017
15018 if !merged {
15019 row_highlights.insert(
15020 ix,
15021 RowHighlight {
15022 range: range.clone(),
15023 index,
15024 color,
15025 should_autoscroll,
15026 },
15027 );
15028 }
15029
15030 // If any of the following highlights intersect with this one, merge them.
15031 while let Some(next_highlight) = row_highlights.get(ix + 1) {
15032 let highlight = &row_highlights[ix];
15033 if next_highlight
15034 .range
15035 .start
15036 .cmp(&highlight.range.end, &snapshot)
15037 .is_le()
15038 {
15039 if next_highlight
15040 .range
15041 .end
15042 .cmp(&highlight.range.end, &snapshot)
15043 .is_gt()
15044 {
15045 row_highlights[ix].range.end = next_highlight.range.end;
15046 }
15047 row_highlights.remove(ix + 1);
15048 } else {
15049 break;
15050 }
15051 }
15052 }
15053 }
15054
15055 /// Remove any highlighted row ranges of the given type that intersect the
15056 /// given ranges.
15057 pub fn remove_highlighted_rows<T: 'static>(
15058 &mut self,
15059 ranges_to_remove: Vec<Range<Anchor>>,
15060 cx: &mut Context<Self>,
15061 ) {
15062 let snapshot = self.buffer().read(cx).snapshot(cx);
15063 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15064 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15065 row_highlights.retain(|highlight| {
15066 while let Some(range_to_remove) = ranges_to_remove.peek() {
15067 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15068 Ordering::Less | Ordering::Equal => {
15069 ranges_to_remove.next();
15070 }
15071 Ordering::Greater => {
15072 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15073 Ordering::Less | Ordering::Equal => {
15074 return false;
15075 }
15076 Ordering::Greater => break,
15077 }
15078 }
15079 }
15080 }
15081
15082 true
15083 })
15084 }
15085
15086 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15087 pub fn clear_row_highlights<T: 'static>(&mut self) {
15088 self.highlighted_rows.remove(&TypeId::of::<T>());
15089 }
15090
15091 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15092 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15093 self.highlighted_rows
15094 .get(&TypeId::of::<T>())
15095 .map_or(&[] as &[_], |vec| vec.as_slice())
15096 .iter()
15097 .map(|highlight| (highlight.range.clone(), highlight.color))
15098 }
15099
15100 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15101 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15102 /// Allows to ignore certain kinds of highlights.
15103 pub fn highlighted_display_rows(
15104 &self,
15105 window: &mut Window,
15106 cx: &mut App,
15107 ) -> BTreeMap<DisplayRow, LineHighlight> {
15108 let snapshot = self.snapshot(window, cx);
15109 let mut used_highlight_orders = HashMap::default();
15110 self.highlighted_rows
15111 .iter()
15112 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15113 .fold(
15114 BTreeMap::<DisplayRow, LineHighlight>::new(),
15115 |mut unique_rows, highlight| {
15116 let start = highlight.range.start.to_display_point(&snapshot);
15117 let end = highlight.range.end.to_display_point(&snapshot);
15118 let start_row = start.row().0;
15119 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15120 && end.column() == 0
15121 {
15122 end.row().0.saturating_sub(1)
15123 } else {
15124 end.row().0
15125 };
15126 for row in start_row..=end_row {
15127 let used_index =
15128 used_highlight_orders.entry(row).or_insert(highlight.index);
15129 if highlight.index >= *used_index {
15130 *used_index = highlight.index;
15131 unique_rows.insert(DisplayRow(row), highlight.color.into());
15132 }
15133 }
15134 unique_rows
15135 },
15136 )
15137 }
15138
15139 pub fn highlighted_display_row_for_autoscroll(
15140 &self,
15141 snapshot: &DisplaySnapshot,
15142 ) -> Option<DisplayRow> {
15143 self.highlighted_rows
15144 .values()
15145 .flat_map(|highlighted_rows| highlighted_rows.iter())
15146 .filter_map(|highlight| {
15147 if highlight.should_autoscroll {
15148 Some(highlight.range.start.to_display_point(snapshot).row())
15149 } else {
15150 None
15151 }
15152 })
15153 .min()
15154 }
15155
15156 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15157 self.highlight_background::<SearchWithinRange>(
15158 ranges,
15159 |colors| colors.editor_document_highlight_read_background,
15160 cx,
15161 )
15162 }
15163
15164 pub fn set_breadcrumb_header(&mut self, new_header: String) {
15165 self.breadcrumb_header = Some(new_header);
15166 }
15167
15168 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15169 self.clear_background_highlights::<SearchWithinRange>(cx);
15170 }
15171
15172 pub fn highlight_background<T: 'static>(
15173 &mut self,
15174 ranges: &[Range<Anchor>],
15175 color_fetcher: fn(&ThemeColors) -> Hsla,
15176 cx: &mut Context<Self>,
15177 ) {
15178 self.background_highlights
15179 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15180 self.scrollbar_marker_state.dirty = true;
15181 cx.notify();
15182 }
15183
15184 pub fn clear_background_highlights<T: 'static>(
15185 &mut self,
15186 cx: &mut Context<Self>,
15187 ) -> Option<BackgroundHighlight> {
15188 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15189 if !text_highlights.1.is_empty() {
15190 self.scrollbar_marker_state.dirty = true;
15191 cx.notify();
15192 }
15193 Some(text_highlights)
15194 }
15195
15196 pub fn highlight_gutter<T: 'static>(
15197 &mut self,
15198 ranges: &[Range<Anchor>],
15199 color_fetcher: fn(&App) -> Hsla,
15200 cx: &mut Context<Self>,
15201 ) {
15202 self.gutter_highlights
15203 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15204 cx.notify();
15205 }
15206
15207 pub fn clear_gutter_highlights<T: 'static>(
15208 &mut self,
15209 cx: &mut Context<Self>,
15210 ) -> Option<GutterHighlight> {
15211 cx.notify();
15212 self.gutter_highlights.remove(&TypeId::of::<T>())
15213 }
15214
15215 #[cfg(feature = "test-support")]
15216 pub fn all_text_background_highlights(
15217 &self,
15218 window: &mut Window,
15219 cx: &mut Context<Self>,
15220 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15221 let snapshot = self.snapshot(window, cx);
15222 let buffer = &snapshot.buffer_snapshot;
15223 let start = buffer.anchor_before(0);
15224 let end = buffer.anchor_after(buffer.len());
15225 let theme = cx.theme().colors();
15226 self.background_highlights_in_range(start..end, &snapshot, theme)
15227 }
15228
15229 #[cfg(feature = "test-support")]
15230 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15231 let snapshot = self.buffer().read(cx).snapshot(cx);
15232
15233 let highlights = self
15234 .background_highlights
15235 .get(&TypeId::of::<items::BufferSearchHighlights>());
15236
15237 if let Some((_color, ranges)) = highlights {
15238 ranges
15239 .iter()
15240 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15241 .collect_vec()
15242 } else {
15243 vec![]
15244 }
15245 }
15246
15247 fn document_highlights_for_position<'a>(
15248 &'a self,
15249 position: Anchor,
15250 buffer: &'a MultiBufferSnapshot,
15251 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15252 let read_highlights = self
15253 .background_highlights
15254 .get(&TypeId::of::<DocumentHighlightRead>())
15255 .map(|h| &h.1);
15256 let write_highlights = self
15257 .background_highlights
15258 .get(&TypeId::of::<DocumentHighlightWrite>())
15259 .map(|h| &h.1);
15260 let left_position = position.bias_left(buffer);
15261 let right_position = position.bias_right(buffer);
15262 read_highlights
15263 .into_iter()
15264 .chain(write_highlights)
15265 .flat_map(move |ranges| {
15266 let start_ix = match ranges.binary_search_by(|probe| {
15267 let cmp = probe.end.cmp(&left_position, buffer);
15268 if cmp.is_ge() {
15269 Ordering::Greater
15270 } else {
15271 Ordering::Less
15272 }
15273 }) {
15274 Ok(i) | Err(i) => i,
15275 };
15276
15277 ranges[start_ix..]
15278 .iter()
15279 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15280 })
15281 }
15282
15283 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15284 self.background_highlights
15285 .get(&TypeId::of::<T>())
15286 .map_or(false, |(_, highlights)| !highlights.is_empty())
15287 }
15288
15289 pub fn background_highlights_in_range(
15290 &self,
15291 search_range: Range<Anchor>,
15292 display_snapshot: &DisplaySnapshot,
15293 theme: &ThemeColors,
15294 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15295 let mut results = Vec::new();
15296 for (color_fetcher, ranges) in self.background_highlights.values() {
15297 let color = color_fetcher(theme);
15298 let start_ix = match ranges.binary_search_by(|probe| {
15299 let cmp = probe
15300 .end
15301 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15302 if cmp.is_gt() {
15303 Ordering::Greater
15304 } else {
15305 Ordering::Less
15306 }
15307 }) {
15308 Ok(i) | Err(i) => i,
15309 };
15310 for range in &ranges[start_ix..] {
15311 if range
15312 .start
15313 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15314 .is_ge()
15315 {
15316 break;
15317 }
15318
15319 let start = range.start.to_display_point(display_snapshot);
15320 let end = range.end.to_display_point(display_snapshot);
15321 results.push((start..end, color))
15322 }
15323 }
15324 results
15325 }
15326
15327 pub fn background_highlight_row_ranges<T: 'static>(
15328 &self,
15329 search_range: Range<Anchor>,
15330 display_snapshot: &DisplaySnapshot,
15331 count: usize,
15332 ) -> Vec<RangeInclusive<DisplayPoint>> {
15333 let mut results = Vec::new();
15334 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15335 return vec![];
15336 };
15337
15338 let start_ix = match ranges.binary_search_by(|probe| {
15339 let cmp = probe
15340 .end
15341 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15342 if cmp.is_gt() {
15343 Ordering::Greater
15344 } else {
15345 Ordering::Less
15346 }
15347 }) {
15348 Ok(i) | Err(i) => i,
15349 };
15350 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15351 if let (Some(start_display), Some(end_display)) = (start, end) {
15352 results.push(
15353 start_display.to_display_point(display_snapshot)
15354 ..=end_display.to_display_point(display_snapshot),
15355 );
15356 }
15357 };
15358 let mut start_row: Option<Point> = None;
15359 let mut end_row: Option<Point> = None;
15360 if ranges.len() > count {
15361 return Vec::new();
15362 }
15363 for range in &ranges[start_ix..] {
15364 if range
15365 .start
15366 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15367 .is_ge()
15368 {
15369 break;
15370 }
15371 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15372 if let Some(current_row) = &end_row {
15373 if end.row == current_row.row {
15374 continue;
15375 }
15376 }
15377 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15378 if start_row.is_none() {
15379 assert_eq!(end_row, None);
15380 start_row = Some(start);
15381 end_row = Some(end);
15382 continue;
15383 }
15384 if let Some(current_end) = end_row.as_mut() {
15385 if start.row > current_end.row + 1 {
15386 push_region(start_row, end_row);
15387 start_row = Some(start);
15388 end_row = Some(end);
15389 } else {
15390 // Merge two hunks.
15391 *current_end = end;
15392 }
15393 } else {
15394 unreachable!();
15395 }
15396 }
15397 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15398 push_region(start_row, end_row);
15399 results
15400 }
15401
15402 pub fn gutter_highlights_in_range(
15403 &self,
15404 search_range: Range<Anchor>,
15405 display_snapshot: &DisplaySnapshot,
15406 cx: &App,
15407 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15408 let mut results = Vec::new();
15409 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15410 let color = color_fetcher(cx);
15411 let start_ix = match ranges.binary_search_by(|probe| {
15412 let cmp = probe
15413 .end
15414 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15415 if cmp.is_gt() {
15416 Ordering::Greater
15417 } else {
15418 Ordering::Less
15419 }
15420 }) {
15421 Ok(i) | Err(i) => i,
15422 };
15423 for range in &ranges[start_ix..] {
15424 if range
15425 .start
15426 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15427 .is_ge()
15428 {
15429 break;
15430 }
15431
15432 let start = range.start.to_display_point(display_snapshot);
15433 let end = range.end.to_display_point(display_snapshot);
15434 results.push((start..end, color))
15435 }
15436 }
15437 results
15438 }
15439
15440 /// Get the text ranges corresponding to the redaction query
15441 pub fn redacted_ranges(
15442 &self,
15443 search_range: Range<Anchor>,
15444 display_snapshot: &DisplaySnapshot,
15445 cx: &App,
15446 ) -> Vec<Range<DisplayPoint>> {
15447 display_snapshot
15448 .buffer_snapshot
15449 .redacted_ranges(search_range, |file| {
15450 if let Some(file) = file {
15451 file.is_private()
15452 && EditorSettings::get(
15453 Some(SettingsLocation {
15454 worktree_id: file.worktree_id(cx),
15455 path: file.path().as_ref(),
15456 }),
15457 cx,
15458 )
15459 .redact_private_values
15460 } else {
15461 false
15462 }
15463 })
15464 .map(|range| {
15465 range.start.to_display_point(display_snapshot)
15466 ..range.end.to_display_point(display_snapshot)
15467 })
15468 .collect()
15469 }
15470
15471 pub fn highlight_text<T: 'static>(
15472 &mut self,
15473 ranges: Vec<Range<Anchor>>,
15474 style: HighlightStyle,
15475 cx: &mut Context<Self>,
15476 ) {
15477 self.display_map.update(cx, |map, _| {
15478 map.highlight_text(TypeId::of::<T>(), ranges, style)
15479 });
15480 cx.notify();
15481 }
15482
15483 pub(crate) fn highlight_inlays<T: 'static>(
15484 &mut self,
15485 highlights: Vec<InlayHighlight>,
15486 style: HighlightStyle,
15487 cx: &mut Context<Self>,
15488 ) {
15489 self.display_map.update(cx, |map, _| {
15490 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15491 });
15492 cx.notify();
15493 }
15494
15495 pub fn text_highlights<'a, T: 'static>(
15496 &'a self,
15497 cx: &'a App,
15498 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15499 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15500 }
15501
15502 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15503 let cleared = self
15504 .display_map
15505 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15506 if cleared {
15507 cx.notify();
15508 }
15509 }
15510
15511 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15512 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15513 && self.focus_handle.is_focused(window)
15514 }
15515
15516 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15517 self.show_cursor_when_unfocused = is_enabled;
15518 cx.notify();
15519 }
15520
15521 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15522 cx.notify();
15523 }
15524
15525 fn on_buffer_event(
15526 &mut self,
15527 multibuffer: &Entity<MultiBuffer>,
15528 event: &multi_buffer::Event,
15529 window: &mut Window,
15530 cx: &mut Context<Self>,
15531 ) {
15532 match event {
15533 multi_buffer::Event::Edited {
15534 singleton_buffer_edited,
15535 edited_buffer: buffer_edited,
15536 } => {
15537 self.scrollbar_marker_state.dirty = true;
15538 self.active_indent_guides_state.dirty = true;
15539 self.refresh_active_diagnostics(cx);
15540 self.refresh_code_actions(window, cx);
15541 if self.has_active_inline_completion() {
15542 self.update_visible_inline_completion(window, cx);
15543 }
15544 if let Some(buffer) = buffer_edited {
15545 let buffer_id = buffer.read(cx).remote_id();
15546 if !self.registered_buffers.contains_key(&buffer_id) {
15547 if let Some(project) = self.project.as_ref() {
15548 project.update(cx, |project, cx| {
15549 self.registered_buffers.insert(
15550 buffer_id,
15551 project.register_buffer_with_language_servers(&buffer, cx),
15552 );
15553 })
15554 }
15555 }
15556 }
15557 cx.emit(EditorEvent::BufferEdited);
15558 cx.emit(SearchEvent::MatchesInvalidated);
15559 if *singleton_buffer_edited {
15560 if let Some(project) = &self.project {
15561 #[allow(clippy::mutable_key_type)]
15562 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15563 multibuffer
15564 .all_buffers()
15565 .into_iter()
15566 .filter_map(|buffer| {
15567 buffer.update(cx, |buffer, cx| {
15568 let language = buffer.language()?;
15569 let should_discard = project.update(cx, |project, cx| {
15570 project.is_local()
15571 && !project.has_language_servers_for(buffer, cx)
15572 });
15573 should_discard.not().then_some(language.clone())
15574 })
15575 })
15576 .collect::<HashSet<_>>()
15577 });
15578 if !languages_affected.is_empty() {
15579 self.refresh_inlay_hints(
15580 InlayHintRefreshReason::BufferEdited(languages_affected),
15581 cx,
15582 );
15583 }
15584 }
15585 }
15586
15587 let Some(project) = &self.project else { return };
15588 let (telemetry, is_via_ssh) = {
15589 let project = project.read(cx);
15590 let telemetry = project.client().telemetry().clone();
15591 let is_via_ssh = project.is_via_ssh();
15592 (telemetry, is_via_ssh)
15593 };
15594 refresh_linked_ranges(self, window, cx);
15595 telemetry.log_edit_event("editor", is_via_ssh);
15596 }
15597 multi_buffer::Event::ExcerptsAdded {
15598 buffer,
15599 predecessor,
15600 excerpts,
15601 } => {
15602 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15603 let buffer_id = buffer.read(cx).remote_id();
15604 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15605 if let Some(project) = &self.project {
15606 get_uncommitted_diff_for_buffer(
15607 project,
15608 [buffer.clone()],
15609 self.buffer.clone(),
15610 cx,
15611 )
15612 .detach();
15613 }
15614 }
15615 cx.emit(EditorEvent::ExcerptsAdded {
15616 buffer: buffer.clone(),
15617 predecessor: *predecessor,
15618 excerpts: excerpts.clone(),
15619 });
15620 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15621 }
15622 multi_buffer::Event::ExcerptsRemoved { ids } => {
15623 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15624 let buffer = self.buffer.read(cx);
15625 self.registered_buffers
15626 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15627 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15628 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15629 }
15630 multi_buffer::Event::ExcerptsEdited {
15631 excerpt_ids,
15632 buffer_ids,
15633 } => {
15634 self.display_map.update(cx, |map, cx| {
15635 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15636 });
15637 cx.emit(EditorEvent::ExcerptsEdited {
15638 ids: excerpt_ids.clone(),
15639 })
15640 }
15641 multi_buffer::Event::ExcerptsExpanded { ids } => {
15642 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15643 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15644 }
15645 multi_buffer::Event::Reparsed(buffer_id) => {
15646 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15647 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15648
15649 cx.emit(EditorEvent::Reparsed(*buffer_id));
15650 }
15651 multi_buffer::Event::DiffHunksToggled => {
15652 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15653 }
15654 multi_buffer::Event::LanguageChanged(buffer_id) => {
15655 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15656 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15657 cx.emit(EditorEvent::Reparsed(*buffer_id));
15658 cx.notify();
15659 }
15660 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15661 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15662 multi_buffer::Event::FileHandleChanged
15663 | multi_buffer::Event::Reloaded
15664 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15665 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15666 multi_buffer::Event::DiagnosticsUpdated => {
15667 self.refresh_active_diagnostics(cx);
15668 self.refresh_inline_diagnostics(true, window, cx);
15669 self.scrollbar_marker_state.dirty = true;
15670 cx.notify();
15671 }
15672 _ => {}
15673 };
15674 }
15675
15676 fn on_display_map_changed(
15677 &mut self,
15678 _: Entity<DisplayMap>,
15679 _: &mut Window,
15680 cx: &mut Context<Self>,
15681 ) {
15682 cx.notify();
15683 }
15684
15685 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15686 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15687 self.update_edit_prediction_settings(cx);
15688 self.refresh_inline_completion(true, false, window, cx);
15689 self.refresh_inlay_hints(
15690 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15691 self.selections.newest_anchor().head(),
15692 &self.buffer.read(cx).snapshot(cx),
15693 cx,
15694 )),
15695 cx,
15696 );
15697
15698 let old_cursor_shape = self.cursor_shape;
15699
15700 {
15701 let editor_settings = EditorSettings::get_global(cx);
15702 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15703 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15704 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15705 }
15706
15707 if old_cursor_shape != self.cursor_shape {
15708 cx.emit(EditorEvent::CursorShapeChanged);
15709 }
15710
15711 let project_settings = ProjectSettings::get_global(cx);
15712 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15713
15714 if self.mode == EditorMode::Full {
15715 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15716 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15717 if self.show_inline_diagnostics != show_inline_diagnostics {
15718 self.show_inline_diagnostics = show_inline_diagnostics;
15719 self.refresh_inline_diagnostics(false, window, cx);
15720 }
15721
15722 if self.git_blame_inline_enabled != inline_blame_enabled {
15723 self.toggle_git_blame_inline_internal(false, window, cx);
15724 }
15725 }
15726
15727 cx.notify();
15728 }
15729
15730 pub fn set_searchable(&mut self, searchable: bool) {
15731 self.searchable = searchable;
15732 }
15733
15734 pub fn searchable(&self) -> bool {
15735 self.searchable
15736 }
15737
15738 fn open_proposed_changes_editor(
15739 &mut self,
15740 _: &OpenProposedChangesEditor,
15741 window: &mut Window,
15742 cx: &mut Context<Self>,
15743 ) {
15744 let Some(workspace) = self.workspace() else {
15745 cx.propagate();
15746 return;
15747 };
15748
15749 let selections = self.selections.all::<usize>(cx);
15750 let multi_buffer = self.buffer.read(cx);
15751 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15752 let mut new_selections_by_buffer = HashMap::default();
15753 for selection in selections {
15754 for (buffer, range, _) in
15755 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15756 {
15757 let mut range = range.to_point(buffer);
15758 range.start.column = 0;
15759 range.end.column = buffer.line_len(range.end.row);
15760 new_selections_by_buffer
15761 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15762 .or_insert(Vec::new())
15763 .push(range)
15764 }
15765 }
15766
15767 let proposed_changes_buffers = new_selections_by_buffer
15768 .into_iter()
15769 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15770 .collect::<Vec<_>>();
15771 let proposed_changes_editor = cx.new(|cx| {
15772 ProposedChangesEditor::new(
15773 "Proposed changes",
15774 proposed_changes_buffers,
15775 self.project.clone(),
15776 window,
15777 cx,
15778 )
15779 });
15780
15781 window.defer(cx, move |window, cx| {
15782 workspace.update(cx, |workspace, cx| {
15783 workspace.active_pane().update(cx, |pane, cx| {
15784 pane.add_item(
15785 Box::new(proposed_changes_editor),
15786 true,
15787 true,
15788 None,
15789 window,
15790 cx,
15791 );
15792 });
15793 });
15794 });
15795 }
15796
15797 pub fn open_excerpts_in_split(
15798 &mut self,
15799 _: &OpenExcerptsSplit,
15800 window: &mut Window,
15801 cx: &mut Context<Self>,
15802 ) {
15803 self.open_excerpts_common(None, true, window, cx)
15804 }
15805
15806 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15807 self.open_excerpts_common(None, false, window, cx)
15808 }
15809
15810 fn open_excerpts_common(
15811 &mut self,
15812 jump_data: Option<JumpData>,
15813 split: bool,
15814 window: &mut Window,
15815 cx: &mut Context<Self>,
15816 ) {
15817 let Some(workspace) = self.workspace() else {
15818 cx.propagate();
15819 return;
15820 };
15821
15822 if self.buffer.read(cx).is_singleton() {
15823 cx.propagate();
15824 return;
15825 }
15826
15827 let mut new_selections_by_buffer = HashMap::default();
15828 match &jump_data {
15829 Some(JumpData::MultiBufferPoint {
15830 excerpt_id,
15831 position,
15832 anchor,
15833 line_offset_from_top,
15834 }) => {
15835 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15836 if let Some(buffer) = multi_buffer_snapshot
15837 .buffer_id_for_excerpt(*excerpt_id)
15838 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15839 {
15840 let buffer_snapshot = buffer.read(cx).snapshot();
15841 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15842 language::ToPoint::to_point(anchor, &buffer_snapshot)
15843 } else {
15844 buffer_snapshot.clip_point(*position, Bias::Left)
15845 };
15846 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15847 new_selections_by_buffer.insert(
15848 buffer,
15849 (
15850 vec![jump_to_offset..jump_to_offset],
15851 Some(*line_offset_from_top),
15852 ),
15853 );
15854 }
15855 }
15856 Some(JumpData::MultiBufferRow {
15857 row,
15858 line_offset_from_top,
15859 }) => {
15860 let point = MultiBufferPoint::new(row.0, 0);
15861 if let Some((buffer, buffer_point, _)) =
15862 self.buffer.read(cx).point_to_buffer_point(point, cx)
15863 {
15864 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15865 new_selections_by_buffer
15866 .entry(buffer)
15867 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15868 .0
15869 .push(buffer_offset..buffer_offset)
15870 }
15871 }
15872 None => {
15873 let selections = self.selections.all::<usize>(cx);
15874 let multi_buffer = self.buffer.read(cx);
15875 for selection in selections {
15876 for (snapshot, range, _, anchor) in multi_buffer
15877 .snapshot(cx)
15878 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15879 {
15880 if let Some(anchor) = anchor {
15881 // selection is in a deleted hunk
15882 let Some(buffer_id) = anchor.buffer_id else {
15883 continue;
15884 };
15885 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15886 continue;
15887 };
15888 let offset = text::ToOffset::to_offset(
15889 &anchor.text_anchor,
15890 &buffer_handle.read(cx).snapshot(),
15891 );
15892 let range = offset..offset;
15893 new_selections_by_buffer
15894 .entry(buffer_handle)
15895 .or_insert((Vec::new(), None))
15896 .0
15897 .push(range)
15898 } else {
15899 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15900 else {
15901 continue;
15902 };
15903 new_selections_by_buffer
15904 .entry(buffer_handle)
15905 .or_insert((Vec::new(), None))
15906 .0
15907 .push(range)
15908 }
15909 }
15910 }
15911 }
15912 }
15913
15914 if new_selections_by_buffer.is_empty() {
15915 return;
15916 }
15917
15918 // We defer the pane interaction because we ourselves are a workspace item
15919 // and activating a new item causes the pane to call a method on us reentrantly,
15920 // which panics if we're on the stack.
15921 window.defer(cx, move |window, cx| {
15922 workspace.update(cx, |workspace, cx| {
15923 let pane = if split {
15924 workspace.adjacent_pane(window, cx)
15925 } else {
15926 workspace.active_pane().clone()
15927 };
15928
15929 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15930 let editor = buffer
15931 .read(cx)
15932 .file()
15933 .is_none()
15934 .then(|| {
15935 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15936 // so `workspace.open_project_item` will never find them, always opening a new editor.
15937 // Instead, we try to activate the existing editor in the pane first.
15938 let (editor, pane_item_index) =
15939 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15940 let editor = item.downcast::<Editor>()?;
15941 let singleton_buffer =
15942 editor.read(cx).buffer().read(cx).as_singleton()?;
15943 if singleton_buffer == buffer {
15944 Some((editor, i))
15945 } else {
15946 None
15947 }
15948 })?;
15949 pane.update(cx, |pane, cx| {
15950 pane.activate_item(pane_item_index, true, true, window, cx)
15951 });
15952 Some(editor)
15953 })
15954 .flatten()
15955 .unwrap_or_else(|| {
15956 workspace.open_project_item::<Self>(
15957 pane.clone(),
15958 buffer,
15959 true,
15960 true,
15961 window,
15962 cx,
15963 )
15964 });
15965
15966 editor.update(cx, |editor, cx| {
15967 let autoscroll = match scroll_offset {
15968 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15969 None => Autoscroll::newest(),
15970 };
15971 let nav_history = editor.nav_history.take();
15972 editor.change_selections(Some(autoscroll), window, cx, |s| {
15973 s.select_ranges(ranges);
15974 });
15975 editor.nav_history = nav_history;
15976 });
15977 }
15978 })
15979 });
15980 }
15981
15982 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15983 let snapshot = self.buffer.read(cx).read(cx);
15984 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15985 Some(
15986 ranges
15987 .iter()
15988 .map(move |range| {
15989 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15990 })
15991 .collect(),
15992 )
15993 }
15994
15995 fn selection_replacement_ranges(
15996 &self,
15997 range: Range<OffsetUtf16>,
15998 cx: &mut App,
15999 ) -> Vec<Range<OffsetUtf16>> {
16000 let selections = self.selections.all::<OffsetUtf16>(cx);
16001 let newest_selection = selections
16002 .iter()
16003 .max_by_key(|selection| selection.id)
16004 .unwrap();
16005 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16006 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16007 let snapshot = self.buffer.read(cx).read(cx);
16008 selections
16009 .into_iter()
16010 .map(|mut selection| {
16011 selection.start.0 =
16012 (selection.start.0 as isize).saturating_add(start_delta) as usize;
16013 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16014 snapshot.clip_offset_utf16(selection.start, Bias::Left)
16015 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16016 })
16017 .collect()
16018 }
16019
16020 fn report_editor_event(
16021 &self,
16022 event_type: &'static str,
16023 file_extension: Option<String>,
16024 cx: &App,
16025 ) {
16026 if cfg!(any(test, feature = "test-support")) {
16027 return;
16028 }
16029
16030 let Some(project) = &self.project else { return };
16031
16032 // If None, we are in a file without an extension
16033 let file = self
16034 .buffer
16035 .read(cx)
16036 .as_singleton()
16037 .and_then(|b| b.read(cx).file());
16038 let file_extension = file_extension.or(file
16039 .as_ref()
16040 .and_then(|file| Path::new(file.file_name(cx)).extension())
16041 .and_then(|e| e.to_str())
16042 .map(|a| a.to_string()));
16043
16044 let vim_mode = cx
16045 .global::<SettingsStore>()
16046 .raw_user_settings()
16047 .get("vim_mode")
16048 == Some(&serde_json::Value::Bool(true));
16049
16050 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16051 let copilot_enabled = edit_predictions_provider
16052 == language::language_settings::EditPredictionProvider::Copilot;
16053 let copilot_enabled_for_language = self
16054 .buffer
16055 .read(cx)
16056 .language_settings(cx)
16057 .show_edit_predictions;
16058
16059 let project = project.read(cx);
16060 telemetry::event!(
16061 event_type,
16062 file_extension,
16063 vim_mode,
16064 copilot_enabled,
16065 copilot_enabled_for_language,
16066 edit_predictions_provider,
16067 is_via_ssh = project.is_via_ssh(),
16068 );
16069 }
16070
16071 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16072 /// with each line being an array of {text, highlight} objects.
16073 fn copy_highlight_json(
16074 &mut self,
16075 _: &CopyHighlightJson,
16076 window: &mut Window,
16077 cx: &mut Context<Self>,
16078 ) {
16079 #[derive(Serialize)]
16080 struct Chunk<'a> {
16081 text: String,
16082 highlight: Option<&'a str>,
16083 }
16084
16085 let snapshot = self.buffer.read(cx).snapshot(cx);
16086 let range = self
16087 .selected_text_range(false, window, cx)
16088 .and_then(|selection| {
16089 if selection.range.is_empty() {
16090 None
16091 } else {
16092 Some(selection.range)
16093 }
16094 })
16095 .unwrap_or_else(|| 0..snapshot.len());
16096
16097 let chunks = snapshot.chunks(range, true);
16098 let mut lines = Vec::new();
16099 let mut line: VecDeque<Chunk> = VecDeque::new();
16100
16101 let Some(style) = self.style.as_ref() else {
16102 return;
16103 };
16104
16105 for chunk in chunks {
16106 let highlight = chunk
16107 .syntax_highlight_id
16108 .and_then(|id| id.name(&style.syntax));
16109 let mut chunk_lines = chunk.text.split('\n').peekable();
16110 while let Some(text) = chunk_lines.next() {
16111 let mut merged_with_last_token = false;
16112 if let Some(last_token) = line.back_mut() {
16113 if last_token.highlight == highlight {
16114 last_token.text.push_str(text);
16115 merged_with_last_token = true;
16116 }
16117 }
16118
16119 if !merged_with_last_token {
16120 line.push_back(Chunk {
16121 text: text.into(),
16122 highlight,
16123 });
16124 }
16125
16126 if chunk_lines.peek().is_some() {
16127 if line.len() > 1 && line.front().unwrap().text.is_empty() {
16128 line.pop_front();
16129 }
16130 if line.len() > 1 && line.back().unwrap().text.is_empty() {
16131 line.pop_back();
16132 }
16133
16134 lines.push(mem::take(&mut line));
16135 }
16136 }
16137 }
16138
16139 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16140 return;
16141 };
16142 cx.write_to_clipboard(ClipboardItem::new_string(lines));
16143 }
16144
16145 pub fn open_context_menu(
16146 &mut self,
16147 _: &OpenContextMenu,
16148 window: &mut Window,
16149 cx: &mut Context<Self>,
16150 ) {
16151 self.request_autoscroll(Autoscroll::newest(), cx);
16152 let position = self.selections.newest_display(cx).start;
16153 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16154 }
16155
16156 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16157 &self.inlay_hint_cache
16158 }
16159
16160 pub fn replay_insert_event(
16161 &mut self,
16162 text: &str,
16163 relative_utf16_range: Option<Range<isize>>,
16164 window: &mut Window,
16165 cx: &mut Context<Self>,
16166 ) {
16167 if !self.input_enabled {
16168 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16169 return;
16170 }
16171 if let Some(relative_utf16_range) = relative_utf16_range {
16172 let selections = self.selections.all::<OffsetUtf16>(cx);
16173 self.change_selections(None, window, cx, |s| {
16174 let new_ranges = selections.into_iter().map(|range| {
16175 let start = OffsetUtf16(
16176 range
16177 .head()
16178 .0
16179 .saturating_add_signed(relative_utf16_range.start),
16180 );
16181 let end = OffsetUtf16(
16182 range
16183 .head()
16184 .0
16185 .saturating_add_signed(relative_utf16_range.end),
16186 );
16187 start..end
16188 });
16189 s.select_ranges(new_ranges);
16190 });
16191 }
16192
16193 self.handle_input(text, window, cx);
16194 }
16195
16196 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16197 let Some(provider) = self.semantics_provider.as_ref() else {
16198 return false;
16199 };
16200
16201 let mut supports = false;
16202 self.buffer().update(cx, |this, cx| {
16203 this.for_each_buffer(|buffer| {
16204 supports |= provider.supports_inlay_hints(buffer, cx);
16205 });
16206 });
16207
16208 supports
16209 }
16210
16211 pub fn is_focused(&self, window: &Window) -> bool {
16212 self.focus_handle.is_focused(window)
16213 }
16214
16215 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16216 cx.emit(EditorEvent::Focused);
16217
16218 if let Some(descendant) = self
16219 .last_focused_descendant
16220 .take()
16221 .and_then(|descendant| descendant.upgrade())
16222 {
16223 window.focus(&descendant);
16224 } else {
16225 if let Some(blame) = self.blame.as_ref() {
16226 blame.update(cx, GitBlame::focus)
16227 }
16228
16229 self.blink_manager.update(cx, BlinkManager::enable);
16230 self.show_cursor_names(window, cx);
16231 self.buffer.update(cx, |buffer, cx| {
16232 buffer.finalize_last_transaction(cx);
16233 if self.leader_peer_id.is_none() {
16234 buffer.set_active_selections(
16235 &self.selections.disjoint_anchors(),
16236 self.selections.line_mode,
16237 self.cursor_shape,
16238 cx,
16239 );
16240 }
16241 });
16242 }
16243 }
16244
16245 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16246 cx.emit(EditorEvent::FocusedIn)
16247 }
16248
16249 fn handle_focus_out(
16250 &mut self,
16251 event: FocusOutEvent,
16252 _window: &mut Window,
16253 cx: &mut Context<Self>,
16254 ) {
16255 if event.blurred != self.focus_handle {
16256 self.last_focused_descendant = Some(event.blurred);
16257 }
16258 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16259 }
16260
16261 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16262 self.blink_manager.update(cx, BlinkManager::disable);
16263 self.buffer
16264 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16265
16266 if let Some(blame) = self.blame.as_ref() {
16267 blame.update(cx, GitBlame::blur)
16268 }
16269 if !self.hover_state.focused(window, cx) {
16270 hide_hover(self, cx);
16271 }
16272 if !self
16273 .context_menu
16274 .borrow()
16275 .as_ref()
16276 .is_some_and(|context_menu| context_menu.focused(window, cx))
16277 {
16278 self.hide_context_menu(window, cx);
16279 }
16280 self.discard_inline_completion(false, cx);
16281 cx.emit(EditorEvent::Blurred);
16282 cx.notify();
16283 }
16284
16285 pub fn register_action<A: Action>(
16286 &mut self,
16287 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16288 ) -> Subscription {
16289 let id = self.next_editor_action_id.post_inc();
16290 let listener = Arc::new(listener);
16291 self.editor_actions.borrow_mut().insert(
16292 id,
16293 Box::new(move |window, _| {
16294 let listener = listener.clone();
16295 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16296 let action = action.downcast_ref().unwrap();
16297 if phase == DispatchPhase::Bubble {
16298 listener(action, window, cx)
16299 }
16300 })
16301 }),
16302 );
16303
16304 let editor_actions = self.editor_actions.clone();
16305 Subscription::new(move || {
16306 editor_actions.borrow_mut().remove(&id);
16307 })
16308 }
16309
16310 pub fn file_header_size(&self) -> u32 {
16311 FILE_HEADER_HEIGHT
16312 }
16313
16314 pub fn restore(
16315 &mut self,
16316 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16317 window: &mut Window,
16318 cx: &mut Context<Self>,
16319 ) {
16320 let workspace = self.workspace();
16321 let project = self.project.as_ref();
16322 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16323 let mut tasks = Vec::new();
16324 for (buffer_id, changes) in revert_changes {
16325 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16326 buffer.update(cx, |buffer, cx| {
16327 buffer.edit(
16328 changes
16329 .into_iter()
16330 .map(|(range, text)| (range, text.to_string())),
16331 None,
16332 cx,
16333 );
16334 });
16335
16336 if let Some(project) =
16337 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16338 {
16339 project.update(cx, |project, cx| {
16340 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16341 })
16342 }
16343 }
16344 }
16345 tasks
16346 });
16347 cx.spawn_in(window, |_, mut cx| async move {
16348 for (buffer, task) in save_tasks {
16349 let result = task.await;
16350 if result.is_err() {
16351 let Some(path) = buffer
16352 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16353 .ok()
16354 else {
16355 continue;
16356 };
16357 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16358 let Some(task) = cx
16359 .update_window_entity(&workspace, |workspace, window, cx| {
16360 workspace
16361 .open_path_preview(path, None, false, false, false, window, cx)
16362 })
16363 .ok()
16364 else {
16365 continue;
16366 };
16367 task.await.log_err();
16368 }
16369 }
16370 }
16371 })
16372 .detach();
16373 self.change_selections(None, window, cx, |selections| selections.refresh());
16374 }
16375
16376 pub fn to_pixel_point(
16377 &self,
16378 source: multi_buffer::Anchor,
16379 editor_snapshot: &EditorSnapshot,
16380 window: &mut Window,
16381 ) -> Option<gpui::Point<Pixels>> {
16382 let source_point = source.to_display_point(editor_snapshot);
16383 self.display_to_pixel_point(source_point, editor_snapshot, window)
16384 }
16385
16386 pub fn display_to_pixel_point(
16387 &self,
16388 source: DisplayPoint,
16389 editor_snapshot: &EditorSnapshot,
16390 window: &mut Window,
16391 ) -> Option<gpui::Point<Pixels>> {
16392 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16393 let text_layout_details = self.text_layout_details(window);
16394 let scroll_top = text_layout_details
16395 .scroll_anchor
16396 .scroll_position(editor_snapshot)
16397 .y;
16398
16399 if source.row().as_f32() < scroll_top.floor() {
16400 return None;
16401 }
16402 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16403 let source_y = line_height * (source.row().as_f32() - scroll_top);
16404 Some(gpui::Point::new(source_x, source_y))
16405 }
16406
16407 pub fn has_visible_completions_menu(&self) -> bool {
16408 !self.edit_prediction_preview_is_active()
16409 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16410 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16411 })
16412 }
16413
16414 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16415 self.addons
16416 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16417 }
16418
16419 pub fn unregister_addon<T: Addon>(&mut self) {
16420 self.addons.remove(&std::any::TypeId::of::<T>());
16421 }
16422
16423 pub fn addon<T: Addon>(&self) -> Option<&T> {
16424 let type_id = std::any::TypeId::of::<T>();
16425 self.addons
16426 .get(&type_id)
16427 .and_then(|item| item.to_any().downcast_ref::<T>())
16428 }
16429
16430 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16431 let text_layout_details = self.text_layout_details(window);
16432 let style = &text_layout_details.editor_style;
16433 let font_id = window.text_system().resolve_font(&style.text.font());
16434 let font_size = style.text.font_size.to_pixels(window.rem_size());
16435 let line_height = style.text.line_height_in_pixels(window.rem_size());
16436 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16437
16438 gpui::Size::new(em_width, line_height)
16439 }
16440
16441 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16442 self.load_diff_task.clone()
16443 }
16444
16445 fn read_selections_from_db(
16446 &mut self,
16447 item_id: u64,
16448 workspace_id: WorkspaceId,
16449 window: &mut Window,
16450 cx: &mut Context<Editor>,
16451 ) {
16452 if !self.is_singleton(cx)
16453 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16454 {
16455 return;
16456 }
16457 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16458 return;
16459 };
16460 if selections.is_empty() {
16461 return;
16462 }
16463
16464 let snapshot = self.buffer.read(cx).snapshot(cx);
16465 self.change_selections(None, window, cx, |s| {
16466 s.select_ranges(selections.into_iter().map(|(start, end)| {
16467 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16468 }));
16469 });
16470 }
16471}
16472
16473fn insert_extra_newline_brackets(
16474 buffer: &MultiBufferSnapshot,
16475 range: Range<usize>,
16476 language: &language::LanguageScope,
16477) -> bool {
16478 let leading_whitespace_len = buffer
16479 .reversed_chars_at(range.start)
16480 .take_while(|c| c.is_whitespace() && *c != '\n')
16481 .map(|c| c.len_utf8())
16482 .sum::<usize>();
16483 let trailing_whitespace_len = buffer
16484 .chars_at(range.end)
16485 .take_while(|c| c.is_whitespace() && *c != '\n')
16486 .map(|c| c.len_utf8())
16487 .sum::<usize>();
16488 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16489
16490 language.brackets().any(|(pair, enabled)| {
16491 let pair_start = pair.start.trim_end();
16492 let pair_end = pair.end.trim_start();
16493
16494 enabled
16495 && pair.newline
16496 && buffer.contains_str_at(range.end, pair_end)
16497 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16498 })
16499}
16500
16501fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16502 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16503 [(buffer, range, _)] => (*buffer, range.clone()),
16504 _ => return false,
16505 };
16506 let pair = {
16507 let mut result: Option<BracketMatch> = None;
16508
16509 for pair in buffer
16510 .all_bracket_ranges(range.clone())
16511 .filter(move |pair| {
16512 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16513 })
16514 {
16515 let len = pair.close_range.end - pair.open_range.start;
16516
16517 if let Some(existing) = &result {
16518 let existing_len = existing.close_range.end - existing.open_range.start;
16519 if len > existing_len {
16520 continue;
16521 }
16522 }
16523
16524 result = Some(pair);
16525 }
16526
16527 result
16528 };
16529 let Some(pair) = pair else {
16530 return false;
16531 };
16532 pair.newline_only
16533 && buffer
16534 .chars_for_range(pair.open_range.end..range.start)
16535 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16536 .all(|c| c.is_whitespace() && c != '\n')
16537}
16538
16539fn get_uncommitted_diff_for_buffer(
16540 project: &Entity<Project>,
16541 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16542 buffer: Entity<MultiBuffer>,
16543 cx: &mut App,
16544) -> Task<()> {
16545 let mut tasks = Vec::new();
16546 project.update(cx, |project, cx| {
16547 for buffer in buffers {
16548 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16549 }
16550 });
16551 cx.spawn(|mut cx| async move {
16552 let diffs = future::join_all(tasks).await;
16553 buffer
16554 .update(&mut cx, |buffer, cx| {
16555 for diff in diffs.into_iter().flatten() {
16556 buffer.add_diff(diff, cx);
16557 }
16558 })
16559 .ok();
16560 })
16561}
16562
16563fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16564 let tab_size = tab_size.get() as usize;
16565 let mut width = offset;
16566
16567 for ch in text.chars() {
16568 width += if ch == '\t' {
16569 tab_size - (width % tab_size)
16570 } else {
16571 1
16572 };
16573 }
16574
16575 width - offset
16576}
16577
16578#[cfg(test)]
16579mod tests {
16580 use super::*;
16581
16582 #[test]
16583 fn test_string_size_with_expanded_tabs() {
16584 let nz = |val| NonZeroU32::new(val).unwrap();
16585 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16586 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16587 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16588 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16589 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16590 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16591 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16592 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16593 }
16594}
16595
16596/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16597struct WordBreakingTokenizer<'a> {
16598 input: &'a str,
16599}
16600
16601impl<'a> WordBreakingTokenizer<'a> {
16602 fn new(input: &'a str) -> Self {
16603 Self { input }
16604 }
16605}
16606
16607fn is_char_ideographic(ch: char) -> bool {
16608 use unicode_script::Script::*;
16609 use unicode_script::UnicodeScript;
16610 matches!(ch.script(), Han | Tangut | Yi)
16611}
16612
16613fn is_grapheme_ideographic(text: &str) -> bool {
16614 text.chars().any(is_char_ideographic)
16615}
16616
16617fn is_grapheme_whitespace(text: &str) -> bool {
16618 text.chars().any(|x| x.is_whitespace())
16619}
16620
16621fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16622 text.chars().next().map_or(false, |ch| {
16623 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16624 })
16625}
16626
16627#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16628struct WordBreakToken<'a> {
16629 token: &'a str,
16630 grapheme_len: usize,
16631 is_whitespace: bool,
16632}
16633
16634impl<'a> Iterator for WordBreakingTokenizer<'a> {
16635 /// Yields a span, the count of graphemes in the token, and whether it was
16636 /// whitespace. Note that it also breaks at word boundaries.
16637 type Item = WordBreakToken<'a>;
16638
16639 fn next(&mut self) -> Option<Self::Item> {
16640 use unicode_segmentation::UnicodeSegmentation;
16641 if self.input.is_empty() {
16642 return None;
16643 }
16644
16645 let mut iter = self.input.graphemes(true).peekable();
16646 let mut offset = 0;
16647 let mut graphemes = 0;
16648 if let Some(first_grapheme) = iter.next() {
16649 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16650 offset += first_grapheme.len();
16651 graphemes += 1;
16652 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16653 if let Some(grapheme) = iter.peek().copied() {
16654 if should_stay_with_preceding_ideograph(grapheme) {
16655 offset += grapheme.len();
16656 graphemes += 1;
16657 }
16658 }
16659 } else {
16660 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16661 let mut next_word_bound = words.peek().copied();
16662 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16663 next_word_bound = words.next();
16664 }
16665 while let Some(grapheme) = iter.peek().copied() {
16666 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16667 break;
16668 };
16669 if is_grapheme_whitespace(grapheme) != is_whitespace {
16670 break;
16671 };
16672 offset += grapheme.len();
16673 graphemes += 1;
16674 iter.next();
16675 }
16676 }
16677 let token = &self.input[..offset];
16678 self.input = &self.input[offset..];
16679 if is_whitespace {
16680 Some(WordBreakToken {
16681 token: " ",
16682 grapheme_len: 1,
16683 is_whitespace: true,
16684 })
16685 } else {
16686 Some(WordBreakToken {
16687 token,
16688 grapheme_len: graphemes,
16689 is_whitespace: false,
16690 })
16691 }
16692 } else {
16693 None
16694 }
16695 }
16696}
16697
16698#[test]
16699fn test_word_breaking_tokenizer() {
16700 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16701 ("", &[]),
16702 (" ", &[(" ", 1, true)]),
16703 ("Ʒ", &[("Ʒ", 1, false)]),
16704 ("Ǽ", &[("Ǽ", 1, false)]),
16705 ("⋑", &[("⋑", 1, false)]),
16706 ("⋑⋑", &[("⋑⋑", 2, false)]),
16707 (
16708 "原理,进而",
16709 &[
16710 ("原", 1, false),
16711 ("理,", 2, false),
16712 ("进", 1, false),
16713 ("而", 1, false),
16714 ],
16715 ),
16716 (
16717 "hello world",
16718 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16719 ),
16720 (
16721 "hello, world",
16722 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16723 ),
16724 (
16725 " hello world",
16726 &[
16727 (" ", 1, true),
16728 ("hello", 5, false),
16729 (" ", 1, true),
16730 ("world", 5, false),
16731 ],
16732 ),
16733 (
16734 "这是什么 \n 钢笔",
16735 &[
16736 ("这", 1, false),
16737 ("是", 1, false),
16738 ("什", 1, false),
16739 ("么", 1, false),
16740 (" ", 1, true),
16741 ("钢", 1, false),
16742 ("笔", 1, false),
16743 ],
16744 ),
16745 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16746 ];
16747
16748 for (input, result) in tests {
16749 assert_eq!(
16750 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16751 result
16752 .iter()
16753 .copied()
16754 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16755 token,
16756 grapheme_len,
16757 is_whitespace,
16758 })
16759 .collect::<Vec<_>>()
16760 );
16761 }
16762}
16763
16764fn wrap_with_prefix(
16765 line_prefix: String,
16766 unwrapped_text: String,
16767 wrap_column: usize,
16768 tab_size: NonZeroU32,
16769) -> String {
16770 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16771 let mut wrapped_text = String::new();
16772 let mut current_line = line_prefix.clone();
16773
16774 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16775 let mut current_line_len = line_prefix_len;
16776 for WordBreakToken {
16777 token,
16778 grapheme_len,
16779 is_whitespace,
16780 } in tokenizer
16781 {
16782 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16783 wrapped_text.push_str(current_line.trim_end());
16784 wrapped_text.push('\n');
16785 current_line.truncate(line_prefix.len());
16786 current_line_len = line_prefix_len;
16787 if !is_whitespace {
16788 current_line.push_str(token);
16789 current_line_len += grapheme_len;
16790 }
16791 } else if !is_whitespace {
16792 current_line.push_str(token);
16793 current_line_len += grapheme_len;
16794 } else if current_line_len != line_prefix_len {
16795 current_line.push(' ');
16796 current_line_len += 1;
16797 }
16798 }
16799
16800 if !current_line.is_empty() {
16801 wrapped_text.push_str(¤t_line);
16802 }
16803 wrapped_text
16804}
16805
16806#[test]
16807fn test_wrap_with_prefix() {
16808 assert_eq!(
16809 wrap_with_prefix(
16810 "# ".to_string(),
16811 "abcdefg".to_string(),
16812 4,
16813 NonZeroU32::new(4).unwrap()
16814 ),
16815 "# abcdefg"
16816 );
16817 assert_eq!(
16818 wrap_with_prefix(
16819 "".to_string(),
16820 "\thello world".to_string(),
16821 8,
16822 NonZeroU32::new(4).unwrap()
16823 ),
16824 "hello\nworld"
16825 );
16826 assert_eq!(
16827 wrap_with_prefix(
16828 "// ".to_string(),
16829 "xx \nyy zz aa bb cc".to_string(),
16830 12,
16831 NonZeroU32::new(4).unwrap()
16832 ),
16833 "// xx yy zz\n// aa bb cc"
16834 );
16835 assert_eq!(
16836 wrap_with_prefix(
16837 String::new(),
16838 "这是什么 \n 钢笔".to_string(),
16839 3,
16840 NonZeroU32::new(4).unwrap()
16841 ),
16842 "这是什\n么 钢\n笔"
16843 );
16844}
16845
16846pub trait CollaborationHub {
16847 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16848 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16849 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16850}
16851
16852impl CollaborationHub for Entity<Project> {
16853 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16854 self.read(cx).collaborators()
16855 }
16856
16857 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16858 self.read(cx).user_store().read(cx).participant_indices()
16859 }
16860
16861 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16862 let this = self.read(cx);
16863 let user_ids = this.collaborators().values().map(|c| c.user_id);
16864 this.user_store().read_with(cx, |user_store, cx| {
16865 user_store.participant_names(user_ids, cx)
16866 })
16867 }
16868}
16869
16870pub trait SemanticsProvider {
16871 fn hover(
16872 &self,
16873 buffer: &Entity<Buffer>,
16874 position: text::Anchor,
16875 cx: &mut App,
16876 ) -> Option<Task<Vec<project::Hover>>>;
16877
16878 fn inlay_hints(
16879 &self,
16880 buffer_handle: Entity<Buffer>,
16881 range: Range<text::Anchor>,
16882 cx: &mut App,
16883 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16884
16885 fn resolve_inlay_hint(
16886 &self,
16887 hint: InlayHint,
16888 buffer_handle: Entity<Buffer>,
16889 server_id: LanguageServerId,
16890 cx: &mut App,
16891 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16892
16893 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16894
16895 fn document_highlights(
16896 &self,
16897 buffer: &Entity<Buffer>,
16898 position: text::Anchor,
16899 cx: &mut App,
16900 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16901
16902 fn definitions(
16903 &self,
16904 buffer: &Entity<Buffer>,
16905 position: text::Anchor,
16906 kind: GotoDefinitionKind,
16907 cx: &mut App,
16908 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16909
16910 fn range_for_rename(
16911 &self,
16912 buffer: &Entity<Buffer>,
16913 position: text::Anchor,
16914 cx: &mut App,
16915 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16916
16917 fn perform_rename(
16918 &self,
16919 buffer: &Entity<Buffer>,
16920 position: text::Anchor,
16921 new_name: String,
16922 cx: &mut App,
16923 ) -> Option<Task<Result<ProjectTransaction>>>;
16924}
16925
16926pub trait CompletionProvider {
16927 fn completions(
16928 &self,
16929 buffer: &Entity<Buffer>,
16930 buffer_position: text::Anchor,
16931 trigger: CompletionContext,
16932 window: &mut Window,
16933 cx: &mut Context<Editor>,
16934 ) -> Task<Result<Vec<Completion>>>;
16935
16936 fn resolve_completions(
16937 &self,
16938 buffer: Entity<Buffer>,
16939 completion_indices: Vec<usize>,
16940 completions: Rc<RefCell<Box<[Completion]>>>,
16941 cx: &mut Context<Editor>,
16942 ) -> Task<Result<bool>>;
16943
16944 fn apply_additional_edits_for_completion(
16945 &self,
16946 _buffer: Entity<Buffer>,
16947 _completions: Rc<RefCell<Box<[Completion]>>>,
16948 _completion_index: usize,
16949 _push_to_history: bool,
16950 _cx: &mut Context<Editor>,
16951 ) -> Task<Result<Option<language::Transaction>>> {
16952 Task::ready(Ok(None))
16953 }
16954
16955 fn is_completion_trigger(
16956 &self,
16957 buffer: &Entity<Buffer>,
16958 position: language::Anchor,
16959 text: &str,
16960 trigger_in_words: bool,
16961 cx: &mut Context<Editor>,
16962 ) -> bool;
16963
16964 fn sort_completions(&self) -> bool {
16965 true
16966 }
16967}
16968
16969pub trait CodeActionProvider {
16970 fn id(&self) -> Arc<str>;
16971
16972 fn code_actions(
16973 &self,
16974 buffer: &Entity<Buffer>,
16975 range: Range<text::Anchor>,
16976 window: &mut Window,
16977 cx: &mut App,
16978 ) -> Task<Result<Vec<CodeAction>>>;
16979
16980 fn apply_code_action(
16981 &self,
16982 buffer_handle: Entity<Buffer>,
16983 action: CodeAction,
16984 excerpt_id: ExcerptId,
16985 push_to_history: bool,
16986 window: &mut Window,
16987 cx: &mut App,
16988 ) -> Task<Result<ProjectTransaction>>;
16989}
16990
16991impl CodeActionProvider for Entity<Project> {
16992 fn id(&self) -> Arc<str> {
16993 "project".into()
16994 }
16995
16996 fn code_actions(
16997 &self,
16998 buffer: &Entity<Buffer>,
16999 range: Range<text::Anchor>,
17000 _window: &mut Window,
17001 cx: &mut App,
17002 ) -> Task<Result<Vec<CodeAction>>> {
17003 self.update(cx, |project, cx| {
17004 project.code_actions(buffer, range, None, cx)
17005 })
17006 }
17007
17008 fn apply_code_action(
17009 &self,
17010 buffer_handle: Entity<Buffer>,
17011 action: CodeAction,
17012 _excerpt_id: ExcerptId,
17013 push_to_history: bool,
17014 _window: &mut Window,
17015 cx: &mut App,
17016 ) -> Task<Result<ProjectTransaction>> {
17017 self.update(cx, |project, cx| {
17018 project.apply_code_action(buffer_handle, action, push_to_history, cx)
17019 })
17020 }
17021}
17022
17023fn snippet_completions(
17024 project: &Project,
17025 buffer: &Entity<Buffer>,
17026 buffer_position: text::Anchor,
17027 cx: &mut App,
17028) -> Task<Result<Vec<Completion>>> {
17029 let language = buffer.read(cx).language_at(buffer_position);
17030 let language_name = language.as_ref().map(|language| language.lsp_id());
17031 let snippet_store = project.snippets().read(cx);
17032 let snippets = snippet_store.snippets_for(language_name, cx);
17033
17034 if snippets.is_empty() {
17035 return Task::ready(Ok(vec![]));
17036 }
17037 let snapshot = buffer.read(cx).text_snapshot();
17038 let chars: String = snapshot
17039 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17040 .collect();
17041
17042 let scope = language.map(|language| language.default_scope());
17043 let executor = cx.background_executor().clone();
17044
17045 cx.background_spawn(async move {
17046 let classifier = CharClassifier::new(scope).for_completion(true);
17047 let mut last_word = chars
17048 .chars()
17049 .take_while(|c| classifier.is_word(*c))
17050 .collect::<String>();
17051 last_word = last_word.chars().rev().collect();
17052
17053 if last_word.is_empty() {
17054 return Ok(vec![]);
17055 }
17056
17057 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17058 let to_lsp = |point: &text::Anchor| {
17059 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
17060 point_to_lsp(end)
17061 };
17062 let lsp_end = to_lsp(&buffer_position);
17063
17064 let candidates = snippets
17065 .iter()
17066 .enumerate()
17067 .flat_map(|(ix, snippet)| {
17068 snippet
17069 .prefix
17070 .iter()
17071 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
17072 })
17073 .collect::<Vec<StringMatchCandidate>>();
17074
17075 let mut matches = fuzzy::match_strings(
17076 &candidates,
17077 &last_word,
17078 last_word.chars().any(|c| c.is_uppercase()),
17079 100,
17080 &Default::default(),
17081 executor,
17082 )
17083 .await;
17084
17085 // Remove all candidates where the query's start does not match the start of any word in the candidate
17086 if let Some(query_start) = last_word.chars().next() {
17087 matches.retain(|string_match| {
17088 split_words(&string_match.string).any(|word| {
17089 // Check that the first codepoint of the word as lowercase matches the first
17090 // codepoint of the query as lowercase
17091 word.chars()
17092 .flat_map(|codepoint| codepoint.to_lowercase())
17093 .zip(query_start.to_lowercase())
17094 .all(|(word_cp, query_cp)| word_cp == query_cp)
17095 })
17096 });
17097 }
17098
17099 let matched_strings = matches
17100 .into_iter()
17101 .map(|m| m.string)
17102 .collect::<HashSet<_>>();
17103
17104 let result: Vec<Completion> = snippets
17105 .into_iter()
17106 .filter_map(|snippet| {
17107 let matching_prefix = snippet
17108 .prefix
17109 .iter()
17110 .find(|prefix| matched_strings.contains(*prefix))?;
17111 let start = as_offset - last_word.len();
17112 let start = snapshot.anchor_before(start);
17113 let range = start..buffer_position;
17114 let lsp_start = to_lsp(&start);
17115 let lsp_range = lsp::Range {
17116 start: lsp_start,
17117 end: lsp_end,
17118 };
17119 Some(Completion {
17120 old_range: range,
17121 new_text: snippet.body.clone(),
17122 source: CompletionSource::Lsp {
17123 server_id: LanguageServerId(usize::MAX),
17124 resolved: true,
17125 lsp_completion: Box::new(lsp::CompletionItem {
17126 label: snippet.prefix.first().unwrap().clone(),
17127 kind: Some(CompletionItemKind::SNIPPET),
17128 label_details: snippet.description.as_ref().map(|description| {
17129 lsp::CompletionItemLabelDetails {
17130 detail: Some(description.clone()),
17131 description: None,
17132 }
17133 }),
17134 insert_text_format: Some(InsertTextFormat::SNIPPET),
17135 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17136 lsp::InsertReplaceEdit {
17137 new_text: snippet.body.clone(),
17138 insert: lsp_range,
17139 replace: lsp_range,
17140 },
17141 )),
17142 filter_text: Some(snippet.body.clone()),
17143 sort_text: Some(char::MAX.to_string()),
17144 ..lsp::CompletionItem::default()
17145 }),
17146 lsp_defaults: None,
17147 },
17148 label: CodeLabel {
17149 text: matching_prefix.clone(),
17150 runs: Vec::new(),
17151 filter_range: 0..matching_prefix.len(),
17152 },
17153 documentation: snippet
17154 .description
17155 .clone()
17156 .map(|description| CompletionDocumentation::SingleLine(description.into())),
17157 confirm: None,
17158 })
17159 })
17160 .collect();
17161
17162 Ok(result)
17163 })
17164}
17165
17166impl CompletionProvider for Entity<Project> {
17167 fn completions(
17168 &self,
17169 buffer: &Entity<Buffer>,
17170 buffer_position: text::Anchor,
17171 options: CompletionContext,
17172 _window: &mut Window,
17173 cx: &mut Context<Editor>,
17174 ) -> Task<Result<Vec<Completion>>> {
17175 self.update(cx, |project, cx| {
17176 let snippets = snippet_completions(project, buffer, buffer_position, cx);
17177 let project_completions = project.completions(buffer, buffer_position, options, cx);
17178 cx.background_spawn(async move {
17179 let mut completions = project_completions.await?;
17180 let snippets_completions = snippets.await?;
17181 completions.extend(snippets_completions);
17182 Ok(completions)
17183 })
17184 })
17185 }
17186
17187 fn resolve_completions(
17188 &self,
17189 buffer: Entity<Buffer>,
17190 completion_indices: Vec<usize>,
17191 completions: Rc<RefCell<Box<[Completion]>>>,
17192 cx: &mut Context<Editor>,
17193 ) -> Task<Result<bool>> {
17194 self.update(cx, |project, cx| {
17195 project.lsp_store().update(cx, |lsp_store, cx| {
17196 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17197 })
17198 })
17199 }
17200
17201 fn apply_additional_edits_for_completion(
17202 &self,
17203 buffer: Entity<Buffer>,
17204 completions: Rc<RefCell<Box<[Completion]>>>,
17205 completion_index: usize,
17206 push_to_history: bool,
17207 cx: &mut Context<Editor>,
17208 ) -> Task<Result<Option<language::Transaction>>> {
17209 self.update(cx, |project, cx| {
17210 project.lsp_store().update(cx, |lsp_store, cx| {
17211 lsp_store.apply_additional_edits_for_completion(
17212 buffer,
17213 completions,
17214 completion_index,
17215 push_to_history,
17216 cx,
17217 )
17218 })
17219 })
17220 }
17221
17222 fn is_completion_trigger(
17223 &self,
17224 buffer: &Entity<Buffer>,
17225 position: language::Anchor,
17226 text: &str,
17227 trigger_in_words: bool,
17228 cx: &mut Context<Editor>,
17229 ) -> bool {
17230 let mut chars = text.chars();
17231 let char = if let Some(char) = chars.next() {
17232 char
17233 } else {
17234 return false;
17235 };
17236 if chars.next().is_some() {
17237 return false;
17238 }
17239
17240 let buffer = buffer.read(cx);
17241 let snapshot = buffer.snapshot();
17242 if !snapshot.settings_at(position, cx).show_completions_on_input {
17243 return false;
17244 }
17245 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17246 if trigger_in_words && classifier.is_word(char) {
17247 return true;
17248 }
17249
17250 buffer.completion_triggers().contains(text)
17251 }
17252}
17253
17254impl SemanticsProvider for Entity<Project> {
17255 fn hover(
17256 &self,
17257 buffer: &Entity<Buffer>,
17258 position: text::Anchor,
17259 cx: &mut App,
17260 ) -> Option<Task<Vec<project::Hover>>> {
17261 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17262 }
17263
17264 fn document_highlights(
17265 &self,
17266 buffer: &Entity<Buffer>,
17267 position: text::Anchor,
17268 cx: &mut App,
17269 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17270 Some(self.update(cx, |project, cx| {
17271 project.document_highlights(buffer, position, cx)
17272 }))
17273 }
17274
17275 fn definitions(
17276 &self,
17277 buffer: &Entity<Buffer>,
17278 position: text::Anchor,
17279 kind: GotoDefinitionKind,
17280 cx: &mut App,
17281 ) -> Option<Task<Result<Vec<LocationLink>>>> {
17282 Some(self.update(cx, |project, cx| match kind {
17283 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17284 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17285 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17286 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17287 }))
17288 }
17289
17290 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17291 // TODO: make this work for remote projects
17292 self.update(cx, |this, cx| {
17293 buffer.update(cx, |buffer, cx| {
17294 this.any_language_server_supports_inlay_hints(buffer, cx)
17295 })
17296 })
17297 }
17298
17299 fn inlay_hints(
17300 &self,
17301 buffer_handle: Entity<Buffer>,
17302 range: Range<text::Anchor>,
17303 cx: &mut App,
17304 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17305 Some(self.update(cx, |project, cx| {
17306 project.inlay_hints(buffer_handle, range, cx)
17307 }))
17308 }
17309
17310 fn resolve_inlay_hint(
17311 &self,
17312 hint: InlayHint,
17313 buffer_handle: Entity<Buffer>,
17314 server_id: LanguageServerId,
17315 cx: &mut App,
17316 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17317 Some(self.update(cx, |project, cx| {
17318 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17319 }))
17320 }
17321
17322 fn range_for_rename(
17323 &self,
17324 buffer: &Entity<Buffer>,
17325 position: text::Anchor,
17326 cx: &mut App,
17327 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17328 Some(self.update(cx, |project, cx| {
17329 let buffer = buffer.clone();
17330 let task = project.prepare_rename(buffer.clone(), position, cx);
17331 cx.spawn(|_, mut cx| async move {
17332 Ok(match task.await? {
17333 PrepareRenameResponse::Success(range) => Some(range),
17334 PrepareRenameResponse::InvalidPosition => None,
17335 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17336 // Fallback on using TreeSitter info to determine identifier range
17337 buffer.update(&mut cx, |buffer, _| {
17338 let snapshot = buffer.snapshot();
17339 let (range, kind) = snapshot.surrounding_word(position);
17340 if kind != Some(CharKind::Word) {
17341 return None;
17342 }
17343 Some(
17344 snapshot.anchor_before(range.start)
17345 ..snapshot.anchor_after(range.end),
17346 )
17347 })?
17348 }
17349 })
17350 })
17351 }))
17352 }
17353
17354 fn perform_rename(
17355 &self,
17356 buffer: &Entity<Buffer>,
17357 position: text::Anchor,
17358 new_name: String,
17359 cx: &mut App,
17360 ) -> Option<Task<Result<ProjectTransaction>>> {
17361 Some(self.update(cx, |project, cx| {
17362 project.perform_rename(buffer.clone(), position, new_name, cx)
17363 }))
17364 }
17365}
17366
17367fn inlay_hint_settings(
17368 location: Anchor,
17369 snapshot: &MultiBufferSnapshot,
17370 cx: &mut Context<Editor>,
17371) -> InlayHintSettings {
17372 let file = snapshot.file_at(location);
17373 let language = snapshot.language_at(location).map(|l| l.name());
17374 language_settings(language, file, cx).inlay_hints
17375}
17376
17377fn consume_contiguous_rows(
17378 contiguous_row_selections: &mut Vec<Selection<Point>>,
17379 selection: &Selection<Point>,
17380 display_map: &DisplaySnapshot,
17381 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17382) -> (MultiBufferRow, MultiBufferRow) {
17383 contiguous_row_selections.push(selection.clone());
17384 let start_row = MultiBufferRow(selection.start.row);
17385 let mut end_row = ending_row(selection, display_map);
17386
17387 while let Some(next_selection) = selections.peek() {
17388 if next_selection.start.row <= end_row.0 {
17389 end_row = ending_row(next_selection, display_map);
17390 contiguous_row_selections.push(selections.next().unwrap().clone());
17391 } else {
17392 break;
17393 }
17394 }
17395 (start_row, end_row)
17396}
17397
17398fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17399 if next_selection.end.column > 0 || next_selection.is_empty() {
17400 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17401 } else {
17402 MultiBufferRow(next_selection.end.row)
17403 }
17404}
17405
17406impl EditorSnapshot {
17407 pub fn remote_selections_in_range<'a>(
17408 &'a self,
17409 range: &'a Range<Anchor>,
17410 collaboration_hub: &dyn CollaborationHub,
17411 cx: &'a App,
17412 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17413 let participant_names = collaboration_hub.user_names(cx);
17414 let participant_indices = collaboration_hub.user_participant_indices(cx);
17415 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17416 let collaborators_by_replica_id = collaborators_by_peer_id
17417 .iter()
17418 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17419 .collect::<HashMap<_, _>>();
17420 self.buffer_snapshot
17421 .selections_in_range(range, false)
17422 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17423 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17424 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17425 let user_name = participant_names.get(&collaborator.user_id).cloned();
17426 Some(RemoteSelection {
17427 replica_id,
17428 selection,
17429 cursor_shape,
17430 line_mode,
17431 participant_index,
17432 peer_id: collaborator.peer_id,
17433 user_name,
17434 })
17435 })
17436 }
17437
17438 pub fn hunks_for_ranges(
17439 &self,
17440 ranges: impl IntoIterator<Item = Range<Point>>,
17441 ) -> Vec<MultiBufferDiffHunk> {
17442 let mut hunks = Vec::new();
17443 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17444 HashMap::default();
17445 for query_range in ranges {
17446 let query_rows =
17447 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17448 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17449 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17450 ) {
17451 // Include deleted hunks that are adjacent to the query range, because
17452 // otherwise they would be missed.
17453 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17454 if hunk.status().is_deleted() {
17455 intersects_range |= hunk.row_range.start == query_rows.end;
17456 intersects_range |= hunk.row_range.end == query_rows.start;
17457 }
17458 if intersects_range {
17459 if !processed_buffer_rows
17460 .entry(hunk.buffer_id)
17461 .or_default()
17462 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17463 {
17464 continue;
17465 }
17466 hunks.push(hunk);
17467 }
17468 }
17469 }
17470
17471 hunks
17472 }
17473
17474 fn display_diff_hunks_for_rows<'a>(
17475 &'a self,
17476 display_rows: Range<DisplayRow>,
17477 folded_buffers: &'a HashSet<BufferId>,
17478 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17479 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17480 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17481
17482 self.buffer_snapshot
17483 .diff_hunks_in_range(buffer_start..buffer_end)
17484 .filter_map(|hunk| {
17485 if folded_buffers.contains(&hunk.buffer_id) {
17486 return None;
17487 }
17488
17489 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17490 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17491
17492 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17493 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17494
17495 let display_hunk = if hunk_display_start.column() != 0 {
17496 DisplayDiffHunk::Folded {
17497 display_row: hunk_display_start.row(),
17498 }
17499 } else {
17500 let mut end_row = hunk_display_end.row();
17501 if hunk_display_end.column() > 0 {
17502 end_row.0 += 1;
17503 }
17504 let is_created_file = hunk.is_created_file();
17505 DisplayDiffHunk::Unfolded {
17506 status: hunk.status(),
17507 diff_base_byte_range: hunk.diff_base_byte_range,
17508 display_row_range: hunk_display_start.row()..end_row,
17509 multi_buffer_range: Anchor::range_in_buffer(
17510 hunk.excerpt_id,
17511 hunk.buffer_id,
17512 hunk.buffer_range,
17513 ),
17514 is_created_file,
17515 }
17516 };
17517
17518 Some(display_hunk)
17519 })
17520 }
17521
17522 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17523 self.display_snapshot.buffer_snapshot.language_at(position)
17524 }
17525
17526 pub fn is_focused(&self) -> bool {
17527 self.is_focused
17528 }
17529
17530 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17531 self.placeholder_text.as_ref()
17532 }
17533
17534 pub fn scroll_position(&self) -> gpui::Point<f32> {
17535 self.scroll_anchor.scroll_position(&self.display_snapshot)
17536 }
17537
17538 fn gutter_dimensions(
17539 &self,
17540 font_id: FontId,
17541 font_size: Pixels,
17542 max_line_number_width: Pixels,
17543 cx: &App,
17544 ) -> Option<GutterDimensions> {
17545 if !self.show_gutter {
17546 return None;
17547 }
17548
17549 let descent = cx.text_system().descent(font_id, font_size);
17550 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17551 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17552
17553 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17554 matches!(
17555 ProjectSettings::get_global(cx).git.git_gutter,
17556 Some(GitGutterSetting::TrackedFiles)
17557 )
17558 });
17559 let gutter_settings = EditorSettings::get_global(cx).gutter;
17560 let show_line_numbers = self
17561 .show_line_numbers
17562 .unwrap_or(gutter_settings.line_numbers);
17563 let line_gutter_width = if show_line_numbers {
17564 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17565 let min_width_for_number_on_gutter = em_advance * 4.0;
17566 max_line_number_width.max(min_width_for_number_on_gutter)
17567 } else {
17568 0.0.into()
17569 };
17570
17571 let show_code_actions = self
17572 .show_code_actions
17573 .unwrap_or(gutter_settings.code_actions);
17574
17575 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17576
17577 let git_blame_entries_width =
17578 self.git_blame_gutter_max_author_length
17579 .map(|max_author_length| {
17580 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17581
17582 /// The number of characters to dedicate to gaps and margins.
17583 const SPACING_WIDTH: usize = 4;
17584
17585 let max_char_count = max_author_length
17586 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17587 + ::git::SHORT_SHA_LENGTH
17588 + MAX_RELATIVE_TIMESTAMP.len()
17589 + SPACING_WIDTH;
17590
17591 em_advance * max_char_count
17592 });
17593
17594 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17595 left_padding += if show_code_actions || show_runnables {
17596 em_width * 3.0
17597 } else if show_git_gutter && show_line_numbers {
17598 em_width * 2.0
17599 } else if show_git_gutter || show_line_numbers {
17600 em_width
17601 } else {
17602 px(0.)
17603 };
17604
17605 let right_padding = if gutter_settings.folds && show_line_numbers {
17606 em_width * 4.0
17607 } else if gutter_settings.folds {
17608 em_width * 3.0
17609 } else if show_line_numbers {
17610 em_width
17611 } else {
17612 px(0.)
17613 };
17614
17615 Some(GutterDimensions {
17616 left_padding,
17617 right_padding,
17618 width: line_gutter_width + left_padding + right_padding,
17619 margin: -descent,
17620 git_blame_entries_width,
17621 })
17622 }
17623
17624 pub fn render_crease_toggle(
17625 &self,
17626 buffer_row: MultiBufferRow,
17627 row_contains_cursor: bool,
17628 editor: Entity<Editor>,
17629 window: &mut Window,
17630 cx: &mut App,
17631 ) -> Option<AnyElement> {
17632 let folded = self.is_line_folded(buffer_row);
17633 let mut is_foldable = false;
17634
17635 if let Some(crease) = self
17636 .crease_snapshot
17637 .query_row(buffer_row, &self.buffer_snapshot)
17638 {
17639 is_foldable = true;
17640 match crease {
17641 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17642 if let Some(render_toggle) = render_toggle {
17643 let toggle_callback =
17644 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17645 if folded {
17646 editor.update(cx, |editor, cx| {
17647 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17648 });
17649 } else {
17650 editor.update(cx, |editor, cx| {
17651 editor.unfold_at(
17652 &crate::UnfoldAt { buffer_row },
17653 window,
17654 cx,
17655 )
17656 });
17657 }
17658 });
17659 return Some((render_toggle)(
17660 buffer_row,
17661 folded,
17662 toggle_callback,
17663 window,
17664 cx,
17665 ));
17666 }
17667 }
17668 }
17669 }
17670
17671 is_foldable |= self.starts_indent(buffer_row);
17672
17673 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17674 Some(
17675 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17676 .toggle_state(folded)
17677 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17678 if folded {
17679 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17680 } else {
17681 this.fold_at(&FoldAt { buffer_row }, window, cx);
17682 }
17683 }))
17684 .into_any_element(),
17685 )
17686 } else {
17687 None
17688 }
17689 }
17690
17691 pub fn render_crease_trailer(
17692 &self,
17693 buffer_row: MultiBufferRow,
17694 window: &mut Window,
17695 cx: &mut App,
17696 ) -> Option<AnyElement> {
17697 let folded = self.is_line_folded(buffer_row);
17698 if let Crease::Inline { render_trailer, .. } = self
17699 .crease_snapshot
17700 .query_row(buffer_row, &self.buffer_snapshot)?
17701 {
17702 let render_trailer = render_trailer.as_ref()?;
17703 Some(render_trailer(buffer_row, folded, window, cx))
17704 } else {
17705 None
17706 }
17707 }
17708}
17709
17710impl Deref for EditorSnapshot {
17711 type Target = DisplaySnapshot;
17712
17713 fn deref(&self) -> &Self::Target {
17714 &self.display_snapshot
17715 }
17716}
17717
17718#[derive(Clone, Debug, PartialEq, Eq)]
17719pub enum EditorEvent {
17720 InputIgnored {
17721 text: Arc<str>,
17722 },
17723 InputHandled {
17724 utf16_range_to_replace: Option<Range<isize>>,
17725 text: Arc<str>,
17726 },
17727 ExcerptsAdded {
17728 buffer: Entity<Buffer>,
17729 predecessor: ExcerptId,
17730 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17731 },
17732 ExcerptsRemoved {
17733 ids: Vec<ExcerptId>,
17734 },
17735 BufferFoldToggled {
17736 ids: Vec<ExcerptId>,
17737 folded: bool,
17738 },
17739 ExcerptsEdited {
17740 ids: Vec<ExcerptId>,
17741 },
17742 ExcerptsExpanded {
17743 ids: Vec<ExcerptId>,
17744 },
17745 BufferEdited,
17746 Edited {
17747 transaction_id: clock::Lamport,
17748 },
17749 Reparsed(BufferId),
17750 Focused,
17751 FocusedIn,
17752 Blurred,
17753 DirtyChanged,
17754 Saved,
17755 TitleChanged,
17756 DiffBaseChanged,
17757 SelectionsChanged {
17758 local: bool,
17759 },
17760 ScrollPositionChanged {
17761 local: bool,
17762 autoscroll: bool,
17763 },
17764 Closed,
17765 TransactionUndone {
17766 transaction_id: clock::Lamport,
17767 },
17768 TransactionBegun {
17769 transaction_id: clock::Lamport,
17770 },
17771 Reloaded,
17772 CursorShapeChanged,
17773}
17774
17775impl EventEmitter<EditorEvent> for Editor {}
17776
17777impl Focusable for Editor {
17778 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17779 self.focus_handle.clone()
17780 }
17781}
17782
17783impl Render for Editor {
17784 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17785 let settings = ThemeSettings::get_global(cx);
17786
17787 let mut text_style = match self.mode {
17788 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17789 color: cx.theme().colors().editor_foreground,
17790 font_family: settings.ui_font.family.clone(),
17791 font_features: settings.ui_font.features.clone(),
17792 font_fallbacks: settings.ui_font.fallbacks.clone(),
17793 font_size: rems(0.875).into(),
17794 font_weight: settings.ui_font.weight,
17795 line_height: relative(settings.buffer_line_height.value()),
17796 ..Default::default()
17797 },
17798 EditorMode::Full => TextStyle {
17799 color: cx.theme().colors().editor_foreground,
17800 font_family: settings.buffer_font.family.clone(),
17801 font_features: settings.buffer_font.features.clone(),
17802 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17803 font_size: settings.buffer_font_size(cx).into(),
17804 font_weight: settings.buffer_font.weight,
17805 line_height: relative(settings.buffer_line_height.value()),
17806 ..Default::default()
17807 },
17808 };
17809 if let Some(text_style_refinement) = &self.text_style_refinement {
17810 text_style.refine(text_style_refinement)
17811 }
17812
17813 let background = match self.mode {
17814 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17815 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17816 EditorMode::Full => cx.theme().colors().editor_background,
17817 };
17818
17819 EditorElement::new(
17820 &cx.entity(),
17821 EditorStyle {
17822 background,
17823 local_player: cx.theme().players().local(),
17824 text: text_style,
17825 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17826 syntax: cx.theme().syntax().clone(),
17827 status: cx.theme().status().clone(),
17828 inlay_hints_style: make_inlay_hints_style(cx),
17829 inline_completion_styles: make_suggestion_styles(cx),
17830 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17831 },
17832 )
17833 }
17834}
17835
17836impl EntityInputHandler for Editor {
17837 fn text_for_range(
17838 &mut self,
17839 range_utf16: Range<usize>,
17840 adjusted_range: &mut Option<Range<usize>>,
17841 _: &mut Window,
17842 cx: &mut Context<Self>,
17843 ) -> Option<String> {
17844 let snapshot = self.buffer.read(cx).read(cx);
17845 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17846 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17847 if (start.0..end.0) != range_utf16 {
17848 adjusted_range.replace(start.0..end.0);
17849 }
17850 Some(snapshot.text_for_range(start..end).collect())
17851 }
17852
17853 fn selected_text_range(
17854 &mut self,
17855 ignore_disabled_input: bool,
17856 _: &mut Window,
17857 cx: &mut Context<Self>,
17858 ) -> Option<UTF16Selection> {
17859 // Prevent the IME menu from appearing when holding down an alphabetic key
17860 // while input is disabled.
17861 if !ignore_disabled_input && !self.input_enabled {
17862 return None;
17863 }
17864
17865 let selection = self.selections.newest::<OffsetUtf16>(cx);
17866 let range = selection.range();
17867
17868 Some(UTF16Selection {
17869 range: range.start.0..range.end.0,
17870 reversed: selection.reversed,
17871 })
17872 }
17873
17874 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17875 let snapshot = self.buffer.read(cx).read(cx);
17876 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17877 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17878 }
17879
17880 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17881 self.clear_highlights::<InputComposition>(cx);
17882 self.ime_transaction.take();
17883 }
17884
17885 fn replace_text_in_range(
17886 &mut self,
17887 range_utf16: Option<Range<usize>>,
17888 text: &str,
17889 window: &mut Window,
17890 cx: &mut Context<Self>,
17891 ) {
17892 if !self.input_enabled {
17893 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17894 return;
17895 }
17896
17897 self.transact(window, cx, |this, window, cx| {
17898 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17899 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17900 Some(this.selection_replacement_ranges(range_utf16, cx))
17901 } else {
17902 this.marked_text_ranges(cx)
17903 };
17904
17905 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17906 let newest_selection_id = this.selections.newest_anchor().id;
17907 this.selections
17908 .all::<OffsetUtf16>(cx)
17909 .iter()
17910 .zip(ranges_to_replace.iter())
17911 .find_map(|(selection, range)| {
17912 if selection.id == newest_selection_id {
17913 Some(
17914 (range.start.0 as isize - selection.head().0 as isize)
17915 ..(range.end.0 as isize - selection.head().0 as isize),
17916 )
17917 } else {
17918 None
17919 }
17920 })
17921 });
17922
17923 cx.emit(EditorEvent::InputHandled {
17924 utf16_range_to_replace: range_to_replace,
17925 text: text.into(),
17926 });
17927
17928 if let Some(new_selected_ranges) = new_selected_ranges {
17929 this.change_selections(None, window, cx, |selections| {
17930 selections.select_ranges(new_selected_ranges)
17931 });
17932 this.backspace(&Default::default(), window, cx);
17933 }
17934
17935 this.handle_input(text, window, cx);
17936 });
17937
17938 if let Some(transaction) = self.ime_transaction {
17939 self.buffer.update(cx, |buffer, cx| {
17940 buffer.group_until_transaction(transaction, cx);
17941 });
17942 }
17943
17944 self.unmark_text(window, cx);
17945 }
17946
17947 fn replace_and_mark_text_in_range(
17948 &mut self,
17949 range_utf16: Option<Range<usize>>,
17950 text: &str,
17951 new_selected_range_utf16: Option<Range<usize>>,
17952 window: &mut Window,
17953 cx: &mut Context<Self>,
17954 ) {
17955 if !self.input_enabled {
17956 return;
17957 }
17958
17959 let transaction = self.transact(window, cx, |this, window, cx| {
17960 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17961 let snapshot = this.buffer.read(cx).read(cx);
17962 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17963 for marked_range in &mut marked_ranges {
17964 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17965 marked_range.start.0 += relative_range_utf16.start;
17966 marked_range.start =
17967 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17968 marked_range.end =
17969 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17970 }
17971 }
17972 Some(marked_ranges)
17973 } else if let Some(range_utf16) = range_utf16 {
17974 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17975 Some(this.selection_replacement_ranges(range_utf16, cx))
17976 } else {
17977 None
17978 };
17979
17980 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17981 let newest_selection_id = this.selections.newest_anchor().id;
17982 this.selections
17983 .all::<OffsetUtf16>(cx)
17984 .iter()
17985 .zip(ranges_to_replace.iter())
17986 .find_map(|(selection, range)| {
17987 if selection.id == newest_selection_id {
17988 Some(
17989 (range.start.0 as isize - selection.head().0 as isize)
17990 ..(range.end.0 as isize - selection.head().0 as isize),
17991 )
17992 } else {
17993 None
17994 }
17995 })
17996 });
17997
17998 cx.emit(EditorEvent::InputHandled {
17999 utf16_range_to_replace: range_to_replace,
18000 text: text.into(),
18001 });
18002
18003 if let Some(ranges) = ranges_to_replace {
18004 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18005 }
18006
18007 let marked_ranges = {
18008 let snapshot = this.buffer.read(cx).read(cx);
18009 this.selections
18010 .disjoint_anchors()
18011 .iter()
18012 .map(|selection| {
18013 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18014 })
18015 .collect::<Vec<_>>()
18016 };
18017
18018 if text.is_empty() {
18019 this.unmark_text(window, cx);
18020 } else {
18021 this.highlight_text::<InputComposition>(
18022 marked_ranges.clone(),
18023 HighlightStyle {
18024 underline: Some(UnderlineStyle {
18025 thickness: px(1.),
18026 color: None,
18027 wavy: false,
18028 }),
18029 ..Default::default()
18030 },
18031 cx,
18032 );
18033 }
18034
18035 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18036 let use_autoclose = this.use_autoclose;
18037 let use_auto_surround = this.use_auto_surround;
18038 this.set_use_autoclose(false);
18039 this.set_use_auto_surround(false);
18040 this.handle_input(text, window, cx);
18041 this.set_use_autoclose(use_autoclose);
18042 this.set_use_auto_surround(use_auto_surround);
18043
18044 if let Some(new_selected_range) = new_selected_range_utf16 {
18045 let snapshot = this.buffer.read(cx).read(cx);
18046 let new_selected_ranges = marked_ranges
18047 .into_iter()
18048 .map(|marked_range| {
18049 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
18050 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
18051 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
18052 snapshot.clip_offset_utf16(new_start, Bias::Left)
18053 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
18054 })
18055 .collect::<Vec<_>>();
18056
18057 drop(snapshot);
18058 this.change_selections(None, window, cx, |selections| {
18059 selections.select_ranges(new_selected_ranges)
18060 });
18061 }
18062 });
18063
18064 self.ime_transaction = self.ime_transaction.or(transaction);
18065 if let Some(transaction) = self.ime_transaction {
18066 self.buffer.update(cx, |buffer, cx| {
18067 buffer.group_until_transaction(transaction, cx);
18068 });
18069 }
18070
18071 if self.text_highlights::<InputComposition>(cx).is_none() {
18072 self.ime_transaction.take();
18073 }
18074 }
18075
18076 fn bounds_for_range(
18077 &mut self,
18078 range_utf16: Range<usize>,
18079 element_bounds: gpui::Bounds<Pixels>,
18080 window: &mut Window,
18081 cx: &mut Context<Self>,
18082 ) -> Option<gpui::Bounds<Pixels>> {
18083 let text_layout_details = self.text_layout_details(window);
18084 let gpui::Size {
18085 width: em_width,
18086 height: line_height,
18087 } = self.character_size(window);
18088
18089 let snapshot = self.snapshot(window, cx);
18090 let scroll_position = snapshot.scroll_position();
18091 let scroll_left = scroll_position.x * em_width;
18092
18093 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
18094 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
18095 + self.gutter_dimensions.width
18096 + self.gutter_dimensions.margin;
18097 let y = line_height * (start.row().as_f32() - scroll_position.y);
18098
18099 Some(Bounds {
18100 origin: element_bounds.origin + point(x, y),
18101 size: size(em_width, line_height),
18102 })
18103 }
18104
18105 fn character_index_for_point(
18106 &mut self,
18107 point: gpui::Point<Pixels>,
18108 _window: &mut Window,
18109 _cx: &mut Context<Self>,
18110 ) -> Option<usize> {
18111 let position_map = self.last_position_map.as_ref()?;
18112 if !position_map.text_hitbox.contains(&point) {
18113 return None;
18114 }
18115 let display_point = position_map.point_for_position(point).previous_valid;
18116 let anchor = position_map
18117 .snapshot
18118 .display_point_to_anchor(display_point, Bias::Left);
18119 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18120 Some(utf16_offset.0)
18121 }
18122}
18123
18124trait SelectionExt {
18125 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18126 fn spanned_rows(
18127 &self,
18128 include_end_if_at_line_start: bool,
18129 map: &DisplaySnapshot,
18130 ) -> Range<MultiBufferRow>;
18131}
18132
18133impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18134 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18135 let start = self
18136 .start
18137 .to_point(&map.buffer_snapshot)
18138 .to_display_point(map);
18139 let end = self
18140 .end
18141 .to_point(&map.buffer_snapshot)
18142 .to_display_point(map);
18143 if self.reversed {
18144 end..start
18145 } else {
18146 start..end
18147 }
18148 }
18149
18150 fn spanned_rows(
18151 &self,
18152 include_end_if_at_line_start: bool,
18153 map: &DisplaySnapshot,
18154 ) -> Range<MultiBufferRow> {
18155 let start = self.start.to_point(&map.buffer_snapshot);
18156 let mut end = self.end.to_point(&map.buffer_snapshot);
18157 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18158 end.row -= 1;
18159 }
18160
18161 let buffer_start = map.prev_line_boundary(start).0;
18162 let buffer_end = map.next_line_boundary(end).0;
18163 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18164 }
18165}
18166
18167impl<T: InvalidationRegion> InvalidationStack<T> {
18168 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18169 where
18170 S: Clone + ToOffset,
18171 {
18172 while let Some(region) = self.last() {
18173 let all_selections_inside_invalidation_ranges =
18174 if selections.len() == region.ranges().len() {
18175 selections
18176 .iter()
18177 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18178 .all(|(selection, invalidation_range)| {
18179 let head = selection.head().to_offset(buffer);
18180 invalidation_range.start <= head && invalidation_range.end >= head
18181 })
18182 } else {
18183 false
18184 };
18185
18186 if all_selections_inside_invalidation_ranges {
18187 break;
18188 } else {
18189 self.pop();
18190 }
18191 }
18192 }
18193}
18194
18195impl<T> Default for InvalidationStack<T> {
18196 fn default() -> Self {
18197 Self(Default::default())
18198 }
18199}
18200
18201impl<T> Deref for InvalidationStack<T> {
18202 type Target = Vec<T>;
18203
18204 fn deref(&self) -> &Self::Target {
18205 &self.0
18206 }
18207}
18208
18209impl<T> DerefMut for InvalidationStack<T> {
18210 fn deref_mut(&mut self) -> &mut Self::Target {
18211 &mut self.0
18212 }
18213}
18214
18215impl InvalidationRegion for SnippetState {
18216 fn ranges(&self) -> &[Range<Anchor>] {
18217 &self.ranges[self.active_index]
18218 }
18219}
18220
18221pub fn diagnostic_block_renderer(
18222 diagnostic: Diagnostic,
18223 max_message_rows: Option<u8>,
18224 allow_closing: bool,
18225) -> RenderBlock {
18226 let (text_without_backticks, code_ranges) =
18227 highlight_diagnostic_message(&diagnostic, max_message_rows);
18228
18229 Arc::new(move |cx: &mut BlockContext| {
18230 let group_id: SharedString = cx.block_id.to_string().into();
18231
18232 let mut text_style = cx.window.text_style().clone();
18233 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18234 let theme_settings = ThemeSettings::get_global(cx);
18235 text_style.font_family = theme_settings.buffer_font.family.clone();
18236 text_style.font_style = theme_settings.buffer_font.style;
18237 text_style.font_features = theme_settings.buffer_font.features.clone();
18238 text_style.font_weight = theme_settings.buffer_font.weight;
18239
18240 let multi_line_diagnostic = diagnostic.message.contains('\n');
18241
18242 let buttons = |diagnostic: &Diagnostic| {
18243 if multi_line_diagnostic {
18244 v_flex()
18245 } else {
18246 h_flex()
18247 }
18248 .when(allow_closing, |div| {
18249 div.children(diagnostic.is_primary.then(|| {
18250 IconButton::new("close-block", IconName::XCircle)
18251 .icon_color(Color::Muted)
18252 .size(ButtonSize::Compact)
18253 .style(ButtonStyle::Transparent)
18254 .visible_on_hover(group_id.clone())
18255 .on_click(move |_click, window, cx| {
18256 window.dispatch_action(Box::new(Cancel), cx)
18257 })
18258 .tooltip(|window, cx| {
18259 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18260 })
18261 }))
18262 })
18263 .child(
18264 IconButton::new("copy-block", IconName::Copy)
18265 .icon_color(Color::Muted)
18266 .size(ButtonSize::Compact)
18267 .style(ButtonStyle::Transparent)
18268 .visible_on_hover(group_id.clone())
18269 .on_click({
18270 let message = diagnostic.message.clone();
18271 move |_click, _, cx| {
18272 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18273 }
18274 })
18275 .tooltip(Tooltip::text("Copy diagnostic message")),
18276 )
18277 };
18278
18279 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18280 AvailableSpace::min_size(),
18281 cx.window,
18282 cx.app,
18283 );
18284
18285 h_flex()
18286 .id(cx.block_id)
18287 .group(group_id.clone())
18288 .relative()
18289 .size_full()
18290 .block_mouse_down()
18291 .pl(cx.gutter_dimensions.width)
18292 .w(cx.max_width - cx.gutter_dimensions.full_width())
18293 .child(
18294 div()
18295 .flex()
18296 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18297 .flex_shrink(),
18298 )
18299 .child(buttons(&diagnostic))
18300 .child(div().flex().flex_shrink_0().child(
18301 StyledText::new(text_without_backticks.clone()).with_default_highlights(
18302 &text_style,
18303 code_ranges.iter().map(|range| {
18304 (
18305 range.clone(),
18306 HighlightStyle {
18307 font_weight: Some(FontWeight::BOLD),
18308 ..Default::default()
18309 },
18310 )
18311 }),
18312 ),
18313 ))
18314 .into_any_element()
18315 })
18316}
18317
18318fn inline_completion_edit_text(
18319 current_snapshot: &BufferSnapshot,
18320 edits: &[(Range<Anchor>, String)],
18321 edit_preview: &EditPreview,
18322 include_deletions: bool,
18323 cx: &App,
18324) -> HighlightedText {
18325 let edits = edits
18326 .iter()
18327 .map(|(anchor, text)| {
18328 (
18329 anchor.start.text_anchor..anchor.end.text_anchor,
18330 text.clone(),
18331 )
18332 })
18333 .collect::<Vec<_>>();
18334
18335 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18336}
18337
18338pub fn highlight_diagnostic_message(
18339 diagnostic: &Diagnostic,
18340 mut max_message_rows: Option<u8>,
18341) -> (SharedString, Vec<Range<usize>>) {
18342 let mut text_without_backticks = String::new();
18343 let mut code_ranges = Vec::new();
18344
18345 if let Some(source) = &diagnostic.source {
18346 text_without_backticks.push_str(source);
18347 code_ranges.push(0..source.len());
18348 text_without_backticks.push_str(": ");
18349 }
18350
18351 let mut prev_offset = 0;
18352 let mut in_code_block = false;
18353 let has_row_limit = max_message_rows.is_some();
18354 let mut newline_indices = diagnostic
18355 .message
18356 .match_indices('\n')
18357 .filter(|_| has_row_limit)
18358 .map(|(ix, _)| ix)
18359 .fuse()
18360 .peekable();
18361
18362 for (quote_ix, _) in diagnostic
18363 .message
18364 .match_indices('`')
18365 .chain([(diagnostic.message.len(), "")])
18366 {
18367 let mut first_newline_ix = None;
18368 let mut last_newline_ix = None;
18369 while let Some(newline_ix) = newline_indices.peek() {
18370 if *newline_ix < quote_ix {
18371 if first_newline_ix.is_none() {
18372 first_newline_ix = Some(*newline_ix);
18373 }
18374 last_newline_ix = Some(*newline_ix);
18375
18376 if let Some(rows_left) = &mut max_message_rows {
18377 if *rows_left == 0 {
18378 break;
18379 } else {
18380 *rows_left -= 1;
18381 }
18382 }
18383 let _ = newline_indices.next();
18384 } else {
18385 break;
18386 }
18387 }
18388 let prev_len = text_without_backticks.len();
18389 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18390 text_without_backticks.push_str(new_text);
18391 if in_code_block {
18392 code_ranges.push(prev_len..text_without_backticks.len());
18393 }
18394 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18395 in_code_block = !in_code_block;
18396 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18397 text_without_backticks.push_str("...");
18398 break;
18399 }
18400 }
18401
18402 (text_without_backticks.into(), code_ranges)
18403}
18404
18405fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18406 match severity {
18407 DiagnosticSeverity::ERROR => colors.error,
18408 DiagnosticSeverity::WARNING => colors.warning,
18409 DiagnosticSeverity::INFORMATION => colors.info,
18410 DiagnosticSeverity::HINT => colors.info,
18411 _ => colors.ignored,
18412 }
18413}
18414
18415pub fn styled_runs_for_code_label<'a>(
18416 label: &'a CodeLabel,
18417 syntax_theme: &'a theme::SyntaxTheme,
18418) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18419 let fade_out = HighlightStyle {
18420 fade_out: Some(0.35),
18421 ..Default::default()
18422 };
18423
18424 let mut prev_end = label.filter_range.end;
18425 label
18426 .runs
18427 .iter()
18428 .enumerate()
18429 .flat_map(move |(ix, (range, highlight_id))| {
18430 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18431 style
18432 } else {
18433 return Default::default();
18434 };
18435 let mut muted_style = style;
18436 muted_style.highlight(fade_out);
18437
18438 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18439 if range.start >= label.filter_range.end {
18440 if range.start > prev_end {
18441 runs.push((prev_end..range.start, fade_out));
18442 }
18443 runs.push((range.clone(), muted_style));
18444 } else if range.end <= label.filter_range.end {
18445 runs.push((range.clone(), style));
18446 } else {
18447 runs.push((range.start..label.filter_range.end, style));
18448 runs.push((label.filter_range.end..range.end, muted_style));
18449 }
18450 prev_end = cmp::max(prev_end, range.end);
18451
18452 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18453 runs.push((prev_end..label.text.len(), fade_out));
18454 }
18455
18456 runs
18457 })
18458}
18459
18460pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18461 let mut prev_index = 0;
18462 let mut prev_codepoint: Option<char> = None;
18463 text.char_indices()
18464 .chain([(text.len(), '\0')])
18465 .filter_map(move |(index, codepoint)| {
18466 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18467 let is_boundary = index == text.len()
18468 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18469 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18470 if is_boundary {
18471 let chunk = &text[prev_index..index];
18472 prev_index = index;
18473 Some(chunk)
18474 } else {
18475 None
18476 }
18477 })
18478}
18479
18480pub trait RangeToAnchorExt: Sized {
18481 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18482
18483 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18484 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18485 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18486 }
18487}
18488
18489impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18490 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18491 let start_offset = self.start.to_offset(snapshot);
18492 let end_offset = self.end.to_offset(snapshot);
18493 if start_offset == end_offset {
18494 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18495 } else {
18496 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18497 }
18498 }
18499}
18500
18501pub trait RowExt {
18502 fn as_f32(&self) -> f32;
18503
18504 fn next_row(&self) -> Self;
18505
18506 fn previous_row(&self) -> Self;
18507
18508 fn minus(&self, other: Self) -> u32;
18509}
18510
18511impl RowExt for DisplayRow {
18512 fn as_f32(&self) -> f32 {
18513 self.0 as f32
18514 }
18515
18516 fn next_row(&self) -> Self {
18517 Self(self.0 + 1)
18518 }
18519
18520 fn previous_row(&self) -> Self {
18521 Self(self.0.saturating_sub(1))
18522 }
18523
18524 fn minus(&self, other: Self) -> u32 {
18525 self.0 - other.0
18526 }
18527}
18528
18529impl RowExt for MultiBufferRow {
18530 fn as_f32(&self) -> f32 {
18531 self.0 as f32
18532 }
18533
18534 fn next_row(&self) -> Self {
18535 Self(self.0 + 1)
18536 }
18537
18538 fn previous_row(&self) -> Self {
18539 Self(self.0.saturating_sub(1))
18540 }
18541
18542 fn minus(&self, other: Self) -> u32 {
18543 self.0 - other.0
18544 }
18545}
18546
18547trait RowRangeExt {
18548 type Row;
18549
18550 fn len(&self) -> usize;
18551
18552 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18553}
18554
18555impl RowRangeExt for Range<MultiBufferRow> {
18556 type Row = MultiBufferRow;
18557
18558 fn len(&self) -> usize {
18559 (self.end.0 - self.start.0) as usize
18560 }
18561
18562 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18563 (self.start.0..self.end.0).map(MultiBufferRow)
18564 }
18565}
18566
18567impl RowRangeExt for Range<DisplayRow> {
18568 type Row = DisplayRow;
18569
18570 fn len(&self) -> usize {
18571 (self.end.0 - self.start.0) as usize
18572 }
18573
18574 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18575 (self.start.0..self.end.0).map(DisplayRow)
18576 }
18577}
18578
18579/// If select range has more than one line, we
18580/// just point the cursor to range.start.
18581fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18582 if range.start.row == range.end.row {
18583 range
18584 } else {
18585 range.start..range.start
18586 }
18587}
18588pub struct KillRing(ClipboardItem);
18589impl Global for KillRing {}
18590
18591const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18592
18593fn all_edits_insertions_or_deletions(
18594 edits: &Vec<(Range<Anchor>, String)>,
18595 snapshot: &MultiBufferSnapshot,
18596) -> bool {
18597 let mut all_insertions = true;
18598 let mut all_deletions = true;
18599
18600 for (range, new_text) in edits.iter() {
18601 let range_is_empty = range.to_offset(&snapshot).is_empty();
18602 let text_is_empty = new_text.is_empty();
18603
18604 if range_is_empty != text_is_empty {
18605 if range_is_empty {
18606 all_deletions = false;
18607 } else {
18608 all_insertions = false;
18609 }
18610 } else {
18611 return false;
18612 }
18613
18614 if !all_insertions && !all_deletions {
18615 return false;
18616 }
18617 }
18618 all_insertions || all_deletions
18619}
18620
18621struct MissingEditPredictionKeybindingTooltip;
18622
18623impl Render for MissingEditPredictionKeybindingTooltip {
18624 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18625 ui::tooltip_container(window, cx, |container, _, cx| {
18626 container
18627 .flex_shrink_0()
18628 .max_w_80()
18629 .min_h(rems_from_px(124.))
18630 .justify_between()
18631 .child(
18632 v_flex()
18633 .flex_1()
18634 .text_ui_sm(cx)
18635 .child(Label::new("Conflict with Accept Keybinding"))
18636 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18637 )
18638 .child(
18639 h_flex()
18640 .pb_1()
18641 .gap_1()
18642 .items_end()
18643 .w_full()
18644 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18645 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18646 }))
18647 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18648 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18649 })),
18650 )
18651 })
18652 }
18653}
18654
18655#[derive(Debug, Clone, Copy, PartialEq)]
18656pub struct LineHighlight {
18657 pub background: Background,
18658 pub border: Option<gpui::Hsla>,
18659}
18660
18661impl From<Hsla> for LineHighlight {
18662 fn from(hsla: Hsla) -> Self {
18663 Self {
18664 background: hsla.into(),
18665 border: None,
18666 }
18667 }
18668}
18669
18670impl From<Background> for LineHighlight {
18671 fn from(background: Background) -> Self {
18672 Self {
18673 background,
18674 border: None,
18675 }
18676 }
18677}