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 linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use ::git::Restore;
77use code_context_menus::{
78 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
79 CompletionsMenu, ContextMenuOrigin,
80};
81use git::blame::GitBlame;
82use gpui::{
83 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
84 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
85 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Entity, EntityInputHandler,
86 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
87 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
88 ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
89 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
90 WeakEntity, WeakFocusHandle, Window,
91};
92use highlight_matching_bracket::refresh_matching_bracket_highlights;
93use hover_popover::{hide_hover, HoverState};
94use indent_guides::ActiveIndentGuidesState;
95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
96pub use inline_completion::Direction;
97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
98pub use items::MAX_TAB_TITLE_LEN;
99use itertools::Itertools;
100use language::{
101 language_settings::{
102 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
103 },
104 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
105 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, DiskState,
106 EditPredictionsMode, EditPreview, HighlightedText, IndentKind, IndentSize, Language,
107 OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
108};
109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
110use linked_editing_ranges::refresh_linked_ranges;
111use mouse_context_menu::MouseContextMenu;
112use persistence::DB;
113pub use proposed_changes_editor::{
114 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
115};
116use std::iter::Peekable;
117use task::{ResolvedTask, TaskTemplate, TaskVariables};
118
119use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
120pub use lsp::CompletionContext;
121use lsp::{
122 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
123 LanguageServerId, LanguageServerName,
124};
125
126use language::BufferSnapshot;
127use movement::TextLayoutDetails;
128pub use multi_buffer::{
129 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
130 ToOffset, ToPoint,
131};
132use multi_buffer::{
133 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
134 ToOffsetUtf16,
135};
136use project::{
137 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
138 project_settings::{GitGutterSetting, ProjectSettings},
139 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
140 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
141};
142use rand::prelude::*;
143use rpc::{proto::*, ErrorExt};
144use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
145use selections_collection::{
146 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
147};
148use serde::{Deserialize, Serialize};
149use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
150use smallvec::SmallVec;
151use snippet::Snippet;
152use std::{
153 any::TypeId,
154 borrow::Cow,
155 cell::RefCell,
156 cmp::{self, Ordering, Reverse},
157 mem,
158 num::NonZeroU32,
159 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
160 path::{Path, PathBuf},
161 rc::Rc,
162 sync::Arc,
163 time::{Duration, Instant},
164};
165pub use sum_tree::Bias;
166use sum_tree::TreeMap;
167use text::{BufferId, OffsetUtf16, Rope};
168use theme::{
169 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
170 ThemeColors, ThemeSettings,
171};
172use ui::{
173 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
174 Tooltip,
175};
176use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
177use workspace::{
178 item::{ItemHandle, PreviewTabsSettings},
179 ItemId, RestoreOnStartupBehavior,
180};
181use workspace::{
182 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
183 WorkspaceSettings,
184};
185use workspace::{
186 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
187};
188use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
189
190use crate::hover_links::{find_url, find_url_from_range};
191use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
192
193pub const FILE_HEADER_HEIGHT: u32 = 2;
194pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
195pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
196pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
197const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
198const MAX_LINE_LEN: usize = 1024;
199const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
200const MAX_SELECTION_HISTORY_LEN: usize = 1024;
201pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
202#[doc(hidden)]
203pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
204
205pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
206pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
207
208pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
209pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
210
211const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
212 alt: true,
213 shift: true,
214 control: false,
215 platform: false,
216 function: false,
217};
218
219#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
220pub enum InlayId {
221 InlineCompletion(usize),
222 Hint(usize),
223}
224
225impl InlayId {
226 fn id(&self) -> usize {
227 match self {
228 Self::InlineCompletion(id) => *id,
229 Self::Hint(id) => *id,
230 }
231 }
232}
233
234enum DocumentHighlightRead {}
235enum DocumentHighlightWrite {}
236enum InputComposition {}
237enum SelectedTextHighlight {}
238
239#[derive(Debug, Copy, Clone, PartialEq, Eq)]
240pub enum Navigated {
241 Yes,
242 No,
243}
244
245impl Navigated {
246 pub fn from_bool(yes: bool) -> Navigated {
247 if yes {
248 Navigated::Yes
249 } else {
250 Navigated::No
251 }
252 }
253}
254
255pub fn init_settings(cx: &mut App) {
256 EditorSettings::register(cx);
257}
258
259pub fn init(cx: &mut App) {
260 init_settings(cx);
261
262 workspace::register_project_item::<Editor>(cx);
263 workspace::FollowableViewRegistry::register::<Editor>(cx);
264 workspace::register_serializable_item::<Editor>(cx);
265
266 cx.observe_new(
267 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
268 workspace.register_action(Editor::new_file);
269 workspace.register_action(Editor::new_file_vertical);
270 workspace.register_action(Editor::new_file_horizontal);
271 workspace.register_action(Editor::cancel_language_server_work);
272 },
273 )
274 .detach();
275
276 cx.on_action(move |_: &workspace::NewFile, cx| {
277 let app_state = workspace::AppState::global(cx);
278 if let Some(app_state) = app_state.upgrade() {
279 workspace::open_new(
280 Default::default(),
281 app_state,
282 cx,
283 |workspace, window, cx| {
284 Editor::new_file(workspace, &Default::default(), window, cx)
285 },
286 )
287 .detach();
288 }
289 });
290 cx.on_action(move |_: &workspace::NewWindow, cx| {
291 let app_state = workspace::AppState::global(cx);
292 if let Some(app_state) = app_state.upgrade() {
293 workspace::open_new(
294 Default::default(),
295 app_state,
296 cx,
297 |workspace, window, cx| {
298 cx.activate(true);
299 Editor::new_file(workspace, &Default::default(), window, cx)
300 },
301 )
302 .detach();
303 }
304 });
305}
306
307pub struct SearchWithinRange;
308
309trait InvalidationRegion {
310 fn ranges(&self) -> &[Range<Anchor>];
311}
312
313#[derive(Clone, Debug, PartialEq)]
314pub enum SelectPhase {
315 Begin {
316 position: DisplayPoint,
317 add: bool,
318 click_count: usize,
319 },
320 BeginColumnar {
321 position: DisplayPoint,
322 reset: bool,
323 goal_column: u32,
324 },
325 Extend {
326 position: DisplayPoint,
327 click_count: usize,
328 },
329 Update {
330 position: DisplayPoint,
331 goal_column: u32,
332 scroll_delta: gpui::Point<f32>,
333 },
334 End,
335}
336
337#[derive(Clone, Debug)]
338pub enum SelectMode {
339 Character,
340 Word(Range<Anchor>),
341 Line(Range<Anchor>),
342 All,
343}
344
345#[derive(Copy, Clone, PartialEq, Eq, Debug)]
346pub enum EditorMode {
347 SingleLine { auto_width: bool },
348 AutoHeight { max_lines: usize },
349 Full,
350}
351
352#[derive(Copy, Clone, Debug)]
353pub enum SoftWrap {
354 /// Prefer not to wrap at all.
355 ///
356 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
357 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
358 GitDiff,
359 /// Prefer a single line generally, unless an overly long line is encountered.
360 None,
361 /// Soft wrap lines that exceed the editor width.
362 EditorWidth,
363 /// Soft wrap lines at the preferred line length.
364 Column(u32),
365 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
366 Bounded(u32),
367}
368
369#[derive(Clone)]
370pub struct EditorStyle {
371 pub background: Hsla,
372 pub local_player: PlayerColor,
373 pub text: TextStyle,
374 pub scrollbar_width: Pixels,
375 pub syntax: Arc<SyntaxTheme>,
376 pub status: StatusColors,
377 pub inlay_hints_style: HighlightStyle,
378 pub inline_completion_styles: InlineCompletionStyles,
379 pub unnecessary_code_fade: f32,
380}
381
382impl Default for EditorStyle {
383 fn default() -> Self {
384 Self {
385 background: Hsla::default(),
386 local_player: PlayerColor::default(),
387 text: TextStyle::default(),
388 scrollbar_width: Pixels::default(),
389 syntax: Default::default(),
390 // HACK: Status colors don't have a real default.
391 // We should look into removing the status colors from the editor
392 // style and retrieve them directly from the theme.
393 status: StatusColors::dark(),
394 inlay_hints_style: HighlightStyle::default(),
395 inline_completion_styles: InlineCompletionStyles {
396 insertion: HighlightStyle::default(),
397 whitespace: HighlightStyle::default(),
398 },
399 unnecessary_code_fade: Default::default(),
400 }
401 }
402}
403
404pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
405 let show_background = language_settings::language_settings(None, None, cx)
406 .inlay_hints
407 .show_background;
408
409 HighlightStyle {
410 color: Some(cx.theme().status().hint),
411 background_color: show_background.then(|| cx.theme().status().hint_background),
412 ..HighlightStyle::default()
413 }
414}
415
416pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
417 InlineCompletionStyles {
418 insertion: HighlightStyle {
419 color: Some(cx.theme().status().predictive),
420 ..HighlightStyle::default()
421 },
422 whitespace: HighlightStyle {
423 background_color: Some(cx.theme().status().created_background),
424 ..HighlightStyle::default()
425 },
426 }
427}
428
429type CompletionId = usize;
430
431pub(crate) enum EditDisplayMode {
432 TabAccept,
433 DiffPopover,
434 Inline,
435}
436
437enum InlineCompletion {
438 Edit {
439 edits: Vec<(Range<Anchor>, String)>,
440 edit_preview: Option<EditPreview>,
441 display_mode: EditDisplayMode,
442 snapshot: BufferSnapshot,
443 },
444 Move {
445 target: Anchor,
446 snapshot: BufferSnapshot,
447 },
448}
449
450struct InlineCompletionState {
451 inlay_ids: Vec<InlayId>,
452 completion: InlineCompletion,
453 completion_id: Option<SharedString>,
454 invalidation_range: Range<Anchor>,
455}
456
457enum EditPredictionSettings {
458 Disabled,
459 Enabled {
460 show_in_menu: bool,
461 preview_requires_modifier: bool,
462 },
463}
464
465enum InlineCompletionHighlight {}
466
467pub enum MenuInlineCompletionsPolicy {
468 Never,
469 ByProvider,
470}
471
472pub enum EditPredictionPreview {
473 /// Modifier is not pressed
474 Inactive,
475 /// Modifier pressed
476 Active {
477 previous_scroll_position: Option<ScrollAnchor>,
478 },
479}
480
481#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
482struct EditorActionId(usize);
483
484impl EditorActionId {
485 pub fn post_inc(&mut self) -> Self {
486 let answer = self.0;
487
488 *self = Self(answer + 1);
489
490 Self(answer)
491 }
492}
493
494// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
495// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
496
497type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
498type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
499
500#[derive(Default)]
501struct ScrollbarMarkerState {
502 scrollbar_size: Size<Pixels>,
503 dirty: bool,
504 markers: Arc<[PaintQuad]>,
505 pending_refresh: Option<Task<Result<()>>>,
506}
507
508impl ScrollbarMarkerState {
509 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
510 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
511 }
512}
513
514#[derive(Clone, Debug)]
515struct RunnableTasks {
516 templates: Vec<(TaskSourceKind, TaskTemplate)>,
517 offset: MultiBufferOffset,
518 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
519 column: u32,
520 // Values of all named captures, including those starting with '_'
521 extra_variables: HashMap<String, String>,
522 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
523 context_range: Range<BufferOffset>,
524}
525
526impl RunnableTasks {
527 fn resolve<'a>(
528 &'a self,
529 cx: &'a task::TaskContext,
530 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
531 self.templates.iter().filter_map(|(kind, template)| {
532 template
533 .resolve_task(&kind.to_id_base(), cx)
534 .map(|task| (kind.clone(), task))
535 })
536 }
537}
538
539#[derive(Clone)]
540struct ResolvedTasks {
541 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
542 position: Anchor,
543}
544#[derive(Copy, Clone, Debug)]
545struct MultiBufferOffset(usize);
546#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
547struct BufferOffset(usize);
548
549// Addons allow storing per-editor state in other crates (e.g. Vim)
550pub trait Addon: 'static {
551 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
552
553 fn render_buffer_header_controls(
554 &self,
555 _: &ExcerptInfo,
556 _: &Window,
557 _: &App,
558 ) -> Option<AnyElement> {
559 None
560 }
561
562 fn to_any(&self) -> &dyn std::any::Any;
563}
564
565#[derive(Debug, Copy, Clone, PartialEq, Eq)]
566pub enum IsVimMode {
567 Yes,
568 No,
569}
570
571/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
572///
573/// See the [module level documentation](self) for more information.
574pub struct Editor {
575 focus_handle: FocusHandle,
576 last_focused_descendant: Option<WeakFocusHandle>,
577 /// The text buffer being edited
578 buffer: Entity<MultiBuffer>,
579 /// Map of how text in the buffer should be displayed.
580 /// Handles soft wraps, folds, fake inlay text insertions, etc.
581 pub display_map: Entity<DisplayMap>,
582 pub selections: SelectionsCollection,
583 pub scroll_manager: ScrollManager,
584 /// When inline assist editors are linked, they all render cursors because
585 /// typing enters text into each of them, even the ones that aren't focused.
586 pub(crate) show_cursor_when_unfocused: bool,
587 columnar_selection_tail: Option<Anchor>,
588 add_selections_state: Option<AddSelectionsState>,
589 select_next_state: Option<SelectNextState>,
590 select_prev_state: Option<SelectNextState>,
591 selection_history: SelectionHistory,
592 autoclose_regions: Vec<AutocloseRegion>,
593 snippet_stack: InvalidationStack<SnippetState>,
594 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
595 ime_transaction: Option<TransactionId>,
596 active_diagnostics: Option<ActiveDiagnosticGroup>,
597 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
598
599 // TODO: make this a access method
600 pub project: Option<Entity<Project>>,
601 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
602 completion_provider: Option<Box<dyn CompletionProvider>>,
603 collaboration_hub: Option<Box<dyn CollaborationHub>>,
604 blink_manager: Entity<BlinkManager>,
605 show_cursor_names: bool,
606 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
607 pub show_local_selections: bool,
608 mode: EditorMode,
609 show_breadcrumbs: bool,
610 show_gutter: bool,
611 show_scrollbars: bool,
612 show_line_numbers: Option<bool>,
613 use_relative_line_numbers: Option<bool>,
614 show_git_diff_gutter: Option<bool>,
615 show_code_actions: Option<bool>,
616 show_runnables: Option<bool>,
617 show_wrap_guides: Option<bool>,
618 show_indent_guides: Option<bool>,
619 placeholder_text: Option<Arc<str>>,
620 highlight_order: usize,
621 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
622 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
623 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
624 scrollbar_marker_state: ScrollbarMarkerState,
625 active_indent_guides_state: ActiveIndentGuidesState,
626 nav_history: Option<ItemNavHistory>,
627 context_menu: RefCell<Option<CodeContextMenu>>,
628 mouse_context_menu: Option<MouseContextMenu>,
629 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
630 signature_help_state: SignatureHelpState,
631 auto_signature_help: Option<bool>,
632 find_all_references_task_sources: Vec<Anchor>,
633 next_completion_id: CompletionId,
634 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
635 code_actions_task: Option<Task<Result<()>>>,
636 selection_highlight_task: Option<Task<()>>,
637 document_highlights_task: Option<Task<()>>,
638 linked_editing_range_task: Option<Task<Option<()>>>,
639 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
640 pending_rename: Option<RenameState>,
641 searchable: bool,
642 cursor_shape: CursorShape,
643 current_line_highlight: Option<CurrentLineHighlight>,
644 collapse_matches: bool,
645 autoindent_mode: Option<AutoindentMode>,
646 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
647 input_enabled: bool,
648 use_modal_editing: bool,
649 read_only: bool,
650 leader_peer_id: Option<PeerId>,
651 remote_id: Option<ViewId>,
652 hover_state: HoverState,
653 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
654 gutter_hovered: bool,
655 hovered_link_state: Option<HoveredLinkState>,
656 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
657 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
658 active_inline_completion: Option<InlineCompletionState>,
659 /// Used to prevent flickering as the user types while the menu is open
660 stale_inline_completion_in_menu: Option<InlineCompletionState>,
661 edit_prediction_settings: EditPredictionSettings,
662 inline_completions_hidden_for_vim_mode: bool,
663 show_inline_completions_override: Option<bool>,
664 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
665 edit_prediction_preview: EditPredictionPreview,
666 edit_prediction_cursor_on_leading_whitespace: bool,
667 edit_prediction_requires_modifier_in_leading_space: bool,
668 inlay_hint_cache: InlayHintCache,
669 next_inlay_id: usize,
670 _subscriptions: Vec<Subscription>,
671 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
672 gutter_dimensions: GutterDimensions,
673 style: Option<EditorStyle>,
674 text_style_refinement: Option<TextStyleRefinement>,
675 next_editor_action_id: EditorActionId,
676 editor_actions:
677 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
678 use_autoclose: bool,
679 use_auto_surround: bool,
680 auto_replace_emoji_shortcode: bool,
681 show_git_blame_gutter: bool,
682 show_git_blame_inline: bool,
683 show_git_blame_inline_delay_task: Option<Task<()>>,
684 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
685 distinguish_unstaged_diff_hunks: bool,
686 git_blame_inline_enabled: bool,
687 serialize_dirty_buffers: bool,
688 show_selection_menu: Option<bool>,
689 blame: Option<Entity<GitBlame>>,
690 blame_subscription: Option<Subscription>,
691 custom_context_menu: Option<
692 Box<
693 dyn 'static
694 + Fn(
695 &mut Self,
696 DisplayPoint,
697 &mut Window,
698 &mut Context<Self>,
699 ) -> Option<Entity<ui::ContextMenu>>,
700 >,
701 >,
702 last_bounds: Option<Bounds<Pixels>>,
703 last_position_map: Option<Rc<PositionMap>>,
704 expect_bounds_change: Option<Bounds<Pixels>>,
705 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
706 tasks_update_task: Option<Task<()>>,
707 in_project_search: bool,
708 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
709 breadcrumb_header: Option<String>,
710 focused_block: Option<FocusedBlock>,
711 next_scroll_position: NextScrollCursorCenterTopBottom,
712 addons: HashMap<TypeId, Box<dyn Addon>>,
713 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
714 load_diff_task: Option<Shared<Task<()>>>,
715 selection_mark_mode: bool,
716 toggle_fold_multiple_buffers: Task<()>,
717 _scroll_cursor_center_top_bottom_task: Task<()>,
718 serialize_selections: Task<()>,
719 mouse_cursor_hidden: bool,
720 hide_mouse_while_typing: bool,
721}
722
723#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
724enum NextScrollCursorCenterTopBottom {
725 #[default]
726 Center,
727 Top,
728 Bottom,
729}
730
731impl NextScrollCursorCenterTopBottom {
732 fn next(&self) -> Self {
733 match self {
734 Self::Center => Self::Top,
735 Self::Top => Self::Bottom,
736 Self::Bottom => Self::Center,
737 }
738 }
739}
740
741#[derive(Clone)]
742pub struct EditorSnapshot {
743 pub mode: EditorMode,
744 show_gutter: bool,
745 show_line_numbers: Option<bool>,
746 show_git_diff_gutter: Option<bool>,
747 show_code_actions: Option<bool>,
748 show_runnables: Option<bool>,
749 git_blame_gutter_max_author_length: Option<usize>,
750 pub display_snapshot: DisplaySnapshot,
751 pub placeholder_text: Option<Arc<str>>,
752 is_focused: bool,
753 scroll_anchor: ScrollAnchor,
754 ongoing_scroll: OngoingScroll,
755 current_line_highlight: CurrentLineHighlight,
756 gutter_hovered: bool,
757}
758
759const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
760
761#[derive(Default, Debug, Clone, Copy)]
762pub struct GutterDimensions {
763 pub left_padding: Pixels,
764 pub right_padding: Pixels,
765 pub width: Pixels,
766 pub margin: Pixels,
767 pub git_blame_entries_width: Option<Pixels>,
768}
769
770impl GutterDimensions {
771 /// The full width of the space taken up by the gutter.
772 pub fn full_width(&self) -> Pixels {
773 self.margin + self.width
774 }
775
776 /// The width of the space reserved for the fold indicators,
777 /// use alongside 'justify_end' and `gutter_width` to
778 /// right align content with the line numbers
779 pub fn fold_area_width(&self) -> Pixels {
780 self.margin + self.right_padding
781 }
782}
783
784#[derive(Debug)]
785pub struct RemoteSelection {
786 pub replica_id: ReplicaId,
787 pub selection: Selection<Anchor>,
788 pub cursor_shape: CursorShape,
789 pub peer_id: PeerId,
790 pub line_mode: bool,
791 pub participant_index: Option<ParticipantIndex>,
792 pub user_name: Option<SharedString>,
793}
794
795#[derive(Clone, Debug)]
796struct SelectionHistoryEntry {
797 selections: Arc<[Selection<Anchor>]>,
798 select_next_state: Option<SelectNextState>,
799 select_prev_state: Option<SelectNextState>,
800 add_selections_state: Option<AddSelectionsState>,
801}
802
803enum SelectionHistoryMode {
804 Normal,
805 Undoing,
806 Redoing,
807}
808
809#[derive(Clone, PartialEq, Eq, Hash)]
810struct HoveredCursor {
811 replica_id: u16,
812 selection_id: usize,
813}
814
815impl Default for SelectionHistoryMode {
816 fn default() -> Self {
817 Self::Normal
818 }
819}
820
821#[derive(Default)]
822struct SelectionHistory {
823 #[allow(clippy::type_complexity)]
824 selections_by_transaction:
825 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
826 mode: SelectionHistoryMode,
827 undo_stack: VecDeque<SelectionHistoryEntry>,
828 redo_stack: VecDeque<SelectionHistoryEntry>,
829}
830
831impl SelectionHistory {
832 fn insert_transaction(
833 &mut self,
834 transaction_id: TransactionId,
835 selections: Arc<[Selection<Anchor>]>,
836 ) {
837 self.selections_by_transaction
838 .insert(transaction_id, (selections, None));
839 }
840
841 #[allow(clippy::type_complexity)]
842 fn transaction(
843 &self,
844 transaction_id: TransactionId,
845 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
846 self.selections_by_transaction.get(&transaction_id)
847 }
848
849 #[allow(clippy::type_complexity)]
850 fn transaction_mut(
851 &mut self,
852 transaction_id: TransactionId,
853 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
854 self.selections_by_transaction.get_mut(&transaction_id)
855 }
856
857 fn push(&mut self, entry: SelectionHistoryEntry) {
858 if !entry.selections.is_empty() {
859 match self.mode {
860 SelectionHistoryMode::Normal => {
861 self.push_undo(entry);
862 self.redo_stack.clear();
863 }
864 SelectionHistoryMode::Undoing => self.push_redo(entry),
865 SelectionHistoryMode::Redoing => self.push_undo(entry),
866 }
867 }
868 }
869
870 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
871 if self
872 .undo_stack
873 .back()
874 .map_or(true, |e| e.selections != entry.selections)
875 {
876 self.undo_stack.push_back(entry);
877 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
878 self.undo_stack.pop_front();
879 }
880 }
881 }
882
883 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
884 if self
885 .redo_stack
886 .back()
887 .map_or(true, |e| e.selections != entry.selections)
888 {
889 self.redo_stack.push_back(entry);
890 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
891 self.redo_stack.pop_front();
892 }
893 }
894 }
895}
896
897struct RowHighlight {
898 index: usize,
899 range: Range<Anchor>,
900 color: Hsla,
901 should_autoscroll: bool,
902}
903
904#[derive(Clone, Debug)]
905struct AddSelectionsState {
906 above: bool,
907 stack: Vec<usize>,
908}
909
910#[derive(Clone)]
911struct SelectNextState {
912 query: AhoCorasick,
913 wordwise: bool,
914 done: bool,
915}
916
917impl std::fmt::Debug for SelectNextState {
918 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
919 f.debug_struct(std::any::type_name::<Self>())
920 .field("wordwise", &self.wordwise)
921 .field("done", &self.done)
922 .finish()
923 }
924}
925
926#[derive(Debug)]
927struct AutocloseRegion {
928 selection_id: usize,
929 range: Range<Anchor>,
930 pair: BracketPair,
931}
932
933#[derive(Debug)]
934struct SnippetState {
935 ranges: Vec<Vec<Range<Anchor>>>,
936 active_index: usize,
937 choices: Vec<Option<Vec<String>>>,
938}
939
940#[doc(hidden)]
941pub struct RenameState {
942 pub range: Range<Anchor>,
943 pub old_name: Arc<str>,
944 pub editor: Entity<Editor>,
945 block_id: CustomBlockId,
946}
947
948struct InvalidationStack<T>(Vec<T>);
949
950struct RegisteredInlineCompletionProvider {
951 provider: Arc<dyn InlineCompletionProviderHandle>,
952 _subscription: Subscription,
953}
954
955#[derive(Debug)]
956struct ActiveDiagnosticGroup {
957 primary_range: Range<Anchor>,
958 primary_message: String,
959 group_id: usize,
960 blocks: HashMap<CustomBlockId, Diagnostic>,
961 is_valid: bool,
962}
963
964#[derive(Serialize, Deserialize, Clone, Debug)]
965pub struct ClipboardSelection {
966 pub len: usize,
967 pub is_entire_line: bool,
968 pub first_line_indent: u32,
969}
970
971#[derive(Debug)]
972pub(crate) struct NavigationData {
973 cursor_anchor: Anchor,
974 cursor_position: Point,
975 scroll_anchor: ScrollAnchor,
976 scroll_top_row: u32,
977}
978
979#[derive(Debug, Clone, Copy, PartialEq, Eq)]
980pub enum GotoDefinitionKind {
981 Symbol,
982 Declaration,
983 Type,
984 Implementation,
985}
986
987#[derive(Debug, Clone)]
988enum InlayHintRefreshReason {
989 Toggle(bool),
990 SettingsChange(InlayHintSettings),
991 NewLinesShown,
992 BufferEdited(HashSet<Arc<Language>>),
993 RefreshRequested,
994 ExcerptsRemoved(Vec<ExcerptId>),
995}
996
997impl InlayHintRefreshReason {
998 fn description(&self) -> &'static str {
999 match self {
1000 Self::Toggle(_) => "toggle",
1001 Self::SettingsChange(_) => "settings change",
1002 Self::NewLinesShown => "new lines shown",
1003 Self::BufferEdited(_) => "buffer edited",
1004 Self::RefreshRequested => "refresh requested",
1005 Self::ExcerptsRemoved(_) => "excerpts removed",
1006 }
1007 }
1008}
1009
1010pub enum FormatTarget {
1011 Buffers,
1012 Ranges(Vec<Range<MultiBufferPoint>>),
1013}
1014
1015pub(crate) struct FocusedBlock {
1016 id: BlockId,
1017 focus_handle: WeakFocusHandle,
1018}
1019
1020#[derive(Clone)]
1021enum JumpData {
1022 MultiBufferRow {
1023 row: MultiBufferRow,
1024 line_offset_from_top: u32,
1025 },
1026 MultiBufferPoint {
1027 excerpt_id: ExcerptId,
1028 position: Point,
1029 anchor: text::Anchor,
1030 line_offset_from_top: u32,
1031 },
1032}
1033
1034pub enum MultibufferSelectionMode {
1035 First,
1036 All,
1037}
1038
1039impl Editor {
1040 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1041 let buffer = cx.new(|cx| Buffer::local("", cx));
1042 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1043 Self::new(
1044 EditorMode::SingleLine { auto_width: false },
1045 buffer,
1046 None,
1047 false,
1048 window,
1049 cx,
1050 )
1051 }
1052
1053 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1054 let buffer = cx.new(|cx| Buffer::local("", cx));
1055 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1056 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1057 }
1058
1059 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1060 let buffer = cx.new(|cx| Buffer::local("", cx));
1061 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1062 Self::new(
1063 EditorMode::SingleLine { auto_width: true },
1064 buffer,
1065 None,
1066 false,
1067 window,
1068 cx,
1069 )
1070 }
1071
1072 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1073 let buffer = cx.new(|cx| Buffer::local("", cx));
1074 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1075 Self::new(
1076 EditorMode::AutoHeight { max_lines },
1077 buffer,
1078 None,
1079 false,
1080 window,
1081 cx,
1082 )
1083 }
1084
1085 pub fn for_buffer(
1086 buffer: Entity<Buffer>,
1087 project: Option<Entity<Project>>,
1088 window: &mut Window,
1089 cx: &mut Context<Self>,
1090 ) -> Self {
1091 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1092 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1093 }
1094
1095 pub fn for_multibuffer(
1096 buffer: Entity<MultiBuffer>,
1097 project: Option<Entity<Project>>,
1098 show_excerpt_controls: bool,
1099 window: &mut Window,
1100 cx: &mut Context<Self>,
1101 ) -> Self {
1102 Self::new(
1103 EditorMode::Full,
1104 buffer,
1105 project,
1106 show_excerpt_controls,
1107 window,
1108 cx,
1109 )
1110 }
1111
1112 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1113 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1114 let mut clone = Self::new(
1115 self.mode,
1116 self.buffer.clone(),
1117 self.project.clone(),
1118 show_excerpt_controls,
1119 window,
1120 cx,
1121 );
1122 self.display_map.update(cx, |display_map, cx| {
1123 let snapshot = display_map.snapshot(cx);
1124 clone.display_map.update(cx, |display_map, cx| {
1125 display_map.set_state(&snapshot, cx);
1126 });
1127 });
1128 clone.selections.clone_state(&self.selections);
1129 clone.scroll_manager.clone_state(&self.scroll_manager);
1130 clone.searchable = self.searchable;
1131 clone
1132 }
1133
1134 pub fn new(
1135 mode: EditorMode,
1136 buffer: Entity<MultiBuffer>,
1137 project: Option<Entity<Project>>,
1138 show_excerpt_controls: bool,
1139 window: &mut Window,
1140 cx: &mut Context<Self>,
1141 ) -> Self {
1142 let style = window.text_style();
1143 let font_size = style.font_size.to_pixels(window.rem_size());
1144 let editor = cx.entity().downgrade();
1145 let fold_placeholder = FoldPlaceholder {
1146 constrain_width: true,
1147 render: Arc::new(move |fold_id, fold_range, cx| {
1148 let editor = editor.clone();
1149 div()
1150 .id(fold_id)
1151 .bg(cx.theme().colors().ghost_element_background)
1152 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1153 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1154 .rounded_sm()
1155 .size_full()
1156 .cursor_pointer()
1157 .child("⋯")
1158 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1159 .on_click(move |_, _window, cx| {
1160 editor
1161 .update(cx, |editor, cx| {
1162 editor.unfold_ranges(
1163 &[fold_range.start..fold_range.end],
1164 true,
1165 false,
1166 cx,
1167 );
1168 cx.stop_propagation();
1169 })
1170 .ok();
1171 })
1172 .into_any()
1173 }),
1174 merge_adjacent: true,
1175 ..Default::default()
1176 };
1177 let display_map = cx.new(|cx| {
1178 DisplayMap::new(
1179 buffer.clone(),
1180 style.font(),
1181 font_size,
1182 None,
1183 show_excerpt_controls,
1184 FILE_HEADER_HEIGHT,
1185 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1186 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1187 fold_placeholder,
1188 cx,
1189 )
1190 });
1191
1192 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1193
1194 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1195
1196 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1197 .then(|| language_settings::SoftWrap::None);
1198
1199 let mut project_subscriptions = Vec::new();
1200 if mode == EditorMode::Full {
1201 if let Some(project) = project.as_ref() {
1202 if buffer.read(cx).is_singleton() {
1203 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1204 cx.emit(EditorEvent::TitleChanged);
1205 }));
1206 }
1207 project_subscriptions.push(cx.subscribe_in(
1208 project,
1209 window,
1210 |editor, _, event, window, cx| {
1211 if let project::Event::RefreshInlayHints = event {
1212 editor
1213 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1214 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1215 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1216 let focus_handle = editor.focus_handle(cx);
1217 if focus_handle.is_focused(window) {
1218 let snapshot = buffer.read(cx).snapshot();
1219 for (range, snippet) in snippet_edits {
1220 let editor_range =
1221 language::range_from_lsp(*range).to_offset(&snapshot);
1222 editor
1223 .insert_snippet(
1224 &[editor_range],
1225 snippet.clone(),
1226 window,
1227 cx,
1228 )
1229 .ok();
1230 }
1231 }
1232 }
1233 }
1234 },
1235 ));
1236 if let Some(task_inventory) = project
1237 .read(cx)
1238 .task_store()
1239 .read(cx)
1240 .task_inventory()
1241 .cloned()
1242 {
1243 project_subscriptions.push(cx.observe_in(
1244 &task_inventory,
1245 window,
1246 |editor, _, window, cx| {
1247 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1248 },
1249 ));
1250 }
1251 }
1252 }
1253
1254 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1255
1256 let inlay_hint_settings =
1257 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1258 let focus_handle = cx.focus_handle();
1259 cx.on_focus(&focus_handle, window, Self::handle_focus)
1260 .detach();
1261 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1262 .detach();
1263 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1264 .detach();
1265 cx.on_blur(&focus_handle, window, Self::handle_blur)
1266 .detach();
1267
1268 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1269 Some(false)
1270 } else {
1271 None
1272 };
1273
1274 let mut code_action_providers = Vec::new();
1275 let mut load_uncommitted_diff = None;
1276 if let Some(project) = project.clone() {
1277 load_uncommitted_diff = Some(
1278 get_uncommitted_diff_for_buffer(
1279 &project,
1280 buffer.read(cx).all_buffers(),
1281 buffer.clone(),
1282 cx,
1283 )
1284 .shared(),
1285 );
1286 code_action_providers.push(Rc::new(project) as Rc<_>);
1287 }
1288
1289 let mut this = Self {
1290 focus_handle,
1291 show_cursor_when_unfocused: false,
1292 last_focused_descendant: None,
1293 buffer: buffer.clone(),
1294 display_map: display_map.clone(),
1295 selections,
1296 scroll_manager: ScrollManager::new(cx),
1297 columnar_selection_tail: None,
1298 add_selections_state: None,
1299 select_next_state: None,
1300 select_prev_state: None,
1301 selection_history: Default::default(),
1302 autoclose_regions: Default::default(),
1303 snippet_stack: Default::default(),
1304 select_larger_syntax_node_stack: Vec::new(),
1305 ime_transaction: Default::default(),
1306 active_diagnostics: None,
1307 soft_wrap_mode_override,
1308 completion_provider: project.clone().map(|project| Box::new(project) as _),
1309 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1310 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1311 project,
1312 blink_manager: blink_manager.clone(),
1313 show_local_selections: true,
1314 show_scrollbars: true,
1315 mode,
1316 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1317 show_gutter: mode == EditorMode::Full,
1318 show_line_numbers: None,
1319 use_relative_line_numbers: None,
1320 show_git_diff_gutter: None,
1321 show_code_actions: None,
1322 show_runnables: None,
1323 show_wrap_guides: None,
1324 show_indent_guides,
1325 placeholder_text: None,
1326 highlight_order: 0,
1327 highlighted_rows: HashMap::default(),
1328 background_highlights: Default::default(),
1329 gutter_highlights: TreeMap::default(),
1330 scrollbar_marker_state: ScrollbarMarkerState::default(),
1331 active_indent_guides_state: ActiveIndentGuidesState::default(),
1332 nav_history: None,
1333 context_menu: RefCell::new(None),
1334 mouse_context_menu: None,
1335 completion_tasks: Default::default(),
1336 signature_help_state: SignatureHelpState::default(),
1337 auto_signature_help: None,
1338 find_all_references_task_sources: Vec::new(),
1339 next_completion_id: 0,
1340 next_inlay_id: 0,
1341 code_action_providers,
1342 available_code_actions: Default::default(),
1343 code_actions_task: Default::default(),
1344 selection_highlight_task: Default::default(),
1345 document_highlights_task: Default::default(),
1346 linked_editing_range_task: Default::default(),
1347 pending_rename: Default::default(),
1348 searchable: true,
1349 cursor_shape: EditorSettings::get_global(cx)
1350 .cursor_shape
1351 .unwrap_or_default(),
1352 current_line_highlight: None,
1353 autoindent_mode: Some(AutoindentMode::EachLine),
1354 collapse_matches: false,
1355 workspace: None,
1356 input_enabled: true,
1357 use_modal_editing: mode == EditorMode::Full,
1358 read_only: false,
1359 use_autoclose: true,
1360 use_auto_surround: true,
1361 auto_replace_emoji_shortcode: false,
1362 leader_peer_id: None,
1363 remote_id: None,
1364 hover_state: Default::default(),
1365 pending_mouse_down: None,
1366 hovered_link_state: Default::default(),
1367 edit_prediction_provider: None,
1368 active_inline_completion: None,
1369 stale_inline_completion_in_menu: None,
1370 edit_prediction_preview: EditPredictionPreview::Inactive,
1371 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1372
1373 gutter_hovered: false,
1374 pixel_position_of_newest_cursor: None,
1375 last_bounds: None,
1376 last_position_map: None,
1377 expect_bounds_change: None,
1378 gutter_dimensions: GutterDimensions::default(),
1379 style: None,
1380 show_cursor_names: false,
1381 hovered_cursors: Default::default(),
1382 next_editor_action_id: EditorActionId::default(),
1383 editor_actions: Rc::default(),
1384 inline_completions_hidden_for_vim_mode: false,
1385 show_inline_completions_override: None,
1386 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1387 edit_prediction_settings: EditPredictionSettings::Disabled,
1388 edit_prediction_cursor_on_leading_whitespace: false,
1389 edit_prediction_requires_modifier_in_leading_space: true,
1390 custom_context_menu: None,
1391 show_git_blame_gutter: false,
1392 show_git_blame_inline: false,
1393 distinguish_unstaged_diff_hunks: false,
1394 show_selection_menu: None,
1395 show_git_blame_inline_delay_task: None,
1396 git_blame_inline_tooltip: None,
1397 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1398 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1399 .session
1400 .restore_unsaved_buffers,
1401 blame: None,
1402 blame_subscription: None,
1403 tasks: Default::default(),
1404 _subscriptions: vec![
1405 cx.observe(&buffer, Self::on_buffer_changed),
1406 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1407 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1408 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1409 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1410 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1411 cx.observe_window_activation(window, |editor, window, cx| {
1412 let active = window.is_window_active();
1413 editor.blink_manager.update(cx, |blink_manager, cx| {
1414 if active {
1415 blink_manager.enable(cx);
1416 } else {
1417 blink_manager.disable(cx);
1418 }
1419 });
1420 }),
1421 ],
1422 tasks_update_task: None,
1423 linked_edit_ranges: Default::default(),
1424 in_project_search: false,
1425 previous_search_ranges: None,
1426 breadcrumb_header: None,
1427 focused_block: None,
1428 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1429 addons: HashMap::default(),
1430 registered_buffers: HashMap::default(),
1431 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1432 selection_mark_mode: false,
1433 toggle_fold_multiple_buffers: Task::ready(()),
1434 serialize_selections: Task::ready(()),
1435 text_style_refinement: None,
1436 load_diff_task: load_uncommitted_diff,
1437 mouse_cursor_hidden: false,
1438 hide_mouse_while_typing: EditorSettings::get_global(cx)
1439 .hide_mouse_while_typing
1440 .unwrap_or(true),
1441 };
1442 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1443 this._subscriptions.extend(project_subscriptions);
1444
1445 this.end_selection(window, cx);
1446 this.scroll_manager.show_scrollbar(window, cx);
1447
1448 if mode == EditorMode::Full {
1449 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1450 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1451
1452 if this.git_blame_inline_enabled {
1453 this.git_blame_inline_enabled = true;
1454 this.start_git_blame_inline(false, window, cx);
1455 }
1456
1457 if let Some(buffer) = buffer.read(cx).as_singleton() {
1458 if let Some(project) = this.project.as_ref() {
1459 let handle = project.update(cx, |project, cx| {
1460 project.register_buffer_with_language_servers(&buffer, cx)
1461 });
1462 this.registered_buffers
1463 .insert(buffer.read(cx).remote_id(), handle);
1464 }
1465 }
1466 }
1467
1468 this.report_editor_event("Editor Opened", None, cx);
1469 this
1470 }
1471
1472 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1473 self.mouse_context_menu
1474 .as_ref()
1475 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1476 }
1477
1478 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1479 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1480 }
1481
1482 fn key_context_internal(
1483 &self,
1484 has_active_edit_prediction: bool,
1485 window: &Window,
1486 cx: &App,
1487 ) -> KeyContext {
1488 let mut key_context = KeyContext::new_with_defaults();
1489 key_context.add("Editor");
1490 let mode = match self.mode {
1491 EditorMode::SingleLine { .. } => "single_line",
1492 EditorMode::AutoHeight { .. } => "auto_height",
1493 EditorMode::Full => "full",
1494 };
1495
1496 if EditorSettings::jupyter_enabled(cx) {
1497 key_context.add("jupyter");
1498 }
1499
1500 key_context.set("mode", mode);
1501 if self.pending_rename.is_some() {
1502 key_context.add("renaming");
1503 }
1504
1505 match self.context_menu.borrow().as_ref() {
1506 Some(CodeContextMenu::Completions(_)) => {
1507 key_context.add("menu");
1508 key_context.add("showing_completions");
1509 }
1510 Some(CodeContextMenu::CodeActions(_)) => {
1511 key_context.add("menu");
1512 key_context.add("showing_code_actions")
1513 }
1514 None => {}
1515 }
1516
1517 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1518 if !self.focus_handle(cx).contains_focused(window, cx)
1519 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1520 {
1521 for addon in self.addons.values() {
1522 addon.extend_key_context(&mut key_context, cx)
1523 }
1524 }
1525
1526 if let Some(extension) = self
1527 .buffer
1528 .read(cx)
1529 .as_singleton()
1530 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1531 {
1532 key_context.set("extension", extension.to_string());
1533 }
1534
1535 if has_active_edit_prediction {
1536 if self.edit_prediction_in_conflict() {
1537 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1538 } else {
1539 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1540 key_context.add("copilot_suggestion");
1541 }
1542 }
1543
1544 if self.selection_mark_mode {
1545 key_context.add("selection_mode");
1546 }
1547
1548 key_context
1549 }
1550
1551 pub fn edit_prediction_in_conflict(&self) -> bool {
1552 if !self.show_edit_predictions_in_menu() {
1553 return false;
1554 }
1555
1556 let showing_completions = self
1557 .context_menu
1558 .borrow()
1559 .as_ref()
1560 .map_or(false, |context| {
1561 matches!(context, CodeContextMenu::Completions(_))
1562 });
1563
1564 showing_completions
1565 || self.edit_prediction_requires_modifier()
1566 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1567 // bindings to insert tab characters.
1568 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1569 }
1570
1571 pub fn accept_edit_prediction_keybind(
1572 &self,
1573 window: &Window,
1574 cx: &App,
1575 ) -> AcceptEditPredictionBinding {
1576 let key_context = self.key_context_internal(true, window, cx);
1577 let in_conflict = self.edit_prediction_in_conflict();
1578
1579 AcceptEditPredictionBinding(
1580 window
1581 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1582 .into_iter()
1583 .filter(|binding| {
1584 !in_conflict
1585 || binding
1586 .keystrokes()
1587 .first()
1588 .map_or(false, |keystroke| keystroke.modifiers.modified())
1589 })
1590 .rev()
1591 .min_by_key(|binding| {
1592 binding
1593 .keystrokes()
1594 .first()
1595 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1596 }),
1597 )
1598 }
1599
1600 pub fn new_file(
1601 workspace: &mut Workspace,
1602 _: &workspace::NewFile,
1603 window: &mut Window,
1604 cx: &mut Context<Workspace>,
1605 ) {
1606 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1607 "Failed to create buffer",
1608 window,
1609 cx,
1610 |e, _, _| match e.error_code() {
1611 ErrorCode::RemoteUpgradeRequired => Some(format!(
1612 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1613 e.error_tag("required").unwrap_or("the latest version")
1614 )),
1615 _ => None,
1616 },
1617 );
1618 }
1619
1620 pub fn new_in_workspace(
1621 workspace: &mut Workspace,
1622 window: &mut Window,
1623 cx: &mut Context<Workspace>,
1624 ) -> Task<Result<Entity<Editor>>> {
1625 let project = workspace.project().clone();
1626 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1627
1628 cx.spawn_in(window, |workspace, mut cx| async move {
1629 let buffer = create.await?;
1630 workspace.update_in(&mut cx, |workspace, window, cx| {
1631 let editor =
1632 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1633 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1634 editor
1635 })
1636 })
1637 }
1638
1639 fn new_file_vertical(
1640 workspace: &mut Workspace,
1641 _: &workspace::NewFileSplitVertical,
1642 window: &mut Window,
1643 cx: &mut Context<Workspace>,
1644 ) {
1645 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1646 }
1647
1648 fn new_file_horizontal(
1649 workspace: &mut Workspace,
1650 _: &workspace::NewFileSplitHorizontal,
1651 window: &mut Window,
1652 cx: &mut Context<Workspace>,
1653 ) {
1654 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1655 }
1656
1657 fn new_file_in_direction(
1658 workspace: &mut Workspace,
1659 direction: SplitDirection,
1660 window: &mut Window,
1661 cx: &mut Context<Workspace>,
1662 ) {
1663 let project = workspace.project().clone();
1664 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1665
1666 cx.spawn_in(window, |workspace, mut cx| async move {
1667 let buffer = create.await?;
1668 workspace.update_in(&mut cx, move |workspace, window, cx| {
1669 workspace.split_item(
1670 direction,
1671 Box::new(
1672 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1673 ),
1674 window,
1675 cx,
1676 )
1677 })?;
1678 anyhow::Ok(())
1679 })
1680 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1681 match e.error_code() {
1682 ErrorCode::RemoteUpgradeRequired => Some(format!(
1683 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1684 e.error_tag("required").unwrap_or("the latest version")
1685 )),
1686 _ => None,
1687 }
1688 });
1689 }
1690
1691 pub fn leader_peer_id(&self) -> Option<PeerId> {
1692 self.leader_peer_id
1693 }
1694
1695 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1696 &self.buffer
1697 }
1698
1699 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1700 self.workspace.as_ref()?.0.upgrade()
1701 }
1702
1703 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1704 self.buffer().read(cx).title(cx)
1705 }
1706
1707 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1708 let git_blame_gutter_max_author_length = self
1709 .render_git_blame_gutter(cx)
1710 .then(|| {
1711 if let Some(blame) = self.blame.as_ref() {
1712 let max_author_length =
1713 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1714 Some(max_author_length)
1715 } else {
1716 None
1717 }
1718 })
1719 .flatten();
1720
1721 EditorSnapshot {
1722 mode: self.mode,
1723 show_gutter: self.show_gutter,
1724 show_line_numbers: self.show_line_numbers,
1725 show_git_diff_gutter: self.show_git_diff_gutter,
1726 show_code_actions: self.show_code_actions,
1727 show_runnables: self.show_runnables,
1728 git_blame_gutter_max_author_length,
1729 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1730 scroll_anchor: self.scroll_manager.anchor(),
1731 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1732 placeholder_text: self.placeholder_text.clone(),
1733 is_focused: self.focus_handle.is_focused(window),
1734 current_line_highlight: self
1735 .current_line_highlight
1736 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1737 gutter_hovered: self.gutter_hovered,
1738 }
1739 }
1740
1741 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1742 self.buffer.read(cx).language_at(point, cx)
1743 }
1744
1745 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1746 self.buffer.read(cx).read(cx).file_at(point).cloned()
1747 }
1748
1749 pub fn active_excerpt(
1750 &self,
1751 cx: &App,
1752 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1753 self.buffer
1754 .read(cx)
1755 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1756 }
1757
1758 pub fn mode(&self) -> EditorMode {
1759 self.mode
1760 }
1761
1762 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1763 self.collaboration_hub.as_deref()
1764 }
1765
1766 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1767 self.collaboration_hub = Some(hub);
1768 }
1769
1770 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1771 self.in_project_search = in_project_search;
1772 }
1773
1774 pub fn set_custom_context_menu(
1775 &mut self,
1776 f: impl 'static
1777 + Fn(
1778 &mut Self,
1779 DisplayPoint,
1780 &mut Window,
1781 &mut Context<Self>,
1782 ) -> Option<Entity<ui::ContextMenu>>,
1783 ) {
1784 self.custom_context_menu = Some(Box::new(f))
1785 }
1786
1787 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1788 self.completion_provider = provider;
1789 }
1790
1791 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1792 self.semantics_provider.clone()
1793 }
1794
1795 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1796 self.semantics_provider = provider;
1797 }
1798
1799 pub fn set_edit_prediction_provider<T>(
1800 &mut self,
1801 provider: Option<Entity<T>>,
1802 window: &mut Window,
1803 cx: &mut Context<Self>,
1804 ) where
1805 T: EditPredictionProvider,
1806 {
1807 self.edit_prediction_provider =
1808 provider.map(|provider| RegisteredInlineCompletionProvider {
1809 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1810 if this.focus_handle.is_focused(window) {
1811 this.update_visible_inline_completion(window, cx);
1812 }
1813 }),
1814 provider: Arc::new(provider),
1815 });
1816 self.refresh_inline_completion(false, false, window, cx);
1817 }
1818
1819 pub fn placeholder_text(&self) -> Option<&str> {
1820 self.placeholder_text.as_deref()
1821 }
1822
1823 pub fn set_placeholder_text(
1824 &mut self,
1825 placeholder_text: impl Into<Arc<str>>,
1826 cx: &mut Context<Self>,
1827 ) {
1828 let placeholder_text = Some(placeholder_text.into());
1829 if self.placeholder_text != placeholder_text {
1830 self.placeholder_text = placeholder_text;
1831 cx.notify();
1832 }
1833 }
1834
1835 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1836 self.cursor_shape = cursor_shape;
1837
1838 // Disrupt blink for immediate user feedback that the cursor shape has changed
1839 self.blink_manager.update(cx, BlinkManager::show_cursor);
1840
1841 cx.notify();
1842 }
1843
1844 pub fn set_current_line_highlight(
1845 &mut self,
1846 current_line_highlight: Option<CurrentLineHighlight>,
1847 ) {
1848 self.current_line_highlight = current_line_highlight;
1849 }
1850
1851 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1852 self.collapse_matches = collapse_matches;
1853 }
1854
1855 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1856 let buffers = self.buffer.read(cx).all_buffers();
1857 let Some(project) = self.project.as_ref() else {
1858 return;
1859 };
1860 project.update(cx, |project, cx| {
1861 for buffer in buffers {
1862 self.registered_buffers
1863 .entry(buffer.read(cx).remote_id())
1864 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1865 }
1866 })
1867 }
1868
1869 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1870 if self.collapse_matches {
1871 return range.start..range.start;
1872 }
1873 range.clone()
1874 }
1875
1876 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1877 if self.display_map.read(cx).clip_at_line_ends != clip {
1878 self.display_map
1879 .update(cx, |map, _| map.clip_at_line_ends = clip);
1880 }
1881 }
1882
1883 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1884 self.input_enabled = input_enabled;
1885 }
1886
1887 pub fn set_inline_completions_hidden_for_vim_mode(
1888 &mut self,
1889 hidden: bool,
1890 window: &mut Window,
1891 cx: &mut Context<Self>,
1892 ) {
1893 if hidden != self.inline_completions_hidden_for_vim_mode {
1894 self.inline_completions_hidden_for_vim_mode = hidden;
1895 if hidden {
1896 self.update_visible_inline_completion(window, cx);
1897 } else {
1898 self.refresh_inline_completion(true, false, window, cx);
1899 }
1900 }
1901 }
1902
1903 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1904 self.menu_inline_completions_policy = value;
1905 }
1906
1907 pub fn set_autoindent(&mut self, autoindent: bool) {
1908 if autoindent {
1909 self.autoindent_mode = Some(AutoindentMode::EachLine);
1910 } else {
1911 self.autoindent_mode = None;
1912 }
1913 }
1914
1915 pub fn read_only(&self, cx: &App) -> bool {
1916 self.read_only || self.buffer.read(cx).read_only()
1917 }
1918
1919 pub fn set_read_only(&mut self, read_only: bool) {
1920 self.read_only = read_only;
1921 }
1922
1923 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1924 self.use_autoclose = autoclose;
1925 }
1926
1927 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1928 self.use_auto_surround = auto_surround;
1929 }
1930
1931 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1932 self.auto_replace_emoji_shortcode = auto_replace;
1933 }
1934
1935 pub fn toggle_inline_completions(
1936 &mut self,
1937 _: &ToggleEditPrediction,
1938 window: &mut Window,
1939 cx: &mut Context<Self>,
1940 ) {
1941 if self.show_inline_completions_override.is_some() {
1942 self.set_show_edit_predictions(None, window, cx);
1943 } else {
1944 let show_edit_predictions = !self.edit_predictions_enabled();
1945 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1946 }
1947 }
1948
1949 pub fn set_show_edit_predictions(
1950 &mut self,
1951 show_edit_predictions: Option<bool>,
1952 window: &mut Window,
1953 cx: &mut Context<Self>,
1954 ) {
1955 self.show_inline_completions_override = show_edit_predictions;
1956 self.refresh_inline_completion(false, true, window, cx);
1957 }
1958
1959 fn inline_completions_disabled_in_scope(
1960 &self,
1961 buffer: &Entity<Buffer>,
1962 buffer_position: language::Anchor,
1963 cx: &App,
1964 ) -> bool {
1965 let snapshot = buffer.read(cx).snapshot();
1966 let settings = snapshot.settings_at(buffer_position, cx);
1967
1968 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1969 return false;
1970 };
1971
1972 scope.override_name().map_or(false, |scope_name| {
1973 settings
1974 .edit_predictions_disabled_in
1975 .iter()
1976 .any(|s| s == scope_name)
1977 })
1978 }
1979
1980 pub fn set_use_modal_editing(&mut self, to: bool) {
1981 self.use_modal_editing = to;
1982 }
1983
1984 pub fn use_modal_editing(&self) -> bool {
1985 self.use_modal_editing
1986 }
1987
1988 fn selections_did_change(
1989 &mut self,
1990 local: bool,
1991 old_cursor_position: &Anchor,
1992 show_completions: bool,
1993 window: &mut Window,
1994 cx: &mut Context<Self>,
1995 ) {
1996 window.invalidate_character_coordinates();
1997
1998 // Copy selections to primary selection buffer
1999 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2000 if local {
2001 let selections = self.selections.all::<usize>(cx);
2002 let buffer_handle = self.buffer.read(cx).read(cx);
2003
2004 let mut text = String::new();
2005 for (index, selection) in selections.iter().enumerate() {
2006 let text_for_selection = buffer_handle
2007 .text_for_range(selection.start..selection.end)
2008 .collect::<String>();
2009
2010 text.push_str(&text_for_selection);
2011 if index != selections.len() - 1 {
2012 text.push('\n');
2013 }
2014 }
2015
2016 if !text.is_empty() {
2017 cx.write_to_primary(ClipboardItem::new_string(text));
2018 }
2019 }
2020
2021 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2022 self.buffer.update(cx, |buffer, cx| {
2023 buffer.set_active_selections(
2024 &self.selections.disjoint_anchors(),
2025 self.selections.line_mode,
2026 self.cursor_shape,
2027 cx,
2028 )
2029 });
2030 }
2031 let display_map = self
2032 .display_map
2033 .update(cx, |display_map, cx| display_map.snapshot(cx));
2034 let buffer = &display_map.buffer_snapshot;
2035 self.add_selections_state = None;
2036 self.select_next_state = None;
2037 self.select_prev_state = None;
2038 self.select_larger_syntax_node_stack.clear();
2039 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2040 self.snippet_stack
2041 .invalidate(&self.selections.disjoint_anchors(), buffer);
2042 self.take_rename(false, window, cx);
2043
2044 let new_cursor_position = self.selections.newest_anchor().head();
2045
2046 self.push_to_nav_history(
2047 *old_cursor_position,
2048 Some(new_cursor_position.to_point(buffer)),
2049 cx,
2050 );
2051
2052 if local {
2053 let new_cursor_position = self.selections.newest_anchor().head();
2054 let mut context_menu = self.context_menu.borrow_mut();
2055 let completion_menu = match context_menu.as_ref() {
2056 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2057 _ => {
2058 *context_menu = None;
2059 None
2060 }
2061 };
2062 if let Some(buffer_id) = new_cursor_position.buffer_id {
2063 if !self.registered_buffers.contains_key(&buffer_id) {
2064 if let Some(project) = self.project.as_ref() {
2065 project.update(cx, |project, cx| {
2066 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2067 return;
2068 };
2069 self.registered_buffers.insert(
2070 buffer_id,
2071 project.register_buffer_with_language_servers(&buffer, cx),
2072 );
2073 })
2074 }
2075 }
2076 }
2077
2078 if let Some(completion_menu) = completion_menu {
2079 let cursor_position = new_cursor_position.to_offset(buffer);
2080 let (word_range, kind) =
2081 buffer.surrounding_word(completion_menu.initial_position, true);
2082 if kind == Some(CharKind::Word)
2083 && word_range.to_inclusive().contains(&cursor_position)
2084 {
2085 let mut completion_menu = completion_menu.clone();
2086 drop(context_menu);
2087
2088 let query = Self::completion_query(buffer, cursor_position);
2089 cx.spawn(move |this, mut cx| async move {
2090 completion_menu
2091 .filter(query.as_deref(), cx.background_executor().clone())
2092 .await;
2093
2094 this.update(&mut cx, |this, cx| {
2095 let mut context_menu = this.context_menu.borrow_mut();
2096 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2097 else {
2098 return;
2099 };
2100
2101 if menu.id > completion_menu.id {
2102 return;
2103 }
2104
2105 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2106 drop(context_menu);
2107 cx.notify();
2108 })
2109 })
2110 .detach();
2111
2112 if show_completions {
2113 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2114 }
2115 } else {
2116 drop(context_menu);
2117 self.hide_context_menu(window, cx);
2118 }
2119 } else {
2120 drop(context_menu);
2121 }
2122
2123 hide_hover(self, cx);
2124
2125 if old_cursor_position.to_display_point(&display_map).row()
2126 != new_cursor_position.to_display_point(&display_map).row()
2127 {
2128 self.available_code_actions.take();
2129 }
2130 self.refresh_code_actions(window, cx);
2131 self.refresh_document_highlights(cx);
2132 self.refresh_selected_text_highlights(window, cx);
2133 refresh_matching_bracket_highlights(self, window, cx);
2134 self.update_visible_inline_completion(window, cx);
2135 self.edit_prediction_requires_modifier_in_leading_space = true;
2136 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2137 if self.git_blame_inline_enabled {
2138 self.start_inline_blame_timer(window, cx);
2139 }
2140 }
2141
2142 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2143 cx.emit(EditorEvent::SelectionsChanged { local });
2144
2145 let selections = &self.selections.disjoint;
2146 if selections.len() == 1 {
2147 cx.emit(SearchEvent::ActiveMatchChanged)
2148 }
2149 if local
2150 && self.is_singleton(cx)
2151 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2152 {
2153 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2154 let background_executor = cx.background_executor().clone();
2155 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2156 let snapshot = self.buffer().read(cx).snapshot(cx);
2157 let selections = selections.clone();
2158 self.serialize_selections = cx.background_spawn(async move {
2159 background_executor.timer(Duration::from_millis(100)).await;
2160 let selections = selections
2161 .iter()
2162 .map(|selection| {
2163 (
2164 selection.start.to_offset(&snapshot),
2165 selection.end.to_offset(&snapshot),
2166 )
2167 })
2168 .collect();
2169 DB.save_editor_selections(editor_id, workspace_id, selections)
2170 .await
2171 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2172 .log_err();
2173 });
2174 }
2175 }
2176
2177 cx.notify();
2178 }
2179
2180 pub fn change_selections<R>(
2181 &mut self,
2182 autoscroll: Option<Autoscroll>,
2183 window: &mut Window,
2184 cx: &mut Context<Self>,
2185 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2186 ) -> R {
2187 self.change_selections_inner(autoscroll, true, window, cx, change)
2188 }
2189
2190 fn change_selections_inner<R>(
2191 &mut self,
2192 autoscroll: Option<Autoscroll>,
2193 request_completions: bool,
2194 window: &mut Window,
2195 cx: &mut Context<Self>,
2196 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2197 ) -> R {
2198 let old_cursor_position = self.selections.newest_anchor().head();
2199 self.push_to_selection_history();
2200
2201 let (changed, result) = self.selections.change_with(cx, change);
2202
2203 if changed {
2204 if let Some(autoscroll) = autoscroll {
2205 self.request_autoscroll(autoscroll, cx);
2206 }
2207 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2208
2209 if self.should_open_signature_help_automatically(
2210 &old_cursor_position,
2211 self.signature_help_state.backspace_pressed(),
2212 cx,
2213 ) {
2214 self.show_signature_help(&ShowSignatureHelp, window, cx);
2215 }
2216 self.signature_help_state.set_backspace_pressed(false);
2217 }
2218
2219 result
2220 }
2221
2222 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2223 where
2224 I: IntoIterator<Item = (Range<S>, T)>,
2225 S: ToOffset,
2226 T: Into<Arc<str>>,
2227 {
2228 if self.read_only(cx) {
2229 return;
2230 }
2231
2232 self.buffer
2233 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2234 }
2235
2236 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2237 where
2238 I: IntoIterator<Item = (Range<S>, T)>,
2239 S: ToOffset,
2240 T: Into<Arc<str>>,
2241 {
2242 if self.read_only(cx) {
2243 return;
2244 }
2245
2246 self.buffer.update(cx, |buffer, cx| {
2247 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2248 });
2249 }
2250
2251 pub fn edit_with_block_indent<I, S, T>(
2252 &mut self,
2253 edits: I,
2254 original_indent_columns: Vec<u32>,
2255 cx: &mut Context<Self>,
2256 ) where
2257 I: IntoIterator<Item = (Range<S>, T)>,
2258 S: ToOffset,
2259 T: Into<Arc<str>>,
2260 {
2261 if self.read_only(cx) {
2262 return;
2263 }
2264
2265 self.buffer.update(cx, |buffer, cx| {
2266 buffer.edit(
2267 edits,
2268 Some(AutoindentMode::Block {
2269 original_indent_columns,
2270 }),
2271 cx,
2272 )
2273 });
2274 }
2275
2276 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2277 self.hide_context_menu(window, cx);
2278
2279 match phase {
2280 SelectPhase::Begin {
2281 position,
2282 add,
2283 click_count,
2284 } => self.begin_selection(position, add, click_count, window, cx),
2285 SelectPhase::BeginColumnar {
2286 position,
2287 goal_column,
2288 reset,
2289 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2290 SelectPhase::Extend {
2291 position,
2292 click_count,
2293 } => self.extend_selection(position, click_count, window, cx),
2294 SelectPhase::Update {
2295 position,
2296 goal_column,
2297 scroll_delta,
2298 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2299 SelectPhase::End => self.end_selection(window, cx),
2300 }
2301 }
2302
2303 fn extend_selection(
2304 &mut self,
2305 position: DisplayPoint,
2306 click_count: usize,
2307 window: &mut Window,
2308 cx: &mut Context<Self>,
2309 ) {
2310 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2311 let tail = self.selections.newest::<usize>(cx).tail();
2312 self.begin_selection(position, false, click_count, window, cx);
2313
2314 let position = position.to_offset(&display_map, Bias::Left);
2315 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2316
2317 let mut pending_selection = self
2318 .selections
2319 .pending_anchor()
2320 .expect("extend_selection not called with pending selection");
2321 if position >= tail {
2322 pending_selection.start = tail_anchor;
2323 } else {
2324 pending_selection.end = tail_anchor;
2325 pending_selection.reversed = true;
2326 }
2327
2328 let mut pending_mode = self.selections.pending_mode().unwrap();
2329 match &mut pending_mode {
2330 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2331 _ => {}
2332 }
2333
2334 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2335 s.set_pending(pending_selection, pending_mode)
2336 });
2337 }
2338
2339 fn begin_selection(
2340 &mut self,
2341 position: DisplayPoint,
2342 add: bool,
2343 click_count: usize,
2344 window: &mut Window,
2345 cx: &mut Context<Self>,
2346 ) {
2347 if !self.focus_handle.is_focused(window) {
2348 self.last_focused_descendant = None;
2349 window.focus(&self.focus_handle);
2350 }
2351
2352 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2353 let buffer = &display_map.buffer_snapshot;
2354 let newest_selection = self.selections.newest_anchor().clone();
2355 let position = display_map.clip_point(position, Bias::Left);
2356
2357 let start;
2358 let end;
2359 let mode;
2360 let mut auto_scroll;
2361 match click_count {
2362 1 => {
2363 start = buffer.anchor_before(position.to_point(&display_map));
2364 end = start;
2365 mode = SelectMode::Character;
2366 auto_scroll = true;
2367 }
2368 2 => {
2369 let range = movement::surrounding_word(&display_map, position);
2370 start = buffer.anchor_before(range.start.to_point(&display_map));
2371 end = buffer.anchor_before(range.end.to_point(&display_map));
2372 mode = SelectMode::Word(start..end);
2373 auto_scroll = true;
2374 }
2375 3 => {
2376 let position = display_map
2377 .clip_point(position, Bias::Left)
2378 .to_point(&display_map);
2379 let line_start = display_map.prev_line_boundary(position).0;
2380 let next_line_start = buffer.clip_point(
2381 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2382 Bias::Left,
2383 );
2384 start = buffer.anchor_before(line_start);
2385 end = buffer.anchor_before(next_line_start);
2386 mode = SelectMode::Line(start..end);
2387 auto_scroll = true;
2388 }
2389 _ => {
2390 start = buffer.anchor_before(0);
2391 end = buffer.anchor_before(buffer.len());
2392 mode = SelectMode::All;
2393 auto_scroll = false;
2394 }
2395 }
2396 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2397
2398 let point_to_delete: Option<usize> = {
2399 let selected_points: Vec<Selection<Point>> =
2400 self.selections.disjoint_in_range(start..end, cx);
2401
2402 if !add || click_count > 1 {
2403 None
2404 } else if !selected_points.is_empty() {
2405 Some(selected_points[0].id)
2406 } else {
2407 let clicked_point_already_selected =
2408 self.selections.disjoint.iter().find(|selection| {
2409 selection.start.to_point(buffer) == start.to_point(buffer)
2410 || selection.end.to_point(buffer) == end.to_point(buffer)
2411 });
2412
2413 clicked_point_already_selected.map(|selection| selection.id)
2414 }
2415 };
2416
2417 let selections_count = self.selections.count();
2418
2419 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2420 if let Some(point_to_delete) = point_to_delete {
2421 s.delete(point_to_delete);
2422
2423 if selections_count == 1 {
2424 s.set_pending_anchor_range(start..end, mode);
2425 }
2426 } else {
2427 if !add {
2428 s.clear_disjoint();
2429 } else if click_count > 1 {
2430 s.delete(newest_selection.id)
2431 }
2432
2433 s.set_pending_anchor_range(start..end, mode);
2434 }
2435 });
2436 }
2437
2438 fn begin_columnar_selection(
2439 &mut self,
2440 position: DisplayPoint,
2441 goal_column: u32,
2442 reset: bool,
2443 window: &mut Window,
2444 cx: &mut Context<Self>,
2445 ) {
2446 if !self.focus_handle.is_focused(window) {
2447 self.last_focused_descendant = None;
2448 window.focus(&self.focus_handle);
2449 }
2450
2451 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2452
2453 if reset {
2454 let pointer_position = display_map
2455 .buffer_snapshot
2456 .anchor_before(position.to_point(&display_map));
2457
2458 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2459 s.clear_disjoint();
2460 s.set_pending_anchor_range(
2461 pointer_position..pointer_position,
2462 SelectMode::Character,
2463 );
2464 });
2465 }
2466
2467 let tail = self.selections.newest::<Point>(cx).tail();
2468 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2469
2470 if !reset {
2471 self.select_columns(
2472 tail.to_display_point(&display_map),
2473 position,
2474 goal_column,
2475 &display_map,
2476 window,
2477 cx,
2478 );
2479 }
2480 }
2481
2482 fn update_selection(
2483 &mut self,
2484 position: DisplayPoint,
2485 goal_column: u32,
2486 scroll_delta: gpui::Point<f32>,
2487 window: &mut Window,
2488 cx: &mut Context<Self>,
2489 ) {
2490 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2491
2492 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2493 let tail = tail.to_display_point(&display_map);
2494 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2495 } else if let Some(mut pending) = self.selections.pending_anchor() {
2496 let buffer = self.buffer.read(cx).snapshot(cx);
2497 let head;
2498 let tail;
2499 let mode = self.selections.pending_mode().unwrap();
2500 match &mode {
2501 SelectMode::Character => {
2502 head = position.to_point(&display_map);
2503 tail = pending.tail().to_point(&buffer);
2504 }
2505 SelectMode::Word(original_range) => {
2506 let original_display_range = original_range.start.to_display_point(&display_map)
2507 ..original_range.end.to_display_point(&display_map);
2508 let original_buffer_range = original_display_range.start.to_point(&display_map)
2509 ..original_display_range.end.to_point(&display_map);
2510 if movement::is_inside_word(&display_map, position)
2511 || original_display_range.contains(&position)
2512 {
2513 let word_range = movement::surrounding_word(&display_map, position);
2514 if word_range.start < original_display_range.start {
2515 head = word_range.start.to_point(&display_map);
2516 } else {
2517 head = word_range.end.to_point(&display_map);
2518 }
2519 } else {
2520 head = position.to_point(&display_map);
2521 }
2522
2523 if head <= original_buffer_range.start {
2524 tail = original_buffer_range.end;
2525 } else {
2526 tail = original_buffer_range.start;
2527 }
2528 }
2529 SelectMode::Line(original_range) => {
2530 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2531
2532 let position = display_map
2533 .clip_point(position, Bias::Left)
2534 .to_point(&display_map);
2535 let line_start = display_map.prev_line_boundary(position).0;
2536 let next_line_start = buffer.clip_point(
2537 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2538 Bias::Left,
2539 );
2540
2541 if line_start < original_range.start {
2542 head = line_start
2543 } else {
2544 head = next_line_start
2545 }
2546
2547 if head <= original_range.start {
2548 tail = original_range.end;
2549 } else {
2550 tail = original_range.start;
2551 }
2552 }
2553 SelectMode::All => {
2554 return;
2555 }
2556 };
2557
2558 if head < tail {
2559 pending.start = buffer.anchor_before(head);
2560 pending.end = buffer.anchor_before(tail);
2561 pending.reversed = true;
2562 } else {
2563 pending.start = buffer.anchor_before(tail);
2564 pending.end = buffer.anchor_before(head);
2565 pending.reversed = false;
2566 }
2567
2568 self.change_selections(None, window, cx, |s| {
2569 s.set_pending(pending, mode);
2570 });
2571 } else {
2572 log::error!("update_selection dispatched with no pending selection");
2573 return;
2574 }
2575
2576 self.apply_scroll_delta(scroll_delta, window, cx);
2577 cx.notify();
2578 }
2579
2580 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2581 self.columnar_selection_tail.take();
2582 if self.selections.pending_anchor().is_some() {
2583 let selections = self.selections.all::<usize>(cx);
2584 self.change_selections(None, window, cx, |s| {
2585 s.select(selections);
2586 s.clear_pending();
2587 });
2588 }
2589 }
2590
2591 fn select_columns(
2592 &mut self,
2593 tail: DisplayPoint,
2594 head: DisplayPoint,
2595 goal_column: u32,
2596 display_map: &DisplaySnapshot,
2597 window: &mut Window,
2598 cx: &mut Context<Self>,
2599 ) {
2600 let start_row = cmp::min(tail.row(), head.row());
2601 let end_row = cmp::max(tail.row(), head.row());
2602 let start_column = cmp::min(tail.column(), goal_column);
2603 let end_column = cmp::max(tail.column(), goal_column);
2604 let reversed = start_column < tail.column();
2605
2606 let selection_ranges = (start_row.0..=end_row.0)
2607 .map(DisplayRow)
2608 .filter_map(|row| {
2609 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2610 let start = display_map
2611 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2612 .to_point(display_map);
2613 let end = display_map
2614 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2615 .to_point(display_map);
2616 if reversed {
2617 Some(end..start)
2618 } else {
2619 Some(start..end)
2620 }
2621 } else {
2622 None
2623 }
2624 })
2625 .collect::<Vec<_>>();
2626
2627 self.change_selections(None, window, cx, |s| {
2628 s.select_ranges(selection_ranges);
2629 });
2630 cx.notify();
2631 }
2632
2633 pub fn has_pending_nonempty_selection(&self) -> bool {
2634 let pending_nonempty_selection = match self.selections.pending_anchor() {
2635 Some(Selection { start, end, .. }) => start != end,
2636 None => false,
2637 };
2638
2639 pending_nonempty_selection
2640 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2641 }
2642
2643 pub fn has_pending_selection(&self) -> bool {
2644 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2645 }
2646
2647 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2648 self.selection_mark_mode = false;
2649
2650 if self.clear_expanded_diff_hunks(cx) {
2651 cx.notify();
2652 return;
2653 }
2654 if self.dismiss_menus_and_popups(true, window, cx) {
2655 return;
2656 }
2657
2658 if self.mode == EditorMode::Full
2659 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2660 {
2661 return;
2662 }
2663
2664 cx.propagate();
2665 }
2666
2667 pub fn dismiss_menus_and_popups(
2668 &mut self,
2669 is_user_requested: bool,
2670 window: &mut Window,
2671 cx: &mut Context<Self>,
2672 ) -> bool {
2673 if self.take_rename(false, window, cx).is_some() {
2674 return true;
2675 }
2676
2677 if hide_hover(self, cx) {
2678 return true;
2679 }
2680
2681 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2682 return true;
2683 }
2684
2685 if self.hide_context_menu(window, cx).is_some() {
2686 return true;
2687 }
2688
2689 if self.mouse_context_menu.take().is_some() {
2690 return true;
2691 }
2692
2693 if is_user_requested && self.discard_inline_completion(true, cx) {
2694 return true;
2695 }
2696
2697 if self.snippet_stack.pop().is_some() {
2698 return true;
2699 }
2700
2701 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2702 self.dismiss_diagnostics(cx);
2703 return true;
2704 }
2705
2706 false
2707 }
2708
2709 fn linked_editing_ranges_for(
2710 &self,
2711 selection: Range<text::Anchor>,
2712 cx: &App,
2713 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2714 if self.linked_edit_ranges.is_empty() {
2715 return None;
2716 }
2717 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2718 selection.end.buffer_id.and_then(|end_buffer_id| {
2719 if selection.start.buffer_id != Some(end_buffer_id) {
2720 return None;
2721 }
2722 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2723 let snapshot = buffer.read(cx).snapshot();
2724 self.linked_edit_ranges
2725 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2726 .map(|ranges| (ranges, snapshot, buffer))
2727 })?;
2728 use text::ToOffset as TO;
2729 // find offset from the start of current range to current cursor position
2730 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2731
2732 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2733 let start_difference = start_offset - start_byte_offset;
2734 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2735 let end_difference = end_offset - start_byte_offset;
2736 // Current range has associated linked ranges.
2737 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2738 for range in linked_ranges.iter() {
2739 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2740 let end_offset = start_offset + end_difference;
2741 let start_offset = start_offset + start_difference;
2742 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2743 continue;
2744 }
2745 if self.selections.disjoint_anchor_ranges().any(|s| {
2746 if s.start.buffer_id != selection.start.buffer_id
2747 || s.end.buffer_id != selection.end.buffer_id
2748 {
2749 return false;
2750 }
2751 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2752 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2753 }) {
2754 continue;
2755 }
2756 let start = buffer_snapshot.anchor_after(start_offset);
2757 let end = buffer_snapshot.anchor_after(end_offset);
2758 linked_edits
2759 .entry(buffer.clone())
2760 .or_default()
2761 .push(start..end);
2762 }
2763 Some(linked_edits)
2764 }
2765
2766 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2767 let text: Arc<str> = text.into();
2768
2769 if self.read_only(cx) {
2770 return;
2771 }
2772
2773 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
2774
2775 let selections = self.selections.all_adjusted(cx);
2776 let mut bracket_inserted = false;
2777 let mut edits = Vec::new();
2778 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2779 let mut new_selections = Vec::with_capacity(selections.len());
2780 let mut new_autoclose_regions = Vec::new();
2781 let snapshot = self.buffer.read(cx).read(cx);
2782
2783 for (selection, autoclose_region) in
2784 self.selections_with_autoclose_regions(selections, &snapshot)
2785 {
2786 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2787 // Determine if the inserted text matches the opening or closing
2788 // bracket of any of this language's bracket pairs.
2789 let mut bracket_pair = None;
2790 let mut is_bracket_pair_start = false;
2791 let mut is_bracket_pair_end = false;
2792 if !text.is_empty() {
2793 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2794 // and they are removing the character that triggered IME popup.
2795 for (pair, enabled) in scope.brackets() {
2796 if !pair.close && !pair.surround {
2797 continue;
2798 }
2799
2800 if enabled && pair.start.ends_with(text.as_ref()) {
2801 let prefix_len = pair.start.len() - text.len();
2802 let preceding_text_matches_prefix = prefix_len == 0
2803 || (selection.start.column >= (prefix_len as u32)
2804 && snapshot.contains_str_at(
2805 Point::new(
2806 selection.start.row,
2807 selection.start.column - (prefix_len as u32),
2808 ),
2809 &pair.start[..prefix_len],
2810 ));
2811 if preceding_text_matches_prefix {
2812 bracket_pair = Some(pair.clone());
2813 is_bracket_pair_start = true;
2814 break;
2815 }
2816 }
2817 if pair.end.as_str() == text.as_ref() {
2818 bracket_pair = Some(pair.clone());
2819 is_bracket_pair_end = true;
2820 break;
2821 }
2822 }
2823 }
2824
2825 if let Some(bracket_pair) = bracket_pair {
2826 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2827 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2828 let auto_surround =
2829 self.use_auto_surround && snapshot_settings.use_auto_surround;
2830 if selection.is_empty() {
2831 if is_bracket_pair_start {
2832 // If the inserted text is a suffix of an opening bracket and the
2833 // selection is preceded by the rest of the opening bracket, then
2834 // insert the closing bracket.
2835 let following_text_allows_autoclose = snapshot
2836 .chars_at(selection.start)
2837 .next()
2838 .map_or(true, |c| scope.should_autoclose_before(c));
2839
2840 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2841 && bracket_pair.start.len() == 1
2842 {
2843 let target = bracket_pair.start.chars().next().unwrap();
2844 let current_line_count = snapshot
2845 .reversed_chars_at(selection.start)
2846 .take_while(|&c| c != '\n')
2847 .filter(|&c| c == target)
2848 .count();
2849 current_line_count % 2 == 1
2850 } else {
2851 false
2852 };
2853
2854 if autoclose
2855 && bracket_pair.close
2856 && following_text_allows_autoclose
2857 && !is_closing_quote
2858 {
2859 let anchor = snapshot.anchor_before(selection.end);
2860 new_selections.push((selection.map(|_| anchor), text.len()));
2861 new_autoclose_regions.push((
2862 anchor,
2863 text.len(),
2864 selection.id,
2865 bracket_pair.clone(),
2866 ));
2867 edits.push((
2868 selection.range(),
2869 format!("{}{}", text, bracket_pair.end).into(),
2870 ));
2871 bracket_inserted = true;
2872 continue;
2873 }
2874 }
2875
2876 if let Some(region) = autoclose_region {
2877 // If the selection is followed by an auto-inserted closing bracket,
2878 // then don't insert that closing bracket again; just move the selection
2879 // past the closing bracket.
2880 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2881 && text.as_ref() == region.pair.end.as_str();
2882 if should_skip {
2883 let anchor = snapshot.anchor_after(selection.end);
2884 new_selections
2885 .push((selection.map(|_| anchor), region.pair.end.len()));
2886 continue;
2887 }
2888 }
2889
2890 let always_treat_brackets_as_autoclosed = snapshot
2891 .settings_at(selection.start, cx)
2892 .always_treat_brackets_as_autoclosed;
2893 if always_treat_brackets_as_autoclosed
2894 && is_bracket_pair_end
2895 && snapshot.contains_str_at(selection.end, text.as_ref())
2896 {
2897 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2898 // and the inserted text is a closing bracket and the selection is followed
2899 // by the closing bracket then move the selection past the closing bracket.
2900 let anchor = snapshot.anchor_after(selection.end);
2901 new_selections.push((selection.map(|_| anchor), text.len()));
2902 continue;
2903 }
2904 }
2905 // If an opening bracket is 1 character long and is typed while
2906 // text is selected, then surround that text with the bracket pair.
2907 else if auto_surround
2908 && bracket_pair.surround
2909 && is_bracket_pair_start
2910 && bracket_pair.start.chars().count() == 1
2911 {
2912 edits.push((selection.start..selection.start, text.clone()));
2913 edits.push((
2914 selection.end..selection.end,
2915 bracket_pair.end.as_str().into(),
2916 ));
2917 bracket_inserted = true;
2918 new_selections.push((
2919 Selection {
2920 id: selection.id,
2921 start: snapshot.anchor_after(selection.start),
2922 end: snapshot.anchor_before(selection.end),
2923 reversed: selection.reversed,
2924 goal: selection.goal,
2925 },
2926 0,
2927 ));
2928 continue;
2929 }
2930 }
2931 }
2932
2933 if self.auto_replace_emoji_shortcode
2934 && selection.is_empty()
2935 && text.as_ref().ends_with(':')
2936 {
2937 if let Some(possible_emoji_short_code) =
2938 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2939 {
2940 if !possible_emoji_short_code.is_empty() {
2941 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2942 let emoji_shortcode_start = Point::new(
2943 selection.start.row,
2944 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2945 );
2946
2947 // Remove shortcode from buffer
2948 edits.push((
2949 emoji_shortcode_start..selection.start,
2950 "".to_string().into(),
2951 ));
2952 new_selections.push((
2953 Selection {
2954 id: selection.id,
2955 start: snapshot.anchor_after(emoji_shortcode_start),
2956 end: snapshot.anchor_before(selection.start),
2957 reversed: selection.reversed,
2958 goal: selection.goal,
2959 },
2960 0,
2961 ));
2962
2963 // Insert emoji
2964 let selection_start_anchor = snapshot.anchor_after(selection.start);
2965 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2966 edits.push((selection.start..selection.end, emoji.to_string().into()));
2967
2968 continue;
2969 }
2970 }
2971 }
2972 }
2973
2974 // If not handling any auto-close operation, then just replace the selected
2975 // text with the given input and move the selection to the end of the
2976 // newly inserted text.
2977 let anchor = snapshot.anchor_after(selection.end);
2978 if !self.linked_edit_ranges.is_empty() {
2979 let start_anchor = snapshot.anchor_before(selection.start);
2980
2981 let is_word_char = text.chars().next().map_or(true, |char| {
2982 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2983 classifier.is_word(char)
2984 });
2985
2986 if is_word_char {
2987 if let Some(ranges) = self
2988 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2989 {
2990 for (buffer, edits) in ranges {
2991 linked_edits
2992 .entry(buffer.clone())
2993 .or_default()
2994 .extend(edits.into_iter().map(|range| (range, text.clone())));
2995 }
2996 }
2997 }
2998 }
2999
3000 new_selections.push((selection.map(|_| anchor), 0));
3001 edits.push((selection.start..selection.end, text.clone()));
3002 }
3003
3004 drop(snapshot);
3005
3006 self.transact(window, cx, |this, window, cx| {
3007 this.buffer.update(cx, |buffer, cx| {
3008 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3009 });
3010 for (buffer, edits) in linked_edits {
3011 buffer.update(cx, |buffer, cx| {
3012 let snapshot = buffer.snapshot();
3013 let edits = edits
3014 .into_iter()
3015 .map(|(range, text)| {
3016 use text::ToPoint as TP;
3017 let end_point = TP::to_point(&range.end, &snapshot);
3018 let start_point = TP::to_point(&range.start, &snapshot);
3019 (start_point..end_point, text)
3020 })
3021 .sorted_by_key(|(range, _)| range.start)
3022 .collect::<Vec<_>>();
3023 buffer.edit(edits, None, cx);
3024 })
3025 }
3026 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3027 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3028 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3029 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3030 .zip(new_selection_deltas)
3031 .map(|(selection, delta)| Selection {
3032 id: selection.id,
3033 start: selection.start + delta,
3034 end: selection.end + delta,
3035 reversed: selection.reversed,
3036 goal: SelectionGoal::None,
3037 })
3038 .collect::<Vec<_>>();
3039
3040 let mut i = 0;
3041 for (position, delta, selection_id, pair) in new_autoclose_regions {
3042 let position = position.to_offset(&map.buffer_snapshot) + delta;
3043 let start = map.buffer_snapshot.anchor_before(position);
3044 let end = map.buffer_snapshot.anchor_after(position);
3045 while let Some(existing_state) = this.autoclose_regions.get(i) {
3046 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3047 Ordering::Less => i += 1,
3048 Ordering::Greater => break,
3049 Ordering::Equal => {
3050 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3051 Ordering::Less => i += 1,
3052 Ordering::Equal => break,
3053 Ordering::Greater => break,
3054 }
3055 }
3056 }
3057 }
3058 this.autoclose_regions.insert(
3059 i,
3060 AutocloseRegion {
3061 selection_id,
3062 range: start..end,
3063 pair,
3064 },
3065 );
3066 }
3067
3068 let had_active_inline_completion = this.has_active_inline_completion();
3069 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3070 s.select(new_selections)
3071 });
3072
3073 if !bracket_inserted {
3074 if let Some(on_type_format_task) =
3075 this.trigger_on_type_formatting(text.to_string(), window, cx)
3076 {
3077 on_type_format_task.detach_and_log_err(cx);
3078 }
3079 }
3080
3081 let editor_settings = EditorSettings::get_global(cx);
3082 if bracket_inserted
3083 && (editor_settings.auto_signature_help
3084 || editor_settings.show_signature_help_after_edits)
3085 {
3086 this.show_signature_help(&ShowSignatureHelp, window, cx);
3087 }
3088
3089 let trigger_in_words =
3090 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3091 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3092 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3093 this.refresh_inline_completion(true, false, window, cx);
3094 });
3095 }
3096
3097 fn find_possible_emoji_shortcode_at_position(
3098 snapshot: &MultiBufferSnapshot,
3099 position: Point,
3100 ) -> Option<String> {
3101 let mut chars = Vec::new();
3102 let mut found_colon = false;
3103 for char in snapshot.reversed_chars_at(position).take(100) {
3104 // Found a possible emoji shortcode in the middle of the buffer
3105 if found_colon {
3106 if char.is_whitespace() {
3107 chars.reverse();
3108 return Some(chars.iter().collect());
3109 }
3110 // If the previous character is not a whitespace, we are in the middle of a word
3111 // and we only want to complete the shortcode if the word is made up of other emojis
3112 let mut containing_word = String::new();
3113 for ch in snapshot
3114 .reversed_chars_at(position)
3115 .skip(chars.len() + 1)
3116 .take(100)
3117 {
3118 if ch.is_whitespace() {
3119 break;
3120 }
3121 containing_word.push(ch);
3122 }
3123 let containing_word = containing_word.chars().rev().collect::<String>();
3124 if util::word_consists_of_emojis(containing_word.as_str()) {
3125 chars.reverse();
3126 return Some(chars.iter().collect());
3127 }
3128 }
3129
3130 if char.is_whitespace() || !char.is_ascii() {
3131 return None;
3132 }
3133 if char == ':' {
3134 found_colon = true;
3135 } else {
3136 chars.push(char);
3137 }
3138 }
3139 // Found a possible emoji shortcode at the beginning of the buffer
3140 chars.reverse();
3141 Some(chars.iter().collect())
3142 }
3143
3144 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3145 self.transact(window, cx, |this, window, cx| {
3146 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3147 let selections = this.selections.all::<usize>(cx);
3148 let multi_buffer = this.buffer.read(cx);
3149 let buffer = multi_buffer.snapshot(cx);
3150 selections
3151 .iter()
3152 .map(|selection| {
3153 let start_point = selection.start.to_point(&buffer);
3154 let mut indent =
3155 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3156 indent.len = cmp::min(indent.len, start_point.column);
3157 let start = selection.start;
3158 let end = selection.end;
3159 let selection_is_empty = start == end;
3160 let language_scope = buffer.language_scope_at(start);
3161 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3162 &language_scope
3163 {
3164 let insert_extra_newline =
3165 insert_extra_newline_brackets(&buffer, start..end, language)
3166 || insert_extra_newline_tree_sitter(&buffer, start..end);
3167
3168 // Comment extension on newline is allowed only for cursor selections
3169 let comment_delimiter = maybe!({
3170 if !selection_is_empty {
3171 return None;
3172 }
3173
3174 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3175 return None;
3176 }
3177
3178 let delimiters = language.line_comment_prefixes();
3179 let max_len_of_delimiter =
3180 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3181 let (snapshot, range) =
3182 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3183
3184 let mut index_of_first_non_whitespace = 0;
3185 let comment_candidate = snapshot
3186 .chars_for_range(range)
3187 .skip_while(|c| {
3188 let should_skip = c.is_whitespace();
3189 if should_skip {
3190 index_of_first_non_whitespace += 1;
3191 }
3192 should_skip
3193 })
3194 .take(max_len_of_delimiter)
3195 .collect::<String>();
3196 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3197 comment_candidate.starts_with(comment_prefix.as_ref())
3198 })?;
3199 let cursor_is_placed_after_comment_marker =
3200 index_of_first_non_whitespace + comment_prefix.len()
3201 <= start_point.column as usize;
3202 if cursor_is_placed_after_comment_marker {
3203 Some(comment_prefix.clone())
3204 } else {
3205 None
3206 }
3207 });
3208 (comment_delimiter, insert_extra_newline)
3209 } else {
3210 (None, false)
3211 };
3212
3213 let capacity_for_delimiter = comment_delimiter
3214 .as_deref()
3215 .map(str::len)
3216 .unwrap_or_default();
3217 let mut new_text =
3218 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3219 new_text.push('\n');
3220 new_text.extend(indent.chars());
3221 if let Some(delimiter) = &comment_delimiter {
3222 new_text.push_str(delimiter);
3223 }
3224 if insert_extra_newline {
3225 new_text = new_text.repeat(2);
3226 }
3227
3228 let anchor = buffer.anchor_after(end);
3229 let new_selection = selection.map(|_| anchor);
3230 (
3231 (start..end, new_text),
3232 (insert_extra_newline, new_selection),
3233 )
3234 })
3235 .unzip()
3236 };
3237
3238 this.edit_with_autoindent(edits, cx);
3239 let buffer = this.buffer.read(cx).snapshot(cx);
3240 let new_selections = selection_fixup_info
3241 .into_iter()
3242 .map(|(extra_newline_inserted, new_selection)| {
3243 let mut cursor = new_selection.end.to_point(&buffer);
3244 if extra_newline_inserted {
3245 cursor.row -= 1;
3246 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3247 }
3248 new_selection.map(|_| cursor)
3249 })
3250 .collect();
3251
3252 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3253 s.select(new_selections)
3254 });
3255 this.refresh_inline_completion(true, false, window, cx);
3256 });
3257 }
3258
3259 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3260 let buffer = self.buffer.read(cx);
3261 let snapshot = buffer.snapshot(cx);
3262
3263 let mut edits = Vec::new();
3264 let mut rows = Vec::new();
3265
3266 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3267 let cursor = selection.head();
3268 let row = cursor.row;
3269
3270 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3271
3272 let newline = "\n".to_string();
3273 edits.push((start_of_line..start_of_line, newline));
3274
3275 rows.push(row + rows_inserted as u32);
3276 }
3277
3278 self.transact(window, cx, |editor, window, cx| {
3279 editor.edit(edits, cx);
3280
3281 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3282 let mut index = 0;
3283 s.move_cursors_with(|map, _, _| {
3284 let row = rows[index];
3285 index += 1;
3286
3287 let point = Point::new(row, 0);
3288 let boundary = map.next_line_boundary(point).1;
3289 let clipped = map.clip_point(boundary, Bias::Left);
3290
3291 (clipped, SelectionGoal::None)
3292 });
3293 });
3294
3295 let mut indent_edits = Vec::new();
3296 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3297 for row in rows {
3298 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3299 for (row, indent) in indents {
3300 if indent.len == 0 {
3301 continue;
3302 }
3303
3304 let text = match indent.kind {
3305 IndentKind::Space => " ".repeat(indent.len as usize),
3306 IndentKind::Tab => "\t".repeat(indent.len as usize),
3307 };
3308 let point = Point::new(row.0, 0);
3309 indent_edits.push((point..point, text));
3310 }
3311 }
3312 editor.edit(indent_edits, cx);
3313 });
3314 }
3315
3316 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3317 let buffer = self.buffer.read(cx);
3318 let snapshot = buffer.snapshot(cx);
3319
3320 let mut edits = Vec::new();
3321 let mut rows = Vec::new();
3322 let mut rows_inserted = 0;
3323
3324 for selection in self.selections.all_adjusted(cx) {
3325 let cursor = selection.head();
3326 let row = cursor.row;
3327
3328 let point = Point::new(row + 1, 0);
3329 let start_of_line = snapshot.clip_point(point, Bias::Left);
3330
3331 let newline = "\n".to_string();
3332 edits.push((start_of_line..start_of_line, newline));
3333
3334 rows_inserted += 1;
3335 rows.push(row + rows_inserted);
3336 }
3337
3338 self.transact(window, cx, |editor, window, cx| {
3339 editor.edit(edits, cx);
3340
3341 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3342 let mut index = 0;
3343 s.move_cursors_with(|map, _, _| {
3344 let row = rows[index];
3345 index += 1;
3346
3347 let point = Point::new(row, 0);
3348 let boundary = map.next_line_boundary(point).1;
3349 let clipped = map.clip_point(boundary, Bias::Left);
3350
3351 (clipped, SelectionGoal::None)
3352 });
3353 });
3354
3355 let mut indent_edits = Vec::new();
3356 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3357 for row in rows {
3358 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3359 for (row, indent) in indents {
3360 if indent.len == 0 {
3361 continue;
3362 }
3363
3364 let text = match indent.kind {
3365 IndentKind::Space => " ".repeat(indent.len as usize),
3366 IndentKind::Tab => "\t".repeat(indent.len as usize),
3367 };
3368 let point = Point::new(row.0, 0);
3369 indent_edits.push((point..point, text));
3370 }
3371 }
3372 editor.edit(indent_edits, cx);
3373 });
3374 }
3375
3376 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3377 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3378 original_indent_columns: Vec::new(),
3379 });
3380 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3381 }
3382
3383 fn insert_with_autoindent_mode(
3384 &mut self,
3385 text: &str,
3386 autoindent_mode: Option<AutoindentMode>,
3387 window: &mut Window,
3388 cx: &mut Context<Self>,
3389 ) {
3390 if self.read_only(cx) {
3391 return;
3392 }
3393
3394 let text: Arc<str> = text.into();
3395 self.transact(window, cx, |this, window, cx| {
3396 let old_selections = this.selections.all_adjusted(cx);
3397 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3398 let anchors = {
3399 let snapshot = buffer.read(cx);
3400 old_selections
3401 .iter()
3402 .map(|s| {
3403 let anchor = snapshot.anchor_after(s.head());
3404 s.map(|_| anchor)
3405 })
3406 .collect::<Vec<_>>()
3407 };
3408 buffer.edit(
3409 old_selections
3410 .iter()
3411 .map(|s| (s.start..s.end, text.clone())),
3412 autoindent_mode,
3413 cx,
3414 );
3415 anchors
3416 });
3417
3418 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3419 s.select_anchors(selection_anchors);
3420 });
3421
3422 cx.notify();
3423 });
3424 }
3425
3426 fn trigger_completion_on_input(
3427 &mut self,
3428 text: &str,
3429 trigger_in_words: bool,
3430 window: &mut Window,
3431 cx: &mut Context<Self>,
3432 ) {
3433 if self.is_completion_trigger(text, trigger_in_words, cx) {
3434 self.show_completions(
3435 &ShowCompletions {
3436 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3437 },
3438 window,
3439 cx,
3440 );
3441 } else {
3442 self.hide_context_menu(window, cx);
3443 }
3444 }
3445
3446 fn is_completion_trigger(
3447 &self,
3448 text: &str,
3449 trigger_in_words: bool,
3450 cx: &mut Context<Self>,
3451 ) -> bool {
3452 let position = self.selections.newest_anchor().head();
3453 let multibuffer = self.buffer.read(cx);
3454 let Some(buffer) = position
3455 .buffer_id
3456 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3457 else {
3458 return false;
3459 };
3460
3461 if let Some(completion_provider) = &self.completion_provider {
3462 completion_provider.is_completion_trigger(
3463 &buffer,
3464 position.text_anchor,
3465 text,
3466 trigger_in_words,
3467 cx,
3468 )
3469 } else {
3470 false
3471 }
3472 }
3473
3474 /// If any empty selections is touching the start of its innermost containing autoclose
3475 /// region, expand it to select the brackets.
3476 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3477 let selections = self.selections.all::<usize>(cx);
3478 let buffer = self.buffer.read(cx).read(cx);
3479 let new_selections = self
3480 .selections_with_autoclose_regions(selections, &buffer)
3481 .map(|(mut selection, region)| {
3482 if !selection.is_empty() {
3483 return selection;
3484 }
3485
3486 if let Some(region) = region {
3487 let mut range = region.range.to_offset(&buffer);
3488 if selection.start == range.start && range.start >= region.pair.start.len() {
3489 range.start -= region.pair.start.len();
3490 if buffer.contains_str_at(range.start, ®ion.pair.start)
3491 && buffer.contains_str_at(range.end, ®ion.pair.end)
3492 {
3493 range.end += region.pair.end.len();
3494 selection.start = range.start;
3495 selection.end = range.end;
3496
3497 return selection;
3498 }
3499 }
3500 }
3501
3502 let always_treat_brackets_as_autoclosed = buffer
3503 .settings_at(selection.start, cx)
3504 .always_treat_brackets_as_autoclosed;
3505
3506 if !always_treat_brackets_as_autoclosed {
3507 return selection;
3508 }
3509
3510 if let Some(scope) = buffer.language_scope_at(selection.start) {
3511 for (pair, enabled) in scope.brackets() {
3512 if !enabled || !pair.close {
3513 continue;
3514 }
3515
3516 if buffer.contains_str_at(selection.start, &pair.end) {
3517 let pair_start_len = pair.start.len();
3518 if buffer.contains_str_at(
3519 selection.start.saturating_sub(pair_start_len),
3520 &pair.start,
3521 ) {
3522 selection.start -= pair_start_len;
3523 selection.end += pair.end.len();
3524
3525 return selection;
3526 }
3527 }
3528 }
3529 }
3530
3531 selection
3532 })
3533 .collect();
3534
3535 drop(buffer);
3536 self.change_selections(None, window, cx, |selections| {
3537 selections.select(new_selections)
3538 });
3539 }
3540
3541 /// Iterate the given selections, and for each one, find the smallest surrounding
3542 /// autoclose region. This uses the ordering of the selections and the autoclose
3543 /// regions to avoid repeated comparisons.
3544 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3545 &'a self,
3546 selections: impl IntoIterator<Item = Selection<D>>,
3547 buffer: &'a MultiBufferSnapshot,
3548 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3549 let mut i = 0;
3550 let mut regions = self.autoclose_regions.as_slice();
3551 selections.into_iter().map(move |selection| {
3552 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3553
3554 let mut enclosing = None;
3555 while let Some(pair_state) = regions.get(i) {
3556 if pair_state.range.end.to_offset(buffer) < range.start {
3557 regions = ®ions[i + 1..];
3558 i = 0;
3559 } else if pair_state.range.start.to_offset(buffer) > range.end {
3560 break;
3561 } else {
3562 if pair_state.selection_id == selection.id {
3563 enclosing = Some(pair_state);
3564 }
3565 i += 1;
3566 }
3567 }
3568
3569 (selection, enclosing)
3570 })
3571 }
3572
3573 /// Remove any autoclose regions that no longer contain their selection.
3574 fn invalidate_autoclose_regions(
3575 &mut self,
3576 mut selections: &[Selection<Anchor>],
3577 buffer: &MultiBufferSnapshot,
3578 ) {
3579 self.autoclose_regions.retain(|state| {
3580 let mut i = 0;
3581 while let Some(selection) = selections.get(i) {
3582 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3583 selections = &selections[1..];
3584 continue;
3585 }
3586 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3587 break;
3588 }
3589 if selection.id == state.selection_id {
3590 return true;
3591 } else {
3592 i += 1;
3593 }
3594 }
3595 false
3596 });
3597 }
3598
3599 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3600 let offset = position.to_offset(buffer);
3601 let (word_range, kind) = buffer.surrounding_word(offset, true);
3602 if offset > word_range.start && kind == Some(CharKind::Word) {
3603 Some(
3604 buffer
3605 .text_for_range(word_range.start..offset)
3606 .collect::<String>(),
3607 )
3608 } else {
3609 None
3610 }
3611 }
3612
3613 pub fn toggle_inlay_hints(
3614 &mut self,
3615 _: &ToggleInlayHints,
3616 _: &mut Window,
3617 cx: &mut Context<Self>,
3618 ) {
3619 self.refresh_inlay_hints(
3620 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3621 cx,
3622 );
3623 }
3624
3625 pub fn inlay_hints_enabled(&self) -> bool {
3626 self.inlay_hint_cache.enabled
3627 }
3628
3629 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3630 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3631 return;
3632 }
3633
3634 let reason_description = reason.description();
3635 let ignore_debounce = matches!(
3636 reason,
3637 InlayHintRefreshReason::SettingsChange(_)
3638 | InlayHintRefreshReason::Toggle(_)
3639 | InlayHintRefreshReason::ExcerptsRemoved(_)
3640 );
3641 let (invalidate_cache, required_languages) = match reason {
3642 InlayHintRefreshReason::Toggle(enabled) => {
3643 self.inlay_hint_cache.enabled = enabled;
3644 if enabled {
3645 (InvalidationStrategy::RefreshRequested, None)
3646 } else {
3647 self.inlay_hint_cache.clear();
3648 self.splice_inlays(
3649 &self
3650 .visible_inlay_hints(cx)
3651 .iter()
3652 .map(|inlay| inlay.id)
3653 .collect::<Vec<InlayId>>(),
3654 Vec::new(),
3655 cx,
3656 );
3657 return;
3658 }
3659 }
3660 InlayHintRefreshReason::SettingsChange(new_settings) => {
3661 match self.inlay_hint_cache.update_settings(
3662 &self.buffer,
3663 new_settings,
3664 self.visible_inlay_hints(cx),
3665 cx,
3666 ) {
3667 ControlFlow::Break(Some(InlaySplice {
3668 to_remove,
3669 to_insert,
3670 })) => {
3671 self.splice_inlays(&to_remove, to_insert, cx);
3672 return;
3673 }
3674 ControlFlow::Break(None) => return,
3675 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3676 }
3677 }
3678 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3679 if let Some(InlaySplice {
3680 to_remove,
3681 to_insert,
3682 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3683 {
3684 self.splice_inlays(&to_remove, to_insert, cx);
3685 }
3686 return;
3687 }
3688 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3689 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3690 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3691 }
3692 InlayHintRefreshReason::RefreshRequested => {
3693 (InvalidationStrategy::RefreshRequested, None)
3694 }
3695 };
3696
3697 if let Some(InlaySplice {
3698 to_remove,
3699 to_insert,
3700 }) = self.inlay_hint_cache.spawn_hint_refresh(
3701 reason_description,
3702 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3703 invalidate_cache,
3704 ignore_debounce,
3705 cx,
3706 ) {
3707 self.splice_inlays(&to_remove, to_insert, cx);
3708 }
3709 }
3710
3711 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3712 self.display_map
3713 .read(cx)
3714 .current_inlays()
3715 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3716 .cloned()
3717 .collect()
3718 }
3719
3720 pub fn excerpts_for_inlay_hints_query(
3721 &self,
3722 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3723 cx: &mut Context<Editor>,
3724 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3725 let Some(project) = self.project.as_ref() else {
3726 return HashMap::default();
3727 };
3728 let project = project.read(cx);
3729 let multi_buffer = self.buffer().read(cx);
3730 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3731 let multi_buffer_visible_start = self
3732 .scroll_manager
3733 .anchor()
3734 .anchor
3735 .to_point(&multi_buffer_snapshot);
3736 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3737 multi_buffer_visible_start
3738 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3739 Bias::Left,
3740 );
3741 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3742 multi_buffer_snapshot
3743 .range_to_buffer_ranges(multi_buffer_visible_range)
3744 .into_iter()
3745 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3746 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3747 let buffer_file = project::File::from_dyn(buffer.file())?;
3748 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3749 let worktree_entry = buffer_worktree
3750 .read(cx)
3751 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3752 if worktree_entry.is_ignored {
3753 return None;
3754 }
3755
3756 let language = buffer.language()?;
3757 if let Some(restrict_to_languages) = restrict_to_languages {
3758 if !restrict_to_languages.contains(language) {
3759 return None;
3760 }
3761 }
3762 Some((
3763 excerpt_id,
3764 (
3765 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3766 buffer.version().clone(),
3767 excerpt_visible_range,
3768 ),
3769 ))
3770 })
3771 .collect()
3772 }
3773
3774 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3775 TextLayoutDetails {
3776 text_system: window.text_system().clone(),
3777 editor_style: self.style.clone().unwrap(),
3778 rem_size: window.rem_size(),
3779 scroll_anchor: self.scroll_manager.anchor(),
3780 visible_rows: self.visible_line_count(),
3781 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3782 }
3783 }
3784
3785 pub fn splice_inlays(
3786 &self,
3787 to_remove: &[InlayId],
3788 to_insert: Vec<Inlay>,
3789 cx: &mut Context<Self>,
3790 ) {
3791 self.display_map.update(cx, |display_map, cx| {
3792 display_map.splice_inlays(to_remove, to_insert, cx)
3793 });
3794 cx.notify();
3795 }
3796
3797 fn trigger_on_type_formatting(
3798 &self,
3799 input: String,
3800 window: &mut Window,
3801 cx: &mut Context<Self>,
3802 ) -> Option<Task<Result<()>>> {
3803 if input.len() != 1 {
3804 return None;
3805 }
3806
3807 let project = self.project.as_ref()?;
3808 let position = self.selections.newest_anchor().head();
3809 let (buffer, buffer_position) = self
3810 .buffer
3811 .read(cx)
3812 .text_anchor_for_position(position, cx)?;
3813
3814 let settings = language_settings::language_settings(
3815 buffer
3816 .read(cx)
3817 .language_at(buffer_position)
3818 .map(|l| l.name()),
3819 buffer.read(cx).file(),
3820 cx,
3821 );
3822 if !settings.use_on_type_format {
3823 return None;
3824 }
3825
3826 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3827 // hence we do LSP request & edit on host side only — add formats to host's history.
3828 let push_to_lsp_host_history = true;
3829 // If this is not the host, append its history with new edits.
3830 let push_to_client_history = project.read(cx).is_via_collab();
3831
3832 let on_type_formatting = project.update(cx, |project, cx| {
3833 project.on_type_format(
3834 buffer.clone(),
3835 buffer_position,
3836 input,
3837 push_to_lsp_host_history,
3838 cx,
3839 )
3840 });
3841 Some(cx.spawn_in(window, |editor, mut cx| async move {
3842 if let Some(transaction) = on_type_formatting.await? {
3843 if push_to_client_history {
3844 buffer
3845 .update(&mut cx, |buffer, _| {
3846 buffer.push_transaction(transaction, Instant::now());
3847 })
3848 .ok();
3849 }
3850 editor.update(&mut cx, |editor, cx| {
3851 editor.refresh_document_highlights(cx);
3852 })?;
3853 }
3854 Ok(())
3855 }))
3856 }
3857
3858 pub fn show_completions(
3859 &mut self,
3860 options: &ShowCompletions,
3861 window: &mut Window,
3862 cx: &mut Context<Self>,
3863 ) {
3864 if self.pending_rename.is_some() {
3865 return;
3866 }
3867
3868 let Some(provider) = self.completion_provider.as_ref() else {
3869 return;
3870 };
3871
3872 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3873 return;
3874 }
3875
3876 let position = self.selections.newest_anchor().head();
3877 if position.diff_base_anchor.is_some() {
3878 return;
3879 }
3880 let (buffer, buffer_position) =
3881 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3882 output
3883 } else {
3884 return;
3885 };
3886 let show_completion_documentation = buffer
3887 .read(cx)
3888 .snapshot()
3889 .settings_at(buffer_position, cx)
3890 .show_completion_documentation;
3891
3892 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3893
3894 let trigger_kind = match &options.trigger {
3895 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3896 CompletionTriggerKind::TRIGGER_CHARACTER
3897 }
3898 _ => CompletionTriggerKind::INVOKED,
3899 };
3900 let completion_context = CompletionContext {
3901 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3902 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3903 Some(String::from(trigger))
3904 } else {
3905 None
3906 }
3907 }),
3908 trigger_kind,
3909 };
3910 let completions =
3911 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3912 let sort_completions = provider.sort_completions();
3913
3914 let id = post_inc(&mut self.next_completion_id);
3915 let task = cx.spawn_in(window, |editor, mut cx| {
3916 async move {
3917 editor.update(&mut cx, |this, _| {
3918 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3919 })?;
3920 let completions = completions.await.log_err();
3921 let menu = if let Some(completions) = completions {
3922 let mut menu = CompletionsMenu::new(
3923 id,
3924 sort_completions,
3925 show_completion_documentation,
3926 position,
3927 buffer.clone(),
3928 completions.into(),
3929 );
3930
3931 menu.filter(query.as_deref(), cx.background_executor().clone())
3932 .await;
3933
3934 menu.visible().then_some(menu)
3935 } else {
3936 None
3937 };
3938
3939 editor.update_in(&mut cx, |editor, window, cx| {
3940 match editor.context_menu.borrow().as_ref() {
3941 None => {}
3942 Some(CodeContextMenu::Completions(prev_menu)) => {
3943 if prev_menu.id > id {
3944 return;
3945 }
3946 }
3947 _ => return,
3948 }
3949
3950 if editor.focus_handle.is_focused(window) && menu.is_some() {
3951 let mut menu = menu.unwrap();
3952 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3953
3954 *editor.context_menu.borrow_mut() =
3955 Some(CodeContextMenu::Completions(menu));
3956
3957 if editor.show_edit_predictions_in_menu() {
3958 editor.update_visible_inline_completion(window, cx);
3959 } else {
3960 editor.discard_inline_completion(false, cx);
3961 }
3962
3963 cx.notify();
3964 } else if editor.completion_tasks.len() <= 1 {
3965 // If there are no more completion tasks and the last menu was
3966 // empty, we should hide it.
3967 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3968 // If it was already hidden and we don't show inline
3969 // completions in the menu, we should also show the
3970 // inline-completion when available.
3971 if was_hidden && editor.show_edit_predictions_in_menu() {
3972 editor.update_visible_inline_completion(window, cx);
3973 }
3974 }
3975 })?;
3976
3977 Ok::<_, anyhow::Error>(())
3978 }
3979 .log_err()
3980 });
3981
3982 self.completion_tasks.push((id, task));
3983 }
3984
3985 pub fn confirm_completion(
3986 &mut self,
3987 action: &ConfirmCompletion,
3988 window: &mut Window,
3989 cx: &mut Context<Self>,
3990 ) -> Option<Task<Result<()>>> {
3991 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3992 }
3993
3994 pub fn compose_completion(
3995 &mut self,
3996 action: &ComposeCompletion,
3997 window: &mut Window,
3998 cx: &mut Context<Self>,
3999 ) -> Option<Task<Result<()>>> {
4000 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4001 }
4002
4003 fn do_completion(
4004 &mut self,
4005 item_ix: Option<usize>,
4006 intent: CompletionIntent,
4007 window: &mut Window,
4008 cx: &mut Context<Editor>,
4009 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4010 use language::ToOffset as _;
4011
4012 let completions_menu =
4013 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4014 menu
4015 } else {
4016 return None;
4017 };
4018
4019 let entries = completions_menu.entries.borrow();
4020 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4021 if self.show_edit_predictions_in_menu() {
4022 self.discard_inline_completion(true, cx);
4023 }
4024 let candidate_id = mat.candidate_id;
4025 drop(entries);
4026
4027 let buffer_handle = completions_menu.buffer;
4028 let completion = completions_menu
4029 .completions
4030 .borrow()
4031 .get(candidate_id)?
4032 .clone();
4033 cx.stop_propagation();
4034
4035 let snippet;
4036 let text;
4037
4038 if completion.is_snippet() {
4039 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4040 text = snippet.as_ref().unwrap().text.clone();
4041 } else {
4042 snippet = None;
4043 text = completion.new_text.clone();
4044 };
4045 let selections = self.selections.all::<usize>(cx);
4046 let buffer = buffer_handle.read(cx);
4047 let old_range = completion.old_range.to_offset(buffer);
4048 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4049
4050 let newest_selection = self.selections.newest_anchor();
4051 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4052 return None;
4053 }
4054
4055 let lookbehind = newest_selection
4056 .start
4057 .text_anchor
4058 .to_offset(buffer)
4059 .saturating_sub(old_range.start);
4060 let lookahead = old_range
4061 .end
4062 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4063 let mut common_prefix_len = old_text
4064 .bytes()
4065 .zip(text.bytes())
4066 .take_while(|(a, b)| a == b)
4067 .count();
4068
4069 let snapshot = self.buffer.read(cx).snapshot(cx);
4070 let mut range_to_replace: Option<Range<isize>> = None;
4071 let mut ranges = Vec::new();
4072 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4073 for selection in &selections {
4074 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4075 let start = selection.start.saturating_sub(lookbehind);
4076 let end = selection.end + lookahead;
4077 if selection.id == newest_selection.id {
4078 range_to_replace = Some(
4079 ((start + common_prefix_len) as isize - selection.start as isize)
4080 ..(end as isize - selection.start as isize),
4081 );
4082 }
4083 ranges.push(start + common_prefix_len..end);
4084 } else {
4085 common_prefix_len = 0;
4086 ranges.clear();
4087 ranges.extend(selections.iter().map(|s| {
4088 if s.id == newest_selection.id {
4089 range_to_replace = Some(
4090 old_range.start.to_offset_utf16(&snapshot).0 as isize
4091 - selection.start as isize
4092 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4093 - selection.start as isize,
4094 );
4095 old_range.clone()
4096 } else {
4097 s.start..s.end
4098 }
4099 }));
4100 break;
4101 }
4102 if !self.linked_edit_ranges.is_empty() {
4103 let start_anchor = snapshot.anchor_before(selection.head());
4104 let end_anchor = snapshot.anchor_after(selection.tail());
4105 if let Some(ranges) = self
4106 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4107 {
4108 for (buffer, edits) in ranges {
4109 linked_edits.entry(buffer.clone()).or_default().extend(
4110 edits
4111 .into_iter()
4112 .map(|range| (range, text[common_prefix_len..].to_owned())),
4113 );
4114 }
4115 }
4116 }
4117 }
4118 let text = &text[common_prefix_len..];
4119
4120 cx.emit(EditorEvent::InputHandled {
4121 utf16_range_to_replace: range_to_replace,
4122 text: text.into(),
4123 });
4124
4125 self.transact(window, cx, |this, window, cx| {
4126 if let Some(mut snippet) = snippet {
4127 snippet.text = text.to_string();
4128 for tabstop in snippet
4129 .tabstops
4130 .iter_mut()
4131 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4132 {
4133 tabstop.start -= common_prefix_len as isize;
4134 tabstop.end -= common_prefix_len as isize;
4135 }
4136
4137 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4138 } else {
4139 this.buffer.update(cx, |buffer, cx| {
4140 buffer.edit(
4141 ranges.iter().map(|range| (range.clone(), text)),
4142 this.autoindent_mode.clone(),
4143 cx,
4144 );
4145 });
4146 }
4147 for (buffer, edits) in linked_edits {
4148 buffer.update(cx, |buffer, cx| {
4149 let snapshot = buffer.snapshot();
4150 let edits = edits
4151 .into_iter()
4152 .map(|(range, text)| {
4153 use text::ToPoint as TP;
4154 let end_point = TP::to_point(&range.end, &snapshot);
4155 let start_point = TP::to_point(&range.start, &snapshot);
4156 (start_point..end_point, text)
4157 })
4158 .sorted_by_key(|(range, _)| range.start)
4159 .collect::<Vec<_>>();
4160 buffer.edit(edits, None, cx);
4161 })
4162 }
4163
4164 this.refresh_inline_completion(true, false, window, cx);
4165 });
4166
4167 let show_new_completions_on_confirm = completion
4168 .confirm
4169 .as_ref()
4170 .map_or(false, |confirm| confirm(intent, window, cx));
4171 if show_new_completions_on_confirm {
4172 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4173 }
4174
4175 let provider = self.completion_provider.as_ref()?;
4176 drop(completion);
4177 let apply_edits = provider.apply_additional_edits_for_completion(
4178 buffer_handle,
4179 completions_menu.completions.clone(),
4180 candidate_id,
4181 true,
4182 cx,
4183 );
4184
4185 let editor_settings = EditorSettings::get_global(cx);
4186 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4187 // After the code completion is finished, users often want to know what signatures are needed.
4188 // so we should automatically call signature_help
4189 self.show_signature_help(&ShowSignatureHelp, window, cx);
4190 }
4191
4192 Some(cx.foreground_executor().spawn(async move {
4193 apply_edits.await?;
4194 Ok(())
4195 }))
4196 }
4197
4198 pub fn toggle_code_actions(
4199 &mut self,
4200 action: &ToggleCodeActions,
4201 window: &mut Window,
4202 cx: &mut Context<Self>,
4203 ) {
4204 let mut context_menu = self.context_menu.borrow_mut();
4205 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4206 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4207 // Toggle if we're selecting the same one
4208 *context_menu = None;
4209 cx.notify();
4210 return;
4211 } else {
4212 // Otherwise, clear it and start a new one
4213 *context_menu = None;
4214 cx.notify();
4215 }
4216 }
4217 drop(context_menu);
4218 let snapshot = self.snapshot(window, cx);
4219 let deployed_from_indicator = action.deployed_from_indicator;
4220 let mut task = self.code_actions_task.take();
4221 let action = action.clone();
4222 cx.spawn_in(window, |editor, mut cx| async move {
4223 while let Some(prev_task) = task {
4224 prev_task.await.log_err();
4225 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4226 }
4227
4228 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4229 if editor.focus_handle.is_focused(window) {
4230 let multibuffer_point = action
4231 .deployed_from_indicator
4232 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4233 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4234 let (buffer, buffer_row) = snapshot
4235 .buffer_snapshot
4236 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4237 .and_then(|(buffer_snapshot, range)| {
4238 editor
4239 .buffer
4240 .read(cx)
4241 .buffer(buffer_snapshot.remote_id())
4242 .map(|buffer| (buffer, range.start.row))
4243 })?;
4244 let (_, code_actions) = editor
4245 .available_code_actions
4246 .clone()
4247 .and_then(|(location, code_actions)| {
4248 let snapshot = location.buffer.read(cx).snapshot();
4249 let point_range = location.range.to_point(&snapshot);
4250 let point_range = point_range.start.row..=point_range.end.row;
4251 if point_range.contains(&buffer_row) {
4252 Some((location, code_actions))
4253 } else {
4254 None
4255 }
4256 })
4257 .unzip();
4258 let buffer_id = buffer.read(cx).remote_id();
4259 let tasks = editor
4260 .tasks
4261 .get(&(buffer_id, buffer_row))
4262 .map(|t| Arc::new(t.to_owned()));
4263 if tasks.is_none() && code_actions.is_none() {
4264 return None;
4265 }
4266
4267 editor.completion_tasks.clear();
4268 editor.discard_inline_completion(false, cx);
4269 let task_context =
4270 tasks
4271 .as_ref()
4272 .zip(editor.project.clone())
4273 .map(|(tasks, project)| {
4274 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4275 });
4276
4277 Some(cx.spawn_in(window, |editor, mut cx| async move {
4278 let task_context = match task_context {
4279 Some(task_context) => task_context.await,
4280 None => None,
4281 };
4282 let resolved_tasks =
4283 tasks.zip(task_context).map(|(tasks, task_context)| {
4284 Rc::new(ResolvedTasks {
4285 templates: tasks.resolve(&task_context).collect(),
4286 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4287 multibuffer_point.row,
4288 tasks.column,
4289 )),
4290 })
4291 });
4292 let spawn_straight_away = resolved_tasks
4293 .as_ref()
4294 .map_or(false, |tasks| tasks.templates.len() == 1)
4295 && code_actions
4296 .as_ref()
4297 .map_or(true, |actions| actions.is_empty());
4298 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4299 *editor.context_menu.borrow_mut() =
4300 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4301 buffer,
4302 actions: CodeActionContents {
4303 tasks: resolved_tasks,
4304 actions: code_actions,
4305 },
4306 selected_item: Default::default(),
4307 scroll_handle: UniformListScrollHandle::default(),
4308 deployed_from_indicator,
4309 }));
4310 if spawn_straight_away {
4311 if let Some(task) = editor.confirm_code_action(
4312 &ConfirmCodeAction { item_ix: Some(0) },
4313 window,
4314 cx,
4315 ) {
4316 cx.notify();
4317 return task;
4318 }
4319 }
4320 cx.notify();
4321 Task::ready(Ok(()))
4322 }) {
4323 task.await
4324 } else {
4325 Ok(())
4326 }
4327 }))
4328 } else {
4329 Some(Task::ready(Ok(())))
4330 }
4331 })?;
4332 if let Some(task) = spawned_test_task {
4333 task.await?;
4334 }
4335
4336 Ok::<_, anyhow::Error>(())
4337 })
4338 .detach_and_log_err(cx);
4339 }
4340
4341 pub fn confirm_code_action(
4342 &mut self,
4343 action: &ConfirmCodeAction,
4344 window: &mut Window,
4345 cx: &mut Context<Self>,
4346 ) -> Option<Task<Result<()>>> {
4347 let actions_menu =
4348 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4349 menu
4350 } else {
4351 return None;
4352 };
4353 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4354 let action = actions_menu.actions.get(action_ix)?;
4355 let title = action.label();
4356 let buffer = actions_menu.buffer;
4357 let workspace = self.workspace()?;
4358
4359 match action {
4360 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4361 workspace.update(cx, |workspace, cx| {
4362 workspace::tasks::schedule_resolved_task(
4363 workspace,
4364 task_source_kind,
4365 resolved_task,
4366 false,
4367 cx,
4368 );
4369
4370 Some(Task::ready(Ok(())))
4371 })
4372 }
4373 CodeActionsItem::CodeAction {
4374 excerpt_id,
4375 action,
4376 provider,
4377 } => {
4378 let apply_code_action =
4379 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4380 let workspace = workspace.downgrade();
4381 Some(cx.spawn_in(window, |editor, cx| async move {
4382 let project_transaction = apply_code_action.await?;
4383 Self::open_project_transaction(
4384 &editor,
4385 workspace,
4386 project_transaction,
4387 title,
4388 cx,
4389 )
4390 .await
4391 }))
4392 }
4393 }
4394 }
4395
4396 pub async fn open_project_transaction(
4397 this: &WeakEntity<Editor>,
4398 workspace: WeakEntity<Workspace>,
4399 transaction: ProjectTransaction,
4400 title: String,
4401 mut cx: AsyncWindowContext,
4402 ) -> Result<()> {
4403 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4404 cx.update(|_, cx| {
4405 entries.sort_unstable_by_key(|(buffer, _)| {
4406 buffer.read(cx).file().map(|f| f.path().clone())
4407 });
4408 })?;
4409
4410 // If the project transaction's edits are all contained within this editor, then
4411 // avoid opening a new editor to display them.
4412
4413 if let Some((buffer, transaction)) = entries.first() {
4414 if entries.len() == 1 {
4415 let excerpt = this.update(&mut cx, |editor, cx| {
4416 editor
4417 .buffer()
4418 .read(cx)
4419 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4420 })?;
4421 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4422 if excerpted_buffer == *buffer {
4423 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4424 let excerpt_range = excerpt_range.to_offset(buffer);
4425 buffer
4426 .edited_ranges_for_transaction::<usize>(transaction)
4427 .all(|range| {
4428 excerpt_range.start <= range.start
4429 && excerpt_range.end >= range.end
4430 })
4431 })?;
4432
4433 if all_edits_within_excerpt {
4434 return Ok(());
4435 }
4436 }
4437 }
4438 }
4439 } else {
4440 return Ok(());
4441 }
4442
4443 let mut ranges_to_highlight = Vec::new();
4444 let excerpt_buffer = cx.new(|cx| {
4445 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4446 for (buffer_handle, transaction) in &entries {
4447 let buffer = buffer_handle.read(cx);
4448 ranges_to_highlight.extend(
4449 multibuffer.push_excerpts_with_context_lines(
4450 buffer_handle.clone(),
4451 buffer
4452 .edited_ranges_for_transaction::<usize>(transaction)
4453 .collect(),
4454 DEFAULT_MULTIBUFFER_CONTEXT,
4455 cx,
4456 ),
4457 );
4458 }
4459 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4460 multibuffer
4461 })?;
4462
4463 workspace.update_in(&mut cx, |workspace, window, cx| {
4464 let project = workspace.project().clone();
4465 let editor = cx
4466 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4467 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4468 editor.update(cx, |editor, cx| {
4469 editor.highlight_background::<Self>(
4470 &ranges_to_highlight,
4471 |theme| theme.editor_highlighted_line_background,
4472 cx,
4473 );
4474 });
4475 })?;
4476
4477 Ok(())
4478 }
4479
4480 pub fn clear_code_action_providers(&mut self) {
4481 self.code_action_providers.clear();
4482 self.available_code_actions.take();
4483 }
4484
4485 pub fn add_code_action_provider(
4486 &mut self,
4487 provider: Rc<dyn CodeActionProvider>,
4488 window: &mut Window,
4489 cx: &mut Context<Self>,
4490 ) {
4491 if self
4492 .code_action_providers
4493 .iter()
4494 .any(|existing_provider| existing_provider.id() == provider.id())
4495 {
4496 return;
4497 }
4498
4499 self.code_action_providers.push(provider);
4500 self.refresh_code_actions(window, cx);
4501 }
4502
4503 pub fn remove_code_action_provider(
4504 &mut self,
4505 id: Arc<str>,
4506 window: &mut Window,
4507 cx: &mut Context<Self>,
4508 ) {
4509 self.code_action_providers
4510 .retain(|provider| provider.id() != id);
4511 self.refresh_code_actions(window, cx);
4512 }
4513
4514 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4515 let buffer = self.buffer.read(cx);
4516 let newest_selection = self.selections.newest_anchor().clone();
4517 if newest_selection.head().diff_base_anchor.is_some() {
4518 return None;
4519 }
4520 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4521 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4522 if start_buffer != end_buffer {
4523 return None;
4524 }
4525
4526 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4527 cx.background_executor()
4528 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4529 .await;
4530
4531 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4532 let providers = this.code_action_providers.clone();
4533 let tasks = this
4534 .code_action_providers
4535 .iter()
4536 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4537 .collect::<Vec<_>>();
4538 (providers, tasks)
4539 })?;
4540
4541 let mut actions = Vec::new();
4542 for (provider, provider_actions) in
4543 providers.into_iter().zip(future::join_all(tasks).await)
4544 {
4545 if let Some(provider_actions) = provider_actions.log_err() {
4546 actions.extend(provider_actions.into_iter().map(|action| {
4547 AvailableCodeAction {
4548 excerpt_id: newest_selection.start.excerpt_id,
4549 action,
4550 provider: provider.clone(),
4551 }
4552 }));
4553 }
4554 }
4555
4556 this.update(&mut cx, |this, cx| {
4557 this.available_code_actions = if actions.is_empty() {
4558 None
4559 } else {
4560 Some((
4561 Location {
4562 buffer: start_buffer,
4563 range: start..end,
4564 },
4565 actions.into(),
4566 ))
4567 };
4568 cx.notify();
4569 })
4570 }));
4571 None
4572 }
4573
4574 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4575 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4576 self.show_git_blame_inline = false;
4577
4578 self.show_git_blame_inline_delay_task =
4579 Some(cx.spawn_in(window, |this, mut cx| async move {
4580 cx.background_executor().timer(delay).await;
4581
4582 this.update(&mut cx, |this, cx| {
4583 this.show_git_blame_inline = true;
4584 cx.notify();
4585 })
4586 .log_err();
4587 }));
4588 }
4589 }
4590
4591 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4592 if self.pending_rename.is_some() {
4593 return None;
4594 }
4595
4596 let provider = self.semantics_provider.clone()?;
4597 let buffer = self.buffer.read(cx);
4598 let newest_selection = self.selections.newest_anchor().clone();
4599 let cursor_position = newest_selection.head();
4600 let (cursor_buffer, cursor_buffer_position) =
4601 buffer.text_anchor_for_position(cursor_position, cx)?;
4602 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4603 if cursor_buffer != tail_buffer {
4604 return None;
4605 }
4606 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4607 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4608 cx.background_executor()
4609 .timer(Duration::from_millis(debounce))
4610 .await;
4611
4612 let highlights = if let Some(highlights) = cx
4613 .update(|cx| {
4614 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4615 })
4616 .ok()
4617 .flatten()
4618 {
4619 highlights.await.log_err()
4620 } else {
4621 None
4622 };
4623
4624 if let Some(highlights) = highlights {
4625 this.update(&mut cx, |this, cx| {
4626 if this.pending_rename.is_some() {
4627 return;
4628 }
4629
4630 let buffer_id = cursor_position.buffer_id;
4631 let buffer = this.buffer.read(cx);
4632 if !buffer
4633 .text_anchor_for_position(cursor_position, cx)
4634 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4635 {
4636 return;
4637 }
4638
4639 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4640 let mut write_ranges = Vec::new();
4641 let mut read_ranges = Vec::new();
4642 for highlight in highlights {
4643 for (excerpt_id, excerpt_range) in
4644 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4645 {
4646 let start = highlight
4647 .range
4648 .start
4649 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4650 let end = highlight
4651 .range
4652 .end
4653 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4654 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4655 continue;
4656 }
4657
4658 let range = Anchor {
4659 buffer_id,
4660 excerpt_id,
4661 text_anchor: start,
4662 diff_base_anchor: None,
4663 }..Anchor {
4664 buffer_id,
4665 excerpt_id,
4666 text_anchor: end,
4667 diff_base_anchor: None,
4668 };
4669 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4670 write_ranges.push(range);
4671 } else {
4672 read_ranges.push(range);
4673 }
4674 }
4675 }
4676
4677 this.highlight_background::<DocumentHighlightRead>(
4678 &read_ranges,
4679 |theme| theme.editor_document_highlight_read_background,
4680 cx,
4681 );
4682 this.highlight_background::<DocumentHighlightWrite>(
4683 &write_ranges,
4684 |theme| theme.editor_document_highlight_write_background,
4685 cx,
4686 );
4687 cx.notify();
4688 })
4689 .log_err();
4690 }
4691 }));
4692 None
4693 }
4694
4695 pub fn refresh_selected_text_highlights(
4696 &mut self,
4697 window: &mut Window,
4698 cx: &mut Context<Editor>,
4699 ) {
4700 self.selection_highlight_task.take();
4701 if !EditorSettings::get_global(cx).selection_highlight {
4702 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4703 return;
4704 }
4705 if self.selections.count() != 1 || self.selections.line_mode {
4706 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4707 return;
4708 }
4709 let selection = self.selections.newest::<Point>(cx);
4710 if selection.is_empty() || selection.start.row != selection.end.row {
4711 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4712 return;
4713 }
4714 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4715 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4716 cx.background_executor()
4717 .timer(Duration::from_millis(debounce))
4718 .await;
4719 let Some(Some(matches_task)) = editor
4720 .update_in(&mut cx, |editor, _, cx| {
4721 if editor.selections.count() != 1 || editor.selections.line_mode {
4722 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4723 return None;
4724 }
4725 let selection = editor.selections.newest::<Point>(cx);
4726 if selection.is_empty() || selection.start.row != selection.end.row {
4727 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4728 return None;
4729 }
4730 let buffer = editor.buffer().read(cx).snapshot(cx);
4731 let query = buffer.text_for_range(selection.range()).collect::<String>();
4732 if query.trim().is_empty() {
4733 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4734 return None;
4735 }
4736 Some(cx.background_spawn(async move {
4737 let mut ranges = Vec::new();
4738 let selection_anchors = selection.range().to_anchors(&buffer);
4739 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4740 for (search_buffer, search_range, excerpt_id) in
4741 buffer.range_to_buffer_ranges(range)
4742 {
4743 ranges.extend(
4744 project::search::SearchQuery::text(
4745 query.clone(),
4746 false,
4747 false,
4748 false,
4749 Default::default(),
4750 Default::default(),
4751 None,
4752 )
4753 .unwrap()
4754 .search(search_buffer, Some(search_range.clone()))
4755 .await
4756 .into_iter()
4757 .filter_map(
4758 |match_range| {
4759 let start = search_buffer.anchor_after(
4760 search_range.start + match_range.start,
4761 );
4762 let end = search_buffer.anchor_before(
4763 search_range.start + match_range.end,
4764 );
4765 let range = Anchor::range_in_buffer(
4766 excerpt_id,
4767 search_buffer.remote_id(),
4768 start..end,
4769 );
4770 (range != selection_anchors).then_some(range)
4771 },
4772 ),
4773 );
4774 }
4775 }
4776 ranges
4777 }))
4778 })
4779 .log_err()
4780 else {
4781 return;
4782 };
4783 let matches = matches_task.await;
4784 editor
4785 .update_in(&mut cx, |editor, _, cx| {
4786 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4787 if !matches.is_empty() {
4788 editor.highlight_background::<SelectedTextHighlight>(
4789 &matches,
4790 |theme| theme.editor_document_highlight_bracket_background,
4791 cx,
4792 )
4793 }
4794 })
4795 .log_err();
4796 }));
4797 }
4798
4799 pub fn refresh_inline_completion(
4800 &mut self,
4801 debounce: bool,
4802 user_requested: bool,
4803 window: &mut Window,
4804 cx: &mut Context<Self>,
4805 ) -> Option<()> {
4806 let provider = self.edit_prediction_provider()?;
4807 let cursor = self.selections.newest_anchor().head();
4808 let (buffer, cursor_buffer_position) =
4809 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4810
4811 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4812 self.discard_inline_completion(false, cx);
4813 return None;
4814 }
4815
4816 if !user_requested
4817 && (!self.should_show_edit_predictions()
4818 || !self.is_focused(window)
4819 || buffer.read(cx).is_empty())
4820 {
4821 self.discard_inline_completion(false, cx);
4822 return None;
4823 }
4824
4825 self.update_visible_inline_completion(window, cx);
4826 provider.refresh(
4827 self.project.clone(),
4828 buffer,
4829 cursor_buffer_position,
4830 debounce,
4831 cx,
4832 );
4833 Some(())
4834 }
4835
4836 fn show_edit_predictions_in_menu(&self) -> bool {
4837 match self.edit_prediction_settings {
4838 EditPredictionSettings::Disabled => false,
4839 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4840 }
4841 }
4842
4843 pub fn edit_predictions_enabled(&self) -> bool {
4844 match self.edit_prediction_settings {
4845 EditPredictionSettings::Disabled => false,
4846 EditPredictionSettings::Enabled { .. } => true,
4847 }
4848 }
4849
4850 fn edit_prediction_requires_modifier(&self) -> bool {
4851 match self.edit_prediction_settings {
4852 EditPredictionSettings::Disabled => false,
4853 EditPredictionSettings::Enabled {
4854 preview_requires_modifier,
4855 ..
4856 } => preview_requires_modifier,
4857 }
4858 }
4859
4860 fn edit_prediction_settings_at_position(
4861 &self,
4862 buffer: &Entity<Buffer>,
4863 buffer_position: language::Anchor,
4864 cx: &App,
4865 ) -> EditPredictionSettings {
4866 if self.mode != EditorMode::Full
4867 || !self.show_inline_completions_override.unwrap_or(true)
4868 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4869 {
4870 return EditPredictionSettings::Disabled;
4871 }
4872
4873 let buffer = buffer.read(cx);
4874
4875 let file = buffer.file();
4876
4877 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4878 return EditPredictionSettings::Disabled;
4879 };
4880
4881 let by_provider = matches!(
4882 self.menu_inline_completions_policy,
4883 MenuInlineCompletionsPolicy::ByProvider
4884 );
4885
4886 let show_in_menu = by_provider
4887 && self
4888 .edit_prediction_provider
4889 .as_ref()
4890 .map_or(false, |provider| {
4891 provider.provider.show_completions_in_menu()
4892 });
4893
4894 let preview_requires_modifier =
4895 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4896
4897 EditPredictionSettings::Enabled {
4898 show_in_menu,
4899 preview_requires_modifier,
4900 }
4901 }
4902
4903 fn should_show_edit_predictions(&self) -> bool {
4904 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4905 }
4906
4907 pub fn edit_prediction_preview_is_active(&self) -> bool {
4908 matches!(
4909 self.edit_prediction_preview,
4910 EditPredictionPreview::Active { .. }
4911 )
4912 }
4913
4914 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4915 let cursor = self.selections.newest_anchor().head();
4916 if let Some((buffer, cursor_position)) =
4917 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4918 {
4919 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4920 } else {
4921 false
4922 }
4923 }
4924
4925 fn inline_completions_enabled_in_buffer(
4926 &self,
4927 buffer: &Entity<Buffer>,
4928 buffer_position: language::Anchor,
4929 cx: &App,
4930 ) -> bool {
4931 maybe!({
4932 let provider = self.edit_prediction_provider()?;
4933 if !provider.is_enabled(&buffer, buffer_position, cx) {
4934 return Some(false);
4935 }
4936 let buffer = buffer.read(cx);
4937 let Some(file) = buffer.file() else {
4938 return Some(true);
4939 };
4940 let settings = all_language_settings(Some(file), cx);
4941 Some(settings.inline_completions_enabled_for_path(file.path()))
4942 })
4943 .unwrap_or(false)
4944 }
4945
4946 fn cycle_inline_completion(
4947 &mut self,
4948 direction: Direction,
4949 window: &mut Window,
4950 cx: &mut Context<Self>,
4951 ) -> Option<()> {
4952 let provider = self.edit_prediction_provider()?;
4953 let cursor = self.selections.newest_anchor().head();
4954 let (buffer, cursor_buffer_position) =
4955 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4956 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4957 return None;
4958 }
4959
4960 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4961 self.update_visible_inline_completion(window, cx);
4962
4963 Some(())
4964 }
4965
4966 pub fn show_inline_completion(
4967 &mut self,
4968 _: &ShowEditPrediction,
4969 window: &mut Window,
4970 cx: &mut Context<Self>,
4971 ) {
4972 if !self.has_active_inline_completion() {
4973 self.refresh_inline_completion(false, true, window, cx);
4974 return;
4975 }
4976
4977 self.update_visible_inline_completion(window, cx);
4978 }
4979
4980 pub fn display_cursor_names(
4981 &mut self,
4982 _: &DisplayCursorNames,
4983 window: &mut Window,
4984 cx: &mut Context<Self>,
4985 ) {
4986 self.show_cursor_names(window, cx);
4987 }
4988
4989 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4990 self.show_cursor_names = true;
4991 cx.notify();
4992 cx.spawn_in(window, |this, mut cx| async move {
4993 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4994 this.update(&mut cx, |this, cx| {
4995 this.show_cursor_names = false;
4996 cx.notify()
4997 })
4998 .ok()
4999 })
5000 .detach();
5001 }
5002
5003 pub fn next_edit_prediction(
5004 &mut self,
5005 _: &NextEditPrediction,
5006 window: &mut Window,
5007 cx: &mut Context<Self>,
5008 ) {
5009 if self.has_active_inline_completion() {
5010 self.cycle_inline_completion(Direction::Next, window, cx);
5011 } else {
5012 let is_copilot_disabled = self
5013 .refresh_inline_completion(false, true, window, cx)
5014 .is_none();
5015 if is_copilot_disabled {
5016 cx.propagate();
5017 }
5018 }
5019 }
5020
5021 pub fn previous_edit_prediction(
5022 &mut self,
5023 _: &PreviousEditPrediction,
5024 window: &mut Window,
5025 cx: &mut Context<Self>,
5026 ) {
5027 if self.has_active_inline_completion() {
5028 self.cycle_inline_completion(Direction::Prev, window, cx);
5029 } else {
5030 let is_copilot_disabled = self
5031 .refresh_inline_completion(false, true, window, cx)
5032 .is_none();
5033 if is_copilot_disabled {
5034 cx.propagate();
5035 }
5036 }
5037 }
5038
5039 pub fn accept_edit_prediction(
5040 &mut self,
5041 _: &AcceptEditPrediction,
5042 window: &mut Window,
5043 cx: &mut Context<Self>,
5044 ) {
5045 if self.show_edit_predictions_in_menu() {
5046 self.hide_context_menu(window, cx);
5047 }
5048
5049 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5050 return;
5051 };
5052
5053 self.report_inline_completion_event(
5054 active_inline_completion.completion_id.clone(),
5055 true,
5056 cx,
5057 );
5058
5059 match &active_inline_completion.completion {
5060 InlineCompletion::Move { target, .. } => {
5061 let target = *target;
5062
5063 if let Some(position_map) = &self.last_position_map {
5064 if position_map
5065 .visible_row_range
5066 .contains(&target.to_display_point(&position_map.snapshot).row())
5067 || !self.edit_prediction_requires_modifier()
5068 {
5069 self.unfold_ranges(&[target..target], true, false, cx);
5070 // Note that this is also done in vim's handler of the Tab action.
5071 self.change_selections(
5072 Some(Autoscroll::newest()),
5073 window,
5074 cx,
5075 |selections| {
5076 selections.select_anchor_ranges([target..target]);
5077 },
5078 );
5079 self.clear_row_highlights::<EditPredictionPreview>();
5080
5081 self.edit_prediction_preview = EditPredictionPreview::Active {
5082 previous_scroll_position: None,
5083 };
5084 } else {
5085 self.edit_prediction_preview = EditPredictionPreview::Active {
5086 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5087 };
5088 self.highlight_rows::<EditPredictionPreview>(
5089 target..target,
5090 cx.theme().colors().editor_highlighted_line_background,
5091 true,
5092 cx,
5093 );
5094 self.request_autoscroll(Autoscroll::fit(), cx);
5095 }
5096 }
5097 }
5098 InlineCompletion::Edit { edits, .. } => {
5099 if let Some(provider) = self.edit_prediction_provider() {
5100 provider.accept(cx);
5101 }
5102
5103 let snapshot = self.buffer.read(cx).snapshot(cx);
5104 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5105
5106 self.buffer.update(cx, |buffer, cx| {
5107 buffer.edit(edits.iter().cloned(), None, cx)
5108 });
5109
5110 self.change_selections(None, window, cx, |s| {
5111 s.select_anchor_ranges([last_edit_end..last_edit_end])
5112 });
5113
5114 self.update_visible_inline_completion(window, cx);
5115 if self.active_inline_completion.is_none() {
5116 self.refresh_inline_completion(true, true, window, cx);
5117 }
5118
5119 cx.notify();
5120 }
5121 }
5122
5123 self.edit_prediction_requires_modifier_in_leading_space = false;
5124 }
5125
5126 pub fn accept_partial_inline_completion(
5127 &mut self,
5128 _: &AcceptPartialEditPrediction,
5129 window: &mut Window,
5130 cx: &mut Context<Self>,
5131 ) {
5132 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5133 return;
5134 };
5135 if self.selections.count() != 1 {
5136 return;
5137 }
5138
5139 self.report_inline_completion_event(
5140 active_inline_completion.completion_id.clone(),
5141 true,
5142 cx,
5143 );
5144
5145 match &active_inline_completion.completion {
5146 InlineCompletion::Move { target, .. } => {
5147 let target = *target;
5148 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5149 selections.select_anchor_ranges([target..target]);
5150 });
5151 }
5152 InlineCompletion::Edit { edits, .. } => {
5153 // Find an insertion that starts at the cursor position.
5154 let snapshot = self.buffer.read(cx).snapshot(cx);
5155 let cursor_offset = self.selections.newest::<usize>(cx).head();
5156 let insertion = edits.iter().find_map(|(range, text)| {
5157 let range = range.to_offset(&snapshot);
5158 if range.is_empty() && range.start == cursor_offset {
5159 Some(text)
5160 } else {
5161 None
5162 }
5163 });
5164
5165 if let Some(text) = insertion {
5166 let mut partial_completion = text
5167 .chars()
5168 .by_ref()
5169 .take_while(|c| c.is_alphabetic())
5170 .collect::<String>();
5171 if partial_completion.is_empty() {
5172 partial_completion = text
5173 .chars()
5174 .by_ref()
5175 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5176 .collect::<String>();
5177 }
5178
5179 cx.emit(EditorEvent::InputHandled {
5180 utf16_range_to_replace: None,
5181 text: partial_completion.clone().into(),
5182 });
5183
5184 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5185
5186 self.refresh_inline_completion(true, true, window, cx);
5187 cx.notify();
5188 } else {
5189 self.accept_edit_prediction(&Default::default(), window, cx);
5190 }
5191 }
5192 }
5193 }
5194
5195 fn discard_inline_completion(
5196 &mut self,
5197 should_report_inline_completion_event: bool,
5198 cx: &mut Context<Self>,
5199 ) -> bool {
5200 if should_report_inline_completion_event {
5201 let completion_id = self
5202 .active_inline_completion
5203 .as_ref()
5204 .and_then(|active_completion| active_completion.completion_id.clone());
5205
5206 self.report_inline_completion_event(completion_id, false, cx);
5207 }
5208
5209 if let Some(provider) = self.edit_prediction_provider() {
5210 provider.discard(cx);
5211 }
5212
5213 self.take_active_inline_completion(cx)
5214 }
5215
5216 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5217 let Some(provider) = self.edit_prediction_provider() else {
5218 return;
5219 };
5220
5221 let Some((_, buffer, _)) = self
5222 .buffer
5223 .read(cx)
5224 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5225 else {
5226 return;
5227 };
5228
5229 let extension = buffer
5230 .read(cx)
5231 .file()
5232 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5233
5234 let event_type = match accepted {
5235 true => "Edit Prediction Accepted",
5236 false => "Edit Prediction Discarded",
5237 };
5238 telemetry::event!(
5239 event_type,
5240 provider = provider.name(),
5241 prediction_id = id,
5242 suggestion_accepted = accepted,
5243 file_extension = extension,
5244 );
5245 }
5246
5247 pub fn has_active_inline_completion(&self) -> bool {
5248 self.active_inline_completion.is_some()
5249 }
5250
5251 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5252 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5253 return false;
5254 };
5255
5256 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5257 self.clear_highlights::<InlineCompletionHighlight>(cx);
5258 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5259 true
5260 }
5261
5262 /// Returns true when we're displaying the edit prediction popover below the cursor
5263 /// like we are not previewing and the LSP autocomplete menu is visible
5264 /// or we are in `when_holding_modifier` mode.
5265 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5266 if self.edit_prediction_preview_is_active()
5267 || !self.show_edit_predictions_in_menu()
5268 || !self.edit_predictions_enabled()
5269 {
5270 return false;
5271 }
5272
5273 if self.has_visible_completions_menu() {
5274 return true;
5275 }
5276
5277 has_completion && self.edit_prediction_requires_modifier()
5278 }
5279
5280 fn handle_modifiers_changed(
5281 &mut self,
5282 modifiers: Modifiers,
5283 position_map: &PositionMap,
5284 window: &mut Window,
5285 cx: &mut Context<Self>,
5286 ) {
5287 if self.show_edit_predictions_in_menu() {
5288 self.update_edit_prediction_preview(&modifiers, window, cx);
5289 }
5290
5291 self.update_selection_mode(&modifiers, position_map, window, cx);
5292
5293 let mouse_position = window.mouse_position();
5294 if !position_map.text_hitbox.is_hovered(window) {
5295 return;
5296 }
5297
5298 self.update_hovered_link(
5299 position_map.point_for_position(mouse_position),
5300 &position_map.snapshot,
5301 modifiers,
5302 window,
5303 cx,
5304 )
5305 }
5306
5307 fn update_selection_mode(
5308 &mut self,
5309 modifiers: &Modifiers,
5310 position_map: &PositionMap,
5311 window: &mut Window,
5312 cx: &mut Context<Self>,
5313 ) {
5314 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5315 return;
5316 }
5317
5318 let mouse_position = window.mouse_position();
5319 let point_for_position = position_map.point_for_position(mouse_position);
5320 let position = point_for_position.previous_valid;
5321
5322 self.select(
5323 SelectPhase::BeginColumnar {
5324 position,
5325 reset: false,
5326 goal_column: point_for_position.exact_unclipped.column(),
5327 },
5328 window,
5329 cx,
5330 );
5331 }
5332
5333 fn update_edit_prediction_preview(
5334 &mut self,
5335 modifiers: &Modifiers,
5336 window: &mut Window,
5337 cx: &mut Context<Self>,
5338 ) {
5339 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5340 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5341 return;
5342 };
5343
5344 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5345 if matches!(
5346 self.edit_prediction_preview,
5347 EditPredictionPreview::Inactive
5348 ) {
5349 self.edit_prediction_preview = EditPredictionPreview::Active {
5350 previous_scroll_position: None,
5351 };
5352
5353 self.update_visible_inline_completion(window, cx);
5354 cx.notify();
5355 }
5356 } else if let EditPredictionPreview::Active {
5357 previous_scroll_position,
5358 } = self.edit_prediction_preview
5359 {
5360 if let (Some(previous_scroll_position), Some(position_map)) =
5361 (previous_scroll_position, self.last_position_map.as_ref())
5362 {
5363 self.set_scroll_position(
5364 previous_scroll_position
5365 .scroll_position(&position_map.snapshot.display_snapshot),
5366 window,
5367 cx,
5368 );
5369 }
5370
5371 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5372 self.clear_row_highlights::<EditPredictionPreview>();
5373 self.update_visible_inline_completion(window, cx);
5374 cx.notify();
5375 }
5376 }
5377
5378 fn update_visible_inline_completion(
5379 &mut self,
5380 _window: &mut Window,
5381 cx: &mut Context<Self>,
5382 ) -> Option<()> {
5383 let selection = self.selections.newest_anchor();
5384 let cursor = selection.head();
5385 let multibuffer = self.buffer.read(cx).snapshot(cx);
5386 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5387 let excerpt_id = cursor.excerpt_id;
5388
5389 let show_in_menu = self.show_edit_predictions_in_menu();
5390 let completions_menu_has_precedence = !show_in_menu
5391 && (self.context_menu.borrow().is_some()
5392 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5393
5394 if completions_menu_has_precedence
5395 || !offset_selection.is_empty()
5396 || self
5397 .active_inline_completion
5398 .as_ref()
5399 .map_or(false, |completion| {
5400 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5401 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5402 !invalidation_range.contains(&offset_selection.head())
5403 })
5404 {
5405 self.discard_inline_completion(false, cx);
5406 return None;
5407 }
5408
5409 self.take_active_inline_completion(cx);
5410 let Some(provider) = self.edit_prediction_provider() else {
5411 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5412 return None;
5413 };
5414
5415 let (buffer, cursor_buffer_position) =
5416 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5417
5418 self.edit_prediction_settings =
5419 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5420
5421 self.edit_prediction_cursor_on_leading_whitespace =
5422 multibuffer.is_line_whitespace_upto(cursor);
5423
5424 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5425 let edits = inline_completion
5426 .edits
5427 .into_iter()
5428 .flat_map(|(range, new_text)| {
5429 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5430 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5431 Some((start..end, new_text))
5432 })
5433 .collect::<Vec<_>>();
5434 if edits.is_empty() {
5435 return None;
5436 }
5437
5438 let first_edit_start = edits.first().unwrap().0.start;
5439 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5440 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5441
5442 let last_edit_end = edits.last().unwrap().0.end;
5443 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5444 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5445
5446 let cursor_row = cursor.to_point(&multibuffer).row;
5447
5448 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5449
5450 let mut inlay_ids = Vec::new();
5451 let invalidation_row_range;
5452 let move_invalidation_row_range = if cursor_row < edit_start_row {
5453 Some(cursor_row..edit_end_row)
5454 } else if cursor_row > edit_end_row {
5455 Some(edit_start_row..cursor_row)
5456 } else {
5457 None
5458 };
5459 let is_move =
5460 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5461 let completion = if is_move {
5462 invalidation_row_range =
5463 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5464 let target = first_edit_start;
5465 InlineCompletion::Move { target, snapshot }
5466 } else {
5467 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5468 && !self.inline_completions_hidden_for_vim_mode;
5469
5470 if show_completions_in_buffer {
5471 if edits
5472 .iter()
5473 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5474 {
5475 let mut inlays = Vec::new();
5476 for (range, new_text) in &edits {
5477 let inlay = Inlay::inline_completion(
5478 post_inc(&mut self.next_inlay_id),
5479 range.start,
5480 new_text.as_str(),
5481 );
5482 inlay_ids.push(inlay.id);
5483 inlays.push(inlay);
5484 }
5485
5486 self.splice_inlays(&[], inlays, cx);
5487 } else {
5488 let background_color = cx.theme().status().deleted_background;
5489 self.highlight_text::<InlineCompletionHighlight>(
5490 edits.iter().map(|(range, _)| range.clone()).collect(),
5491 HighlightStyle {
5492 background_color: Some(background_color),
5493 ..Default::default()
5494 },
5495 cx,
5496 );
5497 }
5498 }
5499
5500 invalidation_row_range = edit_start_row..edit_end_row;
5501
5502 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5503 if provider.show_tab_accept_marker() {
5504 EditDisplayMode::TabAccept
5505 } else {
5506 EditDisplayMode::Inline
5507 }
5508 } else {
5509 EditDisplayMode::DiffPopover
5510 };
5511
5512 InlineCompletion::Edit {
5513 edits,
5514 edit_preview: inline_completion.edit_preview,
5515 display_mode,
5516 snapshot,
5517 }
5518 };
5519
5520 let invalidation_range = multibuffer
5521 .anchor_before(Point::new(invalidation_row_range.start, 0))
5522 ..multibuffer.anchor_after(Point::new(
5523 invalidation_row_range.end,
5524 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5525 ));
5526
5527 self.stale_inline_completion_in_menu = None;
5528 self.active_inline_completion = Some(InlineCompletionState {
5529 inlay_ids,
5530 completion,
5531 completion_id: inline_completion.id,
5532 invalidation_range,
5533 });
5534
5535 cx.notify();
5536
5537 Some(())
5538 }
5539
5540 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5541 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5542 }
5543
5544 fn render_code_actions_indicator(
5545 &self,
5546 _style: &EditorStyle,
5547 row: DisplayRow,
5548 is_active: bool,
5549 cx: &mut Context<Self>,
5550 ) -> Option<IconButton> {
5551 if self.available_code_actions.is_some() {
5552 Some(
5553 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5554 .shape(ui::IconButtonShape::Square)
5555 .icon_size(IconSize::XSmall)
5556 .icon_color(Color::Muted)
5557 .toggle_state(is_active)
5558 .tooltip({
5559 let focus_handle = self.focus_handle.clone();
5560 move |window, cx| {
5561 Tooltip::for_action_in(
5562 "Toggle Code Actions",
5563 &ToggleCodeActions {
5564 deployed_from_indicator: None,
5565 },
5566 &focus_handle,
5567 window,
5568 cx,
5569 )
5570 }
5571 })
5572 .on_click(cx.listener(move |editor, _e, window, cx| {
5573 window.focus(&editor.focus_handle(cx));
5574 editor.toggle_code_actions(
5575 &ToggleCodeActions {
5576 deployed_from_indicator: Some(row),
5577 },
5578 window,
5579 cx,
5580 );
5581 })),
5582 )
5583 } else {
5584 None
5585 }
5586 }
5587
5588 fn clear_tasks(&mut self) {
5589 self.tasks.clear()
5590 }
5591
5592 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5593 if self.tasks.insert(key, value).is_some() {
5594 // This case should hopefully be rare, but just in case...
5595 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5596 }
5597 }
5598
5599 fn build_tasks_context(
5600 project: &Entity<Project>,
5601 buffer: &Entity<Buffer>,
5602 buffer_row: u32,
5603 tasks: &Arc<RunnableTasks>,
5604 cx: &mut Context<Self>,
5605 ) -> Task<Option<task::TaskContext>> {
5606 let position = Point::new(buffer_row, tasks.column);
5607 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5608 let location = Location {
5609 buffer: buffer.clone(),
5610 range: range_start..range_start,
5611 };
5612 // Fill in the environmental variables from the tree-sitter captures
5613 let mut captured_task_variables = TaskVariables::default();
5614 for (capture_name, value) in tasks.extra_variables.clone() {
5615 captured_task_variables.insert(
5616 task::VariableName::Custom(capture_name.into()),
5617 value.clone(),
5618 );
5619 }
5620 project.update(cx, |project, cx| {
5621 project.task_store().update(cx, |task_store, cx| {
5622 task_store.task_context_for_location(captured_task_variables, location, cx)
5623 })
5624 })
5625 }
5626
5627 pub fn spawn_nearest_task(
5628 &mut self,
5629 action: &SpawnNearestTask,
5630 window: &mut Window,
5631 cx: &mut Context<Self>,
5632 ) {
5633 let Some((workspace, _)) = self.workspace.clone() else {
5634 return;
5635 };
5636 let Some(project) = self.project.clone() else {
5637 return;
5638 };
5639
5640 // Try to find a closest, enclosing node using tree-sitter that has a
5641 // task
5642 let Some((buffer, buffer_row, tasks)) = self
5643 .find_enclosing_node_task(cx)
5644 // Or find the task that's closest in row-distance.
5645 .or_else(|| self.find_closest_task(cx))
5646 else {
5647 return;
5648 };
5649
5650 let reveal_strategy = action.reveal;
5651 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5652 cx.spawn_in(window, |_, mut cx| async move {
5653 let context = task_context.await?;
5654 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5655
5656 let resolved = resolved_task.resolved.as_mut()?;
5657 resolved.reveal = reveal_strategy;
5658
5659 workspace
5660 .update(&mut cx, |workspace, cx| {
5661 workspace::tasks::schedule_resolved_task(
5662 workspace,
5663 task_source_kind,
5664 resolved_task,
5665 false,
5666 cx,
5667 );
5668 })
5669 .ok()
5670 })
5671 .detach();
5672 }
5673
5674 fn find_closest_task(
5675 &mut self,
5676 cx: &mut Context<Self>,
5677 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5678 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5679
5680 let ((buffer_id, row), tasks) = self
5681 .tasks
5682 .iter()
5683 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5684
5685 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5686 let tasks = Arc::new(tasks.to_owned());
5687 Some((buffer, *row, tasks))
5688 }
5689
5690 fn find_enclosing_node_task(
5691 &mut self,
5692 cx: &mut Context<Self>,
5693 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5694 let snapshot = self.buffer.read(cx).snapshot(cx);
5695 let offset = self.selections.newest::<usize>(cx).head();
5696 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5697 let buffer_id = excerpt.buffer().remote_id();
5698
5699 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5700 let mut cursor = layer.node().walk();
5701
5702 while cursor.goto_first_child_for_byte(offset).is_some() {
5703 if cursor.node().end_byte() == offset {
5704 cursor.goto_next_sibling();
5705 }
5706 }
5707
5708 // Ascend to the smallest ancestor that contains the range and has a task.
5709 loop {
5710 let node = cursor.node();
5711 let node_range = node.byte_range();
5712 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5713
5714 // Check if this node contains our offset
5715 if node_range.start <= offset && node_range.end >= offset {
5716 // If it contains offset, check for task
5717 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5718 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5719 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5720 }
5721 }
5722
5723 if !cursor.goto_parent() {
5724 break;
5725 }
5726 }
5727 None
5728 }
5729
5730 fn render_run_indicator(
5731 &self,
5732 _style: &EditorStyle,
5733 is_active: bool,
5734 row: DisplayRow,
5735 cx: &mut Context<Self>,
5736 ) -> IconButton {
5737 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5738 .shape(ui::IconButtonShape::Square)
5739 .icon_size(IconSize::XSmall)
5740 .icon_color(Color::Muted)
5741 .toggle_state(is_active)
5742 .on_click(cx.listener(move |editor, _e, window, cx| {
5743 window.focus(&editor.focus_handle(cx));
5744 editor.toggle_code_actions(
5745 &ToggleCodeActions {
5746 deployed_from_indicator: Some(row),
5747 },
5748 window,
5749 cx,
5750 );
5751 }))
5752 }
5753
5754 pub fn context_menu_visible(&self) -> bool {
5755 !self.edit_prediction_preview_is_active()
5756 && self
5757 .context_menu
5758 .borrow()
5759 .as_ref()
5760 .map_or(false, |menu| menu.visible())
5761 }
5762
5763 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5764 self.context_menu
5765 .borrow()
5766 .as_ref()
5767 .map(|menu| menu.origin())
5768 }
5769
5770 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5771 px(30.)
5772 }
5773
5774 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5775 if self.read_only(cx) {
5776 cx.theme().players().read_only()
5777 } else {
5778 self.style.as_ref().unwrap().local_player
5779 }
5780 }
5781
5782 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5783 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5784 let accept_keystroke = accept_binding.keystroke()?;
5785
5786 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
5787
5788 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
5789 Color::Accent
5790 } else {
5791 Color::Muted
5792 };
5793
5794 h_flex()
5795 .px_0p5()
5796 .when(is_platform_style_mac, |parent| parent.gap_0p5())
5797 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5798 .text_size(TextSize::XSmall.rems(cx))
5799 .child(h_flex().children(ui::render_modifiers(
5800 &accept_keystroke.modifiers,
5801 PlatformStyle::platform(),
5802 Some(modifiers_color),
5803 Some(IconSize::XSmall.rems().into()),
5804 true,
5805 )))
5806 .when(is_platform_style_mac, |parent| {
5807 parent.child(accept_keystroke.key.clone())
5808 })
5809 .when(!is_platform_style_mac, |parent| {
5810 parent.child(
5811 Key::new(
5812 util::capitalize(&accept_keystroke.key),
5813 Some(Color::Default),
5814 )
5815 .size(Some(IconSize::XSmall.rems().into())),
5816 )
5817 })
5818 .into()
5819 }
5820
5821 fn render_edit_prediction_line_popover(
5822 &self,
5823 label: impl Into<SharedString>,
5824 icon: Option<IconName>,
5825 window: &mut Window,
5826 cx: &App,
5827 ) -> Option<Div> {
5828 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5829
5830 let result = h_flex()
5831 .py_0p5()
5832 .pl_1()
5833 .pr(padding_right)
5834 .gap_1()
5835 .rounded(px(6.))
5836 .border_1()
5837 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5838 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
5839 .shadow_sm()
5840 .children(self.render_edit_prediction_accept_keybind(window, cx))
5841 .child(Label::new(label).size(LabelSize::Small))
5842 .when_some(icon, |element, icon| {
5843 element.child(
5844 div()
5845 .mt(px(1.5))
5846 .child(Icon::new(icon).size(IconSize::Small)),
5847 )
5848 });
5849
5850 Some(result)
5851 }
5852
5853 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5854 let accent_color = cx.theme().colors().text_accent;
5855 let editor_bg_color = cx.theme().colors().editor_background;
5856 editor_bg_color.blend(accent_color.opacity(0.1))
5857 }
5858
5859 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
5860 let accent_color = cx.theme().colors().text_accent;
5861 let editor_bg_color = cx.theme().colors().editor_background;
5862 editor_bg_color.blend(accent_color.opacity(0.6))
5863 }
5864
5865 #[allow(clippy::too_many_arguments)]
5866 fn render_edit_prediction_cursor_popover(
5867 &self,
5868 min_width: Pixels,
5869 max_width: Pixels,
5870 cursor_point: Point,
5871 style: &EditorStyle,
5872 accept_keystroke: Option<&gpui::Keystroke>,
5873 _window: &Window,
5874 cx: &mut Context<Editor>,
5875 ) -> Option<AnyElement> {
5876 let provider = self.edit_prediction_provider.as_ref()?;
5877
5878 if provider.provider.needs_terms_acceptance(cx) {
5879 return Some(
5880 h_flex()
5881 .min_w(min_width)
5882 .flex_1()
5883 .px_2()
5884 .py_1()
5885 .gap_3()
5886 .elevation_2(cx)
5887 .hover(|style| style.bg(cx.theme().colors().element_hover))
5888 .id("accept-terms")
5889 .cursor_pointer()
5890 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5891 .on_click(cx.listener(|this, _event, window, cx| {
5892 cx.stop_propagation();
5893 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5894 window.dispatch_action(
5895 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5896 cx,
5897 );
5898 }))
5899 .child(
5900 h_flex()
5901 .flex_1()
5902 .gap_2()
5903 .child(Icon::new(IconName::ZedPredict))
5904 .child(Label::new("Accept Terms of Service"))
5905 .child(div().w_full())
5906 .child(
5907 Icon::new(IconName::ArrowUpRight)
5908 .color(Color::Muted)
5909 .size(IconSize::Small),
5910 )
5911 .into_any_element(),
5912 )
5913 .into_any(),
5914 );
5915 }
5916
5917 let is_refreshing = provider.provider.is_refreshing(cx);
5918
5919 fn pending_completion_container() -> Div {
5920 h_flex()
5921 .h_full()
5922 .flex_1()
5923 .gap_2()
5924 .child(Icon::new(IconName::ZedPredict))
5925 }
5926
5927 let completion = match &self.active_inline_completion {
5928 Some(completion) => match &completion.completion {
5929 InlineCompletion::Move {
5930 target, snapshot, ..
5931 } if !self.has_visible_completions_menu() => {
5932 use text::ToPoint as _;
5933
5934 return Some(
5935 h_flex()
5936 .px_2()
5937 .py_1()
5938 .gap_2()
5939 .elevation_2(cx)
5940 .border_color(cx.theme().colors().border)
5941 .rounded(px(6.))
5942 .rounded_tl(px(0.))
5943 .child(
5944 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5945 Icon::new(IconName::ZedPredictDown)
5946 } else {
5947 Icon::new(IconName::ZedPredictUp)
5948 },
5949 )
5950 .child(Label::new("Hold").size(LabelSize::Small))
5951 .child(h_flex().children(ui::render_modifiers(
5952 &accept_keystroke?.modifiers,
5953 PlatformStyle::platform(),
5954 Some(Color::Default),
5955 Some(IconSize::Small.rems().into()),
5956 false,
5957 )))
5958 .into_any(),
5959 );
5960 }
5961 _ => self.render_edit_prediction_cursor_popover_preview(
5962 completion,
5963 cursor_point,
5964 style,
5965 cx,
5966 )?,
5967 },
5968
5969 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5970 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5971 stale_completion,
5972 cursor_point,
5973 style,
5974 cx,
5975 )?,
5976
5977 None => {
5978 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5979 }
5980 },
5981
5982 None => pending_completion_container().child(Label::new("No Prediction")),
5983 };
5984
5985 let completion = if is_refreshing {
5986 completion
5987 .with_animation(
5988 "loading-completion",
5989 Animation::new(Duration::from_secs(2))
5990 .repeat()
5991 .with_easing(pulsating_between(0.4, 0.8)),
5992 |label, delta| label.opacity(delta),
5993 )
5994 .into_any_element()
5995 } else {
5996 completion.into_any_element()
5997 };
5998
5999 let has_completion = self.active_inline_completion.is_some();
6000
6001 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6002 Some(
6003 h_flex()
6004 .min_w(min_width)
6005 .max_w(max_width)
6006 .flex_1()
6007 .elevation_2(cx)
6008 .border_color(cx.theme().colors().border)
6009 .child(
6010 div()
6011 .flex_1()
6012 .py_1()
6013 .px_2()
6014 .overflow_hidden()
6015 .child(completion),
6016 )
6017 .when_some(accept_keystroke, |el, accept_keystroke| {
6018 if !accept_keystroke.modifiers.modified() {
6019 return el;
6020 }
6021
6022 el.child(
6023 h_flex()
6024 .h_full()
6025 .border_l_1()
6026 .rounded_r_lg()
6027 .border_color(cx.theme().colors().border)
6028 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6029 .gap_1()
6030 .py_1()
6031 .px_2()
6032 .child(
6033 h_flex()
6034 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6035 .when(is_platform_style_mac, |parent| parent.gap_1())
6036 .child(h_flex().children(ui::render_modifiers(
6037 &accept_keystroke.modifiers,
6038 PlatformStyle::platform(),
6039 Some(if !has_completion {
6040 Color::Muted
6041 } else {
6042 Color::Default
6043 }),
6044 None,
6045 false,
6046 ))),
6047 )
6048 .child(Label::new("Preview").into_any_element())
6049 .opacity(if has_completion { 1.0 } else { 0.4 }),
6050 )
6051 })
6052 .into_any(),
6053 )
6054 }
6055
6056 fn render_edit_prediction_cursor_popover_preview(
6057 &self,
6058 completion: &InlineCompletionState,
6059 cursor_point: Point,
6060 style: &EditorStyle,
6061 cx: &mut Context<Editor>,
6062 ) -> Option<Div> {
6063 use text::ToPoint as _;
6064
6065 fn render_relative_row_jump(
6066 prefix: impl Into<String>,
6067 current_row: u32,
6068 target_row: u32,
6069 ) -> Div {
6070 let (row_diff, arrow) = if target_row < current_row {
6071 (current_row - target_row, IconName::ArrowUp)
6072 } else {
6073 (target_row - current_row, IconName::ArrowDown)
6074 };
6075
6076 h_flex()
6077 .child(
6078 Label::new(format!("{}{}", prefix.into(), row_diff))
6079 .color(Color::Muted)
6080 .size(LabelSize::Small),
6081 )
6082 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6083 }
6084
6085 match &completion.completion {
6086 InlineCompletion::Move {
6087 target, snapshot, ..
6088 } => Some(
6089 h_flex()
6090 .px_2()
6091 .gap_2()
6092 .flex_1()
6093 .child(
6094 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6095 Icon::new(IconName::ZedPredictDown)
6096 } else {
6097 Icon::new(IconName::ZedPredictUp)
6098 },
6099 )
6100 .child(Label::new("Jump to Edit")),
6101 ),
6102
6103 InlineCompletion::Edit {
6104 edits,
6105 edit_preview,
6106 snapshot,
6107 display_mode: _,
6108 } => {
6109 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6110
6111 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6112 &snapshot,
6113 &edits,
6114 edit_preview.as_ref()?,
6115 true,
6116 cx,
6117 )
6118 .first_line_preview();
6119
6120 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6121 .with_highlights(&style.text, highlighted_edits.highlights);
6122
6123 let preview = h_flex()
6124 .gap_1()
6125 .min_w_16()
6126 .child(styled_text)
6127 .when(has_more_lines, |parent| parent.child("…"));
6128
6129 let left = if first_edit_row != cursor_point.row {
6130 render_relative_row_jump("", cursor_point.row, first_edit_row)
6131 .into_any_element()
6132 } else {
6133 Icon::new(IconName::ZedPredict).into_any_element()
6134 };
6135
6136 Some(
6137 h_flex()
6138 .h_full()
6139 .flex_1()
6140 .gap_2()
6141 .pr_1()
6142 .overflow_x_hidden()
6143 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6144 .child(left)
6145 .child(preview),
6146 )
6147 }
6148 }
6149 }
6150
6151 fn render_context_menu(
6152 &self,
6153 style: &EditorStyle,
6154 max_height_in_lines: u32,
6155 y_flipped: bool,
6156 window: &mut Window,
6157 cx: &mut Context<Editor>,
6158 ) -> Option<AnyElement> {
6159 let menu = self.context_menu.borrow();
6160 let menu = menu.as_ref()?;
6161 if !menu.visible() {
6162 return None;
6163 };
6164 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6165 }
6166
6167 fn render_context_menu_aside(
6168 &mut self,
6169 max_size: Size<Pixels>,
6170 window: &mut Window,
6171 cx: &mut Context<Editor>,
6172 ) -> Option<AnyElement> {
6173 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6174 if menu.visible() {
6175 menu.render_aside(self, max_size, window, cx)
6176 } else {
6177 None
6178 }
6179 })
6180 }
6181
6182 fn hide_context_menu(
6183 &mut self,
6184 window: &mut Window,
6185 cx: &mut Context<Self>,
6186 ) -> Option<CodeContextMenu> {
6187 cx.notify();
6188 self.completion_tasks.clear();
6189 let context_menu = self.context_menu.borrow_mut().take();
6190 self.stale_inline_completion_in_menu.take();
6191 self.update_visible_inline_completion(window, cx);
6192 context_menu
6193 }
6194
6195 fn show_snippet_choices(
6196 &mut self,
6197 choices: &Vec<String>,
6198 selection: Range<Anchor>,
6199 cx: &mut Context<Self>,
6200 ) {
6201 if selection.start.buffer_id.is_none() {
6202 return;
6203 }
6204 let buffer_id = selection.start.buffer_id.unwrap();
6205 let buffer = self.buffer().read(cx).buffer(buffer_id);
6206 let id = post_inc(&mut self.next_completion_id);
6207
6208 if let Some(buffer) = buffer {
6209 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6210 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6211 ));
6212 }
6213 }
6214
6215 pub fn insert_snippet(
6216 &mut self,
6217 insertion_ranges: &[Range<usize>],
6218 snippet: Snippet,
6219 window: &mut Window,
6220 cx: &mut Context<Self>,
6221 ) -> Result<()> {
6222 struct Tabstop<T> {
6223 is_end_tabstop: bool,
6224 ranges: Vec<Range<T>>,
6225 choices: Option<Vec<String>>,
6226 }
6227
6228 let tabstops = self.buffer.update(cx, |buffer, cx| {
6229 let snippet_text: Arc<str> = snippet.text.clone().into();
6230 buffer.edit(
6231 insertion_ranges
6232 .iter()
6233 .cloned()
6234 .map(|range| (range, snippet_text.clone())),
6235 Some(AutoindentMode::EachLine),
6236 cx,
6237 );
6238
6239 let snapshot = &*buffer.read(cx);
6240 let snippet = &snippet;
6241 snippet
6242 .tabstops
6243 .iter()
6244 .map(|tabstop| {
6245 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6246 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6247 });
6248 let mut tabstop_ranges = tabstop
6249 .ranges
6250 .iter()
6251 .flat_map(|tabstop_range| {
6252 let mut delta = 0_isize;
6253 insertion_ranges.iter().map(move |insertion_range| {
6254 let insertion_start = insertion_range.start as isize + delta;
6255 delta +=
6256 snippet.text.len() as isize - insertion_range.len() as isize;
6257
6258 let start = ((insertion_start + tabstop_range.start) as usize)
6259 .min(snapshot.len());
6260 let end = ((insertion_start + tabstop_range.end) as usize)
6261 .min(snapshot.len());
6262 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6263 })
6264 })
6265 .collect::<Vec<_>>();
6266 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6267
6268 Tabstop {
6269 is_end_tabstop,
6270 ranges: tabstop_ranges,
6271 choices: tabstop.choices.clone(),
6272 }
6273 })
6274 .collect::<Vec<_>>()
6275 });
6276 if let Some(tabstop) = tabstops.first() {
6277 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6278 s.select_ranges(tabstop.ranges.iter().cloned());
6279 });
6280
6281 if let Some(choices) = &tabstop.choices {
6282 if let Some(selection) = tabstop.ranges.first() {
6283 self.show_snippet_choices(choices, selection.clone(), cx)
6284 }
6285 }
6286
6287 // If we're already at the last tabstop and it's at the end of the snippet,
6288 // we're done, we don't need to keep the state around.
6289 if !tabstop.is_end_tabstop {
6290 let choices = tabstops
6291 .iter()
6292 .map(|tabstop| tabstop.choices.clone())
6293 .collect();
6294
6295 let ranges = tabstops
6296 .into_iter()
6297 .map(|tabstop| tabstop.ranges)
6298 .collect::<Vec<_>>();
6299
6300 self.snippet_stack.push(SnippetState {
6301 active_index: 0,
6302 ranges,
6303 choices,
6304 });
6305 }
6306
6307 // Check whether the just-entered snippet ends with an auto-closable bracket.
6308 if self.autoclose_regions.is_empty() {
6309 let snapshot = self.buffer.read(cx).snapshot(cx);
6310 for selection in &mut self.selections.all::<Point>(cx) {
6311 let selection_head = selection.head();
6312 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6313 continue;
6314 };
6315
6316 let mut bracket_pair = None;
6317 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6318 let prev_chars = snapshot
6319 .reversed_chars_at(selection_head)
6320 .collect::<String>();
6321 for (pair, enabled) in scope.brackets() {
6322 if enabled
6323 && pair.close
6324 && prev_chars.starts_with(pair.start.as_str())
6325 && next_chars.starts_with(pair.end.as_str())
6326 {
6327 bracket_pair = Some(pair.clone());
6328 break;
6329 }
6330 }
6331 if let Some(pair) = bracket_pair {
6332 let start = snapshot.anchor_after(selection_head);
6333 let end = snapshot.anchor_after(selection_head);
6334 self.autoclose_regions.push(AutocloseRegion {
6335 selection_id: selection.id,
6336 range: start..end,
6337 pair,
6338 });
6339 }
6340 }
6341 }
6342 }
6343 Ok(())
6344 }
6345
6346 pub fn move_to_next_snippet_tabstop(
6347 &mut self,
6348 window: &mut Window,
6349 cx: &mut Context<Self>,
6350 ) -> bool {
6351 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6352 }
6353
6354 pub fn move_to_prev_snippet_tabstop(
6355 &mut self,
6356 window: &mut Window,
6357 cx: &mut Context<Self>,
6358 ) -> bool {
6359 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6360 }
6361
6362 pub fn move_to_snippet_tabstop(
6363 &mut self,
6364 bias: Bias,
6365 window: &mut Window,
6366 cx: &mut Context<Self>,
6367 ) -> bool {
6368 if let Some(mut snippet) = self.snippet_stack.pop() {
6369 match bias {
6370 Bias::Left => {
6371 if snippet.active_index > 0 {
6372 snippet.active_index -= 1;
6373 } else {
6374 self.snippet_stack.push(snippet);
6375 return false;
6376 }
6377 }
6378 Bias::Right => {
6379 if snippet.active_index + 1 < snippet.ranges.len() {
6380 snippet.active_index += 1;
6381 } else {
6382 self.snippet_stack.push(snippet);
6383 return false;
6384 }
6385 }
6386 }
6387 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6388 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6389 s.select_anchor_ranges(current_ranges.iter().cloned())
6390 });
6391
6392 if let Some(choices) = &snippet.choices[snippet.active_index] {
6393 if let Some(selection) = current_ranges.first() {
6394 self.show_snippet_choices(&choices, selection.clone(), cx);
6395 }
6396 }
6397
6398 // If snippet state is not at the last tabstop, push it back on the stack
6399 if snippet.active_index + 1 < snippet.ranges.len() {
6400 self.snippet_stack.push(snippet);
6401 }
6402 return true;
6403 }
6404 }
6405
6406 false
6407 }
6408
6409 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6410 self.transact(window, cx, |this, window, cx| {
6411 this.select_all(&SelectAll, window, cx);
6412 this.insert("", window, cx);
6413 });
6414 }
6415
6416 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6417 self.transact(window, cx, |this, window, cx| {
6418 this.select_autoclose_pair(window, cx);
6419 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6420 if !this.linked_edit_ranges.is_empty() {
6421 let selections = this.selections.all::<MultiBufferPoint>(cx);
6422 let snapshot = this.buffer.read(cx).snapshot(cx);
6423
6424 for selection in selections.iter() {
6425 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6426 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6427 if selection_start.buffer_id != selection_end.buffer_id {
6428 continue;
6429 }
6430 if let Some(ranges) =
6431 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6432 {
6433 for (buffer, entries) in ranges {
6434 linked_ranges.entry(buffer).or_default().extend(entries);
6435 }
6436 }
6437 }
6438 }
6439
6440 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6441 if !this.selections.line_mode {
6442 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6443 for selection in &mut selections {
6444 if selection.is_empty() {
6445 let old_head = selection.head();
6446 let mut new_head =
6447 movement::left(&display_map, old_head.to_display_point(&display_map))
6448 .to_point(&display_map);
6449 if let Some((buffer, line_buffer_range)) = display_map
6450 .buffer_snapshot
6451 .buffer_line_for_row(MultiBufferRow(old_head.row))
6452 {
6453 let indent_size =
6454 buffer.indent_size_for_line(line_buffer_range.start.row);
6455 let indent_len = match indent_size.kind {
6456 IndentKind::Space => {
6457 buffer.settings_at(line_buffer_range.start, cx).tab_size
6458 }
6459 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6460 };
6461 if old_head.column <= indent_size.len && old_head.column > 0 {
6462 let indent_len = indent_len.get();
6463 new_head = cmp::min(
6464 new_head,
6465 MultiBufferPoint::new(
6466 old_head.row,
6467 ((old_head.column - 1) / indent_len) * indent_len,
6468 ),
6469 );
6470 }
6471 }
6472
6473 selection.set_head(new_head, SelectionGoal::None);
6474 }
6475 }
6476 }
6477
6478 this.signature_help_state.set_backspace_pressed(true);
6479 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6480 s.select(selections)
6481 });
6482 this.insert("", window, cx);
6483 let empty_str: Arc<str> = Arc::from("");
6484 for (buffer, edits) in linked_ranges {
6485 let snapshot = buffer.read(cx).snapshot();
6486 use text::ToPoint as TP;
6487
6488 let edits = edits
6489 .into_iter()
6490 .map(|range| {
6491 let end_point = TP::to_point(&range.end, &snapshot);
6492 let mut start_point = TP::to_point(&range.start, &snapshot);
6493
6494 if end_point == start_point {
6495 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6496 .saturating_sub(1);
6497 start_point =
6498 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6499 };
6500
6501 (start_point..end_point, empty_str.clone())
6502 })
6503 .sorted_by_key(|(range, _)| range.start)
6504 .collect::<Vec<_>>();
6505 buffer.update(cx, |this, cx| {
6506 this.edit(edits, None, cx);
6507 })
6508 }
6509 this.refresh_inline_completion(true, false, window, cx);
6510 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6511 });
6512 }
6513
6514 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6515 self.transact(window, cx, |this, window, cx| {
6516 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6517 let line_mode = s.line_mode;
6518 s.move_with(|map, selection| {
6519 if selection.is_empty() && !line_mode {
6520 let cursor = movement::right(map, selection.head());
6521 selection.end = cursor;
6522 selection.reversed = true;
6523 selection.goal = SelectionGoal::None;
6524 }
6525 })
6526 });
6527 this.insert("", window, cx);
6528 this.refresh_inline_completion(true, false, window, cx);
6529 });
6530 }
6531
6532 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6533 if self.move_to_prev_snippet_tabstop(window, cx) {
6534 return;
6535 }
6536
6537 self.outdent(&Outdent, window, cx);
6538 }
6539
6540 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6541 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6542 return;
6543 }
6544
6545 let mut selections = self.selections.all_adjusted(cx);
6546 let buffer = self.buffer.read(cx);
6547 let snapshot = buffer.snapshot(cx);
6548 let rows_iter = selections.iter().map(|s| s.head().row);
6549 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6550
6551 let mut edits = Vec::new();
6552 let mut prev_edited_row = 0;
6553 let mut row_delta = 0;
6554 for selection in &mut selections {
6555 if selection.start.row != prev_edited_row {
6556 row_delta = 0;
6557 }
6558 prev_edited_row = selection.end.row;
6559
6560 // If the selection is non-empty, then increase the indentation of the selected lines.
6561 if !selection.is_empty() {
6562 row_delta =
6563 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6564 continue;
6565 }
6566
6567 // If the selection is empty and the cursor is in the leading whitespace before the
6568 // suggested indentation, then auto-indent the line.
6569 let cursor = selection.head();
6570 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6571 if let Some(suggested_indent) =
6572 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6573 {
6574 if cursor.column < suggested_indent.len
6575 && cursor.column <= current_indent.len
6576 && current_indent.len <= suggested_indent.len
6577 {
6578 selection.start = Point::new(cursor.row, suggested_indent.len);
6579 selection.end = selection.start;
6580 if row_delta == 0 {
6581 edits.extend(Buffer::edit_for_indent_size_adjustment(
6582 cursor.row,
6583 current_indent,
6584 suggested_indent,
6585 ));
6586 row_delta = suggested_indent.len - current_indent.len;
6587 }
6588 continue;
6589 }
6590 }
6591
6592 // Otherwise, insert a hard or soft tab.
6593 let settings = buffer.settings_at(cursor, cx);
6594 let tab_size = if settings.hard_tabs {
6595 IndentSize::tab()
6596 } else {
6597 let tab_size = settings.tab_size.get();
6598 let char_column = snapshot
6599 .text_for_range(Point::new(cursor.row, 0)..cursor)
6600 .flat_map(str::chars)
6601 .count()
6602 + row_delta as usize;
6603 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6604 IndentSize::spaces(chars_to_next_tab_stop)
6605 };
6606 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6607 selection.end = selection.start;
6608 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6609 row_delta += tab_size.len;
6610 }
6611
6612 self.transact(window, cx, |this, window, cx| {
6613 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6614 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6615 s.select(selections)
6616 });
6617 this.refresh_inline_completion(true, false, window, cx);
6618 });
6619 }
6620
6621 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6622 if self.read_only(cx) {
6623 return;
6624 }
6625 let mut selections = self.selections.all::<Point>(cx);
6626 let mut prev_edited_row = 0;
6627 let mut row_delta = 0;
6628 let mut edits = Vec::new();
6629 let buffer = self.buffer.read(cx);
6630 let snapshot = buffer.snapshot(cx);
6631 for selection in &mut selections {
6632 if selection.start.row != prev_edited_row {
6633 row_delta = 0;
6634 }
6635 prev_edited_row = selection.end.row;
6636
6637 row_delta =
6638 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6639 }
6640
6641 self.transact(window, cx, |this, window, cx| {
6642 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6643 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6644 s.select(selections)
6645 });
6646 });
6647 }
6648
6649 fn indent_selection(
6650 buffer: &MultiBuffer,
6651 snapshot: &MultiBufferSnapshot,
6652 selection: &mut Selection<Point>,
6653 edits: &mut Vec<(Range<Point>, String)>,
6654 delta_for_start_row: u32,
6655 cx: &App,
6656 ) -> u32 {
6657 let settings = buffer.settings_at(selection.start, cx);
6658 let tab_size = settings.tab_size.get();
6659 let indent_kind = if settings.hard_tabs {
6660 IndentKind::Tab
6661 } else {
6662 IndentKind::Space
6663 };
6664 let mut start_row = selection.start.row;
6665 let mut end_row = selection.end.row + 1;
6666
6667 // If a selection ends at the beginning of a line, don't indent
6668 // that last line.
6669 if selection.end.column == 0 && selection.end.row > selection.start.row {
6670 end_row -= 1;
6671 }
6672
6673 // Avoid re-indenting a row that has already been indented by a
6674 // previous selection, but still update this selection's column
6675 // to reflect that indentation.
6676 if delta_for_start_row > 0 {
6677 start_row += 1;
6678 selection.start.column += delta_for_start_row;
6679 if selection.end.row == selection.start.row {
6680 selection.end.column += delta_for_start_row;
6681 }
6682 }
6683
6684 let mut delta_for_end_row = 0;
6685 let has_multiple_rows = start_row + 1 != end_row;
6686 for row in start_row..end_row {
6687 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6688 let indent_delta = match (current_indent.kind, indent_kind) {
6689 (IndentKind::Space, IndentKind::Space) => {
6690 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6691 IndentSize::spaces(columns_to_next_tab_stop)
6692 }
6693 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6694 (_, IndentKind::Tab) => IndentSize::tab(),
6695 };
6696
6697 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6698 0
6699 } else {
6700 selection.start.column
6701 };
6702 let row_start = Point::new(row, start);
6703 edits.push((
6704 row_start..row_start,
6705 indent_delta.chars().collect::<String>(),
6706 ));
6707
6708 // Update this selection's endpoints to reflect the indentation.
6709 if row == selection.start.row {
6710 selection.start.column += indent_delta.len;
6711 }
6712 if row == selection.end.row {
6713 selection.end.column += indent_delta.len;
6714 delta_for_end_row = indent_delta.len;
6715 }
6716 }
6717
6718 if selection.start.row == selection.end.row {
6719 delta_for_start_row + delta_for_end_row
6720 } else {
6721 delta_for_end_row
6722 }
6723 }
6724
6725 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6726 if self.read_only(cx) {
6727 return;
6728 }
6729 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6730 let selections = self.selections.all::<Point>(cx);
6731 let mut deletion_ranges = Vec::new();
6732 let mut last_outdent = None;
6733 {
6734 let buffer = self.buffer.read(cx);
6735 let snapshot = buffer.snapshot(cx);
6736 for selection in &selections {
6737 let settings = buffer.settings_at(selection.start, cx);
6738 let tab_size = settings.tab_size.get();
6739 let mut rows = selection.spanned_rows(false, &display_map);
6740
6741 // Avoid re-outdenting a row that has already been outdented by a
6742 // previous selection.
6743 if let Some(last_row) = last_outdent {
6744 if last_row == rows.start {
6745 rows.start = rows.start.next_row();
6746 }
6747 }
6748 let has_multiple_rows = rows.len() > 1;
6749 for row in rows.iter_rows() {
6750 let indent_size = snapshot.indent_size_for_line(row);
6751 if indent_size.len > 0 {
6752 let deletion_len = match indent_size.kind {
6753 IndentKind::Space => {
6754 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6755 if columns_to_prev_tab_stop == 0 {
6756 tab_size
6757 } else {
6758 columns_to_prev_tab_stop
6759 }
6760 }
6761 IndentKind::Tab => 1,
6762 };
6763 let start = if has_multiple_rows
6764 || deletion_len > selection.start.column
6765 || indent_size.len < selection.start.column
6766 {
6767 0
6768 } else {
6769 selection.start.column - deletion_len
6770 };
6771 deletion_ranges.push(
6772 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6773 );
6774 last_outdent = Some(row);
6775 }
6776 }
6777 }
6778 }
6779
6780 self.transact(window, cx, |this, window, cx| {
6781 this.buffer.update(cx, |buffer, cx| {
6782 let empty_str: Arc<str> = Arc::default();
6783 buffer.edit(
6784 deletion_ranges
6785 .into_iter()
6786 .map(|range| (range, empty_str.clone())),
6787 None,
6788 cx,
6789 );
6790 });
6791 let selections = this.selections.all::<usize>(cx);
6792 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6793 s.select(selections)
6794 });
6795 });
6796 }
6797
6798 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6799 if self.read_only(cx) {
6800 return;
6801 }
6802 let selections = self
6803 .selections
6804 .all::<usize>(cx)
6805 .into_iter()
6806 .map(|s| s.range());
6807
6808 self.transact(window, cx, |this, window, cx| {
6809 this.buffer.update(cx, |buffer, cx| {
6810 buffer.autoindent_ranges(selections, cx);
6811 });
6812 let selections = this.selections.all::<usize>(cx);
6813 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6814 s.select(selections)
6815 });
6816 });
6817 }
6818
6819 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6820 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6821 let selections = self.selections.all::<Point>(cx);
6822
6823 let mut new_cursors = Vec::new();
6824 let mut edit_ranges = Vec::new();
6825 let mut selections = selections.iter().peekable();
6826 while let Some(selection) = selections.next() {
6827 let mut rows = selection.spanned_rows(false, &display_map);
6828 let goal_display_column = selection.head().to_display_point(&display_map).column();
6829
6830 // Accumulate contiguous regions of rows that we want to delete.
6831 while let Some(next_selection) = selections.peek() {
6832 let next_rows = next_selection.spanned_rows(false, &display_map);
6833 if next_rows.start <= rows.end {
6834 rows.end = next_rows.end;
6835 selections.next().unwrap();
6836 } else {
6837 break;
6838 }
6839 }
6840
6841 let buffer = &display_map.buffer_snapshot;
6842 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6843 let edit_end;
6844 let cursor_buffer_row;
6845 if buffer.max_point().row >= rows.end.0 {
6846 // If there's a line after the range, delete the \n from the end of the row range
6847 // and position the cursor on the next line.
6848 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6849 cursor_buffer_row = rows.end;
6850 } else {
6851 // If there isn't a line after the range, delete the \n from the line before the
6852 // start of the row range and position the cursor there.
6853 edit_start = edit_start.saturating_sub(1);
6854 edit_end = buffer.len();
6855 cursor_buffer_row = rows.start.previous_row();
6856 }
6857
6858 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6859 *cursor.column_mut() =
6860 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6861
6862 new_cursors.push((
6863 selection.id,
6864 buffer.anchor_after(cursor.to_point(&display_map)),
6865 ));
6866 edit_ranges.push(edit_start..edit_end);
6867 }
6868
6869 self.transact(window, cx, |this, window, cx| {
6870 let buffer = this.buffer.update(cx, |buffer, cx| {
6871 let empty_str: Arc<str> = Arc::default();
6872 buffer.edit(
6873 edit_ranges
6874 .into_iter()
6875 .map(|range| (range, empty_str.clone())),
6876 None,
6877 cx,
6878 );
6879 buffer.snapshot(cx)
6880 });
6881 let new_selections = new_cursors
6882 .into_iter()
6883 .map(|(id, cursor)| {
6884 let cursor = cursor.to_point(&buffer);
6885 Selection {
6886 id,
6887 start: cursor,
6888 end: cursor,
6889 reversed: false,
6890 goal: SelectionGoal::None,
6891 }
6892 })
6893 .collect();
6894
6895 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6896 s.select(new_selections);
6897 });
6898 });
6899 }
6900
6901 pub fn join_lines_impl(
6902 &mut self,
6903 insert_whitespace: bool,
6904 window: &mut Window,
6905 cx: &mut Context<Self>,
6906 ) {
6907 if self.read_only(cx) {
6908 return;
6909 }
6910 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6911 for selection in self.selections.all::<Point>(cx) {
6912 let start = MultiBufferRow(selection.start.row);
6913 // Treat single line selections as if they include the next line. Otherwise this action
6914 // would do nothing for single line selections individual cursors.
6915 let end = if selection.start.row == selection.end.row {
6916 MultiBufferRow(selection.start.row + 1)
6917 } else {
6918 MultiBufferRow(selection.end.row)
6919 };
6920
6921 if let Some(last_row_range) = row_ranges.last_mut() {
6922 if start <= last_row_range.end {
6923 last_row_range.end = end;
6924 continue;
6925 }
6926 }
6927 row_ranges.push(start..end);
6928 }
6929
6930 let snapshot = self.buffer.read(cx).snapshot(cx);
6931 let mut cursor_positions = Vec::new();
6932 for row_range in &row_ranges {
6933 let anchor = snapshot.anchor_before(Point::new(
6934 row_range.end.previous_row().0,
6935 snapshot.line_len(row_range.end.previous_row()),
6936 ));
6937 cursor_positions.push(anchor..anchor);
6938 }
6939
6940 self.transact(window, cx, |this, window, cx| {
6941 for row_range in row_ranges.into_iter().rev() {
6942 for row in row_range.iter_rows().rev() {
6943 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6944 let next_line_row = row.next_row();
6945 let indent = snapshot.indent_size_for_line(next_line_row);
6946 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6947
6948 let replace =
6949 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6950 " "
6951 } else {
6952 ""
6953 };
6954
6955 this.buffer.update(cx, |buffer, cx| {
6956 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6957 });
6958 }
6959 }
6960
6961 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6962 s.select_anchor_ranges(cursor_positions)
6963 });
6964 });
6965 }
6966
6967 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6968 self.join_lines_impl(true, window, cx);
6969 }
6970
6971 pub fn sort_lines_case_sensitive(
6972 &mut self,
6973 _: &SortLinesCaseSensitive,
6974 window: &mut Window,
6975 cx: &mut Context<Self>,
6976 ) {
6977 self.manipulate_lines(window, cx, |lines| lines.sort())
6978 }
6979
6980 pub fn sort_lines_case_insensitive(
6981 &mut self,
6982 _: &SortLinesCaseInsensitive,
6983 window: &mut Window,
6984 cx: &mut Context<Self>,
6985 ) {
6986 self.manipulate_lines(window, cx, |lines| {
6987 lines.sort_by_key(|line| line.to_lowercase())
6988 })
6989 }
6990
6991 pub fn unique_lines_case_insensitive(
6992 &mut self,
6993 _: &UniqueLinesCaseInsensitive,
6994 window: &mut Window,
6995 cx: &mut Context<Self>,
6996 ) {
6997 self.manipulate_lines(window, cx, |lines| {
6998 let mut seen = HashSet::default();
6999 lines.retain(|line| seen.insert(line.to_lowercase()));
7000 })
7001 }
7002
7003 pub fn unique_lines_case_sensitive(
7004 &mut self,
7005 _: &UniqueLinesCaseSensitive,
7006 window: &mut Window,
7007 cx: &mut Context<Self>,
7008 ) {
7009 self.manipulate_lines(window, cx, |lines| {
7010 let mut seen = HashSet::default();
7011 lines.retain(|line| seen.insert(*line));
7012 })
7013 }
7014
7015 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7016 let Some(project) = self.project.clone() else {
7017 return;
7018 };
7019 self.reload(project, window, cx)
7020 .detach_and_notify_err(window, cx);
7021 }
7022
7023 pub fn restore_file(
7024 &mut self,
7025 _: &::git::RestoreFile,
7026 window: &mut Window,
7027 cx: &mut Context<Self>,
7028 ) {
7029 let mut buffer_ids = HashSet::default();
7030 let snapshot = self.buffer().read(cx).snapshot(cx);
7031 for selection in self.selections.all::<usize>(cx) {
7032 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7033 }
7034
7035 let buffer = self.buffer().read(cx);
7036 let ranges = buffer_ids
7037 .into_iter()
7038 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7039 .collect::<Vec<_>>();
7040
7041 self.restore_hunks_in_ranges(ranges, window, cx);
7042 }
7043
7044 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7045 let selections = self
7046 .selections
7047 .all(cx)
7048 .into_iter()
7049 .map(|s| s.range())
7050 .collect();
7051 self.restore_hunks_in_ranges(selections, window, cx);
7052 }
7053
7054 fn restore_hunks_in_ranges(
7055 &mut self,
7056 ranges: Vec<Range<Point>>,
7057 window: &mut Window,
7058 cx: &mut Context<Editor>,
7059 ) {
7060 let mut revert_changes = HashMap::default();
7061 let snapshot = self.buffer.read(cx).snapshot(cx);
7062 let Some(project) = &self.project else {
7063 return;
7064 };
7065
7066 let chunk_by = self
7067 .snapshot(window, cx)
7068 .hunks_for_ranges(ranges.into_iter())
7069 .into_iter()
7070 .chunk_by(|hunk| hunk.buffer_id);
7071 for (buffer_id, hunks) in &chunk_by {
7072 let hunks = hunks.collect::<Vec<_>>();
7073 for hunk in &hunks {
7074 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7075 }
7076 Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
7077 }
7078 drop(chunk_by);
7079 if !revert_changes.is_empty() {
7080 self.transact(window, cx, |editor, window, cx| {
7081 editor.revert(revert_changes, window, cx);
7082 });
7083 }
7084 }
7085
7086 pub fn open_active_item_in_terminal(
7087 &mut self,
7088 _: &OpenInTerminal,
7089 window: &mut Window,
7090 cx: &mut Context<Self>,
7091 ) {
7092 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7093 let project_path = buffer.read(cx).project_path(cx)?;
7094 let project = self.project.as_ref()?.read(cx);
7095 let entry = project.entry_for_path(&project_path, cx)?;
7096 let parent = match &entry.canonical_path {
7097 Some(canonical_path) => canonical_path.to_path_buf(),
7098 None => project.absolute_path(&project_path, cx)?,
7099 }
7100 .parent()?
7101 .to_path_buf();
7102 Some(parent)
7103 }) {
7104 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7105 }
7106 }
7107
7108 pub fn prepare_restore_change(
7109 &self,
7110 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7111 hunk: &MultiBufferDiffHunk,
7112 cx: &mut App,
7113 ) -> Option<()> {
7114 let buffer = self.buffer.read(cx);
7115 let diff = buffer.diff_for(hunk.buffer_id)?;
7116 let buffer = buffer.buffer(hunk.buffer_id)?;
7117 let buffer = buffer.read(cx);
7118 let original_text = diff
7119 .read(cx)
7120 .base_text()
7121 .as_ref()?
7122 .as_rope()
7123 .slice(hunk.diff_base_byte_range.clone());
7124 let buffer_snapshot = buffer.snapshot();
7125 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7126 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7127 probe
7128 .0
7129 .start
7130 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7131 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7132 }) {
7133 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7134 Some(())
7135 } else {
7136 None
7137 }
7138 }
7139
7140 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7141 self.manipulate_lines(window, cx, |lines| lines.reverse())
7142 }
7143
7144 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7145 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7146 }
7147
7148 fn manipulate_lines<Fn>(
7149 &mut self,
7150 window: &mut Window,
7151 cx: &mut Context<Self>,
7152 mut callback: Fn,
7153 ) where
7154 Fn: FnMut(&mut Vec<&str>),
7155 {
7156 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7157 let buffer = self.buffer.read(cx).snapshot(cx);
7158
7159 let mut edits = Vec::new();
7160
7161 let selections = self.selections.all::<Point>(cx);
7162 let mut selections = selections.iter().peekable();
7163 let mut contiguous_row_selections = Vec::new();
7164 let mut new_selections = Vec::new();
7165 let mut added_lines = 0;
7166 let mut removed_lines = 0;
7167
7168 while let Some(selection) = selections.next() {
7169 let (start_row, end_row) = consume_contiguous_rows(
7170 &mut contiguous_row_selections,
7171 selection,
7172 &display_map,
7173 &mut selections,
7174 );
7175
7176 let start_point = Point::new(start_row.0, 0);
7177 let end_point = Point::new(
7178 end_row.previous_row().0,
7179 buffer.line_len(end_row.previous_row()),
7180 );
7181 let text = buffer
7182 .text_for_range(start_point..end_point)
7183 .collect::<String>();
7184
7185 let mut lines = text.split('\n').collect_vec();
7186
7187 let lines_before = lines.len();
7188 callback(&mut lines);
7189 let lines_after = lines.len();
7190
7191 edits.push((start_point..end_point, lines.join("\n")));
7192
7193 // Selections must change based on added and removed line count
7194 let start_row =
7195 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7196 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7197 new_selections.push(Selection {
7198 id: selection.id,
7199 start: start_row,
7200 end: end_row,
7201 goal: SelectionGoal::None,
7202 reversed: selection.reversed,
7203 });
7204
7205 if lines_after > lines_before {
7206 added_lines += lines_after - lines_before;
7207 } else if lines_before > lines_after {
7208 removed_lines += lines_before - lines_after;
7209 }
7210 }
7211
7212 self.transact(window, cx, |this, window, cx| {
7213 let buffer = this.buffer.update(cx, |buffer, cx| {
7214 buffer.edit(edits, None, cx);
7215 buffer.snapshot(cx)
7216 });
7217
7218 // Recalculate offsets on newly edited buffer
7219 let new_selections = new_selections
7220 .iter()
7221 .map(|s| {
7222 let start_point = Point::new(s.start.0, 0);
7223 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7224 Selection {
7225 id: s.id,
7226 start: buffer.point_to_offset(start_point),
7227 end: buffer.point_to_offset(end_point),
7228 goal: s.goal,
7229 reversed: s.reversed,
7230 }
7231 })
7232 .collect();
7233
7234 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7235 s.select(new_selections);
7236 });
7237
7238 this.request_autoscroll(Autoscroll::fit(), cx);
7239 });
7240 }
7241
7242 pub fn convert_to_upper_case(
7243 &mut self,
7244 _: &ConvertToUpperCase,
7245 window: &mut Window,
7246 cx: &mut Context<Self>,
7247 ) {
7248 self.manipulate_text(window, cx, |text| text.to_uppercase())
7249 }
7250
7251 pub fn convert_to_lower_case(
7252 &mut self,
7253 _: &ConvertToLowerCase,
7254 window: &mut Window,
7255 cx: &mut Context<Self>,
7256 ) {
7257 self.manipulate_text(window, cx, |text| text.to_lowercase())
7258 }
7259
7260 pub fn convert_to_title_case(
7261 &mut self,
7262 _: &ConvertToTitleCase,
7263 window: &mut Window,
7264 cx: &mut Context<Self>,
7265 ) {
7266 self.manipulate_text(window, cx, |text| {
7267 text.split('\n')
7268 .map(|line| line.to_case(Case::Title))
7269 .join("\n")
7270 })
7271 }
7272
7273 pub fn convert_to_snake_case(
7274 &mut self,
7275 _: &ConvertToSnakeCase,
7276 window: &mut Window,
7277 cx: &mut Context<Self>,
7278 ) {
7279 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7280 }
7281
7282 pub fn convert_to_kebab_case(
7283 &mut self,
7284 _: &ConvertToKebabCase,
7285 window: &mut Window,
7286 cx: &mut Context<Self>,
7287 ) {
7288 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7289 }
7290
7291 pub fn convert_to_upper_camel_case(
7292 &mut self,
7293 _: &ConvertToUpperCamelCase,
7294 window: &mut Window,
7295 cx: &mut Context<Self>,
7296 ) {
7297 self.manipulate_text(window, cx, |text| {
7298 text.split('\n')
7299 .map(|line| line.to_case(Case::UpperCamel))
7300 .join("\n")
7301 })
7302 }
7303
7304 pub fn convert_to_lower_camel_case(
7305 &mut self,
7306 _: &ConvertToLowerCamelCase,
7307 window: &mut Window,
7308 cx: &mut Context<Self>,
7309 ) {
7310 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7311 }
7312
7313 pub fn convert_to_opposite_case(
7314 &mut self,
7315 _: &ConvertToOppositeCase,
7316 window: &mut Window,
7317 cx: &mut Context<Self>,
7318 ) {
7319 self.manipulate_text(window, cx, |text| {
7320 text.chars()
7321 .fold(String::with_capacity(text.len()), |mut t, c| {
7322 if c.is_uppercase() {
7323 t.extend(c.to_lowercase());
7324 } else {
7325 t.extend(c.to_uppercase());
7326 }
7327 t
7328 })
7329 })
7330 }
7331
7332 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7333 where
7334 Fn: FnMut(&str) -> String,
7335 {
7336 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7337 let buffer = self.buffer.read(cx).snapshot(cx);
7338
7339 let mut new_selections = Vec::new();
7340 let mut edits = Vec::new();
7341 let mut selection_adjustment = 0i32;
7342
7343 for selection in self.selections.all::<usize>(cx) {
7344 let selection_is_empty = selection.is_empty();
7345
7346 let (start, end) = if selection_is_empty {
7347 let word_range = movement::surrounding_word(
7348 &display_map,
7349 selection.start.to_display_point(&display_map),
7350 );
7351 let start = word_range.start.to_offset(&display_map, Bias::Left);
7352 let end = word_range.end.to_offset(&display_map, Bias::Left);
7353 (start, end)
7354 } else {
7355 (selection.start, selection.end)
7356 };
7357
7358 let text = buffer.text_for_range(start..end).collect::<String>();
7359 let old_length = text.len() as i32;
7360 let text = callback(&text);
7361
7362 new_selections.push(Selection {
7363 start: (start as i32 - selection_adjustment) as usize,
7364 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7365 goal: SelectionGoal::None,
7366 ..selection
7367 });
7368
7369 selection_adjustment += old_length - text.len() as i32;
7370
7371 edits.push((start..end, text));
7372 }
7373
7374 self.transact(window, cx, |this, window, cx| {
7375 this.buffer.update(cx, |buffer, cx| {
7376 buffer.edit(edits, None, cx);
7377 });
7378
7379 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7380 s.select(new_selections);
7381 });
7382
7383 this.request_autoscroll(Autoscroll::fit(), cx);
7384 });
7385 }
7386
7387 pub fn duplicate(
7388 &mut self,
7389 upwards: bool,
7390 whole_lines: bool,
7391 window: &mut Window,
7392 cx: &mut Context<Self>,
7393 ) {
7394 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7395 let buffer = &display_map.buffer_snapshot;
7396 let selections = self.selections.all::<Point>(cx);
7397
7398 let mut edits = Vec::new();
7399 let mut selections_iter = selections.iter().peekable();
7400 while let Some(selection) = selections_iter.next() {
7401 let mut rows = selection.spanned_rows(false, &display_map);
7402 // duplicate line-wise
7403 if whole_lines || selection.start == selection.end {
7404 // Avoid duplicating the same lines twice.
7405 while let Some(next_selection) = selections_iter.peek() {
7406 let next_rows = next_selection.spanned_rows(false, &display_map);
7407 if next_rows.start < rows.end {
7408 rows.end = next_rows.end;
7409 selections_iter.next().unwrap();
7410 } else {
7411 break;
7412 }
7413 }
7414
7415 // Copy the text from the selected row region and splice it either at the start
7416 // or end of the region.
7417 let start = Point::new(rows.start.0, 0);
7418 let end = Point::new(
7419 rows.end.previous_row().0,
7420 buffer.line_len(rows.end.previous_row()),
7421 );
7422 let text = buffer
7423 .text_for_range(start..end)
7424 .chain(Some("\n"))
7425 .collect::<String>();
7426 let insert_location = if upwards {
7427 Point::new(rows.end.0, 0)
7428 } else {
7429 start
7430 };
7431 edits.push((insert_location..insert_location, text));
7432 } else {
7433 // duplicate character-wise
7434 let start = selection.start;
7435 let end = selection.end;
7436 let text = buffer.text_for_range(start..end).collect::<String>();
7437 edits.push((selection.end..selection.end, text));
7438 }
7439 }
7440
7441 self.transact(window, cx, |this, _, cx| {
7442 this.buffer.update(cx, |buffer, cx| {
7443 buffer.edit(edits, None, cx);
7444 });
7445
7446 this.request_autoscroll(Autoscroll::fit(), cx);
7447 });
7448 }
7449
7450 pub fn duplicate_line_up(
7451 &mut self,
7452 _: &DuplicateLineUp,
7453 window: &mut Window,
7454 cx: &mut Context<Self>,
7455 ) {
7456 self.duplicate(true, true, window, cx);
7457 }
7458
7459 pub fn duplicate_line_down(
7460 &mut self,
7461 _: &DuplicateLineDown,
7462 window: &mut Window,
7463 cx: &mut Context<Self>,
7464 ) {
7465 self.duplicate(false, true, window, cx);
7466 }
7467
7468 pub fn duplicate_selection(
7469 &mut self,
7470 _: &DuplicateSelection,
7471 window: &mut Window,
7472 cx: &mut Context<Self>,
7473 ) {
7474 self.duplicate(false, false, window, cx);
7475 }
7476
7477 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7478 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7479 let buffer = self.buffer.read(cx).snapshot(cx);
7480
7481 let mut edits = Vec::new();
7482 let mut unfold_ranges = Vec::new();
7483 let mut refold_creases = Vec::new();
7484
7485 let selections = self.selections.all::<Point>(cx);
7486 let mut selections = selections.iter().peekable();
7487 let mut contiguous_row_selections = Vec::new();
7488 let mut new_selections = Vec::new();
7489
7490 while let Some(selection) = selections.next() {
7491 // Find all the selections that span a contiguous row range
7492 let (start_row, end_row) = consume_contiguous_rows(
7493 &mut contiguous_row_selections,
7494 selection,
7495 &display_map,
7496 &mut selections,
7497 );
7498
7499 // Move the text spanned by the row range to be before the line preceding the row range
7500 if start_row.0 > 0 {
7501 let range_to_move = Point::new(
7502 start_row.previous_row().0,
7503 buffer.line_len(start_row.previous_row()),
7504 )
7505 ..Point::new(
7506 end_row.previous_row().0,
7507 buffer.line_len(end_row.previous_row()),
7508 );
7509 let insertion_point = display_map
7510 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7511 .0;
7512
7513 // Don't move lines across excerpts
7514 if buffer
7515 .excerpt_containing(insertion_point..range_to_move.end)
7516 .is_some()
7517 {
7518 let text = buffer
7519 .text_for_range(range_to_move.clone())
7520 .flat_map(|s| s.chars())
7521 .skip(1)
7522 .chain(['\n'])
7523 .collect::<String>();
7524
7525 edits.push((
7526 buffer.anchor_after(range_to_move.start)
7527 ..buffer.anchor_before(range_to_move.end),
7528 String::new(),
7529 ));
7530 let insertion_anchor = buffer.anchor_after(insertion_point);
7531 edits.push((insertion_anchor..insertion_anchor, text));
7532
7533 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7534
7535 // Move selections up
7536 new_selections.extend(contiguous_row_selections.drain(..).map(
7537 |mut selection| {
7538 selection.start.row -= row_delta;
7539 selection.end.row -= row_delta;
7540 selection
7541 },
7542 ));
7543
7544 // Move folds up
7545 unfold_ranges.push(range_to_move.clone());
7546 for fold in display_map.folds_in_range(
7547 buffer.anchor_before(range_to_move.start)
7548 ..buffer.anchor_after(range_to_move.end),
7549 ) {
7550 let mut start = fold.range.start.to_point(&buffer);
7551 let mut end = fold.range.end.to_point(&buffer);
7552 start.row -= row_delta;
7553 end.row -= row_delta;
7554 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7555 }
7556 }
7557 }
7558
7559 // If we didn't move line(s), preserve the existing selections
7560 new_selections.append(&mut contiguous_row_selections);
7561 }
7562
7563 self.transact(window, cx, |this, window, cx| {
7564 this.unfold_ranges(&unfold_ranges, true, true, cx);
7565 this.buffer.update(cx, |buffer, cx| {
7566 for (range, text) in edits {
7567 buffer.edit([(range, text)], None, cx);
7568 }
7569 });
7570 this.fold_creases(refold_creases, true, window, cx);
7571 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7572 s.select(new_selections);
7573 })
7574 });
7575 }
7576
7577 pub fn move_line_down(
7578 &mut self,
7579 _: &MoveLineDown,
7580 window: &mut Window,
7581 cx: &mut Context<Self>,
7582 ) {
7583 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7584 let buffer = self.buffer.read(cx).snapshot(cx);
7585
7586 let mut edits = Vec::new();
7587 let mut unfold_ranges = Vec::new();
7588 let mut refold_creases = Vec::new();
7589
7590 let selections = self.selections.all::<Point>(cx);
7591 let mut selections = selections.iter().peekable();
7592 let mut contiguous_row_selections = Vec::new();
7593 let mut new_selections = Vec::new();
7594
7595 while let Some(selection) = selections.next() {
7596 // Find all the selections that span a contiguous row range
7597 let (start_row, end_row) = consume_contiguous_rows(
7598 &mut contiguous_row_selections,
7599 selection,
7600 &display_map,
7601 &mut selections,
7602 );
7603
7604 // Move the text spanned by the row range to be after the last line of the row range
7605 if end_row.0 <= buffer.max_point().row {
7606 let range_to_move =
7607 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7608 let insertion_point = display_map
7609 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7610 .0;
7611
7612 // Don't move lines across excerpt boundaries
7613 if buffer
7614 .excerpt_containing(range_to_move.start..insertion_point)
7615 .is_some()
7616 {
7617 let mut text = String::from("\n");
7618 text.extend(buffer.text_for_range(range_to_move.clone()));
7619 text.pop(); // Drop trailing newline
7620 edits.push((
7621 buffer.anchor_after(range_to_move.start)
7622 ..buffer.anchor_before(range_to_move.end),
7623 String::new(),
7624 ));
7625 let insertion_anchor = buffer.anchor_after(insertion_point);
7626 edits.push((insertion_anchor..insertion_anchor, text));
7627
7628 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7629
7630 // Move selections down
7631 new_selections.extend(contiguous_row_selections.drain(..).map(
7632 |mut selection| {
7633 selection.start.row += row_delta;
7634 selection.end.row += row_delta;
7635 selection
7636 },
7637 ));
7638
7639 // Move folds down
7640 unfold_ranges.push(range_to_move.clone());
7641 for fold in display_map.folds_in_range(
7642 buffer.anchor_before(range_to_move.start)
7643 ..buffer.anchor_after(range_to_move.end),
7644 ) {
7645 let mut start = fold.range.start.to_point(&buffer);
7646 let mut end = fold.range.end.to_point(&buffer);
7647 start.row += row_delta;
7648 end.row += row_delta;
7649 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7650 }
7651 }
7652 }
7653
7654 // If we didn't move line(s), preserve the existing selections
7655 new_selections.append(&mut contiguous_row_selections);
7656 }
7657
7658 self.transact(window, cx, |this, window, cx| {
7659 this.unfold_ranges(&unfold_ranges, true, true, cx);
7660 this.buffer.update(cx, |buffer, cx| {
7661 for (range, text) in edits {
7662 buffer.edit([(range, text)], None, cx);
7663 }
7664 });
7665 this.fold_creases(refold_creases, true, window, cx);
7666 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7667 s.select(new_selections)
7668 });
7669 });
7670 }
7671
7672 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7673 let text_layout_details = &self.text_layout_details(window);
7674 self.transact(window, cx, |this, window, cx| {
7675 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7676 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7677 let line_mode = s.line_mode;
7678 s.move_with(|display_map, selection| {
7679 if !selection.is_empty() || line_mode {
7680 return;
7681 }
7682
7683 let mut head = selection.head();
7684 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7685 if head.column() == display_map.line_len(head.row()) {
7686 transpose_offset = display_map
7687 .buffer_snapshot
7688 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7689 }
7690
7691 if transpose_offset == 0 {
7692 return;
7693 }
7694
7695 *head.column_mut() += 1;
7696 head = display_map.clip_point(head, Bias::Right);
7697 let goal = SelectionGoal::HorizontalPosition(
7698 display_map
7699 .x_for_display_point(head, text_layout_details)
7700 .into(),
7701 );
7702 selection.collapse_to(head, goal);
7703
7704 let transpose_start = display_map
7705 .buffer_snapshot
7706 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7707 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7708 let transpose_end = display_map
7709 .buffer_snapshot
7710 .clip_offset(transpose_offset + 1, Bias::Right);
7711 if let Some(ch) =
7712 display_map.buffer_snapshot.chars_at(transpose_start).next()
7713 {
7714 edits.push((transpose_start..transpose_offset, String::new()));
7715 edits.push((transpose_end..transpose_end, ch.to_string()));
7716 }
7717 }
7718 });
7719 edits
7720 });
7721 this.buffer
7722 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7723 let selections = this.selections.all::<usize>(cx);
7724 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7725 s.select(selections);
7726 });
7727 });
7728 }
7729
7730 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7731 self.rewrap_impl(IsVimMode::No, cx)
7732 }
7733
7734 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7735 let buffer = self.buffer.read(cx).snapshot(cx);
7736 let selections = self.selections.all::<Point>(cx);
7737 let mut selections = selections.iter().peekable();
7738
7739 let mut edits = Vec::new();
7740 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7741
7742 while let Some(selection) = selections.next() {
7743 let mut start_row = selection.start.row;
7744 let mut end_row = selection.end.row;
7745
7746 // Skip selections that overlap with a range that has already been rewrapped.
7747 let selection_range = start_row..end_row;
7748 if rewrapped_row_ranges
7749 .iter()
7750 .any(|range| range.overlaps(&selection_range))
7751 {
7752 continue;
7753 }
7754
7755 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7756
7757 // Since not all lines in the selection may be at the same indent
7758 // level, choose the indent size that is the most common between all
7759 // of the lines.
7760 //
7761 // If there is a tie, we use the deepest indent.
7762 let (indent_size, indent_end) = {
7763 let mut indent_size_occurrences = HashMap::default();
7764 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7765
7766 for row in start_row..=end_row {
7767 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7768 rows_by_indent_size.entry(indent).or_default().push(row);
7769 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7770 }
7771
7772 let indent_size = indent_size_occurrences
7773 .into_iter()
7774 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7775 .map(|(indent, _)| indent)
7776 .unwrap_or_default();
7777 let row = rows_by_indent_size[&indent_size][0];
7778 let indent_end = Point::new(row, indent_size.len);
7779
7780 (indent_size, indent_end)
7781 };
7782
7783 let mut line_prefix = indent_size.chars().collect::<String>();
7784
7785 let mut inside_comment = false;
7786 if let Some(comment_prefix) =
7787 buffer
7788 .language_scope_at(selection.head())
7789 .and_then(|language| {
7790 language
7791 .line_comment_prefixes()
7792 .iter()
7793 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7794 .cloned()
7795 })
7796 {
7797 line_prefix.push_str(&comment_prefix);
7798 inside_comment = true;
7799 }
7800
7801 let language_settings = buffer.settings_at(selection.head(), cx);
7802 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
7803 RewrapBehavior::InComments => inside_comment,
7804 RewrapBehavior::InSelections => !selection.is_empty(),
7805 RewrapBehavior::Anywhere => true,
7806 };
7807
7808 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
7809 if !should_rewrap {
7810 continue;
7811 }
7812
7813 if selection.is_empty() {
7814 'expand_upwards: while start_row > 0 {
7815 let prev_row = start_row - 1;
7816 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7817 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7818 {
7819 start_row = prev_row;
7820 } else {
7821 break 'expand_upwards;
7822 }
7823 }
7824
7825 'expand_downwards: while end_row < buffer.max_point().row {
7826 let next_row = end_row + 1;
7827 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7828 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7829 {
7830 end_row = next_row;
7831 } else {
7832 break 'expand_downwards;
7833 }
7834 }
7835 }
7836
7837 let start = Point::new(start_row, 0);
7838 let start_offset = start.to_offset(&buffer);
7839 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7840 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7841 let Some(lines_without_prefixes) = selection_text
7842 .lines()
7843 .map(|line| {
7844 line.strip_prefix(&line_prefix)
7845 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7846 .ok_or_else(|| {
7847 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7848 })
7849 })
7850 .collect::<Result<Vec<_>, _>>()
7851 .log_err()
7852 else {
7853 continue;
7854 };
7855
7856 let wrap_column = buffer
7857 .settings_at(Point::new(start_row, 0), cx)
7858 .preferred_line_length as usize;
7859 let wrapped_text = wrap_with_prefix(
7860 line_prefix,
7861 lines_without_prefixes.join(" "),
7862 wrap_column,
7863 tab_size,
7864 );
7865
7866 // TODO: should always use char-based diff while still supporting cursor behavior that
7867 // matches vim.
7868 let mut diff_options = DiffOptions::default();
7869 if is_vim_mode == IsVimMode::Yes {
7870 diff_options.max_word_diff_len = 0;
7871 diff_options.max_word_diff_line_count = 0;
7872 } else {
7873 diff_options.max_word_diff_len = usize::MAX;
7874 diff_options.max_word_diff_line_count = usize::MAX;
7875 }
7876
7877 for (old_range, new_text) in
7878 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
7879 {
7880 let edit_start = buffer.anchor_after(start_offset + old_range.start);
7881 let edit_end = buffer.anchor_after(start_offset + old_range.end);
7882 edits.push((edit_start..edit_end, new_text));
7883 }
7884
7885 rewrapped_row_ranges.push(start_row..=end_row);
7886 }
7887
7888 self.buffer
7889 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7890 }
7891
7892 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7893 let mut text = String::new();
7894 let buffer = self.buffer.read(cx).snapshot(cx);
7895 let mut selections = self.selections.all::<Point>(cx);
7896 let mut clipboard_selections = Vec::with_capacity(selections.len());
7897 {
7898 let max_point = buffer.max_point();
7899 let mut is_first = true;
7900 for selection in &mut selections {
7901 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7902 if is_entire_line {
7903 selection.start = Point::new(selection.start.row, 0);
7904 if !selection.is_empty() && selection.end.column == 0 {
7905 selection.end = cmp::min(max_point, selection.end);
7906 } else {
7907 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7908 }
7909 selection.goal = SelectionGoal::None;
7910 }
7911 if is_first {
7912 is_first = false;
7913 } else {
7914 text += "\n";
7915 }
7916 let mut len = 0;
7917 for chunk in buffer.text_for_range(selection.start..selection.end) {
7918 text.push_str(chunk);
7919 len += chunk.len();
7920 }
7921 clipboard_selections.push(ClipboardSelection {
7922 len,
7923 is_entire_line,
7924 first_line_indent: buffer
7925 .indent_size_for_line(MultiBufferRow(selection.start.row))
7926 .len,
7927 });
7928 }
7929 }
7930
7931 self.transact(window, cx, |this, window, cx| {
7932 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7933 s.select(selections);
7934 });
7935 this.insert("", window, cx);
7936 });
7937 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7938 }
7939
7940 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7941 let item = self.cut_common(window, cx);
7942 cx.write_to_clipboard(item);
7943 }
7944
7945 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7946 self.change_selections(None, window, cx, |s| {
7947 s.move_with(|snapshot, sel| {
7948 if sel.is_empty() {
7949 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7950 }
7951 });
7952 });
7953 let item = self.cut_common(window, cx);
7954 cx.set_global(KillRing(item))
7955 }
7956
7957 pub fn kill_ring_yank(
7958 &mut self,
7959 _: &KillRingYank,
7960 window: &mut Window,
7961 cx: &mut Context<Self>,
7962 ) {
7963 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7964 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7965 (kill_ring.text().to_string(), kill_ring.metadata_json())
7966 } else {
7967 return;
7968 }
7969 } else {
7970 return;
7971 };
7972 self.do_paste(&text, metadata, false, window, cx);
7973 }
7974
7975 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7976 let selections = self.selections.all::<Point>(cx);
7977 let buffer = self.buffer.read(cx).read(cx);
7978 let mut text = String::new();
7979
7980 let mut clipboard_selections = Vec::with_capacity(selections.len());
7981 {
7982 let max_point = buffer.max_point();
7983 let mut is_first = true;
7984 for selection in selections.iter() {
7985 let mut start = selection.start;
7986 let mut end = selection.end;
7987 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7988 if is_entire_line {
7989 start = Point::new(start.row, 0);
7990 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7991 }
7992 if is_first {
7993 is_first = false;
7994 } else {
7995 text += "\n";
7996 }
7997 let mut len = 0;
7998 for chunk in buffer.text_for_range(start..end) {
7999 text.push_str(chunk);
8000 len += chunk.len();
8001 }
8002 clipboard_selections.push(ClipboardSelection {
8003 len,
8004 is_entire_line,
8005 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8006 });
8007 }
8008 }
8009
8010 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8011 text,
8012 clipboard_selections,
8013 ));
8014 }
8015
8016 pub fn do_paste(
8017 &mut self,
8018 text: &String,
8019 clipboard_selections: Option<Vec<ClipboardSelection>>,
8020 handle_entire_lines: bool,
8021 window: &mut Window,
8022 cx: &mut Context<Self>,
8023 ) {
8024 if self.read_only(cx) {
8025 return;
8026 }
8027
8028 let clipboard_text = Cow::Borrowed(text);
8029
8030 self.transact(window, cx, |this, window, cx| {
8031 if let Some(mut clipboard_selections) = clipboard_selections {
8032 let old_selections = this.selections.all::<usize>(cx);
8033 let all_selections_were_entire_line =
8034 clipboard_selections.iter().all(|s| s.is_entire_line);
8035 let first_selection_indent_column =
8036 clipboard_selections.first().map(|s| s.first_line_indent);
8037 if clipboard_selections.len() != old_selections.len() {
8038 clipboard_selections.drain(..);
8039 }
8040 let cursor_offset = this.selections.last::<usize>(cx).head();
8041 let mut auto_indent_on_paste = true;
8042
8043 this.buffer.update(cx, |buffer, cx| {
8044 let snapshot = buffer.read(cx);
8045 auto_indent_on_paste =
8046 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8047
8048 let mut start_offset = 0;
8049 let mut edits = Vec::new();
8050 let mut original_indent_columns = Vec::new();
8051 for (ix, selection) in old_selections.iter().enumerate() {
8052 let to_insert;
8053 let entire_line;
8054 let original_indent_column;
8055 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8056 let end_offset = start_offset + clipboard_selection.len;
8057 to_insert = &clipboard_text[start_offset..end_offset];
8058 entire_line = clipboard_selection.is_entire_line;
8059 start_offset = end_offset + 1;
8060 original_indent_column = Some(clipboard_selection.first_line_indent);
8061 } else {
8062 to_insert = clipboard_text.as_str();
8063 entire_line = all_selections_were_entire_line;
8064 original_indent_column = first_selection_indent_column
8065 }
8066
8067 // If the corresponding selection was empty when this slice of the
8068 // clipboard text was written, then the entire line containing the
8069 // selection was copied. If this selection is also currently empty,
8070 // then paste the line before the current line of the buffer.
8071 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8072 let column = selection.start.to_point(&snapshot).column as usize;
8073 let line_start = selection.start - column;
8074 line_start..line_start
8075 } else {
8076 selection.range()
8077 };
8078
8079 edits.push((range, to_insert));
8080 original_indent_columns.extend(original_indent_column);
8081 }
8082 drop(snapshot);
8083
8084 buffer.edit(
8085 edits,
8086 if auto_indent_on_paste {
8087 Some(AutoindentMode::Block {
8088 original_indent_columns,
8089 })
8090 } else {
8091 None
8092 },
8093 cx,
8094 );
8095 });
8096
8097 let selections = this.selections.all::<usize>(cx);
8098 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8099 s.select(selections)
8100 });
8101 } else {
8102 this.insert(&clipboard_text, window, cx);
8103 }
8104 });
8105 }
8106
8107 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8108 if let Some(item) = cx.read_from_clipboard() {
8109 let entries = item.entries();
8110
8111 match entries.first() {
8112 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8113 // of all the pasted entries.
8114 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8115 .do_paste(
8116 clipboard_string.text(),
8117 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8118 true,
8119 window,
8120 cx,
8121 ),
8122 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8123 }
8124 }
8125 }
8126
8127 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8128 if self.read_only(cx) {
8129 return;
8130 }
8131
8132 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8133 if let Some((selections, _)) =
8134 self.selection_history.transaction(transaction_id).cloned()
8135 {
8136 self.change_selections(None, window, cx, |s| {
8137 s.select_anchors(selections.to_vec());
8138 });
8139 }
8140 self.request_autoscroll(Autoscroll::fit(), cx);
8141 self.unmark_text(window, cx);
8142 self.refresh_inline_completion(true, false, window, cx);
8143 cx.emit(EditorEvent::Edited { transaction_id });
8144 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8145 }
8146 }
8147
8148 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8149 if self.read_only(cx) {
8150 return;
8151 }
8152
8153 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8154 if let Some((_, Some(selections))) =
8155 self.selection_history.transaction(transaction_id).cloned()
8156 {
8157 self.change_selections(None, window, cx, |s| {
8158 s.select_anchors(selections.to_vec());
8159 });
8160 }
8161 self.request_autoscroll(Autoscroll::fit(), cx);
8162 self.unmark_text(window, cx);
8163 self.refresh_inline_completion(true, false, window, cx);
8164 cx.emit(EditorEvent::Edited { transaction_id });
8165 }
8166 }
8167
8168 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8169 self.buffer
8170 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8171 }
8172
8173 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8174 self.buffer
8175 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8176 }
8177
8178 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8179 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8180 let line_mode = s.line_mode;
8181 s.move_with(|map, selection| {
8182 let cursor = if selection.is_empty() && !line_mode {
8183 movement::left(map, selection.start)
8184 } else {
8185 selection.start
8186 };
8187 selection.collapse_to(cursor, SelectionGoal::None);
8188 });
8189 })
8190 }
8191
8192 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8193 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8194 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8195 })
8196 }
8197
8198 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8199 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8200 let line_mode = s.line_mode;
8201 s.move_with(|map, selection| {
8202 let cursor = if selection.is_empty() && !line_mode {
8203 movement::right(map, selection.end)
8204 } else {
8205 selection.end
8206 };
8207 selection.collapse_to(cursor, SelectionGoal::None)
8208 });
8209 })
8210 }
8211
8212 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8213 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8214 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8215 })
8216 }
8217
8218 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8219 if self.take_rename(true, window, cx).is_some() {
8220 return;
8221 }
8222
8223 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8224 cx.propagate();
8225 return;
8226 }
8227
8228 let text_layout_details = &self.text_layout_details(window);
8229 let selection_count = self.selections.count();
8230 let first_selection = self.selections.first_anchor();
8231
8232 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8233 let line_mode = s.line_mode;
8234 s.move_with(|map, selection| {
8235 if !selection.is_empty() && !line_mode {
8236 selection.goal = SelectionGoal::None;
8237 }
8238 let (cursor, goal) = movement::up(
8239 map,
8240 selection.start,
8241 selection.goal,
8242 false,
8243 text_layout_details,
8244 );
8245 selection.collapse_to(cursor, goal);
8246 });
8247 });
8248
8249 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8250 {
8251 cx.propagate();
8252 }
8253 }
8254
8255 pub fn move_up_by_lines(
8256 &mut self,
8257 action: &MoveUpByLines,
8258 window: &mut Window,
8259 cx: &mut Context<Self>,
8260 ) {
8261 if self.take_rename(true, window, cx).is_some() {
8262 return;
8263 }
8264
8265 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8266 cx.propagate();
8267 return;
8268 }
8269
8270 let text_layout_details = &self.text_layout_details(window);
8271
8272 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8273 let line_mode = s.line_mode;
8274 s.move_with(|map, selection| {
8275 if !selection.is_empty() && !line_mode {
8276 selection.goal = SelectionGoal::None;
8277 }
8278 let (cursor, goal) = movement::up_by_rows(
8279 map,
8280 selection.start,
8281 action.lines,
8282 selection.goal,
8283 false,
8284 text_layout_details,
8285 );
8286 selection.collapse_to(cursor, goal);
8287 });
8288 })
8289 }
8290
8291 pub fn move_down_by_lines(
8292 &mut self,
8293 action: &MoveDownByLines,
8294 window: &mut Window,
8295 cx: &mut Context<Self>,
8296 ) {
8297 if self.take_rename(true, window, cx).is_some() {
8298 return;
8299 }
8300
8301 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8302 cx.propagate();
8303 return;
8304 }
8305
8306 let text_layout_details = &self.text_layout_details(window);
8307
8308 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8309 let line_mode = s.line_mode;
8310 s.move_with(|map, selection| {
8311 if !selection.is_empty() && !line_mode {
8312 selection.goal = SelectionGoal::None;
8313 }
8314 let (cursor, goal) = movement::down_by_rows(
8315 map,
8316 selection.start,
8317 action.lines,
8318 selection.goal,
8319 false,
8320 text_layout_details,
8321 );
8322 selection.collapse_to(cursor, goal);
8323 });
8324 })
8325 }
8326
8327 pub fn select_down_by_lines(
8328 &mut self,
8329 action: &SelectDownByLines,
8330 window: &mut Window,
8331 cx: &mut Context<Self>,
8332 ) {
8333 let text_layout_details = &self.text_layout_details(window);
8334 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8335 s.move_heads_with(|map, head, goal| {
8336 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8337 })
8338 })
8339 }
8340
8341 pub fn select_up_by_lines(
8342 &mut self,
8343 action: &SelectUpByLines,
8344 window: &mut Window,
8345 cx: &mut Context<Self>,
8346 ) {
8347 let text_layout_details = &self.text_layout_details(window);
8348 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8349 s.move_heads_with(|map, head, goal| {
8350 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8351 })
8352 })
8353 }
8354
8355 pub fn select_page_up(
8356 &mut self,
8357 _: &SelectPageUp,
8358 window: &mut Window,
8359 cx: &mut Context<Self>,
8360 ) {
8361 let Some(row_count) = self.visible_row_count() else {
8362 return;
8363 };
8364
8365 let text_layout_details = &self.text_layout_details(window);
8366
8367 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8368 s.move_heads_with(|map, head, goal| {
8369 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8370 })
8371 })
8372 }
8373
8374 pub fn move_page_up(
8375 &mut self,
8376 action: &MovePageUp,
8377 window: &mut Window,
8378 cx: &mut Context<Self>,
8379 ) {
8380 if self.take_rename(true, window, cx).is_some() {
8381 return;
8382 }
8383
8384 if self
8385 .context_menu
8386 .borrow_mut()
8387 .as_mut()
8388 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8389 .unwrap_or(false)
8390 {
8391 return;
8392 }
8393
8394 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8395 cx.propagate();
8396 return;
8397 }
8398
8399 let Some(row_count) = self.visible_row_count() else {
8400 return;
8401 };
8402
8403 let autoscroll = if action.center_cursor {
8404 Autoscroll::center()
8405 } else {
8406 Autoscroll::fit()
8407 };
8408
8409 let text_layout_details = &self.text_layout_details(window);
8410
8411 self.change_selections(Some(autoscroll), window, cx, |s| {
8412 let line_mode = s.line_mode;
8413 s.move_with(|map, selection| {
8414 if !selection.is_empty() && !line_mode {
8415 selection.goal = SelectionGoal::None;
8416 }
8417 let (cursor, goal) = movement::up_by_rows(
8418 map,
8419 selection.end,
8420 row_count,
8421 selection.goal,
8422 false,
8423 text_layout_details,
8424 );
8425 selection.collapse_to(cursor, goal);
8426 });
8427 });
8428 }
8429
8430 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8431 let text_layout_details = &self.text_layout_details(window);
8432 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8433 s.move_heads_with(|map, head, goal| {
8434 movement::up(map, head, goal, false, text_layout_details)
8435 })
8436 })
8437 }
8438
8439 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8440 self.take_rename(true, window, cx);
8441
8442 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8443 cx.propagate();
8444 return;
8445 }
8446
8447 let text_layout_details = &self.text_layout_details(window);
8448 let selection_count = self.selections.count();
8449 let first_selection = self.selections.first_anchor();
8450
8451 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8452 let line_mode = s.line_mode;
8453 s.move_with(|map, selection| {
8454 if !selection.is_empty() && !line_mode {
8455 selection.goal = SelectionGoal::None;
8456 }
8457 let (cursor, goal) = movement::down(
8458 map,
8459 selection.end,
8460 selection.goal,
8461 false,
8462 text_layout_details,
8463 );
8464 selection.collapse_to(cursor, goal);
8465 });
8466 });
8467
8468 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8469 {
8470 cx.propagate();
8471 }
8472 }
8473
8474 pub fn select_page_down(
8475 &mut self,
8476 _: &SelectPageDown,
8477 window: &mut Window,
8478 cx: &mut Context<Self>,
8479 ) {
8480 let Some(row_count) = self.visible_row_count() else {
8481 return;
8482 };
8483
8484 let text_layout_details = &self.text_layout_details(window);
8485
8486 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8487 s.move_heads_with(|map, head, goal| {
8488 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8489 })
8490 })
8491 }
8492
8493 pub fn move_page_down(
8494 &mut self,
8495 action: &MovePageDown,
8496 window: &mut Window,
8497 cx: &mut Context<Self>,
8498 ) {
8499 if self.take_rename(true, window, cx).is_some() {
8500 return;
8501 }
8502
8503 if self
8504 .context_menu
8505 .borrow_mut()
8506 .as_mut()
8507 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8508 .unwrap_or(false)
8509 {
8510 return;
8511 }
8512
8513 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8514 cx.propagate();
8515 return;
8516 }
8517
8518 let Some(row_count) = self.visible_row_count() else {
8519 return;
8520 };
8521
8522 let autoscroll = if action.center_cursor {
8523 Autoscroll::center()
8524 } else {
8525 Autoscroll::fit()
8526 };
8527
8528 let text_layout_details = &self.text_layout_details(window);
8529 self.change_selections(Some(autoscroll), window, cx, |s| {
8530 let line_mode = s.line_mode;
8531 s.move_with(|map, selection| {
8532 if !selection.is_empty() && !line_mode {
8533 selection.goal = SelectionGoal::None;
8534 }
8535 let (cursor, goal) = movement::down_by_rows(
8536 map,
8537 selection.end,
8538 row_count,
8539 selection.goal,
8540 false,
8541 text_layout_details,
8542 );
8543 selection.collapse_to(cursor, goal);
8544 });
8545 });
8546 }
8547
8548 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8549 let text_layout_details = &self.text_layout_details(window);
8550 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8551 s.move_heads_with(|map, head, goal| {
8552 movement::down(map, head, goal, false, text_layout_details)
8553 })
8554 });
8555 }
8556
8557 pub fn context_menu_first(
8558 &mut self,
8559 _: &ContextMenuFirst,
8560 _window: &mut Window,
8561 cx: &mut Context<Self>,
8562 ) {
8563 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8564 context_menu.select_first(self.completion_provider.as_deref(), cx);
8565 }
8566 }
8567
8568 pub fn context_menu_prev(
8569 &mut self,
8570 _: &ContextMenuPrev,
8571 _window: &mut Window,
8572 cx: &mut Context<Self>,
8573 ) {
8574 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8575 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8576 }
8577 }
8578
8579 pub fn context_menu_next(
8580 &mut self,
8581 _: &ContextMenuNext,
8582 _window: &mut Window,
8583 cx: &mut Context<Self>,
8584 ) {
8585 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8586 context_menu.select_next(self.completion_provider.as_deref(), cx);
8587 }
8588 }
8589
8590 pub fn context_menu_last(
8591 &mut self,
8592 _: &ContextMenuLast,
8593 _window: &mut Window,
8594 cx: &mut Context<Self>,
8595 ) {
8596 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8597 context_menu.select_last(self.completion_provider.as_deref(), cx);
8598 }
8599 }
8600
8601 pub fn move_to_previous_word_start(
8602 &mut self,
8603 _: &MoveToPreviousWordStart,
8604 window: &mut Window,
8605 cx: &mut Context<Self>,
8606 ) {
8607 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8608 s.move_cursors_with(|map, head, _| {
8609 (
8610 movement::previous_word_start(map, head),
8611 SelectionGoal::None,
8612 )
8613 });
8614 })
8615 }
8616
8617 pub fn move_to_previous_subword_start(
8618 &mut self,
8619 _: &MoveToPreviousSubwordStart,
8620 window: &mut Window,
8621 cx: &mut Context<Self>,
8622 ) {
8623 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8624 s.move_cursors_with(|map, head, _| {
8625 (
8626 movement::previous_subword_start(map, head),
8627 SelectionGoal::None,
8628 )
8629 });
8630 })
8631 }
8632
8633 pub fn select_to_previous_word_start(
8634 &mut self,
8635 _: &SelectToPreviousWordStart,
8636 window: &mut Window,
8637 cx: &mut Context<Self>,
8638 ) {
8639 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8640 s.move_heads_with(|map, head, _| {
8641 (
8642 movement::previous_word_start(map, head),
8643 SelectionGoal::None,
8644 )
8645 });
8646 })
8647 }
8648
8649 pub fn select_to_previous_subword_start(
8650 &mut self,
8651 _: &SelectToPreviousSubwordStart,
8652 window: &mut Window,
8653 cx: &mut Context<Self>,
8654 ) {
8655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8656 s.move_heads_with(|map, head, _| {
8657 (
8658 movement::previous_subword_start(map, head),
8659 SelectionGoal::None,
8660 )
8661 });
8662 })
8663 }
8664
8665 pub fn delete_to_previous_word_start(
8666 &mut self,
8667 action: &DeleteToPreviousWordStart,
8668 window: &mut Window,
8669 cx: &mut Context<Self>,
8670 ) {
8671 self.transact(window, cx, |this, window, cx| {
8672 this.select_autoclose_pair(window, cx);
8673 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8674 let line_mode = s.line_mode;
8675 s.move_with(|map, selection| {
8676 if selection.is_empty() && !line_mode {
8677 let cursor = if action.ignore_newlines {
8678 movement::previous_word_start(map, selection.head())
8679 } else {
8680 movement::previous_word_start_or_newline(map, selection.head())
8681 };
8682 selection.set_head(cursor, SelectionGoal::None);
8683 }
8684 });
8685 });
8686 this.insert("", window, cx);
8687 });
8688 }
8689
8690 pub fn delete_to_previous_subword_start(
8691 &mut self,
8692 _: &DeleteToPreviousSubwordStart,
8693 window: &mut Window,
8694 cx: &mut Context<Self>,
8695 ) {
8696 self.transact(window, cx, |this, window, cx| {
8697 this.select_autoclose_pair(window, cx);
8698 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8699 let line_mode = s.line_mode;
8700 s.move_with(|map, selection| {
8701 if selection.is_empty() && !line_mode {
8702 let cursor = movement::previous_subword_start(map, selection.head());
8703 selection.set_head(cursor, SelectionGoal::None);
8704 }
8705 });
8706 });
8707 this.insert("", window, cx);
8708 });
8709 }
8710
8711 pub fn move_to_next_word_end(
8712 &mut self,
8713 _: &MoveToNextWordEnd,
8714 window: &mut Window,
8715 cx: &mut Context<Self>,
8716 ) {
8717 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8718 s.move_cursors_with(|map, head, _| {
8719 (movement::next_word_end(map, head), SelectionGoal::None)
8720 });
8721 })
8722 }
8723
8724 pub fn move_to_next_subword_end(
8725 &mut self,
8726 _: &MoveToNextSubwordEnd,
8727 window: &mut Window,
8728 cx: &mut Context<Self>,
8729 ) {
8730 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8731 s.move_cursors_with(|map, head, _| {
8732 (movement::next_subword_end(map, head), SelectionGoal::None)
8733 });
8734 })
8735 }
8736
8737 pub fn select_to_next_word_end(
8738 &mut self,
8739 _: &SelectToNextWordEnd,
8740 window: &mut Window,
8741 cx: &mut Context<Self>,
8742 ) {
8743 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8744 s.move_heads_with(|map, head, _| {
8745 (movement::next_word_end(map, head), SelectionGoal::None)
8746 });
8747 })
8748 }
8749
8750 pub fn select_to_next_subword_end(
8751 &mut self,
8752 _: &SelectToNextSubwordEnd,
8753 window: &mut Window,
8754 cx: &mut Context<Self>,
8755 ) {
8756 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8757 s.move_heads_with(|map, head, _| {
8758 (movement::next_subword_end(map, head), SelectionGoal::None)
8759 });
8760 })
8761 }
8762
8763 pub fn delete_to_next_word_end(
8764 &mut self,
8765 action: &DeleteToNextWordEnd,
8766 window: &mut Window,
8767 cx: &mut Context<Self>,
8768 ) {
8769 self.transact(window, cx, |this, window, cx| {
8770 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8771 let line_mode = s.line_mode;
8772 s.move_with(|map, selection| {
8773 if selection.is_empty() && !line_mode {
8774 let cursor = if action.ignore_newlines {
8775 movement::next_word_end(map, selection.head())
8776 } else {
8777 movement::next_word_end_or_newline(map, selection.head())
8778 };
8779 selection.set_head(cursor, SelectionGoal::None);
8780 }
8781 });
8782 });
8783 this.insert("", window, cx);
8784 });
8785 }
8786
8787 pub fn delete_to_next_subword_end(
8788 &mut self,
8789 _: &DeleteToNextSubwordEnd,
8790 window: &mut Window,
8791 cx: &mut Context<Self>,
8792 ) {
8793 self.transact(window, cx, |this, window, cx| {
8794 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8795 s.move_with(|map, selection| {
8796 if selection.is_empty() {
8797 let cursor = movement::next_subword_end(map, selection.head());
8798 selection.set_head(cursor, SelectionGoal::None);
8799 }
8800 });
8801 });
8802 this.insert("", window, cx);
8803 });
8804 }
8805
8806 pub fn move_to_beginning_of_line(
8807 &mut self,
8808 action: &MoveToBeginningOfLine,
8809 window: &mut Window,
8810 cx: &mut Context<Self>,
8811 ) {
8812 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8813 s.move_cursors_with(|map, head, _| {
8814 (
8815 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8816 SelectionGoal::None,
8817 )
8818 });
8819 })
8820 }
8821
8822 pub fn select_to_beginning_of_line(
8823 &mut self,
8824 action: &SelectToBeginningOfLine,
8825 window: &mut Window,
8826 cx: &mut Context<Self>,
8827 ) {
8828 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8829 s.move_heads_with(|map, head, _| {
8830 (
8831 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8832 SelectionGoal::None,
8833 )
8834 });
8835 });
8836 }
8837
8838 pub fn delete_to_beginning_of_line(
8839 &mut self,
8840 _: &DeleteToBeginningOfLine,
8841 window: &mut Window,
8842 cx: &mut Context<Self>,
8843 ) {
8844 self.transact(window, cx, |this, window, cx| {
8845 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8846 s.move_with(|_, selection| {
8847 selection.reversed = true;
8848 });
8849 });
8850
8851 this.select_to_beginning_of_line(
8852 &SelectToBeginningOfLine {
8853 stop_at_soft_wraps: false,
8854 },
8855 window,
8856 cx,
8857 );
8858 this.backspace(&Backspace, window, cx);
8859 });
8860 }
8861
8862 pub fn move_to_end_of_line(
8863 &mut self,
8864 action: &MoveToEndOfLine,
8865 window: &mut Window,
8866 cx: &mut Context<Self>,
8867 ) {
8868 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8869 s.move_cursors_with(|map, head, _| {
8870 (
8871 movement::line_end(map, head, action.stop_at_soft_wraps),
8872 SelectionGoal::None,
8873 )
8874 });
8875 })
8876 }
8877
8878 pub fn select_to_end_of_line(
8879 &mut self,
8880 action: &SelectToEndOfLine,
8881 window: &mut Window,
8882 cx: &mut Context<Self>,
8883 ) {
8884 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8885 s.move_heads_with(|map, head, _| {
8886 (
8887 movement::line_end(map, head, action.stop_at_soft_wraps),
8888 SelectionGoal::None,
8889 )
8890 });
8891 })
8892 }
8893
8894 pub fn delete_to_end_of_line(
8895 &mut self,
8896 _: &DeleteToEndOfLine,
8897 window: &mut Window,
8898 cx: &mut Context<Self>,
8899 ) {
8900 self.transact(window, cx, |this, window, cx| {
8901 this.select_to_end_of_line(
8902 &SelectToEndOfLine {
8903 stop_at_soft_wraps: false,
8904 },
8905 window,
8906 cx,
8907 );
8908 this.delete(&Delete, window, cx);
8909 });
8910 }
8911
8912 pub fn cut_to_end_of_line(
8913 &mut self,
8914 _: &CutToEndOfLine,
8915 window: &mut Window,
8916 cx: &mut Context<Self>,
8917 ) {
8918 self.transact(window, cx, |this, window, cx| {
8919 this.select_to_end_of_line(
8920 &SelectToEndOfLine {
8921 stop_at_soft_wraps: false,
8922 },
8923 window,
8924 cx,
8925 );
8926 this.cut(&Cut, window, cx);
8927 });
8928 }
8929
8930 pub fn move_to_start_of_paragraph(
8931 &mut self,
8932 _: &MoveToStartOfParagraph,
8933 window: &mut Window,
8934 cx: &mut Context<Self>,
8935 ) {
8936 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8937 cx.propagate();
8938 return;
8939 }
8940
8941 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8942 s.move_with(|map, selection| {
8943 selection.collapse_to(
8944 movement::start_of_paragraph(map, selection.head(), 1),
8945 SelectionGoal::None,
8946 )
8947 });
8948 })
8949 }
8950
8951 pub fn move_to_end_of_paragraph(
8952 &mut self,
8953 _: &MoveToEndOfParagraph,
8954 window: &mut Window,
8955 cx: &mut Context<Self>,
8956 ) {
8957 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8958 cx.propagate();
8959 return;
8960 }
8961
8962 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8963 s.move_with(|map, selection| {
8964 selection.collapse_to(
8965 movement::end_of_paragraph(map, selection.head(), 1),
8966 SelectionGoal::None,
8967 )
8968 });
8969 })
8970 }
8971
8972 pub fn select_to_start_of_paragraph(
8973 &mut self,
8974 _: &SelectToStartOfParagraph,
8975 window: &mut Window,
8976 cx: &mut Context<Self>,
8977 ) {
8978 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8979 cx.propagate();
8980 return;
8981 }
8982
8983 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8984 s.move_heads_with(|map, head, _| {
8985 (
8986 movement::start_of_paragraph(map, head, 1),
8987 SelectionGoal::None,
8988 )
8989 });
8990 })
8991 }
8992
8993 pub fn select_to_end_of_paragraph(
8994 &mut self,
8995 _: &SelectToEndOfParagraph,
8996 window: &mut Window,
8997 cx: &mut Context<Self>,
8998 ) {
8999 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9000 cx.propagate();
9001 return;
9002 }
9003
9004 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9005 s.move_heads_with(|map, head, _| {
9006 (
9007 movement::end_of_paragraph(map, head, 1),
9008 SelectionGoal::None,
9009 )
9010 });
9011 })
9012 }
9013
9014 pub fn move_to_beginning(
9015 &mut self,
9016 _: &MoveToBeginning,
9017 window: &mut Window,
9018 cx: &mut Context<Self>,
9019 ) {
9020 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9021 cx.propagate();
9022 return;
9023 }
9024
9025 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9026 s.select_ranges(vec![0..0]);
9027 });
9028 }
9029
9030 pub fn select_to_beginning(
9031 &mut self,
9032 _: &SelectToBeginning,
9033 window: &mut Window,
9034 cx: &mut Context<Self>,
9035 ) {
9036 let mut selection = self.selections.last::<Point>(cx);
9037 selection.set_head(Point::zero(), SelectionGoal::None);
9038
9039 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9040 s.select(vec![selection]);
9041 });
9042 }
9043
9044 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9045 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9046 cx.propagate();
9047 return;
9048 }
9049
9050 let cursor = self.buffer.read(cx).read(cx).len();
9051 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9052 s.select_ranges(vec![cursor..cursor])
9053 });
9054 }
9055
9056 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9057 self.nav_history = nav_history;
9058 }
9059
9060 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9061 self.nav_history.as_ref()
9062 }
9063
9064 fn push_to_nav_history(
9065 &mut self,
9066 cursor_anchor: Anchor,
9067 new_position: Option<Point>,
9068 cx: &mut Context<Self>,
9069 ) {
9070 if let Some(nav_history) = self.nav_history.as_mut() {
9071 let buffer = self.buffer.read(cx).read(cx);
9072 let cursor_position = cursor_anchor.to_point(&buffer);
9073 let scroll_state = self.scroll_manager.anchor();
9074 let scroll_top_row = scroll_state.top_row(&buffer);
9075 drop(buffer);
9076
9077 if let Some(new_position) = new_position {
9078 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9079 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9080 return;
9081 }
9082 }
9083
9084 nav_history.push(
9085 Some(NavigationData {
9086 cursor_anchor,
9087 cursor_position,
9088 scroll_anchor: scroll_state,
9089 scroll_top_row,
9090 }),
9091 cx,
9092 );
9093 }
9094 }
9095
9096 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9097 let buffer = self.buffer.read(cx).snapshot(cx);
9098 let mut selection = self.selections.first::<usize>(cx);
9099 selection.set_head(buffer.len(), SelectionGoal::None);
9100 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9101 s.select(vec![selection]);
9102 });
9103 }
9104
9105 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9106 let end = self.buffer.read(cx).read(cx).len();
9107 self.change_selections(None, window, cx, |s| {
9108 s.select_ranges(vec![0..end]);
9109 });
9110 }
9111
9112 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9113 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9114 let mut selections = self.selections.all::<Point>(cx);
9115 let max_point = display_map.buffer_snapshot.max_point();
9116 for selection in &mut selections {
9117 let rows = selection.spanned_rows(true, &display_map);
9118 selection.start = Point::new(rows.start.0, 0);
9119 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9120 selection.reversed = false;
9121 }
9122 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9123 s.select(selections);
9124 });
9125 }
9126
9127 pub fn split_selection_into_lines(
9128 &mut self,
9129 _: &SplitSelectionIntoLines,
9130 window: &mut Window,
9131 cx: &mut Context<Self>,
9132 ) {
9133 let selections = self
9134 .selections
9135 .all::<Point>(cx)
9136 .into_iter()
9137 .map(|selection| selection.start..selection.end)
9138 .collect::<Vec<_>>();
9139 self.unfold_ranges(&selections, true, true, cx);
9140
9141 let mut new_selection_ranges = Vec::new();
9142 {
9143 let buffer = self.buffer.read(cx).read(cx);
9144 for selection in selections {
9145 for row in selection.start.row..selection.end.row {
9146 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9147 new_selection_ranges.push(cursor..cursor);
9148 }
9149
9150 let is_multiline_selection = selection.start.row != selection.end.row;
9151 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9152 // so this action feels more ergonomic when paired with other selection operations
9153 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9154 if !should_skip_last {
9155 new_selection_ranges.push(selection.end..selection.end);
9156 }
9157 }
9158 }
9159 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9160 s.select_ranges(new_selection_ranges);
9161 });
9162 }
9163
9164 pub fn add_selection_above(
9165 &mut self,
9166 _: &AddSelectionAbove,
9167 window: &mut Window,
9168 cx: &mut Context<Self>,
9169 ) {
9170 self.add_selection(true, window, cx);
9171 }
9172
9173 pub fn add_selection_below(
9174 &mut self,
9175 _: &AddSelectionBelow,
9176 window: &mut Window,
9177 cx: &mut Context<Self>,
9178 ) {
9179 self.add_selection(false, window, cx);
9180 }
9181
9182 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9183 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9184 let mut selections = self.selections.all::<Point>(cx);
9185 let text_layout_details = self.text_layout_details(window);
9186 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9187 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9188 let range = oldest_selection.display_range(&display_map).sorted();
9189
9190 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9191 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9192 let positions = start_x.min(end_x)..start_x.max(end_x);
9193
9194 selections.clear();
9195 let mut stack = Vec::new();
9196 for row in range.start.row().0..=range.end.row().0 {
9197 if let Some(selection) = self.selections.build_columnar_selection(
9198 &display_map,
9199 DisplayRow(row),
9200 &positions,
9201 oldest_selection.reversed,
9202 &text_layout_details,
9203 ) {
9204 stack.push(selection.id);
9205 selections.push(selection);
9206 }
9207 }
9208
9209 if above {
9210 stack.reverse();
9211 }
9212
9213 AddSelectionsState { above, stack }
9214 });
9215
9216 let last_added_selection = *state.stack.last().unwrap();
9217 let mut new_selections = Vec::new();
9218 if above == state.above {
9219 let end_row = if above {
9220 DisplayRow(0)
9221 } else {
9222 display_map.max_point().row()
9223 };
9224
9225 'outer: for selection in selections {
9226 if selection.id == last_added_selection {
9227 let range = selection.display_range(&display_map).sorted();
9228 debug_assert_eq!(range.start.row(), range.end.row());
9229 let mut row = range.start.row();
9230 let positions =
9231 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9232 px(start)..px(end)
9233 } else {
9234 let start_x =
9235 display_map.x_for_display_point(range.start, &text_layout_details);
9236 let end_x =
9237 display_map.x_for_display_point(range.end, &text_layout_details);
9238 start_x.min(end_x)..start_x.max(end_x)
9239 };
9240
9241 while row != end_row {
9242 if above {
9243 row.0 -= 1;
9244 } else {
9245 row.0 += 1;
9246 }
9247
9248 if let Some(new_selection) = self.selections.build_columnar_selection(
9249 &display_map,
9250 row,
9251 &positions,
9252 selection.reversed,
9253 &text_layout_details,
9254 ) {
9255 state.stack.push(new_selection.id);
9256 if above {
9257 new_selections.push(new_selection);
9258 new_selections.push(selection);
9259 } else {
9260 new_selections.push(selection);
9261 new_selections.push(new_selection);
9262 }
9263
9264 continue 'outer;
9265 }
9266 }
9267 }
9268
9269 new_selections.push(selection);
9270 }
9271 } else {
9272 new_selections = selections;
9273 new_selections.retain(|s| s.id != last_added_selection);
9274 state.stack.pop();
9275 }
9276
9277 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9278 s.select(new_selections);
9279 });
9280 if state.stack.len() > 1 {
9281 self.add_selections_state = Some(state);
9282 }
9283 }
9284
9285 pub fn select_next_match_internal(
9286 &mut self,
9287 display_map: &DisplaySnapshot,
9288 replace_newest: bool,
9289 autoscroll: Option<Autoscroll>,
9290 window: &mut Window,
9291 cx: &mut Context<Self>,
9292 ) -> Result<()> {
9293 fn select_next_match_ranges(
9294 this: &mut Editor,
9295 range: Range<usize>,
9296 replace_newest: bool,
9297 auto_scroll: Option<Autoscroll>,
9298 window: &mut Window,
9299 cx: &mut Context<Editor>,
9300 ) {
9301 this.unfold_ranges(&[range.clone()], false, true, cx);
9302 this.change_selections(auto_scroll, window, cx, |s| {
9303 if replace_newest {
9304 s.delete(s.newest_anchor().id);
9305 }
9306 s.insert_range(range.clone());
9307 });
9308 }
9309
9310 let buffer = &display_map.buffer_snapshot;
9311 let mut selections = self.selections.all::<usize>(cx);
9312 if let Some(mut select_next_state) = self.select_next_state.take() {
9313 let query = &select_next_state.query;
9314 if !select_next_state.done {
9315 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9316 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9317 let mut next_selected_range = None;
9318
9319 let bytes_after_last_selection =
9320 buffer.bytes_in_range(last_selection.end..buffer.len());
9321 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9322 let query_matches = query
9323 .stream_find_iter(bytes_after_last_selection)
9324 .map(|result| (last_selection.end, result))
9325 .chain(
9326 query
9327 .stream_find_iter(bytes_before_first_selection)
9328 .map(|result| (0, result)),
9329 );
9330
9331 for (start_offset, query_match) in query_matches {
9332 let query_match = query_match.unwrap(); // can only fail due to I/O
9333 let offset_range =
9334 start_offset + query_match.start()..start_offset + query_match.end();
9335 let display_range = offset_range.start.to_display_point(display_map)
9336 ..offset_range.end.to_display_point(display_map);
9337
9338 if !select_next_state.wordwise
9339 || (!movement::is_inside_word(display_map, display_range.start)
9340 && !movement::is_inside_word(display_map, display_range.end))
9341 {
9342 // TODO: This is n^2, because we might check all the selections
9343 if !selections
9344 .iter()
9345 .any(|selection| selection.range().overlaps(&offset_range))
9346 {
9347 next_selected_range = Some(offset_range);
9348 break;
9349 }
9350 }
9351 }
9352
9353 if let Some(next_selected_range) = next_selected_range {
9354 select_next_match_ranges(
9355 self,
9356 next_selected_range,
9357 replace_newest,
9358 autoscroll,
9359 window,
9360 cx,
9361 );
9362 } else {
9363 select_next_state.done = true;
9364 }
9365 }
9366
9367 self.select_next_state = Some(select_next_state);
9368 } else {
9369 let mut only_carets = true;
9370 let mut same_text_selected = true;
9371 let mut selected_text = None;
9372
9373 let mut selections_iter = selections.iter().peekable();
9374 while let Some(selection) = selections_iter.next() {
9375 if selection.start != selection.end {
9376 only_carets = false;
9377 }
9378
9379 if same_text_selected {
9380 if selected_text.is_none() {
9381 selected_text =
9382 Some(buffer.text_for_range(selection.range()).collect::<String>());
9383 }
9384
9385 if let Some(next_selection) = selections_iter.peek() {
9386 if next_selection.range().len() == selection.range().len() {
9387 let next_selected_text = buffer
9388 .text_for_range(next_selection.range())
9389 .collect::<String>();
9390 if Some(next_selected_text) != selected_text {
9391 same_text_selected = false;
9392 selected_text = None;
9393 }
9394 } else {
9395 same_text_selected = false;
9396 selected_text = None;
9397 }
9398 }
9399 }
9400 }
9401
9402 if only_carets {
9403 for selection in &mut selections {
9404 let word_range = movement::surrounding_word(
9405 display_map,
9406 selection.start.to_display_point(display_map),
9407 );
9408 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9409 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9410 selection.goal = SelectionGoal::None;
9411 selection.reversed = false;
9412 select_next_match_ranges(
9413 self,
9414 selection.start..selection.end,
9415 replace_newest,
9416 autoscroll,
9417 window,
9418 cx,
9419 );
9420 }
9421
9422 if selections.len() == 1 {
9423 let selection = selections
9424 .last()
9425 .expect("ensured that there's only one selection");
9426 let query = buffer
9427 .text_for_range(selection.start..selection.end)
9428 .collect::<String>();
9429 let is_empty = query.is_empty();
9430 let select_state = SelectNextState {
9431 query: AhoCorasick::new(&[query])?,
9432 wordwise: true,
9433 done: is_empty,
9434 };
9435 self.select_next_state = Some(select_state);
9436 } else {
9437 self.select_next_state = None;
9438 }
9439 } else if let Some(selected_text) = selected_text {
9440 self.select_next_state = Some(SelectNextState {
9441 query: AhoCorasick::new(&[selected_text])?,
9442 wordwise: false,
9443 done: false,
9444 });
9445 self.select_next_match_internal(
9446 display_map,
9447 replace_newest,
9448 autoscroll,
9449 window,
9450 cx,
9451 )?;
9452 }
9453 }
9454 Ok(())
9455 }
9456
9457 pub fn select_all_matches(
9458 &mut self,
9459 _action: &SelectAllMatches,
9460 window: &mut Window,
9461 cx: &mut Context<Self>,
9462 ) -> Result<()> {
9463 self.push_to_selection_history();
9464 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9465
9466 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9467 let Some(select_next_state) = self.select_next_state.as_mut() else {
9468 return Ok(());
9469 };
9470 if select_next_state.done {
9471 return Ok(());
9472 }
9473
9474 let mut new_selections = self.selections.all::<usize>(cx);
9475
9476 let buffer = &display_map.buffer_snapshot;
9477 let query_matches = select_next_state
9478 .query
9479 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9480
9481 for query_match in query_matches {
9482 let query_match = query_match.unwrap(); // can only fail due to I/O
9483 let offset_range = query_match.start()..query_match.end();
9484 let display_range = offset_range.start.to_display_point(&display_map)
9485 ..offset_range.end.to_display_point(&display_map);
9486
9487 if !select_next_state.wordwise
9488 || (!movement::is_inside_word(&display_map, display_range.start)
9489 && !movement::is_inside_word(&display_map, display_range.end))
9490 {
9491 self.selections.change_with(cx, |selections| {
9492 new_selections.push(Selection {
9493 id: selections.new_selection_id(),
9494 start: offset_range.start,
9495 end: offset_range.end,
9496 reversed: false,
9497 goal: SelectionGoal::None,
9498 });
9499 });
9500 }
9501 }
9502
9503 new_selections.sort_by_key(|selection| selection.start);
9504 let mut ix = 0;
9505 while ix + 1 < new_selections.len() {
9506 let current_selection = &new_selections[ix];
9507 let next_selection = &new_selections[ix + 1];
9508 if current_selection.range().overlaps(&next_selection.range()) {
9509 if current_selection.id < next_selection.id {
9510 new_selections.remove(ix + 1);
9511 } else {
9512 new_selections.remove(ix);
9513 }
9514 } else {
9515 ix += 1;
9516 }
9517 }
9518
9519 let reversed = self.selections.oldest::<usize>(cx).reversed;
9520
9521 for selection in new_selections.iter_mut() {
9522 selection.reversed = reversed;
9523 }
9524
9525 select_next_state.done = true;
9526 self.unfold_ranges(
9527 &new_selections
9528 .iter()
9529 .map(|selection| selection.range())
9530 .collect::<Vec<_>>(),
9531 false,
9532 false,
9533 cx,
9534 );
9535 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9536 selections.select(new_selections)
9537 });
9538
9539 Ok(())
9540 }
9541
9542 pub fn select_next(
9543 &mut self,
9544 action: &SelectNext,
9545 window: &mut Window,
9546 cx: &mut Context<Self>,
9547 ) -> Result<()> {
9548 self.push_to_selection_history();
9549 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9550 self.select_next_match_internal(
9551 &display_map,
9552 action.replace_newest,
9553 Some(Autoscroll::newest()),
9554 window,
9555 cx,
9556 )?;
9557 Ok(())
9558 }
9559
9560 pub fn select_previous(
9561 &mut self,
9562 action: &SelectPrevious,
9563 window: &mut Window,
9564 cx: &mut Context<Self>,
9565 ) -> Result<()> {
9566 self.push_to_selection_history();
9567 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9568 let buffer = &display_map.buffer_snapshot;
9569 let mut selections = self.selections.all::<usize>(cx);
9570 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9571 let query = &select_prev_state.query;
9572 if !select_prev_state.done {
9573 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9574 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9575 let mut next_selected_range = None;
9576 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9577 let bytes_before_last_selection =
9578 buffer.reversed_bytes_in_range(0..last_selection.start);
9579 let bytes_after_first_selection =
9580 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9581 let query_matches = query
9582 .stream_find_iter(bytes_before_last_selection)
9583 .map(|result| (last_selection.start, result))
9584 .chain(
9585 query
9586 .stream_find_iter(bytes_after_first_selection)
9587 .map(|result| (buffer.len(), result)),
9588 );
9589 for (end_offset, query_match) in query_matches {
9590 let query_match = query_match.unwrap(); // can only fail due to I/O
9591 let offset_range =
9592 end_offset - query_match.end()..end_offset - query_match.start();
9593 let display_range = offset_range.start.to_display_point(&display_map)
9594 ..offset_range.end.to_display_point(&display_map);
9595
9596 if !select_prev_state.wordwise
9597 || (!movement::is_inside_word(&display_map, display_range.start)
9598 && !movement::is_inside_word(&display_map, display_range.end))
9599 {
9600 next_selected_range = Some(offset_range);
9601 break;
9602 }
9603 }
9604
9605 if let Some(next_selected_range) = next_selected_range {
9606 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9607 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9608 if action.replace_newest {
9609 s.delete(s.newest_anchor().id);
9610 }
9611 s.insert_range(next_selected_range);
9612 });
9613 } else {
9614 select_prev_state.done = true;
9615 }
9616 }
9617
9618 self.select_prev_state = Some(select_prev_state);
9619 } else {
9620 let mut only_carets = true;
9621 let mut same_text_selected = true;
9622 let mut selected_text = None;
9623
9624 let mut selections_iter = selections.iter().peekable();
9625 while let Some(selection) = selections_iter.next() {
9626 if selection.start != selection.end {
9627 only_carets = false;
9628 }
9629
9630 if same_text_selected {
9631 if selected_text.is_none() {
9632 selected_text =
9633 Some(buffer.text_for_range(selection.range()).collect::<String>());
9634 }
9635
9636 if let Some(next_selection) = selections_iter.peek() {
9637 if next_selection.range().len() == selection.range().len() {
9638 let next_selected_text = buffer
9639 .text_for_range(next_selection.range())
9640 .collect::<String>();
9641 if Some(next_selected_text) != selected_text {
9642 same_text_selected = false;
9643 selected_text = None;
9644 }
9645 } else {
9646 same_text_selected = false;
9647 selected_text = None;
9648 }
9649 }
9650 }
9651 }
9652
9653 if only_carets {
9654 for selection in &mut selections {
9655 let word_range = movement::surrounding_word(
9656 &display_map,
9657 selection.start.to_display_point(&display_map),
9658 );
9659 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9660 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9661 selection.goal = SelectionGoal::None;
9662 selection.reversed = false;
9663 }
9664 if selections.len() == 1 {
9665 let selection = selections
9666 .last()
9667 .expect("ensured that there's only one selection");
9668 let query = buffer
9669 .text_for_range(selection.start..selection.end)
9670 .collect::<String>();
9671 let is_empty = query.is_empty();
9672 let select_state = SelectNextState {
9673 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9674 wordwise: true,
9675 done: is_empty,
9676 };
9677 self.select_prev_state = Some(select_state);
9678 } else {
9679 self.select_prev_state = None;
9680 }
9681
9682 self.unfold_ranges(
9683 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9684 false,
9685 true,
9686 cx,
9687 );
9688 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9689 s.select(selections);
9690 });
9691 } else if let Some(selected_text) = selected_text {
9692 self.select_prev_state = Some(SelectNextState {
9693 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9694 wordwise: false,
9695 done: false,
9696 });
9697 self.select_previous(action, window, cx)?;
9698 }
9699 }
9700 Ok(())
9701 }
9702
9703 pub fn toggle_comments(
9704 &mut self,
9705 action: &ToggleComments,
9706 window: &mut Window,
9707 cx: &mut Context<Self>,
9708 ) {
9709 if self.read_only(cx) {
9710 return;
9711 }
9712 let text_layout_details = &self.text_layout_details(window);
9713 self.transact(window, cx, |this, window, cx| {
9714 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9715 let mut edits = Vec::new();
9716 let mut selection_edit_ranges = Vec::new();
9717 let mut last_toggled_row = None;
9718 let snapshot = this.buffer.read(cx).read(cx);
9719 let empty_str: Arc<str> = Arc::default();
9720 let mut suffixes_inserted = Vec::new();
9721 let ignore_indent = action.ignore_indent;
9722
9723 fn comment_prefix_range(
9724 snapshot: &MultiBufferSnapshot,
9725 row: MultiBufferRow,
9726 comment_prefix: &str,
9727 comment_prefix_whitespace: &str,
9728 ignore_indent: bool,
9729 ) -> Range<Point> {
9730 let indent_size = if ignore_indent {
9731 0
9732 } else {
9733 snapshot.indent_size_for_line(row).len
9734 };
9735
9736 let start = Point::new(row.0, indent_size);
9737
9738 let mut line_bytes = snapshot
9739 .bytes_in_range(start..snapshot.max_point())
9740 .flatten()
9741 .copied();
9742
9743 // If this line currently begins with the line comment prefix, then record
9744 // the range containing the prefix.
9745 if line_bytes
9746 .by_ref()
9747 .take(comment_prefix.len())
9748 .eq(comment_prefix.bytes())
9749 {
9750 // Include any whitespace that matches the comment prefix.
9751 let matching_whitespace_len = line_bytes
9752 .zip(comment_prefix_whitespace.bytes())
9753 .take_while(|(a, b)| a == b)
9754 .count() as u32;
9755 let end = Point::new(
9756 start.row,
9757 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9758 );
9759 start..end
9760 } else {
9761 start..start
9762 }
9763 }
9764
9765 fn comment_suffix_range(
9766 snapshot: &MultiBufferSnapshot,
9767 row: MultiBufferRow,
9768 comment_suffix: &str,
9769 comment_suffix_has_leading_space: bool,
9770 ) -> Range<Point> {
9771 let end = Point::new(row.0, snapshot.line_len(row));
9772 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9773
9774 let mut line_end_bytes = snapshot
9775 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9776 .flatten()
9777 .copied();
9778
9779 let leading_space_len = if suffix_start_column > 0
9780 && line_end_bytes.next() == Some(b' ')
9781 && comment_suffix_has_leading_space
9782 {
9783 1
9784 } else {
9785 0
9786 };
9787
9788 // If this line currently begins with the line comment prefix, then record
9789 // the range containing the prefix.
9790 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9791 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9792 start..end
9793 } else {
9794 end..end
9795 }
9796 }
9797
9798 // TODO: Handle selections that cross excerpts
9799 for selection in &mut selections {
9800 let start_column = snapshot
9801 .indent_size_for_line(MultiBufferRow(selection.start.row))
9802 .len;
9803 let language = if let Some(language) =
9804 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9805 {
9806 language
9807 } else {
9808 continue;
9809 };
9810
9811 selection_edit_ranges.clear();
9812
9813 // If multiple selections contain a given row, avoid processing that
9814 // row more than once.
9815 let mut start_row = MultiBufferRow(selection.start.row);
9816 if last_toggled_row == Some(start_row) {
9817 start_row = start_row.next_row();
9818 }
9819 let end_row =
9820 if selection.end.row > selection.start.row && selection.end.column == 0 {
9821 MultiBufferRow(selection.end.row - 1)
9822 } else {
9823 MultiBufferRow(selection.end.row)
9824 };
9825 last_toggled_row = Some(end_row);
9826
9827 if start_row > end_row {
9828 continue;
9829 }
9830
9831 // If the language has line comments, toggle those.
9832 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9833
9834 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9835 if ignore_indent {
9836 full_comment_prefixes = full_comment_prefixes
9837 .into_iter()
9838 .map(|s| Arc::from(s.trim_end()))
9839 .collect();
9840 }
9841
9842 if !full_comment_prefixes.is_empty() {
9843 let first_prefix = full_comment_prefixes
9844 .first()
9845 .expect("prefixes is non-empty");
9846 let prefix_trimmed_lengths = full_comment_prefixes
9847 .iter()
9848 .map(|p| p.trim_end_matches(' ').len())
9849 .collect::<SmallVec<[usize; 4]>>();
9850
9851 let mut all_selection_lines_are_comments = true;
9852
9853 for row in start_row.0..=end_row.0 {
9854 let row = MultiBufferRow(row);
9855 if start_row < end_row && snapshot.is_line_blank(row) {
9856 continue;
9857 }
9858
9859 let prefix_range = full_comment_prefixes
9860 .iter()
9861 .zip(prefix_trimmed_lengths.iter().copied())
9862 .map(|(prefix, trimmed_prefix_len)| {
9863 comment_prefix_range(
9864 snapshot.deref(),
9865 row,
9866 &prefix[..trimmed_prefix_len],
9867 &prefix[trimmed_prefix_len..],
9868 ignore_indent,
9869 )
9870 })
9871 .max_by_key(|range| range.end.column - range.start.column)
9872 .expect("prefixes is non-empty");
9873
9874 if prefix_range.is_empty() {
9875 all_selection_lines_are_comments = false;
9876 }
9877
9878 selection_edit_ranges.push(prefix_range);
9879 }
9880
9881 if all_selection_lines_are_comments {
9882 edits.extend(
9883 selection_edit_ranges
9884 .iter()
9885 .cloned()
9886 .map(|range| (range, empty_str.clone())),
9887 );
9888 } else {
9889 let min_column = selection_edit_ranges
9890 .iter()
9891 .map(|range| range.start.column)
9892 .min()
9893 .unwrap_or(0);
9894 edits.extend(selection_edit_ranges.iter().map(|range| {
9895 let position = Point::new(range.start.row, min_column);
9896 (position..position, first_prefix.clone())
9897 }));
9898 }
9899 } else if let Some((full_comment_prefix, comment_suffix)) =
9900 language.block_comment_delimiters()
9901 {
9902 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9903 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9904 let prefix_range = comment_prefix_range(
9905 snapshot.deref(),
9906 start_row,
9907 comment_prefix,
9908 comment_prefix_whitespace,
9909 ignore_indent,
9910 );
9911 let suffix_range = comment_suffix_range(
9912 snapshot.deref(),
9913 end_row,
9914 comment_suffix.trim_start_matches(' '),
9915 comment_suffix.starts_with(' '),
9916 );
9917
9918 if prefix_range.is_empty() || suffix_range.is_empty() {
9919 edits.push((
9920 prefix_range.start..prefix_range.start,
9921 full_comment_prefix.clone(),
9922 ));
9923 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9924 suffixes_inserted.push((end_row, comment_suffix.len()));
9925 } else {
9926 edits.push((prefix_range, empty_str.clone()));
9927 edits.push((suffix_range, empty_str.clone()));
9928 }
9929 } else {
9930 continue;
9931 }
9932 }
9933
9934 drop(snapshot);
9935 this.buffer.update(cx, |buffer, cx| {
9936 buffer.edit(edits, None, cx);
9937 });
9938
9939 // Adjust selections so that they end before any comment suffixes that
9940 // were inserted.
9941 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9942 let mut selections = this.selections.all::<Point>(cx);
9943 let snapshot = this.buffer.read(cx).read(cx);
9944 for selection in &mut selections {
9945 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9946 match row.cmp(&MultiBufferRow(selection.end.row)) {
9947 Ordering::Less => {
9948 suffixes_inserted.next();
9949 continue;
9950 }
9951 Ordering::Greater => break,
9952 Ordering::Equal => {
9953 if selection.end.column == snapshot.line_len(row) {
9954 if selection.is_empty() {
9955 selection.start.column -= suffix_len as u32;
9956 }
9957 selection.end.column -= suffix_len as u32;
9958 }
9959 break;
9960 }
9961 }
9962 }
9963 }
9964
9965 drop(snapshot);
9966 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9967 s.select(selections)
9968 });
9969
9970 let selections = this.selections.all::<Point>(cx);
9971 let selections_on_single_row = selections.windows(2).all(|selections| {
9972 selections[0].start.row == selections[1].start.row
9973 && selections[0].end.row == selections[1].end.row
9974 && selections[0].start.row == selections[0].end.row
9975 });
9976 let selections_selecting = selections
9977 .iter()
9978 .any(|selection| selection.start != selection.end);
9979 let advance_downwards = action.advance_downwards
9980 && selections_on_single_row
9981 && !selections_selecting
9982 && !matches!(this.mode, EditorMode::SingleLine { .. });
9983
9984 if advance_downwards {
9985 let snapshot = this.buffer.read(cx).snapshot(cx);
9986
9987 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9988 s.move_cursors_with(|display_snapshot, display_point, _| {
9989 let mut point = display_point.to_point(display_snapshot);
9990 point.row += 1;
9991 point = snapshot.clip_point(point, Bias::Left);
9992 let display_point = point.to_display_point(display_snapshot);
9993 let goal = SelectionGoal::HorizontalPosition(
9994 display_snapshot
9995 .x_for_display_point(display_point, text_layout_details)
9996 .into(),
9997 );
9998 (display_point, goal)
9999 })
10000 });
10001 }
10002 });
10003 }
10004
10005 pub fn select_enclosing_symbol(
10006 &mut self,
10007 _: &SelectEnclosingSymbol,
10008 window: &mut Window,
10009 cx: &mut Context<Self>,
10010 ) {
10011 let buffer = self.buffer.read(cx).snapshot(cx);
10012 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10013
10014 fn update_selection(
10015 selection: &Selection<usize>,
10016 buffer_snap: &MultiBufferSnapshot,
10017 ) -> Option<Selection<usize>> {
10018 let cursor = selection.head();
10019 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10020 for symbol in symbols.iter().rev() {
10021 let start = symbol.range.start.to_offset(buffer_snap);
10022 let end = symbol.range.end.to_offset(buffer_snap);
10023 let new_range = start..end;
10024 if start < selection.start || end > selection.end {
10025 return Some(Selection {
10026 id: selection.id,
10027 start: new_range.start,
10028 end: new_range.end,
10029 goal: SelectionGoal::None,
10030 reversed: selection.reversed,
10031 });
10032 }
10033 }
10034 None
10035 }
10036
10037 let mut selected_larger_symbol = false;
10038 let new_selections = old_selections
10039 .iter()
10040 .map(|selection| match update_selection(selection, &buffer) {
10041 Some(new_selection) => {
10042 if new_selection.range() != selection.range() {
10043 selected_larger_symbol = true;
10044 }
10045 new_selection
10046 }
10047 None => selection.clone(),
10048 })
10049 .collect::<Vec<_>>();
10050
10051 if selected_larger_symbol {
10052 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10053 s.select(new_selections);
10054 });
10055 }
10056 }
10057
10058 pub fn select_larger_syntax_node(
10059 &mut self,
10060 _: &SelectLargerSyntaxNode,
10061 window: &mut Window,
10062 cx: &mut Context<Self>,
10063 ) {
10064 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10065 let buffer = self.buffer.read(cx).snapshot(cx);
10066 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10067
10068 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10069 let mut selected_larger_node = false;
10070 let new_selections = old_selections
10071 .iter()
10072 .map(|selection| {
10073 let old_range = selection.start..selection.end;
10074 let mut new_range = old_range.clone();
10075 let mut new_node = None;
10076 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10077 {
10078 new_node = Some(node);
10079 new_range = containing_range;
10080 if !display_map.intersects_fold(new_range.start)
10081 && !display_map.intersects_fold(new_range.end)
10082 {
10083 break;
10084 }
10085 }
10086
10087 if let Some(node) = new_node {
10088 // Log the ancestor, to support using this action as a way to explore TreeSitter
10089 // nodes. Parent and grandparent are also logged because this operation will not
10090 // visit nodes that have the same range as their parent.
10091 log::info!("Node: {node:?}");
10092 let parent = node.parent();
10093 log::info!("Parent: {parent:?}");
10094 let grandparent = parent.and_then(|x| x.parent());
10095 log::info!("Grandparent: {grandparent:?}");
10096 }
10097
10098 selected_larger_node |= new_range != old_range;
10099 Selection {
10100 id: selection.id,
10101 start: new_range.start,
10102 end: new_range.end,
10103 goal: SelectionGoal::None,
10104 reversed: selection.reversed,
10105 }
10106 })
10107 .collect::<Vec<_>>();
10108
10109 if selected_larger_node {
10110 stack.push(old_selections);
10111 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10112 s.select(new_selections);
10113 });
10114 }
10115 self.select_larger_syntax_node_stack = stack;
10116 }
10117
10118 pub fn select_smaller_syntax_node(
10119 &mut self,
10120 _: &SelectSmallerSyntaxNode,
10121 window: &mut Window,
10122 cx: &mut Context<Self>,
10123 ) {
10124 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10125 if let Some(selections) = stack.pop() {
10126 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10127 s.select(selections.to_vec());
10128 });
10129 }
10130 self.select_larger_syntax_node_stack = stack;
10131 }
10132
10133 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10134 if !EditorSettings::get_global(cx).gutter.runnables {
10135 self.clear_tasks();
10136 return Task::ready(());
10137 }
10138 let project = self.project.as_ref().map(Entity::downgrade);
10139 cx.spawn_in(window, |this, mut cx| async move {
10140 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10141 let Some(project) = project.and_then(|p| p.upgrade()) else {
10142 return;
10143 };
10144 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10145 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10146 }) else {
10147 return;
10148 };
10149
10150 let hide_runnables = project
10151 .update(&mut cx, |project, cx| {
10152 // Do not display any test indicators in non-dev server remote projects.
10153 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10154 })
10155 .unwrap_or(true);
10156 if hide_runnables {
10157 return;
10158 }
10159 let new_rows =
10160 cx.background_spawn({
10161 let snapshot = display_snapshot.clone();
10162 async move {
10163 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10164 }
10165 })
10166 .await;
10167
10168 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10169 this.update(&mut cx, |this, _| {
10170 this.clear_tasks();
10171 for (key, value) in rows {
10172 this.insert_tasks(key, value);
10173 }
10174 })
10175 .ok();
10176 })
10177 }
10178 fn fetch_runnable_ranges(
10179 snapshot: &DisplaySnapshot,
10180 range: Range<Anchor>,
10181 ) -> Vec<language::RunnableRange> {
10182 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10183 }
10184
10185 fn runnable_rows(
10186 project: Entity<Project>,
10187 snapshot: DisplaySnapshot,
10188 runnable_ranges: Vec<RunnableRange>,
10189 mut cx: AsyncWindowContext,
10190 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10191 runnable_ranges
10192 .into_iter()
10193 .filter_map(|mut runnable| {
10194 let tasks = cx
10195 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10196 .ok()?;
10197 if tasks.is_empty() {
10198 return None;
10199 }
10200
10201 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10202
10203 let row = snapshot
10204 .buffer_snapshot
10205 .buffer_line_for_row(MultiBufferRow(point.row))?
10206 .1
10207 .start
10208 .row;
10209
10210 let context_range =
10211 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10212 Some((
10213 (runnable.buffer_id, row),
10214 RunnableTasks {
10215 templates: tasks,
10216 offset: MultiBufferOffset(runnable.run_range.start),
10217 context_range,
10218 column: point.column,
10219 extra_variables: runnable.extra_captures,
10220 },
10221 ))
10222 })
10223 .collect()
10224 }
10225
10226 fn templates_with_tags(
10227 project: &Entity<Project>,
10228 runnable: &mut Runnable,
10229 cx: &mut App,
10230 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10231 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10232 let (worktree_id, file) = project
10233 .buffer_for_id(runnable.buffer, cx)
10234 .and_then(|buffer| buffer.read(cx).file())
10235 .map(|file| (file.worktree_id(cx), file.clone()))
10236 .unzip();
10237
10238 (
10239 project.task_store().read(cx).task_inventory().cloned(),
10240 worktree_id,
10241 file,
10242 )
10243 });
10244
10245 let tags = mem::take(&mut runnable.tags);
10246 let mut tags: Vec<_> = tags
10247 .into_iter()
10248 .flat_map(|tag| {
10249 let tag = tag.0.clone();
10250 inventory
10251 .as_ref()
10252 .into_iter()
10253 .flat_map(|inventory| {
10254 inventory.read(cx).list_tasks(
10255 file.clone(),
10256 Some(runnable.language.clone()),
10257 worktree_id,
10258 cx,
10259 )
10260 })
10261 .filter(move |(_, template)| {
10262 template.tags.iter().any(|source_tag| source_tag == &tag)
10263 })
10264 })
10265 .sorted_by_key(|(kind, _)| kind.to_owned())
10266 .collect();
10267 if let Some((leading_tag_source, _)) = tags.first() {
10268 // Strongest source wins; if we have worktree tag binding, prefer that to
10269 // global and language bindings;
10270 // if we have a global binding, prefer that to language binding.
10271 let first_mismatch = tags
10272 .iter()
10273 .position(|(tag_source, _)| tag_source != leading_tag_source);
10274 if let Some(index) = first_mismatch {
10275 tags.truncate(index);
10276 }
10277 }
10278
10279 tags
10280 }
10281
10282 pub fn move_to_enclosing_bracket(
10283 &mut self,
10284 _: &MoveToEnclosingBracket,
10285 window: &mut Window,
10286 cx: &mut Context<Self>,
10287 ) {
10288 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10289 s.move_offsets_with(|snapshot, selection| {
10290 let Some(enclosing_bracket_ranges) =
10291 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10292 else {
10293 return;
10294 };
10295
10296 let mut best_length = usize::MAX;
10297 let mut best_inside = false;
10298 let mut best_in_bracket_range = false;
10299 let mut best_destination = None;
10300 for (open, close) in enclosing_bracket_ranges {
10301 let close = close.to_inclusive();
10302 let length = close.end() - open.start;
10303 let inside = selection.start >= open.end && selection.end <= *close.start();
10304 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10305 || close.contains(&selection.head());
10306
10307 // If best is next to a bracket and current isn't, skip
10308 if !in_bracket_range && best_in_bracket_range {
10309 continue;
10310 }
10311
10312 // Prefer smaller lengths unless best is inside and current isn't
10313 if length > best_length && (best_inside || !inside) {
10314 continue;
10315 }
10316
10317 best_length = length;
10318 best_inside = inside;
10319 best_in_bracket_range = in_bracket_range;
10320 best_destination = Some(
10321 if close.contains(&selection.start) && close.contains(&selection.end) {
10322 if inside {
10323 open.end
10324 } else {
10325 open.start
10326 }
10327 } else if inside {
10328 *close.start()
10329 } else {
10330 *close.end()
10331 },
10332 );
10333 }
10334
10335 if let Some(destination) = best_destination {
10336 selection.collapse_to(destination, SelectionGoal::None);
10337 }
10338 })
10339 });
10340 }
10341
10342 pub fn undo_selection(
10343 &mut self,
10344 _: &UndoSelection,
10345 window: &mut Window,
10346 cx: &mut Context<Self>,
10347 ) {
10348 self.end_selection(window, cx);
10349 self.selection_history.mode = SelectionHistoryMode::Undoing;
10350 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10351 self.change_selections(None, window, cx, |s| {
10352 s.select_anchors(entry.selections.to_vec())
10353 });
10354 self.select_next_state = entry.select_next_state;
10355 self.select_prev_state = entry.select_prev_state;
10356 self.add_selections_state = entry.add_selections_state;
10357 self.request_autoscroll(Autoscroll::newest(), cx);
10358 }
10359 self.selection_history.mode = SelectionHistoryMode::Normal;
10360 }
10361
10362 pub fn redo_selection(
10363 &mut self,
10364 _: &RedoSelection,
10365 window: &mut Window,
10366 cx: &mut Context<Self>,
10367 ) {
10368 self.end_selection(window, cx);
10369 self.selection_history.mode = SelectionHistoryMode::Redoing;
10370 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10371 self.change_selections(None, window, cx, |s| {
10372 s.select_anchors(entry.selections.to_vec())
10373 });
10374 self.select_next_state = entry.select_next_state;
10375 self.select_prev_state = entry.select_prev_state;
10376 self.add_selections_state = entry.add_selections_state;
10377 self.request_autoscroll(Autoscroll::newest(), cx);
10378 }
10379 self.selection_history.mode = SelectionHistoryMode::Normal;
10380 }
10381
10382 pub fn expand_excerpts(
10383 &mut self,
10384 action: &ExpandExcerpts,
10385 _: &mut Window,
10386 cx: &mut Context<Self>,
10387 ) {
10388 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10389 }
10390
10391 pub fn expand_excerpts_down(
10392 &mut self,
10393 action: &ExpandExcerptsDown,
10394 _: &mut Window,
10395 cx: &mut Context<Self>,
10396 ) {
10397 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10398 }
10399
10400 pub fn expand_excerpts_up(
10401 &mut self,
10402 action: &ExpandExcerptsUp,
10403 _: &mut Window,
10404 cx: &mut Context<Self>,
10405 ) {
10406 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10407 }
10408
10409 pub fn expand_excerpts_for_direction(
10410 &mut self,
10411 lines: u32,
10412 direction: ExpandExcerptDirection,
10413
10414 cx: &mut Context<Self>,
10415 ) {
10416 let selections = self.selections.disjoint_anchors();
10417
10418 let lines = if lines == 0 {
10419 EditorSettings::get_global(cx).expand_excerpt_lines
10420 } else {
10421 lines
10422 };
10423
10424 self.buffer.update(cx, |buffer, cx| {
10425 let snapshot = buffer.snapshot(cx);
10426 let mut excerpt_ids = selections
10427 .iter()
10428 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10429 .collect::<Vec<_>>();
10430 excerpt_ids.sort();
10431 excerpt_ids.dedup();
10432 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10433 })
10434 }
10435
10436 pub fn expand_excerpt(
10437 &mut self,
10438 excerpt: ExcerptId,
10439 direction: ExpandExcerptDirection,
10440 cx: &mut Context<Self>,
10441 ) {
10442 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10443 self.buffer.update(cx, |buffer, cx| {
10444 buffer.expand_excerpts([excerpt], lines, direction, cx)
10445 })
10446 }
10447
10448 pub fn go_to_singleton_buffer_point(
10449 &mut self,
10450 point: Point,
10451 window: &mut Window,
10452 cx: &mut Context<Self>,
10453 ) {
10454 self.go_to_singleton_buffer_range(point..point, window, cx);
10455 }
10456
10457 pub fn go_to_singleton_buffer_range(
10458 &mut self,
10459 range: Range<Point>,
10460 window: &mut Window,
10461 cx: &mut Context<Self>,
10462 ) {
10463 let multibuffer = self.buffer().read(cx);
10464 let Some(buffer) = multibuffer.as_singleton() else {
10465 return;
10466 };
10467 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10468 return;
10469 };
10470 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10471 return;
10472 };
10473 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10474 s.select_anchor_ranges([start..end])
10475 });
10476 }
10477
10478 fn go_to_diagnostic(
10479 &mut self,
10480 _: &GoToDiagnostic,
10481 window: &mut Window,
10482 cx: &mut Context<Self>,
10483 ) {
10484 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10485 }
10486
10487 fn go_to_prev_diagnostic(
10488 &mut self,
10489 _: &GoToPrevDiagnostic,
10490 window: &mut Window,
10491 cx: &mut Context<Self>,
10492 ) {
10493 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10494 }
10495
10496 pub fn go_to_diagnostic_impl(
10497 &mut self,
10498 direction: Direction,
10499 window: &mut Window,
10500 cx: &mut Context<Self>,
10501 ) {
10502 let buffer = self.buffer.read(cx).snapshot(cx);
10503 let selection = self.selections.newest::<usize>(cx);
10504
10505 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10506 if direction == Direction::Next {
10507 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10508 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10509 return;
10510 };
10511 self.activate_diagnostics(
10512 buffer_id,
10513 popover.local_diagnostic.diagnostic.group_id,
10514 window,
10515 cx,
10516 );
10517 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10518 let primary_range_start = active_diagnostics.primary_range.start;
10519 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10520 let mut new_selection = s.newest_anchor().clone();
10521 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10522 s.select_anchors(vec![new_selection.clone()]);
10523 });
10524 self.refresh_inline_completion(false, true, window, cx);
10525 }
10526 return;
10527 }
10528 }
10529
10530 let active_group_id = self
10531 .active_diagnostics
10532 .as_ref()
10533 .map(|active_group| active_group.group_id);
10534 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10535 active_diagnostics
10536 .primary_range
10537 .to_offset(&buffer)
10538 .to_inclusive()
10539 });
10540 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10541 if active_primary_range.contains(&selection.head()) {
10542 *active_primary_range.start()
10543 } else {
10544 selection.head()
10545 }
10546 } else {
10547 selection.head()
10548 };
10549
10550 let snapshot = self.snapshot(window, cx);
10551 let primary_diagnostics_before = buffer
10552 .diagnostics_in_range::<usize>(0..search_start)
10553 .filter(|entry| entry.diagnostic.is_primary)
10554 .filter(|entry| entry.range.start != entry.range.end)
10555 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10556 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10557 .collect::<Vec<_>>();
10558 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10559 primary_diagnostics_before
10560 .iter()
10561 .position(|entry| entry.diagnostic.group_id == active_group_id)
10562 });
10563
10564 let primary_diagnostics_after = buffer
10565 .diagnostics_in_range::<usize>(search_start..buffer.len())
10566 .filter(|entry| entry.diagnostic.is_primary)
10567 .filter(|entry| entry.range.start != entry.range.end)
10568 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10569 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10570 .collect::<Vec<_>>();
10571 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10572 primary_diagnostics_after
10573 .iter()
10574 .enumerate()
10575 .rev()
10576 .find_map(|(i, entry)| {
10577 if entry.diagnostic.group_id == active_group_id {
10578 Some(i)
10579 } else {
10580 None
10581 }
10582 })
10583 });
10584
10585 let next_primary_diagnostic = match direction {
10586 Direction::Prev => primary_diagnostics_before
10587 .iter()
10588 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10589 .rev()
10590 .next(),
10591 Direction::Next => primary_diagnostics_after
10592 .iter()
10593 .skip(
10594 last_same_group_diagnostic_after
10595 .map(|index| index + 1)
10596 .unwrap_or(0),
10597 )
10598 .next(),
10599 };
10600
10601 // Cycle around to the start of the buffer, potentially moving back to the start of
10602 // the currently active diagnostic.
10603 let cycle_around = || match direction {
10604 Direction::Prev => primary_diagnostics_after
10605 .iter()
10606 .rev()
10607 .chain(primary_diagnostics_before.iter().rev())
10608 .next(),
10609 Direction::Next => primary_diagnostics_before
10610 .iter()
10611 .chain(primary_diagnostics_after.iter())
10612 .next(),
10613 };
10614
10615 if let Some((primary_range, group_id)) = next_primary_diagnostic
10616 .or_else(cycle_around)
10617 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10618 {
10619 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10620 return;
10621 };
10622 self.activate_diagnostics(buffer_id, group_id, window, cx);
10623 if self.active_diagnostics.is_some() {
10624 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10625 s.select(vec![Selection {
10626 id: selection.id,
10627 start: primary_range.start,
10628 end: primary_range.start,
10629 reversed: false,
10630 goal: SelectionGoal::None,
10631 }]);
10632 });
10633 self.refresh_inline_completion(false, true, window, cx);
10634 }
10635 }
10636 }
10637
10638 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10639 let snapshot = self.snapshot(window, cx);
10640 let selection = self.selections.newest::<Point>(cx);
10641 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10642 }
10643
10644 fn go_to_hunk_after_position(
10645 &mut self,
10646 snapshot: &EditorSnapshot,
10647 position: Point,
10648 window: &mut Window,
10649 cx: &mut Context<Editor>,
10650 ) -> Option<MultiBufferDiffHunk> {
10651 let mut hunk = snapshot
10652 .buffer_snapshot
10653 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10654 .find(|hunk| hunk.row_range.start.0 > position.row);
10655 if hunk.is_none() {
10656 hunk = snapshot
10657 .buffer_snapshot
10658 .diff_hunks_in_range(Point::zero()..position)
10659 .find(|hunk| hunk.row_range.end.0 < position.row)
10660 }
10661 if let Some(hunk) = &hunk {
10662 let destination = Point::new(hunk.row_range.start.0, 0);
10663 self.unfold_ranges(&[destination..destination], false, false, cx);
10664 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10665 s.select_ranges(vec![destination..destination]);
10666 });
10667 }
10668
10669 hunk
10670 }
10671
10672 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10673 let snapshot = self.snapshot(window, cx);
10674 let selection = self.selections.newest::<Point>(cx);
10675 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10676 }
10677
10678 fn go_to_hunk_before_position(
10679 &mut self,
10680 snapshot: &EditorSnapshot,
10681 position: Point,
10682 window: &mut Window,
10683 cx: &mut Context<Editor>,
10684 ) -> Option<MultiBufferDiffHunk> {
10685 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10686 if hunk.is_none() {
10687 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10688 }
10689 if let Some(hunk) = &hunk {
10690 let destination = Point::new(hunk.row_range.start.0, 0);
10691 self.unfold_ranges(&[destination..destination], false, false, cx);
10692 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10693 s.select_ranges(vec![destination..destination]);
10694 });
10695 }
10696
10697 hunk
10698 }
10699
10700 pub fn go_to_definition(
10701 &mut self,
10702 _: &GoToDefinition,
10703 window: &mut Window,
10704 cx: &mut Context<Self>,
10705 ) -> Task<Result<Navigated>> {
10706 let definition =
10707 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10708 cx.spawn_in(window, |editor, mut cx| async move {
10709 if definition.await? == Navigated::Yes {
10710 return Ok(Navigated::Yes);
10711 }
10712 match editor.update_in(&mut cx, |editor, window, cx| {
10713 editor.find_all_references(&FindAllReferences, window, cx)
10714 })? {
10715 Some(references) => references.await,
10716 None => Ok(Navigated::No),
10717 }
10718 })
10719 }
10720
10721 pub fn go_to_declaration(
10722 &mut self,
10723 _: &GoToDeclaration,
10724 window: &mut Window,
10725 cx: &mut Context<Self>,
10726 ) -> Task<Result<Navigated>> {
10727 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10728 }
10729
10730 pub fn go_to_declaration_split(
10731 &mut self,
10732 _: &GoToDeclaration,
10733 window: &mut Window,
10734 cx: &mut Context<Self>,
10735 ) -> Task<Result<Navigated>> {
10736 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10737 }
10738
10739 pub fn go_to_implementation(
10740 &mut self,
10741 _: &GoToImplementation,
10742 window: &mut Window,
10743 cx: &mut Context<Self>,
10744 ) -> Task<Result<Navigated>> {
10745 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10746 }
10747
10748 pub fn go_to_implementation_split(
10749 &mut self,
10750 _: &GoToImplementationSplit,
10751 window: &mut Window,
10752 cx: &mut Context<Self>,
10753 ) -> Task<Result<Navigated>> {
10754 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10755 }
10756
10757 pub fn go_to_type_definition(
10758 &mut self,
10759 _: &GoToTypeDefinition,
10760 window: &mut Window,
10761 cx: &mut Context<Self>,
10762 ) -> Task<Result<Navigated>> {
10763 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10764 }
10765
10766 pub fn go_to_definition_split(
10767 &mut self,
10768 _: &GoToDefinitionSplit,
10769 window: &mut Window,
10770 cx: &mut Context<Self>,
10771 ) -> Task<Result<Navigated>> {
10772 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10773 }
10774
10775 pub fn go_to_type_definition_split(
10776 &mut self,
10777 _: &GoToTypeDefinitionSplit,
10778 window: &mut Window,
10779 cx: &mut Context<Self>,
10780 ) -> Task<Result<Navigated>> {
10781 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10782 }
10783
10784 fn go_to_definition_of_kind(
10785 &mut self,
10786 kind: GotoDefinitionKind,
10787 split: bool,
10788 window: &mut Window,
10789 cx: &mut Context<Self>,
10790 ) -> Task<Result<Navigated>> {
10791 let Some(provider) = self.semantics_provider.clone() else {
10792 return Task::ready(Ok(Navigated::No));
10793 };
10794 let head = self.selections.newest::<usize>(cx).head();
10795 let buffer = self.buffer.read(cx);
10796 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10797 text_anchor
10798 } else {
10799 return Task::ready(Ok(Navigated::No));
10800 };
10801
10802 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10803 return Task::ready(Ok(Navigated::No));
10804 };
10805
10806 cx.spawn_in(window, |editor, mut cx| async move {
10807 let definitions = definitions.await?;
10808 let navigated = editor
10809 .update_in(&mut cx, |editor, window, cx| {
10810 editor.navigate_to_hover_links(
10811 Some(kind),
10812 definitions
10813 .into_iter()
10814 .filter(|location| {
10815 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10816 })
10817 .map(HoverLink::Text)
10818 .collect::<Vec<_>>(),
10819 split,
10820 window,
10821 cx,
10822 )
10823 })?
10824 .await?;
10825 anyhow::Ok(navigated)
10826 })
10827 }
10828
10829 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10830 let selection = self.selections.newest_anchor();
10831 let head = selection.head();
10832 let tail = selection.tail();
10833
10834 let Some((buffer, start_position)) =
10835 self.buffer.read(cx).text_anchor_for_position(head, cx)
10836 else {
10837 return;
10838 };
10839
10840 let end_position = if head != tail {
10841 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10842 return;
10843 };
10844 Some(pos)
10845 } else {
10846 None
10847 };
10848
10849 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10850 let url = if let Some(end_pos) = end_position {
10851 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10852 } else {
10853 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10854 };
10855
10856 if let Some(url) = url {
10857 editor.update(&mut cx, |_, cx| {
10858 cx.open_url(&url);
10859 })
10860 } else {
10861 Ok(())
10862 }
10863 });
10864
10865 url_finder.detach();
10866 }
10867
10868 pub fn open_selected_filename(
10869 &mut self,
10870 _: &OpenSelectedFilename,
10871 window: &mut Window,
10872 cx: &mut Context<Self>,
10873 ) {
10874 let Some(workspace) = self.workspace() else {
10875 return;
10876 };
10877
10878 let position = self.selections.newest_anchor().head();
10879
10880 let Some((buffer, buffer_position)) =
10881 self.buffer.read(cx).text_anchor_for_position(position, cx)
10882 else {
10883 return;
10884 };
10885
10886 let project = self.project.clone();
10887
10888 cx.spawn_in(window, |_, mut cx| async move {
10889 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10890
10891 if let Some((_, path)) = result {
10892 workspace
10893 .update_in(&mut cx, |workspace, window, cx| {
10894 workspace.open_resolved_path(path, window, cx)
10895 })?
10896 .await?;
10897 }
10898 anyhow::Ok(())
10899 })
10900 .detach();
10901 }
10902
10903 pub(crate) fn navigate_to_hover_links(
10904 &mut self,
10905 kind: Option<GotoDefinitionKind>,
10906 mut definitions: Vec<HoverLink>,
10907 split: bool,
10908 window: &mut Window,
10909 cx: &mut Context<Editor>,
10910 ) -> Task<Result<Navigated>> {
10911 // If there is one definition, just open it directly
10912 if definitions.len() == 1 {
10913 let definition = definitions.pop().unwrap();
10914
10915 enum TargetTaskResult {
10916 Location(Option<Location>),
10917 AlreadyNavigated,
10918 }
10919
10920 let target_task = match definition {
10921 HoverLink::Text(link) => {
10922 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10923 }
10924 HoverLink::InlayHint(lsp_location, server_id) => {
10925 let computation =
10926 self.compute_target_location(lsp_location, server_id, window, cx);
10927 cx.background_spawn(async move {
10928 let location = computation.await?;
10929 Ok(TargetTaskResult::Location(location))
10930 })
10931 }
10932 HoverLink::Url(url) => {
10933 cx.open_url(&url);
10934 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10935 }
10936 HoverLink::File(path) => {
10937 if let Some(workspace) = self.workspace() {
10938 cx.spawn_in(window, |_, mut cx| async move {
10939 workspace
10940 .update_in(&mut cx, |workspace, window, cx| {
10941 workspace.open_resolved_path(path, window, cx)
10942 })?
10943 .await
10944 .map(|_| TargetTaskResult::AlreadyNavigated)
10945 })
10946 } else {
10947 Task::ready(Ok(TargetTaskResult::Location(None)))
10948 }
10949 }
10950 };
10951 cx.spawn_in(window, |editor, mut cx| async move {
10952 let target = match target_task.await.context("target resolution task")? {
10953 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10954 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10955 TargetTaskResult::Location(Some(target)) => target,
10956 };
10957
10958 editor.update_in(&mut cx, |editor, window, cx| {
10959 let Some(workspace) = editor.workspace() else {
10960 return Navigated::No;
10961 };
10962 let pane = workspace.read(cx).active_pane().clone();
10963
10964 let range = target.range.to_point(target.buffer.read(cx));
10965 let range = editor.range_for_match(&range);
10966 let range = collapse_multiline_range(range);
10967
10968 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10969 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10970 } else {
10971 window.defer(cx, move |window, cx| {
10972 let target_editor: Entity<Self> =
10973 workspace.update(cx, |workspace, cx| {
10974 let pane = if split {
10975 workspace.adjacent_pane(window, cx)
10976 } else {
10977 workspace.active_pane().clone()
10978 };
10979
10980 workspace.open_project_item(
10981 pane,
10982 target.buffer.clone(),
10983 true,
10984 true,
10985 window,
10986 cx,
10987 )
10988 });
10989 target_editor.update(cx, |target_editor, cx| {
10990 // When selecting a definition in a different buffer, disable the nav history
10991 // to avoid creating a history entry at the previous cursor location.
10992 pane.update(cx, |pane, _| pane.disable_history());
10993 target_editor.go_to_singleton_buffer_range(range, window, cx);
10994 pane.update(cx, |pane, _| pane.enable_history());
10995 });
10996 });
10997 }
10998 Navigated::Yes
10999 })
11000 })
11001 } else if !definitions.is_empty() {
11002 cx.spawn_in(window, |editor, mut cx| async move {
11003 let (title, location_tasks, workspace) = editor
11004 .update_in(&mut cx, |editor, window, cx| {
11005 let tab_kind = match kind {
11006 Some(GotoDefinitionKind::Implementation) => "Implementations",
11007 _ => "Definitions",
11008 };
11009 let title = definitions
11010 .iter()
11011 .find_map(|definition| match definition {
11012 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11013 let buffer = origin.buffer.read(cx);
11014 format!(
11015 "{} for {}",
11016 tab_kind,
11017 buffer
11018 .text_for_range(origin.range.clone())
11019 .collect::<String>()
11020 )
11021 }),
11022 HoverLink::InlayHint(_, _) => None,
11023 HoverLink::Url(_) => None,
11024 HoverLink::File(_) => None,
11025 })
11026 .unwrap_or(tab_kind.to_string());
11027 let location_tasks = definitions
11028 .into_iter()
11029 .map(|definition| match definition {
11030 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11031 HoverLink::InlayHint(lsp_location, server_id) => editor
11032 .compute_target_location(lsp_location, server_id, window, cx),
11033 HoverLink::Url(_) => Task::ready(Ok(None)),
11034 HoverLink::File(_) => Task::ready(Ok(None)),
11035 })
11036 .collect::<Vec<_>>();
11037 (title, location_tasks, editor.workspace().clone())
11038 })
11039 .context("location tasks preparation")?;
11040
11041 let locations = future::join_all(location_tasks)
11042 .await
11043 .into_iter()
11044 .filter_map(|location| location.transpose())
11045 .collect::<Result<_>>()
11046 .context("location tasks")?;
11047
11048 let Some(workspace) = workspace else {
11049 return Ok(Navigated::No);
11050 };
11051 let opened = workspace
11052 .update_in(&mut cx, |workspace, window, cx| {
11053 Self::open_locations_in_multibuffer(
11054 workspace,
11055 locations,
11056 title,
11057 split,
11058 MultibufferSelectionMode::First,
11059 window,
11060 cx,
11061 )
11062 })
11063 .ok();
11064
11065 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11066 })
11067 } else {
11068 Task::ready(Ok(Navigated::No))
11069 }
11070 }
11071
11072 fn compute_target_location(
11073 &self,
11074 lsp_location: lsp::Location,
11075 server_id: LanguageServerId,
11076 window: &mut Window,
11077 cx: &mut Context<Self>,
11078 ) -> Task<anyhow::Result<Option<Location>>> {
11079 let Some(project) = self.project.clone() else {
11080 return Task::ready(Ok(None));
11081 };
11082
11083 cx.spawn_in(window, move |editor, mut cx| async move {
11084 let location_task = editor.update(&mut cx, |_, cx| {
11085 project.update(cx, |project, cx| {
11086 let language_server_name = project
11087 .language_server_statuses(cx)
11088 .find(|(id, _)| server_id == *id)
11089 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11090 language_server_name.map(|language_server_name| {
11091 project.open_local_buffer_via_lsp(
11092 lsp_location.uri.clone(),
11093 server_id,
11094 language_server_name,
11095 cx,
11096 )
11097 })
11098 })
11099 })?;
11100 let location = match location_task {
11101 Some(task) => Some({
11102 let target_buffer_handle = task.await.context("open local buffer")?;
11103 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11104 let target_start = target_buffer
11105 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11106 let target_end = target_buffer
11107 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11108 target_buffer.anchor_after(target_start)
11109 ..target_buffer.anchor_before(target_end)
11110 })?;
11111 Location {
11112 buffer: target_buffer_handle,
11113 range,
11114 }
11115 }),
11116 None => None,
11117 };
11118 Ok(location)
11119 })
11120 }
11121
11122 pub fn find_all_references(
11123 &mut self,
11124 _: &FindAllReferences,
11125 window: &mut Window,
11126 cx: &mut Context<Self>,
11127 ) -> Option<Task<Result<Navigated>>> {
11128 let selection = self.selections.newest::<usize>(cx);
11129 let multi_buffer = self.buffer.read(cx);
11130 let head = selection.head();
11131
11132 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11133 let head_anchor = multi_buffer_snapshot.anchor_at(
11134 head,
11135 if head < selection.tail() {
11136 Bias::Right
11137 } else {
11138 Bias::Left
11139 },
11140 );
11141
11142 match self
11143 .find_all_references_task_sources
11144 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11145 {
11146 Ok(_) => {
11147 log::info!(
11148 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11149 );
11150 return None;
11151 }
11152 Err(i) => {
11153 self.find_all_references_task_sources.insert(i, head_anchor);
11154 }
11155 }
11156
11157 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11158 let workspace = self.workspace()?;
11159 let project = workspace.read(cx).project().clone();
11160 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11161 Some(cx.spawn_in(window, |editor, mut cx| async move {
11162 let _cleanup = defer({
11163 let mut cx = cx.clone();
11164 move || {
11165 let _ = editor.update(&mut cx, |editor, _| {
11166 if let Ok(i) =
11167 editor
11168 .find_all_references_task_sources
11169 .binary_search_by(|anchor| {
11170 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11171 })
11172 {
11173 editor.find_all_references_task_sources.remove(i);
11174 }
11175 });
11176 }
11177 });
11178
11179 let locations = references.await?;
11180 if locations.is_empty() {
11181 return anyhow::Ok(Navigated::No);
11182 }
11183
11184 workspace.update_in(&mut cx, |workspace, window, cx| {
11185 let title = locations
11186 .first()
11187 .as_ref()
11188 .map(|location| {
11189 let buffer = location.buffer.read(cx);
11190 format!(
11191 "References to `{}`",
11192 buffer
11193 .text_for_range(location.range.clone())
11194 .collect::<String>()
11195 )
11196 })
11197 .unwrap();
11198 Self::open_locations_in_multibuffer(
11199 workspace,
11200 locations,
11201 title,
11202 false,
11203 MultibufferSelectionMode::First,
11204 window,
11205 cx,
11206 );
11207 Navigated::Yes
11208 })
11209 }))
11210 }
11211
11212 /// Opens a multibuffer with the given project locations in it
11213 pub fn open_locations_in_multibuffer(
11214 workspace: &mut Workspace,
11215 mut locations: Vec<Location>,
11216 title: String,
11217 split: bool,
11218 multibuffer_selection_mode: MultibufferSelectionMode,
11219 window: &mut Window,
11220 cx: &mut Context<Workspace>,
11221 ) {
11222 // If there are multiple definitions, open them in a multibuffer
11223 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11224 let mut locations = locations.into_iter().peekable();
11225 let mut ranges = Vec::new();
11226 let capability = workspace.project().read(cx).capability();
11227
11228 let excerpt_buffer = cx.new(|cx| {
11229 let mut multibuffer = MultiBuffer::new(capability);
11230 while let Some(location) = locations.next() {
11231 let buffer = location.buffer.read(cx);
11232 let mut ranges_for_buffer = Vec::new();
11233 let range = location.range.to_offset(buffer);
11234 ranges_for_buffer.push(range.clone());
11235
11236 while let Some(next_location) = locations.peek() {
11237 if next_location.buffer == location.buffer {
11238 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11239 locations.next();
11240 } else {
11241 break;
11242 }
11243 }
11244
11245 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11246 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11247 location.buffer.clone(),
11248 ranges_for_buffer,
11249 DEFAULT_MULTIBUFFER_CONTEXT,
11250 cx,
11251 ))
11252 }
11253
11254 multibuffer.with_title(title)
11255 });
11256
11257 let editor = cx.new(|cx| {
11258 Editor::for_multibuffer(
11259 excerpt_buffer,
11260 Some(workspace.project().clone()),
11261 true,
11262 window,
11263 cx,
11264 )
11265 });
11266 editor.update(cx, |editor, cx| {
11267 match multibuffer_selection_mode {
11268 MultibufferSelectionMode::First => {
11269 if let Some(first_range) = ranges.first() {
11270 editor.change_selections(None, window, cx, |selections| {
11271 selections.clear_disjoint();
11272 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11273 });
11274 }
11275 editor.highlight_background::<Self>(
11276 &ranges,
11277 |theme| theme.editor_highlighted_line_background,
11278 cx,
11279 );
11280 }
11281 MultibufferSelectionMode::All => {
11282 editor.change_selections(None, window, cx, |selections| {
11283 selections.clear_disjoint();
11284 selections.select_anchor_ranges(ranges);
11285 });
11286 }
11287 }
11288 editor.register_buffers_with_language_servers(cx);
11289 });
11290
11291 let item = Box::new(editor);
11292 let item_id = item.item_id();
11293
11294 if split {
11295 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11296 } else {
11297 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11298 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11299 pane.close_current_preview_item(window, cx)
11300 } else {
11301 None
11302 }
11303 });
11304 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11305 }
11306 workspace.active_pane().update(cx, |pane, cx| {
11307 pane.set_preview_item_id(Some(item_id), cx);
11308 });
11309 }
11310
11311 pub fn rename(
11312 &mut self,
11313 _: &Rename,
11314 window: &mut Window,
11315 cx: &mut Context<Self>,
11316 ) -> Option<Task<Result<()>>> {
11317 use language::ToOffset as _;
11318
11319 let provider = self.semantics_provider.clone()?;
11320 let selection = self.selections.newest_anchor().clone();
11321 let (cursor_buffer, cursor_buffer_position) = self
11322 .buffer
11323 .read(cx)
11324 .text_anchor_for_position(selection.head(), cx)?;
11325 let (tail_buffer, cursor_buffer_position_end) = self
11326 .buffer
11327 .read(cx)
11328 .text_anchor_for_position(selection.tail(), cx)?;
11329 if tail_buffer != cursor_buffer {
11330 return None;
11331 }
11332
11333 let snapshot = cursor_buffer.read(cx).snapshot();
11334 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11335 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11336 let prepare_rename = provider
11337 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11338 .unwrap_or_else(|| Task::ready(Ok(None)));
11339 drop(snapshot);
11340
11341 Some(cx.spawn_in(window, |this, mut cx| async move {
11342 let rename_range = if let Some(range) = prepare_rename.await? {
11343 Some(range)
11344 } else {
11345 this.update(&mut cx, |this, cx| {
11346 let buffer = this.buffer.read(cx).snapshot(cx);
11347 let mut buffer_highlights = this
11348 .document_highlights_for_position(selection.head(), &buffer)
11349 .filter(|highlight| {
11350 highlight.start.excerpt_id == selection.head().excerpt_id
11351 && highlight.end.excerpt_id == selection.head().excerpt_id
11352 });
11353 buffer_highlights
11354 .next()
11355 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11356 })?
11357 };
11358 if let Some(rename_range) = rename_range {
11359 this.update_in(&mut cx, |this, window, cx| {
11360 let snapshot = cursor_buffer.read(cx).snapshot();
11361 let rename_buffer_range = rename_range.to_offset(&snapshot);
11362 let cursor_offset_in_rename_range =
11363 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11364 let cursor_offset_in_rename_range_end =
11365 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11366
11367 this.take_rename(false, window, cx);
11368 let buffer = this.buffer.read(cx).read(cx);
11369 let cursor_offset = selection.head().to_offset(&buffer);
11370 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11371 let rename_end = rename_start + rename_buffer_range.len();
11372 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11373 let mut old_highlight_id = None;
11374 let old_name: Arc<str> = buffer
11375 .chunks(rename_start..rename_end, true)
11376 .map(|chunk| {
11377 if old_highlight_id.is_none() {
11378 old_highlight_id = chunk.syntax_highlight_id;
11379 }
11380 chunk.text
11381 })
11382 .collect::<String>()
11383 .into();
11384
11385 drop(buffer);
11386
11387 // Position the selection in the rename editor so that it matches the current selection.
11388 this.show_local_selections = false;
11389 let rename_editor = cx.new(|cx| {
11390 let mut editor = Editor::single_line(window, cx);
11391 editor.buffer.update(cx, |buffer, cx| {
11392 buffer.edit([(0..0, old_name.clone())], None, cx)
11393 });
11394 let rename_selection_range = match cursor_offset_in_rename_range
11395 .cmp(&cursor_offset_in_rename_range_end)
11396 {
11397 Ordering::Equal => {
11398 editor.select_all(&SelectAll, window, cx);
11399 return editor;
11400 }
11401 Ordering::Less => {
11402 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11403 }
11404 Ordering::Greater => {
11405 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11406 }
11407 };
11408 if rename_selection_range.end > old_name.len() {
11409 editor.select_all(&SelectAll, window, cx);
11410 } else {
11411 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11412 s.select_ranges([rename_selection_range]);
11413 });
11414 }
11415 editor
11416 });
11417 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11418 if e == &EditorEvent::Focused {
11419 cx.emit(EditorEvent::FocusedIn)
11420 }
11421 })
11422 .detach();
11423
11424 let write_highlights =
11425 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11426 let read_highlights =
11427 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11428 let ranges = write_highlights
11429 .iter()
11430 .flat_map(|(_, ranges)| ranges.iter())
11431 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11432 .cloned()
11433 .collect();
11434
11435 this.highlight_text::<Rename>(
11436 ranges,
11437 HighlightStyle {
11438 fade_out: Some(0.6),
11439 ..Default::default()
11440 },
11441 cx,
11442 );
11443 let rename_focus_handle = rename_editor.focus_handle(cx);
11444 window.focus(&rename_focus_handle);
11445 let block_id = this.insert_blocks(
11446 [BlockProperties {
11447 style: BlockStyle::Flex,
11448 placement: BlockPlacement::Below(range.start),
11449 height: 1,
11450 render: Arc::new({
11451 let rename_editor = rename_editor.clone();
11452 move |cx: &mut BlockContext| {
11453 let mut text_style = cx.editor_style.text.clone();
11454 if let Some(highlight_style) = old_highlight_id
11455 .and_then(|h| h.style(&cx.editor_style.syntax))
11456 {
11457 text_style = text_style.highlight(highlight_style);
11458 }
11459 div()
11460 .block_mouse_down()
11461 .pl(cx.anchor_x)
11462 .child(EditorElement::new(
11463 &rename_editor,
11464 EditorStyle {
11465 background: cx.theme().system().transparent,
11466 local_player: cx.editor_style.local_player,
11467 text: text_style,
11468 scrollbar_width: cx.editor_style.scrollbar_width,
11469 syntax: cx.editor_style.syntax.clone(),
11470 status: cx.editor_style.status.clone(),
11471 inlay_hints_style: HighlightStyle {
11472 font_weight: Some(FontWeight::BOLD),
11473 ..make_inlay_hints_style(cx.app)
11474 },
11475 inline_completion_styles: make_suggestion_styles(
11476 cx.app,
11477 ),
11478 ..EditorStyle::default()
11479 },
11480 ))
11481 .into_any_element()
11482 }
11483 }),
11484 priority: 0,
11485 }],
11486 Some(Autoscroll::fit()),
11487 cx,
11488 )[0];
11489 this.pending_rename = Some(RenameState {
11490 range,
11491 old_name,
11492 editor: rename_editor,
11493 block_id,
11494 });
11495 })?;
11496 }
11497
11498 Ok(())
11499 }))
11500 }
11501
11502 pub fn confirm_rename(
11503 &mut self,
11504 _: &ConfirmRename,
11505 window: &mut Window,
11506 cx: &mut Context<Self>,
11507 ) -> Option<Task<Result<()>>> {
11508 let rename = self.take_rename(false, window, cx)?;
11509 let workspace = self.workspace()?.downgrade();
11510 let (buffer, start) = self
11511 .buffer
11512 .read(cx)
11513 .text_anchor_for_position(rename.range.start, cx)?;
11514 let (end_buffer, _) = self
11515 .buffer
11516 .read(cx)
11517 .text_anchor_for_position(rename.range.end, cx)?;
11518 if buffer != end_buffer {
11519 return None;
11520 }
11521
11522 let old_name = rename.old_name;
11523 let new_name = rename.editor.read(cx).text(cx);
11524
11525 let rename = self.semantics_provider.as_ref()?.perform_rename(
11526 &buffer,
11527 start,
11528 new_name.clone(),
11529 cx,
11530 )?;
11531
11532 Some(cx.spawn_in(window, |editor, mut cx| async move {
11533 let project_transaction = rename.await?;
11534 Self::open_project_transaction(
11535 &editor,
11536 workspace,
11537 project_transaction,
11538 format!("Rename: {} → {}", old_name, new_name),
11539 cx.clone(),
11540 )
11541 .await?;
11542
11543 editor.update(&mut cx, |editor, cx| {
11544 editor.refresh_document_highlights(cx);
11545 })?;
11546 Ok(())
11547 }))
11548 }
11549
11550 fn take_rename(
11551 &mut self,
11552 moving_cursor: bool,
11553 window: &mut Window,
11554 cx: &mut Context<Self>,
11555 ) -> Option<RenameState> {
11556 let rename = self.pending_rename.take()?;
11557 if rename.editor.focus_handle(cx).is_focused(window) {
11558 window.focus(&self.focus_handle);
11559 }
11560
11561 self.remove_blocks(
11562 [rename.block_id].into_iter().collect(),
11563 Some(Autoscroll::fit()),
11564 cx,
11565 );
11566 self.clear_highlights::<Rename>(cx);
11567 self.show_local_selections = true;
11568
11569 if moving_cursor {
11570 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11571 editor.selections.newest::<usize>(cx).head()
11572 });
11573
11574 // Update the selection to match the position of the selection inside
11575 // the rename editor.
11576 let snapshot = self.buffer.read(cx).read(cx);
11577 let rename_range = rename.range.to_offset(&snapshot);
11578 let cursor_in_editor = snapshot
11579 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11580 .min(rename_range.end);
11581 drop(snapshot);
11582
11583 self.change_selections(None, window, cx, |s| {
11584 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11585 });
11586 } else {
11587 self.refresh_document_highlights(cx);
11588 }
11589
11590 Some(rename)
11591 }
11592
11593 pub fn pending_rename(&self) -> Option<&RenameState> {
11594 self.pending_rename.as_ref()
11595 }
11596
11597 fn format(
11598 &mut self,
11599 _: &Format,
11600 window: &mut Window,
11601 cx: &mut Context<Self>,
11602 ) -> Option<Task<Result<()>>> {
11603 let project = match &self.project {
11604 Some(project) => project.clone(),
11605 None => return None,
11606 };
11607
11608 Some(self.perform_format(
11609 project,
11610 FormatTrigger::Manual,
11611 FormatTarget::Buffers,
11612 window,
11613 cx,
11614 ))
11615 }
11616
11617 fn format_selections(
11618 &mut self,
11619 _: &FormatSelections,
11620 window: &mut Window,
11621 cx: &mut Context<Self>,
11622 ) -> Option<Task<Result<()>>> {
11623 let project = match &self.project {
11624 Some(project) => project.clone(),
11625 None => return None,
11626 };
11627
11628 let ranges = self
11629 .selections
11630 .all_adjusted(cx)
11631 .into_iter()
11632 .map(|selection| selection.range())
11633 .collect_vec();
11634
11635 Some(self.perform_format(
11636 project,
11637 FormatTrigger::Manual,
11638 FormatTarget::Ranges(ranges),
11639 window,
11640 cx,
11641 ))
11642 }
11643
11644 fn perform_format(
11645 &mut self,
11646 project: Entity<Project>,
11647 trigger: FormatTrigger,
11648 target: FormatTarget,
11649 window: &mut Window,
11650 cx: &mut Context<Self>,
11651 ) -> Task<Result<()>> {
11652 let buffer = self.buffer.clone();
11653 let (buffers, target) = match target {
11654 FormatTarget::Buffers => {
11655 let mut buffers = buffer.read(cx).all_buffers();
11656 if trigger == FormatTrigger::Save {
11657 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11658 }
11659 (buffers, LspFormatTarget::Buffers)
11660 }
11661 FormatTarget::Ranges(selection_ranges) => {
11662 let multi_buffer = buffer.read(cx);
11663 let snapshot = multi_buffer.read(cx);
11664 let mut buffers = HashSet::default();
11665 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11666 BTreeMap::new();
11667 for selection_range in selection_ranges {
11668 for (buffer, buffer_range, _) in
11669 snapshot.range_to_buffer_ranges(selection_range)
11670 {
11671 let buffer_id = buffer.remote_id();
11672 let start = buffer.anchor_before(buffer_range.start);
11673 let end = buffer.anchor_after(buffer_range.end);
11674 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11675 buffer_id_to_ranges
11676 .entry(buffer_id)
11677 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11678 .or_insert_with(|| vec![start..end]);
11679 }
11680 }
11681 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11682 }
11683 };
11684
11685 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11686 let format = project.update(cx, |project, cx| {
11687 project.format(buffers, target, true, trigger, cx)
11688 });
11689
11690 cx.spawn_in(window, |_, mut cx| async move {
11691 let transaction = futures::select_biased! {
11692 () = timeout => {
11693 log::warn!("timed out waiting for formatting");
11694 None
11695 }
11696 transaction = format.log_err().fuse() => transaction,
11697 };
11698
11699 buffer
11700 .update(&mut cx, |buffer, cx| {
11701 if let Some(transaction) = transaction {
11702 if !buffer.is_singleton() {
11703 buffer.push_transaction(&transaction.0, cx);
11704 }
11705 }
11706
11707 cx.notify();
11708 })
11709 .ok();
11710
11711 Ok(())
11712 })
11713 }
11714
11715 fn restart_language_server(
11716 &mut self,
11717 _: &RestartLanguageServer,
11718 _: &mut Window,
11719 cx: &mut Context<Self>,
11720 ) {
11721 if let Some(project) = self.project.clone() {
11722 self.buffer.update(cx, |multi_buffer, cx| {
11723 project.update(cx, |project, cx| {
11724 project.restart_language_servers_for_buffers(
11725 multi_buffer.all_buffers().into_iter().collect(),
11726 cx,
11727 );
11728 });
11729 })
11730 }
11731 }
11732
11733 fn cancel_language_server_work(
11734 workspace: &mut Workspace,
11735 _: &actions::CancelLanguageServerWork,
11736 _: &mut Window,
11737 cx: &mut Context<Workspace>,
11738 ) {
11739 let project = workspace.project();
11740 let buffers = workspace
11741 .active_item(cx)
11742 .and_then(|item| item.act_as::<Editor>(cx))
11743 .map_or(HashSet::default(), |editor| {
11744 editor.read(cx).buffer.read(cx).all_buffers()
11745 });
11746 project.update(cx, |project, cx| {
11747 project.cancel_language_server_work_for_buffers(buffers, cx);
11748 });
11749 }
11750
11751 fn show_character_palette(
11752 &mut self,
11753 _: &ShowCharacterPalette,
11754 window: &mut Window,
11755 _: &mut Context<Self>,
11756 ) {
11757 window.show_character_palette();
11758 }
11759
11760 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11761 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11762 let buffer = self.buffer.read(cx).snapshot(cx);
11763 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11764 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11765 let is_valid = buffer
11766 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11767 .any(|entry| {
11768 entry.diagnostic.is_primary
11769 && !entry.range.is_empty()
11770 && entry.range.start == primary_range_start
11771 && entry.diagnostic.message == active_diagnostics.primary_message
11772 });
11773
11774 if is_valid != active_diagnostics.is_valid {
11775 active_diagnostics.is_valid = is_valid;
11776 let mut new_styles = HashMap::default();
11777 for (block_id, diagnostic) in &active_diagnostics.blocks {
11778 new_styles.insert(
11779 *block_id,
11780 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11781 );
11782 }
11783 self.display_map.update(cx, |display_map, _cx| {
11784 display_map.replace_blocks(new_styles)
11785 });
11786 }
11787 }
11788 }
11789
11790 fn activate_diagnostics(
11791 &mut self,
11792 buffer_id: BufferId,
11793 group_id: usize,
11794 window: &mut Window,
11795 cx: &mut Context<Self>,
11796 ) {
11797 self.dismiss_diagnostics(cx);
11798 let snapshot = self.snapshot(window, cx);
11799 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11800 let buffer = self.buffer.read(cx).snapshot(cx);
11801
11802 let mut primary_range = None;
11803 let mut primary_message = None;
11804 let diagnostic_group = buffer
11805 .diagnostic_group(buffer_id, group_id)
11806 .filter_map(|entry| {
11807 let start = entry.range.start;
11808 let end = entry.range.end;
11809 if snapshot.is_line_folded(MultiBufferRow(start.row))
11810 && (start.row == end.row
11811 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11812 {
11813 return None;
11814 }
11815 if entry.diagnostic.is_primary {
11816 primary_range = Some(entry.range.clone());
11817 primary_message = Some(entry.diagnostic.message.clone());
11818 }
11819 Some(entry)
11820 })
11821 .collect::<Vec<_>>();
11822 let primary_range = primary_range?;
11823 let primary_message = primary_message?;
11824
11825 let blocks = display_map
11826 .insert_blocks(
11827 diagnostic_group.iter().map(|entry| {
11828 let diagnostic = entry.diagnostic.clone();
11829 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11830 BlockProperties {
11831 style: BlockStyle::Fixed,
11832 placement: BlockPlacement::Below(
11833 buffer.anchor_after(entry.range.start),
11834 ),
11835 height: message_height,
11836 render: diagnostic_block_renderer(diagnostic, None, true, true),
11837 priority: 0,
11838 }
11839 }),
11840 cx,
11841 )
11842 .into_iter()
11843 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11844 .collect();
11845
11846 Some(ActiveDiagnosticGroup {
11847 primary_range: buffer.anchor_before(primary_range.start)
11848 ..buffer.anchor_after(primary_range.end),
11849 primary_message,
11850 group_id,
11851 blocks,
11852 is_valid: true,
11853 })
11854 });
11855 }
11856
11857 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11858 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11859 self.display_map.update(cx, |display_map, cx| {
11860 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11861 });
11862 cx.notify();
11863 }
11864 }
11865
11866 pub fn set_selections_from_remote(
11867 &mut self,
11868 selections: Vec<Selection<Anchor>>,
11869 pending_selection: Option<Selection<Anchor>>,
11870 window: &mut Window,
11871 cx: &mut Context<Self>,
11872 ) {
11873 let old_cursor_position = self.selections.newest_anchor().head();
11874 self.selections.change_with(cx, |s| {
11875 s.select_anchors(selections);
11876 if let Some(pending_selection) = pending_selection {
11877 s.set_pending(pending_selection, SelectMode::Character);
11878 } else {
11879 s.clear_pending();
11880 }
11881 });
11882 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11883 }
11884
11885 fn push_to_selection_history(&mut self) {
11886 self.selection_history.push(SelectionHistoryEntry {
11887 selections: self.selections.disjoint_anchors(),
11888 select_next_state: self.select_next_state.clone(),
11889 select_prev_state: self.select_prev_state.clone(),
11890 add_selections_state: self.add_selections_state.clone(),
11891 });
11892 }
11893
11894 pub fn transact(
11895 &mut self,
11896 window: &mut Window,
11897 cx: &mut Context<Self>,
11898 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11899 ) -> Option<TransactionId> {
11900 self.start_transaction_at(Instant::now(), window, cx);
11901 update(self, window, cx);
11902 self.end_transaction_at(Instant::now(), cx)
11903 }
11904
11905 pub fn start_transaction_at(
11906 &mut self,
11907 now: Instant,
11908 window: &mut Window,
11909 cx: &mut Context<Self>,
11910 ) {
11911 self.end_selection(window, cx);
11912 if let Some(tx_id) = self
11913 .buffer
11914 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11915 {
11916 self.selection_history
11917 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11918 cx.emit(EditorEvent::TransactionBegun {
11919 transaction_id: tx_id,
11920 })
11921 }
11922 }
11923
11924 pub fn end_transaction_at(
11925 &mut self,
11926 now: Instant,
11927 cx: &mut Context<Self>,
11928 ) -> Option<TransactionId> {
11929 if let Some(transaction_id) = self
11930 .buffer
11931 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11932 {
11933 if let Some((_, end_selections)) =
11934 self.selection_history.transaction_mut(transaction_id)
11935 {
11936 *end_selections = Some(self.selections.disjoint_anchors());
11937 } else {
11938 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11939 }
11940
11941 cx.emit(EditorEvent::Edited { transaction_id });
11942 Some(transaction_id)
11943 } else {
11944 None
11945 }
11946 }
11947
11948 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11949 if self.selection_mark_mode {
11950 self.change_selections(None, window, cx, |s| {
11951 s.move_with(|_, sel| {
11952 sel.collapse_to(sel.head(), SelectionGoal::None);
11953 });
11954 })
11955 }
11956 self.selection_mark_mode = true;
11957 cx.notify();
11958 }
11959
11960 pub fn swap_selection_ends(
11961 &mut self,
11962 _: &actions::SwapSelectionEnds,
11963 window: &mut Window,
11964 cx: &mut Context<Self>,
11965 ) {
11966 self.change_selections(None, window, cx, |s| {
11967 s.move_with(|_, sel| {
11968 if sel.start != sel.end {
11969 sel.reversed = !sel.reversed
11970 }
11971 });
11972 });
11973 self.request_autoscroll(Autoscroll::newest(), cx);
11974 cx.notify();
11975 }
11976
11977 pub fn toggle_fold(
11978 &mut self,
11979 _: &actions::ToggleFold,
11980 window: &mut Window,
11981 cx: &mut Context<Self>,
11982 ) {
11983 if self.is_singleton(cx) {
11984 let selection = self.selections.newest::<Point>(cx);
11985
11986 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11987 let range = if selection.is_empty() {
11988 let point = selection.head().to_display_point(&display_map);
11989 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11990 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11991 .to_point(&display_map);
11992 start..end
11993 } else {
11994 selection.range()
11995 };
11996 if display_map.folds_in_range(range).next().is_some() {
11997 self.unfold_lines(&Default::default(), window, cx)
11998 } else {
11999 self.fold(&Default::default(), window, cx)
12000 }
12001 } else {
12002 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12003 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12004 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12005 .map(|(snapshot, _, _)| snapshot.remote_id())
12006 .collect();
12007
12008 for buffer_id in buffer_ids {
12009 if self.is_buffer_folded(buffer_id, cx) {
12010 self.unfold_buffer(buffer_id, cx);
12011 } else {
12012 self.fold_buffer(buffer_id, cx);
12013 }
12014 }
12015 }
12016 }
12017
12018 pub fn toggle_fold_recursive(
12019 &mut self,
12020 _: &actions::ToggleFoldRecursive,
12021 window: &mut Window,
12022 cx: &mut Context<Self>,
12023 ) {
12024 let selection = self.selections.newest::<Point>(cx);
12025
12026 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12027 let range = if selection.is_empty() {
12028 let point = selection.head().to_display_point(&display_map);
12029 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12030 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12031 .to_point(&display_map);
12032 start..end
12033 } else {
12034 selection.range()
12035 };
12036 if display_map.folds_in_range(range).next().is_some() {
12037 self.unfold_recursive(&Default::default(), window, cx)
12038 } else {
12039 self.fold_recursive(&Default::default(), window, cx)
12040 }
12041 }
12042
12043 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12044 if self.is_singleton(cx) {
12045 let mut to_fold = Vec::new();
12046 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12047 let selections = self.selections.all_adjusted(cx);
12048
12049 for selection in selections {
12050 let range = selection.range().sorted();
12051 let buffer_start_row = range.start.row;
12052
12053 if range.start.row != range.end.row {
12054 let mut found = false;
12055 let mut row = range.start.row;
12056 while row <= range.end.row {
12057 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12058 {
12059 found = true;
12060 row = crease.range().end.row + 1;
12061 to_fold.push(crease);
12062 } else {
12063 row += 1
12064 }
12065 }
12066 if found {
12067 continue;
12068 }
12069 }
12070
12071 for row in (0..=range.start.row).rev() {
12072 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12073 if crease.range().end.row >= buffer_start_row {
12074 to_fold.push(crease);
12075 if row <= range.start.row {
12076 break;
12077 }
12078 }
12079 }
12080 }
12081 }
12082
12083 self.fold_creases(to_fold, true, window, cx);
12084 } else {
12085 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12086
12087 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12088 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12089 .map(|(snapshot, _, _)| snapshot.remote_id())
12090 .collect();
12091 for buffer_id in buffer_ids {
12092 self.fold_buffer(buffer_id, cx);
12093 }
12094 }
12095 }
12096
12097 fn fold_at_level(
12098 &mut self,
12099 fold_at: &FoldAtLevel,
12100 window: &mut Window,
12101 cx: &mut Context<Self>,
12102 ) {
12103 if !self.buffer.read(cx).is_singleton() {
12104 return;
12105 }
12106
12107 let fold_at_level = fold_at.0;
12108 let snapshot = self.buffer.read(cx).snapshot(cx);
12109 let mut to_fold = Vec::new();
12110 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12111
12112 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12113 while start_row < end_row {
12114 match self
12115 .snapshot(window, cx)
12116 .crease_for_buffer_row(MultiBufferRow(start_row))
12117 {
12118 Some(crease) => {
12119 let nested_start_row = crease.range().start.row + 1;
12120 let nested_end_row = crease.range().end.row;
12121
12122 if current_level < fold_at_level {
12123 stack.push((nested_start_row, nested_end_row, current_level + 1));
12124 } else if current_level == fold_at_level {
12125 to_fold.push(crease);
12126 }
12127
12128 start_row = nested_end_row + 1;
12129 }
12130 None => start_row += 1,
12131 }
12132 }
12133 }
12134
12135 self.fold_creases(to_fold, true, window, cx);
12136 }
12137
12138 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12139 if self.buffer.read(cx).is_singleton() {
12140 let mut fold_ranges = Vec::new();
12141 let snapshot = self.buffer.read(cx).snapshot(cx);
12142
12143 for row in 0..snapshot.max_row().0 {
12144 if let Some(foldable_range) = self
12145 .snapshot(window, cx)
12146 .crease_for_buffer_row(MultiBufferRow(row))
12147 {
12148 fold_ranges.push(foldable_range);
12149 }
12150 }
12151
12152 self.fold_creases(fold_ranges, true, window, cx);
12153 } else {
12154 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12155 editor
12156 .update_in(&mut cx, |editor, _, cx| {
12157 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12158 editor.fold_buffer(buffer_id, cx);
12159 }
12160 })
12161 .ok();
12162 });
12163 }
12164 }
12165
12166 pub fn fold_function_bodies(
12167 &mut self,
12168 _: &actions::FoldFunctionBodies,
12169 window: &mut Window,
12170 cx: &mut Context<Self>,
12171 ) {
12172 let snapshot = self.buffer.read(cx).snapshot(cx);
12173
12174 let ranges = snapshot
12175 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12176 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12177 .collect::<Vec<_>>();
12178
12179 let creases = ranges
12180 .into_iter()
12181 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12182 .collect();
12183
12184 self.fold_creases(creases, true, window, cx);
12185 }
12186
12187 pub fn fold_recursive(
12188 &mut self,
12189 _: &actions::FoldRecursive,
12190 window: &mut Window,
12191 cx: &mut Context<Self>,
12192 ) {
12193 let mut to_fold = Vec::new();
12194 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12195 let selections = self.selections.all_adjusted(cx);
12196
12197 for selection in selections {
12198 let range = selection.range().sorted();
12199 let buffer_start_row = range.start.row;
12200
12201 if range.start.row != range.end.row {
12202 let mut found = false;
12203 for row in range.start.row..=range.end.row {
12204 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12205 found = true;
12206 to_fold.push(crease);
12207 }
12208 }
12209 if found {
12210 continue;
12211 }
12212 }
12213
12214 for row in (0..=range.start.row).rev() {
12215 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12216 if crease.range().end.row >= buffer_start_row {
12217 to_fold.push(crease);
12218 } else {
12219 break;
12220 }
12221 }
12222 }
12223 }
12224
12225 self.fold_creases(to_fold, true, window, cx);
12226 }
12227
12228 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12229 let buffer_row = fold_at.buffer_row;
12230 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12231
12232 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12233 let autoscroll = self
12234 .selections
12235 .all::<Point>(cx)
12236 .iter()
12237 .any(|selection| crease.range().overlaps(&selection.range()));
12238
12239 self.fold_creases(vec![crease], autoscroll, window, cx);
12240 }
12241 }
12242
12243 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12244 if self.is_singleton(cx) {
12245 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12246 let buffer = &display_map.buffer_snapshot;
12247 let selections = self.selections.all::<Point>(cx);
12248 let ranges = selections
12249 .iter()
12250 .map(|s| {
12251 let range = s.display_range(&display_map).sorted();
12252 let mut start = range.start.to_point(&display_map);
12253 let mut end = range.end.to_point(&display_map);
12254 start.column = 0;
12255 end.column = buffer.line_len(MultiBufferRow(end.row));
12256 start..end
12257 })
12258 .collect::<Vec<_>>();
12259
12260 self.unfold_ranges(&ranges, true, true, cx);
12261 } else {
12262 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12263 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12264 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12265 .map(|(snapshot, _, _)| snapshot.remote_id())
12266 .collect();
12267 for buffer_id in buffer_ids {
12268 self.unfold_buffer(buffer_id, cx);
12269 }
12270 }
12271 }
12272
12273 pub fn unfold_recursive(
12274 &mut self,
12275 _: &UnfoldRecursive,
12276 _window: &mut Window,
12277 cx: &mut Context<Self>,
12278 ) {
12279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12280 let selections = self.selections.all::<Point>(cx);
12281 let ranges = selections
12282 .iter()
12283 .map(|s| {
12284 let mut range = s.display_range(&display_map).sorted();
12285 *range.start.column_mut() = 0;
12286 *range.end.column_mut() = display_map.line_len(range.end.row());
12287 let start = range.start.to_point(&display_map);
12288 let end = range.end.to_point(&display_map);
12289 start..end
12290 })
12291 .collect::<Vec<_>>();
12292
12293 self.unfold_ranges(&ranges, true, true, cx);
12294 }
12295
12296 pub fn unfold_at(
12297 &mut self,
12298 unfold_at: &UnfoldAt,
12299 _window: &mut Window,
12300 cx: &mut Context<Self>,
12301 ) {
12302 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12303
12304 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12305 ..Point::new(
12306 unfold_at.buffer_row.0,
12307 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12308 );
12309
12310 let autoscroll = self
12311 .selections
12312 .all::<Point>(cx)
12313 .iter()
12314 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12315
12316 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12317 }
12318
12319 pub fn unfold_all(
12320 &mut self,
12321 _: &actions::UnfoldAll,
12322 _window: &mut Window,
12323 cx: &mut Context<Self>,
12324 ) {
12325 if self.buffer.read(cx).is_singleton() {
12326 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12327 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12328 } else {
12329 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12330 editor
12331 .update(&mut cx, |editor, cx| {
12332 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12333 editor.unfold_buffer(buffer_id, cx);
12334 }
12335 })
12336 .ok();
12337 });
12338 }
12339 }
12340
12341 pub fn fold_selected_ranges(
12342 &mut self,
12343 _: &FoldSelectedRanges,
12344 window: &mut Window,
12345 cx: &mut Context<Self>,
12346 ) {
12347 let selections = self.selections.all::<Point>(cx);
12348 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12349 let line_mode = self.selections.line_mode;
12350 let ranges = selections
12351 .into_iter()
12352 .map(|s| {
12353 if line_mode {
12354 let start = Point::new(s.start.row, 0);
12355 let end = Point::new(
12356 s.end.row,
12357 display_map
12358 .buffer_snapshot
12359 .line_len(MultiBufferRow(s.end.row)),
12360 );
12361 Crease::simple(start..end, display_map.fold_placeholder.clone())
12362 } else {
12363 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12364 }
12365 })
12366 .collect::<Vec<_>>();
12367 self.fold_creases(ranges, true, window, cx);
12368 }
12369
12370 pub fn fold_ranges<T: ToOffset + Clone>(
12371 &mut self,
12372 ranges: Vec<Range<T>>,
12373 auto_scroll: bool,
12374 window: &mut Window,
12375 cx: &mut Context<Self>,
12376 ) {
12377 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12378 let ranges = ranges
12379 .into_iter()
12380 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12381 .collect::<Vec<_>>();
12382 self.fold_creases(ranges, auto_scroll, window, cx);
12383 }
12384
12385 pub fn fold_creases<T: ToOffset + Clone>(
12386 &mut self,
12387 creases: Vec<Crease<T>>,
12388 auto_scroll: bool,
12389 window: &mut Window,
12390 cx: &mut Context<Self>,
12391 ) {
12392 if creases.is_empty() {
12393 return;
12394 }
12395
12396 let mut buffers_affected = HashSet::default();
12397 let multi_buffer = self.buffer().read(cx);
12398 for crease in &creases {
12399 if let Some((_, buffer, _)) =
12400 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12401 {
12402 buffers_affected.insert(buffer.read(cx).remote_id());
12403 };
12404 }
12405
12406 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12407
12408 if auto_scroll {
12409 self.request_autoscroll(Autoscroll::fit(), cx);
12410 }
12411
12412 cx.notify();
12413
12414 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12415 // Clear diagnostics block when folding a range that contains it.
12416 let snapshot = self.snapshot(window, cx);
12417 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12418 drop(snapshot);
12419 self.active_diagnostics = Some(active_diagnostics);
12420 self.dismiss_diagnostics(cx);
12421 } else {
12422 self.active_diagnostics = Some(active_diagnostics);
12423 }
12424 }
12425
12426 self.scrollbar_marker_state.dirty = true;
12427 }
12428
12429 /// Removes any folds whose ranges intersect any of the given ranges.
12430 pub fn unfold_ranges<T: ToOffset + Clone>(
12431 &mut self,
12432 ranges: &[Range<T>],
12433 inclusive: bool,
12434 auto_scroll: bool,
12435 cx: &mut Context<Self>,
12436 ) {
12437 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12438 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12439 });
12440 }
12441
12442 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12443 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12444 return;
12445 }
12446 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12447 self.display_map
12448 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12449 cx.emit(EditorEvent::BufferFoldToggled {
12450 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12451 folded: true,
12452 });
12453 cx.notify();
12454 }
12455
12456 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12457 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12458 return;
12459 }
12460 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12461 self.display_map.update(cx, |display_map, cx| {
12462 display_map.unfold_buffer(buffer_id, cx);
12463 });
12464 cx.emit(EditorEvent::BufferFoldToggled {
12465 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12466 folded: false,
12467 });
12468 cx.notify();
12469 }
12470
12471 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12472 self.display_map.read(cx).is_buffer_folded(buffer)
12473 }
12474
12475 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12476 self.display_map.read(cx).folded_buffers()
12477 }
12478
12479 /// Removes any folds with the given ranges.
12480 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12481 &mut self,
12482 ranges: &[Range<T>],
12483 type_id: TypeId,
12484 auto_scroll: bool,
12485 cx: &mut Context<Self>,
12486 ) {
12487 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12488 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12489 });
12490 }
12491
12492 fn remove_folds_with<T: ToOffset + Clone>(
12493 &mut self,
12494 ranges: &[Range<T>],
12495 auto_scroll: bool,
12496 cx: &mut Context<Self>,
12497 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12498 ) {
12499 if ranges.is_empty() {
12500 return;
12501 }
12502
12503 let mut buffers_affected = HashSet::default();
12504 let multi_buffer = self.buffer().read(cx);
12505 for range in ranges {
12506 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12507 buffers_affected.insert(buffer.read(cx).remote_id());
12508 };
12509 }
12510
12511 self.display_map.update(cx, update);
12512
12513 if auto_scroll {
12514 self.request_autoscroll(Autoscroll::fit(), cx);
12515 }
12516
12517 cx.notify();
12518 self.scrollbar_marker_state.dirty = true;
12519 self.active_indent_guides_state.dirty = true;
12520 }
12521
12522 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12523 self.display_map.read(cx).fold_placeholder.clone()
12524 }
12525
12526 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12527 self.buffer.update(cx, |buffer, cx| {
12528 buffer.set_all_diff_hunks_expanded(cx);
12529 });
12530 }
12531
12532 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12533 self.distinguish_unstaged_diff_hunks = true;
12534 }
12535
12536 pub fn expand_all_diff_hunks(
12537 &mut self,
12538 _: &ExpandAllHunkDiffs,
12539 _window: &mut Window,
12540 cx: &mut Context<Self>,
12541 ) {
12542 self.buffer.update(cx, |buffer, cx| {
12543 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12544 });
12545 }
12546
12547 pub fn toggle_selected_diff_hunks(
12548 &mut self,
12549 _: &ToggleSelectedDiffHunks,
12550 _window: &mut Window,
12551 cx: &mut Context<Self>,
12552 ) {
12553 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12554 self.toggle_diff_hunks_in_ranges(ranges, cx);
12555 }
12556
12557 fn diff_hunks_in_ranges<'a>(
12558 &'a self,
12559 ranges: &'a [Range<Anchor>],
12560 buffer: &'a MultiBufferSnapshot,
12561 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12562 ranges.iter().flat_map(move |range| {
12563 let end_excerpt_id = range.end.excerpt_id;
12564 let range = range.to_point(buffer);
12565 let mut peek_end = range.end;
12566 if range.end.row < buffer.max_row().0 {
12567 peek_end = Point::new(range.end.row + 1, 0);
12568 }
12569 buffer
12570 .diff_hunks_in_range(range.start..peek_end)
12571 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12572 })
12573 }
12574
12575 pub fn has_stageable_diff_hunks_in_ranges(
12576 &self,
12577 ranges: &[Range<Anchor>],
12578 snapshot: &MultiBufferSnapshot,
12579 ) -> bool {
12580 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12581 hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12582 }
12583
12584 pub fn toggle_staged_selected_diff_hunks(
12585 &mut self,
12586 _: &::git::ToggleStaged,
12587 _window: &mut Window,
12588 cx: &mut Context<Self>,
12589 ) {
12590 let snapshot = self.buffer.read(cx).snapshot(cx);
12591 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12592 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
12593 self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
12594 }
12595
12596 pub fn stage_and_next(
12597 &mut self,
12598 _: &::git::StageAndNext,
12599 window: &mut Window,
12600 cx: &mut Context<Self>,
12601 ) {
12602 let head = self.selections.newest_anchor().head();
12603 self.stage_or_unstage_diff_hunks(true, &[head..head], cx);
12604 self.go_to_next_hunk(&Default::default(), window, cx);
12605 }
12606
12607 pub fn unstage_and_next(
12608 &mut self,
12609 _: &::git::UnstageAndNext,
12610 window: &mut Window,
12611 cx: &mut Context<Self>,
12612 ) {
12613 let head = self.selections.newest_anchor().head();
12614 self.stage_or_unstage_diff_hunks(false, &[head..head], cx);
12615 self.go_to_next_hunk(&Default::default(), window, cx);
12616 }
12617
12618 pub fn stage_or_unstage_diff_hunks(
12619 &mut self,
12620 stage: bool,
12621 ranges: &[Range<Anchor>],
12622 cx: &mut Context<Self>,
12623 ) {
12624 let snapshot = self.buffer.read(cx).snapshot(cx);
12625 let Some(project) = &self.project else {
12626 return;
12627 };
12628
12629 let chunk_by = self
12630 .diff_hunks_in_ranges(&ranges, &snapshot)
12631 .chunk_by(|hunk| hunk.buffer_id);
12632 for (buffer_id, hunks) in &chunk_by {
12633 Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
12634 }
12635 }
12636
12637 fn do_stage_or_unstage(
12638 project: &Entity<Project>,
12639 stage: bool,
12640 buffer_id: BufferId,
12641 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
12642 snapshot: &MultiBufferSnapshot,
12643 cx: &mut Context<Self>,
12644 ) {
12645 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12646 log::debug!("no buffer for id");
12647 return;
12648 };
12649 let buffer = buffer.read(cx).snapshot();
12650 let Some((repo, path)) = project
12651 .read(cx)
12652 .repository_and_path_for_buffer_id(buffer_id, cx)
12653 else {
12654 log::debug!("no git repo for buffer id");
12655 return;
12656 };
12657 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12658 log::debug!("no diff for buffer id");
12659 return;
12660 };
12661 let Some(secondary_diff) = diff.secondary_diff() else {
12662 log::debug!("no secondary diff for buffer id");
12663 return;
12664 };
12665
12666 let edits = diff.secondary_edits_for_stage_or_unstage(
12667 stage,
12668 hunks.filter_map(|hunk| {
12669 if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
12670 return None;
12671 } else if !stage
12672 && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12673 {
12674 return None;
12675 }
12676 Some((
12677 hunk.diff_base_byte_range.clone(),
12678 hunk.secondary_diff_base_byte_range.clone(),
12679 hunk.buffer_range.clone(),
12680 ))
12681 }),
12682 &buffer,
12683 );
12684
12685 let Some(index_base) = secondary_diff
12686 .base_text()
12687 .map(|snapshot| snapshot.text.as_rope().clone())
12688 else {
12689 log::debug!("no index base");
12690 return;
12691 };
12692 let index_buffer = cx.new(|cx| {
12693 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12694 });
12695 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12696 index_buffer.edit(edits, None, cx);
12697 index_buffer.snapshot().as_rope().to_string()
12698 });
12699 let new_index_text = if new_index_text.is_empty()
12700 && (diff.is_single_insertion
12701 || buffer
12702 .file()
12703 .map_or(false, |file| file.disk_state() == DiskState::New))
12704 {
12705 log::debug!("removing from index");
12706 None
12707 } else {
12708 Some(new_index_text)
12709 };
12710
12711 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12712 }
12713
12714 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12715 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12716 self.buffer
12717 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12718 }
12719
12720 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12721 self.buffer.update(cx, |buffer, cx| {
12722 let ranges = vec![Anchor::min()..Anchor::max()];
12723 if !buffer.all_diff_hunks_expanded()
12724 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12725 {
12726 buffer.collapse_diff_hunks(ranges, cx);
12727 true
12728 } else {
12729 false
12730 }
12731 })
12732 }
12733
12734 fn toggle_diff_hunks_in_ranges(
12735 &mut self,
12736 ranges: Vec<Range<Anchor>>,
12737 cx: &mut Context<'_, Editor>,
12738 ) {
12739 self.buffer.update(cx, |buffer, cx| {
12740 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12741 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12742 })
12743 }
12744
12745 fn toggle_diff_hunks_in_ranges_narrow(
12746 &mut self,
12747 ranges: Vec<Range<Anchor>>,
12748 cx: &mut Context<'_, Editor>,
12749 ) {
12750 self.buffer.update(cx, |buffer, cx| {
12751 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12752 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12753 })
12754 }
12755
12756 pub(crate) fn apply_all_diff_hunks(
12757 &mut self,
12758 _: &ApplyAllDiffHunks,
12759 window: &mut Window,
12760 cx: &mut Context<Self>,
12761 ) {
12762 let buffers = self.buffer.read(cx).all_buffers();
12763 for branch_buffer in buffers {
12764 branch_buffer.update(cx, |branch_buffer, cx| {
12765 branch_buffer.merge_into_base(Vec::new(), cx);
12766 });
12767 }
12768
12769 if let Some(project) = self.project.clone() {
12770 self.save(true, project, window, cx).detach_and_log_err(cx);
12771 }
12772 }
12773
12774 pub(crate) fn apply_selected_diff_hunks(
12775 &mut self,
12776 _: &ApplyDiffHunk,
12777 window: &mut Window,
12778 cx: &mut Context<Self>,
12779 ) {
12780 let snapshot = self.snapshot(window, cx);
12781 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12782 let mut ranges_by_buffer = HashMap::default();
12783 self.transact(window, cx, |editor, _window, cx| {
12784 for hunk in hunks {
12785 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12786 ranges_by_buffer
12787 .entry(buffer.clone())
12788 .or_insert_with(Vec::new)
12789 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12790 }
12791 }
12792
12793 for (buffer, ranges) in ranges_by_buffer {
12794 buffer.update(cx, |buffer, cx| {
12795 buffer.merge_into_base(ranges, cx);
12796 });
12797 }
12798 });
12799
12800 if let Some(project) = self.project.clone() {
12801 self.save(true, project, window, cx).detach_and_log_err(cx);
12802 }
12803 }
12804
12805 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12806 if hovered != self.gutter_hovered {
12807 self.gutter_hovered = hovered;
12808 cx.notify();
12809 }
12810 }
12811
12812 pub fn insert_blocks(
12813 &mut self,
12814 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12815 autoscroll: Option<Autoscroll>,
12816 cx: &mut Context<Self>,
12817 ) -> Vec<CustomBlockId> {
12818 let blocks = self
12819 .display_map
12820 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12821 if let Some(autoscroll) = autoscroll {
12822 self.request_autoscroll(autoscroll, cx);
12823 }
12824 cx.notify();
12825 blocks
12826 }
12827
12828 pub fn resize_blocks(
12829 &mut self,
12830 heights: HashMap<CustomBlockId, u32>,
12831 autoscroll: Option<Autoscroll>,
12832 cx: &mut Context<Self>,
12833 ) {
12834 self.display_map
12835 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12836 if let Some(autoscroll) = autoscroll {
12837 self.request_autoscroll(autoscroll, cx);
12838 }
12839 cx.notify();
12840 }
12841
12842 pub fn replace_blocks(
12843 &mut self,
12844 renderers: HashMap<CustomBlockId, RenderBlock>,
12845 autoscroll: Option<Autoscroll>,
12846 cx: &mut Context<Self>,
12847 ) {
12848 self.display_map
12849 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12850 if let Some(autoscroll) = autoscroll {
12851 self.request_autoscroll(autoscroll, cx);
12852 }
12853 cx.notify();
12854 }
12855
12856 pub fn remove_blocks(
12857 &mut self,
12858 block_ids: HashSet<CustomBlockId>,
12859 autoscroll: Option<Autoscroll>,
12860 cx: &mut Context<Self>,
12861 ) {
12862 self.display_map.update(cx, |display_map, cx| {
12863 display_map.remove_blocks(block_ids, cx)
12864 });
12865 if let Some(autoscroll) = autoscroll {
12866 self.request_autoscroll(autoscroll, cx);
12867 }
12868 cx.notify();
12869 }
12870
12871 pub fn row_for_block(
12872 &self,
12873 block_id: CustomBlockId,
12874 cx: &mut Context<Self>,
12875 ) -> Option<DisplayRow> {
12876 self.display_map
12877 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12878 }
12879
12880 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12881 self.focused_block = Some(focused_block);
12882 }
12883
12884 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12885 self.focused_block.take()
12886 }
12887
12888 pub fn insert_creases(
12889 &mut self,
12890 creases: impl IntoIterator<Item = Crease<Anchor>>,
12891 cx: &mut Context<Self>,
12892 ) -> Vec<CreaseId> {
12893 self.display_map
12894 .update(cx, |map, cx| map.insert_creases(creases, cx))
12895 }
12896
12897 pub fn remove_creases(
12898 &mut self,
12899 ids: impl IntoIterator<Item = CreaseId>,
12900 cx: &mut Context<Self>,
12901 ) {
12902 self.display_map
12903 .update(cx, |map, cx| map.remove_creases(ids, cx));
12904 }
12905
12906 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12907 self.display_map
12908 .update(cx, |map, cx| map.snapshot(cx))
12909 .longest_row()
12910 }
12911
12912 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12913 self.display_map
12914 .update(cx, |map, cx| map.snapshot(cx))
12915 .max_point()
12916 }
12917
12918 pub fn text(&self, cx: &App) -> String {
12919 self.buffer.read(cx).read(cx).text()
12920 }
12921
12922 pub fn is_empty(&self, cx: &App) -> bool {
12923 self.buffer.read(cx).read(cx).is_empty()
12924 }
12925
12926 pub fn text_option(&self, cx: &App) -> Option<String> {
12927 let text = self.text(cx);
12928 let text = text.trim();
12929
12930 if text.is_empty() {
12931 return None;
12932 }
12933
12934 Some(text.to_string())
12935 }
12936
12937 pub fn set_text(
12938 &mut self,
12939 text: impl Into<Arc<str>>,
12940 window: &mut Window,
12941 cx: &mut Context<Self>,
12942 ) {
12943 self.transact(window, cx, |this, _, cx| {
12944 this.buffer
12945 .read(cx)
12946 .as_singleton()
12947 .expect("you can only call set_text on editors for singleton buffers")
12948 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12949 });
12950 }
12951
12952 pub fn display_text(&self, cx: &mut App) -> String {
12953 self.display_map
12954 .update(cx, |map, cx| map.snapshot(cx))
12955 .text()
12956 }
12957
12958 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12959 let mut wrap_guides = smallvec::smallvec![];
12960
12961 if self.show_wrap_guides == Some(false) {
12962 return wrap_guides;
12963 }
12964
12965 let settings = self.buffer.read(cx).settings_at(0, cx);
12966 if settings.show_wrap_guides {
12967 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12968 wrap_guides.push((soft_wrap as usize, true));
12969 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12970 wrap_guides.push((soft_wrap as usize, true));
12971 }
12972 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12973 }
12974
12975 wrap_guides
12976 }
12977
12978 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12979 let settings = self.buffer.read(cx).settings_at(0, cx);
12980 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12981 match mode {
12982 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12983 SoftWrap::None
12984 }
12985 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12986 language_settings::SoftWrap::PreferredLineLength => {
12987 SoftWrap::Column(settings.preferred_line_length)
12988 }
12989 language_settings::SoftWrap::Bounded => {
12990 SoftWrap::Bounded(settings.preferred_line_length)
12991 }
12992 }
12993 }
12994
12995 pub fn set_soft_wrap_mode(
12996 &mut self,
12997 mode: language_settings::SoftWrap,
12998
12999 cx: &mut Context<Self>,
13000 ) {
13001 self.soft_wrap_mode_override = Some(mode);
13002 cx.notify();
13003 }
13004
13005 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13006 self.text_style_refinement = Some(style);
13007 }
13008
13009 /// called by the Element so we know what style we were most recently rendered with.
13010 pub(crate) fn set_style(
13011 &mut self,
13012 style: EditorStyle,
13013 window: &mut Window,
13014 cx: &mut Context<Self>,
13015 ) {
13016 let rem_size = window.rem_size();
13017 self.display_map.update(cx, |map, cx| {
13018 map.set_font(
13019 style.text.font(),
13020 style.text.font_size.to_pixels(rem_size),
13021 cx,
13022 )
13023 });
13024 self.style = Some(style);
13025 }
13026
13027 pub fn style(&self) -> Option<&EditorStyle> {
13028 self.style.as_ref()
13029 }
13030
13031 // Called by the element. This method is not designed to be called outside of the editor
13032 // element's layout code because it does not notify when rewrapping is computed synchronously.
13033 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13034 self.display_map
13035 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13036 }
13037
13038 pub fn set_soft_wrap(&mut self) {
13039 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13040 }
13041
13042 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13043 if self.soft_wrap_mode_override.is_some() {
13044 self.soft_wrap_mode_override.take();
13045 } else {
13046 let soft_wrap = match self.soft_wrap_mode(cx) {
13047 SoftWrap::GitDiff => return,
13048 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13049 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13050 language_settings::SoftWrap::None
13051 }
13052 };
13053 self.soft_wrap_mode_override = Some(soft_wrap);
13054 }
13055 cx.notify();
13056 }
13057
13058 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13059 let Some(workspace) = self.workspace() else {
13060 return;
13061 };
13062 let fs = workspace.read(cx).app_state().fs.clone();
13063 let current_show = TabBarSettings::get_global(cx).show;
13064 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13065 setting.show = Some(!current_show);
13066 });
13067 }
13068
13069 pub fn toggle_indent_guides(
13070 &mut self,
13071 _: &ToggleIndentGuides,
13072 _: &mut Window,
13073 cx: &mut Context<Self>,
13074 ) {
13075 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13076 self.buffer
13077 .read(cx)
13078 .settings_at(0, cx)
13079 .indent_guides
13080 .enabled
13081 });
13082 self.show_indent_guides = Some(!currently_enabled);
13083 cx.notify();
13084 }
13085
13086 fn should_show_indent_guides(&self) -> Option<bool> {
13087 self.show_indent_guides
13088 }
13089
13090 pub fn toggle_line_numbers(
13091 &mut self,
13092 _: &ToggleLineNumbers,
13093 _: &mut Window,
13094 cx: &mut Context<Self>,
13095 ) {
13096 let mut editor_settings = EditorSettings::get_global(cx).clone();
13097 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13098 EditorSettings::override_global(editor_settings, cx);
13099 }
13100
13101 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13102 self.use_relative_line_numbers
13103 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13104 }
13105
13106 pub fn toggle_relative_line_numbers(
13107 &mut self,
13108 _: &ToggleRelativeLineNumbers,
13109 _: &mut Window,
13110 cx: &mut Context<Self>,
13111 ) {
13112 let is_relative = self.should_use_relative_line_numbers(cx);
13113 self.set_relative_line_number(Some(!is_relative), cx)
13114 }
13115
13116 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13117 self.use_relative_line_numbers = is_relative;
13118 cx.notify();
13119 }
13120
13121 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13122 self.show_gutter = show_gutter;
13123 cx.notify();
13124 }
13125
13126 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13127 self.show_scrollbars = show_scrollbars;
13128 cx.notify();
13129 }
13130
13131 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13132 self.show_line_numbers = Some(show_line_numbers);
13133 cx.notify();
13134 }
13135
13136 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13137 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13138 cx.notify();
13139 }
13140
13141 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13142 self.show_code_actions = Some(show_code_actions);
13143 cx.notify();
13144 }
13145
13146 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13147 self.show_runnables = Some(show_runnables);
13148 cx.notify();
13149 }
13150
13151 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13152 if self.display_map.read(cx).masked != masked {
13153 self.display_map.update(cx, |map, _| map.masked = masked);
13154 }
13155 cx.notify()
13156 }
13157
13158 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13159 self.show_wrap_guides = Some(show_wrap_guides);
13160 cx.notify();
13161 }
13162
13163 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13164 self.show_indent_guides = Some(show_indent_guides);
13165 cx.notify();
13166 }
13167
13168 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13169 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13170 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13171 if let Some(dir) = file.abs_path(cx).parent() {
13172 return Some(dir.to_owned());
13173 }
13174 }
13175
13176 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13177 return Some(project_path.path.to_path_buf());
13178 }
13179 }
13180
13181 None
13182 }
13183
13184 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13185 self.active_excerpt(cx)?
13186 .1
13187 .read(cx)
13188 .file()
13189 .and_then(|f| f.as_local())
13190 }
13191
13192 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13193 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13194 let buffer = buffer.read(cx);
13195 if let Some(project_path) = buffer.project_path(cx) {
13196 let project = self.project.as_ref()?.read(cx);
13197 project.absolute_path(&project_path, cx)
13198 } else {
13199 buffer
13200 .file()
13201 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13202 }
13203 })
13204 }
13205
13206 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13207 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13208 let project_path = buffer.read(cx).project_path(cx)?;
13209 let project = self.project.as_ref()?.read(cx);
13210 let entry = project.entry_for_path(&project_path, cx)?;
13211 let path = entry.path.to_path_buf();
13212 Some(path)
13213 })
13214 }
13215
13216 pub fn reveal_in_finder(
13217 &mut self,
13218 _: &RevealInFileManager,
13219 _window: &mut Window,
13220 cx: &mut Context<Self>,
13221 ) {
13222 if let Some(target) = self.target_file(cx) {
13223 cx.reveal_path(&target.abs_path(cx));
13224 }
13225 }
13226
13227 pub fn copy_path(
13228 &mut self,
13229 _: &zed_actions::workspace::CopyPath,
13230 _window: &mut Window,
13231 cx: &mut Context<Self>,
13232 ) {
13233 if let Some(path) = self.target_file_abs_path(cx) {
13234 if let Some(path) = path.to_str() {
13235 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13236 }
13237 }
13238 }
13239
13240 pub fn copy_relative_path(
13241 &mut self,
13242 _: &zed_actions::workspace::CopyRelativePath,
13243 _window: &mut Window,
13244 cx: &mut Context<Self>,
13245 ) {
13246 if let Some(path) = self.target_file_path(cx) {
13247 if let Some(path) = path.to_str() {
13248 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13249 }
13250 }
13251 }
13252
13253 pub fn copy_file_name_without_extension(
13254 &mut self,
13255 _: &CopyFileNameWithoutExtension,
13256 _: &mut Window,
13257 cx: &mut Context<Self>,
13258 ) {
13259 if let Some(file) = self.target_file(cx) {
13260 if let Some(file_stem) = file.path().file_stem() {
13261 if let Some(name) = file_stem.to_str() {
13262 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13263 }
13264 }
13265 }
13266 }
13267
13268 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13269 if let Some(file) = self.target_file(cx) {
13270 if let Some(file_name) = file.path().file_name() {
13271 if let Some(name) = file_name.to_str() {
13272 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13273 }
13274 }
13275 }
13276 }
13277
13278 pub fn toggle_git_blame(
13279 &mut self,
13280 _: &ToggleGitBlame,
13281 window: &mut Window,
13282 cx: &mut Context<Self>,
13283 ) {
13284 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13285
13286 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13287 self.start_git_blame(true, window, cx);
13288 }
13289
13290 cx.notify();
13291 }
13292
13293 pub fn toggle_git_blame_inline(
13294 &mut self,
13295 _: &ToggleGitBlameInline,
13296 window: &mut Window,
13297 cx: &mut Context<Self>,
13298 ) {
13299 self.toggle_git_blame_inline_internal(true, window, cx);
13300 cx.notify();
13301 }
13302
13303 pub fn git_blame_inline_enabled(&self) -> bool {
13304 self.git_blame_inline_enabled
13305 }
13306
13307 pub fn toggle_selection_menu(
13308 &mut self,
13309 _: &ToggleSelectionMenu,
13310 _: &mut Window,
13311 cx: &mut Context<Self>,
13312 ) {
13313 self.show_selection_menu = self
13314 .show_selection_menu
13315 .map(|show_selections_menu| !show_selections_menu)
13316 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13317
13318 cx.notify();
13319 }
13320
13321 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13322 self.show_selection_menu
13323 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13324 }
13325
13326 fn start_git_blame(
13327 &mut self,
13328 user_triggered: bool,
13329 window: &mut Window,
13330 cx: &mut Context<Self>,
13331 ) {
13332 if let Some(project) = self.project.as_ref() {
13333 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13334 return;
13335 };
13336
13337 if buffer.read(cx).file().is_none() {
13338 return;
13339 }
13340
13341 let focused = self.focus_handle(cx).contains_focused(window, cx);
13342
13343 let project = project.clone();
13344 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13345 self.blame_subscription =
13346 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13347 self.blame = Some(blame);
13348 }
13349 }
13350
13351 fn toggle_git_blame_inline_internal(
13352 &mut self,
13353 user_triggered: bool,
13354 window: &mut Window,
13355 cx: &mut Context<Self>,
13356 ) {
13357 if self.git_blame_inline_enabled {
13358 self.git_blame_inline_enabled = false;
13359 self.show_git_blame_inline = false;
13360 self.show_git_blame_inline_delay_task.take();
13361 } else {
13362 self.git_blame_inline_enabled = true;
13363 self.start_git_blame_inline(user_triggered, window, cx);
13364 }
13365
13366 cx.notify();
13367 }
13368
13369 fn start_git_blame_inline(
13370 &mut self,
13371 user_triggered: bool,
13372 window: &mut Window,
13373 cx: &mut Context<Self>,
13374 ) {
13375 self.start_git_blame(user_triggered, window, cx);
13376
13377 if ProjectSettings::get_global(cx)
13378 .git
13379 .inline_blame_delay()
13380 .is_some()
13381 {
13382 self.start_inline_blame_timer(window, cx);
13383 } else {
13384 self.show_git_blame_inline = true
13385 }
13386 }
13387
13388 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13389 self.blame.as_ref()
13390 }
13391
13392 pub fn show_git_blame_gutter(&self) -> bool {
13393 self.show_git_blame_gutter
13394 }
13395
13396 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13397 self.show_git_blame_gutter && self.has_blame_entries(cx)
13398 }
13399
13400 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13401 self.show_git_blame_inline
13402 && (self.focus_handle.is_focused(window)
13403 || self
13404 .git_blame_inline_tooltip
13405 .as_ref()
13406 .and_then(|t| t.upgrade())
13407 .is_some())
13408 && !self.newest_selection_head_on_empty_line(cx)
13409 && self.has_blame_entries(cx)
13410 }
13411
13412 fn has_blame_entries(&self, cx: &App) -> bool {
13413 self.blame()
13414 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13415 }
13416
13417 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13418 let cursor_anchor = self.selections.newest_anchor().head();
13419
13420 let snapshot = self.buffer.read(cx).snapshot(cx);
13421 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13422
13423 snapshot.line_len(buffer_row) == 0
13424 }
13425
13426 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13427 let buffer_and_selection = maybe!({
13428 let selection = self.selections.newest::<Point>(cx);
13429 let selection_range = selection.range();
13430
13431 let multi_buffer = self.buffer().read(cx);
13432 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13433 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13434
13435 let (buffer, range, _) = if selection.reversed {
13436 buffer_ranges.first()
13437 } else {
13438 buffer_ranges.last()
13439 }?;
13440
13441 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13442 ..text::ToPoint::to_point(&range.end, &buffer).row;
13443 Some((
13444 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13445 selection,
13446 ))
13447 });
13448
13449 let Some((buffer, selection)) = buffer_and_selection else {
13450 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13451 };
13452
13453 let Some(project) = self.project.as_ref() else {
13454 return Task::ready(Err(anyhow!("editor does not have project")));
13455 };
13456
13457 project.update(cx, |project, cx| {
13458 project.get_permalink_to_line(&buffer, selection, cx)
13459 })
13460 }
13461
13462 pub fn copy_permalink_to_line(
13463 &mut self,
13464 _: &CopyPermalinkToLine,
13465 window: &mut Window,
13466 cx: &mut Context<Self>,
13467 ) {
13468 let permalink_task = self.get_permalink_to_line(cx);
13469 let workspace = self.workspace();
13470
13471 cx.spawn_in(window, |_, mut cx| async move {
13472 match permalink_task.await {
13473 Ok(permalink) => {
13474 cx.update(|_, cx| {
13475 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13476 })
13477 .ok();
13478 }
13479 Err(err) => {
13480 let message = format!("Failed to copy permalink: {err}");
13481
13482 Err::<(), anyhow::Error>(err).log_err();
13483
13484 if let Some(workspace) = workspace {
13485 workspace
13486 .update_in(&mut cx, |workspace, _, cx| {
13487 struct CopyPermalinkToLine;
13488
13489 workspace.show_toast(
13490 Toast::new(
13491 NotificationId::unique::<CopyPermalinkToLine>(),
13492 message,
13493 ),
13494 cx,
13495 )
13496 })
13497 .ok();
13498 }
13499 }
13500 }
13501 })
13502 .detach();
13503 }
13504
13505 pub fn copy_file_location(
13506 &mut self,
13507 _: &CopyFileLocation,
13508 _: &mut Window,
13509 cx: &mut Context<Self>,
13510 ) {
13511 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13512 if let Some(file) = self.target_file(cx) {
13513 if let Some(path) = file.path().to_str() {
13514 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13515 }
13516 }
13517 }
13518
13519 pub fn open_permalink_to_line(
13520 &mut self,
13521 _: &OpenPermalinkToLine,
13522 window: &mut Window,
13523 cx: &mut Context<Self>,
13524 ) {
13525 let permalink_task = self.get_permalink_to_line(cx);
13526 let workspace = self.workspace();
13527
13528 cx.spawn_in(window, |_, mut cx| async move {
13529 match permalink_task.await {
13530 Ok(permalink) => {
13531 cx.update(|_, cx| {
13532 cx.open_url(permalink.as_ref());
13533 })
13534 .ok();
13535 }
13536 Err(err) => {
13537 let message = format!("Failed to open permalink: {err}");
13538
13539 Err::<(), anyhow::Error>(err).log_err();
13540
13541 if let Some(workspace) = workspace {
13542 workspace
13543 .update(&mut cx, |workspace, cx| {
13544 struct OpenPermalinkToLine;
13545
13546 workspace.show_toast(
13547 Toast::new(
13548 NotificationId::unique::<OpenPermalinkToLine>(),
13549 message,
13550 ),
13551 cx,
13552 )
13553 })
13554 .ok();
13555 }
13556 }
13557 }
13558 })
13559 .detach();
13560 }
13561
13562 pub fn insert_uuid_v4(
13563 &mut self,
13564 _: &InsertUuidV4,
13565 window: &mut Window,
13566 cx: &mut Context<Self>,
13567 ) {
13568 self.insert_uuid(UuidVersion::V4, window, cx);
13569 }
13570
13571 pub fn insert_uuid_v7(
13572 &mut self,
13573 _: &InsertUuidV7,
13574 window: &mut Window,
13575 cx: &mut Context<Self>,
13576 ) {
13577 self.insert_uuid(UuidVersion::V7, window, cx);
13578 }
13579
13580 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13581 self.transact(window, cx, |this, window, cx| {
13582 let edits = this
13583 .selections
13584 .all::<Point>(cx)
13585 .into_iter()
13586 .map(|selection| {
13587 let uuid = match version {
13588 UuidVersion::V4 => uuid::Uuid::new_v4(),
13589 UuidVersion::V7 => uuid::Uuid::now_v7(),
13590 };
13591
13592 (selection.range(), uuid.to_string())
13593 });
13594 this.edit(edits, cx);
13595 this.refresh_inline_completion(true, false, window, cx);
13596 });
13597 }
13598
13599 pub fn open_selections_in_multibuffer(
13600 &mut self,
13601 _: &OpenSelectionsInMultibuffer,
13602 window: &mut Window,
13603 cx: &mut Context<Self>,
13604 ) {
13605 let multibuffer = self.buffer.read(cx);
13606
13607 let Some(buffer) = multibuffer.as_singleton() else {
13608 return;
13609 };
13610
13611 let Some(workspace) = self.workspace() else {
13612 return;
13613 };
13614
13615 let locations = self
13616 .selections
13617 .disjoint_anchors()
13618 .iter()
13619 .map(|range| Location {
13620 buffer: buffer.clone(),
13621 range: range.start.text_anchor..range.end.text_anchor,
13622 })
13623 .collect::<Vec<_>>();
13624
13625 let title = multibuffer.title(cx).to_string();
13626
13627 cx.spawn_in(window, |_, mut cx| async move {
13628 workspace.update_in(&mut cx, |workspace, window, cx| {
13629 Self::open_locations_in_multibuffer(
13630 workspace,
13631 locations,
13632 format!("Selections for '{title}'"),
13633 false,
13634 MultibufferSelectionMode::All,
13635 window,
13636 cx,
13637 );
13638 })
13639 })
13640 .detach();
13641 }
13642
13643 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13644 /// last highlight added will be used.
13645 ///
13646 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13647 pub fn highlight_rows<T: 'static>(
13648 &mut self,
13649 range: Range<Anchor>,
13650 color: Hsla,
13651 should_autoscroll: bool,
13652 cx: &mut Context<Self>,
13653 ) {
13654 let snapshot = self.buffer().read(cx).snapshot(cx);
13655 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13656 let ix = row_highlights.binary_search_by(|highlight| {
13657 Ordering::Equal
13658 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13659 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13660 });
13661
13662 if let Err(mut ix) = ix {
13663 let index = post_inc(&mut self.highlight_order);
13664
13665 // If this range intersects with the preceding highlight, then merge it with
13666 // the preceding highlight. Otherwise insert a new highlight.
13667 let mut merged = false;
13668 if ix > 0 {
13669 let prev_highlight = &mut row_highlights[ix - 1];
13670 if prev_highlight
13671 .range
13672 .end
13673 .cmp(&range.start, &snapshot)
13674 .is_ge()
13675 {
13676 ix -= 1;
13677 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13678 prev_highlight.range.end = range.end;
13679 }
13680 merged = true;
13681 prev_highlight.index = index;
13682 prev_highlight.color = color;
13683 prev_highlight.should_autoscroll = should_autoscroll;
13684 }
13685 }
13686
13687 if !merged {
13688 row_highlights.insert(
13689 ix,
13690 RowHighlight {
13691 range: range.clone(),
13692 index,
13693 color,
13694 should_autoscroll,
13695 },
13696 );
13697 }
13698
13699 // If any of the following highlights intersect with this one, merge them.
13700 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13701 let highlight = &row_highlights[ix];
13702 if next_highlight
13703 .range
13704 .start
13705 .cmp(&highlight.range.end, &snapshot)
13706 .is_le()
13707 {
13708 if next_highlight
13709 .range
13710 .end
13711 .cmp(&highlight.range.end, &snapshot)
13712 .is_gt()
13713 {
13714 row_highlights[ix].range.end = next_highlight.range.end;
13715 }
13716 row_highlights.remove(ix + 1);
13717 } else {
13718 break;
13719 }
13720 }
13721 }
13722 }
13723
13724 /// Remove any highlighted row ranges of the given type that intersect the
13725 /// given ranges.
13726 pub fn remove_highlighted_rows<T: 'static>(
13727 &mut self,
13728 ranges_to_remove: Vec<Range<Anchor>>,
13729 cx: &mut Context<Self>,
13730 ) {
13731 let snapshot = self.buffer().read(cx).snapshot(cx);
13732 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13733 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13734 row_highlights.retain(|highlight| {
13735 while let Some(range_to_remove) = ranges_to_remove.peek() {
13736 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13737 Ordering::Less | Ordering::Equal => {
13738 ranges_to_remove.next();
13739 }
13740 Ordering::Greater => {
13741 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13742 Ordering::Less | Ordering::Equal => {
13743 return false;
13744 }
13745 Ordering::Greater => break,
13746 }
13747 }
13748 }
13749 }
13750
13751 true
13752 })
13753 }
13754
13755 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13756 pub fn clear_row_highlights<T: 'static>(&mut self) {
13757 self.highlighted_rows.remove(&TypeId::of::<T>());
13758 }
13759
13760 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13761 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13762 self.highlighted_rows
13763 .get(&TypeId::of::<T>())
13764 .map_or(&[] as &[_], |vec| vec.as_slice())
13765 .iter()
13766 .map(|highlight| (highlight.range.clone(), highlight.color))
13767 }
13768
13769 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13770 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13771 /// Allows to ignore certain kinds of highlights.
13772 pub fn highlighted_display_rows(
13773 &self,
13774 window: &mut Window,
13775 cx: &mut App,
13776 ) -> BTreeMap<DisplayRow, Background> {
13777 let snapshot = self.snapshot(window, cx);
13778 let mut used_highlight_orders = HashMap::default();
13779 self.highlighted_rows
13780 .iter()
13781 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13782 .fold(
13783 BTreeMap::<DisplayRow, Background>::new(),
13784 |mut unique_rows, highlight| {
13785 let start = highlight.range.start.to_display_point(&snapshot);
13786 let end = highlight.range.end.to_display_point(&snapshot);
13787 let start_row = start.row().0;
13788 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13789 && end.column() == 0
13790 {
13791 end.row().0.saturating_sub(1)
13792 } else {
13793 end.row().0
13794 };
13795 for row in start_row..=end_row {
13796 let used_index =
13797 used_highlight_orders.entry(row).or_insert(highlight.index);
13798 if highlight.index >= *used_index {
13799 *used_index = highlight.index;
13800 unique_rows.insert(DisplayRow(row), highlight.color.into());
13801 }
13802 }
13803 unique_rows
13804 },
13805 )
13806 }
13807
13808 pub fn highlighted_display_row_for_autoscroll(
13809 &self,
13810 snapshot: &DisplaySnapshot,
13811 ) -> Option<DisplayRow> {
13812 self.highlighted_rows
13813 .values()
13814 .flat_map(|highlighted_rows| highlighted_rows.iter())
13815 .filter_map(|highlight| {
13816 if highlight.should_autoscroll {
13817 Some(highlight.range.start.to_display_point(snapshot).row())
13818 } else {
13819 None
13820 }
13821 })
13822 .min()
13823 }
13824
13825 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13826 self.highlight_background::<SearchWithinRange>(
13827 ranges,
13828 |colors| colors.editor_document_highlight_read_background,
13829 cx,
13830 )
13831 }
13832
13833 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13834 self.breadcrumb_header = Some(new_header);
13835 }
13836
13837 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13838 self.clear_background_highlights::<SearchWithinRange>(cx);
13839 }
13840
13841 pub fn highlight_background<T: 'static>(
13842 &mut self,
13843 ranges: &[Range<Anchor>],
13844 color_fetcher: fn(&ThemeColors) -> Hsla,
13845 cx: &mut Context<Self>,
13846 ) {
13847 self.background_highlights
13848 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13849 self.scrollbar_marker_state.dirty = true;
13850 cx.notify();
13851 }
13852
13853 pub fn clear_background_highlights<T: 'static>(
13854 &mut self,
13855 cx: &mut Context<Self>,
13856 ) -> Option<BackgroundHighlight> {
13857 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13858 if !text_highlights.1.is_empty() {
13859 self.scrollbar_marker_state.dirty = true;
13860 cx.notify();
13861 }
13862 Some(text_highlights)
13863 }
13864
13865 pub fn highlight_gutter<T: 'static>(
13866 &mut self,
13867 ranges: &[Range<Anchor>],
13868 color_fetcher: fn(&App) -> Hsla,
13869 cx: &mut Context<Self>,
13870 ) {
13871 self.gutter_highlights
13872 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13873 cx.notify();
13874 }
13875
13876 pub fn clear_gutter_highlights<T: 'static>(
13877 &mut self,
13878 cx: &mut Context<Self>,
13879 ) -> Option<GutterHighlight> {
13880 cx.notify();
13881 self.gutter_highlights.remove(&TypeId::of::<T>())
13882 }
13883
13884 #[cfg(feature = "test-support")]
13885 pub fn all_text_background_highlights(
13886 &self,
13887 window: &mut Window,
13888 cx: &mut Context<Self>,
13889 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13890 let snapshot = self.snapshot(window, cx);
13891 let buffer = &snapshot.buffer_snapshot;
13892 let start = buffer.anchor_before(0);
13893 let end = buffer.anchor_after(buffer.len());
13894 let theme = cx.theme().colors();
13895 self.background_highlights_in_range(start..end, &snapshot, theme)
13896 }
13897
13898 #[cfg(feature = "test-support")]
13899 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13900 let snapshot = self.buffer().read(cx).snapshot(cx);
13901
13902 let highlights = self
13903 .background_highlights
13904 .get(&TypeId::of::<items::BufferSearchHighlights>());
13905
13906 if let Some((_color, ranges)) = highlights {
13907 ranges
13908 .iter()
13909 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13910 .collect_vec()
13911 } else {
13912 vec![]
13913 }
13914 }
13915
13916 fn document_highlights_for_position<'a>(
13917 &'a self,
13918 position: Anchor,
13919 buffer: &'a MultiBufferSnapshot,
13920 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13921 let read_highlights = self
13922 .background_highlights
13923 .get(&TypeId::of::<DocumentHighlightRead>())
13924 .map(|h| &h.1);
13925 let write_highlights = self
13926 .background_highlights
13927 .get(&TypeId::of::<DocumentHighlightWrite>())
13928 .map(|h| &h.1);
13929 let left_position = position.bias_left(buffer);
13930 let right_position = position.bias_right(buffer);
13931 read_highlights
13932 .into_iter()
13933 .chain(write_highlights)
13934 .flat_map(move |ranges| {
13935 let start_ix = match ranges.binary_search_by(|probe| {
13936 let cmp = probe.end.cmp(&left_position, buffer);
13937 if cmp.is_ge() {
13938 Ordering::Greater
13939 } else {
13940 Ordering::Less
13941 }
13942 }) {
13943 Ok(i) | Err(i) => i,
13944 };
13945
13946 ranges[start_ix..]
13947 .iter()
13948 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13949 })
13950 }
13951
13952 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13953 self.background_highlights
13954 .get(&TypeId::of::<T>())
13955 .map_or(false, |(_, highlights)| !highlights.is_empty())
13956 }
13957
13958 pub fn background_highlights_in_range(
13959 &self,
13960 search_range: Range<Anchor>,
13961 display_snapshot: &DisplaySnapshot,
13962 theme: &ThemeColors,
13963 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13964 let mut results = Vec::new();
13965 for (color_fetcher, ranges) in self.background_highlights.values() {
13966 let color = color_fetcher(theme);
13967 let start_ix = match ranges.binary_search_by(|probe| {
13968 let cmp = probe
13969 .end
13970 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13971 if cmp.is_gt() {
13972 Ordering::Greater
13973 } else {
13974 Ordering::Less
13975 }
13976 }) {
13977 Ok(i) | Err(i) => i,
13978 };
13979 for range in &ranges[start_ix..] {
13980 if range
13981 .start
13982 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13983 .is_ge()
13984 {
13985 break;
13986 }
13987
13988 let start = range.start.to_display_point(display_snapshot);
13989 let end = range.end.to_display_point(display_snapshot);
13990 results.push((start..end, color))
13991 }
13992 }
13993 results
13994 }
13995
13996 pub fn background_highlight_row_ranges<T: 'static>(
13997 &self,
13998 search_range: Range<Anchor>,
13999 display_snapshot: &DisplaySnapshot,
14000 count: usize,
14001 ) -> Vec<RangeInclusive<DisplayPoint>> {
14002 let mut results = Vec::new();
14003 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14004 return vec![];
14005 };
14006
14007 let start_ix = match ranges.binary_search_by(|probe| {
14008 let cmp = probe
14009 .end
14010 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14011 if cmp.is_gt() {
14012 Ordering::Greater
14013 } else {
14014 Ordering::Less
14015 }
14016 }) {
14017 Ok(i) | Err(i) => i,
14018 };
14019 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14020 if let (Some(start_display), Some(end_display)) = (start, end) {
14021 results.push(
14022 start_display.to_display_point(display_snapshot)
14023 ..=end_display.to_display_point(display_snapshot),
14024 );
14025 }
14026 };
14027 let mut start_row: Option<Point> = None;
14028 let mut end_row: Option<Point> = None;
14029 if ranges.len() > count {
14030 return Vec::new();
14031 }
14032 for range in &ranges[start_ix..] {
14033 if range
14034 .start
14035 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14036 .is_ge()
14037 {
14038 break;
14039 }
14040 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14041 if let Some(current_row) = &end_row {
14042 if end.row == current_row.row {
14043 continue;
14044 }
14045 }
14046 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14047 if start_row.is_none() {
14048 assert_eq!(end_row, None);
14049 start_row = Some(start);
14050 end_row = Some(end);
14051 continue;
14052 }
14053 if let Some(current_end) = end_row.as_mut() {
14054 if start.row > current_end.row + 1 {
14055 push_region(start_row, end_row);
14056 start_row = Some(start);
14057 end_row = Some(end);
14058 } else {
14059 // Merge two hunks.
14060 *current_end = end;
14061 }
14062 } else {
14063 unreachable!();
14064 }
14065 }
14066 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14067 push_region(start_row, end_row);
14068 results
14069 }
14070
14071 pub fn gutter_highlights_in_range(
14072 &self,
14073 search_range: Range<Anchor>,
14074 display_snapshot: &DisplaySnapshot,
14075 cx: &App,
14076 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14077 let mut results = Vec::new();
14078 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14079 let color = color_fetcher(cx);
14080 let start_ix = match ranges.binary_search_by(|probe| {
14081 let cmp = probe
14082 .end
14083 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14084 if cmp.is_gt() {
14085 Ordering::Greater
14086 } else {
14087 Ordering::Less
14088 }
14089 }) {
14090 Ok(i) | Err(i) => i,
14091 };
14092 for range in &ranges[start_ix..] {
14093 if range
14094 .start
14095 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14096 .is_ge()
14097 {
14098 break;
14099 }
14100
14101 let start = range.start.to_display_point(display_snapshot);
14102 let end = range.end.to_display_point(display_snapshot);
14103 results.push((start..end, color))
14104 }
14105 }
14106 results
14107 }
14108
14109 /// Get the text ranges corresponding to the redaction query
14110 pub fn redacted_ranges(
14111 &self,
14112 search_range: Range<Anchor>,
14113 display_snapshot: &DisplaySnapshot,
14114 cx: &App,
14115 ) -> Vec<Range<DisplayPoint>> {
14116 display_snapshot
14117 .buffer_snapshot
14118 .redacted_ranges(search_range, |file| {
14119 if let Some(file) = file {
14120 file.is_private()
14121 && EditorSettings::get(
14122 Some(SettingsLocation {
14123 worktree_id: file.worktree_id(cx),
14124 path: file.path().as_ref(),
14125 }),
14126 cx,
14127 )
14128 .redact_private_values
14129 } else {
14130 false
14131 }
14132 })
14133 .map(|range| {
14134 range.start.to_display_point(display_snapshot)
14135 ..range.end.to_display_point(display_snapshot)
14136 })
14137 .collect()
14138 }
14139
14140 pub fn highlight_text<T: 'static>(
14141 &mut self,
14142 ranges: Vec<Range<Anchor>>,
14143 style: HighlightStyle,
14144 cx: &mut Context<Self>,
14145 ) {
14146 self.display_map.update(cx, |map, _| {
14147 map.highlight_text(TypeId::of::<T>(), ranges, style)
14148 });
14149 cx.notify();
14150 }
14151
14152 pub(crate) fn highlight_inlays<T: 'static>(
14153 &mut self,
14154 highlights: Vec<InlayHighlight>,
14155 style: HighlightStyle,
14156 cx: &mut Context<Self>,
14157 ) {
14158 self.display_map.update(cx, |map, _| {
14159 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14160 });
14161 cx.notify();
14162 }
14163
14164 pub fn text_highlights<'a, T: 'static>(
14165 &'a self,
14166 cx: &'a App,
14167 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14168 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14169 }
14170
14171 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14172 let cleared = self
14173 .display_map
14174 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14175 if cleared {
14176 cx.notify();
14177 }
14178 }
14179
14180 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14181 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14182 && self.focus_handle.is_focused(window)
14183 }
14184
14185 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14186 self.show_cursor_when_unfocused = is_enabled;
14187 cx.notify();
14188 }
14189
14190 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14191 cx.notify();
14192 }
14193
14194 fn on_buffer_event(
14195 &mut self,
14196 multibuffer: &Entity<MultiBuffer>,
14197 event: &multi_buffer::Event,
14198 window: &mut Window,
14199 cx: &mut Context<Self>,
14200 ) {
14201 match event {
14202 multi_buffer::Event::Edited {
14203 singleton_buffer_edited,
14204 edited_buffer: buffer_edited,
14205 } => {
14206 self.scrollbar_marker_state.dirty = true;
14207 self.active_indent_guides_state.dirty = true;
14208 self.refresh_active_diagnostics(cx);
14209 self.refresh_code_actions(window, cx);
14210 if self.has_active_inline_completion() {
14211 self.update_visible_inline_completion(window, cx);
14212 }
14213 if let Some(buffer) = buffer_edited {
14214 let buffer_id = buffer.read(cx).remote_id();
14215 if !self.registered_buffers.contains_key(&buffer_id) {
14216 if let Some(project) = self.project.as_ref() {
14217 project.update(cx, |project, cx| {
14218 self.registered_buffers.insert(
14219 buffer_id,
14220 project.register_buffer_with_language_servers(&buffer, cx),
14221 );
14222 })
14223 }
14224 }
14225 }
14226 cx.emit(EditorEvent::BufferEdited);
14227 cx.emit(SearchEvent::MatchesInvalidated);
14228 if *singleton_buffer_edited {
14229 if let Some(project) = &self.project {
14230 #[allow(clippy::mutable_key_type)]
14231 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14232 multibuffer
14233 .all_buffers()
14234 .into_iter()
14235 .filter_map(|buffer| {
14236 buffer.update(cx, |buffer, cx| {
14237 let language = buffer.language()?;
14238 let should_discard = project.update(cx, |project, cx| {
14239 project.is_local()
14240 && !project.has_language_servers_for(buffer, cx)
14241 });
14242 should_discard.not().then_some(language.clone())
14243 })
14244 })
14245 .collect::<HashSet<_>>()
14246 });
14247 if !languages_affected.is_empty() {
14248 self.refresh_inlay_hints(
14249 InlayHintRefreshReason::BufferEdited(languages_affected),
14250 cx,
14251 );
14252 }
14253 }
14254 }
14255
14256 let Some(project) = &self.project else { return };
14257 let (telemetry, is_via_ssh) = {
14258 let project = project.read(cx);
14259 let telemetry = project.client().telemetry().clone();
14260 let is_via_ssh = project.is_via_ssh();
14261 (telemetry, is_via_ssh)
14262 };
14263 refresh_linked_ranges(self, window, cx);
14264 telemetry.log_edit_event("editor", is_via_ssh);
14265 }
14266 multi_buffer::Event::ExcerptsAdded {
14267 buffer,
14268 predecessor,
14269 excerpts,
14270 } => {
14271 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14272 let buffer_id = buffer.read(cx).remote_id();
14273 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14274 if let Some(project) = &self.project {
14275 get_uncommitted_diff_for_buffer(
14276 project,
14277 [buffer.clone()],
14278 self.buffer.clone(),
14279 cx,
14280 )
14281 .detach();
14282 }
14283 }
14284 cx.emit(EditorEvent::ExcerptsAdded {
14285 buffer: buffer.clone(),
14286 predecessor: *predecessor,
14287 excerpts: excerpts.clone(),
14288 });
14289 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14290 }
14291 multi_buffer::Event::ExcerptsRemoved { ids } => {
14292 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14293 let buffer = self.buffer.read(cx);
14294 self.registered_buffers
14295 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14296 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14297 }
14298 multi_buffer::Event::ExcerptsEdited { ids } => {
14299 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14300 }
14301 multi_buffer::Event::ExcerptsExpanded { ids } => {
14302 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14303 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14304 }
14305 multi_buffer::Event::Reparsed(buffer_id) => {
14306 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14307
14308 cx.emit(EditorEvent::Reparsed(*buffer_id));
14309 }
14310 multi_buffer::Event::DiffHunksToggled => {
14311 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14312 }
14313 multi_buffer::Event::LanguageChanged(buffer_id) => {
14314 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14315 cx.emit(EditorEvent::Reparsed(*buffer_id));
14316 cx.notify();
14317 }
14318 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14319 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14320 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14321 cx.emit(EditorEvent::TitleChanged)
14322 }
14323 // multi_buffer::Event::DiffBaseChanged => {
14324 // self.scrollbar_marker_state.dirty = true;
14325 // cx.emit(EditorEvent::DiffBaseChanged);
14326 // cx.notify();
14327 // }
14328 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14329 multi_buffer::Event::DiagnosticsUpdated => {
14330 self.refresh_active_diagnostics(cx);
14331 self.scrollbar_marker_state.dirty = true;
14332 cx.notify();
14333 }
14334 _ => {}
14335 };
14336 }
14337
14338 fn on_display_map_changed(
14339 &mut self,
14340 _: Entity<DisplayMap>,
14341 _: &mut Window,
14342 cx: &mut Context<Self>,
14343 ) {
14344 cx.notify();
14345 }
14346
14347 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14348 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14349 self.refresh_inline_completion(true, false, window, cx);
14350 self.refresh_inlay_hints(
14351 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14352 self.selections.newest_anchor().head(),
14353 &self.buffer.read(cx).snapshot(cx),
14354 cx,
14355 )),
14356 cx,
14357 );
14358
14359 let old_cursor_shape = self.cursor_shape;
14360
14361 {
14362 let editor_settings = EditorSettings::get_global(cx);
14363 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14364 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14365 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14366 self.hide_mouse_while_typing = editor_settings.hide_mouse_while_typing.unwrap_or(true);
14367
14368 if !self.hide_mouse_while_typing {
14369 self.mouse_cursor_hidden = false;
14370 }
14371 }
14372
14373 if old_cursor_shape != self.cursor_shape {
14374 cx.emit(EditorEvent::CursorShapeChanged);
14375 }
14376
14377 let project_settings = ProjectSettings::get_global(cx);
14378 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14379
14380 if self.mode == EditorMode::Full {
14381 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14382 if self.git_blame_inline_enabled != inline_blame_enabled {
14383 self.toggle_git_blame_inline_internal(false, window, cx);
14384 }
14385 }
14386
14387 cx.notify();
14388 }
14389
14390 pub fn set_searchable(&mut self, searchable: bool) {
14391 self.searchable = searchable;
14392 }
14393
14394 pub fn searchable(&self) -> bool {
14395 self.searchable
14396 }
14397
14398 fn open_proposed_changes_editor(
14399 &mut self,
14400 _: &OpenProposedChangesEditor,
14401 window: &mut Window,
14402 cx: &mut Context<Self>,
14403 ) {
14404 let Some(workspace) = self.workspace() else {
14405 cx.propagate();
14406 return;
14407 };
14408
14409 let selections = self.selections.all::<usize>(cx);
14410 let multi_buffer = self.buffer.read(cx);
14411 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14412 let mut new_selections_by_buffer = HashMap::default();
14413 for selection in selections {
14414 for (buffer, range, _) in
14415 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14416 {
14417 let mut range = range.to_point(buffer);
14418 range.start.column = 0;
14419 range.end.column = buffer.line_len(range.end.row);
14420 new_selections_by_buffer
14421 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14422 .or_insert(Vec::new())
14423 .push(range)
14424 }
14425 }
14426
14427 let proposed_changes_buffers = new_selections_by_buffer
14428 .into_iter()
14429 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14430 .collect::<Vec<_>>();
14431 let proposed_changes_editor = cx.new(|cx| {
14432 ProposedChangesEditor::new(
14433 "Proposed changes",
14434 proposed_changes_buffers,
14435 self.project.clone(),
14436 window,
14437 cx,
14438 )
14439 });
14440
14441 window.defer(cx, move |window, cx| {
14442 workspace.update(cx, |workspace, cx| {
14443 workspace.active_pane().update(cx, |pane, cx| {
14444 pane.add_item(
14445 Box::new(proposed_changes_editor),
14446 true,
14447 true,
14448 None,
14449 window,
14450 cx,
14451 );
14452 });
14453 });
14454 });
14455 }
14456
14457 pub fn open_excerpts_in_split(
14458 &mut self,
14459 _: &OpenExcerptsSplit,
14460 window: &mut Window,
14461 cx: &mut Context<Self>,
14462 ) {
14463 self.open_excerpts_common(None, true, window, cx)
14464 }
14465
14466 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14467 self.open_excerpts_common(None, false, window, cx)
14468 }
14469
14470 fn open_excerpts_common(
14471 &mut self,
14472 jump_data: Option<JumpData>,
14473 split: bool,
14474 window: &mut Window,
14475 cx: &mut Context<Self>,
14476 ) {
14477 let Some(workspace) = self.workspace() else {
14478 cx.propagate();
14479 return;
14480 };
14481
14482 if self.buffer.read(cx).is_singleton() {
14483 cx.propagate();
14484 return;
14485 }
14486
14487 let mut new_selections_by_buffer = HashMap::default();
14488 match &jump_data {
14489 Some(JumpData::MultiBufferPoint {
14490 excerpt_id,
14491 position,
14492 anchor,
14493 line_offset_from_top,
14494 }) => {
14495 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14496 if let Some(buffer) = multi_buffer_snapshot
14497 .buffer_id_for_excerpt(*excerpt_id)
14498 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14499 {
14500 let buffer_snapshot = buffer.read(cx).snapshot();
14501 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14502 language::ToPoint::to_point(anchor, &buffer_snapshot)
14503 } else {
14504 buffer_snapshot.clip_point(*position, Bias::Left)
14505 };
14506 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14507 new_selections_by_buffer.insert(
14508 buffer,
14509 (
14510 vec![jump_to_offset..jump_to_offset],
14511 Some(*line_offset_from_top),
14512 ),
14513 );
14514 }
14515 }
14516 Some(JumpData::MultiBufferRow {
14517 row,
14518 line_offset_from_top,
14519 }) => {
14520 let point = MultiBufferPoint::new(row.0, 0);
14521 if let Some((buffer, buffer_point, _)) =
14522 self.buffer.read(cx).point_to_buffer_point(point, cx)
14523 {
14524 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14525 new_selections_by_buffer
14526 .entry(buffer)
14527 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14528 .0
14529 .push(buffer_offset..buffer_offset)
14530 }
14531 }
14532 None => {
14533 let selections = self.selections.all::<usize>(cx);
14534 let multi_buffer = self.buffer.read(cx);
14535 for selection in selections {
14536 for (buffer, mut range, _) in multi_buffer
14537 .snapshot(cx)
14538 .range_to_buffer_ranges(selection.range())
14539 {
14540 // When editing branch buffers, jump to the corresponding location
14541 // in their base buffer.
14542 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14543 let buffer = buffer_handle.read(cx);
14544 if let Some(base_buffer) = buffer.base_buffer() {
14545 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14546 buffer_handle = base_buffer;
14547 }
14548
14549 if selection.reversed {
14550 mem::swap(&mut range.start, &mut range.end);
14551 }
14552 new_selections_by_buffer
14553 .entry(buffer_handle)
14554 .or_insert((Vec::new(), None))
14555 .0
14556 .push(range)
14557 }
14558 }
14559 }
14560 }
14561
14562 if new_selections_by_buffer.is_empty() {
14563 return;
14564 }
14565
14566 // We defer the pane interaction because we ourselves are a workspace item
14567 // and activating a new item causes the pane to call a method on us reentrantly,
14568 // which panics if we're on the stack.
14569 window.defer(cx, move |window, cx| {
14570 workspace.update(cx, |workspace, cx| {
14571 let pane = if split {
14572 workspace.adjacent_pane(window, cx)
14573 } else {
14574 workspace.active_pane().clone()
14575 };
14576
14577 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14578 let editor = buffer
14579 .read(cx)
14580 .file()
14581 .is_none()
14582 .then(|| {
14583 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14584 // so `workspace.open_project_item` will never find them, always opening a new editor.
14585 // Instead, we try to activate the existing editor in the pane first.
14586 let (editor, pane_item_index) =
14587 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14588 let editor = item.downcast::<Editor>()?;
14589 let singleton_buffer =
14590 editor.read(cx).buffer().read(cx).as_singleton()?;
14591 if singleton_buffer == buffer {
14592 Some((editor, i))
14593 } else {
14594 None
14595 }
14596 })?;
14597 pane.update(cx, |pane, cx| {
14598 pane.activate_item(pane_item_index, true, true, window, cx)
14599 });
14600 Some(editor)
14601 })
14602 .flatten()
14603 .unwrap_or_else(|| {
14604 workspace.open_project_item::<Self>(
14605 pane.clone(),
14606 buffer,
14607 true,
14608 true,
14609 window,
14610 cx,
14611 )
14612 });
14613
14614 editor.update(cx, |editor, cx| {
14615 let autoscroll = match scroll_offset {
14616 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14617 None => Autoscroll::newest(),
14618 };
14619 let nav_history = editor.nav_history.take();
14620 editor.change_selections(Some(autoscroll), window, cx, |s| {
14621 s.select_ranges(ranges);
14622 });
14623 editor.nav_history = nav_history;
14624 });
14625 }
14626 })
14627 });
14628 }
14629
14630 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14631 let snapshot = self.buffer.read(cx).read(cx);
14632 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14633 Some(
14634 ranges
14635 .iter()
14636 .map(move |range| {
14637 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14638 })
14639 .collect(),
14640 )
14641 }
14642
14643 fn selection_replacement_ranges(
14644 &self,
14645 range: Range<OffsetUtf16>,
14646 cx: &mut App,
14647 ) -> Vec<Range<OffsetUtf16>> {
14648 let selections = self.selections.all::<OffsetUtf16>(cx);
14649 let newest_selection = selections
14650 .iter()
14651 .max_by_key(|selection| selection.id)
14652 .unwrap();
14653 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14654 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14655 let snapshot = self.buffer.read(cx).read(cx);
14656 selections
14657 .into_iter()
14658 .map(|mut selection| {
14659 selection.start.0 =
14660 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14661 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14662 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14663 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14664 })
14665 .collect()
14666 }
14667
14668 fn report_editor_event(
14669 &self,
14670 event_type: &'static str,
14671 file_extension: Option<String>,
14672 cx: &App,
14673 ) {
14674 if cfg!(any(test, feature = "test-support")) {
14675 return;
14676 }
14677
14678 let Some(project) = &self.project else { return };
14679
14680 // If None, we are in a file without an extension
14681 let file = self
14682 .buffer
14683 .read(cx)
14684 .as_singleton()
14685 .and_then(|b| b.read(cx).file());
14686 let file_extension = file_extension.or(file
14687 .as_ref()
14688 .and_then(|file| Path::new(file.file_name(cx)).extension())
14689 .and_then(|e| e.to_str())
14690 .map(|a| a.to_string()));
14691
14692 let vim_mode = cx
14693 .global::<SettingsStore>()
14694 .raw_user_settings()
14695 .get("vim_mode")
14696 == Some(&serde_json::Value::Bool(true));
14697
14698 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14699 let copilot_enabled = edit_predictions_provider
14700 == language::language_settings::EditPredictionProvider::Copilot;
14701 let copilot_enabled_for_language = self
14702 .buffer
14703 .read(cx)
14704 .settings_at(0, cx)
14705 .show_edit_predictions;
14706
14707 let project = project.read(cx);
14708 telemetry::event!(
14709 event_type,
14710 file_extension,
14711 vim_mode,
14712 copilot_enabled,
14713 copilot_enabled_for_language,
14714 edit_predictions_provider,
14715 is_via_ssh = project.is_via_ssh(),
14716 );
14717 }
14718
14719 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14720 /// with each line being an array of {text, highlight} objects.
14721 fn copy_highlight_json(
14722 &mut self,
14723 _: &CopyHighlightJson,
14724 window: &mut Window,
14725 cx: &mut Context<Self>,
14726 ) {
14727 #[derive(Serialize)]
14728 struct Chunk<'a> {
14729 text: String,
14730 highlight: Option<&'a str>,
14731 }
14732
14733 let snapshot = self.buffer.read(cx).snapshot(cx);
14734 let range = self
14735 .selected_text_range(false, window, cx)
14736 .and_then(|selection| {
14737 if selection.range.is_empty() {
14738 None
14739 } else {
14740 Some(selection.range)
14741 }
14742 })
14743 .unwrap_or_else(|| 0..snapshot.len());
14744
14745 let chunks = snapshot.chunks(range, true);
14746 let mut lines = Vec::new();
14747 let mut line: VecDeque<Chunk> = VecDeque::new();
14748
14749 let Some(style) = self.style.as_ref() else {
14750 return;
14751 };
14752
14753 for chunk in chunks {
14754 let highlight = chunk
14755 .syntax_highlight_id
14756 .and_then(|id| id.name(&style.syntax));
14757 let mut chunk_lines = chunk.text.split('\n').peekable();
14758 while let Some(text) = chunk_lines.next() {
14759 let mut merged_with_last_token = false;
14760 if let Some(last_token) = line.back_mut() {
14761 if last_token.highlight == highlight {
14762 last_token.text.push_str(text);
14763 merged_with_last_token = true;
14764 }
14765 }
14766
14767 if !merged_with_last_token {
14768 line.push_back(Chunk {
14769 text: text.into(),
14770 highlight,
14771 });
14772 }
14773
14774 if chunk_lines.peek().is_some() {
14775 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14776 line.pop_front();
14777 }
14778 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14779 line.pop_back();
14780 }
14781
14782 lines.push(mem::take(&mut line));
14783 }
14784 }
14785 }
14786
14787 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14788 return;
14789 };
14790 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14791 }
14792
14793 pub fn open_context_menu(
14794 &mut self,
14795 _: &OpenContextMenu,
14796 window: &mut Window,
14797 cx: &mut Context<Self>,
14798 ) {
14799 self.request_autoscroll(Autoscroll::newest(), cx);
14800 let position = self.selections.newest_display(cx).start;
14801 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14802 }
14803
14804 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14805 &self.inlay_hint_cache
14806 }
14807
14808 pub fn replay_insert_event(
14809 &mut self,
14810 text: &str,
14811 relative_utf16_range: Option<Range<isize>>,
14812 window: &mut Window,
14813 cx: &mut Context<Self>,
14814 ) {
14815 if !self.input_enabled {
14816 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14817 return;
14818 }
14819 if let Some(relative_utf16_range) = relative_utf16_range {
14820 let selections = self.selections.all::<OffsetUtf16>(cx);
14821 self.change_selections(None, window, cx, |s| {
14822 let new_ranges = selections.into_iter().map(|range| {
14823 let start = OffsetUtf16(
14824 range
14825 .head()
14826 .0
14827 .saturating_add_signed(relative_utf16_range.start),
14828 );
14829 let end = OffsetUtf16(
14830 range
14831 .head()
14832 .0
14833 .saturating_add_signed(relative_utf16_range.end),
14834 );
14835 start..end
14836 });
14837 s.select_ranges(new_ranges);
14838 });
14839 }
14840
14841 self.handle_input(text, window, cx);
14842 }
14843
14844 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14845 let Some(provider) = self.semantics_provider.as_ref() else {
14846 return false;
14847 };
14848
14849 let mut supports = false;
14850 self.buffer().update(cx, |this, cx| {
14851 this.for_each_buffer(|buffer| {
14852 supports |= provider.supports_inlay_hints(buffer, cx);
14853 });
14854 });
14855
14856 supports
14857 }
14858
14859 pub fn is_focused(&self, window: &Window) -> bool {
14860 self.focus_handle.is_focused(window)
14861 }
14862
14863 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14864 cx.emit(EditorEvent::Focused);
14865
14866 if let Some(descendant) = self
14867 .last_focused_descendant
14868 .take()
14869 .and_then(|descendant| descendant.upgrade())
14870 {
14871 window.focus(&descendant);
14872 } else {
14873 if let Some(blame) = self.blame.as_ref() {
14874 blame.update(cx, GitBlame::focus)
14875 }
14876
14877 self.blink_manager.update(cx, BlinkManager::enable);
14878 self.show_cursor_names(window, cx);
14879 self.buffer.update(cx, |buffer, cx| {
14880 buffer.finalize_last_transaction(cx);
14881 if self.leader_peer_id.is_none() {
14882 buffer.set_active_selections(
14883 &self.selections.disjoint_anchors(),
14884 self.selections.line_mode,
14885 self.cursor_shape,
14886 cx,
14887 );
14888 }
14889 });
14890 }
14891 }
14892
14893 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14894 cx.emit(EditorEvent::FocusedIn)
14895 }
14896
14897 fn handle_focus_out(
14898 &mut self,
14899 event: FocusOutEvent,
14900 _window: &mut Window,
14901 _cx: &mut Context<Self>,
14902 ) {
14903 if event.blurred != self.focus_handle {
14904 self.last_focused_descendant = Some(event.blurred);
14905 }
14906 }
14907
14908 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14909 self.blink_manager.update(cx, BlinkManager::disable);
14910 self.buffer
14911 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14912
14913 if let Some(blame) = self.blame.as_ref() {
14914 blame.update(cx, GitBlame::blur)
14915 }
14916 if !self.hover_state.focused(window, cx) {
14917 hide_hover(self, cx);
14918 }
14919 if !self
14920 .context_menu
14921 .borrow()
14922 .as_ref()
14923 .is_some_and(|context_menu| context_menu.focused(window, cx))
14924 {
14925 self.hide_context_menu(window, cx);
14926 }
14927 self.discard_inline_completion(false, cx);
14928 cx.emit(EditorEvent::Blurred);
14929 cx.notify();
14930 }
14931
14932 pub fn register_action<A: Action>(
14933 &mut self,
14934 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14935 ) -> Subscription {
14936 let id = self.next_editor_action_id.post_inc();
14937 let listener = Arc::new(listener);
14938 self.editor_actions.borrow_mut().insert(
14939 id,
14940 Box::new(move |window, _| {
14941 let listener = listener.clone();
14942 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14943 let action = action.downcast_ref().unwrap();
14944 if phase == DispatchPhase::Bubble {
14945 listener(action, window, cx)
14946 }
14947 })
14948 }),
14949 );
14950
14951 let editor_actions = self.editor_actions.clone();
14952 Subscription::new(move || {
14953 editor_actions.borrow_mut().remove(&id);
14954 })
14955 }
14956
14957 pub fn file_header_size(&self) -> u32 {
14958 FILE_HEADER_HEIGHT
14959 }
14960
14961 pub fn revert(
14962 &mut self,
14963 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14964 window: &mut Window,
14965 cx: &mut Context<Self>,
14966 ) {
14967 self.buffer().update(cx, |multi_buffer, cx| {
14968 for (buffer_id, changes) in revert_changes {
14969 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14970 buffer.update(cx, |buffer, cx| {
14971 buffer.edit(
14972 changes.into_iter().map(|(range, text)| {
14973 (range, text.to_string().map(Arc::<str>::from))
14974 }),
14975 None,
14976 cx,
14977 );
14978 });
14979 }
14980 }
14981 });
14982 self.change_selections(None, window, cx, |selections| selections.refresh());
14983 }
14984
14985 pub fn to_pixel_point(
14986 &self,
14987 source: multi_buffer::Anchor,
14988 editor_snapshot: &EditorSnapshot,
14989 window: &mut Window,
14990 ) -> Option<gpui::Point<Pixels>> {
14991 let source_point = source.to_display_point(editor_snapshot);
14992 self.display_to_pixel_point(source_point, editor_snapshot, window)
14993 }
14994
14995 pub fn display_to_pixel_point(
14996 &self,
14997 source: DisplayPoint,
14998 editor_snapshot: &EditorSnapshot,
14999 window: &mut Window,
15000 ) -> Option<gpui::Point<Pixels>> {
15001 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15002 let text_layout_details = self.text_layout_details(window);
15003 let scroll_top = text_layout_details
15004 .scroll_anchor
15005 .scroll_position(editor_snapshot)
15006 .y;
15007
15008 if source.row().as_f32() < scroll_top.floor() {
15009 return None;
15010 }
15011 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15012 let source_y = line_height * (source.row().as_f32() - scroll_top);
15013 Some(gpui::Point::new(source_x, source_y))
15014 }
15015
15016 pub fn has_visible_completions_menu(&self) -> bool {
15017 !self.edit_prediction_preview_is_active()
15018 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15019 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15020 })
15021 }
15022
15023 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15024 self.addons
15025 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15026 }
15027
15028 pub fn unregister_addon<T: Addon>(&mut self) {
15029 self.addons.remove(&std::any::TypeId::of::<T>());
15030 }
15031
15032 pub fn addon<T: Addon>(&self) -> Option<&T> {
15033 let type_id = std::any::TypeId::of::<T>();
15034 self.addons
15035 .get(&type_id)
15036 .and_then(|item| item.to_any().downcast_ref::<T>())
15037 }
15038
15039 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15040 let text_layout_details = self.text_layout_details(window);
15041 let style = &text_layout_details.editor_style;
15042 let font_id = window.text_system().resolve_font(&style.text.font());
15043 let font_size = style.text.font_size.to_pixels(window.rem_size());
15044 let line_height = style.text.line_height_in_pixels(window.rem_size());
15045 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15046
15047 gpui::Size::new(em_width, line_height)
15048 }
15049
15050 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15051 self.load_diff_task.clone()
15052 }
15053
15054 fn read_selections_from_db(
15055 &mut self,
15056 item_id: u64,
15057 workspace_id: WorkspaceId,
15058 window: &mut Window,
15059 cx: &mut Context<Editor>,
15060 ) {
15061 if !self.is_singleton(cx)
15062 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15063 {
15064 return;
15065 }
15066 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15067 return;
15068 };
15069 if selections.is_empty() {
15070 return;
15071 }
15072
15073 let snapshot = self.buffer.read(cx).snapshot(cx);
15074 self.change_selections(None, window, cx, |s| {
15075 s.select_ranges(selections.into_iter().map(|(start, end)| {
15076 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15077 }));
15078 });
15079 }
15080}
15081
15082fn insert_extra_newline_brackets(
15083 buffer: &MultiBufferSnapshot,
15084 range: Range<usize>,
15085 language: &language::LanguageScope,
15086) -> bool {
15087 let leading_whitespace_len = buffer
15088 .reversed_chars_at(range.start)
15089 .take_while(|c| c.is_whitespace() && *c != '\n')
15090 .map(|c| c.len_utf8())
15091 .sum::<usize>();
15092 let trailing_whitespace_len = buffer
15093 .chars_at(range.end)
15094 .take_while(|c| c.is_whitespace() && *c != '\n')
15095 .map(|c| c.len_utf8())
15096 .sum::<usize>();
15097 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15098
15099 language.brackets().any(|(pair, enabled)| {
15100 let pair_start = pair.start.trim_end();
15101 let pair_end = pair.end.trim_start();
15102
15103 enabled
15104 && pair.newline
15105 && buffer.contains_str_at(range.end, pair_end)
15106 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15107 })
15108}
15109
15110fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15111 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15112 [(buffer, range, _)] => (*buffer, range.clone()),
15113 _ => return false,
15114 };
15115 let pair = {
15116 let mut result: Option<BracketMatch> = None;
15117
15118 for pair in buffer
15119 .all_bracket_ranges(range.clone())
15120 .filter(move |pair| {
15121 pair.open_range.start <= range.start && pair.close_range.end >= range.end
15122 })
15123 {
15124 let len = pair.close_range.end - pair.open_range.start;
15125
15126 if let Some(existing) = &result {
15127 let existing_len = existing.close_range.end - existing.open_range.start;
15128 if len > existing_len {
15129 continue;
15130 }
15131 }
15132
15133 result = Some(pair);
15134 }
15135
15136 result
15137 };
15138 let Some(pair) = pair else {
15139 return false;
15140 };
15141 pair.newline_only
15142 && buffer
15143 .chars_for_range(pair.open_range.end..range.start)
15144 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15145 .all(|c| c.is_whitespace() && c != '\n')
15146}
15147
15148fn get_uncommitted_diff_for_buffer(
15149 project: &Entity<Project>,
15150 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15151 buffer: Entity<MultiBuffer>,
15152 cx: &mut App,
15153) -> Task<()> {
15154 let mut tasks = Vec::new();
15155 project.update(cx, |project, cx| {
15156 for buffer in buffers {
15157 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15158 }
15159 });
15160 cx.spawn(|mut cx| async move {
15161 let diffs = futures::future::join_all(tasks).await;
15162 buffer
15163 .update(&mut cx, |buffer, cx| {
15164 for diff in diffs.into_iter().flatten() {
15165 buffer.add_diff(diff, cx);
15166 }
15167 })
15168 .ok();
15169 })
15170}
15171
15172fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15173 let tab_size = tab_size.get() as usize;
15174 let mut width = offset;
15175
15176 for ch in text.chars() {
15177 width += if ch == '\t' {
15178 tab_size - (width % tab_size)
15179 } else {
15180 1
15181 };
15182 }
15183
15184 width - offset
15185}
15186
15187#[cfg(test)]
15188mod tests {
15189 use super::*;
15190
15191 #[test]
15192 fn test_string_size_with_expanded_tabs() {
15193 let nz = |val| NonZeroU32::new(val).unwrap();
15194 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15195 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15196 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15197 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15198 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15199 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15200 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15201 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15202 }
15203}
15204
15205/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15206struct WordBreakingTokenizer<'a> {
15207 input: &'a str,
15208}
15209
15210impl<'a> WordBreakingTokenizer<'a> {
15211 fn new(input: &'a str) -> Self {
15212 Self { input }
15213 }
15214}
15215
15216fn is_char_ideographic(ch: char) -> bool {
15217 use unicode_script::Script::*;
15218 use unicode_script::UnicodeScript;
15219 matches!(ch.script(), Han | Tangut | Yi)
15220}
15221
15222fn is_grapheme_ideographic(text: &str) -> bool {
15223 text.chars().any(is_char_ideographic)
15224}
15225
15226fn is_grapheme_whitespace(text: &str) -> bool {
15227 text.chars().any(|x| x.is_whitespace())
15228}
15229
15230fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15231 text.chars().next().map_or(false, |ch| {
15232 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15233 })
15234}
15235
15236#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15237struct WordBreakToken<'a> {
15238 token: &'a str,
15239 grapheme_len: usize,
15240 is_whitespace: bool,
15241}
15242
15243impl<'a> Iterator for WordBreakingTokenizer<'a> {
15244 /// Yields a span, the count of graphemes in the token, and whether it was
15245 /// whitespace. Note that it also breaks at word boundaries.
15246 type Item = WordBreakToken<'a>;
15247
15248 fn next(&mut self) -> Option<Self::Item> {
15249 use unicode_segmentation::UnicodeSegmentation;
15250 if self.input.is_empty() {
15251 return None;
15252 }
15253
15254 let mut iter = self.input.graphemes(true).peekable();
15255 let mut offset = 0;
15256 let mut graphemes = 0;
15257 if let Some(first_grapheme) = iter.next() {
15258 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15259 offset += first_grapheme.len();
15260 graphemes += 1;
15261 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15262 if let Some(grapheme) = iter.peek().copied() {
15263 if should_stay_with_preceding_ideograph(grapheme) {
15264 offset += grapheme.len();
15265 graphemes += 1;
15266 }
15267 }
15268 } else {
15269 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15270 let mut next_word_bound = words.peek().copied();
15271 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15272 next_word_bound = words.next();
15273 }
15274 while let Some(grapheme) = iter.peek().copied() {
15275 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15276 break;
15277 };
15278 if is_grapheme_whitespace(grapheme) != is_whitespace {
15279 break;
15280 };
15281 offset += grapheme.len();
15282 graphemes += 1;
15283 iter.next();
15284 }
15285 }
15286 let token = &self.input[..offset];
15287 self.input = &self.input[offset..];
15288 if is_whitespace {
15289 Some(WordBreakToken {
15290 token: " ",
15291 grapheme_len: 1,
15292 is_whitespace: true,
15293 })
15294 } else {
15295 Some(WordBreakToken {
15296 token,
15297 grapheme_len: graphemes,
15298 is_whitespace: false,
15299 })
15300 }
15301 } else {
15302 None
15303 }
15304 }
15305}
15306
15307#[test]
15308fn test_word_breaking_tokenizer() {
15309 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15310 ("", &[]),
15311 (" ", &[(" ", 1, true)]),
15312 ("Ʒ", &[("Ʒ", 1, false)]),
15313 ("Ǽ", &[("Ǽ", 1, false)]),
15314 ("⋑", &[("⋑", 1, false)]),
15315 ("⋑⋑", &[("⋑⋑", 2, false)]),
15316 (
15317 "原理,进而",
15318 &[
15319 ("原", 1, false),
15320 ("理,", 2, false),
15321 ("进", 1, false),
15322 ("而", 1, false),
15323 ],
15324 ),
15325 (
15326 "hello world",
15327 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15328 ),
15329 (
15330 "hello, world",
15331 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15332 ),
15333 (
15334 " hello world",
15335 &[
15336 (" ", 1, true),
15337 ("hello", 5, false),
15338 (" ", 1, true),
15339 ("world", 5, false),
15340 ],
15341 ),
15342 (
15343 "这是什么 \n 钢笔",
15344 &[
15345 ("这", 1, false),
15346 ("是", 1, false),
15347 ("什", 1, false),
15348 ("么", 1, false),
15349 (" ", 1, true),
15350 ("钢", 1, false),
15351 ("笔", 1, false),
15352 ],
15353 ),
15354 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15355 ];
15356
15357 for (input, result) in tests {
15358 assert_eq!(
15359 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15360 result
15361 .iter()
15362 .copied()
15363 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15364 token,
15365 grapheme_len,
15366 is_whitespace,
15367 })
15368 .collect::<Vec<_>>()
15369 );
15370 }
15371}
15372
15373fn wrap_with_prefix(
15374 line_prefix: String,
15375 unwrapped_text: String,
15376 wrap_column: usize,
15377 tab_size: NonZeroU32,
15378) -> String {
15379 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15380 let mut wrapped_text = String::new();
15381 let mut current_line = line_prefix.clone();
15382
15383 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15384 let mut current_line_len = line_prefix_len;
15385 for WordBreakToken {
15386 token,
15387 grapheme_len,
15388 is_whitespace,
15389 } in tokenizer
15390 {
15391 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15392 wrapped_text.push_str(current_line.trim_end());
15393 wrapped_text.push('\n');
15394 current_line.truncate(line_prefix.len());
15395 current_line_len = line_prefix_len;
15396 if !is_whitespace {
15397 current_line.push_str(token);
15398 current_line_len += grapheme_len;
15399 }
15400 } else if !is_whitespace {
15401 current_line.push_str(token);
15402 current_line_len += grapheme_len;
15403 } else if current_line_len != line_prefix_len {
15404 current_line.push(' ');
15405 current_line_len += 1;
15406 }
15407 }
15408
15409 if !current_line.is_empty() {
15410 wrapped_text.push_str(¤t_line);
15411 }
15412 wrapped_text
15413}
15414
15415#[test]
15416fn test_wrap_with_prefix() {
15417 assert_eq!(
15418 wrap_with_prefix(
15419 "# ".to_string(),
15420 "abcdefg".to_string(),
15421 4,
15422 NonZeroU32::new(4).unwrap()
15423 ),
15424 "# abcdefg"
15425 );
15426 assert_eq!(
15427 wrap_with_prefix(
15428 "".to_string(),
15429 "\thello world".to_string(),
15430 8,
15431 NonZeroU32::new(4).unwrap()
15432 ),
15433 "hello\nworld"
15434 );
15435 assert_eq!(
15436 wrap_with_prefix(
15437 "// ".to_string(),
15438 "xx \nyy zz aa bb cc".to_string(),
15439 12,
15440 NonZeroU32::new(4).unwrap()
15441 ),
15442 "// xx yy zz\n// aa bb cc"
15443 );
15444 assert_eq!(
15445 wrap_with_prefix(
15446 String::new(),
15447 "这是什么 \n 钢笔".to_string(),
15448 3,
15449 NonZeroU32::new(4).unwrap()
15450 ),
15451 "这是什\n么 钢\n笔"
15452 );
15453}
15454
15455pub trait CollaborationHub {
15456 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15457 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15458 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15459}
15460
15461impl CollaborationHub for Entity<Project> {
15462 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15463 self.read(cx).collaborators()
15464 }
15465
15466 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15467 self.read(cx).user_store().read(cx).participant_indices()
15468 }
15469
15470 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15471 let this = self.read(cx);
15472 let user_ids = this.collaborators().values().map(|c| c.user_id);
15473 this.user_store().read_with(cx, |user_store, cx| {
15474 user_store.participant_names(user_ids, cx)
15475 })
15476 }
15477}
15478
15479pub trait SemanticsProvider {
15480 fn hover(
15481 &self,
15482 buffer: &Entity<Buffer>,
15483 position: text::Anchor,
15484 cx: &mut App,
15485 ) -> Option<Task<Vec<project::Hover>>>;
15486
15487 fn inlay_hints(
15488 &self,
15489 buffer_handle: Entity<Buffer>,
15490 range: Range<text::Anchor>,
15491 cx: &mut App,
15492 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15493
15494 fn resolve_inlay_hint(
15495 &self,
15496 hint: InlayHint,
15497 buffer_handle: Entity<Buffer>,
15498 server_id: LanguageServerId,
15499 cx: &mut App,
15500 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15501
15502 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15503
15504 fn document_highlights(
15505 &self,
15506 buffer: &Entity<Buffer>,
15507 position: text::Anchor,
15508 cx: &mut App,
15509 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15510
15511 fn definitions(
15512 &self,
15513 buffer: &Entity<Buffer>,
15514 position: text::Anchor,
15515 kind: GotoDefinitionKind,
15516 cx: &mut App,
15517 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15518
15519 fn range_for_rename(
15520 &self,
15521 buffer: &Entity<Buffer>,
15522 position: text::Anchor,
15523 cx: &mut App,
15524 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15525
15526 fn perform_rename(
15527 &self,
15528 buffer: &Entity<Buffer>,
15529 position: text::Anchor,
15530 new_name: String,
15531 cx: &mut App,
15532 ) -> Option<Task<Result<ProjectTransaction>>>;
15533}
15534
15535pub trait CompletionProvider {
15536 fn completions(
15537 &self,
15538 buffer: &Entity<Buffer>,
15539 buffer_position: text::Anchor,
15540 trigger: CompletionContext,
15541 window: &mut Window,
15542 cx: &mut Context<Editor>,
15543 ) -> Task<Result<Vec<Completion>>>;
15544
15545 fn resolve_completions(
15546 &self,
15547 buffer: Entity<Buffer>,
15548 completion_indices: Vec<usize>,
15549 completions: Rc<RefCell<Box<[Completion]>>>,
15550 cx: &mut Context<Editor>,
15551 ) -> Task<Result<bool>>;
15552
15553 fn apply_additional_edits_for_completion(
15554 &self,
15555 _buffer: Entity<Buffer>,
15556 _completions: Rc<RefCell<Box<[Completion]>>>,
15557 _completion_index: usize,
15558 _push_to_history: bool,
15559 _cx: &mut Context<Editor>,
15560 ) -> Task<Result<Option<language::Transaction>>> {
15561 Task::ready(Ok(None))
15562 }
15563
15564 fn is_completion_trigger(
15565 &self,
15566 buffer: &Entity<Buffer>,
15567 position: language::Anchor,
15568 text: &str,
15569 trigger_in_words: bool,
15570 cx: &mut Context<Editor>,
15571 ) -> bool;
15572
15573 fn sort_completions(&self) -> bool {
15574 true
15575 }
15576}
15577
15578pub trait CodeActionProvider {
15579 fn id(&self) -> Arc<str>;
15580
15581 fn code_actions(
15582 &self,
15583 buffer: &Entity<Buffer>,
15584 range: Range<text::Anchor>,
15585 window: &mut Window,
15586 cx: &mut App,
15587 ) -> Task<Result<Vec<CodeAction>>>;
15588
15589 fn apply_code_action(
15590 &self,
15591 buffer_handle: Entity<Buffer>,
15592 action: CodeAction,
15593 excerpt_id: ExcerptId,
15594 push_to_history: bool,
15595 window: &mut Window,
15596 cx: &mut App,
15597 ) -> Task<Result<ProjectTransaction>>;
15598}
15599
15600impl CodeActionProvider for Entity<Project> {
15601 fn id(&self) -> Arc<str> {
15602 "project".into()
15603 }
15604
15605 fn code_actions(
15606 &self,
15607 buffer: &Entity<Buffer>,
15608 range: Range<text::Anchor>,
15609 _window: &mut Window,
15610 cx: &mut App,
15611 ) -> Task<Result<Vec<CodeAction>>> {
15612 self.update(cx, |project, cx| {
15613 project.code_actions(buffer, range, None, cx)
15614 })
15615 }
15616
15617 fn apply_code_action(
15618 &self,
15619 buffer_handle: Entity<Buffer>,
15620 action: CodeAction,
15621 _excerpt_id: ExcerptId,
15622 push_to_history: bool,
15623 _window: &mut Window,
15624 cx: &mut App,
15625 ) -> Task<Result<ProjectTransaction>> {
15626 self.update(cx, |project, cx| {
15627 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15628 })
15629 }
15630}
15631
15632fn snippet_completions(
15633 project: &Project,
15634 buffer: &Entity<Buffer>,
15635 buffer_position: text::Anchor,
15636 cx: &mut App,
15637) -> Task<Result<Vec<Completion>>> {
15638 let language = buffer.read(cx).language_at(buffer_position);
15639 let language_name = language.as_ref().map(|language| language.lsp_id());
15640 let snippet_store = project.snippets().read(cx);
15641 let snippets = snippet_store.snippets_for(language_name, cx);
15642
15643 if snippets.is_empty() {
15644 return Task::ready(Ok(vec![]));
15645 }
15646 let snapshot = buffer.read(cx).text_snapshot();
15647 let chars: String = snapshot
15648 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15649 .collect();
15650
15651 let scope = language.map(|language| language.default_scope());
15652 let executor = cx.background_executor().clone();
15653
15654 cx.background_spawn(async move {
15655 let classifier = CharClassifier::new(scope).for_completion(true);
15656 let mut last_word = chars
15657 .chars()
15658 .take_while(|c| classifier.is_word(*c))
15659 .collect::<String>();
15660 last_word = last_word.chars().rev().collect();
15661
15662 if last_word.is_empty() {
15663 return Ok(vec![]);
15664 }
15665
15666 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15667 let to_lsp = |point: &text::Anchor| {
15668 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15669 point_to_lsp(end)
15670 };
15671 let lsp_end = to_lsp(&buffer_position);
15672
15673 let candidates = snippets
15674 .iter()
15675 .enumerate()
15676 .flat_map(|(ix, snippet)| {
15677 snippet
15678 .prefix
15679 .iter()
15680 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15681 })
15682 .collect::<Vec<StringMatchCandidate>>();
15683
15684 let mut matches = fuzzy::match_strings(
15685 &candidates,
15686 &last_word,
15687 last_word.chars().any(|c| c.is_uppercase()),
15688 100,
15689 &Default::default(),
15690 executor,
15691 )
15692 .await;
15693
15694 // Remove all candidates where the query's start does not match the start of any word in the candidate
15695 if let Some(query_start) = last_word.chars().next() {
15696 matches.retain(|string_match| {
15697 split_words(&string_match.string).any(|word| {
15698 // Check that the first codepoint of the word as lowercase matches the first
15699 // codepoint of the query as lowercase
15700 word.chars()
15701 .flat_map(|codepoint| codepoint.to_lowercase())
15702 .zip(query_start.to_lowercase())
15703 .all(|(word_cp, query_cp)| word_cp == query_cp)
15704 })
15705 });
15706 }
15707
15708 let matched_strings = matches
15709 .into_iter()
15710 .map(|m| m.string)
15711 .collect::<HashSet<_>>();
15712
15713 let result: Vec<Completion> = snippets
15714 .into_iter()
15715 .filter_map(|snippet| {
15716 let matching_prefix = snippet
15717 .prefix
15718 .iter()
15719 .find(|prefix| matched_strings.contains(*prefix))?;
15720 let start = as_offset - last_word.len();
15721 let start = snapshot.anchor_before(start);
15722 let range = start..buffer_position;
15723 let lsp_start = to_lsp(&start);
15724 let lsp_range = lsp::Range {
15725 start: lsp_start,
15726 end: lsp_end,
15727 };
15728 Some(Completion {
15729 old_range: range,
15730 new_text: snippet.body.clone(),
15731 resolved: false,
15732 label: CodeLabel {
15733 text: matching_prefix.clone(),
15734 runs: vec![],
15735 filter_range: 0..matching_prefix.len(),
15736 },
15737 server_id: LanguageServerId(usize::MAX),
15738 documentation: snippet
15739 .description
15740 .clone()
15741 .map(|description| CompletionDocumentation::SingleLine(description.into())),
15742 lsp_completion: lsp::CompletionItem {
15743 label: snippet.prefix.first().unwrap().clone(),
15744 kind: Some(CompletionItemKind::SNIPPET),
15745 label_details: snippet.description.as_ref().map(|description| {
15746 lsp::CompletionItemLabelDetails {
15747 detail: Some(description.clone()),
15748 description: None,
15749 }
15750 }),
15751 insert_text_format: Some(InsertTextFormat::SNIPPET),
15752 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15753 lsp::InsertReplaceEdit {
15754 new_text: snippet.body.clone(),
15755 insert: lsp_range,
15756 replace: lsp_range,
15757 },
15758 )),
15759 filter_text: Some(snippet.body.clone()),
15760 sort_text: Some(char::MAX.to_string()),
15761 ..Default::default()
15762 },
15763 confirm: None,
15764 })
15765 })
15766 .collect();
15767
15768 Ok(result)
15769 })
15770}
15771
15772impl CompletionProvider for Entity<Project> {
15773 fn completions(
15774 &self,
15775 buffer: &Entity<Buffer>,
15776 buffer_position: text::Anchor,
15777 options: CompletionContext,
15778 _window: &mut Window,
15779 cx: &mut Context<Editor>,
15780 ) -> Task<Result<Vec<Completion>>> {
15781 self.update(cx, |project, cx| {
15782 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15783 let project_completions = project.completions(buffer, buffer_position, options, cx);
15784 cx.background_spawn(async move {
15785 let mut completions = project_completions.await?;
15786 let snippets_completions = snippets.await?;
15787 completions.extend(snippets_completions);
15788 Ok(completions)
15789 })
15790 })
15791 }
15792
15793 fn resolve_completions(
15794 &self,
15795 buffer: Entity<Buffer>,
15796 completion_indices: Vec<usize>,
15797 completions: Rc<RefCell<Box<[Completion]>>>,
15798 cx: &mut Context<Editor>,
15799 ) -> Task<Result<bool>> {
15800 self.update(cx, |project, cx| {
15801 project.lsp_store().update(cx, |lsp_store, cx| {
15802 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15803 })
15804 })
15805 }
15806
15807 fn apply_additional_edits_for_completion(
15808 &self,
15809 buffer: Entity<Buffer>,
15810 completions: Rc<RefCell<Box<[Completion]>>>,
15811 completion_index: usize,
15812 push_to_history: bool,
15813 cx: &mut Context<Editor>,
15814 ) -> Task<Result<Option<language::Transaction>>> {
15815 self.update(cx, |project, cx| {
15816 project.lsp_store().update(cx, |lsp_store, cx| {
15817 lsp_store.apply_additional_edits_for_completion(
15818 buffer,
15819 completions,
15820 completion_index,
15821 push_to_history,
15822 cx,
15823 )
15824 })
15825 })
15826 }
15827
15828 fn is_completion_trigger(
15829 &self,
15830 buffer: &Entity<Buffer>,
15831 position: language::Anchor,
15832 text: &str,
15833 trigger_in_words: bool,
15834 cx: &mut Context<Editor>,
15835 ) -> bool {
15836 let mut chars = text.chars();
15837 let char = if let Some(char) = chars.next() {
15838 char
15839 } else {
15840 return false;
15841 };
15842 if chars.next().is_some() {
15843 return false;
15844 }
15845
15846 let buffer = buffer.read(cx);
15847 let snapshot = buffer.snapshot();
15848 if !snapshot.settings_at(position, cx).show_completions_on_input {
15849 return false;
15850 }
15851 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15852 if trigger_in_words && classifier.is_word(char) {
15853 return true;
15854 }
15855
15856 buffer.completion_triggers().contains(text)
15857 }
15858}
15859
15860impl SemanticsProvider for Entity<Project> {
15861 fn hover(
15862 &self,
15863 buffer: &Entity<Buffer>,
15864 position: text::Anchor,
15865 cx: &mut App,
15866 ) -> Option<Task<Vec<project::Hover>>> {
15867 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15868 }
15869
15870 fn document_highlights(
15871 &self,
15872 buffer: &Entity<Buffer>,
15873 position: text::Anchor,
15874 cx: &mut App,
15875 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15876 Some(self.update(cx, |project, cx| {
15877 project.document_highlights(buffer, position, cx)
15878 }))
15879 }
15880
15881 fn definitions(
15882 &self,
15883 buffer: &Entity<Buffer>,
15884 position: text::Anchor,
15885 kind: GotoDefinitionKind,
15886 cx: &mut App,
15887 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15888 Some(self.update(cx, |project, cx| match kind {
15889 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15890 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15891 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15892 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15893 }))
15894 }
15895
15896 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15897 // TODO: make this work for remote projects
15898 self.update(cx, |this, cx| {
15899 buffer.update(cx, |buffer, cx| {
15900 this.any_language_server_supports_inlay_hints(buffer, cx)
15901 })
15902 })
15903 }
15904
15905 fn inlay_hints(
15906 &self,
15907 buffer_handle: Entity<Buffer>,
15908 range: Range<text::Anchor>,
15909 cx: &mut App,
15910 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15911 Some(self.update(cx, |project, cx| {
15912 project.inlay_hints(buffer_handle, range, cx)
15913 }))
15914 }
15915
15916 fn resolve_inlay_hint(
15917 &self,
15918 hint: InlayHint,
15919 buffer_handle: Entity<Buffer>,
15920 server_id: LanguageServerId,
15921 cx: &mut App,
15922 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15923 Some(self.update(cx, |project, cx| {
15924 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15925 }))
15926 }
15927
15928 fn range_for_rename(
15929 &self,
15930 buffer: &Entity<Buffer>,
15931 position: text::Anchor,
15932 cx: &mut App,
15933 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15934 Some(self.update(cx, |project, cx| {
15935 let buffer = buffer.clone();
15936 let task = project.prepare_rename(buffer.clone(), position, cx);
15937 cx.spawn(|_, mut cx| async move {
15938 Ok(match task.await? {
15939 PrepareRenameResponse::Success(range) => Some(range),
15940 PrepareRenameResponse::InvalidPosition => None,
15941 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15942 // Fallback on using TreeSitter info to determine identifier range
15943 buffer.update(&mut cx, |buffer, _| {
15944 let snapshot = buffer.snapshot();
15945 let (range, kind) = snapshot.surrounding_word(position);
15946 if kind != Some(CharKind::Word) {
15947 return None;
15948 }
15949 Some(
15950 snapshot.anchor_before(range.start)
15951 ..snapshot.anchor_after(range.end),
15952 )
15953 })?
15954 }
15955 })
15956 })
15957 }))
15958 }
15959
15960 fn perform_rename(
15961 &self,
15962 buffer: &Entity<Buffer>,
15963 position: text::Anchor,
15964 new_name: String,
15965 cx: &mut App,
15966 ) -> Option<Task<Result<ProjectTransaction>>> {
15967 Some(self.update(cx, |project, cx| {
15968 project.perform_rename(buffer.clone(), position, new_name, cx)
15969 }))
15970 }
15971}
15972
15973fn inlay_hint_settings(
15974 location: Anchor,
15975 snapshot: &MultiBufferSnapshot,
15976 cx: &mut Context<Editor>,
15977) -> InlayHintSettings {
15978 let file = snapshot.file_at(location);
15979 let language = snapshot.language_at(location).map(|l| l.name());
15980 language_settings(language, file, cx).inlay_hints
15981}
15982
15983fn consume_contiguous_rows(
15984 contiguous_row_selections: &mut Vec<Selection<Point>>,
15985 selection: &Selection<Point>,
15986 display_map: &DisplaySnapshot,
15987 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15988) -> (MultiBufferRow, MultiBufferRow) {
15989 contiguous_row_selections.push(selection.clone());
15990 let start_row = MultiBufferRow(selection.start.row);
15991 let mut end_row = ending_row(selection, display_map);
15992
15993 while let Some(next_selection) = selections.peek() {
15994 if next_selection.start.row <= end_row.0 {
15995 end_row = ending_row(next_selection, display_map);
15996 contiguous_row_selections.push(selections.next().unwrap().clone());
15997 } else {
15998 break;
15999 }
16000 }
16001 (start_row, end_row)
16002}
16003
16004fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16005 if next_selection.end.column > 0 || next_selection.is_empty() {
16006 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16007 } else {
16008 MultiBufferRow(next_selection.end.row)
16009 }
16010}
16011
16012impl EditorSnapshot {
16013 pub fn remote_selections_in_range<'a>(
16014 &'a self,
16015 range: &'a Range<Anchor>,
16016 collaboration_hub: &dyn CollaborationHub,
16017 cx: &'a App,
16018 ) -> impl 'a + Iterator<Item = RemoteSelection> {
16019 let participant_names = collaboration_hub.user_names(cx);
16020 let participant_indices = collaboration_hub.user_participant_indices(cx);
16021 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16022 let collaborators_by_replica_id = collaborators_by_peer_id
16023 .iter()
16024 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16025 .collect::<HashMap<_, _>>();
16026 self.buffer_snapshot
16027 .selections_in_range(range, false)
16028 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16029 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16030 let participant_index = participant_indices.get(&collaborator.user_id).copied();
16031 let user_name = participant_names.get(&collaborator.user_id).cloned();
16032 Some(RemoteSelection {
16033 replica_id,
16034 selection,
16035 cursor_shape,
16036 line_mode,
16037 participant_index,
16038 peer_id: collaborator.peer_id,
16039 user_name,
16040 })
16041 })
16042 }
16043
16044 pub fn hunks_for_ranges(
16045 &self,
16046 ranges: impl Iterator<Item = Range<Point>>,
16047 ) -> Vec<MultiBufferDiffHunk> {
16048 let mut hunks = Vec::new();
16049 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16050 HashMap::default();
16051 for query_range in ranges {
16052 let query_rows =
16053 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16054 for hunk in self.buffer_snapshot.diff_hunks_in_range(
16055 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16056 ) {
16057 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16058 // when the caret is just above or just below the deleted hunk.
16059 let allow_adjacent = hunk.status().is_deleted();
16060 let related_to_selection = if allow_adjacent {
16061 hunk.row_range.overlaps(&query_rows)
16062 || hunk.row_range.start == query_rows.end
16063 || hunk.row_range.end == query_rows.start
16064 } else {
16065 hunk.row_range.overlaps(&query_rows)
16066 };
16067 if related_to_selection {
16068 if !processed_buffer_rows
16069 .entry(hunk.buffer_id)
16070 .or_default()
16071 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16072 {
16073 continue;
16074 }
16075 hunks.push(hunk);
16076 }
16077 }
16078 }
16079
16080 hunks
16081 }
16082
16083 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16084 self.display_snapshot.buffer_snapshot.language_at(position)
16085 }
16086
16087 pub fn is_focused(&self) -> bool {
16088 self.is_focused
16089 }
16090
16091 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16092 self.placeholder_text.as_ref()
16093 }
16094
16095 pub fn scroll_position(&self) -> gpui::Point<f32> {
16096 self.scroll_anchor.scroll_position(&self.display_snapshot)
16097 }
16098
16099 fn gutter_dimensions(
16100 &self,
16101 font_id: FontId,
16102 font_size: Pixels,
16103 max_line_number_width: Pixels,
16104 cx: &App,
16105 ) -> Option<GutterDimensions> {
16106 if !self.show_gutter {
16107 return None;
16108 }
16109
16110 let descent = cx.text_system().descent(font_id, font_size);
16111 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16112 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16113
16114 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16115 matches!(
16116 ProjectSettings::get_global(cx).git.git_gutter,
16117 Some(GitGutterSetting::TrackedFiles)
16118 )
16119 });
16120 let gutter_settings = EditorSettings::get_global(cx).gutter;
16121 let show_line_numbers = self
16122 .show_line_numbers
16123 .unwrap_or(gutter_settings.line_numbers);
16124 let line_gutter_width = if show_line_numbers {
16125 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16126 let min_width_for_number_on_gutter = em_advance * 4.0;
16127 max_line_number_width.max(min_width_for_number_on_gutter)
16128 } else {
16129 0.0.into()
16130 };
16131
16132 let show_code_actions = self
16133 .show_code_actions
16134 .unwrap_or(gutter_settings.code_actions);
16135
16136 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16137
16138 let git_blame_entries_width =
16139 self.git_blame_gutter_max_author_length
16140 .map(|max_author_length| {
16141 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16142
16143 /// The number of characters to dedicate to gaps and margins.
16144 const SPACING_WIDTH: usize = 4;
16145
16146 let max_char_count = max_author_length
16147 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16148 + ::git::SHORT_SHA_LENGTH
16149 + MAX_RELATIVE_TIMESTAMP.len()
16150 + SPACING_WIDTH;
16151
16152 em_advance * max_char_count
16153 });
16154
16155 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16156 left_padding += if show_code_actions || show_runnables {
16157 em_width * 3.0
16158 } else if show_git_gutter && show_line_numbers {
16159 em_width * 2.0
16160 } else if show_git_gutter || show_line_numbers {
16161 em_width
16162 } else {
16163 px(0.)
16164 };
16165
16166 let right_padding = if gutter_settings.folds && show_line_numbers {
16167 em_width * 4.0
16168 } else if gutter_settings.folds {
16169 em_width * 3.0
16170 } else if show_line_numbers {
16171 em_width
16172 } else {
16173 px(0.)
16174 };
16175
16176 Some(GutterDimensions {
16177 left_padding,
16178 right_padding,
16179 width: line_gutter_width + left_padding + right_padding,
16180 margin: -descent,
16181 git_blame_entries_width,
16182 })
16183 }
16184
16185 pub fn render_crease_toggle(
16186 &self,
16187 buffer_row: MultiBufferRow,
16188 row_contains_cursor: bool,
16189 editor: Entity<Editor>,
16190 window: &mut Window,
16191 cx: &mut App,
16192 ) -> Option<AnyElement> {
16193 let folded = self.is_line_folded(buffer_row);
16194 let mut is_foldable = false;
16195
16196 if let Some(crease) = self
16197 .crease_snapshot
16198 .query_row(buffer_row, &self.buffer_snapshot)
16199 {
16200 is_foldable = true;
16201 match crease {
16202 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16203 if let Some(render_toggle) = render_toggle {
16204 let toggle_callback =
16205 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16206 if folded {
16207 editor.update(cx, |editor, cx| {
16208 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16209 });
16210 } else {
16211 editor.update(cx, |editor, cx| {
16212 editor.unfold_at(
16213 &crate::UnfoldAt { buffer_row },
16214 window,
16215 cx,
16216 )
16217 });
16218 }
16219 });
16220 return Some((render_toggle)(
16221 buffer_row,
16222 folded,
16223 toggle_callback,
16224 window,
16225 cx,
16226 ));
16227 }
16228 }
16229 }
16230 }
16231
16232 is_foldable |= self.starts_indent(buffer_row);
16233
16234 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16235 Some(
16236 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16237 .toggle_state(folded)
16238 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16239 if folded {
16240 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16241 } else {
16242 this.fold_at(&FoldAt { buffer_row }, window, cx);
16243 }
16244 }))
16245 .into_any_element(),
16246 )
16247 } else {
16248 None
16249 }
16250 }
16251
16252 pub fn render_crease_trailer(
16253 &self,
16254 buffer_row: MultiBufferRow,
16255 window: &mut Window,
16256 cx: &mut App,
16257 ) -> Option<AnyElement> {
16258 let folded = self.is_line_folded(buffer_row);
16259 if let Crease::Inline { render_trailer, .. } = self
16260 .crease_snapshot
16261 .query_row(buffer_row, &self.buffer_snapshot)?
16262 {
16263 let render_trailer = render_trailer.as_ref()?;
16264 Some(render_trailer(buffer_row, folded, window, cx))
16265 } else {
16266 None
16267 }
16268 }
16269}
16270
16271impl Deref for EditorSnapshot {
16272 type Target = DisplaySnapshot;
16273
16274 fn deref(&self) -> &Self::Target {
16275 &self.display_snapshot
16276 }
16277}
16278
16279#[derive(Clone, Debug, PartialEq, Eq)]
16280pub enum EditorEvent {
16281 InputIgnored {
16282 text: Arc<str>,
16283 },
16284 InputHandled {
16285 utf16_range_to_replace: Option<Range<isize>>,
16286 text: Arc<str>,
16287 },
16288 ExcerptsAdded {
16289 buffer: Entity<Buffer>,
16290 predecessor: ExcerptId,
16291 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16292 },
16293 ExcerptsRemoved {
16294 ids: Vec<ExcerptId>,
16295 },
16296 BufferFoldToggled {
16297 ids: Vec<ExcerptId>,
16298 folded: bool,
16299 },
16300 ExcerptsEdited {
16301 ids: Vec<ExcerptId>,
16302 },
16303 ExcerptsExpanded {
16304 ids: Vec<ExcerptId>,
16305 },
16306 BufferEdited,
16307 Edited {
16308 transaction_id: clock::Lamport,
16309 },
16310 Reparsed(BufferId),
16311 Focused,
16312 FocusedIn,
16313 Blurred,
16314 DirtyChanged,
16315 Saved,
16316 TitleChanged,
16317 DiffBaseChanged,
16318 SelectionsChanged {
16319 local: bool,
16320 },
16321 ScrollPositionChanged {
16322 local: bool,
16323 autoscroll: bool,
16324 },
16325 Closed,
16326 TransactionUndone {
16327 transaction_id: clock::Lamport,
16328 },
16329 TransactionBegun {
16330 transaction_id: clock::Lamport,
16331 },
16332 Reloaded,
16333 CursorShapeChanged,
16334}
16335
16336impl EventEmitter<EditorEvent> for Editor {}
16337
16338impl Focusable for Editor {
16339 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16340 self.focus_handle.clone()
16341 }
16342}
16343
16344impl Render for Editor {
16345 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16346 let settings = ThemeSettings::get_global(cx);
16347
16348 let mut text_style = match self.mode {
16349 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16350 color: cx.theme().colors().editor_foreground,
16351 font_family: settings.ui_font.family.clone(),
16352 font_features: settings.ui_font.features.clone(),
16353 font_fallbacks: settings.ui_font.fallbacks.clone(),
16354 font_size: rems(0.875).into(),
16355 font_weight: settings.ui_font.weight,
16356 line_height: relative(settings.buffer_line_height.value()),
16357 ..Default::default()
16358 },
16359 EditorMode::Full => TextStyle {
16360 color: cx.theme().colors().editor_foreground,
16361 font_family: settings.buffer_font.family.clone(),
16362 font_features: settings.buffer_font.features.clone(),
16363 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16364 font_size: settings.buffer_font_size(cx).into(),
16365 font_weight: settings.buffer_font.weight,
16366 line_height: relative(settings.buffer_line_height.value()),
16367 ..Default::default()
16368 },
16369 };
16370 if let Some(text_style_refinement) = &self.text_style_refinement {
16371 text_style.refine(text_style_refinement)
16372 }
16373
16374 let background = match self.mode {
16375 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16376 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16377 EditorMode::Full => cx.theme().colors().editor_background,
16378 };
16379
16380 EditorElement::new(
16381 &cx.entity(),
16382 EditorStyle {
16383 background,
16384 local_player: cx.theme().players().local(),
16385 text: text_style,
16386 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16387 syntax: cx.theme().syntax().clone(),
16388 status: cx.theme().status().clone(),
16389 inlay_hints_style: make_inlay_hints_style(cx),
16390 inline_completion_styles: make_suggestion_styles(cx),
16391 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16392 },
16393 )
16394 }
16395}
16396
16397impl EntityInputHandler for Editor {
16398 fn text_for_range(
16399 &mut self,
16400 range_utf16: Range<usize>,
16401 adjusted_range: &mut Option<Range<usize>>,
16402 _: &mut Window,
16403 cx: &mut Context<Self>,
16404 ) -> Option<String> {
16405 let snapshot = self.buffer.read(cx).read(cx);
16406 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16407 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16408 if (start.0..end.0) != range_utf16 {
16409 adjusted_range.replace(start.0..end.0);
16410 }
16411 Some(snapshot.text_for_range(start..end).collect())
16412 }
16413
16414 fn selected_text_range(
16415 &mut self,
16416 ignore_disabled_input: bool,
16417 _: &mut Window,
16418 cx: &mut Context<Self>,
16419 ) -> Option<UTF16Selection> {
16420 // Prevent the IME menu from appearing when holding down an alphabetic key
16421 // while input is disabled.
16422 if !ignore_disabled_input && !self.input_enabled {
16423 return None;
16424 }
16425
16426 let selection = self.selections.newest::<OffsetUtf16>(cx);
16427 let range = selection.range();
16428
16429 Some(UTF16Selection {
16430 range: range.start.0..range.end.0,
16431 reversed: selection.reversed,
16432 })
16433 }
16434
16435 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16436 let snapshot = self.buffer.read(cx).read(cx);
16437 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16438 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16439 }
16440
16441 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16442 self.clear_highlights::<InputComposition>(cx);
16443 self.ime_transaction.take();
16444 }
16445
16446 fn replace_text_in_range(
16447 &mut self,
16448 range_utf16: Option<Range<usize>>,
16449 text: &str,
16450 window: &mut Window,
16451 cx: &mut Context<Self>,
16452 ) {
16453 if !self.input_enabled {
16454 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16455 return;
16456 }
16457
16458 self.transact(window, cx, |this, window, cx| {
16459 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16460 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16461 Some(this.selection_replacement_ranges(range_utf16, cx))
16462 } else {
16463 this.marked_text_ranges(cx)
16464 };
16465
16466 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16467 let newest_selection_id = this.selections.newest_anchor().id;
16468 this.selections
16469 .all::<OffsetUtf16>(cx)
16470 .iter()
16471 .zip(ranges_to_replace.iter())
16472 .find_map(|(selection, range)| {
16473 if selection.id == newest_selection_id {
16474 Some(
16475 (range.start.0 as isize - selection.head().0 as isize)
16476 ..(range.end.0 as isize - selection.head().0 as isize),
16477 )
16478 } else {
16479 None
16480 }
16481 })
16482 });
16483
16484 cx.emit(EditorEvent::InputHandled {
16485 utf16_range_to_replace: range_to_replace,
16486 text: text.into(),
16487 });
16488
16489 if let Some(new_selected_ranges) = new_selected_ranges {
16490 this.change_selections(None, window, cx, |selections| {
16491 selections.select_ranges(new_selected_ranges)
16492 });
16493 this.backspace(&Default::default(), window, cx);
16494 }
16495
16496 this.handle_input(text, window, cx);
16497 });
16498
16499 if let Some(transaction) = self.ime_transaction {
16500 self.buffer.update(cx, |buffer, cx| {
16501 buffer.group_until_transaction(transaction, cx);
16502 });
16503 }
16504
16505 self.unmark_text(window, cx);
16506 }
16507
16508 fn replace_and_mark_text_in_range(
16509 &mut self,
16510 range_utf16: Option<Range<usize>>,
16511 text: &str,
16512 new_selected_range_utf16: Option<Range<usize>>,
16513 window: &mut Window,
16514 cx: &mut Context<Self>,
16515 ) {
16516 if !self.input_enabled {
16517 return;
16518 }
16519
16520 let transaction = self.transact(window, cx, |this, window, cx| {
16521 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16522 let snapshot = this.buffer.read(cx).read(cx);
16523 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16524 for marked_range in &mut marked_ranges {
16525 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16526 marked_range.start.0 += relative_range_utf16.start;
16527 marked_range.start =
16528 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16529 marked_range.end =
16530 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16531 }
16532 }
16533 Some(marked_ranges)
16534 } else if let Some(range_utf16) = range_utf16 {
16535 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16536 Some(this.selection_replacement_ranges(range_utf16, cx))
16537 } else {
16538 None
16539 };
16540
16541 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16542 let newest_selection_id = this.selections.newest_anchor().id;
16543 this.selections
16544 .all::<OffsetUtf16>(cx)
16545 .iter()
16546 .zip(ranges_to_replace.iter())
16547 .find_map(|(selection, range)| {
16548 if selection.id == newest_selection_id {
16549 Some(
16550 (range.start.0 as isize - selection.head().0 as isize)
16551 ..(range.end.0 as isize - selection.head().0 as isize),
16552 )
16553 } else {
16554 None
16555 }
16556 })
16557 });
16558
16559 cx.emit(EditorEvent::InputHandled {
16560 utf16_range_to_replace: range_to_replace,
16561 text: text.into(),
16562 });
16563
16564 if let Some(ranges) = ranges_to_replace {
16565 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16566 }
16567
16568 let marked_ranges = {
16569 let snapshot = this.buffer.read(cx).read(cx);
16570 this.selections
16571 .disjoint_anchors()
16572 .iter()
16573 .map(|selection| {
16574 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16575 })
16576 .collect::<Vec<_>>()
16577 };
16578
16579 if text.is_empty() {
16580 this.unmark_text(window, cx);
16581 } else {
16582 this.highlight_text::<InputComposition>(
16583 marked_ranges.clone(),
16584 HighlightStyle {
16585 underline: Some(UnderlineStyle {
16586 thickness: px(1.),
16587 color: None,
16588 wavy: false,
16589 }),
16590 ..Default::default()
16591 },
16592 cx,
16593 );
16594 }
16595
16596 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16597 let use_autoclose = this.use_autoclose;
16598 let use_auto_surround = this.use_auto_surround;
16599 this.set_use_autoclose(false);
16600 this.set_use_auto_surround(false);
16601 this.handle_input(text, window, cx);
16602 this.set_use_autoclose(use_autoclose);
16603 this.set_use_auto_surround(use_auto_surround);
16604
16605 if let Some(new_selected_range) = new_selected_range_utf16 {
16606 let snapshot = this.buffer.read(cx).read(cx);
16607 let new_selected_ranges = marked_ranges
16608 .into_iter()
16609 .map(|marked_range| {
16610 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16611 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16612 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16613 snapshot.clip_offset_utf16(new_start, Bias::Left)
16614 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16615 })
16616 .collect::<Vec<_>>();
16617
16618 drop(snapshot);
16619 this.change_selections(None, window, cx, |selections| {
16620 selections.select_ranges(new_selected_ranges)
16621 });
16622 }
16623 });
16624
16625 self.ime_transaction = self.ime_transaction.or(transaction);
16626 if let Some(transaction) = self.ime_transaction {
16627 self.buffer.update(cx, |buffer, cx| {
16628 buffer.group_until_transaction(transaction, cx);
16629 });
16630 }
16631
16632 if self.text_highlights::<InputComposition>(cx).is_none() {
16633 self.ime_transaction.take();
16634 }
16635 }
16636
16637 fn bounds_for_range(
16638 &mut self,
16639 range_utf16: Range<usize>,
16640 element_bounds: gpui::Bounds<Pixels>,
16641 window: &mut Window,
16642 cx: &mut Context<Self>,
16643 ) -> Option<gpui::Bounds<Pixels>> {
16644 let text_layout_details = self.text_layout_details(window);
16645 let gpui::Size {
16646 width: em_width,
16647 height: line_height,
16648 } = self.character_size(window);
16649
16650 let snapshot = self.snapshot(window, cx);
16651 let scroll_position = snapshot.scroll_position();
16652 let scroll_left = scroll_position.x * em_width;
16653
16654 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16655 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16656 + self.gutter_dimensions.width
16657 + self.gutter_dimensions.margin;
16658 let y = line_height * (start.row().as_f32() - scroll_position.y);
16659
16660 Some(Bounds {
16661 origin: element_bounds.origin + point(x, y),
16662 size: size(em_width, line_height),
16663 })
16664 }
16665
16666 fn character_index_for_point(
16667 &mut self,
16668 point: gpui::Point<Pixels>,
16669 _window: &mut Window,
16670 _cx: &mut Context<Self>,
16671 ) -> Option<usize> {
16672 let position_map = self.last_position_map.as_ref()?;
16673 if !position_map.text_hitbox.contains(&point) {
16674 return None;
16675 }
16676 let display_point = position_map.point_for_position(point).previous_valid;
16677 let anchor = position_map
16678 .snapshot
16679 .display_point_to_anchor(display_point, Bias::Left);
16680 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16681 Some(utf16_offset.0)
16682 }
16683}
16684
16685trait SelectionExt {
16686 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16687 fn spanned_rows(
16688 &self,
16689 include_end_if_at_line_start: bool,
16690 map: &DisplaySnapshot,
16691 ) -> Range<MultiBufferRow>;
16692}
16693
16694impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16695 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16696 let start = self
16697 .start
16698 .to_point(&map.buffer_snapshot)
16699 .to_display_point(map);
16700 let end = self
16701 .end
16702 .to_point(&map.buffer_snapshot)
16703 .to_display_point(map);
16704 if self.reversed {
16705 end..start
16706 } else {
16707 start..end
16708 }
16709 }
16710
16711 fn spanned_rows(
16712 &self,
16713 include_end_if_at_line_start: bool,
16714 map: &DisplaySnapshot,
16715 ) -> Range<MultiBufferRow> {
16716 let start = self.start.to_point(&map.buffer_snapshot);
16717 let mut end = self.end.to_point(&map.buffer_snapshot);
16718 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16719 end.row -= 1;
16720 }
16721
16722 let buffer_start = map.prev_line_boundary(start).0;
16723 let buffer_end = map.next_line_boundary(end).0;
16724 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16725 }
16726}
16727
16728impl<T: InvalidationRegion> InvalidationStack<T> {
16729 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16730 where
16731 S: Clone + ToOffset,
16732 {
16733 while let Some(region) = self.last() {
16734 let all_selections_inside_invalidation_ranges =
16735 if selections.len() == region.ranges().len() {
16736 selections
16737 .iter()
16738 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16739 .all(|(selection, invalidation_range)| {
16740 let head = selection.head().to_offset(buffer);
16741 invalidation_range.start <= head && invalidation_range.end >= head
16742 })
16743 } else {
16744 false
16745 };
16746
16747 if all_selections_inside_invalidation_ranges {
16748 break;
16749 } else {
16750 self.pop();
16751 }
16752 }
16753 }
16754}
16755
16756impl<T> Default for InvalidationStack<T> {
16757 fn default() -> Self {
16758 Self(Default::default())
16759 }
16760}
16761
16762impl<T> Deref for InvalidationStack<T> {
16763 type Target = Vec<T>;
16764
16765 fn deref(&self) -> &Self::Target {
16766 &self.0
16767 }
16768}
16769
16770impl<T> DerefMut for InvalidationStack<T> {
16771 fn deref_mut(&mut self) -> &mut Self::Target {
16772 &mut self.0
16773 }
16774}
16775
16776impl InvalidationRegion for SnippetState {
16777 fn ranges(&self) -> &[Range<Anchor>] {
16778 &self.ranges[self.active_index]
16779 }
16780}
16781
16782pub fn diagnostic_block_renderer(
16783 diagnostic: Diagnostic,
16784 max_message_rows: Option<u8>,
16785 allow_closing: bool,
16786 _is_valid: bool,
16787) -> RenderBlock {
16788 let (text_without_backticks, code_ranges) =
16789 highlight_diagnostic_message(&diagnostic, max_message_rows);
16790
16791 Arc::new(move |cx: &mut BlockContext| {
16792 let group_id: SharedString = cx.block_id.to_string().into();
16793
16794 let mut text_style = cx.window.text_style().clone();
16795 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16796 let theme_settings = ThemeSettings::get_global(cx);
16797 text_style.font_family = theme_settings.buffer_font.family.clone();
16798 text_style.font_style = theme_settings.buffer_font.style;
16799 text_style.font_features = theme_settings.buffer_font.features.clone();
16800 text_style.font_weight = theme_settings.buffer_font.weight;
16801
16802 let multi_line_diagnostic = diagnostic.message.contains('\n');
16803
16804 let buttons = |diagnostic: &Diagnostic| {
16805 if multi_line_diagnostic {
16806 v_flex()
16807 } else {
16808 h_flex()
16809 }
16810 .when(allow_closing, |div| {
16811 div.children(diagnostic.is_primary.then(|| {
16812 IconButton::new("close-block", IconName::XCircle)
16813 .icon_color(Color::Muted)
16814 .size(ButtonSize::Compact)
16815 .style(ButtonStyle::Transparent)
16816 .visible_on_hover(group_id.clone())
16817 .on_click(move |_click, window, cx| {
16818 window.dispatch_action(Box::new(Cancel), cx)
16819 })
16820 .tooltip(|window, cx| {
16821 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16822 })
16823 }))
16824 })
16825 .child(
16826 IconButton::new("copy-block", IconName::Copy)
16827 .icon_color(Color::Muted)
16828 .size(ButtonSize::Compact)
16829 .style(ButtonStyle::Transparent)
16830 .visible_on_hover(group_id.clone())
16831 .on_click({
16832 let message = diagnostic.message.clone();
16833 move |_click, _, cx| {
16834 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16835 }
16836 })
16837 .tooltip(Tooltip::text("Copy diagnostic message")),
16838 )
16839 };
16840
16841 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16842 AvailableSpace::min_size(),
16843 cx.window,
16844 cx.app,
16845 );
16846
16847 h_flex()
16848 .id(cx.block_id)
16849 .group(group_id.clone())
16850 .relative()
16851 .size_full()
16852 .block_mouse_down()
16853 .pl(cx.gutter_dimensions.width)
16854 .w(cx.max_width - cx.gutter_dimensions.full_width())
16855 .child(
16856 div()
16857 .flex()
16858 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16859 .flex_shrink(),
16860 )
16861 .child(buttons(&diagnostic))
16862 .child(div().flex().flex_shrink_0().child(
16863 StyledText::new(text_without_backticks.clone()).with_highlights(
16864 &text_style,
16865 code_ranges.iter().map(|range| {
16866 (
16867 range.clone(),
16868 HighlightStyle {
16869 font_weight: Some(FontWeight::BOLD),
16870 ..Default::default()
16871 },
16872 )
16873 }),
16874 ),
16875 ))
16876 .into_any_element()
16877 })
16878}
16879
16880fn inline_completion_edit_text(
16881 current_snapshot: &BufferSnapshot,
16882 edits: &[(Range<Anchor>, String)],
16883 edit_preview: &EditPreview,
16884 include_deletions: bool,
16885 cx: &App,
16886) -> HighlightedText {
16887 let edits = edits
16888 .iter()
16889 .map(|(anchor, text)| {
16890 (
16891 anchor.start.text_anchor..anchor.end.text_anchor,
16892 text.clone(),
16893 )
16894 })
16895 .collect::<Vec<_>>();
16896
16897 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16898}
16899
16900pub fn highlight_diagnostic_message(
16901 diagnostic: &Diagnostic,
16902 mut max_message_rows: Option<u8>,
16903) -> (SharedString, Vec<Range<usize>>) {
16904 let mut text_without_backticks = String::new();
16905 let mut code_ranges = Vec::new();
16906
16907 if let Some(source) = &diagnostic.source {
16908 text_without_backticks.push_str(source);
16909 code_ranges.push(0..source.len());
16910 text_without_backticks.push_str(": ");
16911 }
16912
16913 let mut prev_offset = 0;
16914 let mut in_code_block = false;
16915 let has_row_limit = max_message_rows.is_some();
16916 let mut newline_indices = diagnostic
16917 .message
16918 .match_indices('\n')
16919 .filter(|_| has_row_limit)
16920 .map(|(ix, _)| ix)
16921 .fuse()
16922 .peekable();
16923
16924 for (quote_ix, _) in diagnostic
16925 .message
16926 .match_indices('`')
16927 .chain([(diagnostic.message.len(), "")])
16928 {
16929 let mut first_newline_ix = None;
16930 let mut last_newline_ix = None;
16931 while let Some(newline_ix) = newline_indices.peek() {
16932 if *newline_ix < quote_ix {
16933 if first_newline_ix.is_none() {
16934 first_newline_ix = Some(*newline_ix);
16935 }
16936 last_newline_ix = Some(*newline_ix);
16937
16938 if let Some(rows_left) = &mut max_message_rows {
16939 if *rows_left == 0 {
16940 break;
16941 } else {
16942 *rows_left -= 1;
16943 }
16944 }
16945 let _ = newline_indices.next();
16946 } else {
16947 break;
16948 }
16949 }
16950 let prev_len = text_without_backticks.len();
16951 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16952 text_without_backticks.push_str(new_text);
16953 if in_code_block {
16954 code_ranges.push(prev_len..text_without_backticks.len());
16955 }
16956 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16957 in_code_block = !in_code_block;
16958 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16959 text_without_backticks.push_str("...");
16960 break;
16961 }
16962 }
16963
16964 (text_without_backticks.into(), code_ranges)
16965}
16966
16967fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16968 match severity {
16969 DiagnosticSeverity::ERROR => colors.error,
16970 DiagnosticSeverity::WARNING => colors.warning,
16971 DiagnosticSeverity::INFORMATION => colors.info,
16972 DiagnosticSeverity::HINT => colors.info,
16973 _ => colors.ignored,
16974 }
16975}
16976
16977pub fn styled_runs_for_code_label<'a>(
16978 label: &'a CodeLabel,
16979 syntax_theme: &'a theme::SyntaxTheme,
16980) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16981 let fade_out = HighlightStyle {
16982 fade_out: Some(0.35),
16983 ..Default::default()
16984 };
16985
16986 let mut prev_end = label.filter_range.end;
16987 label
16988 .runs
16989 .iter()
16990 .enumerate()
16991 .flat_map(move |(ix, (range, highlight_id))| {
16992 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16993 style
16994 } else {
16995 return Default::default();
16996 };
16997 let mut muted_style = style;
16998 muted_style.highlight(fade_out);
16999
17000 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17001 if range.start >= label.filter_range.end {
17002 if range.start > prev_end {
17003 runs.push((prev_end..range.start, fade_out));
17004 }
17005 runs.push((range.clone(), muted_style));
17006 } else if range.end <= label.filter_range.end {
17007 runs.push((range.clone(), style));
17008 } else {
17009 runs.push((range.start..label.filter_range.end, style));
17010 runs.push((label.filter_range.end..range.end, muted_style));
17011 }
17012 prev_end = cmp::max(prev_end, range.end);
17013
17014 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17015 runs.push((prev_end..label.text.len(), fade_out));
17016 }
17017
17018 runs
17019 })
17020}
17021
17022pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17023 let mut prev_index = 0;
17024 let mut prev_codepoint: Option<char> = None;
17025 text.char_indices()
17026 .chain([(text.len(), '\0')])
17027 .filter_map(move |(index, codepoint)| {
17028 let prev_codepoint = prev_codepoint.replace(codepoint)?;
17029 let is_boundary = index == text.len()
17030 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17031 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17032 if is_boundary {
17033 let chunk = &text[prev_index..index];
17034 prev_index = index;
17035 Some(chunk)
17036 } else {
17037 None
17038 }
17039 })
17040}
17041
17042pub trait RangeToAnchorExt: Sized {
17043 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17044
17045 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17046 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17047 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17048 }
17049}
17050
17051impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17052 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17053 let start_offset = self.start.to_offset(snapshot);
17054 let end_offset = self.end.to_offset(snapshot);
17055 if start_offset == end_offset {
17056 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17057 } else {
17058 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17059 }
17060 }
17061}
17062
17063pub trait RowExt {
17064 fn as_f32(&self) -> f32;
17065
17066 fn next_row(&self) -> Self;
17067
17068 fn previous_row(&self) -> Self;
17069
17070 fn minus(&self, other: Self) -> u32;
17071}
17072
17073impl RowExt for DisplayRow {
17074 fn as_f32(&self) -> f32 {
17075 self.0 as f32
17076 }
17077
17078 fn next_row(&self) -> Self {
17079 Self(self.0 + 1)
17080 }
17081
17082 fn previous_row(&self) -> Self {
17083 Self(self.0.saturating_sub(1))
17084 }
17085
17086 fn minus(&self, other: Self) -> u32 {
17087 self.0 - other.0
17088 }
17089}
17090
17091impl RowExt for MultiBufferRow {
17092 fn as_f32(&self) -> f32 {
17093 self.0 as f32
17094 }
17095
17096 fn next_row(&self) -> Self {
17097 Self(self.0 + 1)
17098 }
17099
17100 fn previous_row(&self) -> Self {
17101 Self(self.0.saturating_sub(1))
17102 }
17103
17104 fn minus(&self, other: Self) -> u32 {
17105 self.0 - other.0
17106 }
17107}
17108
17109trait RowRangeExt {
17110 type Row;
17111
17112 fn len(&self) -> usize;
17113
17114 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17115}
17116
17117impl RowRangeExt for Range<MultiBufferRow> {
17118 type Row = MultiBufferRow;
17119
17120 fn len(&self) -> usize {
17121 (self.end.0 - self.start.0) as usize
17122 }
17123
17124 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17125 (self.start.0..self.end.0).map(MultiBufferRow)
17126 }
17127}
17128
17129impl RowRangeExt for Range<DisplayRow> {
17130 type Row = DisplayRow;
17131
17132 fn len(&self) -> usize {
17133 (self.end.0 - self.start.0) as usize
17134 }
17135
17136 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17137 (self.start.0..self.end.0).map(DisplayRow)
17138 }
17139}
17140
17141/// If select range has more than one line, we
17142/// just point the cursor to range.start.
17143fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17144 if range.start.row == range.end.row {
17145 range
17146 } else {
17147 range.start..range.start
17148 }
17149}
17150pub struct KillRing(ClipboardItem);
17151impl Global for KillRing {}
17152
17153const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17154
17155fn all_edits_insertions_or_deletions(
17156 edits: &Vec<(Range<Anchor>, String)>,
17157 snapshot: &MultiBufferSnapshot,
17158) -> bool {
17159 let mut all_insertions = true;
17160 let mut all_deletions = true;
17161
17162 for (range, new_text) in edits.iter() {
17163 let range_is_empty = range.to_offset(&snapshot).is_empty();
17164 let text_is_empty = new_text.is_empty();
17165
17166 if range_is_empty != text_is_empty {
17167 if range_is_empty {
17168 all_deletions = false;
17169 } else {
17170 all_insertions = false;
17171 }
17172 } else {
17173 return false;
17174 }
17175
17176 if !all_insertions && !all_deletions {
17177 return false;
17178 }
17179 }
17180 all_insertions || all_deletions
17181}